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
mod.rs
//! Implementations of the Wayland backends using the system `libwayland` use crate::protocol::ArgumentType; use wayland_sys::common::{wl_argument, wl_array}; #[cfg(any(test, feature = "client_system"))]
#[cfg(any(test, feature = "server_system"))] pub mod server; /// Magic static for wayland objects managed by wayland-client or wayland-server /// /// This static serves no purpose other than existing at a stable address. static RUST_MANAGED: u8 = 42; unsafe fn free_arrays(signature: &[ArgumentType], arglist: &[wl_argument]) { for (typ, arg) in signature.iter().zip(arglist.iter()) { if let ArgumentType::Array(_) = typ { // Safety: the arglist provided arglist must be valid for associated signature // and contains pointers to boxed arrays as appropriate let _ = unsafe { Box::from_raw(arg.a as *mut wl_array) }; } } }
pub mod client;
random_line_split
mod.rs
//! Implementations of the Wayland backends using the system `libwayland` use crate::protocol::ArgumentType; use wayland_sys::common::{wl_argument, wl_array}; #[cfg(any(test, feature = "client_system"))] pub mod client; #[cfg(any(test, feature = "server_system"))] pub mod server; /// Magic static for wayland objects managed by wayland-client or wayland-server /// /// This static serves no purpose other than existing at a stable address. static RUST_MANAGED: u8 = 42; unsafe fn
(signature: &[ArgumentType], arglist: &[wl_argument]) { for (typ, arg) in signature.iter().zip(arglist.iter()) { if let ArgumentType::Array(_) = typ { // Safety: the arglist provided arglist must be valid for associated signature // and contains pointers to boxed arrays as appropriate let _ = unsafe { Box::from_raw(arg.a as *mut wl_array) }; } } }
free_arrays
identifier_name
error.rs
use std::error::Error; use std::fmt; use std::io; use crate::credential::CredentialsError; use super::proto::xml::util::XmlParseError; use super::request::{BufferedHttpResponse, HttpDispatchError}; use crate::client::SignAndDispatchError; /// Generic error type returned by all rusoto requests. #[derive(Debug, PartialEq)] pub enum RusotoError<E> { /// A service-specific error occurred. Service(E), /// An error occurred dispatching the HTTP request HttpDispatch(HttpDispatchError), /// An error was encountered with AWS credentials. Credentials(CredentialsError), /// A validation error occurred. Details from AWS are provided. Validation(String), /// An error occurred parsing the response payload. ParseError(String), /// An unknown error occurred. The raw HTTP response is provided. Unknown(BufferedHttpResponse), /// An error occurred when attempting to run a future as blocking Blocking, } /// Result carrying a generic `RusotoError`. pub type RusotoResult<T, E> = Result<T, RusotoError<E>>; /// Header used by AWS on responses to identify the request pub const AWS_REQUEST_ID_HEADER: &str = "x-amzn-requestid"; impl<E> From<XmlParseError> for RusotoError<E> { fn from(err: XmlParseError) -> Self { let XmlParseError(message) = err; RusotoError::ParseError(message) } } impl<E> From<serde_json::error::Error> for RusotoError<E> { fn from(err: serde_json::error::Error) -> Self { RusotoError::ParseError(err.to_string()) } } impl<E> From<CredentialsError> for RusotoError<E> { fn from(err: CredentialsError) -> Self { RusotoError::Credentials(err) } } impl<E> From<HttpDispatchError> for RusotoError<E> { fn from(err: HttpDispatchError) -> Self { RusotoError::HttpDispatch(err) } } impl<E> From<SignAndDispatchError> for RusotoError<E> { fn from(err: SignAndDispatchError) -> Self { match err { SignAndDispatchError::Credentials(e) => Self::from(e), SignAndDispatchError::Dispatch(e) => Self::from(e), } } } impl<E> From<io::Error> for RusotoError<E> { fn
(err: io::Error) -> Self { RusotoError::HttpDispatch(HttpDispatchError::from(err)) } } impl<E: Error +'static> fmt::Display for RusotoError<E> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RusotoError::Service(ref err) => write!(f, "{}", err), RusotoError::Validation(ref cause) => write!(f, "{}", cause), RusotoError::Credentials(ref err) => write!(f, "{}", err), RusotoError::HttpDispatch(ref dispatch_error) => write!(f, "{}", dispatch_error), RusotoError::ParseError(ref cause) => write!(f, "{}", cause), RusotoError::Unknown(ref cause) => write!( f, "Request ID: {:?} Body: {}", cause.headers.get(AWS_REQUEST_ID_HEADER), cause.body_as_str() ), RusotoError::Blocking => write!(f, "Failed to run blocking future"), } } } impl<E: Error +'static> Error for RusotoError<E> { fn source(&self) -> Option<&(dyn Error +'static)> { match *self { RusotoError::Service(ref err) => Some(err), RusotoError::Credentials(ref err) => Some(err), RusotoError::HttpDispatch(ref err) => Some(err), _ => None, } } }
from
identifier_name
error.rs
use std::error::Error; use std::fmt; use std::io; use crate::credential::CredentialsError; use super::proto::xml::util::XmlParseError; use super::request::{BufferedHttpResponse, HttpDispatchError}; use crate::client::SignAndDispatchError; /// Generic error type returned by all rusoto requests. #[derive(Debug, PartialEq)] pub enum RusotoError<E> { /// A service-specific error occurred. Service(E), /// An error occurred dispatching the HTTP request HttpDispatch(HttpDispatchError), /// An error was encountered with AWS credentials. Credentials(CredentialsError), /// A validation error occurred. Details from AWS are provided. Validation(String), /// An error occurred parsing the response payload. ParseError(String), /// An unknown error occurred. The raw HTTP response is provided. Unknown(BufferedHttpResponse), /// An error occurred when attempting to run a future as blocking Blocking, } /// Result carrying a generic `RusotoError`. pub type RusotoResult<T, E> = Result<T, RusotoError<E>>; /// Header used by AWS on responses to identify the request pub const AWS_REQUEST_ID_HEADER: &str = "x-amzn-requestid"; impl<E> From<XmlParseError> for RusotoError<E> { fn from(err: XmlParseError) -> Self { let XmlParseError(message) = err; RusotoError::ParseError(message) } } impl<E> From<serde_json::error::Error> for RusotoError<E> { fn from(err: serde_json::error::Error) -> Self { RusotoError::ParseError(err.to_string()) } } impl<E> From<CredentialsError> for RusotoError<E> { fn from(err: CredentialsError) -> Self { RusotoError::Credentials(err) } } impl<E> From<HttpDispatchError> for RusotoError<E> { fn from(err: HttpDispatchError) -> Self { RusotoError::HttpDispatch(err) } } impl<E> From<SignAndDispatchError> for RusotoError<E> { fn from(err: SignAndDispatchError) -> Self { match err { SignAndDispatchError::Credentials(e) => Self::from(e), SignAndDispatchError::Dispatch(e) => Self::from(e), } } } impl<E> From<io::Error> for RusotoError<E> { fn from(err: io::Error) -> Self
} impl<E: Error +'static> fmt::Display for RusotoError<E> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RusotoError::Service(ref err) => write!(f, "{}", err), RusotoError::Validation(ref cause) => write!(f, "{}", cause), RusotoError::Credentials(ref err) => write!(f, "{}", err), RusotoError::HttpDispatch(ref dispatch_error) => write!(f, "{}", dispatch_error), RusotoError::ParseError(ref cause) => write!(f, "{}", cause), RusotoError::Unknown(ref cause) => write!( f, "Request ID: {:?} Body: {}", cause.headers.get(AWS_REQUEST_ID_HEADER), cause.body_as_str() ), RusotoError::Blocking => write!(f, "Failed to run blocking future"), } } } impl<E: Error +'static> Error for RusotoError<E> { fn source(&self) -> Option<&(dyn Error +'static)> { match *self { RusotoError::Service(ref err) => Some(err), RusotoError::Credentials(ref err) => Some(err), RusotoError::HttpDispatch(ref err) => Some(err), _ => None, } } }
{ RusotoError::HttpDispatch(HttpDispatchError::from(err)) }
identifier_body
error.rs
use std::error::Error; use std::fmt; use std::io; use crate::credential::CredentialsError; use super::proto::xml::util::XmlParseError; use super::request::{BufferedHttpResponse, HttpDispatchError}; use crate::client::SignAndDispatchError; /// Generic error type returned by all rusoto requests. #[derive(Debug, PartialEq)] pub enum RusotoError<E> { /// A service-specific error occurred. Service(E), /// An error occurred dispatching the HTTP request HttpDispatch(HttpDispatchError), /// An error was encountered with AWS credentials. Credentials(CredentialsError), /// A validation error occurred. Details from AWS are provided. Validation(String), /// An error occurred parsing the response payload. ParseError(String), /// An unknown error occurred. The raw HTTP response is provided. Unknown(BufferedHttpResponse), /// An error occurred when attempting to run a future as blocking Blocking, } /// Result carrying a generic `RusotoError`. pub type RusotoResult<T, E> = Result<T, RusotoError<E>>; /// Header used by AWS on responses to identify the request pub const AWS_REQUEST_ID_HEADER: &str = "x-amzn-requestid"; impl<E> From<XmlParseError> for RusotoError<E> { fn from(err: XmlParseError) -> Self { let XmlParseError(message) = err; RusotoError::ParseError(message) } } impl<E> From<serde_json::error::Error> for RusotoError<E> { fn from(err: serde_json::error::Error) -> Self { RusotoError::ParseError(err.to_string()) } } impl<E> From<CredentialsError> for RusotoError<E> { fn from(err: CredentialsError) -> Self { RusotoError::Credentials(err) } } impl<E> From<HttpDispatchError> for RusotoError<E> { fn from(err: HttpDispatchError) -> Self { RusotoError::HttpDispatch(err) } } impl<E> From<SignAndDispatchError> for RusotoError<E> { fn from(err: SignAndDispatchError) -> Self { match err { SignAndDispatchError::Credentials(e) => Self::from(e), SignAndDispatchError::Dispatch(e) => Self::from(e), } } } impl<E> From<io::Error> for RusotoError<E> { fn from(err: io::Error) -> Self { RusotoError::HttpDispatch(HttpDispatchError::from(err)) } } impl<E: Error +'static> fmt::Display for RusotoError<E> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RusotoError::Service(ref err) => write!(f, "{}", err), RusotoError::Validation(ref cause) => write!(f, "{}", cause), RusotoError::Credentials(ref err) => write!(f, "{}", err), RusotoError::HttpDispatch(ref dispatch_error) => write!(f, "{}", dispatch_error), RusotoError::ParseError(ref cause) => write!(f, "{}", cause), RusotoError::Unknown(ref cause) => write!( f, "Request ID: {:?} Body: {}", cause.headers.get(AWS_REQUEST_ID_HEADER), cause.body_as_str() ), RusotoError::Blocking => write!(f, "Failed to run blocking future"), } } } impl<E: Error +'static> Error for RusotoError<E> { fn source(&self) -> Option<&(dyn Error +'static)> { match *self {
} } }
RusotoError::Service(ref err) => Some(err), RusotoError::Credentials(ref err) => Some(err), RusotoError::HttpDispatch(ref err) => Some(err), _ => None,
random_line_split
nohup.rs
#![crate_name = "uu_nohup"] /* * This file is part of the uutils coreutils package. * * (c) 2014 Vsevolod Velichko <[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::{c_char, execvp, signal, dup2}; use libc::{SIGHUP, SIG_IGN}; use std::ffi::CString; use std::fs::{File, OpenOptions}; use std::io::Error; use std::os::unix::prelude::*; use std::path::{Path, PathBuf}; use std::env; use uucore::fs::{is_stderr_interactive, is_stdin_interactive, is_stdout_interactive}; static NAME: &'static str = "nohup"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); #[cfg(target_os = "macos")] extern "C" { fn _vprocmgr_detach_from_console(flags: u32) -> *const libc::c_int; } #[cfg(any(target_os = "linux", target_os = "freebsd"))] unsafe fn _vprocmgr_detach_from_console(_: u32) -> *const libc::c_int { std::ptr::null() } pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("h", "help", "Show help and exit"); opts.optflag("V", "version", "Show version and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { show_error!("{}", f); show_usage(&opts); return 1; } }; if matches.opt_present("V") { println!("{} {}", NAME, VERSION); return 0; } if matches.opt_present("h") { show_usage(&opts); return 0; } if matches.free.is_empty() { show_error!("Missing operand: COMMAND"); println!("Try `{} --help` for more information.", NAME); return 1; } replace_fds(); unsafe { signal(SIGHUP, SIG_IGN) }; if unsafe { _vprocmgr_detach_from_console(0) }!= std::ptr::null() { crash!(2, "Cannot detach from console") }; let cstrs: Vec<CString> = matches .free .iter() .map(|x| CString::new(x.as_bytes()).unwrap()) .collect(); let mut args: Vec<*const c_char> = cstrs.iter().map(|s| s.as_ptr()).collect(); args.push(std::ptr::null()); unsafe { execvp(args[0], args.as_mut_ptr()) } } fn replace_fds() { if is_stdin_interactive() { let new_stdin = match File::open(Path::new("/dev/null")) { Ok(t) => t, Err(e) => crash!(2, "Cannot replace STDIN: {}", e), }; if unsafe { dup2(new_stdin.as_raw_fd(), 0) }!= 0 { crash!(2, "Cannot replace STDIN: {}", Error::last_os_error()) } } if is_stdout_interactive() { let new_stdout = find_stdout(); let fd = new_stdout.as_raw_fd(); if unsafe { dup2(fd, 1) }!= 1 { crash!(2, "Cannot replace STDOUT: {}", Error::last_os_error()) } } if is_stderr_interactive()
} fn find_stdout() -> File { match OpenOptions::new() .write(true) .create(true) .append(true) .open(Path::new("nohup.out")) { Ok(t) => { show_warning!("Output is redirected to: nohup.out"); t } Err(e) => { let home = match env::var("HOME") { Err(_) => crash!(2, "Cannot replace STDOUT: {}", e), Ok(h) => h, }; let mut homeout = PathBuf::from(home); homeout.push("nohup.out"); match OpenOptions::new() .write(true) .create(true) .append(true) .open(&homeout) { Ok(t) => { show_warning!("Output is redirected to: {:?}", homeout); t } Err(e) => crash!(2, "Cannot replace STDOUT: {}", e), } } } } fn show_usage(opts: &getopts::Options) { let msg = format!( "{0} {1} Usage: {0} COMMAND [ARG]... {0} OPTION Run COMMAND ignoring hangup signals. If standard input is terminal, it'll be replaced with /dev/null. If standard output is terminal, it'll be appended to nohup.out instead, or $HOME/nohup.out, if nohup.out open failed. If standard error is terminal, it'll be redirected to stdout.", NAME, VERSION ); print!("{}", opts.usage(&msg)); }
{ if unsafe { dup2(1, 2) } != 2 { crash!(2, "Cannot replace STDERR: {}", Error::last_os_error()) } }
conditional_block
nohup.rs
#![crate_name = "uu_nohup"] /* * This file is part of the uutils coreutils package. * * (c) 2014 Vsevolod Velichko <[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::{c_char, execvp, signal, dup2}; use libc::{SIGHUP, SIG_IGN}; use std::ffi::CString; use std::fs::{File, OpenOptions}; use std::io::Error; use std::os::unix::prelude::*; use std::path::{Path, PathBuf}; use std::env; use uucore::fs::{is_stderr_interactive, is_stdin_interactive, is_stdout_interactive}; static NAME: &'static str = "nohup"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); #[cfg(target_os = "macos")] extern "C" { fn _vprocmgr_detach_from_console(flags: u32) -> *const libc::c_int; } #[cfg(any(target_os = "linux", target_os = "freebsd"))] unsafe fn _vprocmgr_detach_from_console(_: u32) -> *const libc::c_int { std::ptr::null() } pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("h", "help", "Show help and exit"); opts.optflag("V", "version", "Show version and exit");
show_error!("{}", f); show_usage(&opts); return 1; } }; if matches.opt_present("V") { println!("{} {}", NAME, VERSION); return 0; } if matches.opt_present("h") { show_usage(&opts); return 0; } if matches.free.is_empty() { show_error!("Missing operand: COMMAND"); println!("Try `{} --help` for more information.", NAME); return 1; } replace_fds(); unsafe { signal(SIGHUP, SIG_IGN) }; if unsafe { _vprocmgr_detach_from_console(0) }!= std::ptr::null() { crash!(2, "Cannot detach from console") }; let cstrs: Vec<CString> = matches .free .iter() .map(|x| CString::new(x.as_bytes()).unwrap()) .collect(); let mut args: Vec<*const c_char> = cstrs.iter().map(|s| s.as_ptr()).collect(); args.push(std::ptr::null()); unsafe { execvp(args[0], args.as_mut_ptr()) } } fn replace_fds() { if is_stdin_interactive() { let new_stdin = match File::open(Path::new("/dev/null")) { Ok(t) => t, Err(e) => crash!(2, "Cannot replace STDIN: {}", e), }; if unsafe { dup2(new_stdin.as_raw_fd(), 0) }!= 0 { crash!(2, "Cannot replace STDIN: {}", Error::last_os_error()) } } if is_stdout_interactive() { let new_stdout = find_stdout(); let fd = new_stdout.as_raw_fd(); if unsafe { dup2(fd, 1) }!= 1 { crash!(2, "Cannot replace STDOUT: {}", Error::last_os_error()) } } if is_stderr_interactive() { if unsafe { dup2(1, 2) }!= 2 { crash!(2, "Cannot replace STDERR: {}", Error::last_os_error()) } } } fn find_stdout() -> File { match OpenOptions::new() .write(true) .create(true) .append(true) .open(Path::new("nohup.out")) { Ok(t) => { show_warning!("Output is redirected to: nohup.out"); t } Err(e) => { let home = match env::var("HOME") { Err(_) => crash!(2, "Cannot replace STDOUT: {}", e), Ok(h) => h, }; let mut homeout = PathBuf::from(home); homeout.push("nohup.out"); match OpenOptions::new() .write(true) .create(true) .append(true) .open(&homeout) { Ok(t) => { show_warning!("Output is redirected to: {:?}", homeout); t } Err(e) => crash!(2, "Cannot replace STDOUT: {}", e), } } } } fn show_usage(opts: &getopts::Options) { let msg = format!( "{0} {1} Usage: {0} COMMAND [ARG]... {0} OPTION Run COMMAND ignoring hangup signals. If standard input is terminal, it'll be replaced with /dev/null. If standard output is terminal, it'll be appended to nohup.out instead, or $HOME/nohup.out, if nohup.out open failed. If standard error is terminal, it'll be redirected to stdout.", NAME, VERSION ); print!("{}", opts.usage(&msg)); }
let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => {
random_line_split
nohup.rs
#![crate_name = "uu_nohup"] /* * This file is part of the uutils coreutils package. * * (c) 2014 Vsevolod Velichko <[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::{c_char, execvp, signal, dup2}; use libc::{SIGHUP, SIG_IGN}; use std::ffi::CString; use std::fs::{File, OpenOptions}; use std::io::Error; use std::os::unix::prelude::*; use std::path::{Path, PathBuf}; use std::env; use uucore::fs::{is_stderr_interactive, is_stdin_interactive, is_stdout_interactive}; static NAME: &'static str = "nohup"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); #[cfg(target_os = "macos")] extern "C" { fn _vprocmgr_detach_from_console(flags: u32) -> *const libc::c_int; } #[cfg(any(target_os = "linux", target_os = "freebsd"))] unsafe fn _vprocmgr_detach_from_console(_: u32) -> *const libc::c_int { std::ptr::null() } pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("h", "help", "Show help and exit"); opts.optflag("V", "version", "Show version and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { show_error!("{}", f); show_usage(&opts); return 1; } }; if matches.opt_present("V") { println!("{} {}", NAME, VERSION); return 0; } if matches.opt_present("h") { show_usage(&opts); return 0; } if matches.free.is_empty() { show_error!("Missing operand: COMMAND"); println!("Try `{} --help` for more information.", NAME); return 1; } replace_fds(); unsafe { signal(SIGHUP, SIG_IGN) }; if unsafe { _vprocmgr_detach_from_console(0) }!= std::ptr::null() { crash!(2, "Cannot detach from console") }; let cstrs: Vec<CString> = matches .free .iter() .map(|x| CString::new(x.as_bytes()).unwrap()) .collect(); let mut args: Vec<*const c_char> = cstrs.iter().map(|s| s.as_ptr()).collect(); args.push(std::ptr::null()); unsafe { execvp(args[0], args.as_mut_ptr()) } } fn
() { if is_stdin_interactive() { let new_stdin = match File::open(Path::new("/dev/null")) { Ok(t) => t, Err(e) => crash!(2, "Cannot replace STDIN: {}", e), }; if unsafe { dup2(new_stdin.as_raw_fd(), 0) }!= 0 { crash!(2, "Cannot replace STDIN: {}", Error::last_os_error()) } } if is_stdout_interactive() { let new_stdout = find_stdout(); let fd = new_stdout.as_raw_fd(); if unsafe { dup2(fd, 1) }!= 1 { crash!(2, "Cannot replace STDOUT: {}", Error::last_os_error()) } } if is_stderr_interactive() { if unsafe { dup2(1, 2) }!= 2 { crash!(2, "Cannot replace STDERR: {}", Error::last_os_error()) } } } fn find_stdout() -> File { match OpenOptions::new() .write(true) .create(true) .append(true) .open(Path::new("nohup.out")) { Ok(t) => { show_warning!("Output is redirected to: nohup.out"); t } Err(e) => { let home = match env::var("HOME") { Err(_) => crash!(2, "Cannot replace STDOUT: {}", e), Ok(h) => h, }; let mut homeout = PathBuf::from(home); homeout.push("nohup.out"); match OpenOptions::new() .write(true) .create(true) .append(true) .open(&homeout) { Ok(t) => { show_warning!("Output is redirected to: {:?}", homeout); t } Err(e) => crash!(2, "Cannot replace STDOUT: {}", e), } } } } fn show_usage(opts: &getopts::Options) { let msg = format!( "{0} {1} Usage: {0} COMMAND [ARG]... {0} OPTION Run COMMAND ignoring hangup signals. If standard input is terminal, it'll be replaced with /dev/null. If standard output is terminal, it'll be appended to nohup.out instead, or $HOME/nohup.out, if nohup.out open failed. If standard error is terminal, it'll be redirected to stdout.", NAME, VERSION ); print!("{}", opts.usage(&msg)); }
replace_fds
identifier_name
nohup.rs
#![crate_name = "uu_nohup"] /* * This file is part of the uutils coreutils package. * * (c) 2014 Vsevolod Velichko <[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::{c_char, execvp, signal, dup2}; use libc::{SIGHUP, SIG_IGN}; use std::ffi::CString; use std::fs::{File, OpenOptions}; use std::io::Error; use std::os::unix::prelude::*; use std::path::{Path, PathBuf}; use std::env; use uucore::fs::{is_stderr_interactive, is_stdin_interactive, is_stdout_interactive}; static NAME: &'static str = "nohup"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); #[cfg(target_os = "macos")] extern "C" { fn _vprocmgr_detach_from_console(flags: u32) -> *const libc::c_int; } #[cfg(any(target_os = "linux", target_os = "freebsd"))] unsafe fn _vprocmgr_detach_from_console(_: u32) -> *const libc::c_int { std::ptr::null() } pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("h", "help", "Show help and exit"); opts.optflag("V", "version", "Show version and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { show_error!("{}", f); show_usage(&opts); return 1; } }; if matches.opt_present("V") { println!("{} {}", NAME, VERSION); return 0; } if matches.opt_present("h") { show_usage(&opts); return 0; } if matches.free.is_empty() { show_error!("Missing operand: COMMAND"); println!("Try `{} --help` for more information.", NAME); return 1; } replace_fds(); unsafe { signal(SIGHUP, SIG_IGN) }; if unsafe { _vprocmgr_detach_from_console(0) }!= std::ptr::null() { crash!(2, "Cannot detach from console") }; let cstrs: Vec<CString> = matches .free .iter() .map(|x| CString::new(x.as_bytes()).unwrap()) .collect(); let mut args: Vec<*const c_char> = cstrs.iter().map(|s| s.as_ptr()).collect(); args.push(std::ptr::null()); unsafe { execvp(args[0], args.as_mut_ptr()) } } fn replace_fds()
if is_stderr_interactive() { if unsafe { dup2(1, 2) }!= 2 { crash!(2, "Cannot replace STDERR: {}", Error::last_os_error()) } } } fn find_stdout() -> File { match OpenOptions::new() .write(true) .create(true) .append(true) .open(Path::new("nohup.out")) { Ok(t) => { show_warning!("Output is redirected to: nohup.out"); t } Err(e) => { let home = match env::var("HOME") { Err(_) => crash!(2, "Cannot replace STDOUT: {}", e), Ok(h) => h, }; let mut homeout = PathBuf::from(home); homeout.push("nohup.out"); match OpenOptions::new() .write(true) .create(true) .append(true) .open(&homeout) { Ok(t) => { show_warning!("Output is redirected to: {:?}", homeout); t } Err(e) => crash!(2, "Cannot replace STDOUT: {}", e), } } } } fn show_usage(opts: &getopts::Options) { let msg = format!( "{0} {1} Usage: {0} COMMAND [ARG]... {0} OPTION Run COMMAND ignoring hangup signals. If standard input is terminal, it'll be replaced with /dev/null. If standard output is terminal, it'll be appended to nohup.out instead, or $HOME/nohup.out, if nohup.out open failed. If standard error is terminal, it'll be redirected to stdout.", NAME, VERSION ); print!("{}", opts.usage(&msg)); }
{ if is_stdin_interactive() { let new_stdin = match File::open(Path::new("/dev/null")) { Ok(t) => t, Err(e) => crash!(2, "Cannot replace STDIN: {}", e), }; if unsafe { dup2(new_stdin.as_raw_fd(), 0) } != 0 { crash!(2, "Cannot replace STDIN: {}", Error::last_os_error()) } } if is_stdout_interactive() { let new_stdout = find_stdout(); let fd = new_stdout.as_raw_fd(); if unsafe { dup2(fd, 1) } != 1 { crash!(2, "Cannot replace STDOUT: {}", Error::last_os_error()) } }
identifier_body
crate.rs
// Copyright 2012-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. #[allow(dead_code)]; use std::path::Path; use std::vec; /// A crate is a unit of Rust code to be compiled into a binary or library #[deriving(Clone)] pub struct Crate { file: Path, flags: ~[~str], cfgs: ~[~str] } impl Crate { pub fn new(p: &Path) -> Crate
fn flag(&self, flag: ~str) -> Crate { Crate { flags: vec::append(self.flags.clone(), [flag]), .. (*self).clone() } } fn flags(&self, flags: ~[~str]) -> Crate { Crate { flags: vec::append(self.flags.clone(), flags), .. (*self).clone() } } fn cfg(&self, cfg: ~str) -> Crate { Crate { cfgs: vec::append(self.cfgs.clone(), [cfg]), .. (*self).clone() } } fn cfgs(&self, cfgs: ~[~str]) -> Crate { Crate { cfgs: vec::append(self.cfgs.clone(), cfgs), .. (*self).clone() } } }
{ Crate { file: (*p).clone(), flags: ~[], cfgs: ~[] } }
identifier_body
crate.rs
// Copyright 2012-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. #[allow(dead_code)]; use std::path::Path; use std::vec; /// A crate is a unit of Rust code to be compiled into a binary or library #[deriving(Clone)]
} impl Crate { pub fn new(p: &Path) -> Crate { Crate { file: (*p).clone(), flags: ~[], cfgs: ~[] } } fn flag(&self, flag: ~str) -> Crate { Crate { flags: vec::append(self.flags.clone(), [flag]), .. (*self).clone() } } fn flags(&self, flags: ~[~str]) -> Crate { Crate { flags: vec::append(self.flags.clone(), flags), .. (*self).clone() } } fn cfg(&self, cfg: ~str) -> Crate { Crate { cfgs: vec::append(self.cfgs.clone(), [cfg]), .. (*self).clone() } } fn cfgs(&self, cfgs: ~[~str]) -> Crate { Crate { cfgs: vec::append(self.cfgs.clone(), cfgs), .. (*self).clone() } } }
pub struct Crate { file: Path, flags: ~[~str], cfgs: ~[~str]
random_line_split
crate.rs
// Copyright 2012-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. #[allow(dead_code)]; use std::path::Path; use std::vec; /// A crate is a unit of Rust code to be compiled into a binary or library #[deriving(Clone)] pub struct Crate { file: Path, flags: ~[~str], cfgs: ~[~str] } impl Crate { pub fn new(p: &Path) -> Crate { Crate { file: (*p).clone(), flags: ~[], cfgs: ~[] } } fn flag(&self, flag: ~str) -> Crate { Crate { flags: vec::append(self.flags.clone(), [flag]), .. (*self).clone() } } fn
(&self, flags: ~[~str]) -> Crate { Crate { flags: vec::append(self.flags.clone(), flags), .. (*self).clone() } } fn cfg(&self, cfg: ~str) -> Crate { Crate { cfgs: vec::append(self.cfgs.clone(), [cfg]), .. (*self).clone() } } fn cfgs(&self, cfgs: ~[~str]) -> Crate { Crate { cfgs: vec::append(self.cfgs.clone(), cfgs), .. (*self).clone() } } }
flags
identifier_name
prune_hidden_pass.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. //! Prunes things with the #[doc(hidden)] attribute use astsrv; use attr_parser; use doc::ItemUtils; use doc; use fold::Fold; use fold; use pass::Pass; pub fn mk_pass() -> Pass
pub fn run(srv: astsrv::Srv, doc: doc::Doc) -> doc::Doc { let fold = Fold { ctxt: srv.clone(), fold_mod: fold_mod, .. fold::default_any_fold(srv) }; (fold.fold_doc)(&fold, doc) } fn fold_mod( fold: &fold::Fold<astsrv::Srv>, doc: doc::ModDoc ) -> doc::ModDoc { let doc = fold::default_any_fold_mod(fold, doc); doc::ModDoc { items: do doc.items.filtered |ItemTag| { !is_hidden(fold.ctxt.clone(), ItemTag.item()) }, .. doc } } fn is_hidden(srv: astsrv::Srv, doc: doc::ItemDoc) -> bool { use syntax::ast_map; let id = doc.id; do astsrv::exec(srv) |ctxt| { let attrs = match *ctxt.ast_map.get(&id) { ast_map::node_item(item, _) => copy item.attrs, _ => ~[] }; attr_parser::parse_hidden(attrs) } } #[test] fn should_prune_hidden_items() { use core::vec; let doc = test::mk_doc(~"#[doc(hidden)] mod a { }"); assert!(vec::is_empty(doc.cratemod().mods())) } #[cfg(test)] pub mod test { use astsrv; use doc; use extract; use prune_hidden_pass::run; pub fn mk_doc(source: ~str) -> doc::Doc { do astsrv::from_str(copy source) |srv| { let doc = extract::from_srv(srv.clone(), ~""); run(srv.clone(), doc) } } }
{ Pass { name: ~"prune_hidden", f: run } }
identifier_body
prune_hidden_pass.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. //! Prunes things with the #[doc(hidden)] attribute use astsrv; use attr_parser; use doc::ItemUtils; use doc; use fold::Fold; use fold; use pass::Pass; pub fn mk_pass() -> Pass { Pass { name: ~"prune_hidden", f: run } } pub fn run(srv: astsrv::Srv, doc: doc::Doc) -> doc::Doc { let fold = Fold { ctxt: srv.clone(), fold_mod: fold_mod, .. fold::default_any_fold(srv) }; (fold.fold_doc)(&fold, doc) } fn fold_mod( fold: &fold::Fold<astsrv::Srv>, doc: doc::ModDoc ) -> doc::ModDoc { let doc = fold::default_any_fold_mod(fold, doc); doc::ModDoc { items: do doc.items.filtered |ItemTag| { !is_hidden(fold.ctxt.clone(), ItemTag.item()) }, .. doc } } fn
(srv: astsrv::Srv, doc: doc::ItemDoc) -> bool { use syntax::ast_map; let id = doc.id; do astsrv::exec(srv) |ctxt| { let attrs = match *ctxt.ast_map.get(&id) { ast_map::node_item(item, _) => copy item.attrs, _ => ~[] }; attr_parser::parse_hidden(attrs) } } #[test] fn should_prune_hidden_items() { use core::vec; let doc = test::mk_doc(~"#[doc(hidden)] mod a { }"); assert!(vec::is_empty(doc.cratemod().mods())) } #[cfg(test)] pub mod test { use astsrv; use doc; use extract; use prune_hidden_pass::run; pub fn mk_doc(source: ~str) -> doc::Doc { do astsrv::from_str(copy source) |srv| { let doc = extract::from_srv(srv.clone(), ~""); run(srv.clone(), doc) } } }
is_hidden
identifier_name
prune_hidden_pass.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. //! Prunes things with the #[doc(hidden)] attribute use astsrv; use attr_parser; use doc::ItemUtils; use doc; use fold::Fold; use fold;
use pass::Pass; pub fn mk_pass() -> Pass { Pass { name: ~"prune_hidden", f: run } } pub fn run(srv: astsrv::Srv, doc: doc::Doc) -> doc::Doc { let fold = Fold { ctxt: srv.clone(), fold_mod: fold_mod, .. fold::default_any_fold(srv) }; (fold.fold_doc)(&fold, doc) } fn fold_mod( fold: &fold::Fold<astsrv::Srv>, doc: doc::ModDoc ) -> doc::ModDoc { let doc = fold::default_any_fold_mod(fold, doc); doc::ModDoc { items: do doc.items.filtered |ItemTag| { !is_hidden(fold.ctxt.clone(), ItemTag.item()) }, .. doc } } fn is_hidden(srv: astsrv::Srv, doc: doc::ItemDoc) -> bool { use syntax::ast_map; let id = doc.id; do astsrv::exec(srv) |ctxt| { let attrs = match *ctxt.ast_map.get(&id) { ast_map::node_item(item, _) => copy item.attrs, _ => ~[] }; attr_parser::parse_hidden(attrs) } } #[test] fn should_prune_hidden_items() { use core::vec; let doc = test::mk_doc(~"#[doc(hidden)] mod a { }"); assert!(vec::is_empty(doc.cratemod().mods())) } #[cfg(test)] pub mod test { use astsrv; use doc; use extract; use prune_hidden_pass::run; pub fn mk_doc(source: ~str) -> doc::Doc { do astsrv::from_str(copy source) |srv| { let doc = extract::from_srv(srv.clone(), ~""); run(srv.clone(), doc) } } }
random_line_split
julian_time.rs
/* * The MIT License (MIT) * * Copyright (c) 2015 Andres Vahter ([email protected]) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ use time; // Calculates Julian Day Number pub fn julian_timestamp(t: time::Tm) -> f64 { let year = t.tm_year + 1900; let month = t.tm_mon + 1; julian_date_of_year(year) + day_of_the_year(year, month, t.tm_mday) as f64 + fraction_of_day(t.tm_hour, t.tm_min, t.tm_sec) + t.tm_nsec as f64 / 1000_f64 / 8.64e+10 } pub fn julian_to_unix(julian: f64) -> time::Tm { let unix = (julian - 2440587.5) * 86400.; let t = time::Timespec::new(unix.trunc() as i64, unix.fract() as i32); time::at(t) } fn fraction_of_day(h: i32, m: i32, s: i32) -> f64
/// Astronomical Formulae for Calculators, Jean Meeus, pages 23-25. /// Calculate Julian Date of 0.0 Jan year fn julian_date_of_year(yr: i32) -> f64 { let year: u64 = yr as u64 -1; let mut i: f64 = (year as f64 / 100.).trunc(); let a: f64 = i; i = (a / 4.).trunc(); let b: f64 = (2. - a + i).trunc(); i = (365.25 * year as f64).trunc(); i += (30.6001_f64 * 14.0_f64).trunc(); i + 1720994.5 + b } /// Calculates the day of the year for the specified date. fn day_of_the_year(yr: i32, mo: i32, dy: i32) -> i32 { let days: [u8; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; let mut day: i32 = 0; for d in &days[0.. mo as usize - 1] { day += *d as i32; } day += dy; if (yr % 4 == 0) && ((yr % 100!= 0) || (yr % 400 == 0)) && (mo > 2) { day += 1; } day } #[test] fn test_julian_timestamp() { // http://en.wikipedia.org/wiki/Julian_day#Converting_Julian_or_Gregorian_calendar_date_to_Julian_Day_Number let t = time::strptime("2000-1-1 12:00:00", "%Y-%m-%d %H:%M:%S").unwrap(); assert_eq!(julian_timestamp(t), 2451545.0); let t = time::strptime("1970-1-1 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap(); assert_eq!(julian_timestamp(t), 2440587.5); }
{ (h as f64 + (m as f64 + s as f64 / 60.0) / 60.0) / 24.0 }
identifier_body
julian_time.rs
/* * The MIT License (MIT) * * Copyright (c) 2015 Andres Vahter ([email protected]) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ use time; // Calculates Julian Day Number pub fn julian_timestamp(t: time::Tm) -> f64 { let year = t.tm_year + 1900; let month = t.tm_mon + 1; julian_date_of_year(year) + day_of_the_year(year, month, t.tm_mday) as f64 + fraction_of_day(t.tm_hour, t.tm_min, t.tm_sec) + t.tm_nsec as f64 / 1000_f64 / 8.64e+10 } pub fn julian_to_unix(julian: f64) -> time::Tm { let unix = (julian - 2440587.5) * 86400.; let t = time::Timespec::new(unix.trunc() as i64, unix.fract() as i32); time::at(t) } fn fraction_of_day(h: i32, m: i32, s: i32) -> f64{ (h as f64 + (m as f64 + s as f64 / 60.0) / 60.0) / 24.0 } /// Astronomical Formulae for Calculators, Jean Meeus, pages 23-25. /// Calculate Julian Date of 0.0 Jan year fn
(yr: i32) -> f64 { let year: u64 = yr as u64 -1; let mut i: f64 = (year as f64 / 100.).trunc(); let a: f64 = i; i = (a / 4.).trunc(); let b: f64 = (2. - a + i).trunc(); i = (365.25 * year as f64).trunc(); i += (30.6001_f64 * 14.0_f64).trunc(); i + 1720994.5 + b } /// Calculates the day of the year for the specified date. fn day_of_the_year(yr: i32, mo: i32, dy: i32) -> i32 { let days: [u8; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; let mut day: i32 = 0; for d in &days[0.. mo as usize - 1] { day += *d as i32; } day += dy; if (yr % 4 == 0) && ((yr % 100!= 0) || (yr % 400 == 0)) && (mo > 2) { day += 1; } day } #[test] fn test_julian_timestamp() { // http://en.wikipedia.org/wiki/Julian_day#Converting_Julian_or_Gregorian_calendar_date_to_Julian_Day_Number let t = time::strptime("2000-1-1 12:00:00", "%Y-%m-%d %H:%M:%S").unwrap(); assert_eq!(julian_timestamp(t), 2451545.0); let t = time::strptime("1970-1-1 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap(); assert_eq!(julian_timestamp(t), 2440587.5); }
julian_date_of_year
identifier_name
julian_time.rs
/* * The MIT License (MIT) * * Copyright (c) 2015 Andres Vahter ([email protected]) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions:
* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ use time; // Calculates Julian Day Number pub fn julian_timestamp(t: time::Tm) -> f64 { let year = t.tm_year + 1900; let month = t.tm_mon + 1; julian_date_of_year(year) + day_of_the_year(year, month, t.tm_mday) as f64 + fraction_of_day(t.tm_hour, t.tm_min, t.tm_sec) + t.tm_nsec as f64 / 1000_f64 / 8.64e+10 } pub fn julian_to_unix(julian: f64) -> time::Tm { let unix = (julian - 2440587.5) * 86400.; let t = time::Timespec::new(unix.trunc() as i64, unix.fract() as i32); time::at(t) } fn fraction_of_day(h: i32, m: i32, s: i32) -> f64{ (h as f64 + (m as f64 + s as f64 / 60.0) / 60.0) / 24.0 } /// Astronomical Formulae for Calculators, Jean Meeus, pages 23-25. /// Calculate Julian Date of 0.0 Jan year fn julian_date_of_year(yr: i32) -> f64 { let year: u64 = yr as u64 -1; let mut i: f64 = (year as f64 / 100.).trunc(); let a: f64 = i; i = (a / 4.).trunc(); let b: f64 = (2. - a + i).trunc(); i = (365.25 * year as f64).trunc(); i += (30.6001_f64 * 14.0_f64).trunc(); i + 1720994.5 + b } /// Calculates the day of the year for the specified date. fn day_of_the_year(yr: i32, mo: i32, dy: i32) -> i32 { let days: [u8; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; let mut day: i32 = 0; for d in &days[0.. mo as usize - 1] { day += *d as i32; } day += dy; if (yr % 4 == 0) && ((yr % 100!= 0) || (yr % 400 == 0)) && (mo > 2) { day += 1; } day } #[test] fn test_julian_timestamp() { // http://en.wikipedia.org/wiki/Julian_day#Converting_Julian_or_Gregorian_calendar_date_to_Julian_Day_Number let t = time::strptime("2000-1-1 12:00:00", "%Y-%m-%d %H:%M:%S").unwrap(); assert_eq!(julian_timestamp(t), 2451545.0); let t = time::strptime("1970-1-1 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap(); assert_eq!(julian_timestamp(t), 2440587.5); }
* * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software.
random_line_split
julian_time.rs
/* * The MIT License (MIT) * * Copyright (c) 2015 Andres Vahter ([email protected]) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ use time; // Calculates Julian Day Number pub fn julian_timestamp(t: time::Tm) -> f64 { let year = t.tm_year + 1900; let month = t.tm_mon + 1; julian_date_of_year(year) + day_of_the_year(year, month, t.tm_mday) as f64 + fraction_of_day(t.tm_hour, t.tm_min, t.tm_sec) + t.tm_nsec as f64 / 1000_f64 / 8.64e+10 } pub fn julian_to_unix(julian: f64) -> time::Tm { let unix = (julian - 2440587.5) * 86400.; let t = time::Timespec::new(unix.trunc() as i64, unix.fract() as i32); time::at(t) } fn fraction_of_day(h: i32, m: i32, s: i32) -> f64{ (h as f64 + (m as f64 + s as f64 / 60.0) / 60.0) / 24.0 } /// Astronomical Formulae for Calculators, Jean Meeus, pages 23-25. /// Calculate Julian Date of 0.0 Jan year fn julian_date_of_year(yr: i32) -> f64 { let year: u64 = yr as u64 -1; let mut i: f64 = (year as f64 / 100.).trunc(); let a: f64 = i; i = (a / 4.).trunc(); let b: f64 = (2. - a + i).trunc(); i = (365.25 * year as f64).trunc(); i += (30.6001_f64 * 14.0_f64).trunc(); i + 1720994.5 + b } /// Calculates the day of the year for the specified date. fn day_of_the_year(yr: i32, mo: i32, dy: i32) -> i32 { let days: [u8; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; let mut day: i32 = 0; for d in &days[0.. mo as usize - 1] { day += *d as i32; } day += dy; if (yr % 4 == 0) && ((yr % 100!= 0) || (yr % 400 == 0)) && (mo > 2)
day } #[test] fn test_julian_timestamp() { // http://en.wikipedia.org/wiki/Julian_day#Converting_Julian_or_Gregorian_calendar_date_to_Julian_Day_Number let t = time::strptime("2000-1-1 12:00:00", "%Y-%m-%d %H:%M:%S").unwrap(); assert_eq!(julian_timestamp(t), 2451545.0); let t = time::strptime("1970-1-1 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap(); assert_eq!(julian_timestamp(t), 2440587.5); }
{ day += 1; }
conditional_block
scale_button.rs
// Copyright 2013-2015, The Rust-GNOME Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! A button which pops up a scale use libc::c_double; use std::ptr; use ffi; /// ScaleButton — A button which pops up a scale /* * # Availables signals : * * `popdown` : Action * * `popup` : Action * * `value-changed` : Run Last */ struct_Widget!(ScaleButton); impl ScaleButton { // FIXME: icons -> last parameter pub fn ne
ize: i32, min: f64, max: f64, step: f64) -> Option<ScaleButton> { let tmp_pointer = unsafe { ffi::gtk_scale_button_new(size, min as c_double, max as c_double, step as c_double, ptr::null_mut()) }; check_pointer!(tmp_pointer, ScaleButton) } } impl_drop!(ScaleButton); impl_TraitWidget!(ScaleButton); impl ::ContainerTrait for ScaleButton {} impl ::ButtonTrait for ScaleButton {} impl ::ScaleButtonTrait for ScaleButton {} impl ::OrientableTrait for ScaleButton {}
w(s
identifier_name
scale_button.rs
// Copyright 2013-2015, The Rust-GNOME Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! A button which pops up a scale use libc::c_double; use std::ptr; use ffi; /// ScaleButton — A button which pops up a scale /* * # Availables signals : * * `popdown` : Action * * `popup` : Action * * `value-changed` : Run Last */ struct_Widget!(ScaleButton); impl ScaleButton { // FIXME: icons -> last parameter pub fn new(size: i32, min: f64, max: f64, step: f64) -> Option<ScaleButton> {
impl_drop!(ScaleButton); impl_TraitWidget!(ScaleButton); impl ::ContainerTrait for ScaleButton {} impl ::ButtonTrait for ScaleButton {} impl ::ScaleButtonTrait for ScaleButton {} impl ::OrientableTrait for ScaleButton {}
let tmp_pointer = unsafe { ffi::gtk_scale_button_new(size, min as c_double, max as c_double, step as c_double, ptr::null_mut()) }; check_pointer!(tmp_pointer, ScaleButton) } }
identifier_body
scale_button.rs
// Copyright 2013-2015, The Rust-GNOME Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! A button which pops up a scale use libc::c_double; use std::ptr; use ffi; /// ScaleButton — A button which pops up a scale /* * # Availables signals : * * `popdown` : Action * * `popup` : Action * * `value-changed` : Run Last */ struct_Widget!(ScaleButton); impl ScaleButton { // FIXME: icons -> last parameter pub fn new(size: i32, min: f64, max: f64, step: f64) -> Option<ScaleButton> { let tmp_pointer = unsafe { ffi::gtk_scale_button_new(size, min as c_double, max as c_double, step as c_double, ptr::null_mut()) }; check_pointer!(tmp_pointer, ScaleButton) } } impl_drop!(ScaleButton); impl_TraitWidget!(ScaleButton);
impl ::ContainerTrait for ScaleButton {} impl ::ButtonTrait for ScaleButton {} impl ::ScaleButtonTrait for ScaleButton {} impl ::OrientableTrait for ScaleButton {}
random_line_split
newtypes.rs
//! Newtype structures. //! //! Mostly implementation of a fixed point Km representation. use std::ops::{Add, Sub, Mul, Div}; use num::Zero; use std::f64; /// Distance measure in kilometers #[derive(Clone, Copy, PartialEq, Debug, Eq, PartialOrd, Ord)] pub struct Km(u64); const POINT : usize = 32; /// Can be cast to a f64 pub trait ToF64 { /// Cast fn to_f64(&self) -> f64; } impl Km { /// Create a new Km struct, or Km::zero if something goes wrong (NaN, Out of Bounds). pub fn from_f64(f: f64) -> Km { Km((f * (1u64<<POINT) as f64) as u64) } /// Create a new Km struct, or None if something goes wrong (NaN, Out of Bounds). /// /// # Examples /// ``` /// use newtypes::Km; /// use std::u32; /// let valid = Km::from_f64_checked(0.0); /// assert!(valid.is_some()); /// let invalid = Km::from_f64_checked(u32::MAX as f64 + 1.0); /// assert_eq!(invalid, None, "Failed at 1"); /// let invalid = Km::from_f64_checked(-1.0); /// assert_eq!(invalid, None, "Failed at 2"); /// ``` pub fn from_f64_checked(f : f64) -> Option<Km> { // Beware rounding errors! if f >= Km(u64::max_value()).to_f64() { None } else if f < Km(u64::min_value()).to_f64() { None } else {Some(Km::from_f64(f))} } } impl ToF64 for Km { fn to_f64(&self) -> f64 { self.0 as f64/((1u64 << POINT) as f64) } } impl ToF64 for Option<Km> { fn to_f64(&self) -> f64 { self.map(|Km(u)| u as f64/((1u64 << POINT) as f64)).unwrap_or(f64::INFINITY) } } impl Add<Km> for Km { type Output = Km; fn
(self, other: Km) -> Km { Km(self.0 + other.0) } } impl Sub<Km> for Km { type Output = Km; fn sub(self, other: Km) -> Km { Km(self.0 - other.0) } } impl Mul<f64> for Km { type Output = Km; fn mul(self, other: f64) -> Km { Km::from_f64(self.to_f64() * other) } } impl Div<Km> for Km { type Output = f64; fn div(self, other: Km) -> f64 { (self.0 as f64 / other.0 as f64) } } impl Div<Option<Km>> for Km { type Output = f64; fn div(self, other: Option<Km>) -> f64 { other.map(|o| (self.0 as f64 / o.0 as f64)) .unwrap_or(0.0) } } impl Zero for Km { fn zero() -> Km { Km(0) } fn is_zero(&self) -> bool { self.0 == 0 } } use std::fmt; impl fmt::Display for Km { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { self.to_f64().fmt(fmt)?; fmt.write_str(" Km") } }
add
identifier_name
newtypes.rs
//! Newtype structures. //! //! Mostly implementation of a fixed point Km representation. use std::ops::{Add, Sub, Mul, Div}; use num::Zero; use std::f64; /// Distance measure in kilometers #[derive(Clone, Copy, PartialEq, Debug, Eq, PartialOrd, Ord)] pub struct Km(u64); const POINT : usize = 32; /// Can be cast to a f64 pub trait ToF64 { /// Cast fn to_f64(&self) -> f64; } impl Km { /// Create a new Km struct, or Km::zero if something goes wrong (NaN, Out of Bounds). pub fn from_f64(f: f64) -> Km { Km((f * (1u64<<POINT) as f64) as u64) } /// Create a new Km struct, or None if something goes wrong (NaN, Out of Bounds). /// /// # Examples /// ``` /// use newtypes::Km; /// use std::u32; /// let valid = Km::from_f64_checked(0.0); /// assert!(valid.is_some()); /// let invalid = Km::from_f64_checked(u32::MAX as f64 + 1.0); /// assert_eq!(invalid, None, "Failed at 1"); /// let invalid = Km::from_f64_checked(-1.0); /// assert_eq!(invalid, None, "Failed at 2"); /// ``` pub fn from_f64_checked(f : f64) -> Option<Km> { // Beware rounding errors! if f >= Km(u64::max_value()).to_f64() { None } else if f < Km(u64::min_value()).to_f64() { None } else {Some(Km::from_f64(f))} } } impl ToF64 for Km { fn to_f64(&self) -> f64
} impl ToF64 for Option<Km> { fn to_f64(&self) -> f64 { self.map(|Km(u)| u as f64/((1u64 << POINT) as f64)).unwrap_or(f64::INFINITY) } } impl Add<Km> for Km { type Output = Km; fn add(self, other: Km) -> Km { Km(self.0 + other.0) } } impl Sub<Km> for Km { type Output = Km; fn sub(self, other: Km) -> Km { Km(self.0 - other.0) } } impl Mul<f64> for Km { type Output = Km; fn mul(self, other: f64) -> Km { Km::from_f64(self.to_f64() * other) } } impl Div<Km> for Km { type Output = f64; fn div(self, other: Km) -> f64 { (self.0 as f64 / other.0 as f64) } } impl Div<Option<Km>> for Km { type Output = f64; fn div(self, other: Option<Km>) -> f64 { other.map(|o| (self.0 as f64 / o.0 as f64)) .unwrap_or(0.0) } } impl Zero for Km { fn zero() -> Km { Km(0) } fn is_zero(&self) -> bool { self.0 == 0 } } use std::fmt; impl fmt::Display for Km { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { self.to_f64().fmt(fmt)?; fmt.write_str(" Km") } }
{ self.0 as f64/((1u64 << POINT) as f64) }
identifier_body
newtypes.rs
//! Newtype structures. //! //! Mostly implementation of a fixed point Km representation. use std::ops::{Add, Sub, Mul, Div}; use num::Zero; use std::f64; /// Distance measure in kilometers #[derive(Clone, Copy, PartialEq, Debug, Eq, PartialOrd, Ord)] pub struct Km(u64); const POINT : usize = 32; /// Can be cast to a f64 pub trait ToF64 { /// Cast fn to_f64(&self) -> f64; } impl Km { /// Create a new Km struct, or Km::zero if something goes wrong (NaN, Out of Bounds). pub fn from_f64(f: f64) -> Km { Km((f * (1u64<<POINT) as f64) as u64) } /// Create a new Km struct, or None if something goes wrong (NaN, Out of Bounds). ///
/// use std::u32; /// let valid = Km::from_f64_checked(0.0); /// assert!(valid.is_some()); /// let invalid = Km::from_f64_checked(u32::MAX as f64 + 1.0); /// assert_eq!(invalid, None, "Failed at 1"); /// let invalid = Km::from_f64_checked(-1.0); /// assert_eq!(invalid, None, "Failed at 2"); /// ``` pub fn from_f64_checked(f : f64) -> Option<Km> { // Beware rounding errors! if f >= Km(u64::max_value()).to_f64() { None } else if f < Km(u64::min_value()).to_f64() { None } else {Some(Km::from_f64(f))} } } impl ToF64 for Km { fn to_f64(&self) -> f64 { self.0 as f64/((1u64 << POINT) as f64) } } impl ToF64 for Option<Km> { fn to_f64(&self) -> f64 { self.map(|Km(u)| u as f64/((1u64 << POINT) as f64)).unwrap_or(f64::INFINITY) } } impl Add<Km> for Km { type Output = Km; fn add(self, other: Km) -> Km { Km(self.0 + other.0) } } impl Sub<Km> for Km { type Output = Km; fn sub(self, other: Km) -> Km { Km(self.0 - other.0) } } impl Mul<f64> for Km { type Output = Km; fn mul(self, other: f64) -> Km { Km::from_f64(self.to_f64() * other) } } impl Div<Km> for Km { type Output = f64; fn div(self, other: Km) -> f64 { (self.0 as f64 / other.0 as f64) } } impl Div<Option<Km>> for Km { type Output = f64; fn div(self, other: Option<Km>) -> f64 { other.map(|o| (self.0 as f64 / o.0 as f64)) .unwrap_or(0.0) } } impl Zero for Km { fn zero() -> Km { Km(0) } fn is_zero(&self) -> bool { self.0 == 0 } } use std::fmt; impl fmt::Display for Km { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { self.to_f64().fmt(fmt)?; fmt.write_str(" Km") } }
/// # Examples /// ``` /// use newtypes::Km;
random_line_split
lib.rs
extern crate libc; extern crate disasm6502; use libc::*; use std::ffi::CString; const MY_NAME : *const c_char = b"6502.rs\0" as *const [u8] as *const c_char; const R2_VERSION: &'static [u8] = b"1.2.0-git\0"; const MY_ARCH : &'static [u8] = b"6502\0"; const MY_DESC : &'static [u8] = b"6502 disassembler in Rust\0"; const MY_LICENSE : &'static [u8] = b"MIT\0"; // order matters because of libr/util/lib.c #[repr(C,i32)] pub enum RLibType { RLibTypeIo = 0, RLibTypeDbg = 1, RLibTypeLang = 2, RLibTypeAsm = 3, RLibTypeAnal = 4, RLibTypeParse = 5, RLibTypeBin = 6, RLibTypeBinXtr = 7, RLibTypeBp = 8, RLibTypeSyscall = 9, RLibTypeFastcall = 10, RLibTypeCrypto = 11, RLibTypeCore = 12, RLibTypeEgg = 13, RLibTypeFs = 14, RLibTypeLast = 15, } #[repr(C)] pub struct RAsmPlugin { name: *const c_char, arch: *const c_char, cpus: *const c_char, desc: *const c_char, license: *const c_char, //c_char, user: usize, bits: c_int, endian: c_int, pub init: Option<extern "C" fn(*mut c_void) -> bool>, pub fini: Option<extern "C" fn(*mut c_void) -> bool>, pub disassemble: Option<extern "C" fn(*const c_void, *mut RAsmOp, *const uint8_t, c_int) -> c_int>, pub assemble: Option<extern "C" fn(*const c_void, *const c_char) -> c_int>, pub modify: Option<extern "C" fn(*mut c_void, *mut uint8_t, c_int, uint64_t) -> c_int>, pub set_subarch: Option<extern "C" fn(*const c_void, *const c_char) -> c_int>, pub mnemonics: Option<extern "C" fn(*const c_void, c_int, bool) -> *mut c_char>, features: *const [u8] } const sz: usize = 256; type RAsmOpString = [c_char; sz]; #[repr(C)] pub struct RAsmOp { size: c_int, payload: c_int, buf: RAsmOpString, buf_asm: RAsmOpString, buf_hex: RAsmOpString } #[repr(C)] pub struct RLibHandler { pub _type: c_int, pub desc: [c_char; 128], pub user: *const c_void, pub constructor: extern "C" fn(*const RLibPlugin, *mut c_void, *mut c_void), pub destructor: extern "C" fn(*const RLibPlugin, *mut c_void, *mut c_void), } #[repr(C)] pub struct RLibPlugin { pub _type: c_int, pub file: *const c_char, pub data: *const c_void, pub handler: *const RLibHandler, pub dl_handler: *const c_void } #[repr(C)] pub struct RLibStruct { pub _type: RLibType, pub data: *const c_void, pub version: *const [u8] } extern "C" fn _disassemble (asm: *const c_void, asmop: *mut RAsmOp, buf: *const u8, len: c_int) -> c_int { let oplen : usize = std::cmp::min(len, 3) as usize; unsafe { let bytes = std::slice::from_raw_parts(buf as *const u8, oplen); if let Ok(instructions) = disasm6502::from_addr_array(bytes, 0) { if instructions.len() > 0 as usize { let ref ins = instructions[0]; if ins.illegal
let opstr = ins.as_str(); let hexstr = ins.as_hex_str().replace(" ", ""); let inslen = (hexstr.len() / 2) as c_int; (*asmop).size = inslen; (*asmop).payload = 0; (*asmop).buf_asm[0] = 0; let opstrlen = std::cmp::min(opstr.len(), sz); std::ptr::copy( opstr.as_bytes() as *const [u8] as *const c_char, &mut (*asmop).buf_asm as *mut [c_char] as *mut c_char, opstrlen); std::ptr::copy( hexstr.as_bytes() as *const [u8] as *const c_char, &mut (*asmop).buf_hex as *mut [c_char] as *mut c_char, opstrlen); std::ptr::copy( &buf, // as *const [u8] as *const c_char, &mut (*asmop).buf as *mut [c_char] as *mut *const u8, opstrlen); return inslen; } } } -1 } /* extern "C" fn _init (foo: *mut c_void) -> bool { true } extern "C" fn _mnemonics (foo: *const c_void, bar: c_int, cow: bool) -> *mut c_char { b"\0".as_ptr() as *mut c_char } extern "C" fn _assemble (asm: *const c_void, str: *const c_char) -> c_int { 0 } extern "C" fn _modify (asm: *mut c_void, buf: *mut uint8_t, len: c_int, at: uint64_t) -> c_int { 0 } extern "C" fn _set_subarch (asm: *const c_void, arch: *const c_char) -> c_int { 0 } */ const r_asm_plugin_6502rs: RAsmPlugin = RAsmPlugin { name : MY_NAME, arch : MY_ARCH as *const [u8] as *const c_char, license : MY_LICENSE as *const [u8] as *const c_char, user : 0, cpus : b"\0" as *const [u8] as *const c_char, desc : MY_DESC as *const [u8] as *const c_char, bits : 16, endian: 0, disassemble: Some(_disassemble), assemble: None, //Some(_assemble), init: None, fini: None, modify: None, //_modify, set_subarch: None, //_set_subarch, mnemonics: None, //_mnemonics, features: b"\0" }; #[no_mangle] #[allow(non_upper_case_globals)] pub static mut radare_plugin: RLibStruct = RLibStruct { _type : RLibType::RLibTypeAsm, data : ((&r_asm_plugin_6502rs) as *const RAsmPlugin) as *const c_void, version : R2_VERSION }; #[cfg(test)] mod tests { #[test] fn it_works() { } }
{ (*asmop).payload = 0; (*asmop).size = 1; return -1; }
conditional_block
lib.rs
extern crate libc; extern crate disasm6502; use libc::*; use std::ffi::CString; const MY_NAME : *const c_char = b"6502.rs\0" as *const [u8] as *const c_char; const R2_VERSION: &'static [u8] = b"1.2.0-git\0"; const MY_ARCH : &'static [u8] = b"6502\0"; const MY_DESC : &'static [u8] = b"6502 disassembler in Rust\0"; const MY_LICENSE : &'static [u8] = b"MIT\0"; // order matters because of libr/util/lib.c #[repr(C,i32)] pub enum
{ RLibTypeIo = 0, RLibTypeDbg = 1, RLibTypeLang = 2, RLibTypeAsm = 3, RLibTypeAnal = 4, RLibTypeParse = 5, RLibTypeBin = 6, RLibTypeBinXtr = 7, RLibTypeBp = 8, RLibTypeSyscall = 9, RLibTypeFastcall = 10, RLibTypeCrypto = 11, RLibTypeCore = 12, RLibTypeEgg = 13, RLibTypeFs = 14, RLibTypeLast = 15, } #[repr(C)] pub struct RAsmPlugin { name: *const c_char, arch: *const c_char, cpus: *const c_char, desc: *const c_char, license: *const c_char, //c_char, user: usize, bits: c_int, endian: c_int, pub init: Option<extern "C" fn(*mut c_void) -> bool>, pub fini: Option<extern "C" fn(*mut c_void) -> bool>, pub disassemble: Option<extern "C" fn(*const c_void, *mut RAsmOp, *const uint8_t, c_int) -> c_int>, pub assemble: Option<extern "C" fn(*const c_void, *const c_char) -> c_int>, pub modify: Option<extern "C" fn(*mut c_void, *mut uint8_t, c_int, uint64_t) -> c_int>, pub set_subarch: Option<extern "C" fn(*const c_void, *const c_char) -> c_int>, pub mnemonics: Option<extern "C" fn(*const c_void, c_int, bool) -> *mut c_char>, features: *const [u8] } const sz: usize = 256; type RAsmOpString = [c_char; sz]; #[repr(C)] pub struct RAsmOp { size: c_int, payload: c_int, buf: RAsmOpString, buf_asm: RAsmOpString, buf_hex: RAsmOpString } #[repr(C)] pub struct RLibHandler { pub _type: c_int, pub desc: [c_char; 128], pub user: *const c_void, pub constructor: extern "C" fn(*const RLibPlugin, *mut c_void, *mut c_void), pub destructor: extern "C" fn(*const RLibPlugin, *mut c_void, *mut c_void), } #[repr(C)] pub struct RLibPlugin { pub _type: c_int, pub file: *const c_char, pub data: *const c_void, pub handler: *const RLibHandler, pub dl_handler: *const c_void } #[repr(C)] pub struct RLibStruct { pub _type: RLibType, pub data: *const c_void, pub version: *const [u8] } extern "C" fn _disassemble (asm: *const c_void, asmop: *mut RAsmOp, buf: *const u8, len: c_int) -> c_int { let oplen : usize = std::cmp::min(len, 3) as usize; unsafe { let bytes = std::slice::from_raw_parts(buf as *const u8, oplen); if let Ok(instructions) = disasm6502::from_addr_array(bytes, 0) { if instructions.len() > 0 as usize { let ref ins = instructions[0]; if ins.illegal { (*asmop).payload = 0; (*asmop).size = 1; return -1; } let opstr = ins.as_str(); let hexstr = ins.as_hex_str().replace(" ", ""); let inslen = (hexstr.len() / 2) as c_int; (*asmop).size = inslen; (*asmop).payload = 0; (*asmop).buf_asm[0] = 0; let opstrlen = std::cmp::min(opstr.len(), sz); std::ptr::copy( opstr.as_bytes() as *const [u8] as *const c_char, &mut (*asmop).buf_asm as *mut [c_char] as *mut c_char, opstrlen); std::ptr::copy( hexstr.as_bytes() as *const [u8] as *const c_char, &mut (*asmop).buf_hex as *mut [c_char] as *mut c_char, opstrlen); std::ptr::copy( &buf, // as *const [u8] as *const c_char, &mut (*asmop).buf as *mut [c_char] as *mut *const u8, opstrlen); return inslen; } } } -1 } /* extern "C" fn _init (foo: *mut c_void) -> bool { true } extern "C" fn _mnemonics (foo: *const c_void, bar: c_int, cow: bool) -> *mut c_char { b"\0".as_ptr() as *mut c_char } extern "C" fn _assemble (asm: *const c_void, str: *const c_char) -> c_int { 0 } extern "C" fn _modify (asm: *mut c_void, buf: *mut uint8_t, len: c_int, at: uint64_t) -> c_int { 0 } extern "C" fn _set_subarch (asm: *const c_void, arch: *const c_char) -> c_int { 0 } */ const r_asm_plugin_6502rs: RAsmPlugin = RAsmPlugin { name : MY_NAME, arch : MY_ARCH as *const [u8] as *const c_char, license : MY_LICENSE as *const [u8] as *const c_char, user : 0, cpus : b"\0" as *const [u8] as *const c_char, desc : MY_DESC as *const [u8] as *const c_char, bits : 16, endian: 0, disassemble: Some(_disassemble), assemble: None, //Some(_assemble), init: None, fini: None, modify: None, //_modify, set_subarch: None, //_set_subarch, mnemonics: None, //_mnemonics, features: b"\0" }; #[no_mangle] #[allow(non_upper_case_globals)] pub static mut radare_plugin: RLibStruct = RLibStruct { _type : RLibType::RLibTypeAsm, data : ((&r_asm_plugin_6502rs) as *const RAsmPlugin) as *const c_void, version : R2_VERSION }; #[cfg(test)] mod tests { #[test] fn it_works() { } }
RLibType
identifier_name
lib.rs
extern crate libc; extern crate disasm6502; use libc::*; use std::ffi::CString; const MY_NAME : *const c_char = b"6502.rs\0" as *const [u8] as *const c_char; const R2_VERSION: &'static [u8] = b"1.2.0-git\0"; const MY_ARCH : &'static [u8] = b"6502\0"; const MY_DESC : &'static [u8] = b"6502 disassembler in Rust\0"; const MY_LICENSE : &'static [u8] = b"MIT\0"; // order matters because of libr/util/lib.c #[repr(C,i32)] pub enum RLibType { RLibTypeIo = 0, RLibTypeDbg = 1, RLibTypeLang = 2, RLibTypeAsm = 3, RLibTypeAnal = 4, RLibTypeParse = 5, RLibTypeBin = 6, RLibTypeBinXtr = 7, RLibTypeBp = 8, RLibTypeSyscall = 9, RLibTypeFastcall = 10, RLibTypeCrypto = 11, RLibTypeCore = 12, RLibTypeEgg = 13, RLibTypeFs = 14, RLibTypeLast = 15, } #[repr(C)] pub struct RAsmPlugin { name: *const c_char, arch: *const c_char, cpus: *const c_char, desc: *const c_char, license: *const c_char, //c_char, user: usize, bits: c_int, endian: c_int, pub init: Option<extern "C" fn(*mut c_void) -> bool>, pub fini: Option<extern "C" fn(*mut c_void) -> bool>, pub disassemble: Option<extern "C" fn(*const c_void, *mut RAsmOp, *const uint8_t, c_int) -> c_int>, pub assemble: Option<extern "C" fn(*const c_void, *const c_char) -> c_int>, pub modify: Option<extern "C" fn(*mut c_void, *mut uint8_t, c_int, uint64_t) -> c_int>, pub set_subarch: Option<extern "C" fn(*const c_void, *const c_char) -> c_int>, pub mnemonics: Option<extern "C" fn(*const c_void, c_int, bool) -> *mut c_char>, features: *const [u8] } const sz: usize = 256; type RAsmOpString = [c_char; sz]; #[repr(C)] pub struct RAsmOp { size: c_int, payload: c_int, buf: RAsmOpString, buf_asm: RAsmOpString, buf_hex: RAsmOpString } #[repr(C)] pub struct RLibHandler { pub _type: c_int, pub desc: [c_char; 128], pub user: *const c_void, pub constructor: extern "C" fn(*const RLibPlugin, *mut c_void, *mut c_void), pub destructor: extern "C" fn(*const RLibPlugin, *mut c_void, *mut c_void), } #[repr(C)] pub struct RLibPlugin { pub _type: c_int, pub file: *const c_char, pub data: *const c_void, pub handler: *const RLibHandler, pub dl_handler: *const c_void } #[repr(C)] pub struct RLibStruct { pub _type: RLibType, pub data: *const c_void, pub version: *const [u8] } extern "C" fn _disassemble (asm: *const c_void, asmop: *mut RAsmOp, buf: *const u8, len: c_int) -> c_int { let oplen : usize = std::cmp::min(len, 3) as usize; unsafe { let bytes = std::slice::from_raw_parts(buf as *const u8, oplen); if let Ok(instructions) = disasm6502::from_addr_array(bytes, 0) { if instructions.len() > 0 as usize { let ref ins = instructions[0]; if ins.illegal { (*asmop).payload = 0; (*asmop).size = 1; return -1; } let opstr = ins.as_str(); let hexstr = ins.as_hex_str().replace(" ", ""); let inslen = (hexstr.len() / 2) as c_int; (*asmop).size = inslen; (*asmop).payload = 0; (*asmop).buf_asm[0] = 0; let opstrlen = std::cmp::min(opstr.len(), sz); std::ptr::copy( opstr.as_bytes() as *const [u8] as *const c_char, &mut (*asmop).buf_asm as *mut [c_char] as *mut c_char, opstrlen); std::ptr::copy( hexstr.as_bytes() as *const [u8] as *const c_char, &mut (*asmop).buf_hex as *mut [c_char] as *mut c_char,
return inslen; } } } -1 } /* extern "C" fn _init (foo: *mut c_void) -> bool { true } extern "C" fn _mnemonics (foo: *const c_void, bar: c_int, cow: bool) -> *mut c_char { b"\0".as_ptr() as *mut c_char } extern "C" fn _assemble (asm: *const c_void, str: *const c_char) -> c_int { 0 } extern "C" fn _modify (asm: *mut c_void, buf: *mut uint8_t, len: c_int, at: uint64_t) -> c_int { 0 } extern "C" fn _set_subarch (asm: *const c_void, arch: *const c_char) -> c_int { 0 } */ const r_asm_plugin_6502rs: RAsmPlugin = RAsmPlugin { name : MY_NAME, arch : MY_ARCH as *const [u8] as *const c_char, license : MY_LICENSE as *const [u8] as *const c_char, user : 0, cpus : b"\0" as *const [u8] as *const c_char, desc : MY_DESC as *const [u8] as *const c_char, bits : 16, endian: 0, disassemble: Some(_disassemble), assemble: None, //Some(_assemble), init: None, fini: None, modify: None, //_modify, set_subarch: None, //_set_subarch, mnemonics: None, //_mnemonics, features: b"\0" }; #[no_mangle] #[allow(non_upper_case_globals)] pub static mut radare_plugin: RLibStruct = RLibStruct { _type : RLibType::RLibTypeAsm, data : ((&r_asm_plugin_6502rs) as *const RAsmPlugin) as *const c_void, version : R2_VERSION }; #[cfg(test)] mod tests { #[test] fn it_works() { } }
opstrlen); std::ptr::copy( &buf, // as *const [u8] as *const c_char, &mut (*asmop).buf as *mut [c_char] as *mut *const u8, opstrlen);
random_line_split
marking.rs
use crate::gc::root::Slot; use crate::gc::{Address, Region}; pub fn start(rootset: &[Slot], heap: Region, perm: Region) { let mut marking_stack: Vec<Address> = Vec::new(); for root in rootset { let root_ptr = root.get(); if heap.contains(root_ptr) { let root_obj = root_ptr.to_mut_obj(); if!root_obj.header().is_marked_non_atomic() { marking_stack.push(root_ptr); root_obj.header_mut().mark_non_atomic(); } } else { debug_assert!(root_ptr.is_null() || perm.contains(root_ptr)); } } while marking_stack.len() > 0 { let object_addr = marking_stack.pop().expect("stack already empty"); let object = object_addr.to_mut_obj(); object.visit_reference_fields(|field| { let field_addr = field.get(); if heap.contains(field_addr)
else { debug_assert!(field_addr.is_null() || perm.contains(field_addr)); } }); } }
{ let field_obj = field_addr.to_mut_obj(); if !field_obj.header().is_marked_non_atomic() { marking_stack.push(field_addr); field_obj.header_mut().mark_non_atomic(); } }
conditional_block
marking.rs
use crate::gc::root::Slot; use crate::gc::{Address, Region}; pub fn start(rootset: &[Slot], heap: Region, perm: Region) { let mut marking_stack: Vec<Address> = Vec::new(); for root in rootset { let root_ptr = root.get(); if heap.contains(root_ptr) { let root_obj = root_ptr.to_mut_obj(); if!root_obj.header().is_marked_non_atomic() { marking_stack.push(root_ptr); root_obj.header_mut().mark_non_atomic(); } } else { debug_assert!(root_ptr.is_null() || perm.contains(root_ptr)); } } while marking_stack.len() > 0 { let object_addr = marking_stack.pop().expect("stack already empty"); let object = object_addr.to_mut_obj(); object.visit_reference_fields(|field| { let field_addr = field.get();
marking_stack.push(field_addr); field_obj.header_mut().mark_non_atomic(); } } else { debug_assert!(field_addr.is_null() || perm.contains(field_addr)); } }); } }
if heap.contains(field_addr) { let field_obj = field_addr.to_mut_obj(); if !field_obj.header().is_marked_non_atomic() {
random_line_split
marking.rs
use crate::gc::root::Slot; use crate::gc::{Address, Region}; pub fn start(rootset: &[Slot], heap: Region, perm: Region)
let object = object_addr.to_mut_obj(); object.visit_reference_fields(|field| { let field_addr = field.get(); if heap.contains(field_addr) { let field_obj = field_addr.to_mut_obj(); if!field_obj.header().is_marked_non_atomic() { marking_stack.push(field_addr); field_obj.header_mut().mark_non_atomic(); } } else { debug_assert!(field_addr.is_null() || perm.contains(field_addr)); } }); } }
{ let mut marking_stack: Vec<Address> = Vec::new(); for root in rootset { let root_ptr = root.get(); if heap.contains(root_ptr) { let root_obj = root_ptr.to_mut_obj(); if !root_obj.header().is_marked_non_atomic() { marking_stack.push(root_ptr); root_obj.header_mut().mark_non_atomic(); } } else { debug_assert!(root_ptr.is_null() || perm.contains(root_ptr)); } } while marking_stack.len() > 0 { let object_addr = marking_stack.pop().expect("stack already empty");
identifier_body
marking.rs
use crate::gc::root::Slot; use crate::gc::{Address, Region}; pub fn
(rootset: &[Slot], heap: Region, perm: Region) { let mut marking_stack: Vec<Address> = Vec::new(); for root in rootset { let root_ptr = root.get(); if heap.contains(root_ptr) { let root_obj = root_ptr.to_mut_obj(); if!root_obj.header().is_marked_non_atomic() { marking_stack.push(root_ptr); root_obj.header_mut().mark_non_atomic(); } } else { debug_assert!(root_ptr.is_null() || perm.contains(root_ptr)); } } while marking_stack.len() > 0 { let object_addr = marking_stack.pop().expect("stack already empty"); let object = object_addr.to_mut_obj(); object.visit_reference_fields(|field| { let field_addr = field.get(); if heap.contains(field_addr) { let field_obj = field_addr.to_mut_obj(); if!field_obj.header().is_marked_non_atomic() { marking_stack.push(field_addr); field_obj.header_mut().mark_non_atomic(); } } else { debug_assert!(field_addr.is_null() || perm.contains(field_addr)); } }); } }
start
identifier_name
value.rs
/* This module collects value functions. */ use std::str::FromStr; use game; use game::{LineState, Position3, Position2}; #[derive(Clone, Copy, Debug)] pub enum Simple { Subsets, WinOnly, } impl Simple { pub fn value_of(self, state: &game::State, my_color: game::Color) -> i32 { match self { Simple::Subsets => subsets(state, my_color), Simple::WinOnly => win_only(state, my_color), } } } impl FromStr for Simple { type Err = (); fn from_str(s: &str) -> Result<Simple, ()> { match s { "subsets" => Ok(Simple::Subsets), "win" => Ok(Simple::WinOnly), _ => Err(()), } } } // For each possible winning subset, this adds some score. // One piece on a line => 1 Point // Two pieces on a line => 4 Points // Three pieces on a line => 9 Points pub fn subsets(state: &game::State, my_color: game::Color) -> i32 { if let game::VictoryState::Win { winner,.. } = state.victory_state { if winner == my_color { return 1000; } else { return -1000; } } let mut score = 0; for subset in &state.structure.source { score += match subset.win_state(state) { LineState::Empty => 0, LineState::Mixed => 0, LineState::Pure { color, count } => { if color == my_color { (count * count) as i32 } else { -(count * count) as i32 } } LineState::Win(_) => { panic!("If the game is already won this should be caught earlier.") } } } score } #[test] fn test_subsets_values() { use game::{Structure, State, Position2}; use game::Color::White; use std::sync::Arc; use constants::LINES; let structure = Structure::new(&LINES); let mut state = State::new(Arc::new(structure)); assert_eq!(0, subsets(&state, White)); state.insert(Position2::new(0, 0)); assert_eq!(7, subsets(&state, White)); state.insert(Position2::new(0, 3)); assert_eq!(0, subsets(&state, White)); } // This value function only checks if you won the game already. pub fn win_only(state: &game::State, my_color: game::Color) -> i32 { if let game::VictoryState::Win { winner,.. } = state.victory_state { if winner == my_color { return 1; } else { return -1; } } else { 0
/* New idea/project for a value function. Give each point a value, then each column and in conclusion, give one to the whole board (if desired). This can also be used to pick which actions to inspect further. */ // How much a particular action is worth to a player. The LastMissingPiece // variant indicates that playing this action wins the game. // The DirectLoss variant indicates that the player is sure to loose by playing this. #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum SideValue { // Do I win if I place here? LastMissingPiece, // Or do I at least get a piece which aligns with a lot of other pieces? Heuristic(i32), DirectLoss, } // Calculates the point value for White and Black. #[allow(dead_code)] fn point_value(state: &game::State, position: Position3) -> Option<(SideValue, SideValue)> { use game::Color::White; // This is only defined for empty positions. if let game::PointState::Piece(_) = state.at(position) { return None; } let mut white_value = 0; let mut black_value = 0; let mut last_white_piece = false; let mut last_black_piece = false; for subset_index in &state.structure.reverse[position.0 as usize] { let subset = state.structure.source[*subset_index]; let win_state = subset.win_state(state); match win_state { game::LineState::Empty => { white_value += 1; black_value += 1; } game::LineState::Pure { color, count } => { let total_count = count as i32 + 1; if total_count == state.structure.object_size as i32 { if color == White { last_white_piece = true; } else { last_black_piece = true; } } else { if color == White { white_value += total_count * total_count; } else { black_value += total_count * total_count; } } } game::LineState::Mixed => {} game::LineState::Win(_) => { // We made sure that there is at least one empty position. unreachable!(); } } } let white_point_value = if last_white_piece { SideValue::LastMissingPiece } else { SideValue::Heuristic(white_value) }; let black_point_value = if last_black_piece { SideValue::LastMissingPiece } else { SideValue::Heuristic(black_value) }; Some((white_point_value, black_point_value)) } // Is this column worth playing at? #[allow(dead_code)] fn column_value(state: &game::State, position: Position2) -> Option<(SideValue, SideValue)> { use self::SideValue::{LastMissingPiece, Heuristic, DirectLoss}; let height: u8 = state.column_height[position.0 as usize]; match height { 4 => None, 3 => point_value(state, position.with_height(3)), h => { let (white_placement_value, black_placement_value) = point_value(state, position.with_height(h)).unwrap(); let (white_response_value, black_response_value) = point_value(state, position.with_height(h + 1)).unwrap(); let white_value = { if let Heuristic(w) = white_placement_value { if let Heuristic(b) = black_response_value { Heuristic(w - b) } else { DirectLoss } } else { LastMissingPiece } }; let black_value = { if let Heuristic(b) = black_placement_value { if let Heuristic(w) = white_response_value { Heuristic(b - w) } else { DirectLoss } } else { LastMissingPiece } }; Some((white_value, black_value)) } } }
} }
random_line_split
value.rs
/* This module collects value functions. */ use std::str::FromStr; use game; use game::{LineState, Position3, Position2}; #[derive(Clone, Copy, Debug)] pub enum Simple { Subsets, WinOnly, } impl Simple { pub fn value_of(self, state: &game::State, my_color: game::Color) -> i32 { match self { Simple::Subsets => subsets(state, my_color), Simple::WinOnly => win_only(state, my_color), } } } impl FromStr for Simple { type Err = (); fn from_str(s: &str) -> Result<Simple, ()> { match s { "subsets" => Ok(Simple::Subsets), "win" => Ok(Simple::WinOnly), _ => Err(()), } } } // For each possible winning subset, this adds some score. // One piece on a line => 1 Point // Two pieces on a line => 4 Points // Three pieces on a line => 9 Points pub fn subsets(state: &game::State, my_color: game::Color) -> i32 { if let game::VictoryState::Win { winner,.. } = state.victory_state { if winner == my_color { return 1000; } else { return -1000; } } let mut score = 0; for subset in &state.structure.source { score += match subset.win_state(state) { LineState::Empty => 0, LineState::Mixed => 0, LineState::Pure { color, count } => { if color == my_color { (count * count) as i32 } else { -(count * count) as i32 } } LineState::Win(_) => { panic!("If the game is already won this should be caught earlier.") } } } score } #[test] fn test_subsets_values() { use game::{Structure, State, Position2}; use game::Color::White; use std::sync::Arc; use constants::LINES; let structure = Structure::new(&LINES); let mut state = State::new(Arc::new(structure)); assert_eq!(0, subsets(&state, White)); state.insert(Position2::new(0, 0)); assert_eq!(7, subsets(&state, White)); state.insert(Position2::new(0, 3)); assert_eq!(0, subsets(&state, White)); } // This value function only checks if you won the game already. pub fn win_only(state: &game::State, my_color: game::Color) -> i32 { if let game::VictoryState::Win { winner,.. } = state.victory_state { if winner == my_color { return 1; } else { return -1; } } else { 0 } } /* New idea/project for a value function. Give each point a value, then each column and in conclusion, give one to the whole board (if desired). This can also be used to pick which actions to inspect further. */ // How much a particular action is worth to a player. The LastMissingPiece // variant indicates that playing this action wins the game. // The DirectLoss variant indicates that the player is sure to loose by playing this. #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum SideValue { // Do I win if I place here? LastMissingPiece, // Or do I at least get a piece which aligns with a lot of other pieces? Heuristic(i32), DirectLoss, } // Calculates the point value for White and Black. #[allow(dead_code)] fn
(state: &game::State, position: Position3) -> Option<(SideValue, SideValue)> { use game::Color::White; // This is only defined for empty positions. if let game::PointState::Piece(_) = state.at(position) { return None; } let mut white_value = 0; let mut black_value = 0; let mut last_white_piece = false; let mut last_black_piece = false; for subset_index in &state.structure.reverse[position.0 as usize] { let subset = state.structure.source[*subset_index]; let win_state = subset.win_state(state); match win_state { game::LineState::Empty => { white_value += 1; black_value += 1; } game::LineState::Pure { color, count } => { let total_count = count as i32 + 1; if total_count == state.structure.object_size as i32 { if color == White { last_white_piece = true; } else { last_black_piece = true; } } else { if color == White { white_value += total_count * total_count; } else { black_value += total_count * total_count; } } } game::LineState::Mixed => {} game::LineState::Win(_) => { // We made sure that there is at least one empty position. unreachable!(); } } } let white_point_value = if last_white_piece { SideValue::LastMissingPiece } else { SideValue::Heuristic(white_value) }; let black_point_value = if last_black_piece { SideValue::LastMissingPiece } else { SideValue::Heuristic(black_value) }; Some((white_point_value, black_point_value)) } // Is this column worth playing at? #[allow(dead_code)] fn column_value(state: &game::State, position: Position2) -> Option<(SideValue, SideValue)> { use self::SideValue::{LastMissingPiece, Heuristic, DirectLoss}; let height: u8 = state.column_height[position.0 as usize]; match height { 4 => None, 3 => point_value(state, position.with_height(3)), h => { let (white_placement_value, black_placement_value) = point_value(state, position.with_height(h)).unwrap(); let (white_response_value, black_response_value) = point_value(state, position.with_height(h + 1)).unwrap(); let white_value = { if let Heuristic(w) = white_placement_value { if let Heuristic(b) = black_response_value { Heuristic(w - b) } else { DirectLoss } } else { LastMissingPiece } }; let black_value = { if let Heuristic(b) = black_placement_value { if let Heuristic(w) = white_response_value { Heuristic(b - w) } else { DirectLoss } } else { LastMissingPiece } }; Some((white_value, black_value)) } } }
point_value
identifier_name
value.rs
/* This module collects value functions. */ use std::str::FromStr; use game; use game::{LineState, Position3, Position2}; #[derive(Clone, Copy, Debug)] pub enum Simple { Subsets, WinOnly, } impl Simple { pub fn value_of(self, state: &game::State, my_color: game::Color) -> i32 { match self { Simple::Subsets => subsets(state, my_color), Simple::WinOnly => win_only(state, my_color), } } } impl FromStr for Simple { type Err = (); fn from_str(s: &str) -> Result<Simple, ()> { match s { "subsets" => Ok(Simple::Subsets), "win" => Ok(Simple::WinOnly), _ => Err(()), } } } // For each possible winning subset, this adds some score. // One piece on a line => 1 Point // Two pieces on a line => 4 Points // Three pieces on a line => 9 Points pub fn subsets(state: &game::State, my_color: game::Color) -> i32 { if let game::VictoryState::Win { winner,.. } = state.victory_state { if winner == my_color { return 1000; } else { return -1000; } } let mut score = 0; for subset in &state.structure.source { score += match subset.win_state(state) { LineState::Empty => 0, LineState::Mixed => 0, LineState::Pure { color, count } => { if color == my_color { (count * count) as i32 } else { -(count * count) as i32 } } LineState::Win(_) => { panic!("If the game is already won this should be caught earlier.") } } } score } #[test] fn test_subsets_values() { use game::{Structure, State, Position2}; use game::Color::White; use std::sync::Arc; use constants::LINES; let structure = Structure::new(&LINES); let mut state = State::new(Arc::new(structure)); assert_eq!(0, subsets(&state, White)); state.insert(Position2::new(0, 0)); assert_eq!(7, subsets(&state, White)); state.insert(Position2::new(0, 3)); assert_eq!(0, subsets(&state, White)); } // This value function only checks if you won the game already. pub fn win_only(state: &game::State, my_color: game::Color) -> i32
/* New idea/project for a value function. Give each point a value, then each column and in conclusion, give one to the whole board (if desired). This can also be used to pick which actions to inspect further. */ // How much a particular action is worth to a player. The LastMissingPiece // variant indicates that playing this action wins the game. // The DirectLoss variant indicates that the player is sure to loose by playing this. #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum SideValue { // Do I win if I place here? LastMissingPiece, // Or do I at least get a piece which aligns with a lot of other pieces? Heuristic(i32), DirectLoss, } // Calculates the point value for White and Black. #[allow(dead_code)] fn point_value(state: &game::State, position: Position3) -> Option<(SideValue, SideValue)> { use game::Color::White; // This is only defined for empty positions. if let game::PointState::Piece(_) = state.at(position) { return None; } let mut white_value = 0; let mut black_value = 0; let mut last_white_piece = false; let mut last_black_piece = false; for subset_index in &state.structure.reverse[position.0 as usize] { let subset = state.structure.source[*subset_index]; let win_state = subset.win_state(state); match win_state { game::LineState::Empty => { white_value += 1; black_value += 1; } game::LineState::Pure { color, count } => { let total_count = count as i32 + 1; if total_count == state.structure.object_size as i32 { if color == White { last_white_piece = true; } else { last_black_piece = true; } } else { if color == White { white_value += total_count * total_count; } else { black_value += total_count * total_count; } } } game::LineState::Mixed => {} game::LineState::Win(_) => { // We made sure that there is at least one empty position. unreachable!(); } } } let white_point_value = if last_white_piece { SideValue::LastMissingPiece } else { SideValue::Heuristic(white_value) }; let black_point_value = if last_black_piece { SideValue::LastMissingPiece } else { SideValue::Heuristic(black_value) }; Some((white_point_value, black_point_value)) } // Is this column worth playing at? #[allow(dead_code)] fn column_value(state: &game::State, position: Position2) -> Option<(SideValue, SideValue)> { use self::SideValue::{LastMissingPiece, Heuristic, DirectLoss}; let height: u8 = state.column_height[position.0 as usize]; match height { 4 => None, 3 => point_value(state, position.with_height(3)), h => { let (white_placement_value, black_placement_value) = point_value(state, position.with_height(h)).unwrap(); let (white_response_value, black_response_value) = point_value(state, position.with_height(h + 1)).unwrap(); let white_value = { if let Heuristic(w) = white_placement_value { if let Heuristic(b) = black_response_value { Heuristic(w - b) } else { DirectLoss } } else { LastMissingPiece } }; let black_value = { if let Heuristic(b) = black_placement_value { if let Heuristic(w) = white_response_value { Heuristic(b - w) } else { DirectLoss } } else { LastMissingPiece } }; Some((white_value, black_value)) } } }
{ if let game::VictoryState::Win { winner, .. } = state.victory_state { if winner == my_color { return 1; } else { return -1; } } else { 0 } }
identifier_body
graph_builder.rs
use std::rc::Rc; use dl; use graphics; use matrix; use piston::input; use opengl_graphics::GlGraphics; use super::dl_ui::Mouse; use super::node::{Node, NodeAction, NodeResponse}; use super::op::Operation; use super::var_store::{VarIndex, VarStore}; pub enum GraphAction { SelectNode(NodeId), SelectVariable(VarIndex), } pub struct GraphBuilder { pub graph: dl::Graph, pub vars: VarStore, dim_vars: Vec<usize>, nodes: Vec<Node>, edges: Vec<(NodeId, usize, NodeId, usize)>, node_action: Option<(NodeId, NodeAction)>, } impl GraphBuilder { pub fn new() -> Self { GraphBuilder { graph: dl::Graph::new(), vars: VarStore::new(), dim_vars: vec![], nodes: vec![], edges: vec![], node_action: None, } } pub fn add_node(&mut self, name: String, pos: [f64; 2], op: Rc<Operation>) { let num_in = op.num_inputs; let mut outs = Vec::with_capacity(op.num_outputs as usize); for _ in 0..op.num_outputs { outs.push(self.vars.add((1, 1))); } self.nodes.push(Node::new(name, pos, op, num_in, outs)); } pub fn event(&mut self, event: &input::Event, mouse: &Mouse) -> Option<GraphAction> { let mut graph_action = None; let mut new_action: Option<(NodeId, NodeAction)> = None;
new_action = Some((NodeId(i), action)); break; } } if let Some((old_node, old_action)) = self.node_action { if let Some((new_node, _new_action)) = new_action { if let Some(response) = old_action.happened_before(&_new_action, (old_node, new_node)) { match response { NodeResponse::Connect(send_node, send_index, recv_node, recv_index) => { // A connection was made let v = self.nodes[send_node.0].outputs[send_index]; self.nodes[recv_node.0].inputs[recv_index] = Some(v); self.edges.push((send_node, send_index, recv_node, recv_index)); if recv_node == new_node { println!(" -> "); } else { println!(" <- "); } }, NodeResponse::Select => { // Select the node graph_action = Some(GraphAction::SelectNode(new_node)); }, NodeResponse::SelectInput(i) => { // Select one of the node's input's if let Some(v) = self.nodes[new_node.0].inputs[i] { graph_action = Some(GraphAction::SelectVariable(v)); } }, NodeResponse::SelectOutput(i) => { // Select one of the node's output's let v = self.nodes[new_node.0].outputs[i]; graph_action = Some(GraphAction::SelectVariable(v)); }, } new_action = None; } } } if let Some((_, _new_action)) = new_action { match _new_action { NodeAction::DropInput(_) => { new_action = None; }, NodeAction::DropOutput(_) => { new_action = None; }, _ => { }, } } self.node_action = new_action; graph_action } pub fn draw(&self, c: &graphics::Context, gl: &mut GlGraphics) { use graphics::Line; for &(send_node, send_index, recv_node, recv_index) in &self.edges { let start_pos = send_node.get(self).get_output_pos(send_index); let end_pos = recv_node.get(self).get_input_pos(recv_index); Line::new([1.0, 0.0, 0.0, 1.0], 1.0).draw([start_pos[0], start_pos[1], end_pos[0], end_pos[1]], &c.draw_state, c.transform, gl); } for node in &self.nodes { node.draw(c, gl); } } pub fn gpu_build(&mut self, ctx: &matrix::Context) { for node in &mut self.nodes { (node.op.build)(ctx, &mut self.graph, &mut self.vars, &node.inputs, &node.outputs); } } } #[derive(Copy, Clone, PartialEq)] pub struct NodeId(usize); impl NodeId { pub fn get<'a>(&self, graph: &'a GraphBuilder) -> &'a Node { &graph.nodes[self.0] } } #[derive(Copy, Clone, PartialEq)] pub struct DimVar(usize); impl DimVar { pub fn get<'a>(&self, graph: &'a GraphBuilder) -> &'a usize { &graph.dim_vars[self.0] } }
for (i, node) in self.nodes.iter_mut().enumerate() { node.event(event, mouse); if let Some(action) = node.action {
random_line_split
graph_builder.rs
use std::rc::Rc; use dl; use graphics; use matrix; use piston::input; use opengl_graphics::GlGraphics; use super::dl_ui::Mouse; use super::node::{Node, NodeAction, NodeResponse}; use super::op::Operation; use super::var_store::{VarIndex, VarStore}; pub enum
{ SelectNode(NodeId), SelectVariable(VarIndex), } pub struct GraphBuilder { pub graph: dl::Graph, pub vars: VarStore, dim_vars: Vec<usize>, nodes: Vec<Node>, edges: Vec<(NodeId, usize, NodeId, usize)>, node_action: Option<(NodeId, NodeAction)>, } impl GraphBuilder { pub fn new() -> Self { GraphBuilder { graph: dl::Graph::new(), vars: VarStore::new(), dim_vars: vec![], nodes: vec![], edges: vec![], node_action: None, } } pub fn add_node(&mut self, name: String, pos: [f64; 2], op: Rc<Operation>) { let num_in = op.num_inputs; let mut outs = Vec::with_capacity(op.num_outputs as usize); for _ in 0..op.num_outputs { outs.push(self.vars.add((1, 1))); } self.nodes.push(Node::new(name, pos, op, num_in, outs)); } pub fn event(&mut self, event: &input::Event, mouse: &Mouse) -> Option<GraphAction> { let mut graph_action = None; let mut new_action: Option<(NodeId, NodeAction)> = None; for (i, node) in self.nodes.iter_mut().enumerate() { node.event(event, mouse); if let Some(action) = node.action { new_action = Some((NodeId(i), action)); break; } } if let Some((old_node, old_action)) = self.node_action { if let Some((new_node, _new_action)) = new_action { if let Some(response) = old_action.happened_before(&_new_action, (old_node, new_node)) { match response { NodeResponse::Connect(send_node, send_index, recv_node, recv_index) => { // A connection was made let v = self.nodes[send_node.0].outputs[send_index]; self.nodes[recv_node.0].inputs[recv_index] = Some(v); self.edges.push((send_node, send_index, recv_node, recv_index)); if recv_node == new_node { println!(" -> "); } else { println!(" <- "); } }, NodeResponse::Select => { // Select the node graph_action = Some(GraphAction::SelectNode(new_node)); }, NodeResponse::SelectInput(i) => { // Select one of the node's input's if let Some(v) = self.nodes[new_node.0].inputs[i] { graph_action = Some(GraphAction::SelectVariable(v)); } }, NodeResponse::SelectOutput(i) => { // Select one of the node's output's let v = self.nodes[new_node.0].outputs[i]; graph_action = Some(GraphAction::SelectVariable(v)); }, } new_action = None; } } } if let Some((_, _new_action)) = new_action { match _new_action { NodeAction::DropInput(_) => { new_action = None; }, NodeAction::DropOutput(_) => { new_action = None; }, _ => { }, } } self.node_action = new_action; graph_action } pub fn draw(&self, c: &graphics::Context, gl: &mut GlGraphics) { use graphics::Line; for &(send_node, send_index, recv_node, recv_index) in &self.edges { let start_pos = send_node.get(self).get_output_pos(send_index); let end_pos = recv_node.get(self).get_input_pos(recv_index); Line::new([1.0, 0.0, 0.0, 1.0], 1.0).draw([start_pos[0], start_pos[1], end_pos[0], end_pos[1]], &c.draw_state, c.transform, gl); } for node in &self.nodes { node.draw(c, gl); } } pub fn gpu_build(&mut self, ctx: &matrix::Context) { for node in &mut self.nodes { (node.op.build)(ctx, &mut self.graph, &mut self.vars, &node.inputs, &node.outputs); } } } #[derive(Copy, Clone, PartialEq)] pub struct NodeId(usize); impl NodeId { pub fn get<'a>(&self, graph: &'a GraphBuilder) -> &'a Node { &graph.nodes[self.0] } } #[derive(Copy, Clone, PartialEq)] pub struct DimVar(usize); impl DimVar { pub fn get<'a>(&self, graph: &'a GraphBuilder) -> &'a usize { &graph.dim_vars[self.0] } }
GraphAction
identifier_name
wrapping_mul.rs
use num::arithmetic::traits::{WrappingMul, WrappingMulAssign}; macro_rules! impl_wrapping_mul { ($t:ident) => { impl WrappingMul<$t> for $t { type Output = $t; #[inline] fn wrapping_mul(self, other: $t) -> $t { $t::wrapping_mul(self, other) } }
impl WrappingMulAssign<$t> for $t { /// Replaces `self` with `self * other`, wrapping around at the boundary of the type. /// /// $x \gets z$, where $z \equiv xy \mod 2^W$ and $W$ is `$t::WIDTH`. /// /// # Worst-case complexity /// Constant time and additional memory. /// /// # Examples /// See the documentation of the `num::arithmetic::wrapping_mul` module. #[inline] fn wrapping_mul_assign(&mut self, other: $t) { *self = self.wrapping_mul(other); } } }; } apply_to_primitive_ints!(impl_wrapping_mul);
random_line_split
issue-42956.rs
// Copyright 2018 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. // compile-pass #![allow(dead_code)] #![allow(stable_features)] #![feature(associated_consts)] impl A for i32 { type Foo = u32; } impl B for u32 { const BAR: i32 = 0; } trait A { type Foo: B; } trait B { const BAR: i32; } fn generic<T: A>() { // This panics if the universal function call syntax is used as well println!("{}", T::Foo::BAR); } fn
() {}
main
identifier_name
issue-42956.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-pass #![allow(dead_code)] #![allow(stable_features)] #![feature(associated_consts)] impl A for i32 { type Foo = u32; } impl B for u32 { const BAR: i32 = 0; } trait A { type Foo: B; } trait B { const BAR: i32; } fn generic<T: A>() { // This panics if the universal function call syntax is used as well println!("{}", T::Foo::BAR); } fn main() {}
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
random_line_split
issue-42956.rs
// Copyright 2018 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. // compile-pass #![allow(dead_code)] #![allow(stable_features)] #![feature(associated_consts)] impl A for i32 { type Foo = u32; } impl B for u32 { const BAR: i32 = 0; } trait A { type Foo: B; } trait B { const BAR: i32; } fn generic<T: A>() { // This panics if the universal function call syntax is used as well println!("{}", T::Foo::BAR); } fn main()
{}
identifier_body
zap.rs
use std::{fmt, mem, ptr, str, Seek}; use super::from_bytes::FromBytes; const MZAP_ENT_LEN: usize = 64; const MZAP_NAME_LEN: usize = MZAP_ENT_LEN - 8 - 4 - 2; #[repr(u64)] #[derive(Copy, Clone, Debug)] pub enum ZapObjectType {
Micro = (1 << 63) + 3, Header = (1 << 63) + 1, Leaf = 1 << 63, } /// Microzap #[repr(packed)] pub struct MZapPhys { pub block_type: ZapObjectType, // ZapObjectType::Micro pub salt: u64, pub norm_flags: u64, pad: [u64; 5], } pub struct MZapWrapper { pub phys: MZapPhys, pub chunks: Vec<MZapEntPhys>, // variable size depending on block size } impl FromBytes for MZapWrapper { fn from_bytes(data: &[u8]) -> Result<Self, String> { if data.len() >= mem::size_of::<MZapPhys>() { // Read the first part of the mzap -- its base phys struct let mzap_phys = unsafe { ptr::read(data.as_ptr() as *const MZapPhys) }; // Read the mzap entries, aka chunks let mut mzap_entries = Vec::new(); let num_entries = (data.len() - mem::size_of::<MZapPhys>()) / mem::size_of::<MZapEntPhys>(); for i in 0..num_entries { let entry_pos = mem::size_of::<MZapPhys>() + i * mem::size_of::<MZapEntPhys>(); let mzap_ent = unsafe { ptr::read(data[entry_pos..].as_ptr() as *const MZapEntPhys) }; mzap_entries.push(mzap_ent); } Ok(MZapWrapper { phys: mzap_phys, chunks: mzap_entries, }) } else { Err("Error: needs a proper error message".to_string()) } } } impl fmt::Debug for MZapWrapper { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "MZapPhys {{\nblock_type: {:?},\nsalt: {:X},\nnorm_flags: {:X},\nchunk: [\n", self.phys.block_type, self.phys.salt, self.phys.norm_flags)); for chunk in &self.chunks { try!(write!(f, "{:?}\n", chunk)); } try!(write!(f, "] }}\n")); Ok(()) } } #[repr(packed)] pub struct MZapEntPhys { pub value: u64, pub cd: u32, pub pad: u16, pub name: [u8; MZAP_NAME_LEN], } impl MZapEntPhys { pub fn name(&self) -> Option<&str> { let mut len = 0; for c in &self.name[..] { if *c == 0 { break; } len += 1; } str::from_utf8(&self.name[..len]).ok() } } impl fmt::Debug for MZapEntPhys { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "MZapEntPhys {{\nvalue: {:X},\ncd: {:X},\nname: ", self.value, self.cd)); for i in 0..MZAP_NAME_LEN { if self.name[i] == 0 { break; } try!(write!(f, "{}", self.name[i] as char)); } try!(write!(f, "\n}}\n")); Ok(()) } } /// Fatzap #[repr(packed)] pub struct ZapPhys { pub block_type: ZapObjectType, // ZapObjectType::Header pub magic: u64, pub ptr_table: ZapTablePhys, pub free_block: u64, pub num_leafs: u64, pub num_entries: u64, pub salt: u64, pub pad: [u64; 8181], pub leafs: [u64; 8192], } #[repr(packed)] pub struct ZapTablePhys { pub block: u64, pub num_blocks: u64, pub shift: u64, pub next_block: u64, pub block_copied: u64, } const ZAP_LEAF_MAGIC: u32 = 0x2AB1EAF; const ZAP_LEAF_CHUNKSIZE: usize = 24; // The amount of space within the chunk available for the array is: // chunk size - space for type (1) - space for next pointer (2) const ZAP_LEAF_ARRAY_BYTES: usize = ZAP_LEAF_CHUNKSIZE - 3; // pub struct ZapLeafPhys { // pub header: ZapLeafHeader, // hash: [u16; ZAP_LEAF_HASH_NUMENTRIES], // union zap_leaf_chunk { // entry, // array, // free, // } chunks[ZapLeafChunk; ZAP_LEAF_NUMCHUNKS], // } #[repr(packed)] pub struct ZapLeafHeader { pub block_type: ZapObjectType, // ZapObjectType::Leaf pub next: u64, pub prefix: u64, pub magic: u32, pub n_free: u16, pub n_entries: u16, pub prefix_len: u16, pub free_list: u16, pad2: [u8; 12], } #[repr(packed)] struct ZapLeafEntry { leaf_type: u8, int_size: u8, next: u16, name_chunk: u16, name_length: u16, value_chunk: u16, value_length: u16, cd: u16, pad: [u8; 2], hash: u64, } #[repr(packed)] struct ZapLeafArray { leaf_type: u8, array: [u8; ZAP_LEAF_ARRAY_BYTES], next: u16, } #[repr(packed)] struct ZapLeafFree { free_type: u8, pad: [u8; ZAP_LEAF_ARRAY_BYTES], next: u16, }
random_line_split
zap.rs
use std::{fmt, mem, ptr, str, Seek}; use super::from_bytes::FromBytes; const MZAP_ENT_LEN: usize = 64; const MZAP_NAME_LEN: usize = MZAP_ENT_LEN - 8 - 4 - 2; #[repr(u64)] #[derive(Copy, Clone, Debug)] pub enum
{ Micro = (1 << 63) + 3, Header = (1 << 63) + 1, Leaf = 1 << 63, } /// Microzap #[repr(packed)] pub struct MZapPhys { pub block_type: ZapObjectType, // ZapObjectType::Micro pub salt: u64, pub norm_flags: u64, pad: [u64; 5], } pub struct MZapWrapper { pub phys: MZapPhys, pub chunks: Vec<MZapEntPhys>, // variable size depending on block size } impl FromBytes for MZapWrapper { fn from_bytes(data: &[u8]) -> Result<Self, String> { if data.len() >= mem::size_of::<MZapPhys>() { // Read the first part of the mzap -- its base phys struct let mzap_phys = unsafe { ptr::read(data.as_ptr() as *const MZapPhys) }; // Read the mzap entries, aka chunks let mut mzap_entries = Vec::new(); let num_entries = (data.len() - mem::size_of::<MZapPhys>()) / mem::size_of::<MZapEntPhys>(); for i in 0..num_entries { let entry_pos = mem::size_of::<MZapPhys>() + i * mem::size_of::<MZapEntPhys>(); let mzap_ent = unsafe { ptr::read(data[entry_pos..].as_ptr() as *const MZapEntPhys) }; mzap_entries.push(mzap_ent); } Ok(MZapWrapper { phys: mzap_phys, chunks: mzap_entries, }) } else { Err("Error: needs a proper error message".to_string()) } } } impl fmt::Debug for MZapWrapper { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "MZapPhys {{\nblock_type: {:?},\nsalt: {:X},\nnorm_flags: {:X},\nchunk: [\n", self.phys.block_type, self.phys.salt, self.phys.norm_flags)); for chunk in &self.chunks { try!(write!(f, "{:?}\n", chunk)); } try!(write!(f, "] }}\n")); Ok(()) } } #[repr(packed)] pub struct MZapEntPhys { pub value: u64, pub cd: u32, pub pad: u16, pub name: [u8; MZAP_NAME_LEN], } impl MZapEntPhys { pub fn name(&self) -> Option<&str> { let mut len = 0; for c in &self.name[..] { if *c == 0 { break; } len += 1; } str::from_utf8(&self.name[..len]).ok() } } impl fmt::Debug for MZapEntPhys { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "MZapEntPhys {{\nvalue: {:X},\ncd: {:X},\nname: ", self.value, self.cd)); for i in 0..MZAP_NAME_LEN { if self.name[i] == 0 { break; } try!(write!(f, "{}", self.name[i] as char)); } try!(write!(f, "\n}}\n")); Ok(()) } } /// Fatzap #[repr(packed)] pub struct ZapPhys { pub block_type: ZapObjectType, // ZapObjectType::Header pub magic: u64, pub ptr_table: ZapTablePhys, pub free_block: u64, pub num_leafs: u64, pub num_entries: u64, pub salt: u64, pub pad: [u64; 8181], pub leafs: [u64; 8192], } #[repr(packed)] pub struct ZapTablePhys { pub block: u64, pub num_blocks: u64, pub shift: u64, pub next_block: u64, pub block_copied: u64, } const ZAP_LEAF_MAGIC: u32 = 0x2AB1EAF; const ZAP_LEAF_CHUNKSIZE: usize = 24; // The amount of space within the chunk available for the array is: // chunk size - space for type (1) - space for next pointer (2) const ZAP_LEAF_ARRAY_BYTES: usize = ZAP_LEAF_CHUNKSIZE - 3; // pub struct ZapLeafPhys { // pub header: ZapLeafHeader, // hash: [u16; ZAP_LEAF_HASH_NUMENTRIES], // union zap_leaf_chunk { // entry, // array, // free, // } chunks[ZapLeafChunk; ZAP_LEAF_NUMCHUNKS], // } #[repr(packed)] pub struct ZapLeafHeader { pub block_type: ZapObjectType, // ZapObjectType::Leaf pub next: u64, pub prefix: u64, pub magic: u32, pub n_free: u16, pub n_entries: u16, pub prefix_len: u16, pub free_list: u16, pad2: [u8; 12], } #[repr(packed)] struct ZapLeafEntry { leaf_type: u8, int_size: u8, next: u16, name_chunk: u16, name_length: u16, value_chunk: u16, value_length: u16, cd: u16, pad: [u8; 2], hash: u64, } #[repr(packed)] struct ZapLeafArray { leaf_type: u8, array: [u8; ZAP_LEAF_ARRAY_BYTES], next: u16, } #[repr(packed)] struct ZapLeafFree { free_type: u8, pad: [u8; ZAP_LEAF_ARRAY_BYTES], next: u16, }
ZapObjectType
identifier_name
zap.rs
use std::{fmt, mem, ptr, str, Seek}; use super::from_bytes::FromBytes; const MZAP_ENT_LEN: usize = 64; const MZAP_NAME_LEN: usize = MZAP_ENT_LEN - 8 - 4 - 2; #[repr(u64)] #[derive(Copy, Clone, Debug)] pub enum ZapObjectType { Micro = (1 << 63) + 3, Header = (1 << 63) + 1, Leaf = 1 << 63, } /// Microzap #[repr(packed)] pub struct MZapPhys { pub block_type: ZapObjectType, // ZapObjectType::Micro pub salt: u64, pub norm_flags: u64, pad: [u64; 5], } pub struct MZapWrapper { pub phys: MZapPhys, pub chunks: Vec<MZapEntPhys>, // variable size depending on block size } impl FromBytes for MZapWrapper { fn from_bytes(data: &[u8]) -> Result<Self, String> { if data.len() >= mem::size_of::<MZapPhys>()
else { Err("Error: needs a proper error message".to_string()) } } } impl fmt::Debug for MZapWrapper { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "MZapPhys {{\nblock_type: {:?},\nsalt: {:X},\nnorm_flags: {:X},\nchunk: [\n", self.phys.block_type, self.phys.salt, self.phys.norm_flags)); for chunk in &self.chunks { try!(write!(f, "{:?}\n", chunk)); } try!(write!(f, "] }}\n")); Ok(()) } } #[repr(packed)] pub struct MZapEntPhys { pub value: u64, pub cd: u32, pub pad: u16, pub name: [u8; MZAP_NAME_LEN], } impl MZapEntPhys { pub fn name(&self) -> Option<&str> { let mut len = 0; for c in &self.name[..] { if *c == 0 { break; } len += 1; } str::from_utf8(&self.name[..len]).ok() } } impl fmt::Debug for MZapEntPhys { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "MZapEntPhys {{\nvalue: {:X},\ncd: {:X},\nname: ", self.value, self.cd)); for i in 0..MZAP_NAME_LEN { if self.name[i] == 0 { break; } try!(write!(f, "{}", self.name[i] as char)); } try!(write!(f, "\n}}\n")); Ok(()) } } /// Fatzap #[repr(packed)] pub struct ZapPhys { pub block_type: ZapObjectType, // ZapObjectType::Header pub magic: u64, pub ptr_table: ZapTablePhys, pub free_block: u64, pub num_leafs: u64, pub num_entries: u64, pub salt: u64, pub pad: [u64; 8181], pub leafs: [u64; 8192], } #[repr(packed)] pub struct ZapTablePhys { pub block: u64, pub num_blocks: u64, pub shift: u64, pub next_block: u64, pub block_copied: u64, } const ZAP_LEAF_MAGIC: u32 = 0x2AB1EAF; const ZAP_LEAF_CHUNKSIZE: usize = 24; // The amount of space within the chunk available for the array is: // chunk size - space for type (1) - space for next pointer (2) const ZAP_LEAF_ARRAY_BYTES: usize = ZAP_LEAF_CHUNKSIZE - 3; // pub struct ZapLeafPhys { // pub header: ZapLeafHeader, // hash: [u16; ZAP_LEAF_HASH_NUMENTRIES], // union zap_leaf_chunk { // entry, // array, // free, // } chunks[ZapLeafChunk; ZAP_LEAF_NUMCHUNKS], // } #[repr(packed)] pub struct ZapLeafHeader { pub block_type: ZapObjectType, // ZapObjectType::Leaf pub next: u64, pub prefix: u64, pub magic: u32, pub n_free: u16, pub n_entries: u16, pub prefix_len: u16, pub free_list: u16, pad2: [u8; 12], } #[repr(packed)] struct ZapLeafEntry { leaf_type: u8, int_size: u8, next: u16, name_chunk: u16, name_length: u16, value_chunk: u16, value_length: u16, cd: u16, pad: [u8; 2], hash: u64, } #[repr(packed)] struct ZapLeafArray { leaf_type: u8, array: [u8; ZAP_LEAF_ARRAY_BYTES], next: u16, } #[repr(packed)] struct ZapLeafFree { free_type: u8, pad: [u8; ZAP_LEAF_ARRAY_BYTES], next: u16, }
{ // Read the first part of the mzap -- its base phys struct let mzap_phys = unsafe { ptr::read(data.as_ptr() as *const MZapPhys) }; // Read the mzap entries, aka chunks let mut mzap_entries = Vec::new(); let num_entries = (data.len() - mem::size_of::<MZapPhys>()) / mem::size_of::<MZapEntPhys>(); for i in 0..num_entries { let entry_pos = mem::size_of::<MZapPhys>() + i * mem::size_of::<MZapEntPhys>(); let mzap_ent = unsafe { ptr::read(data[entry_pos..].as_ptr() as *const MZapEntPhys) }; mzap_entries.push(mzap_ent); } Ok(MZapWrapper { phys: mzap_phys, chunks: mzap_entries, }) }
conditional_block
zap.rs
use std::{fmt, mem, ptr, str, Seek}; use super::from_bytes::FromBytes; const MZAP_ENT_LEN: usize = 64; const MZAP_NAME_LEN: usize = MZAP_ENT_LEN - 8 - 4 - 2; #[repr(u64)] #[derive(Copy, Clone, Debug)] pub enum ZapObjectType { Micro = (1 << 63) + 3, Header = (1 << 63) + 1, Leaf = 1 << 63, } /// Microzap #[repr(packed)] pub struct MZapPhys { pub block_type: ZapObjectType, // ZapObjectType::Micro pub salt: u64, pub norm_flags: u64, pad: [u64; 5], } pub struct MZapWrapper { pub phys: MZapPhys, pub chunks: Vec<MZapEntPhys>, // variable size depending on block size } impl FromBytes for MZapWrapper { fn from_bytes(data: &[u8]) -> Result<Self, String> { if data.len() >= mem::size_of::<MZapPhys>() { // Read the first part of the mzap -- its base phys struct let mzap_phys = unsafe { ptr::read(data.as_ptr() as *const MZapPhys) }; // Read the mzap entries, aka chunks let mut mzap_entries = Vec::new(); let num_entries = (data.len() - mem::size_of::<MZapPhys>()) / mem::size_of::<MZapEntPhys>(); for i in 0..num_entries { let entry_pos = mem::size_of::<MZapPhys>() + i * mem::size_of::<MZapEntPhys>(); let mzap_ent = unsafe { ptr::read(data[entry_pos..].as_ptr() as *const MZapEntPhys) }; mzap_entries.push(mzap_ent); } Ok(MZapWrapper { phys: mzap_phys, chunks: mzap_entries, }) } else { Err("Error: needs a proper error message".to_string()) } } } impl fmt::Debug for MZapWrapper { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "MZapPhys {{\nblock_type: {:?},\nsalt: {:X},\nnorm_flags: {:X},\nchunk: [\n", self.phys.block_type, self.phys.salt, self.phys.norm_flags)); for chunk in &self.chunks { try!(write!(f, "{:?}\n", chunk)); } try!(write!(f, "] }}\n")); Ok(()) } } #[repr(packed)] pub struct MZapEntPhys { pub value: u64, pub cd: u32, pub pad: u16, pub name: [u8; MZAP_NAME_LEN], } impl MZapEntPhys { pub fn name(&self) -> Option<&str> { let mut len = 0; for c in &self.name[..] { if *c == 0 { break; } len += 1; } str::from_utf8(&self.name[..len]).ok() } } impl fmt::Debug for MZapEntPhys { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
} /// Fatzap #[repr(packed)] pub struct ZapPhys { pub block_type: ZapObjectType, // ZapObjectType::Header pub magic: u64, pub ptr_table: ZapTablePhys, pub free_block: u64, pub num_leafs: u64, pub num_entries: u64, pub salt: u64, pub pad: [u64; 8181], pub leafs: [u64; 8192], } #[repr(packed)] pub struct ZapTablePhys { pub block: u64, pub num_blocks: u64, pub shift: u64, pub next_block: u64, pub block_copied: u64, } const ZAP_LEAF_MAGIC: u32 = 0x2AB1EAF; const ZAP_LEAF_CHUNKSIZE: usize = 24; // The amount of space within the chunk available for the array is: // chunk size - space for type (1) - space for next pointer (2) const ZAP_LEAF_ARRAY_BYTES: usize = ZAP_LEAF_CHUNKSIZE - 3; // pub struct ZapLeafPhys { // pub header: ZapLeafHeader, // hash: [u16; ZAP_LEAF_HASH_NUMENTRIES], // union zap_leaf_chunk { // entry, // array, // free, // } chunks[ZapLeafChunk; ZAP_LEAF_NUMCHUNKS], // } #[repr(packed)] pub struct ZapLeafHeader { pub block_type: ZapObjectType, // ZapObjectType::Leaf pub next: u64, pub prefix: u64, pub magic: u32, pub n_free: u16, pub n_entries: u16, pub prefix_len: u16, pub free_list: u16, pad2: [u8; 12], } #[repr(packed)] struct ZapLeafEntry { leaf_type: u8, int_size: u8, next: u16, name_chunk: u16, name_length: u16, value_chunk: u16, value_length: u16, cd: u16, pad: [u8; 2], hash: u64, } #[repr(packed)] struct ZapLeafArray { leaf_type: u8, array: [u8; ZAP_LEAF_ARRAY_BYTES], next: u16, } #[repr(packed)] struct ZapLeafFree { free_type: u8, pad: [u8; ZAP_LEAF_ARRAY_BYTES], next: u16, }
{ try!(write!(f, "MZapEntPhys {{\nvalue: {:X},\ncd: {:X},\nname: ", self.value, self.cd)); for i in 0..MZAP_NAME_LEN { if self.name[i] == 0 { break; } try!(write!(f, "{}", self.name[i] as char)); } try!(write!(f, "\n}}\n")); Ok(()) }
identifier_body
mod.rs
//! Run-time feature detection on Linux mod auxvec; #[cfg(feature = "std_detect_file_io")] mod cpuinfo; cfg_if! { if #[cfg(target_arch = "aarch64")] { mod aarch64; pub use self::aarch64::check_for; } else if #[cfg(target_arch = "arm")] { mod arm; pub use self::arm::check_for; } else if #[cfg(any(target_arch = "mips", target_arch = "mips64"))] { mod mips; pub use self::mips::check_for; } else if #[cfg(any(target_arch = "powerpc", target_arch = "powerpc64"))] { mod powerpc; pub use self::powerpc::check_for; } else { use crate::detect::Feature; /// Performs run-time feature detection. pub fn check_for(_x: Feature) -> bool { false
} }
}
random_line_split
tempfile.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-windows TempDir may cause IoError on windows: #10463 // These tests are here to exercise the functionality of the `tempfile` module. // One might expect these tests to be located in that module, but sadly they // cannot. The tests need to invoke `os::change_dir` which cannot be done in the // normal test infrastructure. If the tests change the current working // directory, then *all* tests which require relative paths suddenly break b/c // they're in a different location than before. Hence, these tests are all run // serially here. extern crate debug; use std::io::{fs, TempDir}; use std::io; use std::os; use std::task; fn test_tempdir() { let path = { let p = TempDir::new_in(&Path::new("."), "foobar").unwrap(); let p = p.path(); assert!(p.as_vec().ends_with(b"foobar")); p.clone() }; assert!(!path.exists()); } fn test_rm_tempdir() { let (tx, rx) = channel(); let f: proc():Send = proc() { let tmp = TempDir::new("test_rm_tempdir").unwrap(); tx.send(tmp.path().clone()); fail!("fail to unwind past `tmp`"); }; task::try(f); let path = rx.recv(); assert!(!path.exists()); let tmp = TempDir::new("test_rm_tempdir").unwrap(); let path = tmp.path().clone(); let f: proc():Send = proc() { let _tmp = tmp; fail!("fail to unwind past `tmp`"); }; task::try(f); assert!(!path.exists()); let path; { let f = proc() { TempDir::new("test_rm_tempdir").unwrap() }; let tmp = task::try(f).ok().expect("test_rm_tmdir"); path = tmp.path().clone(); assert!(path.exists()); } assert!(!path.exists()); let path; { let tmp = TempDir::new("test_rm_tempdir").unwrap(); path = tmp.unwrap(); } assert!(path.exists()); fs::rmdir_recursive(&path); assert!(!path.exists()); } fn test_rm_tempdir_close() { let (tx, rx) = channel(); let f: proc():Send = proc() { let tmp = TempDir::new("test_rm_tempdir").unwrap(); tx.send(tmp.path().clone()); tmp.close(); fail!("fail to unwind past `tmp`"); }; task::try(f); let path = rx.recv(); assert!(!path.exists()); let tmp = TempDir::new("test_rm_tempdir").unwrap(); let path = tmp.path().clone(); let f: proc():Send = proc() { let tmp = tmp; tmp.close(); fail!("fail to unwind past `tmp`"); }; task::try(f); assert!(!path.exists()); let path; { let f = proc() { TempDir::new("test_rm_tempdir").unwrap() }; let tmp = task::try(f).ok().expect("test_rm_tmdir"); path = tmp.path().clone(); assert!(path.exists()); tmp.close(); } assert!(!path.exists()); let path; { let tmp = TempDir::new("test_rm_tempdir").unwrap(); path = tmp.unwrap(); } assert!(path.exists()); fs::rmdir_recursive(&path); assert!(!path.exists()); } // Ideally these would be in std::os but then core would need // to depend on std fn recursive_mkdir_rel() { let path = Path::new("frob"); let cwd = os::getcwd(); println!("recursive_mkdir_rel: Making: {} in cwd {} [{:?}]", path.display(), cwd.display(), path.exists()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); } fn recursive_mkdir_dot() { let dot = Path::new("."); fs::mkdir_recursive(&dot, io::UserRWX); let dotdot = Path::new(".."); fs::mkdir_recursive(&dotdot, io::UserRWX); } fn
() { let path = Path::new("./frob/baz"); let cwd = os::getcwd(); println!("recursive_mkdir_rel_2: Making: {} in cwd {} [{:?}]", path.display(), cwd.display(), path.exists()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); assert!(path.dir_path().is_dir()); let path2 = Path::new("quux/blat"); println!("recursive_mkdir_rel_2: Making: {} in cwd {}", path2.display(), cwd.display()); fs::mkdir_recursive(&path2, io::UserRWX); assert!(path2.is_dir()); assert!(path2.dir_path().is_dir()); } // Ideally this would be in core, but needs TempFile pub fn test_rmdir_recursive_ok() { let rwx = io::UserRWX; let tmpdir = TempDir::new("test").expect("test_rmdir_recursive_ok: \ couldn't create temp dir"); let tmpdir = tmpdir.path(); let root = tmpdir.join("foo"); println!("making {}", root.display()); fs::mkdir(&root, rwx); fs::mkdir(&root.join("foo"), rwx); fs::mkdir(&root.join("foo").join("bar"), rwx); fs::mkdir(&root.join("foo").join("bar").join("blat"), rwx); fs::rmdir_recursive(&root); assert!(!root.exists()); assert!(!root.join("bar").exists()); assert!(!root.join("bar").join("blat").exists()); } pub fn dont_double_fail() { let r: Result<(), _> = task::try(proc() { let tmpdir = TempDir::new("test").unwrap(); // Remove the temporary directory so that TempDir sees // an error on drop fs::rmdir(tmpdir.path()); // Trigger failure. If TempDir fails *again* due to the rmdir // error then the process will abort. fail!(); }); assert!(r.is_err()); } fn in_tmpdir(f: ||) { let tmpdir = TempDir::new("test").expect("can't make tmpdir"); assert!(os::change_dir(tmpdir.path())); f(); } pub fn main() { in_tmpdir(test_tempdir); in_tmpdir(test_rm_tempdir); in_tmpdir(test_rm_tempdir_close); in_tmpdir(recursive_mkdir_rel); in_tmpdir(recursive_mkdir_dot); in_tmpdir(recursive_mkdir_rel_2); in_tmpdir(test_rmdir_recursive_ok); in_tmpdir(dont_double_fail); }
recursive_mkdir_rel_2
identifier_name
tempfile.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-windows TempDir may cause IoError on windows: #10463 // These tests are here to exercise the functionality of the `tempfile` module. // One might expect these tests to be located in that module, but sadly they // cannot. The tests need to invoke `os::change_dir` which cannot be done in the // normal test infrastructure. If the tests change the current working // directory, then *all* tests which require relative paths suddenly break b/c // they're in a different location than before. Hence, these tests are all run // serially here. extern crate debug; use std::io::{fs, TempDir}; use std::io; use std::os; use std::task; fn test_tempdir() { let path = { let p = TempDir::new_in(&Path::new("."), "foobar").unwrap(); let p = p.path(); assert!(p.as_vec().ends_with(b"foobar")); p.clone() }; assert!(!path.exists()); } fn test_rm_tempdir() { let (tx, rx) = channel(); let f: proc():Send = proc() { let tmp = TempDir::new("test_rm_tempdir").unwrap(); tx.send(tmp.path().clone()); fail!("fail to unwind past `tmp`"); }; task::try(f); let path = rx.recv(); assert!(!path.exists()); let tmp = TempDir::new("test_rm_tempdir").unwrap(); let path = tmp.path().clone(); let f: proc():Send = proc() { let _tmp = tmp; fail!("fail to unwind past `tmp`"); }; task::try(f); assert!(!path.exists()); let path; { let f = proc() { TempDir::new("test_rm_tempdir").unwrap() }; let tmp = task::try(f).ok().expect("test_rm_tmdir"); path = tmp.path().clone(); assert!(path.exists()); } assert!(!path.exists()); let path; { let tmp = TempDir::new("test_rm_tempdir").unwrap(); path = tmp.unwrap(); } assert!(path.exists()); fs::rmdir_recursive(&path); assert!(!path.exists()); } fn test_rm_tempdir_close() { let (tx, rx) = channel(); let f: proc():Send = proc() { let tmp = TempDir::new("test_rm_tempdir").unwrap(); tx.send(tmp.path().clone()); tmp.close(); fail!("fail to unwind past `tmp`"); }; task::try(f); let path = rx.recv(); assert!(!path.exists()); let tmp = TempDir::new("test_rm_tempdir").unwrap(); let path = tmp.path().clone(); let f: proc():Send = proc() { let tmp = tmp; tmp.close(); fail!("fail to unwind past `tmp`"); }; task::try(f); assert!(!path.exists()); let path; { let f = proc() { TempDir::new("test_rm_tempdir").unwrap() }; let tmp = task::try(f).ok().expect("test_rm_tmdir"); path = tmp.path().clone(); assert!(path.exists()); tmp.close(); } assert!(!path.exists()); let path; { let tmp = TempDir::new("test_rm_tempdir").unwrap(); path = tmp.unwrap(); } assert!(path.exists()); fs::rmdir_recursive(&path); assert!(!path.exists()); } // Ideally these would be in std::os but then core would need // to depend on std fn recursive_mkdir_rel() { let path = Path::new("frob"); let cwd = os::getcwd(); println!("recursive_mkdir_rel: Making: {} in cwd {} [{:?}]", path.display(), cwd.display(), path.exists()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); } fn recursive_mkdir_dot() { let dot = Path::new("."); fs::mkdir_recursive(&dot, io::UserRWX); let dotdot = Path::new(".."); fs::mkdir_recursive(&dotdot, io::UserRWX); } fn recursive_mkdir_rel_2()
// Ideally this would be in core, but needs TempFile pub fn test_rmdir_recursive_ok() { let rwx = io::UserRWX; let tmpdir = TempDir::new("test").expect("test_rmdir_recursive_ok: \ couldn't create temp dir"); let tmpdir = tmpdir.path(); let root = tmpdir.join("foo"); println!("making {}", root.display()); fs::mkdir(&root, rwx); fs::mkdir(&root.join("foo"), rwx); fs::mkdir(&root.join("foo").join("bar"), rwx); fs::mkdir(&root.join("foo").join("bar").join("blat"), rwx); fs::rmdir_recursive(&root); assert!(!root.exists()); assert!(!root.join("bar").exists()); assert!(!root.join("bar").join("blat").exists()); } pub fn dont_double_fail() { let r: Result<(), _> = task::try(proc() { let tmpdir = TempDir::new("test").unwrap(); // Remove the temporary directory so that TempDir sees // an error on drop fs::rmdir(tmpdir.path()); // Trigger failure. If TempDir fails *again* due to the rmdir // error then the process will abort. fail!(); }); assert!(r.is_err()); } fn in_tmpdir(f: ||) { let tmpdir = TempDir::new("test").expect("can't make tmpdir"); assert!(os::change_dir(tmpdir.path())); f(); } pub fn main() { in_tmpdir(test_tempdir); in_tmpdir(test_rm_tempdir); in_tmpdir(test_rm_tempdir_close); in_tmpdir(recursive_mkdir_rel); in_tmpdir(recursive_mkdir_dot); in_tmpdir(recursive_mkdir_rel_2); in_tmpdir(test_rmdir_recursive_ok); in_tmpdir(dont_double_fail); }
{ let path = Path::new("./frob/baz"); let cwd = os::getcwd(); println!("recursive_mkdir_rel_2: Making: {} in cwd {} [{:?}]", path.display(), cwd.display(), path.exists()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); assert!(path.dir_path().is_dir()); let path2 = Path::new("quux/blat"); println!("recursive_mkdir_rel_2: Making: {} in cwd {}", path2.display(), cwd.display()); fs::mkdir_recursive(&path2, io::UserRWX); assert!(path2.is_dir()); assert!(path2.dir_path().is_dir()); }
identifier_body
tempfile.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-windows TempDir may cause IoError on windows: #10463 // These tests are here to exercise the functionality of the `tempfile` module. // One might expect these tests to be located in that module, but sadly they // cannot. The tests need to invoke `os::change_dir` which cannot be done in the // normal test infrastructure. If the tests change the current working // directory, then *all* tests which require relative paths suddenly break b/c // they're in a different location than before. Hence, these tests are all run // serially here. extern crate debug; use std::io::{fs, TempDir}; use std::io; use std::os; use std::task; fn test_tempdir() { let path = { let p = TempDir::new_in(&Path::new("."), "foobar").unwrap(); let p = p.path(); assert!(p.as_vec().ends_with(b"foobar")); p.clone() }; assert!(!path.exists()); }
fail!("fail to unwind past `tmp`"); }; task::try(f); let path = rx.recv(); assert!(!path.exists()); let tmp = TempDir::new("test_rm_tempdir").unwrap(); let path = tmp.path().clone(); let f: proc():Send = proc() { let _tmp = tmp; fail!("fail to unwind past `tmp`"); }; task::try(f); assert!(!path.exists()); let path; { let f = proc() { TempDir::new("test_rm_tempdir").unwrap() }; let tmp = task::try(f).ok().expect("test_rm_tmdir"); path = tmp.path().clone(); assert!(path.exists()); } assert!(!path.exists()); let path; { let tmp = TempDir::new("test_rm_tempdir").unwrap(); path = tmp.unwrap(); } assert!(path.exists()); fs::rmdir_recursive(&path); assert!(!path.exists()); } fn test_rm_tempdir_close() { let (tx, rx) = channel(); let f: proc():Send = proc() { let tmp = TempDir::new("test_rm_tempdir").unwrap(); tx.send(tmp.path().clone()); tmp.close(); fail!("fail to unwind past `tmp`"); }; task::try(f); let path = rx.recv(); assert!(!path.exists()); let tmp = TempDir::new("test_rm_tempdir").unwrap(); let path = tmp.path().clone(); let f: proc():Send = proc() { let tmp = tmp; tmp.close(); fail!("fail to unwind past `tmp`"); }; task::try(f); assert!(!path.exists()); let path; { let f = proc() { TempDir::new("test_rm_tempdir").unwrap() }; let tmp = task::try(f).ok().expect("test_rm_tmdir"); path = tmp.path().clone(); assert!(path.exists()); tmp.close(); } assert!(!path.exists()); let path; { let tmp = TempDir::new("test_rm_tempdir").unwrap(); path = tmp.unwrap(); } assert!(path.exists()); fs::rmdir_recursive(&path); assert!(!path.exists()); } // Ideally these would be in std::os but then core would need // to depend on std fn recursive_mkdir_rel() { let path = Path::new("frob"); let cwd = os::getcwd(); println!("recursive_mkdir_rel: Making: {} in cwd {} [{:?}]", path.display(), cwd.display(), path.exists()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); } fn recursive_mkdir_dot() { let dot = Path::new("."); fs::mkdir_recursive(&dot, io::UserRWX); let dotdot = Path::new(".."); fs::mkdir_recursive(&dotdot, io::UserRWX); } fn recursive_mkdir_rel_2() { let path = Path::new("./frob/baz"); let cwd = os::getcwd(); println!("recursive_mkdir_rel_2: Making: {} in cwd {} [{:?}]", path.display(), cwd.display(), path.exists()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); assert!(path.dir_path().is_dir()); let path2 = Path::new("quux/blat"); println!("recursive_mkdir_rel_2: Making: {} in cwd {}", path2.display(), cwd.display()); fs::mkdir_recursive(&path2, io::UserRWX); assert!(path2.is_dir()); assert!(path2.dir_path().is_dir()); } // Ideally this would be in core, but needs TempFile pub fn test_rmdir_recursive_ok() { let rwx = io::UserRWX; let tmpdir = TempDir::new("test").expect("test_rmdir_recursive_ok: \ couldn't create temp dir"); let tmpdir = tmpdir.path(); let root = tmpdir.join("foo"); println!("making {}", root.display()); fs::mkdir(&root, rwx); fs::mkdir(&root.join("foo"), rwx); fs::mkdir(&root.join("foo").join("bar"), rwx); fs::mkdir(&root.join("foo").join("bar").join("blat"), rwx); fs::rmdir_recursive(&root); assert!(!root.exists()); assert!(!root.join("bar").exists()); assert!(!root.join("bar").join("blat").exists()); } pub fn dont_double_fail() { let r: Result<(), _> = task::try(proc() { let tmpdir = TempDir::new("test").unwrap(); // Remove the temporary directory so that TempDir sees // an error on drop fs::rmdir(tmpdir.path()); // Trigger failure. If TempDir fails *again* due to the rmdir // error then the process will abort. fail!(); }); assert!(r.is_err()); } fn in_tmpdir(f: ||) { let tmpdir = TempDir::new("test").expect("can't make tmpdir"); assert!(os::change_dir(tmpdir.path())); f(); } pub fn main() { in_tmpdir(test_tempdir); in_tmpdir(test_rm_tempdir); in_tmpdir(test_rm_tempdir_close); in_tmpdir(recursive_mkdir_rel); in_tmpdir(recursive_mkdir_dot); in_tmpdir(recursive_mkdir_rel_2); in_tmpdir(test_rmdir_recursive_ok); in_tmpdir(dont_double_fail); }
fn test_rm_tempdir() { let (tx, rx) = channel(); let f: proc():Send = proc() { let tmp = TempDir::new("test_rm_tempdir").unwrap(); tx.send(tmp.path().clone());
random_line_split
point.rs
use std::ops::{Add, Sub, Neg}; use num::{ToPrimitive, Num}; use drawable::Drawable; use canvas::{Canvas, Colour}; use std::fmt::Debug; #[derive(Copy, Clone, Debug)] pub struct Point2D<T> { pub x: T, pub y: T } impl<T> Point2D<T> where T: Num { pub fn new(x: T, y: T) -> Point2D<T> { Point2D { x: x, y: y } } } impl<T> Add for Point2D<T> where T: Num + Add<T, Output=T> + Debug { type Output = Point2D<T>; fn add(self, other: Point2D<T>) -> Point2D<T> { Point2D::new(self.x + other.x, self.y + other.y) } } impl<T> Sub for Point2D<T> where T: Num + Sub<T, Output=T> + Debug { type Output = Point2D<T>; fn sub(self, other: Point2D<T>) -> Point2D<T>
} impl<T> Neg for Point2D<T> where T: Num + Neg<Output=T> + Debug { type Output = Point2D<T>; fn neg(self) -> Point2D<T> { Point2D::new(-self.x, -self.y) } } impl<T> Drawable for Point2D<T> where T: Copy + Num + ToPrimitive + Debug{ fn draw(&self, colour: Colour, canvas: &mut Canvas) { canvas.set(self.x, self.y, colour) } } pub fn orient2d<T: Num + Copy>(a: Point2D<T>, b: Point2D<T>, c: Point2D<T>) -> T { //return positive, if c to the left of a->b. //return zero, if c is colinear with a->b. //return negative, if c to the right of a->b. let acx = a.x - c.x; let bcx = b.x - c.x; let acy = a.y - c.y; let bcy = b.y - c.y; acx * bcy - acy * bcx }
{ Point2D::new(self.x - other.x, self.y - other.y) }
identifier_body
point.rs
use std::ops::{Add, Sub, Neg}; use num::{ToPrimitive, Num}; use drawable::Drawable; use canvas::{Canvas, Colour}; use std::fmt::Debug; #[derive(Copy, Clone, Debug)] pub struct
<T> { pub x: T, pub y: T } impl<T> Point2D<T> where T: Num { pub fn new(x: T, y: T) -> Point2D<T> { Point2D { x: x, y: y } } } impl<T> Add for Point2D<T> where T: Num + Add<T, Output=T> + Debug { type Output = Point2D<T>; fn add(self, other: Point2D<T>) -> Point2D<T> { Point2D::new(self.x + other.x, self.y + other.y) } } impl<T> Sub for Point2D<T> where T: Num + Sub<T, Output=T> + Debug { type Output = Point2D<T>; fn sub(self, other: Point2D<T>) -> Point2D<T> { Point2D::new(self.x - other.x, self.y - other.y) } } impl<T> Neg for Point2D<T> where T: Num + Neg<Output=T> + Debug { type Output = Point2D<T>; fn neg(self) -> Point2D<T> { Point2D::new(-self.x, -self.y) } } impl<T> Drawable for Point2D<T> where T: Copy + Num + ToPrimitive + Debug{ fn draw(&self, colour: Colour, canvas: &mut Canvas) { canvas.set(self.x, self.y, colour) } } pub fn orient2d<T: Num + Copy>(a: Point2D<T>, b: Point2D<T>, c: Point2D<T>) -> T { //return positive, if c to the left of a->b. //return zero, if c is colinear with a->b. //return negative, if c to the right of a->b. let acx = a.x - c.x; let bcx = b.x - c.x; let acy = a.y - c.y; let bcy = b.y - c.y; acx * bcy - acy * bcx }
Point2D
identifier_name
point.rs
use std::ops::{Add, Sub, Neg}; use num::{ToPrimitive, Num}; use drawable::Drawable; use canvas::{Canvas, Colour}; use std::fmt::Debug; #[derive(Copy, Clone, Debug)] pub struct Point2D<T> { pub x: T, pub y: T } impl<T> Point2D<T> where T: Num { pub fn new(x: T, y: T) -> Point2D<T> { Point2D { x: x, y: y } }
type Output = Point2D<T>; fn add(self, other: Point2D<T>) -> Point2D<T> { Point2D::new(self.x + other.x, self.y + other.y) } } impl<T> Sub for Point2D<T> where T: Num + Sub<T, Output=T> + Debug { type Output = Point2D<T>; fn sub(self, other: Point2D<T>) -> Point2D<T> { Point2D::new(self.x - other.x, self.y - other.y) } } impl<T> Neg for Point2D<T> where T: Num + Neg<Output=T> + Debug { type Output = Point2D<T>; fn neg(self) -> Point2D<T> { Point2D::new(-self.x, -self.y) } } impl<T> Drawable for Point2D<T> where T: Copy + Num + ToPrimitive + Debug{ fn draw(&self, colour: Colour, canvas: &mut Canvas) { canvas.set(self.x, self.y, colour) } } pub fn orient2d<T: Num + Copy>(a: Point2D<T>, b: Point2D<T>, c: Point2D<T>) -> T { //return positive, if c to the left of a->b. //return zero, if c is colinear with a->b. //return negative, if c to the right of a->b. let acx = a.x - c.x; let bcx = b.x - c.x; let acy = a.y - c.y; let bcy = b.y - c.y; acx * bcy - acy * bcx }
} impl<T> Add for Point2D<T> where T: Num + Add<T, Output=T> + Debug {
random_line_split
mod.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/>. //! Spec deserialization.
pub mod spec; pub mod seal; pub mod engine; pub mod state; pub mod ethash; pub mod validator_set; pub mod instant_seal; pub mod basic_authority; pub mod authority_round; pub mod tendermint; pub use self::account::Account; pub use self::builtin::{Builtin, Pricing, Linear}; pub use self::genesis::Genesis; pub use self::params::Params; pub use self::spec::Spec; pub use self::seal::{Seal, Ethereum, AuthorityRoundSeal, TendermintSeal}; pub use self::engine::Engine; pub use self::state::State; pub use self::ethash::{Ethash, EthashParams}; pub use self::validator_set::ValidatorSet; pub use self::instant_seal::{InstantSeal, InstantSealParams}; pub use self::basic_authority::{BasicAuthority, BasicAuthorityParams}; pub use self::authority_round::{AuthorityRound, AuthorityRoundParams}; pub use self::tendermint::{Tendermint, TendermintParams};
pub mod account; pub mod builtin; pub mod genesis; pub mod params;
random_line_split
super-fast-paren-parsing.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. // exec-env:RUST_MIN_STACK=16000000 // // Big stack is needed for pretty printing, a little sad... static a: int = ((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((( 1 ))))))))))))))))))))))))))))))))))))))))))))))))))) )))))))))))))))))))))))))))))))))))))))))))))))))))
pub fn main() {}
))))))))))))))))))))))))))))))))))))))))))))))))))) ))))))))))))))))))))))))))))))))))))))))))))))))))) ))))))))))))))))))))))))))))))))))))))))))))))))))) ;
random_line_split
super-fast-paren-parsing.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. // exec-env:RUST_MIN_STACK=16000000 // // Big stack is needed for pretty printing, a little sad... static a: int = ((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((( 1 ))))))))))))))))))))))))))))))))))))))))))))))))))) ))))))))))))))))))))))))))))))))))))))))))))))))))) ))))))))))))))))))))))))))))))))))))))))))))))))))) ))))))))))))))))))))))))))))))))))))))))))))))))))) ))))))))))))))))))))))))))))))))))))))))))))))))))) ; pub fn
() {}
main
identifier_name
super-fast-paren-parsing.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. // exec-env:RUST_MIN_STACK=16000000 // // Big stack is needed for pretty printing, a little sad... static a: int = ((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((( 1 ))))))))))))))))))))))))))))))))))))))))))))))))))) ))))))))))))))))))))))))))))))))))))))))))))))))))) ))))))))))))))))))))))))))))))))))))))))))))))))))) ))))))))))))))))))))))))))))))))))))))))))))))))))) ))))))))))))))))))))))))))))))))))))))))))))))))))) ; pub fn main()
{}
identifier_body
iter_cloned_collect.rs
use crate::methods::utils::derefs_to_slice; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::ty::is_type_diagnostic_item;
use rustc_lint::LateContext; use rustc_span::sym; use super::ITER_CLONED_COLLECT; pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, recv: &'tcx hir::Expr<'_>) { if_chain! { if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::Vec); if let Some(slice) = derefs_to_slice(cx, recv, cx.typeck_results().expr_ty(recv)); if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite()); then { span_lint_and_sugg( cx, ITER_CLONED_COLLECT, to_replace, "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \ more readable", "try", ".to_vec()".to_string(), Applicability::MachineApplicable, ); } } }
use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir;
random_line_split
iter_cloned_collect.rs
use crate::methods::utils::derefs_to_slice; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::ty::is_type_diagnostic_item; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_span::sym; use super::ITER_CLONED_COLLECT; pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, recv: &'tcx hir::Expr<'_>)
{ if_chain! { if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::Vec); if let Some(slice) = derefs_to_slice(cx, recv, cx.typeck_results().expr_ty(recv)); if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite()); then { span_lint_and_sugg( cx, ITER_CLONED_COLLECT, to_replace, "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \ more readable", "try", ".to_vec()".to_string(), Applicability::MachineApplicable, ); } } }
identifier_body
iter_cloned_collect.rs
use crate::methods::utils::derefs_to_slice; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::ty::is_type_diagnostic_item; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_span::sym; use super::ITER_CLONED_COLLECT; pub(super) fn
<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, recv: &'tcx hir::Expr<'_>) { if_chain! { if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::Vec); if let Some(slice) = derefs_to_slice(cx, recv, cx.typeck_results().expr_ty(recv)); if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite()); then { span_lint_and_sugg( cx, ITER_CLONED_COLLECT, to_replace, "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \ more readable", "try", ".to_vec()".to_string(), Applicability::MachineApplicable, ); } } }
check
identifier_name
renderer.rs
use sdl2; use sdl2::pixels; use sdl2::rect::Rect; use sdl2::image::LoadTexture; use sdl2::video::{Window, WindowContext}; use sdl2::render::TextureCreator; use std::path::Path; use terminal::Terminal; use font::FontDefinition; use sprites::SpriteSheet; pub struct Renderer { sdl_canvas: sdl2::render::Canvas<Window>, sprite_sheet: SpriteSheet, texture_creator: TextureCreator<WindowContext>, font: FontDefinition, } impl Renderer { pub fn new(terminal: &Terminal, font: FontDefinition) -> Self { let video_subsystem = terminal.sdl_context.video().unwrap(); let window = video_subsystem.window("davokar-rl", (terminal.columns * font.width) as u32, (terminal.rows * font.height) as u32) .position_centered() .build() .unwrap(); let sdl_canvas = window.into_canvas() .accelerated() .build() .unwrap(); let texture_creator = sdl_canvas.texture_creator(); let sprite_sheet = Renderer::load_font_sheet(&font, &texture_creator).unwrap(); Renderer { sdl_canvas, sprite_sheet, texture_creator: texture_creator, font, } } fn load_font_sheet(font: &FontDefinition, texture_creator: &TextureCreator<WindowContext>) -> Result<SpriteSheet, &'static str> { let texture_result = texture_creator.load_texture(Path::new(font.image_path)); match texture_result { Ok(texture) => Ok(SpriteSheet::new(texture, font.width, font.height, font.padding)), Err(_) => Err("failed to load font texture"), } } pub fn draw(&mut self, terminal: &mut Terminal)
cell.bg.a)); let _t = self.sdl_canvas .fill_rect(Rect::new(px as i32, py as i32, sprite.size.width(), sprite.size.height())); // draw the actual character sprite.draw(px as i32, py as i32, &mut self.sdl_canvas); cell.dirty = false; } } self.sdl_canvas.present(); } }
{ let total_cells = terminal.columns * terminal.rows; for i in 0..total_cells { let mut cell = &mut terminal.grid[i as usize]; if cell.dirty { self.sprite_sheet.texture.set_color_mod(cell.fg.r, cell.fg.g, cell.fg.b); let sprite = self.sprite_sheet.get_sprite((cell.glyph as u8) as usize); let x = i % terminal.columns; let y = i / terminal.columns; let px = x * self.font.width; let py = y * self.font.height; // draw the background for the cell self.sdl_canvas .set_draw_color(pixels::Color::RGBA(cell.bg.r, cell.bg.g, cell.bg.b,
identifier_body
renderer.rs
use sdl2; use sdl2::pixels; use sdl2::rect::Rect; use sdl2::image::LoadTexture; use sdl2::video::{Window, WindowContext}; use sdl2::render::TextureCreator; use std::path::Path; use terminal::Terminal; use font::FontDefinition; use sprites::SpriteSheet; pub struct Renderer { sdl_canvas: sdl2::render::Canvas<Window>, sprite_sheet: SpriteSheet, texture_creator: TextureCreator<WindowContext>, font: FontDefinition, } impl Renderer { pub fn new(terminal: &Terminal, font: FontDefinition) -> Self { let video_subsystem = terminal.sdl_context.video().unwrap(); let window = video_subsystem.window("davokar-rl", (terminal.columns * font.width) as u32, (terminal.rows * font.height) as u32) .position_centered() .build() .unwrap(); let sdl_canvas = window.into_canvas() .accelerated() .build() .unwrap(); let texture_creator = sdl_canvas.texture_creator(); let sprite_sheet = Renderer::load_font_sheet(&font, &texture_creator).unwrap(); Renderer { sdl_canvas, sprite_sheet, texture_creator: texture_creator, font, } } fn load_font_sheet(font: &FontDefinition, texture_creator: &TextureCreator<WindowContext>) -> Result<SpriteSheet, &'static str> { let texture_result = texture_creator.load_texture(Path::new(font.image_path)); match texture_result { Ok(texture) => Ok(SpriteSheet::new(texture, font.width, font.height, font.padding)), Err(_) => Err("failed to load font texture"), } } pub fn draw(&mut self, terminal: &mut Terminal) { let total_cells = terminal.columns * terminal.rows; for i in 0..total_cells { let mut cell = &mut terminal.grid[i as usize]; if cell.dirty
// draw the actual character sprite.draw(px as i32, py as i32, &mut self.sdl_canvas); cell.dirty = false; } } self.sdl_canvas.present(); } }
{ self.sprite_sheet.texture.set_color_mod(cell.fg.r, cell.fg.g, cell.fg.b); let sprite = self.sprite_sheet.get_sprite((cell.glyph as u8) as usize); let x = i % terminal.columns; let y = i / terminal.columns; let px = x * self.font.width; let py = y * self.font.height; // draw the background for the cell self.sdl_canvas .set_draw_color(pixels::Color::RGBA(cell.bg.r, cell.bg.g, cell.bg.b, cell.bg.a)); let _t = self.sdl_canvas .fill_rect(Rect::new(px as i32, py as i32, sprite.size.width(), sprite.size.height()));
conditional_block
renderer.rs
use sdl2; use sdl2::pixels; use sdl2::rect::Rect; use sdl2::image::LoadTexture; use sdl2::video::{Window, WindowContext}; use sdl2::render::TextureCreator; use std::path::Path; use terminal::Terminal; use font::FontDefinition; use sprites::SpriteSheet; pub struct Renderer { sdl_canvas: sdl2::render::Canvas<Window>, sprite_sheet: SpriteSheet, texture_creator: TextureCreator<WindowContext>, font: FontDefinition, } impl Renderer { pub fn
(terminal: &Terminal, font: FontDefinition) -> Self { let video_subsystem = terminal.sdl_context.video().unwrap(); let window = video_subsystem.window("davokar-rl", (terminal.columns * font.width) as u32, (terminal.rows * font.height) as u32) .position_centered() .build() .unwrap(); let sdl_canvas = window.into_canvas() .accelerated() .build() .unwrap(); let texture_creator = sdl_canvas.texture_creator(); let sprite_sheet = Renderer::load_font_sheet(&font, &texture_creator).unwrap(); Renderer { sdl_canvas, sprite_sheet, texture_creator: texture_creator, font, } } fn load_font_sheet(font: &FontDefinition, texture_creator: &TextureCreator<WindowContext>) -> Result<SpriteSheet, &'static str> { let texture_result = texture_creator.load_texture(Path::new(font.image_path)); match texture_result { Ok(texture) => Ok(SpriteSheet::new(texture, font.width, font.height, font.padding)), Err(_) => Err("failed to load font texture"), } } pub fn draw(&mut self, terminal: &mut Terminal) { let total_cells = terminal.columns * terminal.rows; for i in 0..total_cells { let mut cell = &mut terminal.grid[i as usize]; if cell.dirty { self.sprite_sheet.texture.set_color_mod(cell.fg.r, cell.fg.g, cell.fg.b); let sprite = self.sprite_sheet.get_sprite((cell.glyph as u8) as usize); let x = i % terminal.columns; let y = i / terminal.columns; let px = x * self.font.width; let py = y * self.font.height; // draw the background for the cell self.sdl_canvas .set_draw_color(pixels::Color::RGBA(cell.bg.r, cell.bg.g, cell.bg.b, cell.bg.a)); let _t = self.sdl_canvas .fill_rect(Rect::new(px as i32, py as i32, sprite.size.width(), sprite.size.height())); // draw the actual character sprite.draw(px as i32, py as i32, &mut self.sdl_canvas); cell.dirty = false; } } self.sdl_canvas.present(); } }
new
identifier_name
renderer.rs
use sdl2; use sdl2::pixels; use sdl2::rect::Rect; use sdl2::image::LoadTexture; use sdl2::video::{Window, WindowContext}; use sdl2::render::TextureCreator; use std::path::Path; use terminal::Terminal; use font::FontDefinition; use sprites::SpriteSheet; pub struct Renderer { sdl_canvas: sdl2::render::Canvas<Window>, sprite_sheet: SpriteSheet, texture_creator: TextureCreator<WindowContext>, font: FontDefinition, } impl Renderer { pub fn new(terminal: &Terminal, font: FontDefinition) -> Self { let video_subsystem = terminal.sdl_context.video().unwrap(); let window = video_subsystem.window("davokar-rl", (terminal.columns * font.width) as u32, (terminal.rows * font.height) as u32) .position_centered() .build() .unwrap(); let sdl_canvas = window.into_canvas() .accelerated() .build() .unwrap(); let texture_creator = sdl_canvas.texture_creator(); let sprite_sheet = Renderer::load_font_sheet(&font, &texture_creator).unwrap(); Renderer { sdl_canvas, sprite_sheet, texture_creator: texture_creator, font, } }
let texture_result = texture_creator.load_texture(Path::new(font.image_path)); match texture_result { Ok(texture) => Ok(SpriteSheet::new(texture, font.width, font.height, font.padding)), Err(_) => Err("failed to load font texture"), } } pub fn draw(&mut self, terminal: &mut Terminal) { let total_cells = terminal.columns * terminal.rows; for i in 0..total_cells { let mut cell = &mut terminal.grid[i as usize]; if cell.dirty { self.sprite_sheet.texture.set_color_mod(cell.fg.r, cell.fg.g, cell.fg.b); let sprite = self.sprite_sheet.get_sprite((cell.glyph as u8) as usize); let x = i % terminal.columns; let y = i / terminal.columns; let px = x * self.font.width; let py = y * self.font.height; // draw the background for the cell self.sdl_canvas .set_draw_color(pixels::Color::RGBA(cell.bg.r, cell.bg.g, cell.bg.b, cell.bg.a)); let _t = self.sdl_canvas .fill_rect(Rect::new(px as i32, py as i32, sprite.size.width(), sprite.size.height())); // draw the actual character sprite.draw(px as i32, py as i32, &mut self.sdl_canvas); cell.dirty = false; } } self.sdl_canvas.present(); } }
fn load_font_sheet(font: &FontDefinition, texture_creator: &TextureCreator<WindowContext>) -> Result<SpriteSheet, &'static str> {
random_line_split
config.in.rs
/* Copyright (c) 2015, Alex Frappier Lachapelle All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ use std::collections::BTreeMap; use std::error::Error; use std::fs::{File, OpenOptions}; use std::io::{Read, Write}; use std::path::PathBuf; extern crate term; use serde_json::Value; //////////////////////////////////////////////////////////// // Macros // //////////////////////////////////////////////////////////// include!("utils_macros.rs"); //////////////////////////////////////////////////////////// // Structs // //////////////////////////////////////////////////////////// #[derive(Clone)] pub struct TrelloBSTConfig { pub key_val_map: BTreeMap<String, String>, pub config_mode: Option<PathBuf> } //////////////////////////////////////////////////////////// // Impls // //////////////////////////////////////////////////////////// impl TrelloBSTConfig { pub fn
() -> TrelloBSTConfig { TrelloBSTConfig { key_val_map: BTreeMap::new(), config_mode: Option::None } } pub fn load(&mut self, config_mode: Option<PathBuf>) -> Result<(), &'static str> { self.config_mode = config_mode; //Parse if we're using a config file, silently skip if were not if self.config_mode.is_some() { //Load file let mut file = match File::open(self.clone().config_mode.unwrap().as_path()) { Ok(file) => file, Err(_) =>{ self.config_mode = Option::None; return Err("Error: Failed to open the configuration file for parsing, TrelloBST will continue without saving inputted values into the configuration file."); } }; //Get config file metadata. let metadata = match file.metadata() { Ok(metadata) => metadata, Err(_) => { self.config_mode = Option::None; return Err("Error: Failed to gather metadata of the configuration file, TrelloBST will continue without saving inputted values into the configuration file.") } }; //Parse config file let file_length: usize = metadata.len() as usize; if file_length == 0 { self.key_val_map = BTreeMap::new(); } else { //Read file let mut file_data: String = String::with_capacity(file_length + 1); match file.read_to_string(&mut file_data) { Ok(_) => (), Err(_) => { self.config_mode = Option::None; return Err("Error: Failed to read the configuration file, TrelloBST will continue without saving inputted values into the configuration file.") } } //Parse let json_data: Value = match serde_json::from_str(&file_data){ Ok(json_data) => json_data, Err(_) => { self.config_mode = Option::None; return Err("Error: Failed to parse the JSON data in the configuration file, TrelloBST will continue without saving inputted values into the configuration file.") } }; //Extract data //Get JSON object let json_object = match json_data.as_object().ok_or("Error: JSON data in the configuration file does not describe a JSON object, TrelloBST will continue without saving inputted values into the configuration file.") { Ok(object) => object.clone(), Err(err) => { self.config_mode = Option::None; return Err(err); } }; //Iterate through object for (key, val) in &json_object { if val.is_string() { self.key_val_map.insert(key.clone(), val.as_str().unwrap().to_string()); } else { println!("Value of the \"{}\" field in the configuration file is not a string, this value will not be considered.", key); } } } } Ok(()) } //Save config pub fn save(&mut self) -> Result<(), String> { if self.config_mode.is_some() { let mut json_map: BTreeMap<String, Value> = BTreeMap::new(); for (key, val) in &self.key_val_map { json_map.insert(key.clone(), Value::String(val.clone())); } let value = Value::Object(json_map); let json_map_string = match serde_json::to_string(&value) { Ok(map) => map, Err(err) => { return Err(err.description().to_string()); } }; //Open file, overwrite config with what we have let mut file: File; match OpenOptions::new().write(true).truncate(true).open(self.config_mode.clone().unwrap().as_path()) { Ok(_file) => { file = _file; match file.write_all(json_map_string.as_bytes()) { Ok(()) => (), Err(_) => { self.config_mode = Option::None; return Err("Error: Failed to write data to the configuration file, TrelloBST will continue without saving inputted values into the configuration file.".to_string()); } } } Err(_) => { self.config_mode = Option::None; return Err("Error: Failed to open the configuration file for saving, TrelloBST will continue without saving inputted values into the configuration file.".to_string()); } } } Ok(()) } //Sets a config key-value pair pub fn set(&mut self, key: &str, val: &str) { self.key_val_map.insert(key.to_string(), val.to_string()); } //Gets a config value for a key, returns "" if key doesnt exist and creates the key pub fn get(&mut self, key: &str) -> String { if self.key_val_map.contains_key(&key.to_string()) { return self.key_val_map.get(&key.to_string()).unwrap().clone(); } else { self.key_val_map.insert(key.to_string(), String::new()); return String::new(); } } }
new
identifier_name
config.in.rs
/* Copyright (c) 2015, Alex Frappier Lachapelle All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use std::collections::BTreeMap; use std::error::Error; use std::fs::{File, OpenOptions}; use std::io::{Read, Write}; use std::path::PathBuf; extern crate term; use serde_json::Value; //////////////////////////////////////////////////////////// // Macros // //////////////////////////////////////////////////////////// include!("utils_macros.rs"); //////////////////////////////////////////////////////////// // Structs // //////////////////////////////////////////////////////////// #[derive(Clone)] pub struct TrelloBSTConfig { pub key_val_map: BTreeMap<String, String>, pub config_mode: Option<PathBuf> } //////////////////////////////////////////////////////////// // Impls // //////////////////////////////////////////////////////////// impl TrelloBSTConfig { pub fn new() -> TrelloBSTConfig { TrelloBSTConfig { key_val_map: BTreeMap::new(), config_mode: Option::None } } pub fn load(&mut self, config_mode: Option<PathBuf>) -> Result<(), &'static str> { self.config_mode = config_mode; //Parse if we're using a config file, silently skip if were not if self.config_mode.is_some() { //Load file let mut file = match File::open(self.clone().config_mode.unwrap().as_path()) { Ok(file) => file, Err(_) =>{ self.config_mode = Option::None; return Err("Error: Failed to open the configuration file for parsing, TrelloBST will continue without saving inputted values into the configuration file."); } }; //Get config file metadata. let metadata = match file.metadata() { Ok(metadata) => metadata, Err(_) => { self.config_mode = Option::None; return Err("Error: Failed to gather metadata of the configuration file, TrelloBST will continue without saving inputted values into the configuration file.") } }; //Parse config file let file_length: usize = metadata.len() as usize; if file_length == 0 { self.key_val_map = BTreeMap::new(); } else { //Read file let mut file_data: String = String::with_capacity(file_length + 1); match file.read_to_string(&mut file_data) { Ok(_) => (), Err(_) => { self.config_mode = Option::None; return Err("Error: Failed to read the configuration file, TrelloBST will continue without saving inputted values into the configuration file.") } } //Parse let json_data: Value = match serde_json::from_str(&file_data){ Ok(json_data) => json_data, Err(_) => { self.config_mode = Option::None; return Err("Error: Failed to parse the JSON data in the configuration file, TrelloBST will continue without saving inputted values into the configuration file.") } }; //Extract data //Get JSON object let json_object = match json_data.as_object().ok_or("Error: JSON data in the configuration file does not describe a JSON object, TrelloBST will continue without saving inputted values into the configuration file.") { Ok(object) => object.clone(), Err(err) => { self.config_mode = Option::None; return Err(err); } }; //Iterate through object for (key, val) in &json_object { if val.is_string() { self.key_val_map.insert(key.clone(), val.as_str().unwrap().to_string()); } else { println!("Value of the \"{}\" field in the configuration file is not a string, this value will not be considered.", key); } } } } Ok(()) } //Save config pub fn save(&mut self) -> Result<(), String> { if self.config_mode.is_some() { let mut json_map: BTreeMap<String, Value> = BTreeMap::new(); for (key, val) in &self.key_val_map { json_map.insert(key.clone(), Value::String(val.clone())); } let value = Value::Object(json_map); let json_map_string = match serde_json::to_string(&value) { Ok(map) => map, Err(err) => { return Err(err.description().to_string()); } }; //Open file, overwrite config with what we have let mut file: File; match OpenOptions::new().write(true).truncate(true).open(self.config_mode.clone().unwrap().as_path()) { Ok(_file) => { file = _file; match file.write_all(json_map_string.as_bytes()) { Ok(()) => (), Err(_) => { self.config_mode = Option::None; return Err("Error: Failed to write data to the configuration file, TrelloBST will continue without saving inputted values into the configuration file.".to_string()); } } } Err(_) => { self.config_mode = Option::None; return Err("Error: Failed to open the configuration file for saving, TrelloBST will continue without saving inputted values into the configuration file.".to_string()); } } } Ok(()) } //Sets a config key-value pair pub fn set(&mut self, key: &str, val: &str) { self.key_val_map.insert(key.to_string(), val.to_string()); } //Gets a config value for a key, returns "" if key doesnt exist and creates the key pub fn get(&mut self, key: &str) -> String { if self.key_val_map.contains_key(&key.to_string()) { return self.key_val_map.get(&key.to_string()).unwrap().clone(); } else { self.key_val_map.insert(key.to_string(), String::new()); return String::new(); } } }
*/
random_line_split
config.in.rs
/* Copyright (c) 2015, Alex Frappier Lachapelle All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ use std::collections::BTreeMap; use std::error::Error; use std::fs::{File, OpenOptions}; use std::io::{Read, Write}; use std::path::PathBuf; extern crate term; use serde_json::Value; //////////////////////////////////////////////////////////// // Macros // //////////////////////////////////////////////////////////// include!("utils_macros.rs"); //////////////////////////////////////////////////////////// // Structs // //////////////////////////////////////////////////////////// #[derive(Clone)] pub struct TrelloBSTConfig { pub key_val_map: BTreeMap<String, String>, pub config_mode: Option<PathBuf> } //////////////////////////////////////////////////////////// // Impls // //////////////////////////////////////////////////////////// impl TrelloBSTConfig { pub fn new() -> TrelloBSTConfig { TrelloBSTConfig { key_val_map: BTreeMap::new(), config_mode: Option::None } } pub fn load(&mut self, config_mode: Option<PathBuf>) -> Result<(), &'static str>
self.config_mode = Option::None; return Err("Error: Failed to gather metadata of the configuration file, TrelloBST will continue without saving inputted values into the configuration file.") } }; //Parse config file let file_length: usize = metadata.len() as usize; if file_length == 0 { self.key_val_map = BTreeMap::new(); } else { //Read file let mut file_data: String = String::with_capacity(file_length + 1); match file.read_to_string(&mut file_data) { Ok(_) => (), Err(_) => { self.config_mode = Option::None; return Err("Error: Failed to read the configuration file, TrelloBST will continue without saving inputted values into the configuration file.") } } //Parse let json_data: Value = match serde_json::from_str(&file_data){ Ok(json_data) => json_data, Err(_) => { self.config_mode = Option::None; return Err("Error: Failed to parse the JSON data in the configuration file, TrelloBST will continue without saving inputted values into the configuration file.") } }; //Extract data //Get JSON object let json_object = match json_data.as_object().ok_or("Error: JSON data in the configuration file does not describe a JSON object, TrelloBST will continue without saving inputted values into the configuration file.") { Ok(object) => object.clone(), Err(err) => { self.config_mode = Option::None; return Err(err); } }; //Iterate through object for (key, val) in &json_object { if val.is_string() { self.key_val_map.insert(key.clone(), val.as_str().unwrap().to_string()); } else { println!("Value of the \"{}\" field in the configuration file is not a string, this value will not be considered.", key); } } } } Ok(()) } //Save config pub fn save(&mut self) -> Result<(), String> { if self.config_mode.is_some() { let mut json_map: BTreeMap<String, Value> = BTreeMap::new(); for (key, val) in &self.key_val_map { json_map.insert(key.clone(), Value::String(val.clone())); } let value = Value::Object(json_map); let json_map_string = match serde_json::to_string(&value) { Ok(map) => map, Err(err) => { return Err(err.description().to_string()); } }; //Open file, overwrite config with what we have let mut file: File; match OpenOptions::new().write(true).truncate(true).open(self.config_mode.clone().unwrap().as_path()) { Ok(_file) => { file = _file; match file.write_all(json_map_string.as_bytes()) { Ok(()) => (), Err(_) => { self.config_mode = Option::None; return Err("Error: Failed to write data to the configuration file, TrelloBST will continue without saving inputted values into the configuration file.".to_string()); } } } Err(_) => { self.config_mode = Option::None; return Err("Error: Failed to open the configuration file for saving, TrelloBST will continue without saving inputted values into the configuration file.".to_string()); } } } Ok(()) } //Sets a config key-value pair pub fn set(&mut self, key: &str, val: &str) { self.key_val_map.insert(key.to_string(), val.to_string()); } //Gets a config value for a key, returns "" if key doesnt exist and creates the key pub fn get(&mut self, key: &str) -> String { if self.key_val_map.contains_key(&key.to_string()) { return self.key_val_map.get(&key.to_string()).unwrap().clone(); } else { self.key_val_map.insert(key.to_string(), String::new()); return String::new(); } } }
{ self.config_mode = config_mode; //Parse if we're using a config file, silently skip if were not if self.config_mode.is_some() { //Load file let mut file = match File::open(self.clone().config_mode.unwrap().as_path()) { Ok(file) => file, Err(_) =>{ self.config_mode = Option::None; return Err("Error: Failed to open the configuration file for parsing, TrelloBST will continue without saving inputted values into the configuration file."); } }; //Get config file metadata. let metadata = match file.metadata() { Ok(metadata) => metadata, Err(_) => {
identifier_body
huffman.rs
use std::fmt; use crate::decoders::basics::*; const DECODE_CACHE_BITS: u32 = 13; pub struct HuffTable { // These two fields directly represent the contents of a JPEG DHT marker pub bits: [u32;17], pub huffval: [u32;256], // Represent the weird shifts that are needed for some NEF files pub shiftval: [u32;256], // Enable the workaround for 16 bit decodes in DNG that need to consume those // bits instead of the value being implied pub dng_bug: bool, // In CRW we only use the len code so the cache is not needed pub disable_cache: bool, // The remaining fields are computed from the above to allow more // efficient coding and decoding and thus private // The max number of bits in a huffman code and the table that converts those // bits into how many bits to consume and the decoded length and shift nbits: u32, hufftable: Vec<(u8,u8,u8)>, // A pregenerated table that goes straight to decoding a diff without first // finding a length, fetching bits, and sign extending them. The table is // sized by DECODE_CACHE_BITS and can have 99%+ hit rate with 13 bits decodecache: [Option<(u8,i16)>; 1<< DECODE_CACHE_BITS], initialized: bool, } struct MockPump { bits: u64,
nbits: u32, } impl MockPump { pub fn empty() -> Self { MockPump { bits: 0, nbits: 0, } } pub fn set(&mut self, bits: u32, nbits: u32) { self.bits = (bits as u64) << 32; self.nbits = nbits + 32; } pub fn validbits(&self) -> i32 { self.nbits as i32 - 32 } } impl BitPump for MockPump { fn peek_bits(&mut self, num: u32) -> u32 { (self.bits >> (self.nbits-num)) as u32 } fn consume_bits(&mut self, num: u32) { self.nbits -= num; self.bits &= (1 << self.nbits) - 1; } } impl HuffTable { pub fn empty() -> HuffTable { HuffTable { bits: [0;17], huffval: [0;256], shiftval: [0;256], dng_bug: false, disable_cache: false, nbits: 0, hufftable: Vec::new(), decodecache: [None; 1 << DECODE_CACHE_BITS], initialized: false, } } pub fn new(bits: [u32;17], huffval: [u32;256], dng_bug: bool) -> Result<HuffTable,String> { let mut tbl = HuffTable { bits: bits, huffval: huffval, shiftval: [0;256], dng_bug: dng_bug, disable_cache: false, nbits: 0, hufftable: Vec::new(), decodecache: [None; 1 << DECODE_CACHE_BITS], initialized: false, }; tbl.initialize()?; Ok(tbl) } pub fn initialize(&mut self) -> Result<(), String> { // Find out the max code length and allocate a table with that size self.nbits = 16; for i in 0..16 { if self.bits[16-i]!= 0 { break; } self.nbits -= 1; } self.hufftable = vec![(0,0,0); 1 << self.nbits]; // Fill in the table itself let mut h = 0; let mut pos = 0; for len in 0..self.nbits { for _ in 0..self.bits[len as usize + 1] { for _ in 0..(1 << (self.nbits-len-1)) { self.hufftable[h] = (len as u8 + 1, self.huffval[pos] as u8, self.shiftval[pos] as u8); h += 1; } pos += 1; } } // Create the decode cache by running the slow code over all the possible // values DECODE_CACHE_BITS wide if!self.disable_cache { let mut pump = MockPump::empty(); let mut i = 0; loop { pump.set(i, DECODE_CACHE_BITS); let (bits, decode) = self.huff_decode_slow(&mut pump); if pump.validbits() >= 0 { self.decodecache[i as usize] = Some((bits, decode as i16)); } i += 1; if i >= 1 << DECODE_CACHE_BITS { break; } } } self.initialized = true; Ok(()) } #[inline(always)] pub fn huff_decode(&self, pump: &mut dyn BitPump) -> Result<i32,String> { let code = pump.peek_bits(DECODE_CACHE_BITS) as usize; if let Some((bits,decode)) = self.decodecache[code] { pump.consume_bits(bits as u32); Ok(decode as i32) } else { let decode = self.huff_decode_slow(pump); Ok(decode.1) } } #[inline(always)] pub fn huff_decode_slow(&self, pump: &mut dyn BitPump) -> (u8,i32) { let len = self.huff_len(pump); (len.0+len.1, self.huff_diff(pump, len)) } #[inline(always)] pub fn huff_len(&self, pump: &mut dyn BitPump) -> (u8,u8,u8) { let code = pump.peek_bits(self.nbits) as usize; let (bits, len, shift) = self.hufftable[code]; pump.consume_bits(bits as u32); (bits, len, shift) } #[inline(always)] pub fn huff_get_bits(&self, pump: &mut dyn BitPump) -> u32 { let code = pump.peek_bits(self.nbits) as usize; let (bits, len, _) = self.hufftable[code]; pump.consume_bits(bits as u32); len as u32 } #[inline(always)] pub fn huff_diff(&self, pump: &mut dyn BitPump, input: (u8,u8,u8)) -> i32 { let (_, len, shift) = input; match len { 0 => 0, 16 => { if self.dng_bug { pump.get_bits(16); // consume can fail because we haven't peeked yet } -32768 }, len => { // decode the difference and extend sign bit let fulllen: i32 = len as i32 + shift as i32; let shift: i32 = shift as i32; let bits = pump.get_bits(len as u32) as i32; let mut diff: i32 = ((bits << 1) + 1) << shift >> 1; if (diff & (1 << (fulllen - 1))) == 0 { diff -= (1 << fulllen) - ((shift == 0) as i32); } diff }, } } } impl fmt::Debug for HuffTable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.initialized { write!(f, "HuffTable {{ bits: {:?} huffval: {:?} }}", self.bits, &self.huffval[..]) } else { write!(f, "HuffTable {{ uninitialized }}") } } }
random_line_split
huffman.rs
use std::fmt; use crate::decoders::basics::*; const DECODE_CACHE_BITS: u32 = 13; pub struct HuffTable { // These two fields directly represent the contents of a JPEG DHT marker pub bits: [u32;17], pub huffval: [u32;256], // Represent the weird shifts that are needed for some NEF files pub shiftval: [u32;256], // Enable the workaround for 16 bit decodes in DNG that need to consume those // bits instead of the value being implied pub dng_bug: bool, // In CRW we only use the len code so the cache is not needed pub disable_cache: bool, // The remaining fields are computed from the above to allow more // efficient coding and decoding and thus private // The max number of bits in a huffman code and the table that converts those // bits into how many bits to consume and the decoded length and shift nbits: u32, hufftable: Vec<(u8,u8,u8)>, // A pregenerated table that goes straight to decoding a diff without first // finding a length, fetching bits, and sign extending them. The table is // sized by DECODE_CACHE_BITS and can have 99%+ hit rate with 13 bits decodecache: [Option<(u8,i16)>; 1<< DECODE_CACHE_BITS], initialized: bool, } struct MockPump { bits: u64, nbits: u32, } impl MockPump { pub fn empty() -> Self { MockPump { bits: 0, nbits: 0, } } pub fn set(&mut self, bits: u32, nbits: u32) { self.bits = (bits as u64) << 32; self.nbits = nbits + 32; } pub fn validbits(&self) -> i32 { self.nbits as i32 - 32 } } impl BitPump for MockPump { fn peek_bits(&mut self, num: u32) -> u32 { (self.bits >> (self.nbits-num)) as u32 } fn consume_bits(&mut self, num: u32) { self.nbits -= num; self.bits &= (1 << self.nbits) - 1; } } impl HuffTable { pub fn empty() -> HuffTable { HuffTable { bits: [0;17], huffval: [0;256], shiftval: [0;256], dng_bug: false, disable_cache: false, nbits: 0, hufftable: Vec::new(), decodecache: [None; 1 << DECODE_CACHE_BITS], initialized: false, } } pub fn new(bits: [u32;17], huffval: [u32;256], dng_bug: bool) -> Result<HuffTable,String>
pub fn initialize(&mut self) -> Result<(), String> { // Find out the max code length and allocate a table with that size self.nbits = 16; for i in 0..16 { if self.bits[16-i]!= 0 { break; } self.nbits -= 1; } self.hufftable = vec![(0,0,0); 1 << self.nbits]; // Fill in the table itself let mut h = 0; let mut pos = 0; for len in 0..self.nbits { for _ in 0..self.bits[len as usize + 1] { for _ in 0..(1 << (self.nbits-len-1)) { self.hufftable[h] = (len as u8 + 1, self.huffval[pos] as u8, self.shiftval[pos] as u8); h += 1; } pos += 1; } } // Create the decode cache by running the slow code over all the possible // values DECODE_CACHE_BITS wide if!self.disable_cache { let mut pump = MockPump::empty(); let mut i = 0; loop { pump.set(i, DECODE_CACHE_BITS); let (bits, decode) = self.huff_decode_slow(&mut pump); if pump.validbits() >= 0 { self.decodecache[i as usize] = Some((bits, decode as i16)); } i += 1; if i >= 1 << DECODE_CACHE_BITS { break; } } } self.initialized = true; Ok(()) } #[inline(always)] pub fn huff_decode(&self, pump: &mut dyn BitPump) -> Result<i32,String> { let code = pump.peek_bits(DECODE_CACHE_BITS) as usize; if let Some((bits,decode)) = self.decodecache[code] { pump.consume_bits(bits as u32); Ok(decode as i32) } else { let decode = self.huff_decode_slow(pump); Ok(decode.1) } } #[inline(always)] pub fn huff_decode_slow(&self, pump: &mut dyn BitPump) -> (u8,i32) { let len = self.huff_len(pump); (len.0+len.1, self.huff_diff(pump, len)) } #[inline(always)] pub fn huff_len(&self, pump: &mut dyn BitPump) -> (u8,u8,u8) { let code = pump.peek_bits(self.nbits) as usize; let (bits, len, shift) = self.hufftable[code]; pump.consume_bits(bits as u32); (bits, len, shift) } #[inline(always)] pub fn huff_get_bits(&self, pump: &mut dyn BitPump) -> u32 { let code = pump.peek_bits(self.nbits) as usize; let (bits, len, _) = self.hufftable[code]; pump.consume_bits(bits as u32); len as u32 } #[inline(always)] pub fn huff_diff(&self, pump: &mut dyn BitPump, input: (u8,u8,u8)) -> i32 { let (_, len, shift) = input; match len { 0 => 0, 16 => { if self.dng_bug { pump.get_bits(16); // consume can fail because we haven't peeked yet } -32768 }, len => { // decode the difference and extend sign bit let fulllen: i32 = len as i32 + shift as i32; let shift: i32 = shift as i32; let bits = pump.get_bits(len as u32) as i32; let mut diff: i32 = ((bits << 1) + 1) << shift >> 1; if (diff & (1 << (fulllen - 1))) == 0 { diff -= (1 << fulllen) - ((shift == 0) as i32); } diff }, } } } impl fmt::Debug for HuffTable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.initialized { write!(f, "HuffTable {{ bits: {:?} huffval: {:?} }}", self.bits, &self.huffval[..]) } else { write!(f, "HuffTable {{ uninitialized }}") } } }
{ let mut tbl = HuffTable { bits: bits, huffval: huffval, shiftval: [0;256], dng_bug: dng_bug, disable_cache: false, nbits: 0, hufftable: Vec::new(), decodecache: [None; 1 << DECODE_CACHE_BITS], initialized: false, }; tbl.initialize()?; Ok(tbl) }
identifier_body
huffman.rs
use std::fmt; use crate::decoders::basics::*; const DECODE_CACHE_BITS: u32 = 13; pub struct HuffTable { // These two fields directly represent the contents of a JPEG DHT marker pub bits: [u32;17], pub huffval: [u32;256], // Represent the weird shifts that are needed for some NEF files pub shiftval: [u32;256], // Enable the workaround for 16 bit decodes in DNG that need to consume those // bits instead of the value being implied pub dng_bug: bool, // In CRW we only use the len code so the cache is not needed pub disable_cache: bool, // The remaining fields are computed from the above to allow more // efficient coding and decoding and thus private // The max number of bits in a huffman code and the table that converts those // bits into how many bits to consume and the decoded length and shift nbits: u32, hufftable: Vec<(u8,u8,u8)>, // A pregenerated table that goes straight to decoding a diff without first // finding a length, fetching bits, and sign extending them. The table is // sized by DECODE_CACHE_BITS and can have 99%+ hit rate with 13 bits decodecache: [Option<(u8,i16)>; 1<< DECODE_CACHE_BITS], initialized: bool, } struct MockPump { bits: u64, nbits: u32, } impl MockPump { pub fn empty() -> Self { MockPump { bits: 0, nbits: 0, } } pub fn set(&mut self, bits: u32, nbits: u32) { self.bits = (bits as u64) << 32; self.nbits = nbits + 32; } pub fn validbits(&self) -> i32 { self.nbits as i32 - 32 } } impl BitPump for MockPump { fn peek_bits(&mut self, num: u32) -> u32 { (self.bits >> (self.nbits-num)) as u32 } fn consume_bits(&mut self, num: u32) { self.nbits -= num; self.bits &= (1 << self.nbits) - 1; } } impl HuffTable { pub fn empty() -> HuffTable { HuffTable { bits: [0;17], huffval: [0;256], shiftval: [0;256], dng_bug: false, disable_cache: false, nbits: 0, hufftable: Vec::new(), decodecache: [None; 1 << DECODE_CACHE_BITS], initialized: false, } } pub fn new(bits: [u32;17], huffval: [u32;256], dng_bug: bool) -> Result<HuffTable,String> { let mut tbl = HuffTable { bits: bits, huffval: huffval, shiftval: [0;256], dng_bug: dng_bug, disable_cache: false, nbits: 0, hufftable: Vec::new(), decodecache: [None; 1 << DECODE_CACHE_BITS], initialized: false, }; tbl.initialize()?; Ok(tbl) } pub fn
(&mut self) -> Result<(), String> { // Find out the max code length and allocate a table with that size self.nbits = 16; for i in 0..16 { if self.bits[16-i]!= 0 { break; } self.nbits -= 1; } self.hufftable = vec![(0,0,0); 1 << self.nbits]; // Fill in the table itself let mut h = 0; let mut pos = 0; for len in 0..self.nbits { for _ in 0..self.bits[len as usize + 1] { for _ in 0..(1 << (self.nbits-len-1)) { self.hufftable[h] = (len as u8 + 1, self.huffval[pos] as u8, self.shiftval[pos] as u8); h += 1; } pos += 1; } } // Create the decode cache by running the slow code over all the possible // values DECODE_CACHE_BITS wide if!self.disable_cache { let mut pump = MockPump::empty(); let mut i = 0; loop { pump.set(i, DECODE_CACHE_BITS); let (bits, decode) = self.huff_decode_slow(&mut pump); if pump.validbits() >= 0 { self.decodecache[i as usize] = Some((bits, decode as i16)); } i += 1; if i >= 1 << DECODE_CACHE_BITS { break; } } } self.initialized = true; Ok(()) } #[inline(always)] pub fn huff_decode(&self, pump: &mut dyn BitPump) -> Result<i32,String> { let code = pump.peek_bits(DECODE_CACHE_BITS) as usize; if let Some((bits,decode)) = self.decodecache[code] { pump.consume_bits(bits as u32); Ok(decode as i32) } else { let decode = self.huff_decode_slow(pump); Ok(decode.1) } } #[inline(always)] pub fn huff_decode_slow(&self, pump: &mut dyn BitPump) -> (u8,i32) { let len = self.huff_len(pump); (len.0+len.1, self.huff_diff(pump, len)) } #[inline(always)] pub fn huff_len(&self, pump: &mut dyn BitPump) -> (u8,u8,u8) { let code = pump.peek_bits(self.nbits) as usize; let (bits, len, shift) = self.hufftable[code]; pump.consume_bits(bits as u32); (bits, len, shift) } #[inline(always)] pub fn huff_get_bits(&self, pump: &mut dyn BitPump) -> u32 { let code = pump.peek_bits(self.nbits) as usize; let (bits, len, _) = self.hufftable[code]; pump.consume_bits(bits as u32); len as u32 } #[inline(always)] pub fn huff_diff(&self, pump: &mut dyn BitPump, input: (u8,u8,u8)) -> i32 { let (_, len, shift) = input; match len { 0 => 0, 16 => { if self.dng_bug { pump.get_bits(16); // consume can fail because we haven't peeked yet } -32768 }, len => { // decode the difference and extend sign bit let fulllen: i32 = len as i32 + shift as i32; let shift: i32 = shift as i32; let bits = pump.get_bits(len as u32) as i32; let mut diff: i32 = ((bits << 1) + 1) << shift >> 1; if (diff & (1 << (fulllen - 1))) == 0 { diff -= (1 << fulllen) - ((shift == 0) as i32); } diff }, } } } impl fmt::Debug for HuffTable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.initialized { write!(f, "HuffTable {{ bits: {:?} huffval: {:?} }}", self.bits, &self.huffval[..]) } else { write!(f, "HuffTable {{ uninitialized }}") } } }
initialize
identifier_name
cube.rs
use vec3::Vec3; use ray::Ray; use model::bvh::{AABB, BoundingBox}; use model::hitable::{HitRecord, Hitable}; use model::hitable::flip_normals; use model::rect::Rect; pub struct Cube { min: Vec3, max: Vec3, sides: Vec<Box<Hitable>> } impl Cube { // Cube of size dimensions pub fn new(dimensions: Vec3) -> Cube { let p0 = Vec3::new(0.0,0.0,0.0); let p1 = dimensions; Cube::new_from_min_max(p0,p1) } pub fn new_from_min_max(p0: Vec3, p1: Vec3) -> Cube { let mut sides: Vec<Box<Hitable>> = Vec::with_capacity(6); sides.push(Box::new(Rect::xy_rect(p0.x, p1.x, p0.y, p1.y, p1.z))); sides.push(Box::new(flip_normals(Rect::xy_rect(p0.x, p1.x, p0.y, p1.y, p0.z)))); sides.push(Box::new(Rect::xz_rect(p0.x, p1.x, p0.z, p1.z, p1.y))); sides.push(Box::new(flip_normals(Rect::xz_rect(p0.x, p1.x, p0.z, p1.z, p0.y)))); sides.push(Box::new(Rect::yz_rect(p0.y, p1.y, p0.z, p1.z, p1.x))); sides.push(Box::new(flip_normals(Rect::yz_rect(p0.y, p1.y, p0.z, p1.z, p0.x)))); Cube { min: p0, max: p1, sides: sides } } pub fn unit_cube() -> Cube { Cube::new_from_min_max(Vec3::new(-1.0,-1.0,-1.0), Vec3::new(1.0,1.0,1.0)) } } impl Hitable for Cube { fn hit(&self, r: &Ray, t_min: f64, t_max: f64) -> Option<HitRecord> { self.sides.hit(r,t_min,t_max) } } impl BoundingBox for Cube { fn bounding_box(&self) -> AABB
}
{ AABB { min: self.min, max: self.max, } }
identifier_body
cube.rs
use vec3::Vec3; use ray::Ray; use model::bvh::{AABB, BoundingBox}; use model::hitable::{HitRecord, Hitable}; use model::hitable::flip_normals; use model::rect::Rect; pub struct Cube { min: Vec3, max: Vec3, sides: Vec<Box<Hitable>> } impl Cube { // Cube of size dimensions pub fn new(dimensions: Vec3) -> Cube { let p0 = Vec3::new(0.0,0.0,0.0); let p1 = dimensions; Cube::new_from_min_max(p0,p1) } pub fn new_from_min_max(p0: Vec3, p1: Vec3) -> Cube { let mut sides: Vec<Box<Hitable>> = Vec::with_capacity(6); sides.push(Box::new(Rect::xy_rect(p0.x, p1.x, p0.y, p1.y, p1.z))); sides.push(Box::new(flip_normals(Rect::xy_rect(p0.x, p1.x, p0.y, p1.y, p0.z)))); sides.push(Box::new(Rect::xz_rect(p0.x, p1.x, p0.z, p1.z, p1.y))); sides.push(Box::new(flip_normals(Rect::xz_rect(p0.x, p1.x, p0.z, p1.z, p0.y)))); sides.push(Box::new(Rect::yz_rect(p0.y, p1.y, p0.z, p1.z, p1.x))); sides.push(Box::new(flip_normals(Rect::yz_rect(p0.y, p1.y, p0.z, p1.z, p0.x)))); Cube { min: p0, max: p1, sides: sides } } pub fn
() -> Cube { Cube::new_from_min_max(Vec3::new(-1.0,-1.0,-1.0), Vec3::new(1.0,1.0,1.0)) } } impl Hitable for Cube { fn hit(&self, r: &Ray, t_min: f64, t_max: f64) -> Option<HitRecord> { self.sides.hit(r,t_min,t_max) } } impl BoundingBox for Cube { fn bounding_box(&self) -> AABB { AABB { min: self.min, max: self.max, } } }
unit_cube
identifier_name
cube.rs
use vec3::Vec3; use ray::Ray; use model::bvh::{AABB, BoundingBox}; use model::hitable::{HitRecord, Hitable}; use model::hitable::flip_normals; use model::rect::Rect; pub struct Cube { min: Vec3, max: Vec3, sides: Vec<Box<Hitable>> } impl Cube { // Cube of size dimensions pub fn new(dimensions: Vec3) -> Cube { let p0 = Vec3::new(0.0,0.0,0.0); let p1 = dimensions; Cube::new_from_min_max(p0,p1) } pub fn new_from_min_max(p0: Vec3, p1: Vec3) -> Cube { let mut sides: Vec<Box<Hitable>> = Vec::with_capacity(6);
sides.push(Box::new(Rect::xy_rect(p0.x, p1.x, p0.y, p1.y, p1.z))); sides.push(Box::new(flip_normals(Rect::xy_rect(p0.x, p1.x, p0.y, p1.y, p0.z)))); sides.push(Box::new(Rect::xz_rect(p0.x, p1.x, p0.z, p1.z, p1.y))); sides.push(Box::new(flip_normals(Rect::xz_rect(p0.x, p1.x, p0.z, p1.z, p0.y)))); sides.push(Box::new(Rect::yz_rect(p0.y, p1.y, p0.z, p1.z, p1.x))); sides.push(Box::new(flip_normals(Rect::yz_rect(p0.y, p1.y, p0.z, p1.z, p0.x)))); Cube { min: p0, max: p1, sides: sides } } pub fn unit_cube() -> Cube { Cube::new_from_min_max(Vec3::new(-1.0,-1.0,-1.0), Vec3::new(1.0,1.0,1.0)) } } impl Hitable for Cube { fn hit(&self, r: &Ray, t_min: f64, t_max: f64) -> Option<HitRecord> { self.sides.hit(r,t_min,t_max) } } impl BoundingBox for Cube { fn bounding_box(&self) -> AABB { AABB { min: self.min, max: self.max, } } }
random_line_split
main.rs
extern crate orbital; use std::fs::File; use std::env; use std::io::{Read, Write}; use wav::WavFile; use orbital::*; mod wav; fn main() { let url = match env::args().nth(1) { Some(arg) => arg.clone(), None => "none:", }; let mut vec: Vec<u8> = Vec::new(); if let Ok(mut file) = File::open(&url) { file.read_to_end(&mut vec); } let mut window = Window::new(-1, -1, 320, 0, &("Player (".to_string() + &url + ")")).unwrap(); window.sync(); let wav = WavFile::from_data(&vec); if!wav.data.is_empty() { if let Ok(mut audio) = File::open("audio://")
} while let Some(event) = window.poll() { if let EventOption::Key(key_event) = event.to_option() { if key_event.pressed && key_event.scancode == K_ESC { break; } } if let EventOption::Quit(_) = event.to_option() { break; } } }
{ audio.write(&wav.data); }
conditional_block
main.rs
extern crate orbital; use std::fs::File; use std::env; use std::io::{Read, Write}; use wav::WavFile; use orbital::*; mod wav; fn main() { let url = match env::args().nth(1) { Some(arg) => arg.clone(), None => "none:", }; let mut vec: Vec<u8> = Vec::new(); if let Ok(mut file) = File::open(&url) { file.read_to_end(&mut vec); } let mut window = Window::new(-1, -1, 320, 0, &("Player (".to_string() + &url + ")")).unwrap(); window.sync(); let wav = WavFile::from_data(&vec);
if!wav.data.is_empty() { if let Ok(mut audio) = File::open("audio://") { audio.write(&wav.data); } } while let Some(event) = window.poll() { if let EventOption::Key(key_event) = event.to_option() { if key_event.pressed && key_event.scancode == K_ESC { break; } } if let EventOption::Quit(_) = event.to_option() { break; } } }
random_line_split
main.rs
extern crate orbital; use std::fs::File; use std::env; use std::io::{Read, Write}; use wav::WavFile; use orbital::*; mod wav; fn main()
} while let Some(event) = window.poll() { if let EventOption::Key(key_event) = event.to_option() { if key_event.pressed && key_event.scancode == K_ESC { break; } } if let EventOption::Quit(_) = event.to_option() { break; } } }
{ let url = match env::args().nth(1) { Some(arg) => arg.clone(), None => "none:", }; let mut vec: Vec<u8> = Vec::new(); if let Ok(mut file) = File::open(&url) { file.read_to_end(&mut vec); } let mut window = Window::new(-1, -1, 320, 0, &("Player (".to_string() + &url + ")")).unwrap(); window.sync(); let wav = WavFile::from_data(&vec); if !wav.data.is_empty() { if let Ok(mut audio) = File::open("audio://") { audio.write(&wav.data); }
identifier_body
main.rs
extern crate orbital; use std::fs::File; use std::env; use std::io::{Read, Write}; use wav::WavFile; use orbital::*; mod wav; fn
() { let url = match env::args().nth(1) { Some(arg) => arg.clone(), None => "none:", }; let mut vec: Vec<u8> = Vec::new(); if let Ok(mut file) = File::open(&url) { file.read_to_end(&mut vec); } let mut window = Window::new(-1, -1, 320, 0, &("Player (".to_string() + &url + ")")).unwrap(); window.sync(); let wav = WavFile::from_data(&vec); if!wav.data.is_empty() { if let Ok(mut audio) = File::open("audio://") { audio.write(&wav.data); } } while let Some(event) = window.poll() { if let EventOption::Key(key_event) = event.to_option() { if key_event.pressed && key_event.scancode == K_ESC { break; } } if let EventOption::Quit(_) = event.to_option() { break; } } }
main
identifier_name
types.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Result as FmtResult; use toml::Value; use toml::map::Map; use anyhow::Result; use anyhow::Error; use libimagerror::errors::Error as EM; pub trait FromValue : Sized { fn from_value(v: &Value) -> Result<Self>; } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct GPSValue { pub degree: i64, pub minutes: i64, pub seconds: i64, } impl GPSValue { pub fn new(d: i64, m: i64, s: i64) -> GPSValue { GPSValue { degree: d, minutes: m, seconds: s } } pub fn degree(&self) -> i64 { self.degree } pub fn minutes(&self) -> i64 { self.minutes } pub fn seconds(&self) -> i64 { self.seconds } } impl Into<Value> for GPSValue { fn into(self) -> Value { let mut map = Map::new(); let _ = map.insert("degree".to_owned(), Value::Integer(self.degree)); let _ = map.insert("minutes".to_owned(), Value::Integer(self.minutes)); let _ = map.insert("seconds".to_owned(), Value::Integer(self.seconds)); Value::Table(map) } } impl FromValue for GPSValue { fn from_value(v: &Value) -> Result<Self> { let int_to_appropriate_width = |v: &Value| { v.as_integer() .ok_or_else(|| Error::from(EM::EntryHeaderTypeError)) }; match *v { Value::Table(ref map) => { Ok(GPSValue::new( map.get("degree") .ok_or_else(|| anyhow!("Degree missing")) .and_then(&int_to_appropriate_width)?, map .get("minutes") .ok_or_else(|| anyhow!("Minutes missing")) .and_then(&int_to_appropriate_width)?, map .get("seconds") .ok_or_else(|| anyhow!("Seconds missing")) .and_then(&int_to_appropriate_width)? )) } _ => Err(Error::from(EM::EntryHeaderTypeError)) } } } impl Display for GPSValue { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "{}° {}\" {}'", self.degree, self.minutes, self.seconds) } } /// Data-transfer type for transfering longitude-latitude-pairs #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct Coordinates { pub longitude: GPSValue, pub latitude: GPSValue, } impl Coordinates { pub fn new(long: GPSValue, lat: GPSValue) -> Coordinates { Coordinates { longitude: long, latitude: lat, } } pub fn longitude(&self) -> &GPSValue { &self.longitude } pub fn latitude(&self) -> &GPSValue { &self.latitude } } impl Into<Value> for Coordinates { fn into(self) -> Value { let mut map = Map::new(); let _ = map.insert("longitude".to_owned(), self.longitude.into()); let _ = map.insert("latitude".to_owned(), self.latitude.into()); Value::Table(map) } } impl FromValue for Coordinates { fn f
v: &Value) -> Result<Self> { v.as_table() .ok_or_else(|| Error::from(EM::EntryHeaderTypeError)) .and_then(|t| { let get = |m: &Map<_, _>, what: &'static str, ek: &'static str| -> Result<GPSValue> { m.get(what) .ok_or_else(|| anyhow!(ek)) .and_then(GPSValue::from_value) }; Ok(Coordinates::new( get(t, "longitude", "Longitude missing")?, get(t, "latitude", "Latitude missing")? )) }) } } impl Display for Coordinates { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "longitude = {}\nlatitude = {}", self.longitude, self.latitude) } }
rom_value(
identifier_name
types.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Result as FmtResult; use toml::Value; use toml::map::Map; use anyhow::Result; use anyhow::Error; use libimagerror::errors::Error as EM; pub trait FromValue : Sized { fn from_value(v: &Value) -> Result<Self>; } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct GPSValue { pub degree: i64, pub minutes: i64, pub seconds: i64, } impl GPSValue { pub fn new(d: i64, m: i64, s: i64) -> GPSValue { GPSValue { degree: d, minutes: m, seconds: s } } pub fn degree(&self) -> i64 { self.degree } pub fn minutes(&self) -> i64 { self.minutes } pub fn seconds(&self) -> i64 { self.seconds } } impl Into<Value> for GPSValue { fn into(self) -> Value { let mut map = Map::new(); let _ = map.insert("degree".to_owned(), Value::Integer(self.degree)); let _ = map.insert("minutes".to_owned(), Value::Integer(self.minutes)); let _ = map.insert("seconds".to_owned(), Value::Integer(self.seconds)); Value::Table(map) } } impl FromValue for GPSValue { fn from_value(v: &Value) -> Result<Self> { let int_to_appropriate_width = |v: &Value| { v.as_integer() .ok_or_else(|| Error::from(EM::EntryHeaderTypeError)) }; match *v { Value::Table(ref map) => { Ok(GPSValue::new( map.get("degree") .ok_or_else(|| anyhow!("Degree missing")) .and_then(&int_to_appropriate_width)?, map .get("minutes") .ok_or_else(|| anyhow!("Minutes missing")) .and_then(&int_to_appropriate_width)?, map .get("seconds") .ok_or_else(|| anyhow!("Seconds missing")) .and_then(&int_to_appropriate_width)? )) } _ => Err(Error::from(EM::EntryHeaderTypeError)) } } } impl Display for GPSValue { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "{}° {}\" {}'", self.degree, self.minutes, self.seconds) } } /// Data-transfer type for transfering longitude-latitude-pairs #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct Coordinates { pub longitude: GPSValue, pub latitude: GPSValue, } impl Coordinates { pub fn new(long: GPSValue, lat: GPSValue) -> Coordinates { Coordinates { longitude: long, latitude: lat, } } pub fn longitude(&self) -> &GPSValue { &self.longitude } pub fn latitude(&self) -> &GPSValue { &self.latitude } } impl Into<Value> for Coordinates { fn into(self) -> Value { let mut map = Map::new(); let _ = map.insert("longitude".to_owned(), self.longitude.into()); let _ = map.insert("latitude".to_owned(), self.latitude.into()); Value::Table(map) } } impl FromValue for Coordinates { fn from_value(v: &Value) -> Result<Self> { v.as_table() .ok_or_else(|| Error::from(EM::EntryHeaderTypeError)) .and_then(|t| { let get = |m: &Map<_, _>, what: &'static str, ek: &'static str| -> Result<GPSValue> { m.get(what) .ok_or_else(|| anyhow!(ek)) .and_then(GPSValue::from_value) }; Ok(Coordinates::new( get(t, "longitude", "Longitude missing")?, get(t, "latitude", "Latitude missing")? )) }) } } impl Display for Coordinates { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "longitude = {}\nlatitude = {}", self.longitude, self.latitude) } }
// Lesser General Public License for more details. //
random_line_split
types.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Result as FmtResult; use toml::Value; use toml::map::Map; use anyhow::Result; use anyhow::Error; use libimagerror::errors::Error as EM; pub trait FromValue : Sized { fn from_value(v: &Value) -> Result<Self>; } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct GPSValue { pub degree: i64, pub minutes: i64, pub seconds: i64, } impl GPSValue { pub fn new(d: i64, m: i64, s: i64) -> GPSValue { GPSValue { degree: d, minutes: m, seconds: s } } pub fn degree(&self) -> i64 { self.degree } pub fn minutes(&self) -> i64 { self.minutes } pub fn seconds(&self) -> i64 { self.seconds } } impl Into<Value> for GPSValue { fn into(self) -> Value { let mut map = Map::new(); let _ = map.insert("degree".to_owned(), Value::Integer(self.degree)); let _ = map.insert("minutes".to_owned(), Value::Integer(self.minutes)); let _ = map.insert("seconds".to_owned(), Value::Integer(self.seconds)); Value::Table(map) } } impl FromValue for GPSValue { fn from_value(v: &Value) -> Result<Self> { let int_to_appropriate_width = |v: &Value| { v.as_integer() .ok_or_else(|| Error::from(EM::EntryHeaderTypeError)) }; match *v { Value::Table(ref map) => { Ok(GPSValue::new( map.get("degree") .ok_or_else(|| anyhow!("Degree missing")) .and_then(&int_to_appropriate_width)?, map .get("minutes") .ok_or_else(|| anyhow!("Minutes missing")) .and_then(&int_to_appropriate_width)?, map .get("seconds") .ok_or_else(|| anyhow!("Seconds missing")) .and_then(&int_to_appropriate_width)? )) } _ => Err(Error::from(EM::EntryHeaderTypeError)) } } } impl Display for GPSValue { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "{}° {}\" {}'", self.degree, self.minutes, self.seconds) } } /// Data-transfer type for transfering longitude-latitude-pairs #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct Coordinates { pub longitude: GPSValue, pub latitude: GPSValue, } impl Coordinates { pub fn new(long: GPSValue, lat: GPSValue) -> Coordinates { Coordinates { longitude: long, latitude: lat, } } pub fn longitude(&self) -> &GPSValue { &self.longitude } pub fn latitude(&self) -> &GPSValue { &self.latitude } } impl Into<Value> for Coordinates { fn into(self) -> Value { let mut map = Map::new(); let _ = map.insert("longitude".to_owned(), self.longitude.into()); let _ = map.insert("latitude".to_owned(), self.latitude.into()); Value::Table(map) } } impl FromValue for Coordinates { fn from_value(v: &Value) -> Result<Self> { v.as_table() .ok_or_else(|| Error::from(EM::EntryHeaderTypeError)) .and_then(|t| { let get = |m: &Map<_, _>, what: &'static str, ek: &'static str| -> Result<GPSValue> { m.get(what) .ok_or_else(|| anyhow!(ek)) .and_then(GPSValue::from_value) }; Ok(Coordinates::new( get(t, "longitude", "Longitude missing")?, get(t, "latitude", "Latitude missing")? )) }) } } impl Display for Coordinates { fn fmt(&self, f: &mut Formatter) -> FmtResult {
}
write!(f, "longitude = {}\nlatitude = {}", self.longitude, self.latitude) }
identifier_body
imagedata.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::ImageDataBinding; use crate::dom::bindings::codegen::Bindings::ImageDataBinding::ImageDataMethods; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; use euclid::{Rect, Size2D}; use ipc_channel::ipc::IpcSharedMemory; use js::jsapi::{Heap, JSContext, JSObject}; use js::rust::Runtime; use js::typedarray::{CreateWith, Uint8ClampedArray}; use std::borrow::Cow; use std::default::Default; use std::ptr; use std::ptr::NonNull; use std::vec::Vec; #[dom_struct] pub struct ImageData { reflector_: Reflector, width: u32, height: u32, #[ignore_malloc_size_of = "mozjs"] data: Heap<*mut JSObject>, } impl ImageData { #[allow(unsafe_code)] pub fn new( global: &GlobalScope, width: u32, height: u32, mut data: Option<Vec<u8>>, ) -> Fallible<DomRoot<ImageData>> { let len = width * height * 4; unsafe { let cx = global.get_cx(); rooted!(in (cx) let mut js_object = ptr::null_mut::<JSObject>()); let data = match data { Some(ref mut d) => { d.resize(len as usize, 0); CreateWith::Slice(&d[..]) }, None => CreateWith::Length(len), }; Uint8ClampedArray::create(cx, data, js_object.handle_mut()).unwrap(); Self::new_with_jsobject(global, width, Some(height), Some(js_object.get())) } } #[allow(unsafe_code)] unsafe fn new_with_jsobject( global: &GlobalScope, width: u32, mut opt_height: Option<u32>, opt_jsobject: Option<*mut JSObject>, ) -> Fallible<DomRoot<ImageData>> { assert!(opt_jsobject.is_some() || opt_height.is_some()); if width == 0 { return Err(Error::IndexSize); } // checking jsobject type and verifying (height * width * 4 == jsobject.byte_len()) if let Some(jsobject) = opt_jsobject { let cx = global.get_cx(); typedarray!(in(cx) let array_res: Uint8ClampedArray = jsobject); let array = array_res.map_err(|_| { Error::Type("Argument to Image data is not an Uint8ClampedArray".to_owned()) })?; let byte_len = array.as_slice().len() as u32; if byte_len % 4!= 0 { return Err(Error::InvalidState); } let len = byte_len / 4; if width == 0 || len % width!= 0 { return Err(Error::IndexSize); } let height = len / width; if opt_height.map_or(false, |x| height!= x) { return Err(Error::IndexSize); } else { opt_height = Some(height); } } let height = opt_height.unwrap(); if height == 0 { return Err(Error::IndexSize); } let imagedata = Box::new(ImageData { reflector_: Reflector::new(), width: width, height: height, data: Heap::default(), }); if let Some(jsobject) = opt_jsobject { (*imagedata).data.set(jsobject); } else { let len = width * height * 4; let cx = global.get_cx(); rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); Uint8ClampedArray::create(cx, CreateWith::Length(len), array.handle_mut()).unwrap(); (*imagedata).data.set(array.get()); } Ok(reflect_dom_object( imagedata, global, ImageDataBinding::Wrap, )) } // https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-3 #[allow(unsafe_code)] pub fn Constructor(global: &GlobalScope, width: u32, height: u32) -> Fallible<DomRoot<Self>> { unsafe { Self::new_with_jsobject(global, width, Some(height), None) } } // https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-4 #[allow(unsafe_code)] #[allow(unused_variables)] pub unsafe fn Constructor_( cx: *mut JSContext, global: &GlobalScope, jsobject: *mut JSObject, width: u32, opt_height: Option<u32>, ) -> Fallible<DomRoot<Self>> { Self::new_with_jsobject(global, width, opt_height, Some(jsobject)) } /// Nothing must change the array on the JS side while the slice is live. #[allow(unsafe_code)] pub unsafe fn as_slice(&self) -> &[u8] { assert!(!self.data.get().is_null()); let cx = Runtime::get(); assert!(!cx.is_null()); typedarray!(in(cx) let array: Uint8ClampedArray = self.data.get()); let array = array.as_ref().unwrap(); // NOTE(nox): This is just as unsafe as `as_slice` itself even though we // are extending the lifetime of the slice, because the data in // this ImageData instance will never change. The method is thus unsafe // because the array may be manipulated from JS while the reference // is live. let ptr = array.as_slice() as *const _; &*ptr } #[allow(unsafe_code)] pub fn to_shared_memory(&self) -> IpcSharedMemory { IpcSharedMemory::from_bytes(unsafe { self.as_slice() }) } #[allow(unsafe_code)] pub unsafe fn get_rect(&self, rect: Rect<u32>) -> Cow<[u8]> { pixels::rgba8_get_rect(self.as_slice(), self.get_size(), rect) } pub fn get_size(&self) -> Size2D<u32> { Size2D::new(self.Width(), self.Height()) } } impl ImageDataMethods for ImageData { // https://html.spec.whatwg.org/multipage/#dom-imagedata-width fn Width(&self) -> u32
// https://html.spec.whatwg.org/multipage/#dom-imagedata-height fn Height(&self) -> u32 { self.height } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-imagedata-data unsafe fn Data(&self, _: *mut JSContext) -> NonNull<JSObject> { NonNull::new(self.data.get()).expect("got a null pointer") } }
{ self.width }
identifier_body
imagedata.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::ImageDataBinding; use crate::dom::bindings::codegen::Bindings::ImageDataBinding::ImageDataMethods; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; use euclid::{Rect, Size2D}; use ipc_channel::ipc::IpcSharedMemory; use js::jsapi::{Heap, JSContext, JSObject}; use js::rust::Runtime; use js::typedarray::{CreateWith, Uint8ClampedArray}; use std::borrow::Cow; use std::default::Default; use std::ptr; use std::ptr::NonNull; use std::vec::Vec; #[dom_struct] pub struct ImageData { reflector_: Reflector, width: u32, height: u32, #[ignore_malloc_size_of = "mozjs"] data: Heap<*mut JSObject>, } impl ImageData { #[allow(unsafe_code)] pub fn new( global: &GlobalScope, width: u32, height: u32, mut data: Option<Vec<u8>>, ) -> Fallible<DomRoot<ImageData>> { let len = width * height * 4; unsafe { let cx = global.get_cx(); rooted!(in (cx) let mut js_object = ptr::null_mut::<JSObject>()); let data = match data { Some(ref mut d) => { d.resize(len as usize, 0); CreateWith::Slice(&d[..]) }, None => CreateWith::Length(len), }; Uint8ClampedArray::create(cx, data, js_object.handle_mut()).unwrap(); Self::new_with_jsobject(global, width, Some(height), Some(js_object.get())) } } #[allow(unsafe_code)] unsafe fn new_with_jsobject( global: &GlobalScope, width: u32, mut opt_height: Option<u32>, opt_jsobject: Option<*mut JSObject>, ) -> Fallible<DomRoot<ImageData>> { assert!(opt_jsobject.is_some() || opt_height.is_some()); if width == 0 { return Err(Error::IndexSize); } // checking jsobject type and verifying (height * width * 4 == jsobject.byte_len()) if let Some(jsobject) = opt_jsobject
} else { opt_height = Some(height); } } let height = opt_height.unwrap(); if height == 0 { return Err(Error::IndexSize); } let imagedata = Box::new(ImageData { reflector_: Reflector::new(), width: width, height: height, data: Heap::default(), }); if let Some(jsobject) = opt_jsobject { (*imagedata).data.set(jsobject); } else { let len = width * height * 4; let cx = global.get_cx(); rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); Uint8ClampedArray::create(cx, CreateWith::Length(len), array.handle_mut()).unwrap(); (*imagedata).data.set(array.get()); } Ok(reflect_dom_object( imagedata, global, ImageDataBinding::Wrap, )) } // https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-3 #[allow(unsafe_code)] pub fn Constructor(global: &GlobalScope, width: u32, height: u32) -> Fallible<DomRoot<Self>> { unsafe { Self::new_with_jsobject(global, width, Some(height), None) } } // https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-4 #[allow(unsafe_code)] #[allow(unused_variables)] pub unsafe fn Constructor_( cx: *mut JSContext, global: &GlobalScope, jsobject: *mut JSObject, width: u32, opt_height: Option<u32>, ) -> Fallible<DomRoot<Self>> { Self::new_with_jsobject(global, width, opt_height, Some(jsobject)) } /// Nothing must change the array on the JS side while the slice is live. #[allow(unsafe_code)] pub unsafe fn as_slice(&self) -> &[u8] { assert!(!self.data.get().is_null()); let cx = Runtime::get(); assert!(!cx.is_null()); typedarray!(in(cx) let array: Uint8ClampedArray = self.data.get()); let array = array.as_ref().unwrap(); // NOTE(nox): This is just as unsafe as `as_slice` itself even though we // are extending the lifetime of the slice, because the data in // this ImageData instance will never change. The method is thus unsafe // because the array may be manipulated from JS while the reference // is live. let ptr = array.as_slice() as *const _; &*ptr } #[allow(unsafe_code)] pub fn to_shared_memory(&self) -> IpcSharedMemory { IpcSharedMemory::from_bytes(unsafe { self.as_slice() }) } #[allow(unsafe_code)] pub unsafe fn get_rect(&self, rect: Rect<u32>) -> Cow<[u8]> { pixels::rgba8_get_rect(self.as_slice(), self.get_size(), rect) } pub fn get_size(&self) -> Size2D<u32> { Size2D::new(self.Width(), self.Height()) } } impl ImageDataMethods for ImageData { // https://html.spec.whatwg.org/multipage/#dom-imagedata-width fn Width(&self) -> u32 { self.width } // https://html.spec.whatwg.org/multipage/#dom-imagedata-height fn Height(&self) -> u32 { self.height } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-imagedata-data unsafe fn Data(&self, _: *mut JSContext) -> NonNull<JSObject> { NonNull::new(self.data.get()).expect("got a null pointer") } }
{ let cx = global.get_cx(); typedarray!(in(cx) let array_res: Uint8ClampedArray = jsobject); let array = array_res.map_err(|_| { Error::Type("Argument to Image data is not an Uint8ClampedArray".to_owned()) })?; let byte_len = array.as_slice().len() as u32; if byte_len % 4 != 0 { return Err(Error::InvalidState); } let len = byte_len / 4; if width == 0 || len % width != 0 { return Err(Error::IndexSize); } let height = len / width; if opt_height.map_or(false, |x| height != x) { return Err(Error::IndexSize);
conditional_block
imagedata.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::ImageDataBinding; use crate::dom::bindings::codegen::Bindings::ImageDataBinding::ImageDataMethods; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; use euclid::{Rect, Size2D}; use ipc_channel::ipc::IpcSharedMemory; use js::jsapi::{Heap, JSContext, JSObject}; use js::rust::Runtime; use js::typedarray::{CreateWith, Uint8ClampedArray}; use std::borrow::Cow; use std::default::Default; use std::ptr; use std::ptr::NonNull; use std::vec::Vec; #[dom_struct] pub struct
{ reflector_: Reflector, width: u32, height: u32, #[ignore_malloc_size_of = "mozjs"] data: Heap<*mut JSObject>, } impl ImageData { #[allow(unsafe_code)] pub fn new( global: &GlobalScope, width: u32, height: u32, mut data: Option<Vec<u8>>, ) -> Fallible<DomRoot<ImageData>> { let len = width * height * 4; unsafe { let cx = global.get_cx(); rooted!(in (cx) let mut js_object = ptr::null_mut::<JSObject>()); let data = match data { Some(ref mut d) => { d.resize(len as usize, 0); CreateWith::Slice(&d[..]) }, None => CreateWith::Length(len), }; Uint8ClampedArray::create(cx, data, js_object.handle_mut()).unwrap(); Self::new_with_jsobject(global, width, Some(height), Some(js_object.get())) } } #[allow(unsafe_code)] unsafe fn new_with_jsobject( global: &GlobalScope, width: u32, mut opt_height: Option<u32>, opt_jsobject: Option<*mut JSObject>, ) -> Fallible<DomRoot<ImageData>> { assert!(opt_jsobject.is_some() || opt_height.is_some()); if width == 0 { return Err(Error::IndexSize); } // checking jsobject type and verifying (height * width * 4 == jsobject.byte_len()) if let Some(jsobject) = opt_jsobject { let cx = global.get_cx(); typedarray!(in(cx) let array_res: Uint8ClampedArray = jsobject); let array = array_res.map_err(|_| { Error::Type("Argument to Image data is not an Uint8ClampedArray".to_owned()) })?; let byte_len = array.as_slice().len() as u32; if byte_len % 4!= 0 { return Err(Error::InvalidState); } let len = byte_len / 4; if width == 0 || len % width!= 0 { return Err(Error::IndexSize); } let height = len / width; if opt_height.map_or(false, |x| height!= x) { return Err(Error::IndexSize); } else { opt_height = Some(height); } } let height = opt_height.unwrap(); if height == 0 { return Err(Error::IndexSize); } let imagedata = Box::new(ImageData { reflector_: Reflector::new(), width: width, height: height, data: Heap::default(), }); if let Some(jsobject) = opt_jsobject { (*imagedata).data.set(jsobject); } else { let len = width * height * 4; let cx = global.get_cx(); rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); Uint8ClampedArray::create(cx, CreateWith::Length(len), array.handle_mut()).unwrap(); (*imagedata).data.set(array.get()); } Ok(reflect_dom_object( imagedata, global, ImageDataBinding::Wrap, )) } // https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-3 #[allow(unsafe_code)] pub fn Constructor(global: &GlobalScope, width: u32, height: u32) -> Fallible<DomRoot<Self>> { unsafe { Self::new_with_jsobject(global, width, Some(height), None) } } // https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-4 #[allow(unsafe_code)] #[allow(unused_variables)] pub unsafe fn Constructor_( cx: *mut JSContext, global: &GlobalScope, jsobject: *mut JSObject, width: u32, opt_height: Option<u32>, ) -> Fallible<DomRoot<Self>> { Self::new_with_jsobject(global, width, opt_height, Some(jsobject)) } /// Nothing must change the array on the JS side while the slice is live. #[allow(unsafe_code)] pub unsafe fn as_slice(&self) -> &[u8] { assert!(!self.data.get().is_null()); let cx = Runtime::get(); assert!(!cx.is_null()); typedarray!(in(cx) let array: Uint8ClampedArray = self.data.get()); let array = array.as_ref().unwrap(); // NOTE(nox): This is just as unsafe as `as_slice` itself even though we // are extending the lifetime of the slice, because the data in // this ImageData instance will never change. The method is thus unsafe // because the array may be manipulated from JS while the reference // is live. let ptr = array.as_slice() as *const _; &*ptr } #[allow(unsafe_code)] pub fn to_shared_memory(&self) -> IpcSharedMemory { IpcSharedMemory::from_bytes(unsafe { self.as_slice() }) } #[allow(unsafe_code)] pub unsafe fn get_rect(&self, rect: Rect<u32>) -> Cow<[u8]> { pixels::rgba8_get_rect(self.as_slice(), self.get_size(), rect) } pub fn get_size(&self) -> Size2D<u32> { Size2D::new(self.Width(), self.Height()) } } impl ImageDataMethods for ImageData { // https://html.spec.whatwg.org/multipage/#dom-imagedata-width fn Width(&self) -> u32 { self.width } // https://html.spec.whatwg.org/multipage/#dom-imagedata-height fn Height(&self) -> u32 { self.height } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-imagedata-data unsafe fn Data(&self, _: *mut JSContext) -> NonNull<JSObject> { NonNull::new(self.data.get()).expect("got a null pointer") } }
ImageData
identifier_name
imagedata.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::ImageDataBinding; use crate::dom::bindings::codegen::Bindings::ImageDataBinding::ImageDataMethods; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; use euclid::{Rect, Size2D}; use ipc_channel::ipc::IpcSharedMemory; use js::jsapi::{Heap, JSContext, JSObject}; use js::rust::Runtime; use js::typedarray::{CreateWith, Uint8ClampedArray}; use std::borrow::Cow; use std::default::Default; use std::ptr; use std::ptr::NonNull; use std::vec::Vec; #[dom_struct] pub struct ImageData { reflector_: Reflector, width: u32, height: u32, #[ignore_malloc_size_of = "mozjs"] data: Heap<*mut JSObject>, } impl ImageData { #[allow(unsafe_code)] pub fn new( global: &GlobalScope, width: u32, height: u32, mut data: Option<Vec<u8>>, ) -> Fallible<DomRoot<ImageData>> { let len = width * height * 4; unsafe { let cx = global.get_cx(); rooted!(in (cx) let mut js_object = ptr::null_mut::<JSObject>()); let data = match data { Some(ref mut d) => { d.resize(len as usize, 0); CreateWith::Slice(&d[..]) }, None => CreateWith::Length(len), }; Uint8ClampedArray::create(cx, data, js_object.handle_mut()).unwrap(); Self::new_with_jsobject(global, width, Some(height), Some(js_object.get())) } } #[allow(unsafe_code)] unsafe fn new_with_jsobject( global: &GlobalScope, width: u32, mut opt_height: Option<u32>, opt_jsobject: Option<*mut JSObject>, ) -> Fallible<DomRoot<ImageData>> { assert!(opt_jsobject.is_some() || opt_height.is_some()); if width == 0 { return Err(Error::IndexSize); } // checking jsobject type and verifying (height * width * 4 == jsobject.byte_len()) if let Some(jsobject) = opt_jsobject { let cx = global.get_cx(); typedarray!(in(cx) let array_res: Uint8ClampedArray = jsobject); let array = array_res.map_err(|_| { Error::Type("Argument to Image data is not an Uint8ClampedArray".to_owned()) })?; let byte_len = array.as_slice().len() as u32; if byte_len % 4!= 0 { return Err(Error::InvalidState); } let len = byte_len / 4; if width == 0 || len % width!= 0 { return Err(Error::IndexSize); } let height = len / width; if opt_height.map_or(false, |x| height!= x) { return Err(Error::IndexSize); } else { opt_height = Some(height); } } let height = opt_height.unwrap(); if height == 0 { return Err(Error::IndexSize); } let imagedata = Box::new(ImageData { reflector_: Reflector::new(), width: width, height: height, data: Heap::default(), }); if let Some(jsobject) = opt_jsobject { (*imagedata).data.set(jsobject); } else { let len = width * height * 4; let cx = global.get_cx(); rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); Uint8ClampedArray::create(cx, CreateWith::Length(len), array.handle_mut()).unwrap(); (*imagedata).data.set(array.get()); } Ok(reflect_dom_object( imagedata, global, ImageDataBinding::Wrap, )) } // https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-3 #[allow(unsafe_code)] pub fn Constructor(global: &GlobalScope, width: u32, height: u32) -> Fallible<DomRoot<Self>> { unsafe { Self::new_with_jsobject(global, width, Some(height), None) } } // https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-4 #[allow(unsafe_code)] #[allow(unused_variables)] pub unsafe fn Constructor_( cx: *mut JSContext, global: &GlobalScope, jsobject: *mut JSObject, width: u32, opt_height: Option<u32>, ) -> Fallible<DomRoot<Self>> { Self::new_with_jsobject(global, width, opt_height, Some(jsobject)) }
assert!(!self.data.get().is_null()); let cx = Runtime::get(); assert!(!cx.is_null()); typedarray!(in(cx) let array: Uint8ClampedArray = self.data.get()); let array = array.as_ref().unwrap(); // NOTE(nox): This is just as unsafe as `as_slice` itself even though we // are extending the lifetime of the slice, because the data in // this ImageData instance will never change. The method is thus unsafe // because the array may be manipulated from JS while the reference // is live. let ptr = array.as_slice() as *const _; &*ptr } #[allow(unsafe_code)] pub fn to_shared_memory(&self) -> IpcSharedMemory { IpcSharedMemory::from_bytes(unsafe { self.as_slice() }) } #[allow(unsafe_code)] pub unsafe fn get_rect(&self, rect: Rect<u32>) -> Cow<[u8]> { pixels::rgba8_get_rect(self.as_slice(), self.get_size(), rect) } pub fn get_size(&self) -> Size2D<u32> { Size2D::new(self.Width(), self.Height()) } } impl ImageDataMethods for ImageData { // https://html.spec.whatwg.org/multipage/#dom-imagedata-width fn Width(&self) -> u32 { self.width } // https://html.spec.whatwg.org/multipage/#dom-imagedata-height fn Height(&self) -> u32 { self.height } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-imagedata-data unsafe fn Data(&self, _: *mut JSContext) -> NonNull<JSObject> { NonNull::new(self.data.get()).expect("got a null pointer") } }
/// Nothing must change the array on the JS side while the slice is live. #[allow(unsafe_code)] pub unsafe fn as_slice(&self) -> &[u8] {
random_line_split
lib.rs
use std::thread; #[no_mangle] pub extern fn process(){ let handles: Vec<_> = (0..10).map(|_| { thread::spawn(|| { let mut _x = 0; for _ in (0..10_000_001) { _x += 1 } }) }).collect(); for h in handles { h.join() .ok() .expect("could not join a thread."); } } #[no_mangle] pub extern fn fibonacci(x: i64) -> i64{ if x <= 2 { return 1; } else
} #[no_mangle] pub extern fn iterative_fibonacci(x: i64) -> i64{ if x <= 2 { return x } let mut fib_prev: i64 = 1; let mut fib: i64 = 1; for _num in (0..x) { let i: i64 = fib; fib = fib + fib_prev; fib_prev = i; } return fib; } #[test] fn process() { } #[test] fn fibonacci() { } #[test] fn iterative_fibonacci() { } // cargo build --release which builds with optimizations on. // We want this to be as fast as possible! // You can find the output of the library in target/release:
{ return fibonacci(x - 1) + fibonacci(x - 2); }
conditional_block
lib.rs
use std::thread; #[no_mangle] pub extern fn process(){ let handles: Vec<_> = (0..10).map(|_| { thread::spawn(|| { let mut _x = 0; for _ in (0..10_000_001) { _x += 1 } }) }).collect(); for h in handles { h.join() .ok() .expect("could not join a thread."); } } #[no_mangle] pub extern fn fibonacci(x: i64) -> i64{ if x <= 2 { return 1; } else { return fibonacci(x - 1) + fibonacci(x - 2); } } #[no_mangle] pub extern fn iterative_fibonacci(x: i64) -> i64{ if x <= 2 { return x } let mut fib_prev: i64 = 1;
fib = fib + fib_prev; fib_prev = i; } return fib; } #[test] fn process() { } #[test] fn fibonacci() { } #[test] fn iterative_fibonacci() { } // cargo build --release which builds with optimizations on. // We want this to be as fast as possible! // You can find the output of the library in target/release:
let mut fib: i64 = 1; for _num in (0..x) { let i: i64 = fib;
random_line_split
lib.rs
use std::thread; #[no_mangle] pub extern fn process(){ let handles: Vec<_> = (0..10).map(|_| { thread::spawn(|| { let mut _x = 0; for _ in (0..10_000_001) { _x += 1 } }) }).collect(); for h in handles { h.join() .ok() .expect("could not join a thread."); } } #[no_mangle] pub extern fn fibonacci(x: i64) -> i64
#[no_mangle] pub extern fn iterative_fibonacci(x: i64) -> i64{ if x <= 2 { return x } let mut fib_prev: i64 = 1; let mut fib: i64 = 1; for _num in (0..x) { let i: i64 = fib; fib = fib + fib_prev; fib_prev = i; } return fib; } #[test] fn process() { } #[test] fn fibonacci() { } #[test] fn iterative_fibonacci() { } // cargo build --release which builds with optimizations on. // We want this to be as fast as possible! // You can find the output of the library in target/release:
{ if x <= 2 { return 1; } else { return fibonacci(x - 1) + fibonacci(x - 2); } }
identifier_body
lib.rs
use std::thread; #[no_mangle] pub extern fn
(){ let handles: Vec<_> = (0..10).map(|_| { thread::spawn(|| { let mut _x = 0; for _ in (0..10_000_001) { _x += 1 } }) }).collect(); for h in handles { h.join() .ok() .expect("could not join a thread."); } } #[no_mangle] pub extern fn fibonacci(x: i64) -> i64{ if x <= 2 { return 1; } else { return fibonacci(x - 1) + fibonacci(x - 2); } } #[no_mangle] pub extern fn iterative_fibonacci(x: i64) -> i64{ if x <= 2 { return x } let mut fib_prev: i64 = 1; let mut fib: i64 = 1; for _num in (0..x) { let i: i64 = fib; fib = fib + fib_prev; fib_prev = i; } return fib; } #[test] fn process() { } #[test] fn fibonacci() { } #[test] fn iterative_fibonacci() { } // cargo build --release which builds with optimizations on. // We want this to be as fast as possible! // You can find the output of the library in target/release:
process
identifier_name
region.rs
use native; use rustrt::rtio; use rustrt::rtio::RtioFileStream; use std::cell::Cell; use std::os; use array::*; use chunk::{ BiomeId, BlockState, Chunk, ChunkColumn, EMPTY_CHUNK, LightLevel, SIZE }; use minecraft::nbt::Nbt; pub struct Region { mmap: os::MemoryMap } impl Region { pub fn open(filename: &Path) -> Region { let mut file = native::io::file::open( &filename.as_str().unwrap().to_c_str(), rtio::Open, rtio::Read ).ok().unwrap(); let min_len = file.fstat().ok().unwrap().size as uint; let options = [ os::MapFd(file.fd()), os::MapReadable ]; Region { mmap: os::MemoryMap::new(min_len, options).unwrap() } } fn as_slice<'a>(&'a self) -> &'a [u8] { use std::mem; use std::raw::Slice; let slice = Slice { data: self.mmap.data() as *const u8, len: self.mmap.len() }; unsafe { mem::transmute(slice) } } pub fn get_chunk_column(&self, x: u8, z: u8) -> Option<ChunkColumn> { let locations = self.as_slice().slice_to(4096); let i = 4 * ((x % 32) as uint + (z % 32) as uint * 32); let start = (locations[i] as uint << 16) | (locations[i + 1] as uint << 8) | locations[i + 2] as uint; let num = locations[i + 3] as uint; if start == 0 || num == 0 { return None; } let sectors = self.as_slice().slice(start * 4096, (start + num) * 4096); let len = (sectors[0] as uint << 24) | (sectors[1] as uint << 16) | (sectors[2] as uint << 8) | sectors[3] as uint; let nbt = match sectors[4] { 1 => Nbt::from_gzip(sectors.slice(5, 4 + len)), 2 => Nbt::from_zlib(sectors.slice(5, 4 + len)), c => panic!("unknown region chunk compression method {}", c) }; let mut c = nbt.unwrap().into_compound().unwrap(); let mut level = c.pop_equiv("Level").unwrap().into_compound().unwrap(); let mut chunks = Vec::new(); for chunk in level.pop_equiv("Sections") .unwrap().into_compound_list().unwrap().into_iter() { let y = chunk.find_equiv("Y") .unwrap().as_byte().unwrap(); let blocks = chunk.find_equiv("Blocks") .unwrap().as_bytearray().unwrap(); let blocks_top = chunk.find_equiv("Add") .and_then(|x| x.as_bytearray()); let blocks_data = chunk.find_equiv("Data") .unwrap().as_bytearray().unwrap(); let block_light = chunk.find_equiv("BlockLight") .unwrap().as_bytearray().unwrap(); let sky_light = chunk.find_equiv("SkyLight") .unwrap().as_bytearray().unwrap(); fn
<T>( f: |uint, uint, uint| -> T ) -> [[[T,..SIZE],..SIZE],..SIZE] { Array::from_fn(|y| -> [[T,..SIZE],..SIZE] Array::from_fn(|z| -> [T,..16] Array::from_fn(|x| f(x, y, z)) ) ) } let chunk = Chunk { blocks: array_16x16x16(|x, y, z| { let i = (y * SIZE + z) * SIZE + x; let top = match blocks_top { Some(blocks_top) => { (blocks_top[i >> 1] >> ((i & 1) * 4)) & 0x0f } None => 0 }; let data = (blocks_data[i >> 1] >> ((i & 1) * 4)) & 0x0f; BlockState { value: (blocks[i] as u16 << 4) | (top as u16 << 12) | (data as u16) } }), light_levels: array_16x16x16(|x, y, z| { let i = (y * 16 + z) * 16 + x; let block = (block_light[i >> 1] >> ((i & 1) * 4)) & 0x0f; let sky = (sky_light[i >> 1] >> ((i & 1) * 4)) & 0x0f; LightLevel { value: block | (sky << 4) } }), }; let len = chunks.len(); if y as uint >= len { chunks.grow(y as uint - len + 1, *EMPTY_CHUNK); } chunks[y as uint] = chunk; } let biomes = level.find_equiv("Biomes") .unwrap().as_bytearray().unwrap(); Some(ChunkColumn { chunks: chunks, buffers: Array::from_fn(|_| Cell::new(None)), biomes: Array::from_fn(|z| -> [BiomeId,..SIZE] Array::from_fn(|x| { BiomeId { value: biomes[z * SIZE + x] } })) }) } }
array_16x16x16
identifier_name
region.rs
use native; use rustrt::rtio; use rustrt::rtio::RtioFileStream; use std::cell::Cell; use std::os; use array::*; use chunk::{ BiomeId, BlockState, Chunk, ChunkColumn, EMPTY_CHUNK, LightLevel, SIZE }; use minecraft::nbt::Nbt; pub struct Region { mmap: os::MemoryMap } impl Region { pub fn open(filename: &Path) -> Region { let mut file = native::io::file::open( &filename.as_str().unwrap().to_c_str(), rtio::Open, rtio::Read ).ok().unwrap(); let min_len = file.fstat().ok().unwrap().size as uint; let options = [ os::MapFd(file.fd()), os::MapReadable ]; Region { mmap: os::MemoryMap::new(min_len, options).unwrap() } } fn as_slice<'a>(&'a self) -> &'a [u8] { use std::mem; use std::raw::Slice; let slice = Slice { data: self.mmap.data() as *const u8, len: self.mmap.len() }; unsafe { mem::transmute(slice) } } pub fn get_chunk_column(&self, x: u8, z: u8) -> Option<ChunkColumn> { let locations = self.as_slice().slice_to(4096); let i = 4 * ((x % 32) as uint + (z % 32) as uint * 32); let start = (locations[i] as uint << 16) | (locations[i + 1] as uint << 8) | locations[i + 2] as uint; let num = locations[i + 3] as uint; if start == 0 || num == 0 { return None; } let sectors = self.as_slice().slice(start * 4096, (start + num) * 4096); let len = (sectors[0] as uint << 24) | (sectors[1] as uint << 16) | (sectors[2] as uint << 8) | sectors[3] as uint; let nbt = match sectors[4] { 1 => Nbt::from_gzip(sectors.slice(5, 4 + len)), 2 => Nbt::from_zlib(sectors.slice(5, 4 + len)), c => panic!("unknown region chunk compression method {}", c) }; let mut c = nbt.unwrap().into_compound().unwrap(); let mut level = c.pop_equiv("Level").unwrap().into_compound().unwrap(); let mut chunks = Vec::new(); for chunk in level.pop_equiv("Sections") .unwrap().into_compound_list().unwrap().into_iter() { let y = chunk.find_equiv("Y") .unwrap().as_byte().unwrap(); let blocks = chunk.find_equiv("Blocks") .unwrap().as_bytearray().unwrap(); let blocks_top = chunk.find_equiv("Add") .and_then(|x| x.as_bytearray()); let blocks_data = chunk.find_equiv("Data") .unwrap().as_bytearray().unwrap(); let block_light = chunk.find_equiv("BlockLight") .unwrap().as_bytearray().unwrap(); let sky_light = chunk.find_equiv("SkyLight") .unwrap().as_bytearray().unwrap(); fn array_16x16x16<T>( f: |uint, uint, uint| -> T ) -> [[[T,..SIZE],..SIZE],..SIZE] { Array::from_fn(|y| -> [[T,..SIZE],..SIZE] Array::from_fn(|z| -> [T,..16] Array::from_fn(|x| f(x, y, z)) ) ) }
blocks: array_16x16x16(|x, y, z| { let i = (y * SIZE + z) * SIZE + x; let top = match blocks_top { Some(blocks_top) => { (blocks_top[i >> 1] >> ((i & 1) * 4)) & 0x0f } None => 0 }; let data = (blocks_data[i >> 1] >> ((i & 1) * 4)) & 0x0f; BlockState { value: (blocks[i] as u16 << 4) | (top as u16 << 12) | (data as u16) } }), light_levels: array_16x16x16(|x, y, z| { let i = (y * 16 + z) * 16 + x; let block = (block_light[i >> 1] >> ((i & 1) * 4)) & 0x0f; let sky = (sky_light[i >> 1] >> ((i & 1) * 4)) & 0x0f; LightLevel { value: block | (sky << 4) } }), }; let len = chunks.len(); if y as uint >= len { chunks.grow(y as uint - len + 1, *EMPTY_CHUNK); } chunks[y as uint] = chunk; } let biomes = level.find_equiv("Biomes") .unwrap().as_bytearray().unwrap(); Some(ChunkColumn { chunks: chunks, buffers: Array::from_fn(|_| Cell::new(None)), biomes: Array::from_fn(|z| -> [BiomeId,..SIZE] Array::from_fn(|x| { BiomeId { value: biomes[z * SIZE + x] } })) }) } }
let chunk = Chunk {
random_line_split
region.rs
use native; use rustrt::rtio; use rustrt::rtio::RtioFileStream; use std::cell::Cell; use std::os; use array::*; use chunk::{ BiomeId, BlockState, Chunk, ChunkColumn, EMPTY_CHUNK, LightLevel, SIZE }; use minecraft::nbt::Nbt; pub struct Region { mmap: os::MemoryMap } impl Region { pub fn open(filename: &Path) -> Region { let mut file = native::io::file::open( &filename.as_str().unwrap().to_c_str(), rtio::Open, rtio::Read ).ok().unwrap(); let min_len = file.fstat().ok().unwrap().size as uint; let options = [ os::MapFd(file.fd()), os::MapReadable ]; Region { mmap: os::MemoryMap::new(min_len, options).unwrap() } } fn as_slice<'a>(&'a self) -> &'a [u8]
pub fn get_chunk_column(&self, x: u8, z: u8) -> Option<ChunkColumn> { let locations = self.as_slice().slice_to(4096); let i = 4 * ((x % 32) as uint + (z % 32) as uint * 32); let start = (locations[i] as uint << 16) | (locations[i + 1] as uint << 8) | locations[i + 2] as uint; let num = locations[i + 3] as uint; if start == 0 || num == 0 { return None; } let sectors = self.as_slice().slice(start * 4096, (start + num) * 4096); let len = (sectors[0] as uint << 24) | (sectors[1] as uint << 16) | (sectors[2] as uint << 8) | sectors[3] as uint; let nbt = match sectors[4] { 1 => Nbt::from_gzip(sectors.slice(5, 4 + len)), 2 => Nbt::from_zlib(sectors.slice(5, 4 + len)), c => panic!("unknown region chunk compression method {}", c) }; let mut c = nbt.unwrap().into_compound().unwrap(); let mut level = c.pop_equiv("Level").unwrap().into_compound().unwrap(); let mut chunks = Vec::new(); for chunk in level.pop_equiv("Sections") .unwrap().into_compound_list().unwrap().into_iter() { let y = chunk.find_equiv("Y") .unwrap().as_byte().unwrap(); let blocks = chunk.find_equiv("Blocks") .unwrap().as_bytearray().unwrap(); let blocks_top = chunk.find_equiv("Add") .and_then(|x| x.as_bytearray()); let blocks_data = chunk.find_equiv("Data") .unwrap().as_bytearray().unwrap(); let block_light = chunk.find_equiv("BlockLight") .unwrap().as_bytearray().unwrap(); let sky_light = chunk.find_equiv("SkyLight") .unwrap().as_bytearray().unwrap(); fn array_16x16x16<T>( f: |uint, uint, uint| -> T ) -> [[[T,..SIZE],..SIZE],..SIZE] { Array::from_fn(|y| -> [[T,..SIZE],..SIZE] Array::from_fn(|z| -> [T,..16] Array::from_fn(|x| f(x, y, z)) ) ) } let chunk = Chunk { blocks: array_16x16x16(|x, y, z| { let i = (y * SIZE + z) * SIZE + x; let top = match blocks_top { Some(blocks_top) => { (blocks_top[i >> 1] >> ((i & 1) * 4)) & 0x0f } None => 0 }; let data = (blocks_data[i >> 1] >> ((i & 1) * 4)) & 0x0f; BlockState { value: (blocks[i] as u16 << 4) | (top as u16 << 12) | (data as u16) } }), light_levels: array_16x16x16(|x, y, z| { let i = (y * 16 + z) * 16 + x; let block = (block_light[i >> 1] >> ((i & 1) * 4)) & 0x0f; let sky = (sky_light[i >> 1] >> ((i & 1) * 4)) & 0x0f; LightLevel { value: block | (sky << 4) } }), }; let len = chunks.len(); if y as uint >= len { chunks.grow(y as uint - len + 1, *EMPTY_CHUNK); } chunks[y as uint] = chunk; } let biomes = level.find_equiv("Biomes") .unwrap().as_bytearray().unwrap(); Some(ChunkColumn { chunks: chunks, buffers: Array::from_fn(|_| Cell::new(None)), biomes: Array::from_fn(|z| -> [BiomeId,..SIZE] Array::from_fn(|x| { BiomeId { value: biomes[z * SIZE + x] } })) }) } }
{ use std::mem; use std::raw::Slice; let slice = Slice { data: self.mmap.data() as *const u8, len: self.mmap.len() }; unsafe { mem::transmute(slice) } }
identifier_body
lib.rs
//! A fast, low-level IO library for Rust focusing on non-blocking APIs, event //! notification, and other useful utilities for building high performance IO //! apps. //! //! # Goals //! //! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...) //! * Zero allocations //! * A scalable readiness-based API, similar to epoll on Linux //! * Design to allow for stack allocated buffers when possible (avoid double buffering). //! * Provide utilities such as a timers, a notification channel, buffer abstractions, and a slab. //! //! # Usage //! //! Using mio starts by creating an [Poll](struct.Poll.html), which reads events from the OS and //! put them into [Events](struct.Events.html). You can handle IO events from the OS with it. //! //! # Example //! //! ``` //! use mio::*; //! use mio::tcp::{TcpListener, TcpStream}; //! //! // Setup some tokens to allow us to identify which event is //! // for which socket. //! const SERVER: Token = Token(0); //! const CLIENT: Token = Token(1); //! //! let addr = "127.0.0.1:13265".parse().unwrap(); //! //! // Setup the server socket //! let server = TcpListener::bind(&addr).unwrap(); //! //! // Create an poll instance //! let poll = Poll::new().unwrap(); //! //! // Start listening for incoming connections //! poll.register(&server, SERVER, Ready::readable(), //! PollOpt::edge()).unwrap(); //! //! // Setup the client socket //! let sock = TcpStream::connect(&addr).unwrap(); //! //! // Register the socket //! poll.register(&sock, CLIENT, Ready::readable(), //! PollOpt::edge()).unwrap(); //! //! // Create storage for events //! let mut events = Events::with_capacity(1024); //! //! loop { //! poll.poll(&mut events, None).unwrap(); //! //! for event in events.iter() { //! match event.token() { //! SERVER => { //! // Accept and drop the socket immediately, this will close //! // the socket and notify the client of the EOF. //! let _ = server.accept(); //! } //! CLIENT => { //! // The server just shuts down the socket, let's just exit //! // from our event loop. //! return; //! } //! _ => unreachable!(), //! } //! } //! } //! //! ``` #![doc(html_root_url = "https://docs.rs/mio/0.6.1")] #![crate_name = "mio"] #![cfg_attr(unix, deny(warnings))] extern crate lazycell; extern crate net2; extern crate slab; #[cfg(unix)] extern crate libc; #[cfg(windows)] extern crate miow; #[cfg(windows)] extern crate winapi; #[cfg(windows)] extern crate kernel32; #[macro_use] extern crate log; #[cfg(test)] extern crate env_logger; mod event; mod io; mod iovec; mod net; mod poll; mod sys; mod token; pub mod channel; pub mod timer; /// EventLoop and other deprecated types pub mod deprecated; pub use event::{ PollOpt, Ready, Event, }; pub use io::{ Evented, would_block, }; pub use iovec::IoVec; pub use net::{ tcp, udp, }; pub use poll::{ Poll, Events, EventsIter, Registration, SetReadiness, }; pub use token::{ Token, }; #[cfg(unix)] pub mod unix { //! Unix only extensions pub use sys::{ EventedFd, }; } /// Windows-only extensions to the mio crate. /// /// Mio on windows is currently implemented with IOCP for a high-performance /// implementation of asynchronous I/O. Mio then provides TCP and UDP as sample /// bindings for the system to connect networking types to asynchronous I/O. On /// Unix this scheme is then also extensible to all other file descriptors with /// the `EventedFd` type, but on Windows no such analog is available. The /// purpose of this module, however, is to similarly provide a mechanism for /// foreign I/O types to get hooked up into the IOCP event loop. /// /// This module provides two types for interfacing with a custom IOCP handle: /// /// * `Binding` - this type is intended to govern binding with mio's `Poll` /// type. Each I/O object should contain an instance of `Binding` that's /// interfaced with for the implementation of the `Evented` trait. The /// `register`, `reregister`, and `deregister` methods for the `Evented` trait /// all have rough analogs with `Binding`. /// /// Note that this type **does not handle readiness**. That is, this type does /// not handle whether sockets are readable/writable/etc. It's intended that /// IOCP types will internally manage this state with a `SetReadiness` type /// from the `poll` module. The `SetReadiness` is typically lazily created on /// the first time that `Evented::register` is called and then stored in the /// I/O object. /// /// Also note that for types which represent streams of bytes the mio /// interface of *readiness* doesn't map directly to the Windows model of /// *completion*. This means that types will have to perform internal /// buffering to ensure that a readiness interface can be provided. For a /// sample implementation see the TCP/UDP modules in mio itself. /// /// * `Overlapped` - this type is intended to be used as the concreate instances /// of the `OVERLAPPED` type that most win32 methods expect. It's crucial, for /// safety, that all asynchronous operations are initiated with an instance of /// `Overlapped` and not another instantiation of `OVERLAPPED`. /// /// Mio's `Overlapped` type is created with a function pointer that receives /// a `OVERLAPPED_ENTRY` type when called. This `OVERLAPPED_ENTRY` type is /// defined in the `winapi` crate. Whenever a completion is posted to an IOCP /// object the `OVERLAPPED` that was signaled will be interpreted as /// `Overlapped` in the mio crate and this function pointer will be invoked. /// Through this function pointer, and through the `OVERLAPPED` pointer, /// implementations can handle management of I/O events. /// /// When put together these two types enable custom Windows handles to be /// registered with mio's event loops. The `Binding` type is used to associate /// handles and the `Overlapped` type is used to execute I/O operations. When /// the I/O operations are completed a custom function pointer is called which /// typically modifies a `SetReadiness` set by `Evented` methods which will get /// later hooked into the mio event loop. #[cfg(windows)] pub mod windows { pub use sys::{Overlapped, Binding}; } // Conversion utilities mod convert { use std::time::Duration; const NANOS_PER_MILLI: u32 = 1_000_000; const MILLIS_PER_SEC: u64 = 1_000; /// Convert a `Duration` to milliseconds, rounding up and saturating at /// `u64::MAX`. /// /// The saturating is fine because `u64::MAX` milliseconds are still many /// million years. pub fn
(duration: Duration) -> u64 { // Round up. let millis = (duration.subsec_nanos() + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI; duration.as_secs().saturating_mul(MILLIS_PER_SEC).saturating_add(millis as u64) } }
millis
identifier_name
lib.rs
//! A fast, low-level IO library for Rust focusing on non-blocking APIs, event //! notification, and other useful utilities for building high performance IO //! apps. //! //! # Goals //! //! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...) //! * Zero allocations //! * A scalable readiness-based API, similar to epoll on Linux //! * Design to allow for stack allocated buffers when possible (avoid double buffering). //! * Provide utilities such as a timers, a notification channel, buffer abstractions, and a slab. //! //! # Usage //! //! Using mio starts by creating an [Poll](struct.Poll.html), which reads events from the OS and //! put them into [Events](struct.Events.html). You can handle IO events from the OS with it. //! //! # Example //! //! ``` //! use mio::*; //! use mio::tcp::{TcpListener, TcpStream}; //! //! // Setup some tokens to allow us to identify which event is //! // for which socket. //! const SERVER: Token = Token(0); //! const CLIENT: Token = Token(1); //! //! let addr = "127.0.0.1:13265".parse().unwrap(); //! //! // Setup the server socket //! let server = TcpListener::bind(&addr).unwrap(); //! //! // Create an poll instance //! let poll = Poll::new().unwrap(); //! //! // Start listening for incoming connections //! poll.register(&server, SERVER, Ready::readable(), //! PollOpt::edge()).unwrap(); //! //! // Setup the client socket //! let sock = TcpStream::connect(&addr).unwrap(); //! //! // Register the socket //! poll.register(&sock, CLIENT, Ready::readable(), //! PollOpt::edge()).unwrap(); //! //! // Create storage for events //! let mut events = Events::with_capacity(1024); //! //! loop { //! poll.poll(&mut events, None).unwrap(); //! //! for event in events.iter() { //! match event.token() { //! SERVER => { //! // Accept and drop the socket immediately, this will close //! // the socket and notify the client of the EOF. //! let _ = server.accept(); //! } //! CLIENT => {
//! _ => unreachable!(), //! } //! } //! } //! //! ``` #![doc(html_root_url = "https://docs.rs/mio/0.6.1")] #![crate_name = "mio"] #![cfg_attr(unix, deny(warnings))] extern crate lazycell; extern crate net2; extern crate slab; #[cfg(unix)] extern crate libc; #[cfg(windows)] extern crate miow; #[cfg(windows)] extern crate winapi; #[cfg(windows)] extern crate kernel32; #[macro_use] extern crate log; #[cfg(test)] extern crate env_logger; mod event; mod io; mod iovec; mod net; mod poll; mod sys; mod token; pub mod channel; pub mod timer; /// EventLoop and other deprecated types pub mod deprecated; pub use event::{ PollOpt, Ready, Event, }; pub use io::{ Evented, would_block, }; pub use iovec::IoVec; pub use net::{ tcp, udp, }; pub use poll::{ Poll, Events, EventsIter, Registration, SetReadiness, }; pub use token::{ Token, }; #[cfg(unix)] pub mod unix { //! Unix only extensions pub use sys::{ EventedFd, }; } /// Windows-only extensions to the mio crate. /// /// Mio on windows is currently implemented with IOCP for a high-performance /// implementation of asynchronous I/O. Mio then provides TCP and UDP as sample /// bindings for the system to connect networking types to asynchronous I/O. On /// Unix this scheme is then also extensible to all other file descriptors with /// the `EventedFd` type, but on Windows no such analog is available. The /// purpose of this module, however, is to similarly provide a mechanism for /// foreign I/O types to get hooked up into the IOCP event loop. /// /// This module provides two types for interfacing with a custom IOCP handle: /// /// * `Binding` - this type is intended to govern binding with mio's `Poll` /// type. Each I/O object should contain an instance of `Binding` that's /// interfaced with for the implementation of the `Evented` trait. The /// `register`, `reregister`, and `deregister` methods for the `Evented` trait /// all have rough analogs with `Binding`. /// /// Note that this type **does not handle readiness**. That is, this type does /// not handle whether sockets are readable/writable/etc. It's intended that /// IOCP types will internally manage this state with a `SetReadiness` type /// from the `poll` module. The `SetReadiness` is typically lazily created on /// the first time that `Evented::register` is called and then stored in the /// I/O object. /// /// Also note that for types which represent streams of bytes the mio /// interface of *readiness* doesn't map directly to the Windows model of /// *completion*. This means that types will have to perform internal /// buffering to ensure that a readiness interface can be provided. For a /// sample implementation see the TCP/UDP modules in mio itself. /// /// * `Overlapped` - this type is intended to be used as the concreate instances /// of the `OVERLAPPED` type that most win32 methods expect. It's crucial, for /// safety, that all asynchronous operations are initiated with an instance of /// `Overlapped` and not another instantiation of `OVERLAPPED`. /// /// Mio's `Overlapped` type is created with a function pointer that receives /// a `OVERLAPPED_ENTRY` type when called. This `OVERLAPPED_ENTRY` type is /// defined in the `winapi` crate. Whenever a completion is posted to an IOCP /// object the `OVERLAPPED` that was signaled will be interpreted as /// `Overlapped` in the mio crate and this function pointer will be invoked. /// Through this function pointer, and through the `OVERLAPPED` pointer, /// implementations can handle management of I/O events. /// /// When put together these two types enable custom Windows handles to be /// registered with mio's event loops. The `Binding` type is used to associate /// handles and the `Overlapped` type is used to execute I/O operations. When /// the I/O operations are completed a custom function pointer is called which /// typically modifies a `SetReadiness` set by `Evented` methods which will get /// later hooked into the mio event loop. #[cfg(windows)] pub mod windows { pub use sys::{Overlapped, Binding}; } // Conversion utilities mod convert { use std::time::Duration; const NANOS_PER_MILLI: u32 = 1_000_000; const MILLIS_PER_SEC: u64 = 1_000; /// Convert a `Duration` to milliseconds, rounding up and saturating at /// `u64::MAX`. /// /// The saturating is fine because `u64::MAX` milliseconds are still many /// million years. pub fn millis(duration: Duration) -> u64 { // Round up. let millis = (duration.subsec_nanos() + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI; duration.as_secs().saturating_mul(MILLIS_PER_SEC).saturating_add(millis as u64) } }
//! // The server just shuts down the socket, let's just exit //! // from our event loop. //! return; //! }
random_line_split
lib.rs
//! A fast, low-level IO library for Rust focusing on non-blocking APIs, event //! notification, and other useful utilities for building high performance IO //! apps. //! //! # Goals //! //! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...) //! * Zero allocations //! * A scalable readiness-based API, similar to epoll on Linux //! * Design to allow for stack allocated buffers when possible (avoid double buffering). //! * Provide utilities such as a timers, a notification channel, buffer abstractions, and a slab. //! //! # Usage //! //! Using mio starts by creating an [Poll](struct.Poll.html), which reads events from the OS and //! put them into [Events](struct.Events.html). You can handle IO events from the OS with it. //! //! # Example //! //! ``` //! use mio::*; //! use mio::tcp::{TcpListener, TcpStream}; //! //! // Setup some tokens to allow us to identify which event is //! // for which socket. //! const SERVER: Token = Token(0); //! const CLIENT: Token = Token(1); //! //! let addr = "127.0.0.1:13265".parse().unwrap(); //! //! // Setup the server socket //! let server = TcpListener::bind(&addr).unwrap(); //! //! // Create an poll instance //! let poll = Poll::new().unwrap(); //! //! // Start listening for incoming connections //! poll.register(&server, SERVER, Ready::readable(), //! PollOpt::edge()).unwrap(); //! //! // Setup the client socket //! let sock = TcpStream::connect(&addr).unwrap(); //! //! // Register the socket //! poll.register(&sock, CLIENT, Ready::readable(), //! PollOpt::edge()).unwrap(); //! //! // Create storage for events //! let mut events = Events::with_capacity(1024); //! //! loop { //! poll.poll(&mut events, None).unwrap(); //! //! for event in events.iter() { //! match event.token() { //! SERVER => { //! // Accept and drop the socket immediately, this will close //! // the socket and notify the client of the EOF. //! let _ = server.accept(); //! } //! CLIENT => { //! // The server just shuts down the socket, let's just exit //! // from our event loop. //! return; //! } //! _ => unreachable!(), //! } //! } //! } //! //! ``` #![doc(html_root_url = "https://docs.rs/mio/0.6.1")] #![crate_name = "mio"] #![cfg_attr(unix, deny(warnings))] extern crate lazycell; extern crate net2; extern crate slab; #[cfg(unix)] extern crate libc; #[cfg(windows)] extern crate miow; #[cfg(windows)] extern crate winapi; #[cfg(windows)] extern crate kernel32; #[macro_use] extern crate log; #[cfg(test)] extern crate env_logger; mod event; mod io; mod iovec; mod net; mod poll; mod sys; mod token; pub mod channel; pub mod timer; /// EventLoop and other deprecated types pub mod deprecated; pub use event::{ PollOpt, Ready, Event, }; pub use io::{ Evented, would_block, }; pub use iovec::IoVec; pub use net::{ tcp, udp, }; pub use poll::{ Poll, Events, EventsIter, Registration, SetReadiness, }; pub use token::{ Token, }; #[cfg(unix)] pub mod unix { //! Unix only extensions pub use sys::{ EventedFd, }; } /// Windows-only extensions to the mio crate. /// /// Mio on windows is currently implemented with IOCP for a high-performance /// implementation of asynchronous I/O. Mio then provides TCP and UDP as sample /// bindings for the system to connect networking types to asynchronous I/O. On /// Unix this scheme is then also extensible to all other file descriptors with /// the `EventedFd` type, but on Windows no such analog is available. The /// purpose of this module, however, is to similarly provide a mechanism for /// foreign I/O types to get hooked up into the IOCP event loop. /// /// This module provides two types for interfacing with a custom IOCP handle: /// /// * `Binding` - this type is intended to govern binding with mio's `Poll` /// type. Each I/O object should contain an instance of `Binding` that's /// interfaced with for the implementation of the `Evented` trait. The /// `register`, `reregister`, and `deregister` methods for the `Evented` trait /// all have rough analogs with `Binding`. /// /// Note that this type **does not handle readiness**. That is, this type does /// not handle whether sockets are readable/writable/etc. It's intended that /// IOCP types will internally manage this state with a `SetReadiness` type /// from the `poll` module. The `SetReadiness` is typically lazily created on /// the first time that `Evented::register` is called and then stored in the /// I/O object. /// /// Also note that for types which represent streams of bytes the mio /// interface of *readiness* doesn't map directly to the Windows model of /// *completion*. This means that types will have to perform internal /// buffering to ensure that a readiness interface can be provided. For a /// sample implementation see the TCP/UDP modules in mio itself. /// /// * `Overlapped` - this type is intended to be used as the concreate instances /// of the `OVERLAPPED` type that most win32 methods expect. It's crucial, for /// safety, that all asynchronous operations are initiated with an instance of /// `Overlapped` and not another instantiation of `OVERLAPPED`. /// /// Mio's `Overlapped` type is created with a function pointer that receives /// a `OVERLAPPED_ENTRY` type when called. This `OVERLAPPED_ENTRY` type is /// defined in the `winapi` crate. Whenever a completion is posted to an IOCP /// object the `OVERLAPPED` that was signaled will be interpreted as /// `Overlapped` in the mio crate and this function pointer will be invoked. /// Through this function pointer, and through the `OVERLAPPED` pointer, /// implementations can handle management of I/O events. /// /// When put together these two types enable custom Windows handles to be /// registered with mio's event loops. The `Binding` type is used to associate /// handles and the `Overlapped` type is used to execute I/O operations. When /// the I/O operations are completed a custom function pointer is called which /// typically modifies a `SetReadiness` set by `Evented` methods which will get /// later hooked into the mio event loop. #[cfg(windows)] pub mod windows { pub use sys::{Overlapped, Binding}; } // Conversion utilities mod convert { use std::time::Duration; const NANOS_PER_MILLI: u32 = 1_000_000; const MILLIS_PER_SEC: u64 = 1_000; /// Convert a `Duration` to milliseconds, rounding up and saturating at /// `u64::MAX`. /// /// The saturating is fine because `u64::MAX` milliseconds are still many /// million years. pub fn millis(duration: Duration) -> u64
}
{ // Round up. let millis = (duration.subsec_nanos() + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI; duration.as_secs().saturating_mul(MILLIS_PER_SEC).saturating_add(millis as u64) }
identifier_body
create-role.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_iam::{Client, Error, Region, PKG_VERSION}; use std::fs; use structopt::StructOpt; #[derive(Debug, StructOpt)] struct Opt { /// The AWS Region. #[structopt(short, long)] region: Option<String>, /// The name of the role. #[structopt(short, long)] name: String,
/// Whether to display additional information. #[structopt(short, long)] verbose: bool, } // Creates a role. // snippet-start:[iam.rust.create-role] async fn make_role(client: &Client, policy_file: &str, name: &str) -> Result<(), Error> { // Read policy doc from file as a string let doc = fs::read_to_string(policy_file).expect("Unable to read file"); let resp = client .create_role() .assume_role_policy_document(doc) .role_name(name) .send() .await?; println!( "Created role with ARN {}", resp.role().unwrap().arn().unwrap() ); Ok(()) } // snippet-end:[iam.rust.create-role] /// Creates an IAM role in the Region. /// /// # Arguments /// /// * `-a ACCOUNT-ID` - Your account ID. /// * `-b BUCKET` - The name of the bucket where Config stores information about resources. /// * `-n NAME` - The name of the role. /// * `-p POLICY-NAME` - The name of the JSON file containing the policy document. /// * `[-r REGION]` - The Region in which the client is created. /// If not supplied, uses the value of the **AWS_REGION** environment variable. /// If the environment variable is not set, defaults to **us-west-2**. /// * `[-v]` - Whether to display information. #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt::init(); let Opt { name, policy_file, region, verbose, } = Opt::from_args(); let region_provider = RegionProviderChain::first_try(region.map(Region::new)) .or_default_provider() .or_else(Region::new("us-west-2")); println!(); if verbose { println!("IAM client version: {}", PKG_VERSION); println!( "Region: {}", region_provider.region().await.unwrap().as_ref() ); println!("Role name: {}", &name); println!("Policy doc filename {}", &policy_file); println!(); } let shared_config = aws_config::from_env().region(region_provider).load().await; let client = Client::new(&shared_config); make_role(&client, &policy_file, &name).await }
/// The name of the file containing the policy document. #[structopt(short, long)] policy_file: String,
random_line_split
create-role.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_iam::{Client, Error, Region, PKG_VERSION}; use std::fs; use structopt::StructOpt; #[derive(Debug, StructOpt)] struct Opt { /// The AWS Region. #[structopt(short, long)] region: Option<String>, /// The name of the role. #[structopt(short, long)] name: String, /// The name of the file containing the policy document. #[structopt(short, long)] policy_file: String, /// Whether to display additional information. #[structopt(short, long)] verbose: bool, } // Creates a role. // snippet-start:[iam.rust.create-role] async fn make_role(client: &Client, policy_file: &str, name: &str) -> Result<(), Error>
// snippet-end:[iam.rust.create-role] /// Creates an IAM role in the Region. /// /// # Arguments /// /// * `-a ACCOUNT-ID` - Your account ID. /// * `-b BUCKET` - The name of the bucket where Config stores information about resources. /// * `-n NAME` - The name of the role. /// * `-p POLICY-NAME` - The name of the JSON file containing the policy document. /// * `[-r REGION]` - The Region in which the client is created. /// If not supplied, uses the value of the **AWS_REGION** environment variable. /// If the environment variable is not set, defaults to **us-west-2**. /// * `[-v]` - Whether to display information. #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt::init(); let Opt { name, policy_file, region, verbose, } = Opt::from_args(); let region_provider = RegionProviderChain::first_try(region.map(Region::new)) .or_default_provider() .or_else(Region::new("us-west-2")); println!(); if verbose { println!("IAM client version: {}", PKG_VERSION); println!( "Region: {}", region_provider.region().await.unwrap().as_ref() ); println!("Role name: {}", &name); println!("Policy doc filename {}", &policy_file); println!(); } let shared_config = aws_config::from_env().region(region_provider).load().await; let client = Client::new(&shared_config); make_role(&client, &policy_file, &name).await }
{ // Read policy doc from file as a string let doc = fs::read_to_string(policy_file).expect("Unable to read file"); let resp = client .create_role() .assume_role_policy_document(doc) .role_name(name) .send() .await?; println!( "Created role with ARN {}", resp.role().unwrap().arn().unwrap() ); Ok(()) }
identifier_body
create-role.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_iam::{Client, Error, Region, PKG_VERSION}; use std::fs; use structopt::StructOpt; #[derive(Debug, StructOpt)] struct Opt { /// The AWS Region. #[structopt(short, long)] region: Option<String>, /// The name of the role. #[structopt(short, long)] name: String, /// The name of the file containing the policy document. #[structopt(short, long)] policy_file: String, /// Whether to display additional information. #[structopt(short, long)] verbose: bool, } // Creates a role. // snippet-start:[iam.rust.create-role] async fn make_role(client: &Client, policy_file: &str, name: &str) -> Result<(), Error> { // Read policy doc from file as a string let doc = fs::read_to_string(policy_file).expect("Unable to read file"); let resp = client .create_role() .assume_role_policy_document(doc) .role_name(name) .send() .await?; println!( "Created role with ARN {}", resp.role().unwrap().arn().unwrap() ); Ok(()) } // snippet-end:[iam.rust.create-role] /// Creates an IAM role in the Region. /// /// # Arguments /// /// * `-a ACCOUNT-ID` - Your account ID. /// * `-b BUCKET` - The name of the bucket where Config stores information about resources. /// * `-n NAME` - The name of the role. /// * `-p POLICY-NAME` - The name of the JSON file containing the policy document. /// * `[-r REGION]` - The Region in which the client is created. /// If not supplied, uses the value of the **AWS_REGION** environment variable. /// If the environment variable is not set, defaults to **us-west-2**. /// * `[-v]` - Whether to display information. #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt::init(); let Opt { name, policy_file, region, verbose, } = Opt::from_args(); let region_provider = RegionProviderChain::first_try(region.map(Region::new)) .or_default_provider() .or_else(Region::new("us-west-2")); println!(); if verbose
let shared_config = aws_config::from_env().region(region_provider).load().await; let client = Client::new(&shared_config); make_role(&client, &policy_file, &name).await }
{ println!("IAM client version: {}", PKG_VERSION); println!( "Region: {}", region_provider.region().await.unwrap().as_ref() ); println!("Role name: {}", &name); println!("Policy doc filename {}", &policy_file); println!(); }
conditional_block
create-role.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_iam::{Client, Error, Region, PKG_VERSION}; use std::fs; use structopt::StructOpt; #[derive(Debug, StructOpt)] struct Opt { /// The AWS Region. #[structopt(short, long)] region: Option<String>, /// The name of the role. #[structopt(short, long)] name: String, /// The name of the file containing the policy document. #[structopt(short, long)] policy_file: String, /// Whether to display additional information. #[structopt(short, long)] verbose: bool, } // Creates a role. // snippet-start:[iam.rust.create-role] async fn
(client: &Client, policy_file: &str, name: &str) -> Result<(), Error> { // Read policy doc from file as a string let doc = fs::read_to_string(policy_file).expect("Unable to read file"); let resp = client .create_role() .assume_role_policy_document(doc) .role_name(name) .send() .await?; println!( "Created role with ARN {}", resp.role().unwrap().arn().unwrap() ); Ok(()) } // snippet-end:[iam.rust.create-role] /// Creates an IAM role in the Region. /// /// # Arguments /// /// * `-a ACCOUNT-ID` - Your account ID. /// * `-b BUCKET` - The name of the bucket where Config stores information about resources. /// * `-n NAME` - The name of the role. /// * `-p POLICY-NAME` - The name of the JSON file containing the policy document. /// * `[-r REGION]` - The Region in which the client is created. /// If not supplied, uses the value of the **AWS_REGION** environment variable. /// If the environment variable is not set, defaults to **us-west-2**. /// * `[-v]` - Whether to display information. #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt::init(); let Opt { name, policy_file, region, verbose, } = Opt::from_args(); let region_provider = RegionProviderChain::first_try(region.map(Region::new)) .or_default_provider() .or_else(Region::new("us-west-2")); println!(); if verbose { println!("IAM client version: {}", PKG_VERSION); println!( "Region: {}", region_provider.region().await.unwrap().as_ref() ); println!("Role name: {}", &name); println!("Policy doc filename {}", &policy_file); println!(); } let shared_config = aws_config::from_env().region(region_provider).load().await; let client = Client::new(&shared_config); make_role(&client, &policy_file, &name).await }
make_role
identifier_name
task_resolvers.rs
use chrono::{prelude::*}; use async_graphql::{Context, FieldResult, ID}; use eyre::{ eyre, // Result, // Context as _, }; use super::{Task, TaskStatus, task_status::TaskStatusGQL}; use crate::{MachineMap, machine::{ MachineData, messages::GetData, }}; /// A spooled set of gcodes to be executed by the machine #[async_graphql::Object] impl Task { async fn id(&self) -> ID { (&self.id).into() } #[graphql(name="partID")] async fn part_id(&self) -> Option<ID> { self.part_id.as_ref().map(Into::into) } // async fn name<'ctx>(&self, ctx: &'ctx Context<'_>) -> FieldResult<String> { // let ctx: &Arc<crate::Context> = ctx.data()?; // if let Some(print) = self.print.as_ref() { // let part = Part::get(&ctx.db, print.part_id)?; // Ok(part.name.to_string()) // } else { // Ok("[UNNAMED_TASK]".to_string()) // } // } #[graphql(name = "status")] async fn _status(&self) -> TaskStatusGQL { (&self.status).into() } #[graphql(name = "paused")] async fn _paused(&self) -> bool { self.status.is_paused() } #[graphql(name = "settled")] async fn _settled(&self) -> bool { self.status.is_settled() } async fn total_lines(&self) -> u64 { self.total_lines } async fn despooled_line_number(&self) -> &Option<u64> { &self.despooled_line_number } async fn percent_complete( &self, #[graphql(desc = r#" The number of digits to the right of the decimal place to round to. eg. * percent_complete(digits: 0) gives 3 * percent_complete(digits: 2) gives 3.14 "#)] digits: Option<u8>, ) -> FieldResult<f32> { let printed_lines = self.despooled_line_number .map(|n| n + 1) .unwrap_or(0) as f32; let percent = if self.status.was_successful() { // Empty tasks need to denote success somehow 100.0 } else { // Empty tasks need to not divide by zero let total_lines = std::cmp::max(self.total_lines, 1) as f32; 100.0 * printed_lines / total_lines }; if let Some(digits) = digits { let scale = 10f32.powi(digits as i32); Ok((percent * scale).round() / scale) } else { Ok(percent) } } async fn estimated_print_time_millis(&self) -> Option<u64> { self.estimated_print_time.map(|print_time| { let millis = print_time.as_millis(); // Saturating conversion to u64 std::cmp::min(millis, std::u64::MAX as u128) as u64 }) } async fn eta<'ctx>(&self, ctx: &'ctx Context<'_>) -> FieldResult<Option<DateTime<Utc>>> { let machines: &MachineMap = ctx.data()?; let machines = machines.load(); let machine_id = (&self.machine_id).into(); let addr = machines.get(&machine_id) .ok_or_else(|| eyre!("Unable to get machine ({:?}) for task", machine_id))?; let machine_data = addr.call(GetData).await??; let print_time = if let Some(print_time) = self.estimated_print_time { print_time } else
; let mut duration = print_time + self.time_paused + self.time_blocked; if let TaskStatus::Paused(paused_status) = &self.status { duration += (Utc::now() - paused_status.paused_at).to_std()?; } else if let Some(blocked_at) = machine_data.blocked_at { if self.status.is_pending() { duration += (Utc::now() - blocked_at).to_std()?; } } let eta= self.created_at + ::chrono::Duration::from_std(duration)?; Ok(Some(eta)) } async fn estimated_filament_meters(&self) -> &Option<f64> { &self.estimated_filament_meters } async fn started_at(&self) -> &DateTime<Utc> { &self.created_at } async fn stopped_at(&self) -> Option<&DateTime<Utc>> { use super::*; match &self.status { | TaskStatus::Finished(Finished { finished_at: t }) | TaskStatus::Paused(Paused { paused_at: t }) | TaskStatus::Cancelled(Cancelled { cancelled_at: t }) | TaskStatus::Errored(Errored { errored_at: t,.. }) => Some(t), _ => None, } } async fn machine<'ctx>(&self, ctx: &'ctx Context<'_>) -> FieldResult<MachineData> { let machines: &MachineMap = ctx.data()?; let machines = machines.load(); let machine_id = (&self.machine_id).into(); let addr = machines.get(&machine_id) .ok_or_else(|| eyre!("Unable to get machine ({:?}) for task", machine_id))?; let machine_data = addr.call(GetData).await??; Ok(machine_data) } }
{ return Ok(None) }
conditional_block
task_resolvers.rs
use chrono::{prelude::*}; use async_graphql::{Context, FieldResult, ID}; use eyre::{ eyre, // Result, // Context as _, }; use super::{Task, TaskStatus, task_status::TaskStatusGQL}; use crate::{MachineMap, machine::{ MachineData, messages::GetData, }}; /// A spooled set of gcodes to be executed by the machine #[async_graphql::Object] impl Task { async fn id(&self) -> ID { (&self.id).into() } #[graphql(name="partID")] async fn part_id(&self) -> Option<ID> { self.part_id.as_ref().map(Into::into) } // async fn name<'ctx>(&self, ctx: &'ctx Context<'_>) -> FieldResult<String> { // let ctx: &Arc<crate::Context> = ctx.data()?; // if let Some(print) = self.print.as_ref() { // let part = Part::get(&ctx.db, print.part_id)?; // Ok(part.name.to_string()) // } else { // Ok("[UNNAMED_TASK]".to_string()) // } // } #[graphql(name = "status")]
#[graphql(name = "settled")] async fn _settled(&self) -> bool { self.status.is_settled() } async fn total_lines(&self) -> u64 { self.total_lines } async fn despooled_line_number(&self) -> &Option<u64> { &self.despooled_line_number } async fn percent_complete( &self, #[graphql(desc = r#" The number of digits to the right of the decimal place to round to. eg. * percent_complete(digits: 0) gives 3 * percent_complete(digits: 2) gives 3.14 "#)] digits: Option<u8>, ) -> FieldResult<f32> { let printed_lines = self.despooled_line_number .map(|n| n + 1) .unwrap_or(0) as f32; let percent = if self.status.was_successful() { // Empty tasks need to denote success somehow 100.0 } else { // Empty tasks need to not divide by zero let total_lines = std::cmp::max(self.total_lines, 1) as f32; 100.0 * printed_lines / total_lines }; if let Some(digits) = digits { let scale = 10f32.powi(digits as i32); Ok((percent * scale).round() / scale) } else { Ok(percent) } } async fn estimated_print_time_millis(&self) -> Option<u64> { self.estimated_print_time.map(|print_time| { let millis = print_time.as_millis(); // Saturating conversion to u64 std::cmp::min(millis, std::u64::MAX as u128) as u64 }) } async fn eta<'ctx>(&self, ctx: &'ctx Context<'_>) -> FieldResult<Option<DateTime<Utc>>> { let machines: &MachineMap = ctx.data()?; let machines = machines.load(); let machine_id = (&self.machine_id).into(); let addr = machines.get(&machine_id) .ok_or_else(|| eyre!("Unable to get machine ({:?}) for task", machine_id))?; let machine_data = addr.call(GetData).await??; let print_time = if let Some(print_time) = self.estimated_print_time { print_time } else { return Ok(None) }; let mut duration = print_time + self.time_paused + self.time_blocked; if let TaskStatus::Paused(paused_status) = &self.status { duration += (Utc::now() - paused_status.paused_at).to_std()?; } else if let Some(blocked_at) = machine_data.blocked_at { if self.status.is_pending() { duration += (Utc::now() - blocked_at).to_std()?; } } let eta= self.created_at + ::chrono::Duration::from_std(duration)?; Ok(Some(eta)) } async fn estimated_filament_meters(&self) -> &Option<f64> { &self.estimated_filament_meters } async fn started_at(&self) -> &DateTime<Utc> { &self.created_at } async fn stopped_at(&self) -> Option<&DateTime<Utc>> { use super::*; match &self.status { | TaskStatus::Finished(Finished { finished_at: t }) | TaskStatus::Paused(Paused { paused_at: t }) | TaskStatus::Cancelled(Cancelled { cancelled_at: t }) | TaskStatus::Errored(Errored { errored_at: t,.. }) => Some(t), _ => None, } } async fn machine<'ctx>(&self, ctx: &'ctx Context<'_>) -> FieldResult<MachineData> { let machines: &MachineMap = ctx.data()?; let machines = machines.load(); let machine_id = (&self.machine_id).into(); let addr = machines.get(&machine_id) .ok_or_else(|| eyre!("Unable to get machine ({:?}) for task", machine_id))?; let machine_data = addr.call(GetData).await??; Ok(machine_data) } }
async fn _status(&self) -> TaskStatusGQL { (&self.status).into() } #[graphql(name = "paused")] async fn _paused(&self) -> bool { self.status.is_paused() }
random_line_split
task_resolvers.rs
use chrono::{prelude::*}; use async_graphql::{Context, FieldResult, ID}; use eyre::{ eyre, // Result, // Context as _, }; use super::{Task, TaskStatus, task_status::TaskStatusGQL}; use crate::{MachineMap, machine::{ MachineData, messages::GetData, }}; /// A spooled set of gcodes to be executed by the machine #[async_graphql::Object] impl Task { async fn id(&self) -> ID { (&self.id).into() } #[graphql(name="partID")] async fn part_id(&self) -> Option<ID> { self.part_id.as_ref().map(Into::into) } // async fn name<'ctx>(&self, ctx: &'ctx Context<'_>) -> FieldResult<String> { // let ctx: &Arc<crate::Context> = ctx.data()?; // if let Some(print) = self.print.as_ref() { // let part = Part::get(&ctx.db, print.part_id)?; // Ok(part.name.to_string()) // } else { // Ok("[UNNAMED_TASK]".to_string()) // } // } #[graphql(name = "status")] async fn _status(&self) -> TaskStatusGQL { (&self.status).into() } #[graphql(name = "paused")] async fn _paused(&self) -> bool { self.status.is_paused() } #[graphql(name = "settled")] async fn _settled(&self) -> bool { self.status.is_settled() } async fn total_lines(&self) -> u64 { self.total_lines } async fn despooled_line_number(&self) -> &Option<u64> { &self.despooled_line_number } async fn percent_complete( &self, #[graphql(desc = r#" The number of digits to the right of the decimal place to round to. eg. * percent_complete(digits: 0) gives 3 * percent_complete(digits: 2) gives 3.14 "#)] digits: Option<u8>, ) -> FieldResult<f32> { let printed_lines = self.despooled_line_number .map(|n| n + 1) .unwrap_or(0) as f32; let percent = if self.status.was_successful() { // Empty tasks need to denote success somehow 100.0 } else { // Empty tasks need to not divide by zero let total_lines = std::cmp::max(self.total_lines, 1) as f32; 100.0 * printed_lines / total_lines }; if let Some(digits) = digits { let scale = 10f32.powi(digits as i32); Ok((percent * scale).round() / scale) } else { Ok(percent) } } async fn estimated_print_time_millis(&self) -> Option<u64>
async fn eta<'ctx>(&self, ctx: &'ctx Context<'_>) -> FieldResult<Option<DateTime<Utc>>> { let machines: &MachineMap = ctx.data()?; let machines = machines.load(); let machine_id = (&self.machine_id).into(); let addr = machines.get(&machine_id) .ok_or_else(|| eyre!("Unable to get machine ({:?}) for task", machine_id))?; let machine_data = addr.call(GetData).await??; let print_time = if let Some(print_time) = self.estimated_print_time { print_time } else { return Ok(None) }; let mut duration = print_time + self.time_paused + self.time_blocked; if let TaskStatus::Paused(paused_status) = &self.status { duration += (Utc::now() - paused_status.paused_at).to_std()?; } else if let Some(blocked_at) = machine_data.blocked_at { if self.status.is_pending() { duration += (Utc::now() - blocked_at).to_std()?; } } let eta= self.created_at + ::chrono::Duration::from_std(duration)?; Ok(Some(eta)) } async fn estimated_filament_meters(&self) -> &Option<f64> { &self.estimated_filament_meters } async fn started_at(&self) -> &DateTime<Utc> { &self.created_at } async fn stopped_at(&self) -> Option<&DateTime<Utc>> { use super::*; match &self.status { | TaskStatus::Finished(Finished { finished_at: t }) | TaskStatus::Paused(Paused { paused_at: t }) | TaskStatus::Cancelled(Cancelled { cancelled_at: t }) | TaskStatus::Errored(Errored { errored_at: t,.. }) => Some(t), _ => None, } } async fn machine<'ctx>(&self, ctx: &'ctx Context<'_>) -> FieldResult<MachineData> { let machines: &MachineMap = ctx.data()?; let machines = machines.load(); let machine_id = (&self.machine_id).into(); let addr = machines.get(&machine_id) .ok_or_else(|| eyre!("Unable to get machine ({:?}) for task", machine_id))?; let machine_data = addr.call(GetData).await??; Ok(machine_data) } }
{ self.estimated_print_time.map(|print_time| { let millis = print_time.as_millis(); // Saturating conversion to u64 std::cmp::min(millis, std::u64::MAX as u128) as u64 }) }
identifier_body