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 |
---|---|---|---|---|
utmpx.rs
|
// This file is part of the uutils coreutils package.
//
// (c) Jian Zeng <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//
//! Aims to provide platform-independent methods to obtain login records
//!
//! **ONLY** support linux, macos and freebsd for the time being
//!
//! # Examples:
//!
//! ```
//! use uucore::utmpx::Utmpx;
//! for ut in Utmpx::iter_all_records() {
//! if ut.is_user_process() {
//! println!("{}: {}", ut.host(), ut.user())
//! }
//! }
//! ```
//!
//! Specifying the path to login record:
//!
//! ```
//! use uucore::utmpx::Utmpx;
//! for ut in Utmpx::iter_all_records().read_from("/some/where/else") {
//! if ut.is_user_process() {
//! println!("{}: {}", ut.host(), ut.user())
//! }
//! }
//! ```
use super::libc;
pub extern crate time;
use self::time::{Tm, Timespec};
use ::std::io::Result as IOResult;
use ::std::io::Error as IOError;
use ::std::ptr;
use ::std::ffi::CString;
pub use self::ut::*;
use libc::utmpx;
// pub use libc::getutxid;
// pub use libc::getutxline;
// pub use libc::pututxline;
pub use libc::getutxent;
pub use libc::setutxent;
pub use libc::endutxent;
#[cfg(any(target_os = "macos", target_os = "linux"))]
pub use libc::utmpxname;
#[cfg(target_os = "freebsd")]
pub unsafe extern "C" fn utmpxname(_file: *const libc::c_char) -> libc::c_int {
0
}
// In case the c_char array doesn' t end with NULL
macro_rules! chars2string {
($arr:expr) => (
$arr.iter().take_while(|i| **i > 0).map(|&i| i as u8 as char).collect::<String>()
)
}
#[cfg(target_os = "linux")]
mod ut {
pub static DEFAULT_FILE: &'static str = "/var/run/utmp";
pub use libc::__UT_LINESIZE as UT_LINESIZE;
pub use libc::__UT_NAMESIZE as UT_NAMESIZE;
pub use libc::__UT_HOSTSIZE as UT_HOSTSIZE;
pub const UT_IDSIZE: usize = 4;
pub use libc::EMPTY;
pub use libc::RUN_LVL;
pub use libc::BOOT_TIME;
pub use libc::NEW_TIME;
pub use libc::OLD_TIME;
pub use libc::INIT_PROCESS;
pub use libc::LOGIN_PROCESS;
pub use libc::USER_PROCESS;
pub use libc::DEAD_PROCESS;
pub use libc::ACCOUNTING;
}
#[cfg(target_os = "macos")]
mod ut {
pub static DEFAULT_FILE: &'static str = "/var/run/utmpx";
pub use libc::_UTX_LINESIZE as UT_LINESIZE;
pub use libc::_UTX_USERSIZE as UT_NAMESIZE;
pub use libc::_UTX_HOSTSIZE as UT_HOSTSIZE;
pub use libc::_UTX_IDSIZE as UT_IDSIZE;
pub use libc::EMPTY;
pub use libc::RUN_LVL;
pub use libc::BOOT_TIME;
pub use libc::NEW_TIME;
pub use libc::OLD_TIME;
pub use libc::INIT_PROCESS;
pub use libc::LOGIN_PROCESS;
pub use libc::USER_PROCESS;
pub use libc::DEAD_PROCESS;
pub use libc::ACCOUNTING;
pub use libc::SIGNATURE;
pub use libc::SHUTDOWN_TIME;
}
#[cfg(target_os = "freebsd")]
mod ut {
use super::libc;
pub static DEFAULT_FILE: &'static str = "";
pub const UT_LINESIZE: usize = 16;
pub const UT_NAMESIZE: usize = 32;
pub const UT_IDSIZE: usize = 8;
pub const UT_HOSTSIZE: usize = 128;
pub use libc::EMPTY;
pub use libc::BOOT_TIME;
pub use libc::OLD_TIME;
pub use libc::NEW_TIME;
pub use libc::USER_PROCESS;
pub use libc::INIT_PROCESS;
pub use libc::LOGIN_PROCESS;
pub use libc::DEAD_PROCESS;
pub use libc::SHUTDOWN_TIME;
}
pub struct Utmpx {
inner: utmpx,
}
impl Utmpx {
/// A.K.A. ut.ut_type
pub fn record_type(&self) -> i16 {
self.inner.ut_type as i16
}
/// A.K.A. ut.ut_pid
pub fn pid(&self) -> i32 {
self.inner.ut_pid as i32
}
/// A.K.A. ut.ut_id
pub fn terminal_suffix(&self) -> String
|
/// A.K.A. ut.ut_user
pub fn user(&self) -> String {
chars2string!(self.inner.ut_user)
}
/// A.K.A. ut.ut_host
pub fn host(&self) -> String {
chars2string!(self.inner.ut_host)
}
/// A.K.A. ut.ut_line
pub fn tty_device(&self) -> String {
chars2string!(self.inner.ut_line)
}
/// A.K.A. ut.ut_tv
pub fn login_time(&self) -> Tm {
time::at(Timespec::new(self.inner.ut_tv.tv_sec as i64,
self.inner.ut_tv.tv_usec as i32))
}
/// A.K.A. ut.ut_exit
///
/// Return (e_termination, e_exit)
#[cfg(any(target_os = "linux", target_os = "android"))]
pub fn exit_status(&self) -> (i16, i16) {
(self.inner.ut_exit.e_termination, self.inner.ut_exit.e_exit)
}
/// A.K.A. ut.ut_exit
///
/// Return (0, 0) on Non-Linux platform
#[cfg(not(any(target_os = "linux", target_os = "android")))]
pub fn exit_status(&self) -> (i16, i16) {
(0, 0)
}
/// Consumes the `Utmpx`, returning the underlying C struct utmpx
pub fn into_inner(self) -> utmpx {
self.inner
}
pub fn is_user_process(&self) -> bool {
!self.user().is_empty() && self.record_type() == USER_PROCESS
}
/// Canonicalize host name using DNS
pub fn canon_host(&self) -> IOResult<String> {
const AI_CANONNAME: libc::c_int = 0x2;
let host = self.host();
let host = host.split(':').nth(0).unwrap();
let hints = libc::addrinfo {
ai_flags: AI_CANONNAME,
ai_family: 0,
ai_socktype: 0,
ai_protocol: 0,
ai_addrlen: 0,
ai_addr: ptr::null_mut(),
ai_canonname: ptr::null_mut(),
ai_next: ptr::null_mut(),
};
let c_host = CString::new(host).unwrap();
let mut res = ptr::null_mut();
let status = unsafe {
libc::getaddrinfo(c_host.as_ptr(),
ptr::null(),
&hints as *const _,
&mut res as *mut _)
};
if status == 0 {
let info: libc::addrinfo = unsafe { ptr::read(res as *const _) };
// http://lists.gnu.org/archive/html/bug-coreutils/2006-09/msg00300.html
// says Darwin 7.9.0 getaddrinfo returns 0 but sets
// res->ai_canonname to NULL.
let ret = if info.ai_canonname.is_null() {
Ok(String::from(host))
} else {
Ok(unsafe { CString::from_raw(info.ai_canonname).into_string().unwrap() })
};
unsafe {
libc::freeaddrinfo(res);
}
ret
} else {
Err(IOError::last_os_error())
}
}
pub fn iter_all_records() -> UtmpxIter {
UtmpxIter
}
}
/// Iterator of login records
pub struct UtmpxIter;
impl UtmpxIter {
/// Sets the name of the utmpx-format file for the other utmpx functions to access.
///
/// If not set, default record file will be used(file path depends on the target OS)
pub fn read_from(self, f: &str) -> Self {
let res = unsafe { utmpxname(CString::new(f).unwrap().as_ptr()) };
if res!= 0 {
println!("Warning: {}", IOError::last_os_error());
}
unsafe {
setutxent();
}
self
}
}
impl Iterator for UtmpxIter {
type Item = Utmpx;
fn next(&mut self) -> Option<Self::Item> {
unsafe {
let res = getutxent();
if!res.is_null() {
Some(Utmpx { inner: ptr::read(res as *const _) })
} else {
endutxent();
None
}
}
}
}
|
{
chars2string!(self.inner.ut_id)
}
|
identifier_body
|
utmpx.rs
|
// This file is part of the uutils coreutils package.
//
// (c) Jian Zeng <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//
//! Aims to provide platform-independent methods to obtain login records
//!
//! **ONLY** support linux, macos and freebsd for the time being
//!
//! # Examples:
//!
//! ```
//! use uucore::utmpx::Utmpx;
//! for ut in Utmpx::iter_all_records() {
//! if ut.is_user_process() {
//! println!("{}: {}", ut.host(), ut.user())
//! }
//! }
//! ```
//!
//! Specifying the path to login record:
//!
//! ```
//! use uucore::utmpx::Utmpx;
//! for ut in Utmpx::iter_all_records().read_from("/some/where/else") {
//! if ut.is_user_process() {
//! println!("{}: {}", ut.host(), ut.user())
//! }
//! }
//! ```
use super::libc;
pub extern crate time;
use self::time::{Tm, Timespec};
use ::std::io::Result as IOResult;
use ::std::io::Error as IOError;
use ::std::ptr;
use ::std::ffi::CString;
pub use self::ut::*;
use libc::utmpx;
// pub use libc::getutxid;
// pub use libc::getutxline;
// pub use libc::pututxline;
pub use libc::getutxent;
pub use libc::setutxent;
pub use libc::endutxent;
#[cfg(any(target_os = "macos", target_os = "linux"))]
pub use libc::utmpxname;
#[cfg(target_os = "freebsd")]
pub unsafe extern "C" fn utmpxname(_file: *const libc::c_char) -> libc::c_int {
0
}
// In case the c_char array doesn' t end with NULL
macro_rules! chars2string {
($arr:expr) => (
$arr.iter().take_while(|i| **i > 0).map(|&i| i as u8 as char).collect::<String>()
)
}
#[cfg(target_os = "linux")]
mod ut {
pub static DEFAULT_FILE: &'static str = "/var/run/utmp";
pub use libc::__UT_LINESIZE as UT_LINESIZE;
pub use libc::__UT_NAMESIZE as UT_NAMESIZE;
pub use libc::__UT_HOSTSIZE as UT_HOSTSIZE;
pub const UT_IDSIZE: usize = 4;
pub use libc::EMPTY;
pub use libc::RUN_LVL;
pub use libc::BOOT_TIME;
pub use libc::NEW_TIME;
pub use libc::OLD_TIME;
pub use libc::INIT_PROCESS;
pub use libc::LOGIN_PROCESS;
pub use libc::USER_PROCESS;
pub use libc::DEAD_PROCESS;
pub use libc::ACCOUNTING;
}
#[cfg(target_os = "macos")]
mod ut {
pub static DEFAULT_FILE: &'static str = "/var/run/utmpx";
pub use libc::_UTX_LINESIZE as UT_LINESIZE;
pub use libc::_UTX_USERSIZE as UT_NAMESIZE;
pub use libc::_UTX_HOSTSIZE as UT_HOSTSIZE;
pub use libc::_UTX_IDSIZE as UT_IDSIZE;
pub use libc::EMPTY;
pub use libc::RUN_LVL;
pub use libc::BOOT_TIME;
pub use libc::NEW_TIME;
pub use libc::OLD_TIME;
pub use libc::INIT_PROCESS;
pub use libc::LOGIN_PROCESS;
pub use libc::USER_PROCESS;
pub use libc::DEAD_PROCESS;
pub use libc::ACCOUNTING;
pub use libc::SIGNATURE;
pub use libc::SHUTDOWN_TIME;
}
#[cfg(target_os = "freebsd")]
mod ut {
use super::libc;
pub static DEFAULT_FILE: &'static str = "";
pub const UT_LINESIZE: usize = 16;
pub const UT_NAMESIZE: usize = 32;
pub const UT_IDSIZE: usize = 8;
pub const UT_HOSTSIZE: usize = 128;
pub use libc::EMPTY;
pub use libc::BOOT_TIME;
pub use libc::OLD_TIME;
pub use libc::NEW_TIME;
pub use libc::USER_PROCESS;
pub use libc::INIT_PROCESS;
pub use libc::LOGIN_PROCESS;
pub use libc::DEAD_PROCESS;
pub use libc::SHUTDOWN_TIME;
}
pub struct Utmpx {
inner: utmpx,
}
impl Utmpx {
/// A.K.A. ut.ut_type
pub fn record_type(&self) -> i16 {
self.inner.ut_type as i16
}
/// A.K.A. ut.ut_pid
pub fn pid(&self) -> i32 {
self.inner.ut_pid as i32
}
/// A.K.A. ut.ut_id
pub fn terminal_suffix(&self) -> String {
chars2string!(self.inner.ut_id)
}
/// A.K.A. ut.ut_user
pub fn user(&self) -> String {
chars2string!(self.inner.ut_user)
}
/// A.K.A. ut.ut_host
pub fn host(&self) -> String {
chars2string!(self.inner.ut_host)
}
/// A.K.A. ut.ut_line
pub fn tty_device(&self) -> String {
chars2string!(self.inner.ut_line)
}
/// A.K.A. ut.ut_tv
pub fn login_time(&self) -> Tm {
time::at(Timespec::new(self.inner.ut_tv.tv_sec as i64,
self.inner.ut_tv.tv_usec as i32))
}
/// A.K.A. ut.ut_exit
///
/// Return (e_termination, e_exit)
#[cfg(any(target_os = "linux", target_os = "android"))]
pub fn exit_status(&self) -> (i16, i16) {
(self.inner.ut_exit.e_termination, self.inner.ut_exit.e_exit)
}
/// A.K.A. ut.ut_exit
///
/// Return (0, 0) on Non-Linux platform
#[cfg(not(any(target_os = "linux", target_os = "android")))]
pub fn exit_status(&self) -> (i16, i16) {
(0, 0)
}
/// Consumes the `Utmpx`, returning the underlying C struct utmpx
pub fn into_inner(self) -> utmpx {
self.inner
}
pub fn is_user_process(&self) -> bool {
!self.user().is_empty() && self.record_type() == USER_PROCESS
}
/// Canonicalize host name using DNS
pub fn canon_host(&self) -> IOResult<String> {
const AI_CANONNAME: libc::c_int = 0x2;
let host = self.host();
let host = host.split(':').nth(0).unwrap();
let hints = libc::addrinfo {
ai_flags: AI_CANONNAME,
ai_family: 0,
ai_socktype: 0,
ai_protocol: 0,
ai_addrlen: 0,
ai_addr: ptr::null_mut(),
ai_canonname: ptr::null_mut(),
ai_next: ptr::null_mut(),
};
let c_host = CString::new(host).unwrap();
let mut res = ptr::null_mut();
let status = unsafe {
libc::getaddrinfo(c_host.as_ptr(),
ptr::null(),
&hints as *const _,
&mut res as *mut _)
};
if status == 0 {
let info: libc::addrinfo = unsafe { ptr::read(res as *const _) };
// http://lists.gnu.org/archive/html/bug-coreutils/2006-09/msg00300.html
// says Darwin 7.9.0 getaddrinfo returns 0 but sets
// res->ai_canonname to NULL.
let ret = if info.ai_canonname.is_null() {
Ok(String::from(host))
} else {
Ok(unsafe { CString::from_raw(info.ai_canonname).into_string().unwrap() })
};
unsafe {
libc::freeaddrinfo(res);
}
ret
} else {
Err(IOError::last_os_error())
}
}
pub fn iter_all_records() -> UtmpxIter {
UtmpxIter
}
}
/// Iterator of login records
pub struct UtmpxIter;
impl UtmpxIter {
/// Sets the name of the utmpx-format file for the other utmpx functions to access.
///
/// If not set, default record file will be used(file path depends on the target OS)
pub fn read_from(self, f: &str) -> Self {
let res = unsafe { utmpxname(CString::new(f).unwrap().as_ptr()) };
if res!= 0 {
println!("Warning: {}", IOError::last_os_error());
}
unsafe {
setutxent();
}
self
}
}
impl Iterator for UtmpxIter {
type Item = Utmpx;
fn next(&mut self) -> Option<Self::Item> {
unsafe {
let res = getutxent();
if!res.is_null() {
Some(Utmpx { inner: ptr::read(res as *const _) })
} else
|
}
}
}
|
{
endutxent();
None
}
|
conditional_block
|
utmpx.rs
|
// This file is part of the uutils coreutils package.
//
// (c) Jian Zeng <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//
//! Aims to provide platform-independent methods to obtain login records
//!
//! **ONLY** support linux, macos and freebsd for the time being
//!
//! # Examples:
//!
//! ```
//! use uucore::utmpx::Utmpx;
//! for ut in Utmpx::iter_all_records() {
//! if ut.is_user_process() {
//! println!("{}: {}", ut.host(), ut.user())
//! }
//! }
//! ```
//!
//! Specifying the path to login record:
//!
//! ```
//! use uucore::utmpx::Utmpx;
//! for ut in Utmpx::iter_all_records().read_from("/some/where/else") {
//! if ut.is_user_process() {
//! println!("{}: {}", ut.host(), ut.user())
//! }
//! }
//! ```
use super::libc;
pub extern crate time;
use self::time::{Tm, Timespec};
use ::std::io::Result as IOResult;
use ::std::io::Error as IOError;
use ::std::ptr;
use ::std::ffi::CString;
pub use self::ut::*;
use libc::utmpx;
// pub use libc::getutxid;
// pub use libc::getutxline;
// pub use libc::pututxline;
pub use libc::getutxent;
pub use libc::setutxent;
pub use libc::endutxent;
#[cfg(any(target_os = "macos", target_os = "linux"))]
pub use libc::utmpxname;
#[cfg(target_os = "freebsd")]
pub unsafe extern "C" fn utmpxname(_file: *const libc::c_char) -> libc::c_int {
0
}
// In case the c_char array doesn' t end with NULL
macro_rules! chars2string {
($arr:expr) => (
$arr.iter().take_while(|i| **i > 0).map(|&i| i as u8 as char).collect::<String>()
)
}
#[cfg(target_os = "linux")]
mod ut {
pub static DEFAULT_FILE: &'static str = "/var/run/utmp";
pub use libc::__UT_LINESIZE as UT_LINESIZE;
pub use libc::__UT_NAMESIZE as UT_NAMESIZE;
pub use libc::__UT_HOSTSIZE as UT_HOSTSIZE;
pub const UT_IDSIZE: usize = 4;
pub use libc::EMPTY;
pub use libc::RUN_LVL;
pub use libc::BOOT_TIME;
pub use libc::NEW_TIME;
pub use libc::OLD_TIME;
pub use libc::INIT_PROCESS;
pub use libc::LOGIN_PROCESS;
pub use libc::USER_PROCESS;
pub use libc::DEAD_PROCESS;
pub use libc::ACCOUNTING;
}
#[cfg(target_os = "macos")]
mod ut {
pub static DEFAULT_FILE: &'static str = "/var/run/utmpx";
pub use libc::_UTX_LINESIZE as UT_LINESIZE;
pub use libc::_UTX_USERSIZE as UT_NAMESIZE;
pub use libc::_UTX_HOSTSIZE as UT_HOSTSIZE;
pub use libc::_UTX_IDSIZE as UT_IDSIZE;
pub use libc::EMPTY;
pub use libc::RUN_LVL;
pub use libc::BOOT_TIME;
pub use libc::NEW_TIME;
pub use libc::OLD_TIME;
pub use libc::INIT_PROCESS;
pub use libc::LOGIN_PROCESS;
pub use libc::USER_PROCESS;
pub use libc::DEAD_PROCESS;
pub use libc::ACCOUNTING;
pub use libc::SIGNATURE;
pub use libc::SHUTDOWN_TIME;
}
#[cfg(target_os = "freebsd")]
mod ut {
use super::libc;
pub static DEFAULT_FILE: &'static str = "";
|
pub const UT_LINESIZE: usize = 16;
pub const UT_NAMESIZE: usize = 32;
pub const UT_IDSIZE: usize = 8;
pub const UT_HOSTSIZE: usize = 128;
pub use libc::EMPTY;
pub use libc::BOOT_TIME;
pub use libc::OLD_TIME;
pub use libc::NEW_TIME;
pub use libc::USER_PROCESS;
pub use libc::INIT_PROCESS;
pub use libc::LOGIN_PROCESS;
pub use libc::DEAD_PROCESS;
pub use libc::SHUTDOWN_TIME;
}
pub struct Utmpx {
inner: utmpx,
}
impl Utmpx {
/// A.K.A. ut.ut_type
pub fn record_type(&self) -> i16 {
self.inner.ut_type as i16
}
/// A.K.A. ut.ut_pid
pub fn pid(&self) -> i32 {
self.inner.ut_pid as i32
}
/// A.K.A. ut.ut_id
pub fn terminal_suffix(&self) -> String {
chars2string!(self.inner.ut_id)
}
/// A.K.A. ut.ut_user
pub fn user(&self) -> String {
chars2string!(self.inner.ut_user)
}
/// A.K.A. ut.ut_host
pub fn host(&self) -> String {
chars2string!(self.inner.ut_host)
}
/// A.K.A. ut.ut_line
pub fn tty_device(&self) -> String {
chars2string!(self.inner.ut_line)
}
/// A.K.A. ut.ut_tv
pub fn login_time(&self) -> Tm {
time::at(Timespec::new(self.inner.ut_tv.tv_sec as i64,
self.inner.ut_tv.tv_usec as i32))
}
/// A.K.A. ut.ut_exit
///
/// Return (e_termination, e_exit)
#[cfg(any(target_os = "linux", target_os = "android"))]
pub fn exit_status(&self) -> (i16, i16) {
(self.inner.ut_exit.e_termination, self.inner.ut_exit.e_exit)
}
/// A.K.A. ut.ut_exit
///
/// Return (0, 0) on Non-Linux platform
#[cfg(not(any(target_os = "linux", target_os = "android")))]
pub fn exit_status(&self) -> (i16, i16) {
(0, 0)
}
/// Consumes the `Utmpx`, returning the underlying C struct utmpx
pub fn into_inner(self) -> utmpx {
self.inner
}
pub fn is_user_process(&self) -> bool {
!self.user().is_empty() && self.record_type() == USER_PROCESS
}
/// Canonicalize host name using DNS
pub fn canon_host(&self) -> IOResult<String> {
const AI_CANONNAME: libc::c_int = 0x2;
let host = self.host();
let host = host.split(':').nth(0).unwrap();
let hints = libc::addrinfo {
ai_flags: AI_CANONNAME,
ai_family: 0,
ai_socktype: 0,
ai_protocol: 0,
ai_addrlen: 0,
ai_addr: ptr::null_mut(),
ai_canonname: ptr::null_mut(),
ai_next: ptr::null_mut(),
};
let c_host = CString::new(host).unwrap();
let mut res = ptr::null_mut();
let status = unsafe {
libc::getaddrinfo(c_host.as_ptr(),
ptr::null(),
&hints as *const _,
&mut res as *mut _)
};
if status == 0 {
let info: libc::addrinfo = unsafe { ptr::read(res as *const _) };
// http://lists.gnu.org/archive/html/bug-coreutils/2006-09/msg00300.html
// says Darwin 7.9.0 getaddrinfo returns 0 but sets
// res->ai_canonname to NULL.
let ret = if info.ai_canonname.is_null() {
Ok(String::from(host))
} else {
Ok(unsafe { CString::from_raw(info.ai_canonname).into_string().unwrap() })
};
unsafe {
libc::freeaddrinfo(res);
}
ret
} else {
Err(IOError::last_os_error())
}
}
pub fn iter_all_records() -> UtmpxIter {
UtmpxIter
}
}
/// Iterator of login records
pub struct UtmpxIter;
impl UtmpxIter {
/// Sets the name of the utmpx-format file for the other utmpx functions to access.
///
/// If not set, default record file will be used(file path depends on the target OS)
pub fn read_from(self, f: &str) -> Self {
let res = unsafe { utmpxname(CString::new(f).unwrap().as_ptr()) };
if res!= 0 {
println!("Warning: {}", IOError::last_os_error());
}
unsafe {
setutxent();
}
self
}
}
impl Iterator for UtmpxIter {
type Item = Utmpx;
fn next(&mut self) -> Option<Self::Item> {
unsafe {
let res = getutxent();
if!res.is_null() {
Some(Utmpx { inner: ptr::read(res as *const _) })
} else {
endutxent();
None
}
}
}
}
|
random_line_split
|
|
main.rs
|
extern crate px8;
extern crate sdl2;
extern crate time;
extern crate rand;
#[macro_use]
extern crate log;
extern crate fern;
extern crate nalgebra;
use std::sync::{Arc, Mutex};
use px8::px8::math;
use px8::frontend;
use px8::gfx;
use px8::cartridge;
use px8::px8::RustPlugin;
use px8::config::Players;
use nalgebra::Vector2;
pub struct Fighter {
pub pos: Vector2<u32>,
}
impl Fighter {
fn new(x: u32, y: u32) -> Fighter {
Fighter {
pos: Vector2::new(x, y)
}
}
fn update(&mut self) {
}
fn draw(&mut self, screen: Arc<Mutex<gfx::Screen>>) {
screen.lock().unwrap().pset(self.pos.x as i32, self.pos.y as i32, 8);
}
}
pub struct FourmisWar {
pub sprite_filename: String,
pub fighters: Vec<Fighter>,
}
impl FourmisWar {
pub fn new(sprite_filename: String) -> FourmisWar {
FourmisWar {
sprite_filename: sprite_filename,
fighters: Vec::new(),
}
}
}
impl RustPlugin for FourmisWar {
fn init(&mut self, screen: Arc<Mutex<gfx::Screen>>) -> f64 {
self.fighters.push(Fighter::new(40, 50));
match cartridge::Cartridge::parse(self.sprite_filename.clone(), false) {
Ok(c) => screen.lock().unwrap().set_sprites(c.gfx.sprites),
Err(e) => panic!("Impossible to load the assets {:?}", e),
}
return 0.;
}
fn update(&mut self, players: Arc<Mutex<Players>>) -> f64 {
let mouse_x = players.lock().unwrap().mouse_coordinate(0);
let mouse_y = players.lock().unwrap().mouse_coordinate(1);
if players.lock().unwrap().mouse_state() == 1 {
info!("CLICK {:?} {:?}", mouse_x, mouse_y);
}
for fighter in self.fighters.iter_mut() {
fighter.update();
}
return 0.;
}
fn draw(&mut self, screen: Arc<Mutex<gfx::Screen>>) -> f64
|
}
fn main() {
let logger_config = fern::DispatchConfig {
format: Box::new(|msg: &str, level: &log::LogLevel, _location: &log::LogLocation| {
format!("[{}][{}] {}",
time::now().strftime("%Y-%m-%d][%H:%M:%S").unwrap(),
level,
msg)
}),
output: vec![fern::OutputConfig::stdout(),
fern::OutputConfig::file("output.log")],
level: log::LogLevelFilter::Trace,
};
if let Err(e) = fern::init_global_logger(logger_config, log::LogLevelFilter::Info) {
panic!("Failed to initialize global logger: {}", e);
}
let war = FourmisWar::new("./fourmiswar.dpx8".to_string());
let mut frontend = match frontend::Frontend::init(px8::gfx::Scale::Scale4x, false, true, true) {
Err(error) => panic!("{:?}", error),
Ok(frontend) => frontend,
};
frontend.px8.register(war);
frontend.start("./gamecontrollerdb.txt".to_string());
frontend.run_native_cartridge();
}
|
{
screen.lock().unwrap().cls();
for fighter in self.fighters.iter_mut() {
fighter.draw(screen.clone());
}
return 0.;
}
|
identifier_body
|
main.rs
|
extern crate px8;
extern crate sdl2;
extern crate time;
extern crate rand;
#[macro_use]
extern crate log;
extern crate fern;
extern crate nalgebra;
use std::sync::{Arc, Mutex};
use px8::px8::math;
use px8::frontend;
use px8::gfx;
use px8::cartridge;
use px8::px8::RustPlugin;
use px8::config::Players;
use nalgebra::Vector2;
pub struct Fighter {
pub pos: Vector2<u32>,
}
impl Fighter {
fn new(x: u32, y: u32) -> Fighter {
Fighter {
pos: Vector2::new(x, y)
}
}
fn update(&mut self) {
}
fn draw(&mut self, screen: Arc<Mutex<gfx::Screen>>) {
screen.lock().unwrap().pset(self.pos.x as i32, self.pos.y as i32, 8);
}
}
pub struct FourmisWar {
pub sprite_filename: String,
pub fighters: Vec<Fighter>,
}
impl FourmisWar {
pub fn new(sprite_filename: String) -> FourmisWar {
FourmisWar {
sprite_filename: sprite_filename,
fighters: Vec::new(),
}
}
}
impl RustPlugin for FourmisWar {
fn init(&mut self, screen: Arc<Mutex<gfx::Screen>>) -> f64 {
self.fighters.push(Fighter::new(40, 50));
match cartridge::Cartridge::parse(self.sprite_filename.clone(), false) {
Ok(c) => screen.lock().unwrap().set_sprites(c.gfx.sprites),
Err(e) => panic!("Impossible to load the assets {:?}", e),
}
return 0.;
}
fn update(&mut self, players: Arc<Mutex<Players>>) -> f64 {
let mouse_x = players.lock().unwrap().mouse_coordinate(0);
let mouse_y = players.lock().unwrap().mouse_coordinate(1);
if players.lock().unwrap().mouse_state() == 1 {
info!("CLICK {:?} {:?}", mouse_x, mouse_y);
}
for fighter in self.fighters.iter_mut() {
fighter.update();
}
return 0.;
}
fn draw(&mut self, screen: Arc<Mutex<gfx::Screen>>) -> f64 {
screen.lock().unwrap().cls();
for fighter in self.fighters.iter_mut() {
fighter.draw(screen.clone());
}
return 0.;
}
}
fn main() {
let logger_config = fern::DispatchConfig {
format: Box::new(|msg: &str, level: &log::LogLevel, _location: &log::LogLocation| {
format!("[{}][{}] {}",
time::now().strftime("%Y-%m-%d][%H:%M:%S").unwrap(),
level,
msg)
}),
output: vec![fern::OutputConfig::stdout(),
fern::OutputConfig::file("output.log")],
level: log::LogLevelFilter::Trace,
};
if let Err(e) = fern::init_global_logger(logger_config, log::LogLevelFilter::Info)
|
let war = FourmisWar::new("./fourmiswar.dpx8".to_string());
let mut frontend = match frontend::Frontend::init(px8::gfx::Scale::Scale4x, false, true, true) {
Err(error) => panic!("{:?}", error),
Ok(frontend) => frontend,
};
frontend.px8.register(war);
frontend.start("./gamecontrollerdb.txt".to_string());
frontend.run_native_cartridge();
}
|
{
panic!("Failed to initialize global logger: {}", e);
}
|
conditional_block
|
main.rs
|
extern crate px8;
extern crate sdl2;
extern crate time;
extern crate rand;
#[macro_use]
extern crate log;
extern crate fern;
extern crate nalgebra;
use std::sync::{Arc, Mutex};
use px8::px8::math;
use px8::frontend;
use px8::gfx;
use px8::cartridge;
use px8::px8::RustPlugin;
use px8::config::Players;
use nalgebra::Vector2;
pub struct Fighter {
pub pos: Vector2<u32>,
}
impl Fighter {
fn
|
(x: u32, y: u32) -> Fighter {
Fighter {
pos: Vector2::new(x, y)
}
}
fn update(&mut self) {
}
fn draw(&mut self, screen: Arc<Mutex<gfx::Screen>>) {
screen.lock().unwrap().pset(self.pos.x as i32, self.pos.y as i32, 8);
}
}
pub struct FourmisWar {
pub sprite_filename: String,
pub fighters: Vec<Fighter>,
}
impl FourmisWar {
pub fn new(sprite_filename: String) -> FourmisWar {
FourmisWar {
sprite_filename: sprite_filename,
fighters: Vec::new(),
}
}
}
impl RustPlugin for FourmisWar {
fn init(&mut self, screen: Arc<Mutex<gfx::Screen>>) -> f64 {
self.fighters.push(Fighter::new(40, 50));
match cartridge::Cartridge::parse(self.sprite_filename.clone(), false) {
Ok(c) => screen.lock().unwrap().set_sprites(c.gfx.sprites),
Err(e) => panic!("Impossible to load the assets {:?}", e),
}
return 0.;
}
fn update(&mut self, players: Arc<Mutex<Players>>) -> f64 {
let mouse_x = players.lock().unwrap().mouse_coordinate(0);
let mouse_y = players.lock().unwrap().mouse_coordinate(1);
if players.lock().unwrap().mouse_state() == 1 {
info!("CLICK {:?} {:?}", mouse_x, mouse_y);
}
for fighter in self.fighters.iter_mut() {
fighter.update();
}
return 0.;
}
fn draw(&mut self, screen: Arc<Mutex<gfx::Screen>>) -> f64 {
screen.lock().unwrap().cls();
for fighter in self.fighters.iter_mut() {
fighter.draw(screen.clone());
}
return 0.;
}
}
fn main() {
let logger_config = fern::DispatchConfig {
format: Box::new(|msg: &str, level: &log::LogLevel, _location: &log::LogLocation| {
format!("[{}][{}] {}",
time::now().strftime("%Y-%m-%d][%H:%M:%S").unwrap(),
level,
msg)
}),
output: vec![fern::OutputConfig::stdout(),
fern::OutputConfig::file("output.log")],
level: log::LogLevelFilter::Trace,
};
if let Err(e) = fern::init_global_logger(logger_config, log::LogLevelFilter::Info) {
panic!("Failed to initialize global logger: {}", e);
}
let war = FourmisWar::new("./fourmiswar.dpx8".to_string());
let mut frontend = match frontend::Frontend::init(px8::gfx::Scale::Scale4x, false, true, true) {
Err(error) => panic!("{:?}", error),
Ok(frontend) => frontend,
};
frontend.px8.register(war);
frontend.start("./gamecontrollerdb.txt".to_string());
frontend.run_native_cartridge();
}
|
new
|
identifier_name
|
main.rs
|
extern crate px8;
extern crate sdl2;
extern crate time;
extern crate rand;
#[macro_use]
extern crate log;
extern crate fern;
extern crate nalgebra;
use std::sync::{Arc, Mutex};
use px8::px8::math;
use px8::frontend;
use px8::gfx;
use px8::cartridge;
use px8::px8::RustPlugin;
use px8::config::Players;
use nalgebra::Vector2;
pub struct Fighter {
pub pos: Vector2<u32>,
}
impl Fighter {
fn new(x: u32, y: u32) -> Fighter {
Fighter {
pos: Vector2::new(x, y)
}
}
fn update(&mut self) {
}
fn draw(&mut self, screen: Arc<Mutex<gfx::Screen>>) {
screen.lock().unwrap().pset(self.pos.x as i32, self.pos.y as i32, 8);
}
}
pub struct FourmisWar {
pub sprite_filename: String,
pub fighters: Vec<Fighter>,
}
impl FourmisWar {
pub fn new(sprite_filename: String) -> FourmisWar {
FourmisWar {
sprite_filename: sprite_filename,
fighters: Vec::new(),
}
|
self.fighters.push(Fighter::new(40, 50));
match cartridge::Cartridge::parse(self.sprite_filename.clone(), false) {
Ok(c) => screen.lock().unwrap().set_sprites(c.gfx.sprites),
Err(e) => panic!("Impossible to load the assets {:?}", e),
}
return 0.;
}
fn update(&mut self, players: Arc<Mutex<Players>>) -> f64 {
let mouse_x = players.lock().unwrap().mouse_coordinate(0);
let mouse_y = players.lock().unwrap().mouse_coordinate(1);
if players.lock().unwrap().mouse_state() == 1 {
info!("CLICK {:?} {:?}", mouse_x, mouse_y);
}
for fighter in self.fighters.iter_mut() {
fighter.update();
}
return 0.;
}
fn draw(&mut self, screen: Arc<Mutex<gfx::Screen>>) -> f64 {
screen.lock().unwrap().cls();
for fighter in self.fighters.iter_mut() {
fighter.draw(screen.clone());
}
return 0.;
}
}
fn main() {
let logger_config = fern::DispatchConfig {
format: Box::new(|msg: &str, level: &log::LogLevel, _location: &log::LogLocation| {
format!("[{}][{}] {}",
time::now().strftime("%Y-%m-%d][%H:%M:%S").unwrap(),
level,
msg)
}),
output: vec![fern::OutputConfig::stdout(),
fern::OutputConfig::file("output.log")],
level: log::LogLevelFilter::Trace,
};
if let Err(e) = fern::init_global_logger(logger_config, log::LogLevelFilter::Info) {
panic!("Failed to initialize global logger: {}", e);
}
let war = FourmisWar::new("./fourmiswar.dpx8".to_string());
let mut frontend = match frontend::Frontend::init(px8::gfx::Scale::Scale4x, false, true, true) {
Err(error) => panic!("{:?}", error),
Ok(frontend) => frontend,
};
frontend.px8.register(war);
frontend.start("./gamecontrollerdb.txt".to_string());
frontend.run_native_cartridge();
}
|
}
}
impl RustPlugin for FourmisWar {
fn init(&mut self, screen: Arc<Mutex<gfx::Screen>>) -> f64 {
|
random_line_split
|
decl.rs
|
use joker::track::*;
use joker::token::StringLiteral;
use id::Id;
use fun::Fun;
use patt::{Patt, CompoundPatt};
use expr::Expr;
use punc::Semi;
#[derive(Debug, PartialEq, Clone, TrackingRef, TrackingMut, Untrack)]
pub enum Import {
// ES6: more import forms
ForEffect(Option<Span>, StringLiteral)
}
#[derive(Debug, PartialEq, Clone, TrackingRef, TrackingMut, Untrack)]
pub enum
|
{
// ES6: more export forms
Var(Option<Span>, Vec<Dtor>, Semi),
Decl(Decl)
}
#[derive(Debug, PartialEq, Clone, TrackingRef, TrackingMut, Untrack)]
pub enum Decl {
Fun(Fun<Id>),
Let(Option<Span>, Vec<Dtor>, Semi),
Const(Option<Span>, Vec<ConstDtor>, Semi)
}
#[derive(Debug, PartialEq, Clone, TrackingRef, TrackingMut, Untrack)]
pub enum Dtor {
Simple(Option<Span>, Id, Option<Expr>),
Compound(Option<Span>, CompoundPatt<Id>, Expr)
}
#[derive(Debug, PartialEq, Clone, TrackingRef, TrackingMut, Untrack)]
pub struct ConstDtor {
pub location: Option<Span>,
pub patt: Patt<Id>,
pub value: Expr
}
pub trait DtorExt: Sized {
fn from_simple_init(Id, Expr) -> Self;
fn from_compound_init(CompoundPatt<Id>, Expr) -> Self;
fn from_init(Patt<Id>, Expr) -> Self;
fn from_init_opt(Patt<Id>, Option<Expr>) -> Result<Self, Patt<Id>>;
}
impl DtorExt for Dtor {
fn from_compound_init(lhs: CompoundPatt<Id>, rhs: Expr) -> Dtor {
Dtor::Compound(span(&lhs, &rhs), lhs, rhs)
}
fn from_simple_init(lhs: Id, rhs: Expr) -> Dtor {
Dtor::Simple(span(&lhs, &rhs), lhs, Some(rhs))
}
fn from_init(lhs: Patt<Id>, rhs: Expr) -> Dtor {
match lhs {
Patt::Simple(id) => Dtor::from_simple_init(id, rhs),
Patt::Compound(patt) => Dtor::from_compound_init(patt, rhs)
}
}
fn from_init_opt(lhs: Patt<Id>, rhs: Option<Expr>) -> Result<Dtor, Patt<Id>> {
match (lhs, rhs) {
(Patt::Simple(id), rhs) => {
Ok(Dtor::Simple(*id.tracking_ref(), id, rhs))
}
(lhs @ Patt::Compound(_), None) => Err(lhs),
(Patt::Compound(patt), Some(rhs)) => {
Ok(Dtor::from_compound_init(patt, rhs))
}
}
}
}
impl DtorExt for ConstDtor {
fn from_compound_init(lhs: CompoundPatt<Id>, rhs: Expr) -> ConstDtor {
ConstDtor::from_init(Patt::Compound(lhs), rhs)
}
fn from_simple_init(lhs: Id, rhs: Expr) -> ConstDtor {
ConstDtor::from_init(Patt::Simple(lhs), rhs)
}
fn from_init(lhs: Patt<Id>, rhs: Expr) -> ConstDtor {
ConstDtor {
location: span(&lhs, &rhs),
patt: lhs,
value: rhs
}
}
fn from_init_opt(lhs: Patt<Id>, rhs: Option<Expr>) -> Result<ConstDtor, Patt<Id>> {
match rhs {
Some(rhs) => Ok(ConstDtor::from_init(lhs, rhs)),
None => Err(lhs)
}
}
}
|
Export
|
identifier_name
|
decl.rs
|
use joker::track::*;
use joker::token::StringLiteral;
use id::Id;
use fun::Fun;
use patt::{Patt, CompoundPatt};
use expr::Expr;
use punc::Semi;
#[derive(Debug, PartialEq, Clone, TrackingRef, TrackingMut, Untrack)]
pub enum Import {
// ES6: more import forms
ForEffect(Option<Span>, StringLiteral)
}
#[derive(Debug, PartialEq, Clone, TrackingRef, TrackingMut, Untrack)]
pub enum Export {
// ES6: more export forms
Var(Option<Span>, Vec<Dtor>, Semi),
Decl(Decl)
}
#[derive(Debug, PartialEq, Clone, TrackingRef, TrackingMut, Untrack)]
pub enum Decl {
Fun(Fun<Id>),
Let(Option<Span>, Vec<Dtor>, Semi),
Const(Option<Span>, Vec<ConstDtor>, Semi)
}
#[derive(Debug, PartialEq, Clone, TrackingRef, TrackingMut, Untrack)]
pub enum Dtor {
Simple(Option<Span>, Id, Option<Expr>),
Compound(Option<Span>, CompoundPatt<Id>, Expr)
}
#[derive(Debug, PartialEq, Clone, TrackingRef, TrackingMut, Untrack)]
pub struct ConstDtor {
pub location: Option<Span>,
pub patt: Patt<Id>,
pub value: Expr
}
pub trait DtorExt: Sized {
fn from_simple_init(Id, Expr) -> Self;
fn from_compound_init(CompoundPatt<Id>, Expr) -> Self;
fn from_init(Patt<Id>, Expr) -> Self;
fn from_init_opt(Patt<Id>, Option<Expr>) -> Result<Self, Patt<Id>>;
}
impl DtorExt for Dtor {
fn from_compound_init(lhs: CompoundPatt<Id>, rhs: Expr) -> Dtor {
Dtor::Compound(span(&lhs, &rhs), lhs, rhs)
}
fn from_simple_init(lhs: Id, rhs: Expr) -> Dtor {
Dtor::Simple(span(&lhs, &rhs), lhs, Some(rhs))
}
fn from_init(lhs: Patt<Id>, rhs: Expr) -> Dtor {
match lhs {
Patt::Simple(id) => Dtor::from_simple_init(id, rhs),
Patt::Compound(patt) => Dtor::from_compound_init(patt, rhs)
}
}
fn from_init_opt(lhs: Patt<Id>, rhs: Option<Expr>) -> Result<Dtor, Patt<Id>> {
match (lhs, rhs) {
(Patt::Simple(id), rhs) => {
Ok(Dtor::Simple(*id.tracking_ref(), id, rhs))
}
|
(lhs @ Patt::Compound(_), None) => Err(lhs),
(Patt::Compound(patt), Some(rhs)) => {
Ok(Dtor::from_compound_init(patt, rhs))
}
}
}
}
impl DtorExt for ConstDtor {
fn from_compound_init(lhs: CompoundPatt<Id>, rhs: Expr) -> ConstDtor {
ConstDtor::from_init(Patt::Compound(lhs), rhs)
}
fn from_simple_init(lhs: Id, rhs: Expr) -> ConstDtor {
ConstDtor::from_init(Patt::Simple(lhs), rhs)
}
fn from_init(lhs: Patt<Id>, rhs: Expr) -> ConstDtor {
ConstDtor {
location: span(&lhs, &rhs),
patt: lhs,
value: rhs
}
}
fn from_init_opt(lhs: Patt<Id>, rhs: Option<Expr>) -> Result<ConstDtor, Patt<Id>> {
match rhs {
Some(rhs) => Ok(ConstDtor::from_init(lhs, rhs)),
None => Err(lhs)
}
}
}
|
random_line_split
|
|
3_07_oscillating_objects.rs
|
// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Example 5-07: Oscillating Objects
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
// An array of type Oscillator
oscillators: Vec<Oscillator>,
}
#[derive(Clone)]
struct Oscillator {
angle: Vector2,
velocity: Vector2,
amplitude: Vector2,
}
impl Oscillator {
fn new(rect: Rect) -> Self {
let angle = vec2(0.0, 0.0);
let velocity = vec2(random_f32() * 0.1 - 0.05, random_f32() * 0.1 - 0.05);
let rand_amp_x = random_range(20.0, rect.right());
let rand_amp_y = random_range(20.0, rect.top());
let amplitude = vec2(rand_amp_x, rand_amp_y);
Oscillator {
angle,
velocity,
amplitude,
}
}
fn oscillate(&mut self) {
self.angle += self.velocity;
}
fn display(&self, draw: &Draw) {
let x = self.angle.x.sin() * self.amplitude.x;
let y = self.angle.y.sin() * self.amplitude.y;
draw.line()
.start(pt2(0.0, 0.0))
.end(pt2(x, y))
.rgb(0.0, 0.0, 0.0)
.stroke_weight(2.0);
draw.ellipse()
.x_y(x, y)
.w_h(32.0, 32.0)
|
}
fn model(app: &App) -> Model {
let rect = Rect::from_w_h(640.0, 360.0);
app.new_window()
.size(rect.w() as u32, rect.h() as u32)
.view(view)
.build()
.unwrap();
//let oscillators = vec![Oscillator::new(app.window_rect()); 10];
let oscillators = (0..10).map(|_| Oscillator::new(rect)).collect();
Model { oscillators }
}
fn update(_app: &App, m: &mut Model, _update: Update) {
for osc in &mut m.oscillators {
osc.oscillate();
}
}
fn view(app: &App, m: &Model, frame: Frame) {
// Begin drawing
let draw = app.draw();
draw.background().rgba(1.0, 1.0, 1.0, 1.0);
for osc in &m.oscillators {
osc.display(&draw);
}
// Write the result of our drawing to the window's frame.
draw.to_frame(app, &frame).unwrap();
}
|
.rgba(0.5, 0.5, 0.5, 0.5)
.stroke(BLACK)
.stroke_weight(2.0);
}
|
random_line_split
|
3_07_oscillating_objects.rs
|
// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Example 5-07: Oscillating Objects
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct
|
{
// An array of type Oscillator
oscillators: Vec<Oscillator>,
}
#[derive(Clone)]
struct Oscillator {
angle: Vector2,
velocity: Vector2,
amplitude: Vector2,
}
impl Oscillator {
fn new(rect: Rect) -> Self {
let angle = vec2(0.0, 0.0);
let velocity = vec2(random_f32() * 0.1 - 0.05, random_f32() * 0.1 - 0.05);
let rand_amp_x = random_range(20.0, rect.right());
let rand_amp_y = random_range(20.0, rect.top());
let amplitude = vec2(rand_amp_x, rand_amp_y);
Oscillator {
angle,
velocity,
amplitude,
}
}
fn oscillate(&mut self) {
self.angle += self.velocity;
}
fn display(&self, draw: &Draw) {
let x = self.angle.x.sin() * self.amplitude.x;
let y = self.angle.y.sin() * self.amplitude.y;
draw.line()
.start(pt2(0.0, 0.0))
.end(pt2(x, y))
.rgb(0.0, 0.0, 0.0)
.stroke_weight(2.0);
draw.ellipse()
.x_y(x, y)
.w_h(32.0, 32.0)
.rgba(0.5, 0.5, 0.5, 0.5)
.stroke(BLACK)
.stroke_weight(2.0);
}
}
fn model(app: &App) -> Model {
let rect = Rect::from_w_h(640.0, 360.0);
app.new_window()
.size(rect.w() as u32, rect.h() as u32)
.view(view)
.build()
.unwrap();
//let oscillators = vec![Oscillator::new(app.window_rect()); 10];
let oscillators = (0..10).map(|_| Oscillator::new(rect)).collect();
Model { oscillators }
}
fn update(_app: &App, m: &mut Model, _update: Update) {
for osc in &mut m.oscillators {
osc.oscillate();
}
}
fn view(app: &App, m: &Model, frame: Frame) {
// Begin drawing
let draw = app.draw();
draw.background().rgba(1.0, 1.0, 1.0, 1.0);
for osc in &m.oscillators {
osc.display(&draw);
}
// Write the result of our drawing to the window's frame.
draw.to_frame(app, &frame).unwrap();
}
|
Model
|
identifier_name
|
3_07_oscillating_objects.rs
|
// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Example 5-07: Oscillating Objects
use nannou::prelude::*;
fn main()
|
struct Model {
// An array of type Oscillator
oscillators: Vec<Oscillator>,
}
#[derive(Clone)]
struct Oscillator {
angle: Vector2,
velocity: Vector2,
amplitude: Vector2,
}
impl Oscillator {
fn new(rect: Rect) -> Self {
let angle = vec2(0.0, 0.0);
let velocity = vec2(random_f32() * 0.1 - 0.05, random_f32() * 0.1 - 0.05);
let rand_amp_x = random_range(20.0, rect.right());
let rand_amp_y = random_range(20.0, rect.top());
let amplitude = vec2(rand_amp_x, rand_amp_y);
Oscillator {
angle,
velocity,
amplitude,
}
}
fn oscillate(&mut self) {
self.angle += self.velocity;
}
fn display(&self, draw: &Draw) {
let x = self.angle.x.sin() * self.amplitude.x;
let y = self.angle.y.sin() * self.amplitude.y;
draw.line()
.start(pt2(0.0, 0.0))
.end(pt2(x, y))
.rgb(0.0, 0.0, 0.0)
.stroke_weight(2.0);
draw.ellipse()
.x_y(x, y)
.w_h(32.0, 32.0)
.rgba(0.5, 0.5, 0.5, 0.5)
.stroke(BLACK)
.stroke_weight(2.0);
}
}
fn model(app: &App) -> Model {
let rect = Rect::from_w_h(640.0, 360.0);
app.new_window()
.size(rect.w() as u32, rect.h() as u32)
.view(view)
.build()
.unwrap();
//let oscillators = vec![Oscillator::new(app.window_rect()); 10];
let oscillators = (0..10).map(|_| Oscillator::new(rect)).collect();
Model { oscillators }
}
fn update(_app: &App, m: &mut Model, _update: Update) {
for osc in &mut m.oscillators {
osc.oscillate();
}
}
fn view(app: &App, m: &Model, frame: Frame) {
// Begin drawing
let draw = app.draw();
draw.background().rgba(1.0, 1.0, 1.0, 1.0);
for osc in &m.oscillators {
osc.display(&draw);
}
// Write the result of our drawing to the window's frame.
draw.to_frame(app, &frame).unwrap();
}
|
{
nannou::app(model).update(update).run();
}
|
identifier_body
|
main.rs
|
use std::io;
struct PrioData {
lists: Vec<PrioList>,
}
struct PrioList {
name: String,
items: Vec<String>,
}
impl PrioList {
fn new(name: &str, items: Vec<String>) -> PrioList {
PrioList {
name: name.to_string(),
items: items.clone(),
}
}
fn add_item(&mut self, new_item: &str)
|
}
fn main() {
let mut data = PrioData {
lists: vec![PrioList::new("High", vec!["something".to_string(), "something else".to_string()])]
};
loop {
let prompt = "What do you want to do? (Type \"back\" at any time to return to the previos menu)";
let choices = vec![
"1. View priority lists".to_string(),
"2. Create a new priority".to_string(),
];
let desire = switch_board(prompt, choices);
match desire.as_ref() {
"1" => {view_priority_lists(&mut data);},
"2" => {create_priority_list(&mut data);},
"back" => {break;},
_ => {println!("Please enter a valid number!");},
}
}
}
fn view_priority_lists(data: &mut PrioData) {
if data.lists.len() == 0 {
println!("You have no lists!");
}
else {
loop {
let mut choices: Vec<String> = vec![];
let mut index = 0;
for list in &data.lists {
index += 1;
let mut text = index.to_string();
text.push_str(". ");
text.push_str(&list.name);
choices.push(text);
}
println!("");
let prompt = "Which list do you want to view?";
let desire = switch_board(prompt, choices);
if desire == "back" {
break;
}
let mut index: usize = desire.parse().unwrap();
index -= 1;
view_list(&mut data.lists[index]);
}
}
}
fn view_list(list: &mut PrioList) {
loop {
println!("\n--{}--", list.name);
for item in &list.items {
println!("{}", item);
}
println!("\nEnter a new item");
let new_item = read_line();
if new_item == "back" {
break;
}
list.add_item(&new_item);
}
}
fn create_priority_list(data: &PrioData) {
println!("create list!");
}
fn switch_board(prompt: &str, choices: Vec<String>) -> String {
println!("\n{}", prompt);
for choice in choices {
println!("{}", choice);
}
let choice = read_line();
choice.to_string()
}
fn read_line() -> String{
let mut line = String::new();
io::stdin().read_line(&mut line)
.ok()
.expect("Failed to read line");
line.trim().to_string()
}
|
{
self.items.push(new_item.to_string());
}
|
identifier_body
|
main.rs
|
use std::io;
struct PrioData {
lists: Vec<PrioList>,
}
struct PrioList {
name: String,
items: Vec<String>,
}
impl PrioList {
fn new(name: &str, items: Vec<String>) -> PrioList {
PrioList {
name: name.to_string(),
items: items.clone(),
}
}
fn add_item(&mut self, new_item: &str) {
self.items.push(new_item.to_string());
}
}
fn main() {
let mut data = PrioData {
lists: vec![PrioList::new("High", vec!["something".to_string(), "something else".to_string()])]
};
loop {
let prompt = "What do you want to do? (Type \"back\" at any time to return to the previos menu)";
let choices = vec![
"1. View priority lists".to_string(),
"2. Create a new priority".to_string(),
];
let desire = switch_board(prompt, choices);
match desire.as_ref() {
"1" => {view_priority_lists(&mut data);},
"2" => {create_priority_list(&mut data);},
"back" => {break;},
_ => {println!("Please enter a valid number!");},
}
}
}
fn view_priority_lists(data: &mut PrioData) {
if data.lists.len() == 0 {
println!("You have no lists!");
}
else {
loop {
let mut choices: Vec<String> = vec![];
let mut index = 0;
for list in &data.lists {
index += 1;
let mut text = index.to_string();
text.push_str(". ");
text.push_str(&list.name);
choices.push(text);
}
println!("");
let prompt = "Which list do you want to view?";
let desire = switch_board(prompt, choices);
if desire == "back" {
break;
}
let mut index: usize = desire.parse().unwrap();
index -= 1;
view_list(&mut data.lists[index]);
}
}
}
fn view_list(list: &mut PrioList) {
loop {
println!("\n--{}--", list.name);
for item in &list.items {
println!("{}", item);
}
println!("\nEnter a new item");
let new_item = read_line();
|
if new_item == "back" {
break;
}
list.add_item(&new_item);
}
}
fn create_priority_list(data: &PrioData) {
println!("create list!");
}
fn switch_board(prompt: &str, choices: Vec<String>) -> String {
println!("\n{}", prompt);
for choice in choices {
println!("{}", choice);
}
let choice = read_line();
choice.to_string()
}
fn read_line() -> String{
let mut line = String::new();
io::stdin().read_line(&mut line)
.ok()
.expect("Failed to read line");
line.trim().to_string()
}
|
random_line_split
|
|
main.rs
|
use std::io;
struct PrioData {
lists: Vec<PrioList>,
}
struct PrioList {
name: String,
items: Vec<String>,
}
impl PrioList {
fn new(name: &str, items: Vec<String>) -> PrioList {
PrioList {
name: name.to_string(),
items: items.clone(),
}
}
fn add_item(&mut self, new_item: &str) {
self.items.push(new_item.to_string());
}
}
fn main() {
let mut data = PrioData {
lists: vec![PrioList::new("High", vec!["something".to_string(), "something else".to_string()])]
};
loop {
let prompt = "What do you want to do? (Type \"back\" at any time to return to the previos menu)";
let choices = vec![
"1. View priority lists".to_string(),
"2. Create a new priority".to_string(),
];
let desire = switch_board(prompt, choices);
match desire.as_ref() {
"1" => {view_priority_lists(&mut data);},
"2" => {create_priority_list(&mut data);},
"back" => {break;},
_ => {println!("Please enter a valid number!");},
}
}
}
fn view_priority_lists(data: &mut PrioData) {
if data.lists.len() == 0 {
println!("You have no lists!");
}
else {
loop {
let mut choices: Vec<String> = vec![];
let mut index = 0;
for list in &data.lists {
index += 1;
let mut text = index.to_string();
text.push_str(". ");
text.push_str(&list.name);
choices.push(text);
}
println!("");
let prompt = "Which list do you want to view?";
let desire = switch_board(prompt, choices);
if desire == "back" {
break;
}
let mut index: usize = desire.parse().unwrap();
index -= 1;
view_list(&mut data.lists[index]);
}
}
}
fn view_list(list: &mut PrioList) {
loop {
println!("\n--{}--", list.name);
for item in &list.items {
println!("{}", item);
}
println!("\nEnter a new item");
let new_item = read_line();
if new_item == "back" {
break;
}
list.add_item(&new_item);
}
}
fn create_priority_list(data: &PrioData) {
println!("create list!");
}
fn
|
(prompt: &str, choices: Vec<String>) -> String {
println!("\n{}", prompt);
for choice in choices {
println!("{}", choice);
}
let choice = read_line();
choice.to_string()
}
fn read_line() -> String{
let mut line = String::new();
io::stdin().read_line(&mut line)
.ok()
.expect("Failed to read line");
line.trim().to_string()
}
|
switch_board
|
identifier_name
|
layout_debug.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Supports writing a trace file created during each layout scope
//! that can be viewed by an external tool to make layout debugging easier.
#![macro_escape]
use flow_ref::FlowRef;
use serialize::json;
use std::cell::RefCell;
use std::io::File;
use std::sync::atomics::{AtomicUint, SeqCst, INIT_ATOMIC_UINT};
local_data_key!(state_key: RefCell<State>)
static mut DEBUG_ID_COUNTER: AtomicUint = INIT_ATOMIC_UINT;
pub struct Scope;
#[macro_export]
macro_rules! layout_debug_scope(
($($arg:tt)*) => (
if cfg!(not(ndebug)) {
layout_debug::Scope::new(format!($($arg)*))
} else {
layout_debug::Scope
}
)
)
#[deriving(Encodable)]
struct ScopeData {
name: String,
pre: String,
post: String,
children: Vec<Box<ScopeData>>,
}
impl ScopeData {
fn new(name: String, pre: String) -> ScopeData {
ScopeData {
name: name,
pre: pre,
post: String::new(),
children: vec!(),
}
}
}
struct State {
flow_root: FlowRef,
scope_stack: Vec<Box<ScopeData>>,
}
/// A layout debugging scope. The entire state of the flow tree
/// will be output at the beginning and end of this scope.
impl Scope {
pub fn new(name: String) -> Scope {
let maybe_refcell = state_key.get();
match maybe_refcell {
Some(refcell) => {
let mut state = refcell.borrow_mut();
let flow_trace = json::encode(&state.flow_root.deref());
let data = box ScopeData::new(name, flow_trace);
state.scope_stack.push(data);
}
None => {}
}
Scope
}
}
#[cfg(not(ndebug))]
impl Drop for Scope {
fn drop(&mut self) {
let maybe_refcell = state_key.get();
match maybe_refcell {
Some(refcell) => {
let mut state = refcell.borrow_mut();
let mut current_scope = state.scope_stack.pop().unwrap();
current_scope.post = json::encode(&state.flow_root.deref());
let previous_scope = state.scope_stack.last_mut().unwrap();
previous_scope.children.push(current_scope);
}
None => {}
}
}
}
/// Generate a unique ID. This is used for items such as Fragment
/// which are often reallocated but represent essentially the
/// same data.
pub fn generate_unique_debug_id() -> u16
|
/// Begin a layout debug trace. If this has not been called,
/// creating debug scopes has no effect.
pub fn begin_trace(flow_root: FlowRef) {
assert!(state_key.get().is_none());
let flow_trace = json::encode(&flow_root.deref());
let state = State {
scope_stack: vec![box ScopeData::new("root".to_string(), flow_trace)],
flow_root: flow_root,
};
state_key.replace(Some(RefCell::new(state)));
}
/// End the debug layout trace. This will write the layout
/// trace to disk in the current directory. The output
/// file can then be viewed with an external tool.
pub fn end_trace() {
let task_state_cell = state_key.replace(None).unwrap();
let mut task_state = task_state_cell.borrow_mut();
assert!(task_state.scope_stack.len() == 1);
let mut root_scope = task_state.scope_stack.pop().unwrap();
root_scope.post = json::encode(&task_state.flow_root.deref());
let result = json::encode(&root_scope);
let path = Path::new("layout_trace.json");
let mut file = File::create(&path).unwrap();
file.write_str(result.as_slice()).unwrap();
}
|
{
unsafe { DEBUG_ID_COUNTER.fetch_add(1, SeqCst) as u16 }
}
|
identifier_body
|
layout_debug.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Supports writing a trace file created during each layout scope
//! that can be viewed by an external tool to make layout debugging easier.
#![macro_escape]
use flow_ref::FlowRef;
use serialize::json;
use std::cell::RefCell;
use std::io::File;
use std::sync::atomics::{AtomicUint, SeqCst, INIT_ATOMIC_UINT};
local_data_key!(state_key: RefCell<State>)
static mut DEBUG_ID_COUNTER: AtomicUint = INIT_ATOMIC_UINT;
pub struct
|
;
#[macro_export]
macro_rules! layout_debug_scope(
($($arg:tt)*) => (
if cfg!(not(ndebug)) {
layout_debug::Scope::new(format!($($arg)*))
} else {
layout_debug::Scope
}
)
)
#[deriving(Encodable)]
struct ScopeData {
name: String,
pre: String,
post: String,
children: Vec<Box<ScopeData>>,
}
impl ScopeData {
fn new(name: String, pre: String) -> ScopeData {
ScopeData {
name: name,
pre: pre,
post: String::new(),
children: vec!(),
}
}
}
struct State {
flow_root: FlowRef,
scope_stack: Vec<Box<ScopeData>>,
}
/// A layout debugging scope. The entire state of the flow tree
/// will be output at the beginning and end of this scope.
impl Scope {
pub fn new(name: String) -> Scope {
let maybe_refcell = state_key.get();
match maybe_refcell {
Some(refcell) => {
let mut state = refcell.borrow_mut();
let flow_trace = json::encode(&state.flow_root.deref());
let data = box ScopeData::new(name, flow_trace);
state.scope_stack.push(data);
}
None => {}
}
Scope
}
}
#[cfg(not(ndebug))]
impl Drop for Scope {
fn drop(&mut self) {
let maybe_refcell = state_key.get();
match maybe_refcell {
Some(refcell) => {
let mut state = refcell.borrow_mut();
let mut current_scope = state.scope_stack.pop().unwrap();
current_scope.post = json::encode(&state.flow_root.deref());
let previous_scope = state.scope_stack.last_mut().unwrap();
previous_scope.children.push(current_scope);
}
None => {}
}
}
}
/// Generate a unique ID. This is used for items such as Fragment
/// which are often reallocated but represent essentially the
/// same data.
pub fn generate_unique_debug_id() -> u16 {
unsafe { DEBUG_ID_COUNTER.fetch_add(1, SeqCst) as u16 }
}
/// Begin a layout debug trace. If this has not been called,
/// creating debug scopes has no effect.
pub fn begin_trace(flow_root: FlowRef) {
assert!(state_key.get().is_none());
let flow_trace = json::encode(&flow_root.deref());
let state = State {
scope_stack: vec![box ScopeData::new("root".to_string(), flow_trace)],
flow_root: flow_root,
};
state_key.replace(Some(RefCell::new(state)));
}
/// End the debug layout trace. This will write the layout
/// trace to disk in the current directory. The output
/// file can then be viewed with an external tool.
pub fn end_trace() {
let task_state_cell = state_key.replace(None).unwrap();
let mut task_state = task_state_cell.borrow_mut();
assert!(task_state.scope_stack.len() == 1);
let mut root_scope = task_state.scope_stack.pop().unwrap();
root_scope.post = json::encode(&task_state.flow_root.deref());
let result = json::encode(&root_scope);
let path = Path::new("layout_trace.json");
let mut file = File::create(&path).unwrap();
file.write_str(result.as_slice()).unwrap();
}
|
Scope
|
identifier_name
|
layout_debug.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Supports writing a trace file created during each layout scope
//! that can be viewed by an external tool to make layout debugging easier.
#![macro_escape]
use flow_ref::FlowRef;
use serialize::json;
use std::cell::RefCell;
use std::io::File;
use std::sync::atomics::{AtomicUint, SeqCst, INIT_ATOMIC_UINT};
local_data_key!(state_key: RefCell<State>)
static mut DEBUG_ID_COUNTER: AtomicUint = INIT_ATOMIC_UINT;
pub struct Scope;
#[macro_export]
macro_rules! layout_debug_scope(
($($arg:tt)*) => (
if cfg!(not(ndebug)) {
layout_debug::Scope::new(format!($($arg)*))
} else {
layout_debug::Scope
}
)
)
#[deriving(Encodable)]
struct ScopeData {
name: String,
pre: String,
post: String,
children: Vec<Box<ScopeData>>,
}
impl ScopeData {
fn new(name: String, pre: String) -> ScopeData {
ScopeData {
name: name,
pre: pre,
post: String::new(),
children: vec!(),
}
}
}
struct State {
flow_root: FlowRef,
scope_stack: Vec<Box<ScopeData>>,
}
/// A layout debugging scope. The entire state of the flow tree
/// will be output at the beginning and end of this scope.
impl Scope {
pub fn new(name: String) -> Scope {
let maybe_refcell = state_key.get();
match maybe_refcell {
Some(refcell) => {
let mut state = refcell.borrow_mut();
let flow_trace = json::encode(&state.flow_root.deref());
let data = box ScopeData::new(name, flow_trace);
state.scope_stack.push(data);
}
None => {}
}
Scope
}
}
#[cfg(not(ndebug))]
impl Drop for Scope {
fn drop(&mut self) {
let maybe_refcell = state_key.get();
match maybe_refcell {
Some(refcell) => {
let mut state = refcell.borrow_mut();
let mut current_scope = state.scope_stack.pop().unwrap();
current_scope.post = json::encode(&state.flow_root.deref());
let previous_scope = state.scope_stack.last_mut().unwrap();
previous_scope.children.push(current_scope);
}
None => {}
}
}
}
/// Generate a unique ID. This is used for items such as Fragment
/// which are often reallocated but represent essentially the
/// same data.
pub fn generate_unique_debug_id() -> u16 {
unsafe { DEBUG_ID_COUNTER.fetch_add(1, SeqCst) as u16 }
}
/// Begin a layout debug trace. If this has not been called,
/// creating debug scopes has no effect.
|
pub fn begin_trace(flow_root: FlowRef) {
assert!(state_key.get().is_none());
let flow_trace = json::encode(&flow_root.deref());
let state = State {
scope_stack: vec![box ScopeData::new("root".to_string(), flow_trace)],
flow_root: flow_root,
};
state_key.replace(Some(RefCell::new(state)));
}
/// End the debug layout trace. This will write the layout
/// trace to disk in the current directory. The output
/// file can then be viewed with an external tool.
pub fn end_trace() {
let task_state_cell = state_key.replace(None).unwrap();
let mut task_state = task_state_cell.borrow_mut();
assert!(task_state.scope_stack.len() == 1);
let mut root_scope = task_state.scope_stack.pop().unwrap();
root_scope.post = json::encode(&task_state.flow_root.deref());
let result = json::encode(&root_scope);
let path = Path::new("layout_trace.json");
let mut file = File::create(&path).unwrap();
file.write_str(result.as_slice()).unwrap();
}
|
random_line_split
|
|
layout_debug.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Supports writing a trace file created during each layout scope
//! that can be viewed by an external tool to make layout debugging easier.
#![macro_escape]
use flow_ref::FlowRef;
use serialize::json;
use std::cell::RefCell;
use std::io::File;
use std::sync::atomics::{AtomicUint, SeqCst, INIT_ATOMIC_UINT};
local_data_key!(state_key: RefCell<State>)
static mut DEBUG_ID_COUNTER: AtomicUint = INIT_ATOMIC_UINT;
pub struct Scope;
#[macro_export]
macro_rules! layout_debug_scope(
($($arg:tt)*) => (
if cfg!(not(ndebug)) {
layout_debug::Scope::new(format!($($arg)*))
} else {
layout_debug::Scope
}
)
)
#[deriving(Encodable)]
struct ScopeData {
name: String,
pre: String,
post: String,
children: Vec<Box<ScopeData>>,
}
impl ScopeData {
fn new(name: String, pre: String) -> ScopeData {
ScopeData {
name: name,
pre: pre,
post: String::new(),
children: vec!(),
}
}
}
struct State {
flow_root: FlowRef,
scope_stack: Vec<Box<ScopeData>>,
}
/// A layout debugging scope. The entire state of the flow tree
/// will be output at the beginning and end of this scope.
impl Scope {
pub fn new(name: String) -> Scope {
let maybe_refcell = state_key.get();
match maybe_refcell {
Some(refcell) => {
let mut state = refcell.borrow_mut();
let flow_trace = json::encode(&state.flow_root.deref());
let data = box ScopeData::new(name, flow_trace);
state.scope_stack.push(data);
}
None =>
|
}
Scope
}
}
#[cfg(not(ndebug))]
impl Drop for Scope {
fn drop(&mut self) {
let maybe_refcell = state_key.get();
match maybe_refcell {
Some(refcell) => {
let mut state = refcell.borrow_mut();
let mut current_scope = state.scope_stack.pop().unwrap();
current_scope.post = json::encode(&state.flow_root.deref());
let previous_scope = state.scope_stack.last_mut().unwrap();
previous_scope.children.push(current_scope);
}
None => {}
}
}
}
/// Generate a unique ID. This is used for items such as Fragment
/// which are often reallocated but represent essentially the
/// same data.
pub fn generate_unique_debug_id() -> u16 {
unsafe { DEBUG_ID_COUNTER.fetch_add(1, SeqCst) as u16 }
}
/// Begin a layout debug trace. If this has not been called,
/// creating debug scopes has no effect.
pub fn begin_trace(flow_root: FlowRef) {
assert!(state_key.get().is_none());
let flow_trace = json::encode(&flow_root.deref());
let state = State {
scope_stack: vec![box ScopeData::new("root".to_string(), flow_trace)],
flow_root: flow_root,
};
state_key.replace(Some(RefCell::new(state)));
}
/// End the debug layout trace. This will write the layout
/// trace to disk in the current directory. The output
/// file can then be viewed with an external tool.
pub fn end_trace() {
let task_state_cell = state_key.replace(None).unwrap();
let mut task_state = task_state_cell.borrow_mut();
assert!(task_state.scope_stack.len() == 1);
let mut root_scope = task_state.scope_stack.pop().unwrap();
root_scope.post = json::encode(&task_state.flow_root.deref());
let result = json::encode(&root_scope);
let path = Path::new("layout_trace.json");
let mut file = File::create(&path).unwrap();
file.write_str(result.as_slice()).unwrap();
}
|
{}
|
conditional_block
|
main.rs
|
#![cfg(not(test))]
extern crate zaldinar;
extern crate getopts;
macro_rules! print_err {
($($arg:tt)*) => (
{
use std::io::prelude::*;
if let Err(e) = write!(&mut ::std::io::stderr(), "{}\n", format_args!($($arg)*)) {
panic!("Failed to write to stderr.\
\nOriginal error output: {}\
\nSecondary error writing to stderr: {}", format!($($arg)*), e);
}
}
)
}
#[cfg(feature = "binary-filewatch")]
extern crate libc;
#[cfg(feature = "binary-filewatch")]
mod execv_linux;
use std::env;
use std::io;
use std::path::PathBuf;
use std::path::Path;
#[cfg(feature = "binary-filewatch")]
use execv_linux::execv_if_possible;
const UNKNOWN_EXECUTABLE: &'static str = "<unknown executable>";
#[cfg(not(feature = "binary-filewatch"))]
fn execv_if_possible(_program_path: &Path) -> i32 {
println!("Can't restart using execv on this platform!");
return 1;
}
fn get_program() -> io::Result<PathBuf> {
// This joins current_dir() and current_exe(), resulting in an absolute path to of the current
// executable
let mut buf = try!(env::current_dir());
buf.push(&try!(env::current_exe()));
return Ok(buf);
}
fn
|
() {
let result = main_exits();
std::process::exit(result);
}
/// Separate function from main to ensure that everything is cleaned up by exiting scope before
/// program exits using std::process::exit();
fn main_exits() -> i32 {
// Because env::current_exe() will change if the executing file is moved, we need to get the
// original program path as soon as we start.
// We have two `program` variables because we still want to use the program gotten from
// env::args() to print help strings.
let original_program = match get_program() {
Ok(v) => v,
Err(e) => {
print_err!("Warning: failed to find current executable: {}", e);
PathBuf::from(UNKNOWN_EXECUTABLE)
}
};
let mut args = env::args();
let display_program = match args.next() {
// TODO: some error catching of lossy strings here or not?
Some(v) => v,
None => original_program.as_os_str().to_string_lossy().into_owned(),
};
let mut opts = getopts::Options::new();
opts.optopt("c", "config", "set config file name", "FILE");
opts.optflag("h", "help", "print this help menu");
opts.optflag("v", "version", "print program version");
// TODO: Bug getopts to use OsString
let matches = match opts.parse(args.collect::<Vec<String>>()) {
Ok(v) => v,
Err(e) => {
print_err!("{}", e.to_string());
return 0;
}
};
if matches.opt_present("help") {
let brief = format!("Usage: {} [options]", display_program);
println!("{}", opts.usage(&brief));
return 0;
} else if matches.opt_present("version") {
println!("zaldinar version {}", zaldinar::VERSION);
return 0;
}
let current_dir = match env::current_dir() {
Ok(v) => v,
Err(e) => {
print_err!("Warning: failed to get current directory: {}", e);
PathBuf::from("") // TODO: return here or just not be absolute?
}
};
let config_path = match matches.opt_str("config") {
Some(v) => {
let absolute = current_dir.join(&Path::new(&v));
println!("Using configuration: {}", absolute.display());
absolute
},
None => current_dir.join(Path::new("config.json")),
};
loop {
let config = match zaldinar::ClientConfiguration::load_from_file(&config_path) {
Ok(v) => v,
Err(e) => {
print_err!("Error loading configuration from `{}`: {}", config_path.display(), e);
return 1;
},
};
match zaldinar::run(config) {
Ok(zaldinar::client::ExecutingState::Done) => {
println!("Done, exiting.");
break
},
Ok(zaldinar::client::ExecutingState::Running)
| Ok(zaldinar::client::ExecutingState::RestartNoExec) => {
println!("Restarting zaldinar main loop.");
continue;
},
Ok(zaldinar::client::ExecutingState::RestartExec) => {
println!("Restarting zaldinar using exec.");
let result = execv_if_possible(&original_program);
return result;
},
Ok(zaldinar::client::ExecutingState::RestartTryExec) => {
println!("Restarting zaldinar using exec.");
execv_if_possible(&original_program);
println!("Restarting using exec failed, restarting main loop.");
continue;
}
Err(e) => {
print_err!("Error running client: {}", e);
return 1;
},
};
}
return 0;
}
|
main
|
identifier_name
|
main.rs
|
#![cfg(not(test))]
extern crate zaldinar;
extern crate getopts;
macro_rules! print_err {
($($arg:tt)*) => (
{
use std::io::prelude::*;
if let Err(e) = write!(&mut ::std::io::stderr(), "{}\n", format_args!($($arg)*)) {
panic!("Failed to write to stderr.\
\nOriginal error output: {}\
\nSecondary error writing to stderr: {}", format!($($arg)*), e);
}
}
)
}
#[cfg(feature = "binary-filewatch")]
extern crate libc;
#[cfg(feature = "binary-filewatch")]
mod execv_linux;
use std::env;
use std::io;
use std::path::PathBuf;
use std::path::Path;
#[cfg(feature = "binary-filewatch")]
use execv_linux::execv_if_possible;
const UNKNOWN_EXECUTABLE: &'static str = "<unknown executable>";
#[cfg(not(feature = "binary-filewatch"))]
fn execv_if_possible(_program_path: &Path) -> i32
|
fn get_program() -> io::Result<PathBuf> {
// This joins current_dir() and current_exe(), resulting in an absolute path to of the current
// executable
let mut buf = try!(env::current_dir());
buf.push(&try!(env::current_exe()));
return Ok(buf);
}
fn main() {
let result = main_exits();
std::process::exit(result);
}
/// Separate function from main to ensure that everything is cleaned up by exiting scope before
/// program exits using std::process::exit();
fn main_exits() -> i32 {
// Because env::current_exe() will change if the executing file is moved, we need to get the
// original program path as soon as we start.
// We have two `program` variables because we still want to use the program gotten from
// env::args() to print help strings.
let original_program = match get_program() {
Ok(v) => v,
Err(e) => {
print_err!("Warning: failed to find current executable: {}", e);
PathBuf::from(UNKNOWN_EXECUTABLE)
}
};
let mut args = env::args();
let display_program = match args.next() {
// TODO: some error catching of lossy strings here or not?
Some(v) => v,
None => original_program.as_os_str().to_string_lossy().into_owned(),
};
let mut opts = getopts::Options::new();
opts.optopt("c", "config", "set config file name", "FILE");
opts.optflag("h", "help", "print this help menu");
opts.optflag("v", "version", "print program version");
// TODO: Bug getopts to use OsString
let matches = match opts.parse(args.collect::<Vec<String>>()) {
Ok(v) => v,
Err(e) => {
print_err!("{}", e.to_string());
return 0;
}
};
if matches.opt_present("help") {
let brief = format!("Usage: {} [options]", display_program);
println!("{}", opts.usage(&brief));
return 0;
} else if matches.opt_present("version") {
println!("zaldinar version {}", zaldinar::VERSION);
return 0;
}
let current_dir = match env::current_dir() {
Ok(v) => v,
Err(e) => {
print_err!("Warning: failed to get current directory: {}", e);
PathBuf::from("") // TODO: return here or just not be absolute?
}
};
let config_path = match matches.opt_str("config") {
Some(v) => {
let absolute = current_dir.join(&Path::new(&v));
println!("Using configuration: {}", absolute.display());
absolute
},
None => current_dir.join(Path::new("config.json")),
};
loop {
let config = match zaldinar::ClientConfiguration::load_from_file(&config_path) {
Ok(v) => v,
Err(e) => {
print_err!("Error loading configuration from `{}`: {}", config_path.display(), e);
return 1;
},
};
match zaldinar::run(config) {
Ok(zaldinar::client::ExecutingState::Done) => {
println!("Done, exiting.");
break
},
Ok(zaldinar::client::ExecutingState::Running)
| Ok(zaldinar::client::ExecutingState::RestartNoExec) => {
println!("Restarting zaldinar main loop.");
continue;
},
Ok(zaldinar::client::ExecutingState::RestartExec) => {
println!("Restarting zaldinar using exec.");
let result = execv_if_possible(&original_program);
return result;
},
Ok(zaldinar::client::ExecutingState::RestartTryExec) => {
println!("Restarting zaldinar using exec.");
execv_if_possible(&original_program);
println!("Restarting using exec failed, restarting main loop.");
continue;
}
Err(e) => {
print_err!("Error running client: {}", e);
return 1;
},
};
}
return 0;
}
|
{
println!("Can't restart using execv on this platform!");
return 1;
}
|
identifier_body
|
main.rs
|
#![cfg(not(test))]
extern crate zaldinar;
extern crate getopts;
macro_rules! print_err {
($($arg:tt)*) => (
{
use std::io::prelude::*;
if let Err(e) = write!(&mut ::std::io::stderr(), "{}\n", format_args!($($arg)*)) {
panic!("Failed to write to stderr.\
\nOriginal error output: {}\
\nSecondary error writing to stderr: {}", format!($($arg)*), e);
}
}
)
}
#[cfg(feature = "binary-filewatch")]
extern crate libc;
#[cfg(feature = "binary-filewatch")]
mod execv_linux;
use std::env;
use std::io;
use std::path::PathBuf;
use std::path::Path;
#[cfg(feature = "binary-filewatch")]
use execv_linux::execv_if_possible;
const UNKNOWN_EXECUTABLE: &'static str = "<unknown executable>";
#[cfg(not(feature = "binary-filewatch"))]
fn execv_if_possible(_program_path: &Path) -> i32 {
println!("Can't restart using execv on this platform!");
return 1;
}
fn get_program() -> io::Result<PathBuf> {
// This joins current_dir() and current_exe(), resulting in an absolute path to of the current
// executable
let mut buf = try!(env::current_dir());
buf.push(&try!(env::current_exe()));
return Ok(buf);
}
fn main() {
let result = main_exits();
std::process::exit(result);
}
/// Separate function from main to ensure that everything is cleaned up by exiting scope before
/// program exits using std::process::exit();
fn main_exits() -> i32 {
// Because env::current_exe() will change if the executing file is moved, we need to get the
// original program path as soon as we start.
// We have two `program` variables because we still want to use the program gotten from
// env::args() to print help strings.
let original_program = match get_program() {
Ok(v) => v,
Err(e) => {
print_err!("Warning: failed to find current executable: {}", e);
PathBuf::from(UNKNOWN_EXECUTABLE)
}
};
let mut args = env::args();
|
};
let mut opts = getopts::Options::new();
opts.optopt("c", "config", "set config file name", "FILE");
opts.optflag("h", "help", "print this help menu");
opts.optflag("v", "version", "print program version");
// TODO: Bug getopts to use OsString
let matches = match opts.parse(args.collect::<Vec<String>>()) {
Ok(v) => v,
Err(e) => {
print_err!("{}", e.to_string());
return 0;
}
};
if matches.opt_present("help") {
let brief = format!("Usage: {} [options]", display_program);
println!("{}", opts.usage(&brief));
return 0;
} else if matches.opt_present("version") {
println!("zaldinar version {}", zaldinar::VERSION);
return 0;
}
let current_dir = match env::current_dir() {
Ok(v) => v,
Err(e) => {
print_err!("Warning: failed to get current directory: {}", e);
PathBuf::from("") // TODO: return here or just not be absolute?
}
};
let config_path = match matches.opt_str("config") {
Some(v) => {
let absolute = current_dir.join(&Path::new(&v));
println!("Using configuration: {}", absolute.display());
absolute
},
None => current_dir.join(Path::new("config.json")),
};
loop {
let config = match zaldinar::ClientConfiguration::load_from_file(&config_path) {
Ok(v) => v,
Err(e) => {
print_err!("Error loading configuration from `{}`: {}", config_path.display(), e);
return 1;
},
};
match zaldinar::run(config) {
Ok(zaldinar::client::ExecutingState::Done) => {
println!("Done, exiting.");
break
},
Ok(zaldinar::client::ExecutingState::Running)
| Ok(zaldinar::client::ExecutingState::RestartNoExec) => {
println!("Restarting zaldinar main loop.");
continue;
},
Ok(zaldinar::client::ExecutingState::RestartExec) => {
println!("Restarting zaldinar using exec.");
let result = execv_if_possible(&original_program);
return result;
},
Ok(zaldinar::client::ExecutingState::RestartTryExec) => {
println!("Restarting zaldinar using exec.");
execv_if_possible(&original_program);
println!("Restarting using exec failed, restarting main loop.");
continue;
}
Err(e) => {
print_err!("Error running client: {}", e);
return 1;
},
};
}
return 0;
}
|
let display_program = match args.next() {
// TODO: some error catching of lossy strings here or not?
Some(v) => v,
None => original_program.as_os_str().to_string_lossy().into_owned(),
|
random_line_split
|
draw_cache.rs
|
use std::cell::RefCell;
use std::fmt;
use ggez::{
graphics::{BlendMode, DrawParam, Drawable},
Context, GameResult,
};
pub trait TryIntoDrawable<T>
where
T: Drawable,
{
fn try_into_drawable(&self, ctx: &mut Context) -> GameResult<T>;
}
pub struct DrawCache<T, U>
where
T: TryIntoDrawable<U>,
U: Drawable,
{
data: T,
cache: RefCell<Option<U>>,
}
impl<T, U> DrawCache<T, U>
where
T: TryIntoDrawable<U>,
U: Drawable,
{
pub fn
|
(data: T) -> Self {
Self {
data,
cache: RefCell::new(None),
}
}
}
impl<T, U> AsRef<T> for DrawCache<T, U>
where
T: TryIntoDrawable<U>,
U: Drawable,
{
fn as_ref(&self) -> &T {
&self.data
}
}
impl<T, U> fmt::Debug for DrawCache<T, U>
where
T: TryIntoDrawable<U> + fmt::Debug,
U: Drawable,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.data)
}
}
impl<T, U> Drawable for DrawCache<T, U>
where
T: TryIntoDrawable<U>,
U: Drawable,
{
fn draw_ex(&self, ctx: &mut Context, param: DrawParam) -> GameResult<()> {
let is_cached = self.cache.borrow().is_some();
if!is_cached {
let drawable = self.data.try_into_drawable(ctx)?;
self.cache.replace(Some(drawable));
}
self.cache
.borrow_mut()
.as_mut()
.unwrap()
.draw_ex(ctx, param)
}
fn set_blend_mode(&mut self, mode: Option<BlendMode>) {
if let Some(ref mut drawable) = *self.cache.get_mut() {
drawable.set_blend_mode(mode);
}
}
fn get_blend_mode(&self) -> Option<BlendMode> {
match *self.cache.borrow() {
None => None,
Some(ref drawable) => drawable.get_blend_mode(),
}
}
}
|
new
|
identifier_name
|
draw_cache.rs
|
use std::cell::RefCell;
use std::fmt;
use ggez::{
graphics::{BlendMode, DrawParam, Drawable},
Context, GameResult,
};
pub trait TryIntoDrawable<T>
where
T: Drawable,
{
fn try_into_drawable(&self, ctx: &mut Context) -> GameResult<T>;
}
pub struct DrawCache<T, U>
where
T: TryIntoDrawable<U>,
U: Drawable,
{
data: T,
cache: RefCell<Option<U>>,
}
impl<T, U> DrawCache<T, U>
where
T: TryIntoDrawable<U>,
U: Drawable,
{
pub fn new(data: T) -> Self {
Self {
data,
cache: RefCell::new(None),
}
}
}
impl<T, U> AsRef<T> for DrawCache<T, U>
where
T: TryIntoDrawable<U>,
U: Drawable,
{
fn as_ref(&self) -> &T {
&self.data
}
}
impl<T, U> fmt::Debug for DrawCache<T, U>
where
T: TryIntoDrawable<U> + fmt::Debug,
U: Drawable,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.data)
}
}
impl<T, U> Drawable for DrawCache<T, U>
where
T: TryIntoDrawable<U>,
U: Drawable,
{
fn draw_ex(&self, ctx: &mut Context, param: DrawParam) -> GameResult<()> {
let is_cached = self.cache.borrow().is_some();
if!is_cached {
let drawable = self.data.try_into_drawable(ctx)?;
self.cache.replace(Some(drawable));
}
self.cache
.borrow_mut()
.as_mut()
.unwrap()
.draw_ex(ctx, param)
}
fn set_blend_mode(&mut self, mode: Option<BlendMode>) {
if let Some(ref mut drawable) = *self.cache.get_mut() {
drawable.set_blend_mode(mode);
}
}
fn get_blend_mode(&self) -> Option<BlendMode> {
match *self.cache.borrow() {
None => None,
Some(ref drawable) => drawable.get_blend_mode(),
}
}
|
}
|
random_line_split
|
|
draw_cache.rs
|
use std::cell::RefCell;
use std::fmt;
use ggez::{
graphics::{BlendMode, DrawParam, Drawable},
Context, GameResult,
};
pub trait TryIntoDrawable<T>
where
T: Drawable,
{
fn try_into_drawable(&self, ctx: &mut Context) -> GameResult<T>;
}
pub struct DrawCache<T, U>
where
T: TryIntoDrawable<U>,
U: Drawable,
{
data: T,
cache: RefCell<Option<U>>,
}
impl<T, U> DrawCache<T, U>
where
T: TryIntoDrawable<U>,
U: Drawable,
{
pub fn new(data: T) -> Self {
Self {
data,
cache: RefCell::new(None),
}
}
}
impl<T, U> AsRef<T> for DrawCache<T, U>
where
T: TryIntoDrawable<U>,
U: Drawable,
{
fn as_ref(&self) -> &T {
&self.data
}
}
impl<T, U> fmt::Debug for DrawCache<T, U>
where
T: TryIntoDrawable<U> + fmt::Debug,
U: Drawable,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.data)
}
}
impl<T, U> Drawable for DrawCache<T, U>
where
T: TryIntoDrawable<U>,
U: Drawable,
{
fn draw_ex(&self, ctx: &mut Context, param: DrawParam) -> GameResult<()>
|
fn set_blend_mode(&mut self, mode: Option<BlendMode>) {
if let Some(ref mut drawable) = *self.cache.get_mut() {
drawable.set_blend_mode(mode);
}
}
fn get_blend_mode(&self) -> Option<BlendMode> {
match *self.cache.borrow() {
None => None,
Some(ref drawable) => drawable.get_blend_mode(),
}
}
}
|
{
let is_cached = self.cache.borrow().is_some();
if !is_cached {
let drawable = self.data.try_into_drawable(ctx)?;
self.cache.replace(Some(drawable));
}
self.cache
.borrow_mut()
.as_mut()
.unwrap()
.draw_ex(ctx, param)
}
|
identifier_body
|
extensions.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::iter::FromIterator;
use core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::OESTextureHalfFloatBinding::OESTextureHalfFloatConstants;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
use dom::bindings::js::Root;
use dom::bindings::trace::JSTraceable;
use dom::webglrenderingcontext::WebGLRenderingContext;
use gleam::gl::GLenum;
use heapsize::HeapSizeOf;
use js::jsapi::{JSContext, JSObject};
use js::jsval::JSVal;
use ref_filter_map::ref_filter_map;
use std::cell::Ref;
use std::collections::{HashMap, HashSet};
use super::{ext, WebGLExtension};
use super::wrapper::{WebGLExtensionWrapper, TypedWebGLExtensionWrapper};
use webrender_traits::WebGLError;
// Data types that are implemented for texImage2D and texSubImage2D in WebGLRenderingContext
// but must trigger a InvalidValue error until the related WebGL Extensions are enabled.
// Example: https://www.khronos.org/registry/webgl/extensions/OES_texture_float/
const DEFAULT_DISABLED_TEX_TYPES: [GLenum; 2] = [
constants::FLOAT, OESTextureHalfFloatConstants::HALF_FLOAT_OES
];
// Data types that are implemented for textures in WebGLRenderingContext
// but not allowed to use with linear filtering until the related WebGL Extensions are enabled.
// Example: https://www.khronos.org/registry/webgl/extensions/OES_texture_float_linear/
const DEFAULT_NOT_FILTERABLE_TEX_TYPES: [GLenum; 2] = [
constants::FLOAT, OESTextureHalfFloatConstants::HALF_FLOAT_OES
];
/// WebGL features that are enabled/disabled by WebGL Extensions.
#[derive(JSTraceable, HeapSizeOf)]
struct WebGLExtensionFeatures {
gl_extensions: HashSet<String>,
disabled_tex_types: HashSet<GLenum>,
not_filterable_tex_types: HashSet<GLenum>,
effective_tex_internal_formats: HashMap<TexFormatType, u32>,
query_parameter_handlers: HashMap<GLenum, WebGLQueryParameterHandler>
}
impl Default for WebGLExtensionFeatures {
fn default() -> WebGLExtensionFeatures {
WebGLExtensionFeatures {
gl_extensions: HashSet::new(),
disabled_tex_types: DEFAULT_DISABLED_TEX_TYPES.iter().cloned().collect(),
not_filterable_tex_types: DEFAULT_NOT_FILTERABLE_TEX_TYPES.iter().cloned().collect(),
effective_tex_internal_formats: HashMap::new(),
query_parameter_handlers: HashMap::new()
}
}
}
/// Handles the list of implemented, supported and enabled WebGL extensions.
#[must_root]
#[derive(JSTraceable, HeapSizeOf)]
pub struct WebGLExtensions {
extensions: DOMRefCell<HashMap<String, Box<WebGLExtensionWrapper>>>,
features: DOMRefCell<WebGLExtensionFeatures>,
}
impl WebGLExtensions {
pub fn new() -> WebGLExtensions {
Self {
extensions: DOMRefCell::new(HashMap::new()),
features: DOMRefCell::new(Default::default())
}
}
pub fn init_once<F>(&self, cb: F) where F: FnOnce() -> String {
if self.extensions.borrow().len() == 0 {
let gl_str = cb();
self.features.borrow_mut().gl_extensions = HashSet::from_iter(gl_str.split(&[',',''][..])
.map(|s| s.into()));
self.register_all_extensions();
|
let name = T::name().to_uppercase();
self.extensions.borrow_mut().insert(name, box TypedWebGLExtensionWrapper::<T>::new());
}
pub fn get_suported_extensions(&self) -> Vec<&'static str> {
self.extensions.borrow().iter()
.filter(|ref v| v.1.is_supported(&self))
.map(|ref v| v.1.name())
.collect()
}
pub fn get_or_init_extension(&self, name: &str, ctx: &WebGLRenderingContext) -> Option<NonZero<*mut JSObject>> {
let name = name.to_uppercase();
self.extensions.borrow().get(&name).and_then(|extension| {
if extension.is_supported(self) {
Some(extension.instance_or_init(ctx, self))
} else {
None
}
})
}
pub fn get_dom_object<T>(&self) -> Option<Root<T::Extension>>
where T:'static + WebGLExtension + JSTraceable + HeapSizeOf {
let name = T::name().to_uppercase();
self.extensions.borrow().get(&name).and_then(|extension| {
extension.as_any().downcast_ref::<TypedWebGLExtensionWrapper<T>>().and_then(|extension| {
extension.dom_object()
})
})
}
pub fn supports_gl_extension(&self, name: &str) -> bool {
self.features.borrow().gl_extensions.contains(name)
}
pub fn supports_any_gl_extension(&self, names: &[&str]) -> bool {
let features = self.features.borrow();
names.iter().any(|name| features.gl_extensions.contains(*name))
}
pub fn enable_tex_type(&self, data_type: GLenum) {
self.features.borrow_mut().disabled_tex_types.remove(&data_type);
}
pub fn is_tex_type_enabled(&self, data_type: GLenum) -> bool {
self.features.borrow().disabled_tex_types.get(&data_type).is_none()
}
pub fn add_effective_tex_internal_format(&self,
source_internal_format: u32,
source_data_type: u32,
effective_internal_format: u32)
{
let format = TexFormatType(source_internal_format, source_data_type);
self.features.borrow_mut().effective_tex_internal_formats.insert(format,
effective_internal_format);
}
pub fn get_effective_tex_internal_format(&self,
source_internal_format: u32,
source_data_type: u32) -> u32 {
let format = TexFormatType(source_internal_format, source_data_type);
*(self.features.borrow().effective_tex_internal_formats.get(&format)
.unwrap_or(&source_internal_format))
}
pub fn enable_filterable_tex_type(&self, text_data_type: GLenum) {
self.features.borrow_mut().not_filterable_tex_types.remove(&text_data_type);
}
pub fn is_filterable(&self, text_data_type: u32) -> bool {
self.features.borrow().not_filterable_tex_types.get(&text_data_type).is_none()
}
pub fn add_query_parameter_handler(&self, name: GLenum, f: Box<WebGLQueryParameterFunc>) {
let handler = WebGLQueryParameterHandler {
func: f
};
self.features.borrow_mut().query_parameter_handlers.insert(name, handler);
}
pub fn get_query_parameter_handler(&self, name: GLenum) -> Option<Ref<Box<WebGLQueryParameterFunc>>> {
ref_filter_map(self.features.borrow(), |features| {
features.query_parameter_handlers.get(&name).map(|item| &item.func)
})
}
fn register_all_extensions(&self) {
self.register::<ext::oestexturefloat::OESTextureFloat>();
self.register::<ext::oestexturefloatlinear::OESTextureFloatLinear>();
self.register::<ext::oestexturehalffloat::OESTextureHalfFloat>();
self.register::<ext::oestexturehalffloatlinear::OESTextureHalfFloatLinear>();
self.register::<ext::oesvertexarrayobject::OESVertexArrayObject>();
}
}
// Helper structs
#[derive(JSTraceable, HeapSizeOf, PartialEq, Eq, Hash)]
struct TexFormatType(u32, u32);
type WebGLQueryParameterFunc = Fn(*mut JSContext, &WebGLRenderingContext)
-> Result<JSVal, WebGLError>;
#[derive(HeapSizeOf)]
struct WebGLQueryParameterHandler {
#[ignore_heap_size_of = "Closures are hard"]
func: Box<WebGLQueryParameterFunc>
}
unsafe_no_jsmanaged_fields!(WebGLQueryParameterHandler);
|
}
}
pub fn register<T:'static + WebGLExtension + JSTraceable + HeapSizeOf>(&self) {
|
random_line_split
|
extensions.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::iter::FromIterator;
use core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::OESTextureHalfFloatBinding::OESTextureHalfFloatConstants;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
use dom::bindings::js::Root;
use dom::bindings::trace::JSTraceable;
use dom::webglrenderingcontext::WebGLRenderingContext;
use gleam::gl::GLenum;
use heapsize::HeapSizeOf;
use js::jsapi::{JSContext, JSObject};
use js::jsval::JSVal;
use ref_filter_map::ref_filter_map;
use std::cell::Ref;
use std::collections::{HashMap, HashSet};
use super::{ext, WebGLExtension};
use super::wrapper::{WebGLExtensionWrapper, TypedWebGLExtensionWrapper};
use webrender_traits::WebGLError;
// Data types that are implemented for texImage2D and texSubImage2D in WebGLRenderingContext
// but must trigger a InvalidValue error until the related WebGL Extensions are enabled.
// Example: https://www.khronos.org/registry/webgl/extensions/OES_texture_float/
const DEFAULT_DISABLED_TEX_TYPES: [GLenum; 2] = [
constants::FLOAT, OESTextureHalfFloatConstants::HALF_FLOAT_OES
];
// Data types that are implemented for textures in WebGLRenderingContext
// but not allowed to use with linear filtering until the related WebGL Extensions are enabled.
// Example: https://www.khronos.org/registry/webgl/extensions/OES_texture_float_linear/
const DEFAULT_NOT_FILTERABLE_TEX_TYPES: [GLenum; 2] = [
constants::FLOAT, OESTextureHalfFloatConstants::HALF_FLOAT_OES
];
/// WebGL features that are enabled/disabled by WebGL Extensions.
#[derive(JSTraceable, HeapSizeOf)]
struct WebGLExtensionFeatures {
gl_extensions: HashSet<String>,
disabled_tex_types: HashSet<GLenum>,
not_filterable_tex_types: HashSet<GLenum>,
effective_tex_internal_formats: HashMap<TexFormatType, u32>,
query_parameter_handlers: HashMap<GLenum, WebGLQueryParameterHandler>
}
impl Default for WebGLExtensionFeatures {
fn default() -> WebGLExtensionFeatures {
WebGLExtensionFeatures {
gl_extensions: HashSet::new(),
disabled_tex_types: DEFAULT_DISABLED_TEX_TYPES.iter().cloned().collect(),
not_filterable_tex_types: DEFAULT_NOT_FILTERABLE_TEX_TYPES.iter().cloned().collect(),
effective_tex_internal_formats: HashMap::new(),
query_parameter_handlers: HashMap::new()
}
}
}
/// Handles the list of implemented, supported and enabled WebGL extensions.
#[must_root]
#[derive(JSTraceable, HeapSizeOf)]
pub struct WebGLExtensions {
extensions: DOMRefCell<HashMap<String, Box<WebGLExtensionWrapper>>>,
features: DOMRefCell<WebGLExtensionFeatures>,
}
impl WebGLExtensions {
pub fn new() -> WebGLExtensions {
Self {
extensions: DOMRefCell::new(HashMap::new()),
features: DOMRefCell::new(Default::default())
}
}
pub fn init_once<F>(&self, cb: F) where F: FnOnce() -> String {
if self.extensions.borrow().len() == 0 {
let gl_str = cb();
self.features.borrow_mut().gl_extensions = HashSet::from_iter(gl_str.split(&[',',''][..])
.map(|s| s.into()));
self.register_all_extensions();
}
}
pub fn register<T:'static + WebGLExtension + JSTraceable + HeapSizeOf>(&self) {
let name = T::name().to_uppercase();
self.extensions.borrow_mut().insert(name, box TypedWebGLExtensionWrapper::<T>::new());
}
pub fn get_suported_extensions(&self) -> Vec<&'static str> {
self.extensions.borrow().iter()
.filter(|ref v| v.1.is_supported(&self))
.map(|ref v| v.1.name())
.collect()
}
pub fn get_or_init_extension(&self, name: &str, ctx: &WebGLRenderingContext) -> Option<NonZero<*mut JSObject>> {
let name = name.to_uppercase();
self.extensions.borrow().get(&name).and_then(|extension| {
if extension.is_supported(self) {
Some(extension.instance_or_init(ctx, self))
} else
|
})
}
pub fn get_dom_object<T>(&self) -> Option<Root<T::Extension>>
where T:'static + WebGLExtension + JSTraceable + HeapSizeOf {
let name = T::name().to_uppercase();
self.extensions.borrow().get(&name).and_then(|extension| {
extension.as_any().downcast_ref::<TypedWebGLExtensionWrapper<T>>().and_then(|extension| {
extension.dom_object()
})
})
}
pub fn supports_gl_extension(&self, name: &str) -> bool {
self.features.borrow().gl_extensions.contains(name)
}
pub fn supports_any_gl_extension(&self, names: &[&str]) -> bool {
let features = self.features.borrow();
names.iter().any(|name| features.gl_extensions.contains(*name))
}
pub fn enable_tex_type(&self, data_type: GLenum) {
self.features.borrow_mut().disabled_tex_types.remove(&data_type);
}
pub fn is_tex_type_enabled(&self, data_type: GLenum) -> bool {
self.features.borrow().disabled_tex_types.get(&data_type).is_none()
}
pub fn add_effective_tex_internal_format(&self,
source_internal_format: u32,
source_data_type: u32,
effective_internal_format: u32)
{
let format = TexFormatType(source_internal_format, source_data_type);
self.features.borrow_mut().effective_tex_internal_formats.insert(format,
effective_internal_format);
}
pub fn get_effective_tex_internal_format(&self,
source_internal_format: u32,
source_data_type: u32) -> u32 {
let format = TexFormatType(source_internal_format, source_data_type);
*(self.features.borrow().effective_tex_internal_formats.get(&format)
.unwrap_or(&source_internal_format))
}
pub fn enable_filterable_tex_type(&self, text_data_type: GLenum) {
self.features.borrow_mut().not_filterable_tex_types.remove(&text_data_type);
}
pub fn is_filterable(&self, text_data_type: u32) -> bool {
self.features.borrow().not_filterable_tex_types.get(&text_data_type).is_none()
}
pub fn add_query_parameter_handler(&self, name: GLenum, f: Box<WebGLQueryParameterFunc>) {
let handler = WebGLQueryParameterHandler {
func: f
};
self.features.borrow_mut().query_parameter_handlers.insert(name, handler);
}
pub fn get_query_parameter_handler(&self, name: GLenum) -> Option<Ref<Box<WebGLQueryParameterFunc>>> {
ref_filter_map(self.features.borrow(), |features| {
features.query_parameter_handlers.get(&name).map(|item| &item.func)
})
}
fn register_all_extensions(&self) {
self.register::<ext::oestexturefloat::OESTextureFloat>();
self.register::<ext::oestexturefloatlinear::OESTextureFloatLinear>();
self.register::<ext::oestexturehalffloat::OESTextureHalfFloat>();
self.register::<ext::oestexturehalffloatlinear::OESTextureHalfFloatLinear>();
self.register::<ext::oesvertexarrayobject::OESVertexArrayObject>();
}
}
// Helper structs
#[derive(JSTraceable, HeapSizeOf, PartialEq, Eq, Hash)]
struct TexFormatType(u32, u32);
type WebGLQueryParameterFunc = Fn(*mut JSContext, &WebGLRenderingContext)
-> Result<JSVal, WebGLError>;
#[derive(HeapSizeOf)]
struct WebGLQueryParameterHandler {
#[ignore_heap_size_of = "Closures are hard"]
func: Box<WebGLQueryParameterFunc>
}
unsafe_no_jsmanaged_fields!(WebGLQueryParameterHandler);
|
{
None
}
|
conditional_block
|
extensions.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::iter::FromIterator;
use core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::OESTextureHalfFloatBinding::OESTextureHalfFloatConstants;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
use dom::bindings::js::Root;
use dom::bindings::trace::JSTraceable;
use dom::webglrenderingcontext::WebGLRenderingContext;
use gleam::gl::GLenum;
use heapsize::HeapSizeOf;
use js::jsapi::{JSContext, JSObject};
use js::jsval::JSVal;
use ref_filter_map::ref_filter_map;
use std::cell::Ref;
use std::collections::{HashMap, HashSet};
use super::{ext, WebGLExtension};
use super::wrapper::{WebGLExtensionWrapper, TypedWebGLExtensionWrapper};
use webrender_traits::WebGLError;
// Data types that are implemented for texImage2D and texSubImage2D in WebGLRenderingContext
// but must trigger a InvalidValue error until the related WebGL Extensions are enabled.
// Example: https://www.khronos.org/registry/webgl/extensions/OES_texture_float/
const DEFAULT_DISABLED_TEX_TYPES: [GLenum; 2] = [
constants::FLOAT, OESTextureHalfFloatConstants::HALF_FLOAT_OES
];
// Data types that are implemented for textures in WebGLRenderingContext
// but not allowed to use with linear filtering until the related WebGL Extensions are enabled.
// Example: https://www.khronos.org/registry/webgl/extensions/OES_texture_float_linear/
const DEFAULT_NOT_FILTERABLE_TEX_TYPES: [GLenum; 2] = [
constants::FLOAT, OESTextureHalfFloatConstants::HALF_FLOAT_OES
];
/// WebGL features that are enabled/disabled by WebGL Extensions.
#[derive(JSTraceable, HeapSizeOf)]
struct WebGLExtensionFeatures {
gl_extensions: HashSet<String>,
disabled_tex_types: HashSet<GLenum>,
not_filterable_tex_types: HashSet<GLenum>,
effective_tex_internal_formats: HashMap<TexFormatType, u32>,
query_parameter_handlers: HashMap<GLenum, WebGLQueryParameterHandler>
}
impl Default for WebGLExtensionFeatures {
fn
|
() -> WebGLExtensionFeatures {
WebGLExtensionFeatures {
gl_extensions: HashSet::new(),
disabled_tex_types: DEFAULT_DISABLED_TEX_TYPES.iter().cloned().collect(),
not_filterable_tex_types: DEFAULT_NOT_FILTERABLE_TEX_TYPES.iter().cloned().collect(),
effective_tex_internal_formats: HashMap::new(),
query_parameter_handlers: HashMap::new()
}
}
}
/// Handles the list of implemented, supported and enabled WebGL extensions.
#[must_root]
#[derive(JSTraceable, HeapSizeOf)]
pub struct WebGLExtensions {
extensions: DOMRefCell<HashMap<String, Box<WebGLExtensionWrapper>>>,
features: DOMRefCell<WebGLExtensionFeatures>,
}
impl WebGLExtensions {
pub fn new() -> WebGLExtensions {
Self {
extensions: DOMRefCell::new(HashMap::new()),
features: DOMRefCell::new(Default::default())
}
}
pub fn init_once<F>(&self, cb: F) where F: FnOnce() -> String {
if self.extensions.borrow().len() == 0 {
let gl_str = cb();
self.features.borrow_mut().gl_extensions = HashSet::from_iter(gl_str.split(&[',',''][..])
.map(|s| s.into()));
self.register_all_extensions();
}
}
pub fn register<T:'static + WebGLExtension + JSTraceable + HeapSizeOf>(&self) {
let name = T::name().to_uppercase();
self.extensions.borrow_mut().insert(name, box TypedWebGLExtensionWrapper::<T>::new());
}
pub fn get_suported_extensions(&self) -> Vec<&'static str> {
self.extensions.borrow().iter()
.filter(|ref v| v.1.is_supported(&self))
.map(|ref v| v.1.name())
.collect()
}
pub fn get_or_init_extension(&self, name: &str, ctx: &WebGLRenderingContext) -> Option<NonZero<*mut JSObject>> {
let name = name.to_uppercase();
self.extensions.borrow().get(&name).and_then(|extension| {
if extension.is_supported(self) {
Some(extension.instance_or_init(ctx, self))
} else {
None
}
})
}
pub fn get_dom_object<T>(&self) -> Option<Root<T::Extension>>
where T:'static + WebGLExtension + JSTraceable + HeapSizeOf {
let name = T::name().to_uppercase();
self.extensions.borrow().get(&name).and_then(|extension| {
extension.as_any().downcast_ref::<TypedWebGLExtensionWrapper<T>>().and_then(|extension| {
extension.dom_object()
})
})
}
pub fn supports_gl_extension(&self, name: &str) -> bool {
self.features.borrow().gl_extensions.contains(name)
}
pub fn supports_any_gl_extension(&self, names: &[&str]) -> bool {
let features = self.features.borrow();
names.iter().any(|name| features.gl_extensions.contains(*name))
}
pub fn enable_tex_type(&self, data_type: GLenum) {
self.features.borrow_mut().disabled_tex_types.remove(&data_type);
}
pub fn is_tex_type_enabled(&self, data_type: GLenum) -> bool {
self.features.borrow().disabled_tex_types.get(&data_type).is_none()
}
pub fn add_effective_tex_internal_format(&self,
source_internal_format: u32,
source_data_type: u32,
effective_internal_format: u32)
{
let format = TexFormatType(source_internal_format, source_data_type);
self.features.borrow_mut().effective_tex_internal_formats.insert(format,
effective_internal_format);
}
pub fn get_effective_tex_internal_format(&self,
source_internal_format: u32,
source_data_type: u32) -> u32 {
let format = TexFormatType(source_internal_format, source_data_type);
*(self.features.borrow().effective_tex_internal_formats.get(&format)
.unwrap_or(&source_internal_format))
}
pub fn enable_filterable_tex_type(&self, text_data_type: GLenum) {
self.features.borrow_mut().not_filterable_tex_types.remove(&text_data_type);
}
pub fn is_filterable(&self, text_data_type: u32) -> bool {
self.features.borrow().not_filterable_tex_types.get(&text_data_type).is_none()
}
pub fn add_query_parameter_handler(&self, name: GLenum, f: Box<WebGLQueryParameterFunc>) {
let handler = WebGLQueryParameterHandler {
func: f
};
self.features.borrow_mut().query_parameter_handlers.insert(name, handler);
}
pub fn get_query_parameter_handler(&self, name: GLenum) -> Option<Ref<Box<WebGLQueryParameterFunc>>> {
ref_filter_map(self.features.borrow(), |features| {
features.query_parameter_handlers.get(&name).map(|item| &item.func)
})
}
fn register_all_extensions(&self) {
self.register::<ext::oestexturefloat::OESTextureFloat>();
self.register::<ext::oestexturefloatlinear::OESTextureFloatLinear>();
self.register::<ext::oestexturehalffloat::OESTextureHalfFloat>();
self.register::<ext::oestexturehalffloatlinear::OESTextureHalfFloatLinear>();
self.register::<ext::oesvertexarrayobject::OESVertexArrayObject>();
}
}
// Helper structs
#[derive(JSTraceable, HeapSizeOf, PartialEq, Eq, Hash)]
struct TexFormatType(u32, u32);
type WebGLQueryParameterFunc = Fn(*mut JSContext, &WebGLRenderingContext)
-> Result<JSVal, WebGLError>;
#[derive(HeapSizeOf)]
struct WebGLQueryParameterHandler {
#[ignore_heap_size_of = "Closures are hard"]
func: Box<WebGLQueryParameterFunc>
}
unsafe_no_jsmanaged_fields!(WebGLQueryParameterHandler);
|
default
|
identifier_name
|
extensions.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::iter::FromIterator;
use core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::OESTextureHalfFloatBinding::OESTextureHalfFloatConstants;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
use dom::bindings::js::Root;
use dom::bindings::trace::JSTraceable;
use dom::webglrenderingcontext::WebGLRenderingContext;
use gleam::gl::GLenum;
use heapsize::HeapSizeOf;
use js::jsapi::{JSContext, JSObject};
use js::jsval::JSVal;
use ref_filter_map::ref_filter_map;
use std::cell::Ref;
use std::collections::{HashMap, HashSet};
use super::{ext, WebGLExtension};
use super::wrapper::{WebGLExtensionWrapper, TypedWebGLExtensionWrapper};
use webrender_traits::WebGLError;
// Data types that are implemented for texImage2D and texSubImage2D in WebGLRenderingContext
// but must trigger a InvalidValue error until the related WebGL Extensions are enabled.
// Example: https://www.khronos.org/registry/webgl/extensions/OES_texture_float/
const DEFAULT_DISABLED_TEX_TYPES: [GLenum; 2] = [
constants::FLOAT, OESTextureHalfFloatConstants::HALF_FLOAT_OES
];
// Data types that are implemented for textures in WebGLRenderingContext
// but not allowed to use with linear filtering until the related WebGL Extensions are enabled.
// Example: https://www.khronos.org/registry/webgl/extensions/OES_texture_float_linear/
const DEFAULT_NOT_FILTERABLE_TEX_TYPES: [GLenum; 2] = [
constants::FLOAT, OESTextureHalfFloatConstants::HALF_FLOAT_OES
];
/// WebGL features that are enabled/disabled by WebGL Extensions.
#[derive(JSTraceable, HeapSizeOf)]
struct WebGLExtensionFeatures {
gl_extensions: HashSet<String>,
disabled_tex_types: HashSet<GLenum>,
not_filterable_tex_types: HashSet<GLenum>,
effective_tex_internal_formats: HashMap<TexFormatType, u32>,
query_parameter_handlers: HashMap<GLenum, WebGLQueryParameterHandler>
}
impl Default for WebGLExtensionFeatures {
fn default() -> WebGLExtensionFeatures {
WebGLExtensionFeatures {
gl_extensions: HashSet::new(),
disabled_tex_types: DEFAULT_DISABLED_TEX_TYPES.iter().cloned().collect(),
not_filterable_tex_types: DEFAULT_NOT_FILTERABLE_TEX_TYPES.iter().cloned().collect(),
effective_tex_internal_formats: HashMap::new(),
query_parameter_handlers: HashMap::new()
}
}
}
/// Handles the list of implemented, supported and enabled WebGL extensions.
#[must_root]
#[derive(JSTraceable, HeapSizeOf)]
pub struct WebGLExtensions {
extensions: DOMRefCell<HashMap<String, Box<WebGLExtensionWrapper>>>,
features: DOMRefCell<WebGLExtensionFeatures>,
}
impl WebGLExtensions {
pub fn new() -> WebGLExtensions {
Self {
extensions: DOMRefCell::new(HashMap::new()),
features: DOMRefCell::new(Default::default())
}
}
pub fn init_once<F>(&self, cb: F) where F: FnOnce() -> String {
if self.extensions.borrow().len() == 0 {
let gl_str = cb();
self.features.borrow_mut().gl_extensions = HashSet::from_iter(gl_str.split(&[',',''][..])
.map(|s| s.into()));
self.register_all_extensions();
}
}
pub fn register<T:'static + WebGLExtension + JSTraceable + HeapSizeOf>(&self) {
let name = T::name().to_uppercase();
self.extensions.borrow_mut().insert(name, box TypedWebGLExtensionWrapper::<T>::new());
}
pub fn get_suported_extensions(&self) -> Vec<&'static str> {
self.extensions.borrow().iter()
.filter(|ref v| v.1.is_supported(&self))
.map(|ref v| v.1.name())
.collect()
}
pub fn get_or_init_extension(&self, name: &str, ctx: &WebGLRenderingContext) -> Option<NonZero<*mut JSObject>> {
let name = name.to_uppercase();
self.extensions.borrow().get(&name).and_then(|extension| {
if extension.is_supported(self) {
Some(extension.instance_or_init(ctx, self))
} else {
None
}
})
}
pub fn get_dom_object<T>(&self) -> Option<Root<T::Extension>>
where T:'static + WebGLExtension + JSTraceable + HeapSizeOf {
let name = T::name().to_uppercase();
self.extensions.borrow().get(&name).and_then(|extension| {
extension.as_any().downcast_ref::<TypedWebGLExtensionWrapper<T>>().and_then(|extension| {
extension.dom_object()
})
})
}
pub fn supports_gl_extension(&self, name: &str) -> bool {
self.features.borrow().gl_extensions.contains(name)
}
pub fn supports_any_gl_extension(&self, names: &[&str]) -> bool {
let features = self.features.borrow();
names.iter().any(|name| features.gl_extensions.contains(*name))
}
pub fn enable_tex_type(&self, data_type: GLenum) {
self.features.borrow_mut().disabled_tex_types.remove(&data_type);
}
pub fn is_tex_type_enabled(&self, data_type: GLenum) -> bool {
self.features.borrow().disabled_tex_types.get(&data_type).is_none()
}
pub fn add_effective_tex_internal_format(&self,
source_internal_format: u32,
source_data_type: u32,
effective_internal_format: u32)
{
let format = TexFormatType(source_internal_format, source_data_type);
self.features.borrow_mut().effective_tex_internal_formats.insert(format,
effective_internal_format);
}
pub fn get_effective_tex_internal_format(&self,
source_internal_format: u32,
source_data_type: u32) -> u32 {
let format = TexFormatType(source_internal_format, source_data_type);
*(self.features.borrow().effective_tex_internal_formats.get(&format)
.unwrap_or(&source_internal_format))
}
pub fn enable_filterable_tex_type(&self, text_data_type: GLenum) {
self.features.borrow_mut().not_filterable_tex_types.remove(&text_data_type);
}
pub fn is_filterable(&self, text_data_type: u32) -> bool {
self.features.borrow().not_filterable_tex_types.get(&text_data_type).is_none()
}
pub fn add_query_parameter_handler(&self, name: GLenum, f: Box<WebGLQueryParameterFunc>)
|
pub fn get_query_parameter_handler(&self, name: GLenum) -> Option<Ref<Box<WebGLQueryParameterFunc>>> {
ref_filter_map(self.features.borrow(), |features| {
features.query_parameter_handlers.get(&name).map(|item| &item.func)
})
}
fn register_all_extensions(&self) {
self.register::<ext::oestexturefloat::OESTextureFloat>();
self.register::<ext::oestexturefloatlinear::OESTextureFloatLinear>();
self.register::<ext::oestexturehalffloat::OESTextureHalfFloat>();
self.register::<ext::oestexturehalffloatlinear::OESTextureHalfFloatLinear>();
self.register::<ext::oesvertexarrayobject::OESVertexArrayObject>();
}
}
// Helper structs
#[derive(JSTraceable, HeapSizeOf, PartialEq, Eq, Hash)]
struct TexFormatType(u32, u32);
type WebGLQueryParameterFunc = Fn(*mut JSContext, &WebGLRenderingContext)
-> Result<JSVal, WebGLError>;
#[derive(HeapSizeOf)]
struct WebGLQueryParameterHandler {
#[ignore_heap_size_of = "Closures are hard"]
func: Box<WebGLQueryParameterFunc>
}
unsafe_no_jsmanaged_fields!(WebGLQueryParameterHandler);
|
{
let handler = WebGLQueryParameterHandler {
func: f
};
self.features.borrow_mut().query_parameter_handlers.insert(name, handler);
}
|
identifier_body
|
literals.rs
|
use nom::{self, IResult, digit, Slice};
use misc::{StrSpan, Location};
macro_rules! recognize2 (
($i:expr, $submac:ident!( $($args:tt)* )) => ({
use nom::Offset;
use nom::Slice;
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,_) => {
let index = ($i).offset(&i);
$crate::IResult::Done(i, ($i).slice(..index))
},
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
});
($i:expr, $f:expr) => (
recognize2!($i, call!($f))
);
);
/// [A literal value]
/// (https://github.com/estree/estree/blob/master/es5.md#literal)
///
/// This has to be used with the `Literal` struct
#[derive(Debug, PartialEq)]
pub enum LiteralValue {
Null,
Number(f64),
String(String),
Boolean(bool),
Regexp { pattern: String, flags: Vec<char> },
}
/// [A literal expression]
/// (https://github.com/estree/estree/blob/master/es5.md#literal)
#[derive(Debug, PartialEq)]
pub struct
|
<'a> {
pub value: LiteralValue,
pub loc: Location<'a>
}
/// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-LineTerminator
const LINE_TERMINATORS: &'static str = "\n\r\u{2028}\u{2029}";
// equivalent to: "\u{000a}\u{000d}\u{2028}\u{2029}";
/// null literal value parser
/// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-NullLiteral
named!(null_literal_value< StrSpan, LiteralValue >, do_parse!(
tag!("null") >>
(LiteralValue::Null)
));
/// boolean literal value parser
/// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-BooleanLiteral
named!(boolean_literal_value< StrSpan, LiteralValue >, alt!(
tag!("true") => { |_| LiteralValue::Boolean(true) } |
tag!("false") => { |_| LiteralValue::Boolean(false) }
));
/// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-SignedInteger
named!(signed_integer< StrSpan, (Option<char>, StrSpan) >, pair!(
opt!(one_of!("-+")),
digit
));
// Adapted from Geal's JSON parser
// https://github.com/Geal/nom/blob/66128e5ccf316f60fdd55a7ae8d266f42955b00c/benches/json.rs#L23-L48
/// Parses decimal floats
/// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-DecimalLiteral
named!(decimal_float< StrSpan, f64 >, map_res!(
recognize2!(
pair!(
alt_complete!(
delimited!(digit, tag!("."), opt!(complete!(digit))) |
delimited!(opt!(digit), tag!("."), digit) |
digit
),
opt2!(
preceded!(
tag_no_case!("e"),
call!(signed_integer)
)
)
)
),
|raw_value: StrSpan| {
raw_value.fragment.parse::<f64>()
}
));
/// Parses octal integers
/// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-OctalIntegerLiteral
named!(octal_integer< StrSpan, f64 >, preceded!(
alt!(
tag_no_case!("0o") |
tag!("0")
),
fold_many1!(one_of!("01234567"), 0.0, digit_accumulator_callback(8))
));
/// Parses binary integers
/// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-BinaryIntegerLiteral
named!(binary_integer< StrSpan, f64 >, preceded!(
tag_no_case!("0b"),
fold_many1!(one_of!("01"), 0.0, digit_accumulator_callback(2))
));
/// Parses hexadecimal integers
/// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-HexIntegerLiteral
named!(hexadecimal_integer< StrSpan, f64 >, preceded!(
tag_no_case!("0x"),
fold_many1!(one_of!("0123456789abcdefABCDEF"), 0.0, digit_accumulator_callback(16))
));
/// Number literal value parser, whether that's in a decimal,
/// an octal, an hexadecimal or a binary base
named!(number_literal_value< StrSpan, LiteralValue >, map!(
alt_complete!(
octal_integer |
binary_integer |
hexadecimal_integer |
decimal_float
), |value| {
LiteralValue::Number(value)
}
));
/// string literal value parser
named!(string_literal_value< StrSpan, LiteralValue >, do_parse!(
string: call!(eat_string) >>
(LiteralValue::String(string.to_string()))
));
named!(regexp_char< StrSpan, String >, alt!(
none_of!("\\/") => { |c: char| c.to_string() } |
preceded!(char!('\\'), take!(1)) => { |c: StrSpan|
if c.to_string() == "\\" { c.to_string() } else { "\\".to_string() + &c.to_string() }
}
));
/// regexp literal value parser
named!(regexp_literal_value< StrSpan, LiteralValue >, do_parse!(
body: delimited!(char!('/'), many1!(regexp_char), char!('/')) >>
flags: many0!(one_of!("abcdefghijklmnopqrstuvwxyz")) >> // FIXME: be closer to the spec
(LiteralValue::Regexp {
pattern: body.join(""),
flags: flags,
})
));
/// generic literal value parser
named!(literal_value< StrSpan, LiteralValue >, alt!(
number_literal_value |
null_literal_value |
boolean_literal_value |
string_literal_value |
regexp_literal_value
));
/// Literal parser
named!(pub literal< StrSpan, Literal >, es_parse!({
value: literal_value
} => (Literal {
value: value
})
));
// ==================================================================
// ============================= HELPERS ============================
// ==================================================================
/// Returns a whole string (with its delimiters), escaping the backslashes
fn eat_string(located_span: StrSpan) -> IResult< StrSpan, String > {
let string = located_span.fragment;
let error = nom::IResult::Error(error_position!(es_error!(InvalidString), string));
if string.len() == 0 {
return IResult::Incomplete(nom::Needed::Unknown);
}
let mut chars = string.char_indices();
let separator = match chars.nth(0) {
Some((_, sep)) if (sep == '"' || sep == '\'') => sep,
// FIXME meaningfull error codes
Some(_) | None => return error
};
let mut escaped = false;
let mut ignore_next_char_if_linefeed = false;
let mut unescaped_string = String::new();
while let Some((idx, item)) = chars.next() {
if ignore_next_char_if_linefeed && item == '\n' {
ignore_next_char_if_linefeed = false;
continue;
}
if escaped {
match item {
// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-LineContinuation
'\r' => ignore_next_char_if_linefeed = true,
c if LINE_TERMINATORS.contains(c) => {},
// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-SingleEscapeCharacter
'b' => unescaped_string.push(0x08 as char),
't' => unescaped_string.push(0x09 as char),
'n' => unescaped_string.push(0x0a as char),
'v' => unescaped_string.push(0x0b as char),
'f' => unescaped_string.push(0x0c as char),
'r' => unescaped_string.push(0x0d as char),
'"' => unescaped_string.push(0x22 as char),
'\'' => unescaped_string.push(0x27 as char),
'\\' => unescaped_string.push(0x5c as char),
// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-HexEscapeSequence
'x' => {
let digits: String = match (chars.next(), chars.next()) {
(Some((_, c0)), Some((_, c1))) => vec![c0, c1].iter().collect(),
(_, None) => return IResult::Incomplete(nom::Needed::Unknown),
(None, Some(_)) => panic!("First call to.next() returned None, but second one did not."),
};
let c = match u8::from_str_radix(&digits, 16) {
Ok(u) => u as char,
// TODO: better error
_ => return error,
};
unescaped_string.push(c);
},
// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-UnicodeEscapeSequence
'u' => {
let digits: String = match chars.next() {
Some((_, c0)) if c0 == '{' => chars.by_ref().take_while(|&(_, c)| c!= '}').map(|(_, c)| c).collect(),
Some((_, c0)) => {
let c1 = chars.next(); let c2 = chars.next();
match chars.next() {
Some((_, c3)) => vec![c0, c1.unwrap().1, c2.unwrap().1, c3].iter().collect(), // These unwraps can't panic
None => return IResult::Incomplete(nom::Needed::Unknown),
}
},
None => return error,
};
let c = match u32::from_str_radix(&digits, 16) {
Ok(u) if u <= 1114111 => {
match ::std::char::from_u32(u) {
Some(c) => c,
None => return error,
}
},
// TODO: better error
_ => return error,
};
unescaped_string.push(c);
},
_ => unescaped_string.push(item),
};
escaped = false;
} else {
match item {
c if c == separator => return IResult::Done(located_span.slice(idx+1..), unescaped_string),
'\\' => escaped = true,
c if LINE_TERMINATORS.contains(c) => return IResult::Incomplete(nom::Needed::Unknown),
_ => unescaped_string.push(item),
}
}
}
return IResult::Error(error_position!(es_error!(InvalidString), string));
}
type DigitAccumulatorCallback = Fn(f64, char) -> f64;
/// Returns an accumulator callback for bases other than decimal.
fn digit_accumulator_callback(base: u32) -> Box<DigitAccumulatorCallback> {
Box::new(move |acc: f64, digit_as_char: char| {
let digit = digit_as_char.to_digit(base)
.expect("unexpected character encountered") as f64;
acc * (base as f64) + digit
})
}
|
Literal
|
identifier_name
|
literals.rs
|
use nom::{self, IResult, digit, Slice};
use misc::{StrSpan, Location};
macro_rules! recognize2 (
($i:expr, $submac:ident!( $($args:tt)* )) => ({
use nom::Offset;
use nom::Slice;
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,_) => {
let index = ($i).offset(&i);
$crate::IResult::Done(i, ($i).slice(..index))
},
|
}
});
($i:expr, $f:expr) => (
recognize2!($i, call!($f))
);
);
/// [A literal value]
/// (https://github.com/estree/estree/blob/master/es5.md#literal)
///
/// This has to be used with the `Literal` struct
#[derive(Debug, PartialEq)]
pub enum LiteralValue {
Null,
Number(f64),
String(String),
Boolean(bool),
Regexp { pattern: String, flags: Vec<char> },
}
/// [A literal expression]
/// (https://github.com/estree/estree/blob/master/es5.md#literal)
#[derive(Debug, PartialEq)]
pub struct Literal<'a> {
pub value: LiteralValue,
pub loc: Location<'a>
}
/// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-LineTerminator
const LINE_TERMINATORS: &'static str = "\n\r\u{2028}\u{2029}";
// equivalent to: "\u{000a}\u{000d}\u{2028}\u{2029}";
/// null literal value parser
/// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-NullLiteral
named!(null_literal_value< StrSpan, LiteralValue >, do_parse!(
tag!("null") >>
(LiteralValue::Null)
));
/// boolean literal value parser
/// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-BooleanLiteral
named!(boolean_literal_value< StrSpan, LiteralValue >, alt!(
tag!("true") => { |_| LiteralValue::Boolean(true) } |
tag!("false") => { |_| LiteralValue::Boolean(false) }
));
/// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-SignedInteger
named!(signed_integer< StrSpan, (Option<char>, StrSpan) >, pair!(
opt!(one_of!("-+")),
digit
));
// Adapted from Geal's JSON parser
// https://github.com/Geal/nom/blob/66128e5ccf316f60fdd55a7ae8d266f42955b00c/benches/json.rs#L23-L48
/// Parses decimal floats
/// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-DecimalLiteral
named!(decimal_float< StrSpan, f64 >, map_res!(
recognize2!(
pair!(
alt_complete!(
delimited!(digit, tag!("."), opt!(complete!(digit))) |
delimited!(opt!(digit), tag!("."), digit) |
digit
),
opt2!(
preceded!(
tag_no_case!("e"),
call!(signed_integer)
)
)
)
),
|raw_value: StrSpan| {
raw_value.fragment.parse::<f64>()
}
));
/// Parses octal integers
/// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-OctalIntegerLiteral
named!(octal_integer< StrSpan, f64 >, preceded!(
alt!(
tag_no_case!("0o") |
tag!("0")
),
fold_many1!(one_of!("01234567"), 0.0, digit_accumulator_callback(8))
));
/// Parses binary integers
/// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-BinaryIntegerLiteral
named!(binary_integer< StrSpan, f64 >, preceded!(
tag_no_case!("0b"),
fold_many1!(one_of!("01"), 0.0, digit_accumulator_callback(2))
));
/// Parses hexadecimal integers
/// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-HexIntegerLiteral
named!(hexadecimal_integer< StrSpan, f64 >, preceded!(
tag_no_case!("0x"),
fold_many1!(one_of!("0123456789abcdefABCDEF"), 0.0, digit_accumulator_callback(16))
));
/// Number literal value parser, whether that's in a decimal,
/// an octal, an hexadecimal or a binary base
named!(number_literal_value< StrSpan, LiteralValue >, map!(
alt_complete!(
octal_integer |
binary_integer |
hexadecimal_integer |
decimal_float
), |value| {
LiteralValue::Number(value)
}
));
/// string literal value parser
named!(string_literal_value< StrSpan, LiteralValue >, do_parse!(
string: call!(eat_string) >>
(LiteralValue::String(string.to_string()))
));
named!(regexp_char< StrSpan, String >, alt!(
none_of!("\\/") => { |c: char| c.to_string() } |
preceded!(char!('\\'), take!(1)) => { |c: StrSpan|
if c.to_string() == "\\" { c.to_string() } else { "\\".to_string() + &c.to_string() }
}
));
/// regexp literal value parser
named!(regexp_literal_value< StrSpan, LiteralValue >, do_parse!(
body: delimited!(char!('/'), many1!(regexp_char), char!('/')) >>
flags: many0!(one_of!("abcdefghijklmnopqrstuvwxyz")) >> // FIXME: be closer to the spec
(LiteralValue::Regexp {
pattern: body.join(""),
flags: flags,
})
));
/// generic literal value parser
named!(literal_value< StrSpan, LiteralValue >, alt!(
number_literal_value |
null_literal_value |
boolean_literal_value |
string_literal_value |
regexp_literal_value
));
/// Literal parser
named!(pub literal< StrSpan, Literal >, es_parse!({
value: literal_value
} => (Literal {
value: value
})
));
// ==================================================================
// ============================= HELPERS ============================
// ==================================================================
/// Returns a whole string (with its delimiters), escaping the backslashes
fn eat_string(located_span: StrSpan) -> IResult< StrSpan, String > {
let string = located_span.fragment;
let error = nom::IResult::Error(error_position!(es_error!(InvalidString), string));
if string.len() == 0 {
return IResult::Incomplete(nom::Needed::Unknown);
}
let mut chars = string.char_indices();
let separator = match chars.nth(0) {
Some((_, sep)) if (sep == '"' || sep == '\'') => sep,
// FIXME meaningfull error codes
Some(_) | None => return error
};
let mut escaped = false;
let mut ignore_next_char_if_linefeed = false;
let mut unescaped_string = String::new();
while let Some((idx, item)) = chars.next() {
if ignore_next_char_if_linefeed && item == '\n' {
ignore_next_char_if_linefeed = false;
continue;
}
if escaped {
match item {
// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-LineContinuation
'\r' => ignore_next_char_if_linefeed = true,
c if LINE_TERMINATORS.contains(c) => {},
// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-SingleEscapeCharacter
'b' => unescaped_string.push(0x08 as char),
't' => unescaped_string.push(0x09 as char),
'n' => unescaped_string.push(0x0a as char),
'v' => unescaped_string.push(0x0b as char),
'f' => unescaped_string.push(0x0c as char),
'r' => unescaped_string.push(0x0d as char),
'"' => unescaped_string.push(0x22 as char),
'\'' => unescaped_string.push(0x27 as char),
'\\' => unescaped_string.push(0x5c as char),
// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-HexEscapeSequence
'x' => {
let digits: String = match (chars.next(), chars.next()) {
(Some((_, c0)), Some((_, c1))) => vec![c0, c1].iter().collect(),
(_, None) => return IResult::Incomplete(nom::Needed::Unknown),
(None, Some(_)) => panic!("First call to.next() returned None, but second one did not."),
};
let c = match u8::from_str_radix(&digits, 16) {
Ok(u) => u as char,
// TODO: better error
_ => return error,
};
unescaped_string.push(c);
},
// https://www.ecma-international.org/ecma-262/7.0/index.html#prod-UnicodeEscapeSequence
'u' => {
let digits: String = match chars.next() {
Some((_, c0)) if c0 == '{' => chars.by_ref().take_while(|&(_, c)| c!= '}').map(|(_, c)| c).collect(),
Some((_, c0)) => {
let c1 = chars.next(); let c2 = chars.next();
match chars.next() {
Some((_, c3)) => vec![c0, c1.unwrap().1, c2.unwrap().1, c3].iter().collect(), // These unwraps can't panic
None => return IResult::Incomplete(nom::Needed::Unknown),
}
},
None => return error,
};
let c = match u32::from_str_radix(&digits, 16) {
Ok(u) if u <= 1114111 => {
match ::std::char::from_u32(u) {
Some(c) => c,
None => return error,
}
},
// TODO: better error
_ => return error,
};
unescaped_string.push(c);
},
_ => unescaped_string.push(item),
};
escaped = false;
} else {
match item {
c if c == separator => return IResult::Done(located_span.slice(idx+1..), unescaped_string),
'\\' => escaped = true,
c if LINE_TERMINATORS.contains(c) => return IResult::Incomplete(nom::Needed::Unknown),
_ => unescaped_string.push(item),
}
}
}
return IResult::Error(error_position!(es_error!(InvalidString), string));
}
type DigitAccumulatorCallback = Fn(f64, char) -> f64;
/// Returns an accumulator callback for bases other than decimal.
fn digit_accumulator_callback(base: u32) -> Box<DigitAccumulatorCallback> {
Box::new(move |acc: f64, digit_as_char: char| {
let digit = digit_as_char.to_digit(base)
.expect("unexpected character encountered") as f64;
acc * (base as f64) + digit
})
}
|
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
|
random_line_split
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate proc_macro;
extern crate syn;
extern crate synstructure;
#[proc_macro_derive(DenyPublicFields)]
pub fn expand_token_stream(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
expand_string(&input.to_string()).parse().unwrap()
}
fn expand_string(input: &str) -> String
|
{
let type_ = syn::parse_macro_input(input).unwrap();
let style = synstructure::BindStyle::Ref.into();
synstructure::each_field(&type_, &style, |binding| {
if binding.field.vis != syn::Visibility::Inherited {
panic!("Field `{}` should not be public",
binding.field.ident.as_ref().unwrap_or(&binding.ident));
}
"".to_owned()
});
"".to_owned()
}
|
identifier_body
|
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate proc_macro;
extern crate syn;
extern crate synstructure;
#[proc_macro_derive(DenyPublicFields)]
pub fn expand_token_stream(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
expand_string(&input.to_string()).parse().unwrap()
}
fn expand_string(input: &str) -> String {
let type_ = syn::parse_macro_input(input).unwrap();
let style = synstructure::BindStyle::Ref.into();
synstructure::each_field(&type_, &style, |binding| {
if binding.field.vis!= syn::Visibility::Inherited
|
"".to_owned()
});
"".to_owned()
}
|
{
panic!("Field `{}` should not be public",
binding.field.ident.as_ref().unwrap_or(&binding.ident));
}
|
conditional_block
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate proc_macro;
extern crate syn;
extern crate synstructure;
#[proc_macro_derive(DenyPublicFields)]
pub fn expand_token_stream(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
expand_string(&input.to_string()).parse().unwrap()
|
let style = synstructure::BindStyle::Ref.into();
synstructure::each_field(&type_, &style, |binding| {
if binding.field.vis!= syn::Visibility::Inherited {
panic!("Field `{}` should not be public",
binding.field.ident.as_ref().unwrap_or(&binding.ident));
}
"".to_owned()
});
"".to_owned()
}
|
}
fn expand_string(input: &str) -> String {
let type_ = syn::parse_macro_input(input).unwrap();
|
random_line_split
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate proc_macro;
extern crate syn;
extern crate synstructure;
#[proc_macro_derive(DenyPublicFields)]
pub fn expand_token_stream(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
expand_string(&input.to_string()).parse().unwrap()
}
fn
|
(input: &str) -> String {
let type_ = syn::parse_macro_input(input).unwrap();
let style = synstructure::BindStyle::Ref.into();
synstructure::each_field(&type_, &style, |binding| {
if binding.field.vis!= syn::Visibility::Inherited {
panic!("Field `{}` should not be public",
binding.field.ident.as_ref().unwrap_or(&binding.ident));
}
"".to_owned()
});
"".to_owned()
}
|
expand_string
|
identifier_name
|
mir_codegen_switch.rs
|
// run-pass
enum Abc {
A(u8),
B(i8),
C,
D,
}
fn foo(x: Abc) -> i32 {
match x {
Abc::C => 3,
Abc::D => 4,
Abc::B(_) => 2,
|
match x {
Abc::D => true,
_ => false
}
}
fn main() {
assert_eq!(1, foo(Abc::A(42)));
assert_eq!(2, foo(Abc::B(-100)));
assert_eq!(3, foo(Abc::C));
assert_eq!(4, foo(Abc::D));
assert_eq!(false, foo2(Abc::A(1)));
assert_eq!(false, foo2(Abc::B(2)));
assert_eq!(false, foo2(Abc::C));
assert_eq!(true, foo2(Abc::D));
}
|
Abc::A(_) => 1,
}
}
fn foo2(x: Abc) -> bool {
|
random_line_split
|
mir_codegen_switch.rs
|
// run-pass
enum Abc {
A(u8),
B(i8),
C,
D,
}
fn foo(x: Abc) -> i32 {
match x {
Abc::C => 3,
Abc::D => 4,
Abc::B(_) => 2,
Abc::A(_) => 1,
}
}
fn foo2(x: Abc) -> bool {
match x {
Abc::D => true,
_ => false
}
}
fn
|
() {
assert_eq!(1, foo(Abc::A(42)));
assert_eq!(2, foo(Abc::B(-100)));
assert_eq!(3, foo(Abc::C));
assert_eq!(4, foo(Abc::D));
assert_eq!(false, foo2(Abc::A(1)));
assert_eq!(false, foo2(Abc::B(2)));
assert_eq!(false, foo2(Abc::C));
assert_eq!(true, foo2(Abc::D));
}
|
main
|
identifier_name
|
mir_codegen_switch.rs
|
// run-pass
enum Abc {
A(u8),
B(i8),
C,
D,
}
fn foo(x: Abc) -> i32 {
match x {
Abc::C => 3,
Abc::D => 4,
Abc::B(_) => 2,
Abc::A(_) => 1,
}
}
fn foo2(x: Abc) -> bool {
match x {
Abc::D => true,
_ => false
}
}
fn main()
|
{
assert_eq!(1, foo(Abc::A(42)));
assert_eq!(2, foo(Abc::B(-100)));
assert_eq!(3, foo(Abc::C));
assert_eq!(4, foo(Abc::D));
assert_eq!(false, foo2(Abc::A(1)));
assert_eq!(false, foo2(Abc::B(2)));
assert_eq!(false, foo2(Abc::C));
assert_eq!(true, foo2(Abc::D));
}
|
identifier_body
|
|
abi.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub use self::Os::*;
pub use self::Abi::*;
pub use self::Architecture::*;
pub use self::AbiArchitecture::*;
use std::fmt;
#[deriving(PartialEq)]
pub enum Os { OsWindows, OsMacos, OsLinux, OsAndroid, OsFreebsd, OsiOS,
OsDragonfly }
#[deriving(PartialEq, Eq, Hash, Encodable, Decodable, Clone)]
pub enum Abi {
// NB: This ordering MUST match the AbiDatas array below.
// (This is ensured by the test indices_are_correct().)
// Single platform ABIs come first (`for_arch()` relies on this)
Cdecl,
Stdcall,
Fastcall,
Aapcs,
Win64,
// Multiplatform ABIs second
Rust,
C,
System,
RustIntrinsic,
RustCall,
}
#[allow(non_camel_case_types)]
#[deriving(PartialEq)]
pub enum Architecture {
X86,
X86_64,
Arm,
Mips,
Mipsel
}
pub struct AbiData {
abi: Abi,
// Name of this ABI as we like it called.
name: &'static str,
}
pub enum AbiArchitecture {
/// Not a real ABI (e.g., intrinsic)
RustArch,
/// An ABI that specifies cross-platform defaults (e.g., "C")
AllArch,
/// Multiple architectures (bitset)
Archs(u32)
}
#[allow(non_upper_case_globals)]
static AbiDatas: &'static [AbiData] = &[
// Platform-specific ABIs
AbiData {abi: Cdecl, name: "cdecl" },
AbiData {abi: Stdcall, name: "stdcall" },
AbiData {abi: Fastcall, name:"fastcall" },
AbiData {abi: Aapcs, name: "aapcs" },
AbiData {abi: Win64, name: "win64" },
// Cross-platform ABIs
//
// NB: Do not adjust this ordering without
// adjusting the indices below.
AbiData {abi: Rust, name: "Rust" },
AbiData {abi: C, name: "C" },
AbiData {abi: System, name: "system" },
AbiData {abi: RustIntrinsic, name: "rust-intrinsic" },
AbiData {abi: RustCall, name: "rust-call" },
];
/// Returns the ABI with the given name (if any).
pub fn lookup(name: &str) -> Option<Abi> {
AbiDatas.iter().find(|abi_data| name == abi_data.name).map(|&x| x.abi)
}
pub fn all_names() -> Vec<&'static str> {
AbiDatas.iter().map(|d| d.name).collect()
}
impl Abi {
#[inline]
pub fn index(&self) -> uint
|
#[inline]
pub fn data(&self) -> &'static AbiData {
&AbiDatas[self.index()]
}
pub fn name(&self) -> &'static str {
self.data().name
}
}
impl fmt::Show for Abi {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\"{}\"", self.name())
}
}
impl fmt::Show for Os {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
OsLinux => "linux".fmt(f),
OsWindows => "windows".fmt(f),
OsMacos => "macos".fmt(f),
OsiOS => "ios".fmt(f),
OsAndroid => "android".fmt(f),
OsFreebsd => "freebsd".fmt(f),
OsDragonfly => "dragonfly".fmt(f)
}
}
}
#[allow(non_snake_case)]
#[test]
fn lookup_Rust() {
let abi = lookup("Rust");
assert!(abi.is_some() && abi.unwrap().data().name == "Rust");
}
#[test]
fn lookup_cdecl() {
let abi = lookup("cdecl");
assert!(abi.is_some() && abi.unwrap().data().name == "cdecl");
}
#[test]
fn lookup_baz() {
let abi = lookup("baz");
assert!(abi.is_none());
}
#[test]
fn indices_are_correct() {
for (i, abi_data) in AbiDatas.iter().enumerate() {
assert_eq!(i, abi_data.abi.index());
}
}
|
{
*self as uint
}
|
identifier_body
|
abi.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub use self::Os::*;
pub use self::Abi::*;
pub use self::Architecture::*;
pub use self::AbiArchitecture::*;
use std::fmt;
#[deriving(PartialEq)]
pub enum Os { OsWindows, OsMacos, OsLinux, OsAndroid, OsFreebsd, OsiOS,
OsDragonfly }
#[deriving(PartialEq, Eq, Hash, Encodable, Decodable, Clone)]
pub enum Abi {
// NB: This ordering MUST match the AbiDatas array below.
// (This is ensured by the test indices_are_correct().)
// Single platform ABIs come first (`for_arch()` relies on this)
Cdecl,
Stdcall,
Fastcall,
Aapcs,
Win64,
// Multiplatform ABIs second
Rust,
C,
System,
RustIntrinsic,
RustCall,
}
#[allow(non_camel_case_types)]
#[deriving(PartialEq)]
pub enum Architecture {
X86,
X86_64,
Arm,
Mips,
Mipsel
}
pub struct AbiData {
abi: Abi,
// Name of this ABI as we like it called.
name: &'static str,
}
pub enum AbiArchitecture {
/// Not a real ABI (e.g., intrinsic)
RustArch,
/// An ABI that specifies cross-platform defaults (e.g., "C")
AllArch,
/// Multiple architectures (bitset)
Archs(u32)
}
#[allow(non_upper_case_globals)]
static AbiDatas: &'static [AbiData] = &[
// Platform-specific ABIs
AbiData {abi: Cdecl, name: "cdecl" },
AbiData {abi: Stdcall, name: "stdcall" },
AbiData {abi: Fastcall, name:"fastcall" },
AbiData {abi: Aapcs, name: "aapcs" },
AbiData {abi: Win64, name: "win64" },
// Cross-platform ABIs
//
// NB: Do not adjust this ordering without
// adjusting the indices below.
AbiData {abi: Rust, name: "Rust" },
AbiData {abi: C, name: "C" },
AbiData {abi: System, name: "system" },
AbiData {abi: RustIntrinsic, name: "rust-intrinsic" },
AbiData {abi: RustCall, name: "rust-call" },
];
/// Returns the ABI with the given name (if any).
pub fn lookup(name: &str) -> Option<Abi> {
AbiDatas.iter().find(|abi_data| name == abi_data.name).map(|&x| x.abi)
}
pub fn all_names() -> Vec<&'static str> {
AbiDatas.iter().map(|d| d.name).collect()
}
impl Abi {
#[inline]
pub fn index(&self) -> uint {
*self as uint
}
#[inline]
pub fn data(&self) -> &'static AbiData {
&AbiDatas[self.index()]
}
pub fn name(&self) -> &'static str {
self.data().name
}
}
impl fmt::Show for Abi {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\"{}\"", self.name())
}
}
impl fmt::Show for Os {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
OsLinux => "linux".fmt(f),
OsWindows => "windows".fmt(f),
OsMacos => "macos".fmt(f),
OsiOS => "ios".fmt(f),
OsAndroid => "android".fmt(f),
OsFreebsd => "freebsd".fmt(f),
OsDragonfly => "dragonfly".fmt(f)
}
}
}
#[allow(non_snake_case)]
#[test]
fn lookup_Rust() {
let abi = lookup("Rust");
assert!(abi.is_some() && abi.unwrap().data().name == "Rust");
}
#[test]
|
assert!(abi.is_some() && abi.unwrap().data().name == "cdecl");
}
#[test]
fn lookup_baz() {
let abi = lookup("baz");
assert!(abi.is_none());
}
#[test]
fn indices_are_correct() {
for (i, abi_data) in AbiDatas.iter().enumerate() {
assert_eq!(i, abi_data.abi.index());
}
}
|
fn lookup_cdecl() {
let abi = lookup("cdecl");
|
random_line_split
|
abi.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub use self::Os::*;
pub use self::Abi::*;
pub use self::Architecture::*;
pub use self::AbiArchitecture::*;
use std::fmt;
#[deriving(PartialEq)]
pub enum Os { OsWindows, OsMacos, OsLinux, OsAndroid, OsFreebsd, OsiOS,
OsDragonfly }
#[deriving(PartialEq, Eq, Hash, Encodable, Decodable, Clone)]
pub enum Abi {
// NB: This ordering MUST match the AbiDatas array below.
// (This is ensured by the test indices_are_correct().)
// Single platform ABIs come first (`for_arch()` relies on this)
Cdecl,
Stdcall,
Fastcall,
Aapcs,
Win64,
// Multiplatform ABIs second
Rust,
C,
System,
RustIntrinsic,
RustCall,
}
#[allow(non_camel_case_types)]
#[deriving(PartialEq)]
pub enum Architecture {
X86,
X86_64,
Arm,
Mips,
Mipsel
}
pub struct AbiData {
abi: Abi,
// Name of this ABI as we like it called.
name: &'static str,
}
pub enum AbiArchitecture {
/// Not a real ABI (e.g., intrinsic)
RustArch,
/// An ABI that specifies cross-platform defaults (e.g., "C")
AllArch,
/// Multiple architectures (bitset)
Archs(u32)
}
#[allow(non_upper_case_globals)]
static AbiDatas: &'static [AbiData] = &[
// Platform-specific ABIs
AbiData {abi: Cdecl, name: "cdecl" },
AbiData {abi: Stdcall, name: "stdcall" },
AbiData {abi: Fastcall, name:"fastcall" },
AbiData {abi: Aapcs, name: "aapcs" },
AbiData {abi: Win64, name: "win64" },
// Cross-platform ABIs
//
// NB: Do not adjust this ordering without
// adjusting the indices below.
AbiData {abi: Rust, name: "Rust" },
AbiData {abi: C, name: "C" },
AbiData {abi: System, name: "system" },
AbiData {abi: RustIntrinsic, name: "rust-intrinsic" },
AbiData {abi: RustCall, name: "rust-call" },
];
/// Returns the ABI with the given name (if any).
pub fn lookup(name: &str) -> Option<Abi> {
AbiDatas.iter().find(|abi_data| name == abi_data.name).map(|&x| x.abi)
}
pub fn all_names() -> Vec<&'static str> {
AbiDatas.iter().map(|d| d.name).collect()
}
impl Abi {
#[inline]
pub fn index(&self) -> uint {
*self as uint
}
#[inline]
pub fn data(&self) -> &'static AbiData {
&AbiDatas[self.index()]
}
pub fn name(&self) -> &'static str {
self.data().name
}
}
impl fmt::Show for Abi {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\"{}\"", self.name())
}
}
impl fmt::Show for Os {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
OsLinux => "linux".fmt(f),
OsWindows => "windows".fmt(f),
OsMacos => "macos".fmt(f),
OsiOS => "ios".fmt(f),
OsAndroid => "android".fmt(f),
OsFreebsd => "freebsd".fmt(f),
OsDragonfly => "dragonfly".fmt(f)
}
}
}
#[allow(non_snake_case)]
#[test]
fn lookup_Rust() {
let abi = lookup("Rust");
assert!(abi.is_some() && abi.unwrap().data().name == "Rust");
}
#[test]
fn
|
() {
let abi = lookup("cdecl");
assert!(abi.is_some() && abi.unwrap().data().name == "cdecl");
}
#[test]
fn lookup_baz() {
let abi = lookup("baz");
assert!(abi.is_none());
}
#[test]
fn indices_are_correct() {
for (i, abi_data) in AbiDatas.iter().enumerate() {
assert_eq!(i, abi_data.abi.index());
}
}
|
lookup_cdecl
|
identifier_name
|
test.rs
|
extern crate vote;
extern crate safex;
use vote::utils::get_address_methods::get_omniwalletorg;
use vote::utils::get_address_methods::OmniList;
use vote::voting::poll_genesis::{PollRound, PollHash, PollPersona};
use vote::voting::vote_genesis::{VoteRound};
use vote::voting::validate_genesis::{VotingOutcome};
use safex::genesis::key_generation::KeyPair;
fn
|
() {
//PollRound::make_poll();
//VoteRound::form_vote();
println!("{:?}", VotingOutcome::validate_outcome());
/*
let the_keys = KeyPair::create().unwrap();
let omni_list = get_omniwalletorg(56);
let our_keys = PollPersona::import_keys();
let keys = our_keys.return_keys();
let our_poll = PollRound::new_wparams("hello".to_string(), 1, 2, vec!["hello".to_string(), "goodbye".to_string()], 3, &keys, omni_list);
//our_poll.write_poll();
//number 56 equates to Omni Smart Property #56 "SafeExchangeCoin"
let the_list = get_omniwalletorg(56);
let list_elements = the_list.return_list();
print!("\n");
let contains_or = the_list.check_existence("15N8mbsRwiwyQpsTUcGfETpStYkTFjcHvh".to_string());
print!("Does the address contain? 15N8mbsRwiwyQpsTUcGfETpStYkTFjcHvh : {:?} \n", contains_or);
let mut int_new = 0;
for thethings in 0..list_elements.len() {
if list_elements[thethings].balance > 0 {
int_new += 1;
println!("#{:?}", int_new);
println!("address: {:?}", &list_elements[thethings].address);
println!("safe exchange coin balance: {:?}", &list_elements[thethings].balance);
}
}
*/
}
|
main
|
identifier_name
|
test.rs
|
extern crate vote;
extern crate safex;
use vote::utils::get_address_methods::get_omniwalletorg;
use vote::utils::get_address_methods::OmniList;
use vote::voting::poll_genesis::{PollRound, PollHash, PollPersona};
use vote::voting::vote_genesis::{VoteRound};
use vote::voting::validate_genesis::{VotingOutcome};
use safex::genesis::key_generation::KeyPair;
fn main() {
//PollRound::make_poll();
//VoteRound::form_vote();
println!("{:?}", VotingOutcome::validate_outcome());
/*
let the_keys = KeyPair::create().unwrap();
let omni_list = get_omniwalletorg(56);
let our_keys = PollPersona::import_keys();
let keys = our_keys.return_keys();
let our_poll = PollRound::new_wparams("hello".to_string(), 1, 2, vec!["hello".to_string(), "goodbye".to_string()], 3, &keys, omni_list);
//our_poll.write_poll();
//number 56 equates to Omni Smart Property #56 "SafeExchangeCoin"
let the_list = get_omniwalletorg(56);
let list_elements = the_list.return_list();
print!("\n");
let contains_or = the_list.check_existence("15N8mbsRwiwyQpsTUcGfETpStYkTFjcHvh".to_string());
print!("Does the address contain? 15N8mbsRwiwyQpsTUcGfETpStYkTFjcHvh : {:?} \n", contains_or);
let mut int_new = 0;
|
if list_elements[thethings].balance > 0 {
int_new += 1;
println!("#{:?}", int_new);
println!("address: {:?}", &list_elements[thethings].address);
println!("safe exchange coin balance: {:?}", &list_elements[thethings].balance);
}
}
*/
}
|
for thethings in 0..list_elements.len() {
|
random_line_split
|
test.rs
|
extern crate vote;
extern crate safex;
use vote::utils::get_address_methods::get_omniwalletorg;
use vote::utils::get_address_methods::OmniList;
use vote::voting::poll_genesis::{PollRound, PollHash, PollPersona};
use vote::voting::vote_genesis::{VoteRound};
use vote::voting::validate_genesis::{VotingOutcome};
use safex::genesis::key_generation::KeyPair;
fn main()
|
print!("\n");
let contains_or = the_list.check_existence("15N8mbsRwiwyQpsTUcGfETpStYkTFjcHvh".to_string());
print!("Does the address contain? 15N8mbsRwiwyQpsTUcGfETpStYkTFjcHvh : {:?} \n", contains_or);
let mut int_new = 0;
for thethings in 0..list_elements.len() {
if list_elements[thethings].balance > 0 {
int_new += 1;
println!("#{:?}", int_new);
println!("address: {:?}", &list_elements[thethings].address);
println!("safe exchange coin balance: {:?}", &list_elements[thethings].balance);
}
}
*/
}
|
{
//PollRound::make_poll();
//VoteRound::form_vote();
println!("{:?}", VotingOutcome::validate_outcome());
/*
let the_keys = KeyPair::create().unwrap();
let omni_list = get_omniwalletorg(56);
let our_keys = PollPersona::import_keys();
let keys = our_keys.return_keys();
let our_poll = PollRound::new_wparams("hello".to_string(), 1, 2, vec!["hello".to_string(), "goodbye".to_string()], 3, &keys, omni_list);
//our_poll.write_poll();
//number 56 equates to Omni Smart Property #56 "SafeExchangeCoin"
let the_list = get_omniwalletorg(56);
let list_elements = the_list.return_list();
|
identifier_body
|
cr1.rs
|
#[doc = "Register `CR1` reader"]
pub struct R(crate::R<CR1_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<CR1_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target
|
}
impl From<crate::R<CR1_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<CR1_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Field `CR1` reader - Compare Register for Channel 1"]
pub struct CR1_R(crate::FieldReader<u16, u16>);
impl CR1_R {
pub(crate) fn new(bits: u16) -> Self {
CR1_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR1_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl R {
#[doc = "Bits 0:15 - Compare Register for Channel 1"]
#[inline(always)]
pub fn cr1(&self) -> CR1_R {
CR1_R::new((self.bits & 0xffff) as u16)
}
}
#[doc = "Channel 1 Compare Value\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cr1](index.html) module"]
pub struct CR1_SPEC;
impl crate::RegisterSpec for CR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [cr1::R](R) reader structure"]
impl crate::Readable for CR1_SPEC {
type Reader = R;
}
#[doc = "`reset()` method sets CR1 to value 0"]
impl crate::Resettable for CR1_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
|
{
&self.0
}
|
identifier_body
|
cr1.rs
|
#[doc = "Register `CR1` reader"]
pub struct R(crate::R<CR1_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<CR1_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<CR1_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<CR1_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Field `CR1` reader - Compare Register for Channel 1"]
pub struct CR1_R(crate::FieldReader<u16, u16>);
impl CR1_R {
pub(crate) fn new(bits: u16) -> Self {
CR1_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR1_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl R {
#[doc = "Bits 0:15 - Compare Register for Channel 1"]
#[inline(always)]
pub fn
|
(&self) -> CR1_R {
CR1_R::new((self.bits & 0xffff) as u16)
}
}
#[doc = "Channel 1 Compare Value\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cr1](index.html) module"]
pub struct CR1_SPEC;
impl crate::RegisterSpec for CR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [cr1::R](R) reader structure"]
impl crate::Readable for CR1_SPEC {
type Reader = R;
}
#[doc = "`reset()` method sets CR1 to value 0"]
impl crate::Resettable for CR1_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
|
cr1
|
identifier_name
|
cr1.rs
|
#[doc = "Register `CR1` reader"]
pub struct R(crate::R<CR1_SPEC>);
impl core::ops::Deref for R {
|
&self.0
}
}
impl From<crate::R<CR1_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<CR1_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Field `CR1` reader - Compare Register for Channel 1"]
pub struct CR1_R(crate::FieldReader<u16, u16>);
impl CR1_R {
pub(crate) fn new(bits: u16) -> Self {
CR1_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CR1_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl R {
#[doc = "Bits 0:15 - Compare Register for Channel 1"]
#[inline(always)]
pub fn cr1(&self) -> CR1_R {
CR1_R::new((self.bits & 0xffff) as u16)
}
}
#[doc = "Channel 1 Compare Value\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cr1](index.html) module"]
pub struct CR1_SPEC;
impl crate::RegisterSpec for CR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [cr1::R](R) reader structure"]
impl crate::Readable for CR1_SPEC {
type Reader = R;
}
#[doc = "`reset()` method sets CR1 to value 0"]
impl crate::Resettable for CR1_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
|
type Target = crate::R<CR1_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
|
random_line_split
|
bitfield-enum-repr-c.rs
|
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
|
impl Foo {
pub const Bar: Foo = Foo(2);
}
impl Foo {
pub const Baz: Foo = Foo(4);
}
impl Foo {
pub const Duplicated: Foo = Foo(4);
}
impl Foo {
pub const Negative: Foo = Foo(-3);
}
impl ::std::ops::BitOr<Foo> for Foo {
type Output = Self;
#[inline]
fn bitor(self, other: Self) -> Self {
Foo(self.0 | other.0)
}
}
impl ::std::ops::BitOrAssign for Foo {
#[inline]
fn bitor_assign(&mut self, rhs: Foo) {
self.0 |= rhs.0;
}
}
impl ::std::ops::BitAnd<Foo> for Foo {
type Output = Self;
#[inline]
fn bitand(self, other: Self) -> Self {
Foo(self.0 & other.0)
}
}
impl ::std::ops::BitAndAssign for Foo {
#[inline]
fn bitand_assign(&mut self, rhs: Foo) {
self.0 &= rhs.0;
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct Foo(pub ::std::os::raw::c_int);
|
non_upper_case_globals
)]
|
random_line_split
|
bitfield-enum-repr-c.rs
|
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
impl Foo {
pub const Bar: Foo = Foo(2);
}
impl Foo {
pub const Baz: Foo = Foo(4);
}
impl Foo {
pub const Duplicated: Foo = Foo(4);
}
impl Foo {
pub const Negative: Foo = Foo(-3);
}
impl ::std::ops::BitOr<Foo> for Foo {
type Output = Self;
#[inline]
fn bitor(self, other: Self) -> Self {
Foo(self.0 | other.0)
}
}
impl ::std::ops::BitOrAssign for Foo {
#[inline]
fn bitor_assign(&mut self, rhs: Foo) {
self.0 |= rhs.0;
}
}
impl ::std::ops::BitAnd<Foo> for Foo {
type Output = Self;
#[inline]
fn bitand(self, other: Self) -> Self {
Foo(self.0 & other.0)
}
}
impl ::std::ops::BitAndAssign for Foo {
#[inline]
fn bitand_assign(&mut self, rhs: Foo)
|
}
#[repr(C)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct Foo(pub ::std::os::raw::c_int);
|
{
self.0 &= rhs.0;
}
|
identifier_body
|
bitfield-enum-repr-c.rs
|
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
impl Foo {
pub const Bar: Foo = Foo(2);
}
impl Foo {
pub const Baz: Foo = Foo(4);
}
impl Foo {
pub const Duplicated: Foo = Foo(4);
}
impl Foo {
pub const Negative: Foo = Foo(-3);
}
impl ::std::ops::BitOr<Foo> for Foo {
type Output = Self;
#[inline]
fn bitor(self, other: Self) -> Self {
Foo(self.0 | other.0)
}
}
impl ::std::ops::BitOrAssign for Foo {
#[inline]
fn bitor_assign(&mut self, rhs: Foo) {
self.0 |= rhs.0;
}
}
impl ::std::ops::BitAnd<Foo> for Foo {
type Output = Self;
#[inline]
fn
|
(self, other: Self) -> Self {
Foo(self.0 & other.0)
}
}
impl ::std::ops::BitAndAssign for Foo {
#[inline]
fn bitand_assign(&mut self, rhs: Foo) {
self.0 &= rhs.0;
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct Foo(pub ::std::os::raw::c_int);
|
bitand
|
identifier_name
|
prompt.rs
|
use std::env::{current_dir, home_dir};
use std::env;
use ansi_term::Colour::Purple;
use ansi_term::Colour::Green;
use ansi_term::Colour::Red;
pub struct Prompt {
user: String,
cwd: String,
error: i8,
}
impl Prompt {
pub fn new() -> Prompt {
let mut prompt = Prompt {
user: match env::var("USER") {
Ok(val) => Purple.paint(val).to_string(),
Err(_) => Purple.paint("?").to_string(),
},
cwd: "".to_string(),
error: 0,
};
prompt.update_cwd();
prompt
}
pub fn print(&self) -> String {
if self.error!= 0 {
format!("{} {}:{} > ", Red.paint(format!("\u{2718} {}", self.error)).to_string(), self.user, self.cwd)
} else {
format!("{}:{} > ", self.user, self.cwd)
}
}
pub fn update_cwd(&mut self)
|
pub fn update_error(&mut self, error: i8) {
self.error = error;
}
}
#[cfg(test)]
mod tests{
#[allow(unused_imports)]
use std::env::{current_dir,home_dir};
use super::*;
#[test]
fn updated_cwd() {
let mut testp = Prompt::new();
testp.update_cwd();
assert_eq!(testp.get_cwd(), current_dir().ok()
.expect("Couldn't get current directory").as_path()
.to_str()
.expect("Failed to go to string").to_owned());
}
}
|
{
let mut cwd = current_dir().unwrap().as_path().to_str().expect("Failed : path -> str").to_string();
let homedir = home_dir().unwrap().as_path().to_str().expect("Failed : path -> str").to_string();
self.cwd = if cwd.starts_with(homedir.as_str()) {
Green.paint(format!("~{}", cwd.split_off(homedir.len()))).to_string()
} else { Green.paint(cwd).to_string() };
}
|
identifier_body
|
prompt.rs
|
use std::env::{current_dir, home_dir};
use std::env;
use ansi_term::Colour::Purple;
use ansi_term::Colour::Green;
use ansi_term::Colour::Red;
pub struct Prompt {
user: String,
cwd: String,
error: i8,
}
impl Prompt {
pub fn new() -> Prompt {
let mut prompt = Prompt {
user: match env::var("USER") {
Ok(val) => Purple.paint(val).to_string(),
Err(_) => Purple.paint("?").to_string(),
},
cwd: "".to_string(),
error: 0,
};
prompt.update_cwd();
prompt
}
pub fn print(&self) -> String {
if self.error!= 0
|
else {
format!("{}:{} > ", self.user, self.cwd)
}
}
pub fn update_cwd(&mut self) {
let mut cwd = current_dir().unwrap().as_path().to_str().expect("Failed : path -> str").to_string();
let homedir = home_dir().unwrap().as_path().to_str().expect("Failed : path -> str").to_string();
self.cwd = if cwd.starts_with(homedir.as_str()) {
Green.paint(format!("~{}", cwd.split_off(homedir.len()))).to_string()
} else { Green.paint(cwd).to_string() };
}
pub fn update_error(&mut self, error: i8) {
self.error = error;
}
}
#[cfg(test)]
mod tests{
#[allow(unused_imports)]
use std::env::{current_dir,home_dir};
use super::*;
#[test]
fn updated_cwd() {
let mut testp = Prompt::new();
testp.update_cwd();
assert_eq!(testp.get_cwd(), current_dir().ok()
.expect("Couldn't get current directory").as_path()
.to_str()
.expect("Failed to go to string").to_owned());
}
}
|
{
format!("{} {}:{} > ", Red.paint(format!("\u{2718} {}", self.error)).to_string(), self.user, self.cwd)
}
|
conditional_block
|
prompt.rs
|
use std::env::{current_dir, home_dir};
use std::env;
use ansi_term::Colour::Purple;
use ansi_term::Colour::Green;
use ansi_term::Colour::Red;
pub struct Prompt {
user: String,
cwd: String,
error: i8,
}
impl Prompt {
pub fn new() -> Prompt {
let mut prompt = Prompt {
user: match env::var("USER") {
Ok(val) => Purple.paint(val).to_string(),
Err(_) => Purple.paint("?").to_string(),
},
cwd: "".to_string(),
error: 0,
};
prompt.update_cwd();
prompt
}
pub fn print(&self) -> String {
if self.error!= 0 {
format!("{} {}:{} > ", Red.paint(format!("\u{2718} {}", self.error)).to_string(), self.user, self.cwd)
} else {
format!("{}:{} > ", self.user, self.cwd)
}
}
pub fn
|
(&mut self) {
let mut cwd = current_dir().unwrap().as_path().to_str().expect("Failed : path -> str").to_string();
let homedir = home_dir().unwrap().as_path().to_str().expect("Failed : path -> str").to_string();
self.cwd = if cwd.starts_with(homedir.as_str()) {
Green.paint(format!("~{}", cwd.split_off(homedir.len()))).to_string()
} else { Green.paint(cwd).to_string() };
}
pub fn update_error(&mut self, error: i8) {
self.error = error;
}
}
#[cfg(test)]
mod tests{
#[allow(unused_imports)]
use std::env::{current_dir,home_dir};
use super::*;
#[test]
fn updated_cwd() {
let mut testp = Prompt::new();
testp.update_cwd();
assert_eq!(testp.get_cwd(), current_dir().ok()
.expect("Couldn't get current directory").as_path()
.to_str()
.expect("Failed to go to string").to_owned());
}
}
|
update_cwd
|
identifier_name
|
prompt.rs
|
use std::env::{current_dir, home_dir};
use std::env;
use ansi_term::Colour::Purple;
use ansi_term::Colour::Green;
use ansi_term::Colour::Red;
pub struct Prompt {
user: String,
cwd: String,
error: i8,
}
impl Prompt {
pub fn new() -> Prompt {
let mut prompt = Prompt {
user: match env::var("USER") {
Ok(val) => Purple.paint(val).to_string(),
Err(_) => Purple.paint("?").to_string(),
},
cwd: "".to_string(),
error: 0,
};
prompt.update_cwd();
prompt
}
pub fn print(&self) -> String {
if self.error!= 0 {
format!("{} {}:{} > ", Red.paint(format!("\u{2718} {}", self.error)).to_string(), self.user, self.cwd)
} else {
format!("{}:{} > ", self.user, self.cwd)
}
}
pub fn update_cwd(&mut self) {
let mut cwd = current_dir().unwrap().as_path().to_str().expect("Failed : path -> str").to_string();
let homedir = home_dir().unwrap().as_path().to_str().expect("Failed : path -> str").to_string();
self.cwd = if cwd.starts_with(homedir.as_str()) {
Green.paint(format!("~{}", cwd.split_off(homedir.len()))).to_string()
} else { Green.paint(cwd).to_string() };
}
pub fn update_error(&mut self, error: i8) {
self.error = error;
}
|
#[cfg(test)]
mod tests{
#[allow(unused_imports)]
use std::env::{current_dir,home_dir};
use super::*;
#[test]
fn updated_cwd() {
let mut testp = Prompt::new();
testp.update_cwd();
assert_eq!(testp.get_cwd(), current_dir().ok()
.expect("Couldn't get current directory").as_path()
.to_str()
.expect("Failed to go to string").to_owned());
}
}
|
}
|
random_line_split
|
signalfd.rs
|
//! Interface for the `signalfd` syscall.
//!
//! # Signal discarding
//! When a signal can't be delivered to a process (or thread), it will become a pending signal.
//! Failure to deliver could happen if the signal is blocked by every thread in the process or if
//! the signal handler is still handling a previous signal.
//!
//! If a signal is sent to a process (or thread) that already has a pending signal of the same
//! type, it will be discarded. This means that if signals of the same type are received faster than
//! they are processed, some of those signals will be dropped. Because of this limitation,
//! `signalfd` in itself cannot be used for reliable communication between processes or threads.
//!
//! Once the signal is unblocked, or the signal handler is finished, and a signal is still pending
//! (ie. not consumed from a signalfd) it will be delivered to the signal handler.
//!
//! Please note that signal discarding is not specific to `signalfd`, but also happens with regular
//! signal handlers.
use libc;
use unistd;
use {Error, Result};
use errno::Errno;
pub use sys::signal::{self, SigSet};
pub use libc::signalfd_siginfo as siginfo;
use std::os::unix::io::{RawFd, AsRawFd};
use std::mem;
libc_bitflags!{
pub struct SfdFlags: libc::c_int {
SFD_NONBLOCK;
SFD_CLOEXEC;
}
}
pub const SIGNALFD_NEW: RawFd = -1;
pub const SIGNALFD_SIGINFO_SIZE: usize = 128;
/// Creates a new file descriptor for reading signals.
///
/// **Important:** please read the module level documentation about signal discarding before using
/// this function!
///
/// The `mask` parameter specifies the set of signals that can be accepted via this file descriptor.
///
/// A signal must be blocked on every thread in a process, otherwise it won't be visible from
/// signalfd (the default handler will be invoked instead).
///
/// See [the signalfd man page for more information](http://man7.org/linux/man-pages/man2/signalfd.2.html)
pub fn signalfd(fd: RawFd, mask: &SigSet, flags: SfdFlags) -> Result<RawFd> {
unsafe {
Errno::result(libc::signalfd(fd as libc::c_int, mask.as_ref(), flags.bits()))
}
}
/// A helper struct for creating, reading and closing a `signalfd` instance.
///
/// **Important:** please read the module level documentation about signal discarding before using
/// this struct!
///
/// # Examples
///
/// ```
/// # use nix::sys::signalfd::*;
/// // Set the thread to block the SIGUSR1 signal, otherwise the default handler will be used
/// let mut mask = SigSet::empty();
/// mask.add(signal::SIGUSR1);
/// mask.thread_block().unwrap();
///
/// // Signals are queued up on the file descriptor
/// let mut sfd = SignalFd::with_flags(&mask, SfdFlags::SFD_NONBLOCK).unwrap();
///
/// match sfd.read_signal() {
/// // we caught a signal
/// Ok(Some(sig)) => (),
/// // there were no signals waiting (only happens when the SFD_NONBLOCK flag is set,
/// // otherwise the read_signal call blocks)
/// Ok(None) => (),
/// Err(err) => (), // some error happend
/// }
/// ```
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct SignalFd(RawFd);
impl SignalFd {
pub fn new(mask: &SigSet) -> Result<SignalFd> {
Self::with_flags(mask, SfdFlags::empty())
}
pub fn
|
(mask: &SigSet, flags: SfdFlags) -> Result<SignalFd> {
let fd = try!(signalfd(SIGNALFD_NEW, mask, flags));
Ok(SignalFd(fd))
}
pub fn set_mask(&mut self, mask: &SigSet) -> Result<()> {
signalfd(self.0, mask, SfdFlags::empty()).map(|_| ())
}
pub fn read_signal(&mut self) -> Result<Option<siginfo>> {
let mut buffer: [u8; SIGNALFD_SIGINFO_SIZE] = unsafe { mem::uninitialized() };
match unistd::read(self.0, &mut buffer) {
Ok(SIGNALFD_SIGINFO_SIZE) => Ok(Some(unsafe { mem::transmute(buffer) })),
Ok(_) => unreachable!("partial read on signalfd"),
Err(Error::Sys(Errno::EAGAIN)) => Ok(None),
Err(error) => Err(error)
}
}
}
impl Drop for SignalFd {
fn drop(&mut self) {
let _ = unistd::close(self.0);
}
}
impl AsRawFd for SignalFd {
fn as_raw_fd(&self) -> RawFd {
self.0
}
}
impl Iterator for SignalFd {
type Item = siginfo;
fn next(&mut self) -> Option<Self::Item> {
match self.read_signal() {
Ok(Some(sig)) => Some(sig),
Ok(None) | Err(_) => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::mem;
use libc;
#[test]
fn check_siginfo_size() {
assert_eq!(mem::size_of::<libc::signalfd_siginfo>(), SIGNALFD_SIGINFO_SIZE);
}
#[test]
fn create_signalfd() {
let mask = SigSet::empty();
let fd = SignalFd::new(&mask);
assert!(fd.is_ok());
}
#[test]
fn create_signalfd_with_opts() {
let mask = SigSet::empty();
let fd = SignalFd::with_flags(&mask, SfdFlags::SFD_CLOEXEC | SfdFlags::SFD_NONBLOCK);
assert!(fd.is_ok());
}
#[test]
fn read_empty_signalfd() {
let mask = SigSet::empty();
let mut fd = SignalFd::with_flags(&mask, SfdFlags::SFD_NONBLOCK).unwrap();
let res = fd.read_signal();
assert!(res.unwrap().is_none());
}
}
|
with_flags
|
identifier_name
|
signalfd.rs
|
//! Interface for the `signalfd` syscall.
//!
//! # Signal discarding
//! When a signal can't be delivered to a process (or thread), it will become a pending signal.
//! Failure to deliver could happen if the signal is blocked by every thread in the process or if
//! the signal handler is still handling a previous signal.
//!
//! If a signal is sent to a process (or thread) that already has a pending signal of the same
//! type, it will be discarded. This means that if signals of the same type are received faster than
//! they are processed, some of those signals will be dropped. Because of this limitation,
//! `signalfd` in itself cannot be used for reliable communication between processes or threads.
//!
//! Once the signal is unblocked, or the signal handler is finished, and a signal is still pending
//! (ie. not consumed from a signalfd) it will be delivered to the signal handler.
//!
//! Please note that signal discarding is not specific to `signalfd`, but also happens with regular
//! signal handlers.
use libc;
use unistd;
use {Error, Result};
use errno::Errno;
pub use sys::signal::{self, SigSet};
pub use libc::signalfd_siginfo as siginfo;
use std::os::unix::io::{RawFd, AsRawFd};
use std::mem;
libc_bitflags!{
pub struct SfdFlags: libc::c_int {
SFD_NONBLOCK;
SFD_CLOEXEC;
}
}
pub const SIGNALFD_NEW: RawFd = -1;
pub const SIGNALFD_SIGINFO_SIZE: usize = 128;
/// Creates a new file descriptor for reading signals.
///
/// **Important:** please read the module level documentation about signal discarding before using
/// this function!
///
/// The `mask` parameter specifies the set of signals that can be accepted via this file descriptor.
///
/// A signal must be blocked on every thread in a process, otherwise it won't be visible from
/// signalfd (the default handler will be invoked instead).
///
/// See [the signalfd man page for more information](http://man7.org/linux/man-pages/man2/signalfd.2.html)
pub fn signalfd(fd: RawFd, mask: &SigSet, flags: SfdFlags) -> Result<RawFd> {
unsafe {
Errno::result(libc::signalfd(fd as libc::c_int, mask.as_ref(), flags.bits()))
}
}
/// A helper struct for creating, reading and closing a `signalfd` instance.
///
/// **Important:** please read the module level documentation about signal discarding before using
/// this struct!
///
/// # Examples
///
/// ```
/// # use nix::sys::signalfd::*;
/// // Set the thread to block the SIGUSR1 signal, otherwise the default handler will be used
/// let mut mask = SigSet::empty();
/// mask.add(signal::SIGUSR1);
/// mask.thread_block().unwrap();
///
/// // Signals are queued up on the file descriptor
/// let mut sfd = SignalFd::with_flags(&mask, SfdFlags::SFD_NONBLOCK).unwrap();
///
/// match sfd.read_signal() {
/// // we caught a signal
/// Ok(Some(sig)) => (),
/// // there were no signals waiting (only happens when the SFD_NONBLOCK flag is set,
/// // otherwise the read_signal call blocks)
/// Ok(None) => (),
/// Err(err) => (), // some error happend
/// }
/// ```
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct SignalFd(RawFd);
impl SignalFd {
pub fn new(mask: &SigSet) -> Result<SignalFd> {
Self::with_flags(mask, SfdFlags::empty())
}
pub fn with_flags(mask: &SigSet, flags: SfdFlags) -> Result<SignalFd> {
let fd = try!(signalfd(SIGNALFD_NEW, mask, flags));
Ok(SignalFd(fd))
}
pub fn set_mask(&mut self, mask: &SigSet) -> Result<()> {
signalfd(self.0, mask, SfdFlags::empty()).map(|_| ())
}
pub fn read_signal(&mut self) -> Result<Option<siginfo>> {
let mut buffer: [u8; SIGNALFD_SIGINFO_SIZE] = unsafe { mem::uninitialized() };
match unistd::read(self.0, &mut buffer) {
Ok(SIGNALFD_SIGINFO_SIZE) => Ok(Some(unsafe { mem::transmute(buffer) })),
Ok(_) => unreachable!("partial read on signalfd"),
Err(Error::Sys(Errno::EAGAIN)) => Ok(None),
Err(error) => Err(error)
}
}
}
impl Drop for SignalFd {
fn drop(&mut self) {
let _ = unistd::close(self.0);
}
}
impl AsRawFd for SignalFd {
fn as_raw_fd(&self) -> RawFd {
self.0
}
}
impl Iterator for SignalFd {
type Item = siginfo;
fn next(&mut self) -> Option<Self::Item> {
match self.read_signal() {
Ok(Some(sig)) => Some(sig),
Ok(None) | Err(_) => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::mem;
use libc;
#[test]
fn check_siginfo_size() {
assert_eq!(mem::size_of::<libc::signalfd_siginfo>(), SIGNALFD_SIGINFO_SIZE);
}
#[test]
fn create_signalfd()
|
#[test]
fn create_signalfd_with_opts() {
let mask = SigSet::empty();
let fd = SignalFd::with_flags(&mask, SfdFlags::SFD_CLOEXEC | SfdFlags::SFD_NONBLOCK);
assert!(fd.is_ok());
}
#[test]
fn read_empty_signalfd() {
let mask = SigSet::empty();
let mut fd = SignalFd::with_flags(&mask, SfdFlags::SFD_NONBLOCK).unwrap();
let res = fd.read_signal();
assert!(res.unwrap().is_none());
}
}
|
{
let mask = SigSet::empty();
let fd = SignalFd::new(&mask);
assert!(fd.is_ok());
}
|
identifier_body
|
signalfd.rs
|
//! Interface for the `signalfd` syscall.
//!
//! # Signal discarding
//! When a signal can't be delivered to a process (or thread), it will become a pending signal.
//! Failure to deliver could happen if the signal is blocked by every thread in the process or if
//! the signal handler is still handling a previous signal.
//!
//! If a signal is sent to a process (or thread) that already has a pending signal of the same
//! type, it will be discarded. This means that if signals of the same type are received faster than
//! they are processed, some of those signals will be dropped. Because of this limitation,
//! `signalfd` in itself cannot be used for reliable communication between processes or threads.
//!
//! Once the signal is unblocked, or the signal handler is finished, and a signal is still pending
//! (ie. not consumed from a signalfd) it will be delivered to the signal handler.
//!
//! Please note that signal discarding is not specific to `signalfd`, but also happens with regular
//! signal handlers.
use libc;
use unistd;
use {Error, Result};
use errno::Errno;
pub use sys::signal::{self, SigSet};
pub use libc::signalfd_siginfo as siginfo;
use std::os::unix::io::{RawFd, AsRawFd};
use std::mem;
libc_bitflags!{
pub struct SfdFlags: libc::c_int {
SFD_NONBLOCK;
SFD_CLOEXEC;
}
}
pub const SIGNALFD_NEW: RawFd = -1;
pub const SIGNALFD_SIGINFO_SIZE: usize = 128;
/// Creates a new file descriptor for reading signals.
///
/// **Important:** please read the module level documentation about signal discarding before using
/// this function!
///
/// The `mask` parameter specifies the set of signals that can be accepted via this file descriptor.
///
/// A signal must be blocked on every thread in a process, otherwise it won't be visible from
/// signalfd (the default handler will be invoked instead).
///
/// See [the signalfd man page for more information](http://man7.org/linux/man-pages/man2/signalfd.2.html)
pub fn signalfd(fd: RawFd, mask: &SigSet, flags: SfdFlags) -> Result<RawFd> {
unsafe {
Errno::result(libc::signalfd(fd as libc::c_int, mask.as_ref(), flags.bits()))
}
}
/// A helper struct for creating, reading and closing a `signalfd` instance.
///
/// **Important:** please read the module level documentation about signal discarding before using
/// this struct!
///
/// # Examples
///
/// ```
/// # use nix::sys::signalfd::*;
/// // Set the thread to block the SIGUSR1 signal, otherwise the default handler will be used
/// let mut mask = SigSet::empty();
/// mask.add(signal::SIGUSR1);
/// mask.thread_block().unwrap();
///
/// // Signals are queued up on the file descriptor
/// let mut sfd = SignalFd::with_flags(&mask, SfdFlags::SFD_NONBLOCK).unwrap();
///
/// match sfd.read_signal() {
/// // we caught a signal
/// Ok(Some(sig)) => (),
/// // there were no signals waiting (only happens when the SFD_NONBLOCK flag is set,
/// // otherwise the read_signal call blocks)
/// Ok(None) => (),
/// Err(err) => (), // some error happend
/// }
/// ```
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct SignalFd(RawFd);
impl SignalFd {
pub fn new(mask: &SigSet) -> Result<SignalFd> {
Self::with_flags(mask, SfdFlags::empty())
}
pub fn with_flags(mask: &SigSet, flags: SfdFlags) -> Result<SignalFd> {
let fd = try!(signalfd(SIGNALFD_NEW, mask, flags));
Ok(SignalFd(fd))
}
pub fn set_mask(&mut self, mask: &SigSet) -> Result<()> {
signalfd(self.0, mask, SfdFlags::empty()).map(|_| ())
}
pub fn read_signal(&mut self) -> Result<Option<siginfo>> {
let mut buffer: [u8; SIGNALFD_SIGINFO_SIZE] = unsafe { mem::uninitialized() };
match unistd::read(self.0, &mut buffer) {
Ok(SIGNALFD_SIGINFO_SIZE) => Ok(Some(unsafe { mem::transmute(buffer) })),
Ok(_) => unreachable!("partial read on signalfd"),
Err(Error::Sys(Errno::EAGAIN)) => Ok(None),
Err(error) => Err(error)
}
}
}
impl Drop for SignalFd {
fn drop(&mut self) {
let _ = unistd::close(self.0);
}
}
impl AsRawFd for SignalFd {
fn as_raw_fd(&self) -> RawFd {
self.0
}
}
impl Iterator for SignalFd {
type Item = siginfo;
fn next(&mut self) -> Option<Self::Item> {
match self.read_signal() {
Ok(Some(sig)) => Some(sig),
Ok(None) | Err(_) => None,
}
}
}
#[cfg(test)]
mod tests {
|
#[test]
fn check_siginfo_size() {
assert_eq!(mem::size_of::<libc::signalfd_siginfo>(), SIGNALFD_SIGINFO_SIZE);
}
#[test]
fn create_signalfd() {
let mask = SigSet::empty();
let fd = SignalFd::new(&mask);
assert!(fd.is_ok());
}
#[test]
fn create_signalfd_with_opts() {
let mask = SigSet::empty();
let fd = SignalFd::with_flags(&mask, SfdFlags::SFD_CLOEXEC | SfdFlags::SFD_NONBLOCK);
assert!(fd.is_ok());
}
#[test]
fn read_empty_signalfd() {
let mask = SigSet::empty();
let mut fd = SignalFd::with_flags(&mask, SfdFlags::SFD_NONBLOCK).unwrap();
let res = fd.read_signal();
assert!(res.unwrap().is_none());
}
}
|
use super::*;
use std::mem;
use libc;
|
random_line_split
|
texture.rs
|
}
pub struct Solid {
pub m: Box<dyn MaterialModel + Sync + Send>
}
impl Medium for Solid {
fn material_at(&self, _pt: Vector3<f64>) -> &Box<dyn MaterialModel + Sync + Send> {
&self.m
}
}
pub struct CheckeredYPlane {
pub m1: Box<dyn MaterialModel + Sync + Send>,
pub m2: Box<dyn MaterialModel + Sync + Send>,
pub xsize: f64,
pub zsize: f64,
}
impl CheckeredYPlane {
pub fn new(m1: Box<dyn MaterialModel + Sync + Send>, m2: Box<dyn MaterialModel + Sync + Send>, xsize: f64, zsize: f64) -> CheckeredYPlane {
CheckeredYPlane { m1, m2, xsize, zsize}
}
}
impl Medium for CheckeredYPlane {
fn material_at(&self, pt: Vector3<f64>) -> &Box<dyn MaterialModel + Sync + Send> {
let zig = if (pt[0].abs() / self.xsize) as i32 % 2 == 0 { pt[0] > 0. } else { pt[0] <= 0. };
let zag = if (pt[2].abs() / self.zsize) as i32 % 2 == 0 { pt[2] > 0. } else { pt[2] <= 0. };
// zig XOR zag
return if!zig!=!zag { &self.m1 } else { &self.m2 };
}
}
|
use na::{Vector3};
use material::model::MaterialModel;
pub trait Medium : Sync{
fn material_at(&self, pt: Vector3<f64>) -> &Box<dyn MaterialModel + Sync + Send>;
|
random_line_split
|
|
texture.rs
|
use na::{Vector3};
use material::model::MaterialModel;
pub trait Medium : Sync{
fn material_at(&self, pt: Vector3<f64>) -> &Box<dyn MaterialModel + Sync + Send>;
}
pub struct Solid {
pub m: Box<dyn MaterialModel + Sync + Send>
}
impl Medium for Solid {
fn material_at(&self, _pt: Vector3<f64>) -> &Box<dyn MaterialModel + Sync + Send> {
&self.m
}
}
pub struct CheckeredYPlane {
pub m1: Box<dyn MaterialModel + Sync + Send>,
pub m2: Box<dyn MaterialModel + Sync + Send>,
pub xsize: f64,
pub zsize: f64,
}
impl CheckeredYPlane {
pub fn new(m1: Box<dyn MaterialModel + Sync + Send>, m2: Box<dyn MaterialModel + Sync + Send>, xsize: f64, zsize: f64) -> CheckeredYPlane {
CheckeredYPlane { m1, m2, xsize, zsize}
}
}
impl Medium for CheckeredYPlane {
fn material_at(&self, pt: Vector3<f64>) -> &Box<dyn MaterialModel + Sync + Send>
|
}
|
{
let zig = if (pt[0].abs() / self.xsize) as i32 % 2 == 0 { pt[0] > 0. } else { pt[0] <= 0. };
let zag = if (pt[2].abs() / self.zsize) as i32 % 2 == 0 { pt[2] > 0. } else { pt[2] <= 0. };
// zig XOR zag
return if !zig != !zag { &self.m1 } else { &self.m2 };
}
|
identifier_body
|
texture.rs
|
use na::{Vector3};
use material::model::MaterialModel;
pub trait Medium : Sync{
fn material_at(&self, pt: Vector3<f64>) -> &Box<dyn MaterialModel + Sync + Send>;
}
pub struct Solid {
pub m: Box<dyn MaterialModel + Sync + Send>
}
impl Medium for Solid {
fn material_at(&self, _pt: Vector3<f64>) -> &Box<dyn MaterialModel + Sync + Send> {
&self.m
}
}
pub struct CheckeredYPlane {
pub m1: Box<dyn MaterialModel + Sync + Send>,
pub m2: Box<dyn MaterialModel + Sync + Send>,
pub xsize: f64,
pub zsize: f64,
}
impl CheckeredYPlane {
pub fn new(m1: Box<dyn MaterialModel + Sync + Send>, m2: Box<dyn MaterialModel + Sync + Send>, xsize: f64, zsize: f64) -> CheckeredYPlane {
CheckeredYPlane { m1, m2, xsize, zsize}
}
}
impl Medium for CheckeredYPlane {
fn material_at(&self, pt: Vector3<f64>) -> &Box<dyn MaterialModel + Sync + Send> {
let zig = if (pt[0].abs() / self.xsize) as i32 % 2 == 0 { pt[0] > 0. } else { pt[0] <= 0. };
let zag = if (pt[2].abs() / self.zsize) as i32 % 2 == 0
|
else { pt[2] <= 0. };
// zig XOR zag
return if!zig!=!zag { &self.m1 } else { &self.m2 };
}
}
|
{ pt[2] > 0. }
|
conditional_block
|
texture.rs
|
use na::{Vector3};
use material::model::MaterialModel;
pub trait Medium : Sync{
fn material_at(&self, pt: Vector3<f64>) -> &Box<dyn MaterialModel + Sync + Send>;
}
pub struct Solid {
pub m: Box<dyn MaterialModel + Sync + Send>
}
impl Medium for Solid {
fn material_at(&self, _pt: Vector3<f64>) -> &Box<dyn MaterialModel + Sync + Send> {
&self.m
}
}
pub struct CheckeredYPlane {
pub m1: Box<dyn MaterialModel + Sync + Send>,
pub m2: Box<dyn MaterialModel + Sync + Send>,
pub xsize: f64,
pub zsize: f64,
}
impl CheckeredYPlane {
pub fn
|
(m1: Box<dyn MaterialModel + Sync + Send>, m2: Box<dyn MaterialModel + Sync + Send>, xsize: f64, zsize: f64) -> CheckeredYPlane {
CheckeredYPlane { m1, m2, xsize, zsize}
}
}
impl Medium for CheckeredYPlane {
fn material_at(&self, pt: Vector3<f64>) -> &Box<dyn MaterialModel + Sync + Send> {
let zig = if (pt[0].abs() / self.xsize) as i32 % 2 == 0 { pt[0] > 0. } else { pt[0] <= 0. };
let zag = if (pt[2].abs() / self.zsize) as i32 % 2 == 0 { pt[2] > 0. } else { pt[2] <= 0. };
// zig XOR zag
return if!zig!=!zag { &self.m1 } else { &self.m2 };
}
}
|
new
|
identifier_name
|
chain.rs
|
// Copyright 2015 Adrien Champion. See the COPYRIGHT file at the top-level
// directory of this distribution.
//
// 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.
/*! Chain (result of splitting an equivalence class. */
use std::fmt ;
use term::{ Term, TermSet } ;
use common::errors::* ;
use Domain ;
/** A chain is an increasing-ordered list containing values and
representative / equivalence class pairs.
It is ordered on the values. */
#[derive(PartialEq, Eq, Clone)]
pub enum Chain< Val: Domain, Info: PartialEq + Eq + Clone > {
/** Empty chain. */
Nil,
/** Chain constructor. */
Cons(Val, Term, Info, Box< Chain<Val, Info> >),
}
impl<
Val: Domain, Info: PartialEq + Eq + Clone
> fmt::Display for Chain<Val, Info> {
fn fmt(& self, fmt: & mut fmt::Formatter) -> fmt::Result {
use self::Chain::* ;
let mut chain = self ;
try!( write!(fmt, "[") ) ;
loop {
match * chain {
Nil => break,
Cons(ref val, ref trm, _, ref tail) => {
chain = & ** tail ;
try!( write!(fmt, " {}<{}>", trm, val) )
},
}
}
write!(fmt, "]")
}
}
impl<Val: Domain, Info: PartialEq + Eq + Clone> Chain<Val, Info> {
/** Empty chain. */
#[inline]
pub fn nil() -> Self { Chain::Nil }
/** Chain constructor. */
#[inline]
pub fn cons(self, v: Val, t: Term, s: Info) -> Self {
Chain::Cons(v, t, s, Box::new(self))
}
/// Returns a pointer to the last element in the chain.
pub fn last(& self) -> Option<(& Val, & Term)> {
use self::Chain::* ;
let mut chain = self ;
let mut res = None ;
loop {
match * chain {
Cons(ref val, ref term, _, ref tail) =>
|
,
Nil => return res,
}
}
}
/// Returns a pointer to the first element in the chain.
pub fn first(& self) -> Option<(& Val, & Term)> {
use self::Chain::* ;
match * self {
Cons(ref val, ref term, _, _) => Some( (val, term) ),
Nil => None,
}
}
/** Checks if a chain is empty. */
#[inline]
pub fn is_empty(& self) -> bool { * self == Chain::Nil }
/** Returns the top value of a chain, if any. */
#[inline]
pub fn top_value(& self) -> Option<(Val, Term)> {
use self::Chain::* ;
match * self {
Cons(ref v, ref rep, _, _) => Some( (v.clone(), rep.clone()) ),
Nil => None,
}
}
/// Fold on a chain.
pub fn fold<
T, F: Fn(T, & Val, & Term, & Info) -> T
>(& self, init: T, f: F) -> T {
use self::Chain::* ;
let mut chain = self ;
let mut val = init ;
while let Cons(ref v, ref trm, ref inf, ref tail) = * chain {
val = f(val, v, trm, inf) ;
chain = & * tail
}
val
}
/** Returns the longest subchain of a chain the values of which are
all greater than or equal to some value, and the rest of the chain.
First subchain is a vector of representatives and is sorted in **increasing
order** on their value (which have been removed at this point).
The second subchain is an actual `Chain` and is still sorted in **decreasing
order**. */
pub fn split_at(mut self, value: & Val) -> (Vec<Term>, Self) {
use self::Chain::* ;
let mut res = Vec::with_capacity(3) ;
loop {
if let Cons(val, rep, set, tail) = self {
if value <= & val {
res.push(rep) ;
self = * tail
} else {
// We have `val < value`, stop here.
self = Cons(val, rep, set, tail) ;
break
}
} else {
// Chain is empty, we done.
break
}
}
res.reverse() ;
(res, self)
}
/** Reverses the first chain and appends it to the second one. */
#[inline]
pub fn rev_append(mut self, mut that: Self) -> Self {
use self::Chain::* ;
while let Cons(val, term, set, tail) = self {
that = Cons( val, term, set, Box::new(that) ) ;
self = * tail
}
that
}
/** Reverses a chain. */
#[inline]
pub fn rev(self) -> Self {
self.rev_append(Chain::Nil)
}
}
impl<Val: Domain> Chain<Val, TermSet> {
/** Maps to `Chain<Val, ()>`, calling a function on each element. */
pub fn map_to_unit<
Input, F: Fn(& mut Input, Val, Term, TermSet)
>(mut self, f: F, i: & mut Input) -> Chain<Val, ()> {
use self::Chain::* ;
let mut res = Nil ;
while let Cons(val, rep, set, tail) = self {
self = * tail ;
f(i, val.clone(), rep.clone(), set) ;
res = res.cons(val, rep, ())
}
res.rev()
}
/** Inserts a term in a chain given its value. */
pub fn insert(mut self, v: Val, t: Term) -> Res<Self> {
use self::Chain::* ;
use std::cmp::Ordering::* ;
let mut prefix = Nil ;
loop {
if let Cons(val, term, mut set, tail) = self {
match val.cmp(& v) {
Less => return Ok(
// Insert term found as a new node in the chain.
prefix.rev_append(
Cons(val, term, set, tail).cons(v, t, TermSet::new())
)
),
Equal => {
// Insert term in the set of this node.
debug_assert!(! set.contains(& t) ) ;
let _ = set.insert(t) ;
return Ok( prefix.rev_append( Cons(val, term, set, tail) ) )
},
Greater => {
// Need to go deeper, iterating.
prefix = prefix.cons(val, term, set) ;
self = * tail
},
}
} else {
// Reached end of list, inserting.
return Ok(
prefix.rev_append( Nil.cons(v, t, TermSet::new()) )
)
}
}
}
}
|
{
res = Some( (val, term) ) ;
chain = & ** tail
}
|
conditional_block
|
chain.rs
|
// Copyright 2015 Adrien Champion. See the COPYRIGHT file at the top-level
// directory of this distribution.
//
// 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.
/*! Chain (result of splitting an equivalence class. */
use std::fmt ;
use term::{ Term, TermSet } ;
use common::errors::* ;
use Domain ;
/** A chain is an increasing-ordered list containing values and
representative / equivalence class pairs.
It is ordered on the values. */
#[derive(PartialEq, Eq, Clone)]
pub enum Chain< Val: Domain, Info: PartialEq + Eq + Clone > {
/** Empty chain. */
Nil,
/** Chain constructor. */
Cons(Val, Term, Info, Box< Chain<Val, Info> >),
}
impl<
Val: Domain, Info: PartialEq + Eq + Clone
> fmt::Display for Chain<Val, Info> {
fn fmt(& self, fmt: & mut fmt::Formatter) -> fmt::Result {
use self::Chain::* ;
let mut chain = self ;
try!( write!(fmt, "[") ) ;
loop {
match * chain {
Nil => break,
Cons(ref val, ref trm, _, ref tail) => {
chain = & ** tail ;
try!( write!(fmt, " {}<{}>", trm, val) )
},
}
}
write!(fmt, "]")
}
}
impl<Val: Domain, Info: PartialEq + Eq + Clone> Chain<Val, Info> {
/** Empty chain. */
#[inline]
pub fn nil() -> Self { Chain::Nil }
/** Chain constructor. */
#[inline]
pub fn cons(self, v: Val, t: Term, s: Info) -> Self {
Chain::Cons(v, t, s, Box::new(self))
}
/// Returns a pointer to the last element in the chain.
pub fn last(& self) -> Option<(& Val, & Term)> {
use self::Chain::* ;
let mut chain = self ;
let mut res = None ;
loop {
match * chain {
Cons(ref val, ref term, _, ref tail) => {
res = Some( (val, term) ) ;
chain = & ** tail
},
Nil => return res,
}
}
}
/// Returns a pointer to the first element in the chain.
pub fn first(& self) -> Option<(& Val, & Term)> {
use self::Chain::* ;
match * self {
Cons(ref val, ref term, _, _) => Some( (val, term) ),
Nil => None,
}
}
/** Checks if a chain is empty. */
#[inline]
pub fn is_empty(& self) -> bool { * self == Chain::Nil }
/** Returns the top value of a chain, if any. */
#[inline]
pub fn top_value(& self) -> Option<(Val, Term)> {
use self::Chain::* ;
match * self {
Cons(ref v, ref rep, _, _) => Some( (v.clone(), rep.clone()) ),
Nil => None,
}
}
/// Fold on a chain.
pub fn
|
<
T, F: Fn(T, & Val, & Term, & Info) -> T
>(& self, init: T, f: F) -> T {
use self::Chain::* ;
let mut chain = self ;
let mut val = init ;
while let Cons(ref v, ref trm, ref inf, ref tail) = * chain {
val = f(val, v, trm, inf) ;
chain = & * tail
}
val
}
/** Returns the longest subchain of a chain the values of which are
all greater than or equal to some value, and the rest of the chain.
First subchain is a vector of representatives and is sorted in **increasing
order** on their value (which have been removed at this point).
The second subchain is an actual `Chain` and is still sorted in **decreasing
order**. */
pub fn split_at(mut self, value: & Val) -> (Vec<Term>, Self) {
use self::Chain::* ;
let mut res = Vec::with_capacity(3) ;
loop {
if let Cons(val, rep, set, tail) = self {
if value <= & val {
res.push(rep) ;
self = * tail
} else {
// We have `val < value`, stop here.
self = Cons(val, rep, set, tail) ;
break
}
} else {
// Chain is empty, we done.
break
}
}
res.reverse() ;
(res, self)
}
/** Reverses the first chain and appends it to the second one. */
#[inline]
pub fn rev_append(mut self, mut that: Self) -> Self {
use self::Chain::* ;
while let Cons(val, term, set, tail) = self {
that = Cons( val, term, set, Box::new(that) ) ;
self = * tail
}
that
}
/** Reverses a chain. */
#[inline]
pub fn rev(self) -> Self {
self.rev_append(Chain::Nil)
}
}
impl<Val: Domain> Chain<Val, TermSet> {
/** Maps to `Chain<Val, ()>`, calling a function on each element. */
pub fn map_to_unit<
Input, F: Fn(& mut Input, Val, Term, TermSet)
>(mut self, f: F, i: & mut Input) -> Chain<Val, ()> {
use self::Chain::* ;
let mut res = Nil ;
while let Cons(val, rep, set, tail) = self {
self = * tail ;
f(i, val.clone(), rep.clone(), set) ;
res = res.cons(val, rep, ())
}
res.rev()
}
/** Inserts a term in a chain given its value. */
pub fn insert(mut self, v: Val, t: Term) -> Res<Self> {
use self::Chain::* ;
use std::cmp::Ordering::* ;
let mut prefix = Nil ;
loop {
if let Cons(val, term, mut set, tail) = self {
match val.cmp(& v) {
Less => return Ok(
// Insert term found as a new node in the chain.
prefix.rev_append(
Cons(val, term, set, tail).cons(v, t, TermSet::new())
)
),
Equal => {
// Insert term in the set of this node.
debug_assert!(! set.contains(& t) ) ;
let _ = set.insert(t) ;
return Ok( prefix.rev_append( Cons(val, term, set, tail) ) )
},
Greater => {
// Need to go deeper, iterating.
prefix = prefix.cons(val, term, set) ;
self = * tail
},
}
} else {
// Reached end of list, inserting.
return Ok(
prefix.rev_append( Nil.cons(v, t, TermSet::new()) )
)
}
}
}
}
|
fold
|
identifier_name
|
chain.rs
|
// Copyright 2015 Adrien Champion. See the COPYRIGHT file at the top-level
// directory of this distribution.
//
// 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.
/*! Chain (result of splitting an equivalence class. */
use std::fmt ;
use term::{ Term, TermSet } ;
use common::errors::* ;
use Domain ;
/** A chain is an increasing-ordered list containing values and
representative / equivalence class pairs.
It is ordered on the values. */
#[derive(PartialEq, Eq, Clone)]
pub enum Chain< Val: Domain, Info: PartialEq + Eq + Clone > {
/** Empty chain. */
Nil,
/** Chain constructor. */
Cons(Val, Term, Info, Box< Chain<Val, Info> >),
}
impl<
Val: Domain, Info: PartialEq + Eq + Clone
> fmt::Display for Chain<Val, Info> {
fn fmt(& self, fmt: & mut fmt::Formatter) -> fmt::Result {
use self::Chain::* ;
let mut chain = self ;
try!( write!(fmt, "[") ) ;
loop {
match * chain {
Nil => break,
Cons(ref val, ref trm, _, ref tail) => {
chain = & ** tail ;
try!( write!(fmt, " {}<{}>", trm, val) )
},
}
}
write!(fmt, "]")
}
}
impl<Val: Domain, Info: PartialEq + Eq + Clone> Chain<Val, Info> {
/** Empty chain. */
#[inline]
pub fn nil() -> Self { Chain::Nil }
/** Chain constructor. */
#[inline]
pub fn cons(self, v: Val, t: Term, s: Info) -> Self {
Chain::Cons(v, t, s, Box::new(self))
}
/// Returns a pointer to the last element in the chain.
pub fn last(& self) -> Option<(& Val, & Term)> {
use self::Chain::* ;
let mut chain = self ;
let mut res = None ;
loop {
match * chain {
Cons(ref val, ref term, _, ref tail) => {
res = Some( (val, term) ) ;
chain = & ** tail
},
Nil => return res,
}
}
}
/// Returns a pointer to the first element in the chain.
pub fn first(& self) -> Option<(& Val, & Term)> {
use self::Chain::* ;
match * self {
Cons(ref val, ref term, _, _) => Some( (val, term) ),
Nil => None,
}
}
/** Checks if a chain is empty. */
#[inline]
pub fn is_empty(& self) -> bool { * self == Chain::Nil }
/** Returns the top value of a chain, if any. */
#[inline]
pub fn top_value(& self) -> Option<(Val, Term)> {
use self::Chain::* ;
match * self {
Cons(ref v, ref rep, _, _) => Some( (v.clone(), rep.clone()) ),
Nil => None,
}
}
/// Fold on a chain.
pub fn fold<
T, F: Fn(T, & Val, & Term, & Info) -> T
>(& self, init: T, f: F) -> T {
use self::Chain::* ;
let mut chain = self ;
let mut val = init ;
while let Cons(ref v, ref trm, ref inf, ref tail) = * chain {
val = f(val, v, trm, inf) ;
chain = & * tail
}
val
}
/** Returns the longest subchain of a chain the values of which are
all greater than or equal to some value, and the rest of the chain.
First subchain is a vector of representatives and is sorted in **increasing
order** on their value (which have been removed at this point).
The second subchain is an actual `Chain` and is still sorted in **decreasing
order**. */
pub fn split_at(mut self, value: & Val) -> (Vec<Term>, Self) {
use self::Chain::* ;
let mut res = Vec::with_capacity(3) ;
loop {
if let Cons(val, rep, set, tail) = self {
if value <= & val {
res.push(rep) ;
self = * tail
} else {
// We have `val < value`, stop here.
self = Cons(val, rep, set, tail) ;
break
}
} else {
// Chain is empty, we done.
break
}
}
res.reverse() ;
(res, self)
}
/** Reverses the first chain and appends it to the second one. */
#[inline]
pub fn rev_append(mut self, mut that: Self) -> Self {
use self::Chain::* ;
while let Cons(val, term, set, tail) = self {
that = Cons( val, term, set, Box::new(that) ) ;
|
}
/** Reverses a chain. */
#[inline]
pub fn rev(self) -> Self {
self.rev_append(Chain::Nil)
}
}
impl<Val: Domain> Chain<Val, TermSet> {
/** Maps to `Chain<Val, ()>`, calling a function on each element. */
pub fn map_to_unit<
Input, F: Fn(& mut Input, Val, Term, TermSet)
>(mut self, f: F, i: & mut Input) -> Chain<Val, ()> {
use self::Chain::* ;
let mut res = Nil ;
while let Cons(val, rep, set, tail) = self {
self = * tail ;
f(i, val.clone(), rep.clone(), set) ;
res = res.cons(val, rep, ())
}
res.rev()
}
/** Inserts a term in a chain given its value. */
pub fn insert(mut self, v: Val, t: Term) -> Res<Self> {
use self::Chain::* ;
use std::cmp::Ordering::* ;
let mut prefix = Nil ;
loop {
if let Cons(val, term, mut set, tail) = self {
match val.cmp(& v) {
Less => return Ok(
// Insert term found as a new node in the chain.
prefix.rev_append(
Cons(val, term, set, tail).cons(v, t, TermSet::new())
)
),
Equal => {
// Insert term in the set of this node.
debug_assert!(! set.contains(& t) ) ;
let _ = set.insert(t) ;
return Ok( prefix.rev_append( Cons(val, term, set, tail) ) )
},
Greater => {
// Need to go deeper, iterating.
prefix = prefix.cons(val, term, set) ;
self = * tail
},
}
} else {
// Reached end of list, inserting.
return Ok(
prefix.rev_append( Nil.cons(v, t, TermSet::new()) )
)
}
}
}
}
|
self = * tail
}
that
|
random_line_split
|
chain.rs
|
// Copyright 2015 Adrien Champion. See the COPYRIGHT file at the top-level
// directory of this distribution.
//
// 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.
/*! Chain (result of splitting an equivalence class. */
use std::fmt ;
use term::{ Term, TermSet } ;
use common::errors::* ;
use Domain ;
/** A chain is an increasing-ordered list containing values and
representative / equivalence class pairs.
It is ordered on the values. */
#[derive(PartialEq, Eq, Clone)]
pub enum Chain< Val: Domain, Info: PartialEq + Eq + Clone > {
/** Empty chain. */
Nil,
/** Chain constructor. */
Cons(Val, Term, Info, Box< Chain<Val, Info> >),
}
impl<
Val: Domain, Info: PartialEq + Eq + Clone
> fmt::Display for Chain<Val, Info> {
fn fmt(& self, fmt: & mut fmt::Formatter) -> fmt::Result {
use self::Chain::* ;
let mut chain = self ;
try!( write!(fmt, "[") ) ;
loop {
match * chain {
Nil => break,
Cons(ref val, ref trm, _, ref tail) => {
chain = & ** tail ;
try!( write!(fmt, " {}<{}>", trm, val) )
},
}
}
write!(fmt, "]")
}
}
impl<Val: Domain, Info: PartialEq + Eq + Clone> Chain<Val, Info> {
/** Empty chain. */
#[inline]
pub fn nil() -> Self { Chain::Nil }
/** Chain constructor. */
#[inline]
pub fn cons(self, v: Val, t: Term, s: Info) -> Self {
Chain::Cons(v, t, s, Box::new(self))
}
/// Returns a pointer to the last element in the chain.
pub fn last(& self) -> Option<(& Val, & Term)>
|
/// Returns a pointer to the first element in the chain.
pub fn first(& self) -> Option<(& Val, & Term)> {
use self::Chain::* ;
match * self {
Cons(ref val, ref term, _, _) => Some( (val, term) ),
Nil => None,
}
}
/** Checks if a chain is empty. */
#[inline]
pub fn is_empty(& self) -> bool { * self == Chain::Nil }
/** Returns the top value of a chain, if any. */
#[inline]
pub fn top_value(& self) -> Option<(Val, Term)> {
use self::Chain::* ;
match * self {
Cons(ref v, ref rep, _, _) => Some( (v.clone(), rep.clone()) ),
Nil => None,
}
}
/// Fold on a chain.
pub fn fold<
T, F: Fn(T, & Val, & Term, & Info) -> T
>(& self, init: T, f: F) -> T {
use self::Chain::* ;
let mut chain = self ;
let mut val = init ;
while let Cons(ref v, ref trm, ref inf, ref tail) = * chain {
val = f(val, v, trm, inf) ;
chain = & * tail
}
val
}
/** Returns the longest subchain of a chain the values of which are
all greater than or equal to some value, and the rest of the chain.
First subchain is a vector of representatives and is sorted in **increasing
order** on their value (which have been removed at this point).
The second subchain is an actual `Chain` and is still sorted in **decreasing
order**. */
pub fn split_at(mut self, value: & Val) -> (Vec<Term>, Self) {
use self::Chain::* ;
let mut res = Vec::with_capacity(3) ;
loop {
if let Cons(val, rep, set, tail) = self {
if value <= & val {
res.push(rep) ;
self = * tail
} else {
// We have `val < value`, stop here.
self = Cons(val, rep, set, tail) ;
break
}
} else {
// Chain is empty, we done.
break
}
}
res.reverse() ;
(res, self)
}
/** Reverses the first chain and appends it to the second one. */
#[inline]
pub fn rev_append(mut self, mut that: Self) -> Self {
use self::Chain::* ;
while let Cons(val, term, set, tail) = self {
that = Cons( val, term, set, Box::new(that) ) ;
self = * tail
}
that
}
/** Reverses a chain. */
#[inline]
pub fn rev(self) -> Self {
self.rev_append(Chain::Nil)
}
}
impl<Val: Domain> Chain<Val, TermSet> {
/** Maps to `Chain<Val, ()>`, calling a function on each element. */
pub fn map_to_unit<
Input, F: Fn(& mut Input, Val, Term, TermSet)
>(mut self, f: F, i: & mut Input) -> Chain<Val, ()> {
use self::Chain::* ;
let mut res = Nil ;
while let Cons(val, rep, set, tail) = self {
self = * tail ;
f(i, val.clone(), rep.clone(), set) ;
res = res.cons(val, rep, ())
}
res.rev()
}
/** Inserts a term in a chain given its value. */
pub fn insert(mut self, v: Val, t: Term) -> Res<Self> {
use self::Chain::* ;
use std::cmp::Ordering::* ;
let mut prefix = Nil ;
loop {
if let Cons(val, term, mut set, tail) = self {
match val.cmp(& v) {
Less => return Ok(
// Insert term found as a new node in the chain.
prefix.rev_append(
Cons(val, term, set, tail).cons(v, t, TermSet::new())
)
),
Equal => {
// Insert term in the set of this node.
debug_assert!(! set.contains(& t) ) ;
let _ = set.insert(t) ;
return Ok( prefix.rev_append( Cons(val, term, set, tail) ) )
},
Greater => {
// Need to go deeper, iterating.
prefix = prefix.cons(val, term, set) ;
self = * tail
},
}
} else {
// Reached end of list, inserting.
return Ok(
prefix.rev_append( Nil.cons(v, t, TermSet::new()) )
)
}
}
}
}
|
{
use self::Chain::* ;
let mut chain = self ;
let mut res = None ;
loop {
match * chain {
Cons(ref val, ref term, _, ref tail) => {
res = Some( (val, term) ) ;
chain = & ** tail
},
Nil => return res,
}
}
}
|
identifier_body
|
issue-14456.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.
#![feature(phase)]
#[phase(plugin, link)]
extern crate green;
extern crate native;
use std::io::process;
use std::io::Command;
use std::io;
use std::os;
green_start!(main)
fn main() {
let args = os::args();
if args.len() > 1 && args.get(1).as_slice() == "child"
|
test();
let (tx, rx) = channel();
native::task::spawn(proc() {
tx.send(test());
});
rx.recv();
}
fn child() {
io::stdout().write_line("foo").unwrap();
io::stderr().write_line("bar").unwrap();
assert_eq!(io::stdin().read_line().err().unwrap().kind, io::EndOfFile);
}
fn test() {
let args = os::args();
let mut p = Command::new(args.get(0).as_slice()).arg("child")
.stdin(process::Ignored)
.stdout(process::Ignored)
.stderr(process::Ignored)
.spawn().unwrap();
assert!(p.wait().unwrap().success());
}
|
{
return child()
}
|
conditional_block
|
issue-14456.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.
#![feature(phase)]
#[phase(plugin, link)]
extern crate green;
extern crate native;
use std::io::process;
use std::io::Command;
use std::io;
use std::os;
green_start!(main)
fn main() {
let args = os::args();
if args.len() > 1 && args.get(1).as_slice() == "child" {
return child()
}
test();
let (tx, rx) = channel();
native::task::spawn(proc() {
tx.send(test());
});
rx.recv();
}
fn child() {
io::stdout().write_line("foo").unwrap();
io::stderr().write_line("bar").unwrap();
assert_eq!(io::stdin().read_line().err().unwrap().kind, io::EndOfFile);
}
|
let mut p = Command::new(args.get(0).as_slice()).arg("child")
.stdin(process::Ignored)
.stdout(process::Ignored)
.stderr(process::Ignored)
.spawn().unwrap();
assert!(p.wait().unwrap().success());
}
|
fn test() {
let args = os::args();
|
random_line_split
|
issue-14456.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.
#![feature(phase)]
#[phase(plugin, link)]
extern crate green;
extern crate native;
use std::io::process;
use std::io::Command;
use std::io;
use std::os;
green_start!(main)
fn main() {
let args = os::args();
if args.len() > 1 && args.get(1).as_slice() == "child" {
return child()
}
test();
let (tx, rx) = channel();
native::task::spawn(proc() {
tx.send(test());
});
rx.recv();
}
fn child() {
io::stdout().write_line("foo").unwrap();
io::stderr().write_line("bar").unwrap();
assert_eq!(io::stdin().read_line().err().unwrap().kind, io::EndOfFile);
}
fn
|
() {
let args = os::args();
let mut p = Command::new(args.get(0).as_slice()).arg("child")
.stdin(process::Ignored)
.stdout(process::Ignored)
.stderr(process::Ignored)
.spawn().unwrap();
assert!(p.wait().unwrap().success());
}
|
test
|
identifier_name
|
issue-14456.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.
#![feature(phase)]
#[phase(plugin, link)]
extern crate green;
extern crate native;
use std::io::process;
use std::io::Command;
use std::io;
use std::os;
green_start!(main)
fn main()
|
fn child() {
io::stdout().write_line("foo").unwrap();
io::stderr().write_line("bar").unwrap();
assert_eq!(io::stdin().read_line().err().unwrap().kind, io::EndOfFile);
}
fn test() {
let args = os::args();
let mut p = Command::new(args.get(0).as_slice()).arg("child")
.stdin(process::Ignored)
.stdout(process::Ignored)
.stderr(process::Ignored)
.spawn().unwrap();
assert!(p.wait().unwrap().success());
}
|
{
let args = os::args();
if args.len() > 1 && args.get(1).as_slice() == "child" {
return child()
}
test();
let (tx, rx) = channel();
native::task::spawn(proc() {
tx.send(test());
});
rx.recv();
}
|
identifier_body
|
const-float-classify.rs
|
// compile-flags: -Zmir-opt-level=0
// run-pass
#![feature(const_float_bits_conv)]
#![feature(const_float_classify)]
#![feature(const_trait_impl)]
// Don't promote
const fn nop<T>(x: T) -> T { x }
macro_rules! const_assert {
($a:expr, $b:expr) => {
{
const _: () = assert!($a == $b);
assert_eq!(nop($a), nop($b));
}
};
}
macro_rules! suite {
|
suite_inner!(f32 $($tt)*);
}
fn f64() {
suite_inner!(f64 $($tt)*);
}
}
}
macro_rules! suite_inner {
(
$ty:ident [$( $fn:ident ),*]
$val:expr => [$($out:ident),*]
$( $tail:tt )*
) => {
$( const_assert!($ty::$fn($val), $out); )*
suite_inner!($ty [$($fn),*] $($tail)*)
};
( $ty:ident [$( $fn:ident ),*]) => {};
}
#[derive(Debug)]
struct NonDet;
impl const PartialEq<NonDet> for bool {
fn eq(&self, _: &NonDet) -> bool {
true
}
fn ne(&self, _: &NonDet) -> bool {
false
}
}
// The result of the `is_sign` methods are not checked for correctness, since LLVM does not
// guarantee anything about the signedness of NaNs. See
// https://github.com/rust-lang/rust/issues/55131.
suite! {
[is_nan, is_infinite, is_finite, is_normal, is_sign_positive, is_sign_negative]
-0.0 / 0.0 => [ true, false, false, false, NonDet, NonDet]
0.0 / 0.0 => [ true, false, false, false, NonDet, NonDet]
1.0 => [ false, false, true, true, true, false]
-1.0 => [ false, false, true, true, false, true]
0.0 => [ false, false, true, false, true, false]
-0.0 => [ false, false, true, false, false, true]
1.0 / 0.0 => [ false, true, false, false, true, false]
-1.0 / 0.0 => [ false, true, false, false, false, true]
}
fn main() {
f32();
f64();
}
|
( $( $tt:tt )* ) => {
fn f32() {
|
random_line_split
|
const-float-classify.rs
|
// compile-flags: -Zmir-opt-level=0
// run-pass
#![feature(const_float_bits_conv)]
#![feature(const_float_classify)]
#![feature(const_trait_impl)]
// Don't promote
const fn nop<T>(x: T) -> T { x }
macro_rules! const_assert {
($a:expr, $b:expr) => {
{
const _: () = assert!($a == $b);
assert_eq!(nop($a), nop($b));
}
};
}
macro_rules! suite {
( $( $tt:tt )* ) => {
fn f32() {
suite_inner!(f32 $($tt)*);
}
fn f64() {
suite_inner!(f64 $($tt)*);
}
}
}
macro_rules! suite_inner {
(
$ty:ident [$( $fn:ident ),*]
$val:expr => [$($out:ident),*]
$( $tail:tt )*
) => {
$( const_assert!($ty::$fn($val), $out); )*
suite_inner!($ty [$($fn),*] $($tail)*)
};
( $ty:ident [$( $fn:ident ),*]) => {};
}
#[derive(Debug)]
struct NonDet;
impl const PartialEq<NonDet> for bool {
fn eq(&self, _: &NonDet) -> bool {
true
}
fn ne(&self, _: &NonDet) -> bool
|
}
// The result of the `is_sign` methods are not checked for correctness, since LLVM does not
// guarantee anything about the signedness of NaNs. See
// https://github.com/rust-lang/rust/issues/55131.
suite! {
[is_nan, is_infinite, is_finite, is_normal, is_sign_positive, is_sign_negative]
-0.0 / 0.0 => [ true, false, false, false, NonDet, NonDet]
0.0 / 0.0 => [ true, false, false, false, NonDet, NonDet]
1.0 => [ false, false, true, true, true, false]
-1.0 => [ false, false, true, true, false, true]
0.0 => [ false, false, true, false, true, false]
-0.0 => [ false, false, true, false, false, true]
1.0 / 0.0 => [ false, true, false, false, true, false]
-1.0 / 0.0 => [ false, true, false, false, false, true]
}
fn main() {
f32();
f64();
}
|
{
false
}
|
identifier_body
|
const-float-classify.rs
|
// compile-flags: -Zmir-opt-level=0
// run-pass
#![feature(const_float_bits_conv)]
#![feature(const_float_classify)]
#![feature(const_trait_impl)]
// Don't promote
const fn nop<T>(x: T) -> T { x }
macro_rules! const_assert {
($a:expr, $b:expr) => {
{
const _: () = assert!($a == $b);
assert_eq!(nop($a), nop($b));
}
};
}
macro_rules! suite {
( $( $tt:tt )* ) => {
fn f32() {
suite_inner!(f32 $($tt)*);
}
fn f64() {
suite_inner!(f64 $($tt)*);
}
}
}
macro_rules! suite_inner {
(
$ty:ident [$( $fn:ident ),*]
$val:expr => [$($out:ident),*]
$( $tail:tt )*
) => {
$( const_assert!($ty::$fn($val), $out); )*
suite_inner!($ty [$($fn),*] $($tail)*)
};
( $ty:ident [$( $fn:ident ),*]) => {};
}
#[derive(Debug)]
struct
|
;
impl const PartialEq<NonDet> for bool {
fn eq(&self, _: &NonDet) -> bool {
true
}
fn ne(&self, _: &NonDet) -> bool {
false
}
}
// The result of the `is_sign` methods are not checked for correctness, since LLVM does not
// guarantee anything about the signedness of NaNs. See
// https://github.com/rust-lang/rust/issues/55131.
suite! {
[is_nan, is_infinite, is_finite, is_normal, is_sign_positive, is_sign_negative]
-0.0 / 0.0 => [ true, false, false, false, NonDet, NonDet]
0.0 / 0.0 => [ true, false, false, false, NonDet, NonDet]
1.0 => [ false, false, true, true, true, false]
-1.0 => [ false, false, true, true, false, true]
0.0 => [ false, false, true, false, true, false]
-0.0 => [ false, false, true, false, false, true]
1.0 / 0.0 => [ false, true, false, false, true, false]
-1.0 / 0.0 => [ false, true, false, false, false, true]
}
fn main() {
f32();
f64();
}
|
NonDet
|
identifier_name
|
switch.rs
|
use core::cell::Cell;
use core::ops::Bound;
use core::sync::atomic::Ordering;
use alloc::sync::Arc;
use spin::RwLock;
use crate::context::signal::signal_handler;
use crate::context::{arch, contexts, Context, Status, CONTEXT_ID};
#[cfg(target_arch = "x86_64")]
use crate::gdt;
use crate::interrupt::irq::PIT_TICKS;
use crate::interrupt;
use crate::ptrace;
use crate::time;
unsafe fn update(context: &mut Context, cpu_id: usize) {
// Take ownership if not already owned
if context.cpu_id == None {
context.cpu_id = Some(cpu_id);
// println!("{}: take {} {}", cpu_id, context.id, *context.name.read());
}
// Restore from signal, must only be done from another context to avoid overwriting the stack!
if context.ksig_restore &&! context.running {
let was_singlestep = ptrace::regs_for(context).map(|s| s.is_singlestep()).unwrap_or(false);
let ksig = context.ksig.take().expect("context::switch: ksig not set with ksig_restore");
context.arch = ksig.0;
if let Some(ref mut kfx) = context.kfx {
kfx.clone_from_slice(&ksig.1.expect("context::switch: ksig kfx not set with ksig_restore"));
} else {
panic!("context::switch: kfx not set with ksig_restore");
}
if let Some(ref mut kstack) = context.kstack {
kstack.clone_from_slice(&ksig.2.expect("context::switch: ksig kstack not set with ksig_restore"));
} else {
panic!("context::switch: kstack not set with ksig_restore");
}
context.ksig_restore = false;
// Keep singlestep flag across jumps
if let Some(regs) = ptrace::regs_for_mut(context) {
regs.set_singlestep(was_singlestep);
}
context.unblock();
}
// Unblock when there are pending signals
if context.status == Status::Blocked &&!context.pending.is_empty() {
context.unblock();
}
// Wake from sleep
if context.status == Status::Blocked && context.wake.is_some() {
let wake = context.wake.expect("context::switch: wake not set");
let current = time::monotonic();
if current.0 > wake.0 || (current.0 == wake.0 && current.1 >= wake.1) {
context.wake = None;
context.unblock();
}
}
}
struct SwitchResult {
prev_lock: Arc<RwLock<Context>>,
next_lock: Arc<RwLock<Context>>,
}
pub unsafe extern "C" fn switch_finish_hook() {
if let Some(SwitchResult { prev_lock, next_lock }) = SWITCH_RESULT.take() {
prev_lock.force_write_unlock();
next_lock.force_write_unlock();
} else
|
arch::CONTEXT_SWITCH_LOCK.store(false, Ordering::SeqCst);
}
#[thread_local]
static SWITCH_RESULT: Cell<Option<SwitchResult>> = Cell::new(None);
unsafe fn runnable(context: &Context, cpu_id: usize) -> bool {
// Switch to context if it needs to run, is not currently running, and is owned by the current CPU
!context.running &&!context.ptrace_stop && context.status == Status::Runnable && context.cpu_id == Some(cpu_id)
}
/// Switch to the next context
///
/// # Safety
///
/// Do not call this while holding locks!
pub unsafe fn switch() -> bool {
// TODO: Better memory orderings?
//set PIT Interrupt counter to 0, giving each process same amount of PIT ticks
let ticks = PIT_TICKS.swap(0, Ordering::SeqCst);
// Set the global lock to avoid the unsafe operations below from causing issues
while arch::CONTEXT_SWITCH_LOCK.compare_exchange_weak(false, true, Ordering::SeqCst, Ordering::Relaxed).is_err() {
interrupt::pause();
}
let cpu_id = crate::cpu_id();
let from_context_lock;
let mut from_context_guard;
let mut to_context_lock: Option<(Arc<spin::RwLock<Context>>, *mut Context)> = None;
let mut to_sig = None;
{
let contexts = contexts();
{
from_context_lock = Arc::clone(contexts
.current()
.expect("context::switch: not inside of context"));
from_context_guard = from_context_lock.write();
from_context_guard.ticks += ticks as u64 + 1; // Always round ticks up
}
for (pid, context_lock) in contexts.iter() {
let mut context;
let context_ref = if *pid == from_context_guard.id {
&mut *from_context_guard
} else {
context = context_lock.write();
&mut *context
};
update(context_ref, cpu_id);
}
for (_pid, context_lock) in contexts
// Include all contexts with IDs greater than the current...
.range(
(Bound::Excluded(from_context_guard.id), Bound::Unbounded)
)
.chain(contexts
//... and all contexts with IDs less than the current...
.range((Bound::Unbounded, Bound::Excluded(from_context_guard.id)))
)
//... but not the current context, which is already locked
{
let context_lock = Arc::clone(context_lock);
let mut to_context_guard = context_lock.write();
if runnable(&*to_context_guard, cpu_id) {
if to_context_guard.ksig.is_none() {
to_sig = to_context_guard.pending.pop_front();
}
let ptr: *mut Context = &mut *to_context_guard;
core::mem::forget(to_context_guard);
to_context_lock = Some((context_lock, ptr));
break;
} else {
continue;
}
}
};
// Switch process states, TSS stack pointer, and store new context ID
if let Some((to_context_lock, to_ptr)) = to_context_lock {
let to_context: &mut Context = &mut *to_ptr;
from_context_guard.running = false;
to_context.running = true;
#[cfg(target_arch = "x86_64")]
{
if let Some(ref stack) = to_context.kstack {
gdt::set_tss_stack(stack.as_ptr() as usize + stack.len());
}
}
#[cfg(target_arch = "aarch64")]
{
let pid = to_context.id.into();
to_context.arch.set_tcb(pid);
}
CONTEXT_ID.store(to_context.id, Ordering::SeqCst);
if let Some(sig) = to_sig {
// Signal was found, run signal handler
//TODO: Allow nested signals
assert!(to_context.ksig.is_none());
let arch = to_context.arch.clone();
let kfx = to_context.kfx.clone();
let kstack = to_context.kstack.clone();
to_context.ksig = Some((arch, kfx, kstack, sig));
to_context.arch.signal_stack(signal_handler, sig);
}
let from_arch_ptr: *mut arch::Context = &mut from_context_guard.arch;
core::mem::forget(from_context_guard);
let prev_arch: &mut arch::Context = &mut *from_arch_ptr;
let next_arch: &mut arch::Context = &mut to_context.arch;
// to_context_guard only exists as a raw pointer, but is still locked
SWITCH_RESULT.set(Some(SwitchResult {
prev_lock: from_context_lock,
next_lock: to_context_lock,
}));
arch::switch_to(prev_arch, next_arch);
// NOTE: After switch_to is called, the return address can even be different from the
// current return address, meaning that we cannot use local variables here, and that we
// need to use the `switch_finish_hook` to be able to release the locks.
true
} else {
// No target was found, unset global lock and return
arch::CONTEXT_SWITCH_LOCK.store(false, Ordering::SeqCst);
false
}
}
|
{
// TODO: unreachable_unchecked()?
core::intrinsics::abort();
}
|
conditional_block
|
switch.rs
|
use core::cell::Cell;
use core::ops::Bound;
use core::sync::atomic::Ordering;
use alloc::sync::Arc;
use spin::RwLock;
use crate::context::signal::signal_handler;
use crate::context::{arch, contexts, Context, Status, CONTEXT_ID};
#[cfg(target_arch = "x86_64")]
use crate::gdt;
use crate::interrupt::irq::PIT_TICKS;
use crate::interrupt;
use crate::ptrace;
use crate::time;
unsafe fn update(context: &mut Context, cpu_id: usize) {
// Take ownership if not already owned
if context.cpu_id == None {
context.cpu_id = Some(cpu_id);
// println!("{}: take {} {}", cpu_id, context.id, *context.name.read());
}
// Restore from signal, must only be done from another context to avoid overwriting the stack!
if context.ksig_restore &&! context.running {
let was_singlestep = ptrace::regs_for(context).map(|s| s.is_singlestep()).unwrap_or(false);
let ksig = context.ksig.take().expect("context::switch: ksig not set with ksig_restore");
context.arch = ksig.0;
if let Some(ref mut kfx) = context.kfx {
kfx.clone_from_slice(&ksig.1.expect("context::switch: ksig kfx not set with ksig_restore"));
} else {
panic!("context::switch: kfx not set with ksig_restore");
}
if let Some(ref mut kstack) = context.kstack {
kstack.clone_from_slice(&ksig.2.expect("context::switch: ksig kstack not set with ksig_restore"));
} else {
panic!("context::switch: kstack not set with ksig_restore");
}
context.ksig_restore = false;
// Keep singlestep flag across jumps
if let Some(regs) = ptrace::regs_for_mut(context) {
regs.set_singlestep(was_singlestep);
}
context.unblock();
}
// Unblock when there are pending signals
if context.status == Status::Blocked &&!context.pending.is_empty() {
context.unblock();
}
// Wake from sleep
if context.status == Status::Blocked && context.wake.is_some() {
let wake = context.wake.expect("context::switch: wake not set");
let current = time::monotonic();
if current.0 > wake.0 || (current.0 == wake.0 && current.1 >= wake.1) {
context.wake = None;
context.unblock();
}
}
}
struct SwitchResult {
prev_lock: Arc<RwLock<Context>>,
next_lock: Arc<RwLock<Context>>,
}
pub unsafe extern "C" fn switch_finish_hook() {
if let Some(SwitchResult { prev_lock, next_lock }) = SWITCH_RESULT.take() {
prev_lock.force_write_unlock();
next_lock.force_write_unlock();
} else {
// TODO: unreachable_unchecked()?
core::intrinsics::abort();
}
arch::CONTEXT_SWITCH_LOCK.store(false, Ordering::SeqCst);
}
#[thread_local]
static SWITCH_RESULT: Cell<Option<SwitchResult>> = Cell::new(None);
unsafe fn runnable(context: &Context, cpu_id: usize) -> bool {
// Switch to context if it needs to run, is not currently running, and is owned by the current CPU
!context.running &&!context.ptrace_stop && context.status == Status::Runnable && context.cpu_id == Some(cpu_id)
}
/// Switch to the next context
///
/// # Safety
///
/// Do not call this while holding locks!
pub unsafe fn switch() -> bool
|
.current()
.expect("context::switch: not inside of context"));
from_context_guard = from_context_lock.write();
from_context_guard.ticks += ticks as u64 + 1; // Always round ticks up
}
for (pid, context_lock) in contexts.iter() {
let mut context;
let context_ref = if *pid == from_context_guard.id {
&mut *from_context_guard
} else {
context = context_lock.write();
&mut *context
};
update(context_ref, cpu_id);
}
for (_pid, context_lock) in contexts
// Include all contexts with IDs greater than the current...
.range(
(Bound::Excluded(from_context_guard.id), Bound::Unbounded)
)
.chain(contexts
//... and all contexts with IDs less than the current...
.range((Bound::Unbounded, Bound::Excluded(from_context_guard.id)))
)
//... but not the current context, which is already locked
{
let context_lock = Arc::clone(context_lock);
let mut to_context_guard = context_lock.write();
if runnable(&*to_context_guard, cpu_id) {
if to_context_guard.ksig.is_none() {
to_sig = to_context_guard.pending.pop_front();
}
let ptr: *mut Context = &mut *to_context_guard;
core::mem::forget(to_context_guard);
to_context_lock = Some((context_lock, ptr));
break;
} else {
continue;
}
}
};
// Switch process states, TSS stack pointer, and store new context ID
if let Some((to_context_lock, to_ptr)) = to_context_lock {
let to_context: &mut Context = &mut *to_ptr;
from_context_guard.running = false;
to_context.running = true;
#[cfg(target_arch = "x86_64")]
{
if let Some(ref stack) = to_context.kstack {
gdt::set_tss_stack(stack.as_ptr() as usize + stack.len());
}
}
#[cfg(target_arch = "aarch64")]
{
let pid = to_context.id.into();
to_context.arch.set_tcb(pid);
}
CONTEXT_ID.store(to_context.id, Ordering::SeqCst);
if let Some(sig) = to_sig {
// Signal was found, run signal handler
//TODO: Allow nested signals
assert!(to_context.ksig.is_none());
let arch = to_context.arch.clone();
let kfx = to_context.kfx.clone();
let kstack = to_context.kstack.clone();
to_context.ksig = Some((arch, kfx, kstack, sig));
to_context.arch.signal_stack(signal_handler, sig);
}
let from_arch_ptr: *mut arch::Context = &mut from_context_guard.arch;
core::mem::forget(from_context_guard);
let prev_arch: &mut arch::Context = &mut *from_arch_ptr;
let next_arch: &mut arch::Context = &mut to_context.arch;
// to_context_guard only exists as a raw pointer, but is still locked
SWITCH_RESULT.set(Some(SwitchResult {
prev_lock: from_context_lock,
next_lock: to_context_lock,
}));
arch::switch_to(prev_arch, next_arch);
// NOTE: After switch_to is called, the return address can even be different from the
// current return address, meaning that we cannot use local variables here, and that we
// need to use the `switch_finish_hook` to be able to release the locks.
true
} else {
// No target was found, unset global lock and return
arch::CONTEXT_SWITCH_LOCK.store(false, Ordering::SeqCst);
false
}
}
|
{
// TODO: Better memory orderings?
//set PIT Interrupt counter to 0, giving each process same amount of PIT ticks
let ticks = PIT_TICKS.swap(0, Ordering::SeqCst);
// Set the global lock to avoid the unsafe operations below from causing issues
while arch::CONTEXT_SWITCH_LOCK.compare_exchange_weak(false, true, Ordering::SeqCst, Ordering::Relaxed).is_err() {
interrupt::pause();
}
let cpu_id = crate::cpu_id();
let from_context_lock;
let mut from_context_guard;
let mut to_context_lock: Option<(Arc<spin::RwLock<Context>>, *mut Context)> = None;
let mut to_sig = None;
{
let contexts = contexts();
{
from_context_lock = Arc::clone(contexts
|
identifier_body
|
switch.rs
|
use core::cell::Cell;
use core::ops::Bound;
use core::sync::atomic::Ordering;
use alloc::sync::Arc;
use spin::RwLock;
use crate::context::signal::signal_handler;
use crate::context::{arch, contexts, Context, Status, CONTEXT_ID};
#[cfg(target_arch = "x86_64")]
use crate::gdt;
use crate::interrupt::irq::PIT_TICKS;
use crate::interrupt;
use crate::ptrace;
use crate::time;
unsafe fn update(context: &mut Context, cpu_id: usize) {
// Take ownership if not already owned
if context.cpu_id == None {
context.cpu_id = Some(cpu_id);
// println!("{}: take {} {}", cpu_id, context.id, *context.name.read());
}
// Restore from signal, must only be done from another context to avoid overwriting the stack!
if context.ksig_restore &&! context.running {
let was_singlestep = ptrace::regs_for(context).map(|s| s.is_singlestep()).unwrap_or(false);
let ksig = context.ksig.take().expect("context::switch: ksig not set with ksig_restore");
context.arch = ksig.0;
if let Some(ref mut kfx) = context.kfx {
kfx.clone_from_slice(&ksig.1.expect("context::switch: ksig kfx not set with ksig_restore"));
} else {
panic!("context::switch: kfx not set with ksig_restore");
}
if let Some(ref mut kstack) = context.kstack {
kstack.clone_from_slice(&ksig.2.expect("context::switch: ksig kstack not set with ksig_restore"));
} else {
panic!("context::switch: kstack not set with ksig_restore");
}
context.ksig_restore = false;
// Keep singlestep flag across jumps
if let Some(regs) = ptrace::regs_for_mut(context) {
regs.set_singlestep(was_singlestep);
}
context.unblock();
}
// Unblock when there are pending signals
if context.status == Status::Blocked &&!context.pending.is_empty() {
context.unblock();
}
// Wake from sleep
if context.status == Status::Blocked && context.wake.is_some() {
let wake = context.wake.expect("context::switch: wake not set");
let current = time::monotonic();
if current.0 > wake.0 || (current.0 == wake.0 && current.1 >= wake.1) {
context.wake = None;
context.unblock();
}
}
}
struct SwitchResult {
prev_lock: Arc<RwLock<Context>>,
next_lock: Arc<RwLock<Context>>,
}
pub unsafe extern "C" fn switch_finish_hook() {
if let Some(SwitchResult { prev_lock, next_lock }) = SWITCH_RESULT.take() {
prev_lock.force_write_unlock();
next_lock.force_write_unlock();
} else {
// TODO: unreachable_unchecked()?
core::intrinsics::abort();
}
arch::CONTEXT_SWITCH_LOCK.store(false, Ordering::SeqCst);
}
#[thread_local]
static SWITCH_RESULT: Cell<Option<SwitchResult>> = Cell::new(None);
unsafe fn runnable(context: &Context, cpu_id: usize) -> bool {
// Switch to context if it needs to run, is not currently running, and is owned by the current CPU
!context.running &&!context.ptrace_stop && context.status == Status::Runnable && context.cpu_id == Some(cpu_id)
}
/// Switch to the next context
///
/// # Safety
///
/// Do not call this while holding locks!
pub unsafe fn
|
() -> bool {
// TODO: Better memory orderings?
//set PIT Interrupt counter to 0, giving each process same amount of PIT ticks
let ticks = PIT_TICKS.swap(0, Ordering::SeqCst);
// Set the global lock to avoid the unsafe operations below from causing issues
while arch::CONTEXT_SWITCH_LOCK.compare_exchange_weak(false, true, Ordering::SeqCst, Ordering::Relaxed).is_err() {
interrupt::pause();
}
let cpu_id = crate::cpu_id();
let from_context_lock;
let mut from_context_guard;
let mut to_context_lock: Option<(Arc<spin::RwLock<Context>>, *mut Context)> = None;
let mut to_sig = None;
{
let contexts = contexts();
{
from_context_lock = Arc::clone(contexts
.current()
.expect("context::switch: not inside of context"));
from_context_guard = from_context_lock.write();
from_context_guard.ticks += ticks as u64 + 1; // Always round ticks up
}
for (pid, context_lock) in contexts.iter() {
let mut context;
let context_ref = if *pid == from_context_guard.id {
&mut *from_context_guard
} else {
context = context_lock.write();
&mut *context
};
update(context_ref, cpu_id);
}
for (_pid, context_lock) in contexts
// Include all contexts with IDs greater than the current...
.range(
(Bound::Excluded(from_context_guard.id), Bound::Unbounded)
)
.chain(contexts
//... and all contexts with IDs less than the current...
.range((Bound::Unbounded, Bound::Excluded(from_context_guard.id)))
)
//... but not the current context, which is already locked
{
let context_lock = Arc::clone(context_lock);
let mut to_context_guard = context_lock.write();
if runnable(&*to_context_guard, cpu_id) {
if to_context_guard.ksig.is_none() {
to_sig = to_context_guard.pending.pop_front();
}
let ptr: *mut Context = &mut *to_context_guard;
core::mem::forget(to_context_guard);
to_context_lock = Some((context_lock, ptr));
break;
} else {
continue;
}
}
};
// Switch process states, TSS stack pointer, and store new context ID
if let Some((to_context_lock, to_ptr)) = to_context_lock {
let to_context: &mut Context = &mut *to_ptr;
from_context_guard.running = false;
to_context.running = true;
#[cfg(target_arch = "x86_64")]
{
if let Some(ref stack) = to_context.kstack {
gdt::set_tss_stack(stack.as_ptr() as usize + stack.len());
}
}
#[cfg(target_arch = "aarch64")]
{
let pid = to_context.id.into();
to_context.arch.set_tcb(pid);
}
CONTEXT_ID.store(to_context.id, Ordering::SeqCst);
if let Some(sig) = to_sig {
// Signal was found, run signal handler
//TODO: Allow nested signals
assert!(to_context.ksig.is_none());
let arch = to_context.arch.clone();
let kfx = to_context.kfx.clone();
let kstack = to_context.kstack.clone();
to_context.ksig = Some((arch, kfx, kstack, sig));
to_context.arch.signal_stack(signal_handler, sig);
}
let from_arch_ptr: *mut arch::Context = &mut from_context_guard.arch;
core::mem::forget(from_context_guard);
let prev_arch: &mut arch::Context = &mut *from_arch_ptr;
let next_arch: &mut arch::Context = &mut to_context.arch;
// to_context_guard only exists as a raw pointer, but is still locked
SWITCH_RESULT.set(Some(SwitchResult {
prev_lock: from_context_lock,
next_lock: to_context_lock,
}));
arch::switch_to(prev_arch, next_arch);
// NOTE: After switch_to is called, the return address can even be different from the
// current return address, meaning that we cannot use local variables here, and that we
// need to use the `switch_finish_hook` to be able to release the locks.
true
} else {
// No target was found, unset global lock and return
arch::CONTEXT_SWITCH_LOCK.store(false, Ordering::SeqCst);
false
}
}
|
switch
|
identifier_name
|
switch.rs
|
use core::cell::Cell;
use core::ops::Bound;
use core::sync::atomic::Ordering;
use alloc::sync::Arc;
use spin::RwLock;
use crate::context::signal::signal_handler;
use crate::context::{arch, contexts, Context, Status, CONTEXT_ID};
#[cfg(target_arch = "x86_64")]
use crate::gdt;
use crate::interrupt::irq::PIT_TICKS;
use crate::interrupt;
use crate::ptrace;
use crate::time;
unsafe fn update(context: &mut Context, cpu_id: usize) {
// Take ownership if not already owned
if context.cpu_id == None {
context.cpu_id = Some(cpu_id);
// println!("{}: take {} {}", cpu_id, context.id, *context.name.read());
}
// Restore from signal, must only be done from another context to avoid overwriting the stack!
if context.ksig_restore &&! context.running {
let was_singlestep = ptrace::regs_for(context).map(|s| s.is_singlestep()).unwrap_or(false);
let ksig = context.ksig.take().expect("context::switch: ksig not set with ksig_restore");
context.arch = ksig.0;
if let Some(ref mut kfx) = context.kfx {
kfx.clone_from_slice(&ksig.1.expect("context::switch: ksig kfx not set with ksig_restore"));
} else {
panic!("context::switch: kfx not set with ksig_restore");
}
if let Some(ref mut kstack) = context.kstack {
kstack.clone_from_slice(&ksig.2.expect("context::switch: ksig kstack not set with ksig_restore"));
} else {
panic!("context::switch: kstack not set with ksig_restore");
}
context.ksig_restore = false;
// Keep singlestep flag across jumps
if let Some(regs) = ptrace::regs_for_mut(context) {
regs.set_singlestep(was_singlestep);
}
context.unblock();
}
// Unblock when there are pending signals
if context.status == Status::Blocked &&!context.pending.is_empty() {
context.unblock();
}
// Wake from sleep
if context.status == Status::Blocked && context.wake.is_some() {
let wake = context.wake.expect("context::switch: wake not set");
let current = time::monotonic();
if current.0 > wake.0 || (current.0 == wake.0 && current.1 >= wake.1) {
context.wake = None;
context.unblock();
}
}
}
struct SwitchResult {
prev_lock: Arc<RwLock<Context>>,
next_lock: Arc<RwLock<Context>>,
}
pub unsafe extern "C" fn switch_finish_hook() {
if let Some(SwitchResult { prev_lock, next_lock }) = SWITCH_RESULT.take() {
prev_lock.force_write_unlock();
next_lock.force_write_unlock();
} else {
// TODO: unreachable_unchecked()?
core::intrinsics::abort();
}
arch::CONTEXT_SWITCH_LOCK.store(false, Ordering::SeqCst);
}
#[thread_local]
static SWITCH_RESULT: Cell<Option<SwitchResult>> = Cell::new(None);
unsafe fn runnable(context: &Context, cpu_id: usize) -> bool {
// Switch to context if it needs to run, is not currently running, and is owned by the current CPU
!context.running &&!context.ptrace_stop && context.status == Status::Runnable && context.cpu_id == Some(cpu_id)
}
/// Switch to the next context
///
/// # Safety
///
/// Do not call this while holding locks!
pub unsafe fn switch() -> bool {
// TODO: Better memory orderings?
//set PIT Interrupt counter to 0, giving each process same amount of PIT ticks
let ticks = PIT_TICKS.swap(0, Ordering::SeqCst);
// Set the global lock to avoid the unsafe operations below from causing issues
while arch::CONTEXT_SWITCH_LOCK.compare_exchange_weak(false, true, Ordering::SeqCst, Ordering::Relaxed).is_err() {
interrupt::pause();
}
let cpu_id = crate::cpu_id();
let from_context_lock;
let mut from_context_guard;
let mut to_context_lock: Option<(Arc<spin::RwLock<Context>>, *mut Context)> = None;
let mut to_sig = None;
{
let contexts = contexts();
{
from_context_lock = Arc::clone(contexts
.current()
.expect("context::switch: not inside of context"));
from_context_guard = from_context_lock.write();
from_context_guard.ticks += ticks as u64 + 1; // Always round ticks up
}
for (pid, context_lock) in contexts.iter() {
let mut context;
let context_ref = if *pid == from_context_guard.id {
&mut *from_context_guard
} else {
context = context_lock.write();
&mut *context
};
update(context_ref, cpu_id);
}
for (_pid, context_lock) in contexts
// Include all contexts with IDs greater than the current...
.range(
(Bound::Excluded(from_context_guard.id), Bound::Unbounded)
)
.chain(contexts
//... and all contexts with IDs less than the current...
.range((Bound::Unbounded, Bound::Excluded(from_context_guard.id)))
)
//... but not the current context, which is already locked
{
let context_lock = Arc::clone(context_lock);
let mut to_context_guard = context_lock.write();
if runnable(&*to_context_guard, cpu_id) {
if to_context_guard.ksig.is_none() {
to_sig = to_context_guard.pending.pop_front();
}
let ptr: *mut Context = &mut *to_context_guard;
core::mem::forget(to_context_guard);
to_context_lock = Some((context_lock, ptr));
break;
} else {
continue;
}
}
};
// Switch process states, TSS stack pointer, and store new context ID
if let Some((to_context_lock, to_ptr)) = to_context_lock {
let to_context: &mut Context = &mut *to_ptr;
from_context_guard.running = false;
to_context.running = true;
#[cfg(target_arch = "x86_64")]
{
if let Some(ref stack) = to_context.kstack {
gdt::set_tss_stack(stack.as_ptr() as usize + stack.len());
}
}
#[cfg(target_arch = "aarch64")]
{
let pid = to_context.id.into();
to_context.arch.set_tcb(pid);
}
CONTEXT_ID.store(to_context.id, Ordering::SeqCst);
if let Some(sig) = to_sig {
// Signal was found, run signal handler
//TODO: Allow nested signals
assert!(to_context.ksig.is_none());
let arch = to_context.arch.clone();
let kfx = to_context.kfx.clone();
let kstack = to_context.kstack.clone();
to_context.ksig = Some((arch, kfx, kstack, sig));
to_context.arch.signal_stack(signal_handler, sig);
}
let from_arch_ptr: *mut arch::Context = &mut from_context_guard.arch;
core::mem::forget(from_context_guard);
let prev_arch: &mut arch::Context = &mut *from_arch_ptr;
let next_arch: &mut arch::Context = &mut to_context.arch;
// to_context_guard only exists as a raw pointer, but is still locked
SWITCH_RESULT.set(Some(SwitchResult {
prev_lock: from_context_lock,
next_lock: to_context_lock,
}));
arch::switch_to(prev_arch, next_arch);
// NOTE: After switch_to is called, the return address can even be different from the
// current return address, meaning that we cannot use local variables here, and that we
// need to use the `switch_finish_hook` to be able to release the locks.
true
} else {
// No target was found, unset global lock and return
arch::CONTEXT_SWITCH_LOCK.store(false, Ordering::SeqCst);
false
}
|
}
|
random_line_split
|
|
main.rs
|
use std::ops::{Add, Sub, Mul, Div};
fn do_operation<F, V>(f: F, v1: V, v2: V) -> V
where
F: Fn(V, V) -> V,
V: Add + Sub + Mul + Div {
f(v1, v2)
}
pub fn rpn(raw: &str) -> f64 {
let mut stack = Vec::new();
for c in raw.split(' ') {
if let Some(i) = c.parse::<f64>().ok() {
stack.push(i);
continue;
}
let r = stack.pop().expect("Invalid equation. No numbers left in stack for the right side of the operation");
let l = stack.pop().expect("Invalid equation. No numbers left in stack for the left side of the operation");
let result = match c {
"+" => do_operation(|l, r| l + r, l, r),
"-" => do_operation(|l, r| l - r, l, r),
"*" => do_operation(|l, r| l * r, l, r),
"/" =>
{
if r == 0.0
{
panic!("Division by zero not allowed");
}
do_operation(|l, r| l / r, l, r)
},
_ => panic!("Unknown character {:?}", c),
};
stack.push(result);
}
if stack.len()!= 1
{
panic!("Invalid equation. Wrong number of elements left in stack. Expected left: 1, actual: {:?}", stack.len());
}
stack.pop().unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic_integer() {
assert_eq!(0.25, rpn("14 4 6 8 + * /"));
assert_eq!(14.0, rpn("5 1 2 + 4 * + 3 -"));
assert_eq!(0.5, rpn("5 4 6 + /"));
assert_eq!(2.0, rpn("2 5 * 4 + 3 2 * 1 + /"));
}
#[test]
fn basic_floating_point() {
assert_eq!(20.04, rpn("5.5 1.3 2.3 + 4.9 * + 3.1 -"));
assert_eq!(11.25, rpn("1.5 3.0 4.5 + *"));
}
#[test]
fn negative() {
assert_eq!(-2503.0, rpn("-4 -9 -33 -76 * + -"));
assert_eq!(2653660.0, rpn("-56 -34 + -54 * 43 23 54 + * -800 * -"));
}
#[test]
#[should_panic]
fn divide_by_zero() {
assert_eq!(-2503.0, rpn("2 0 /"));
}
#[test]
#[should_panic]
fn invalid_input_1() {
rpn("");
}
#[test]
#[should_panic]
fn invalid_input_2() {
rpn("14 4 6 8 +. /");
}
#[test]
#[should_panic]
fn invalid_input_3() {
rpn("POTATO");
}
#[test]
#[should_panic]
fn invalid_input_4()
|
#[test]
fn long_equation() {
let mut eq = "2 ".to_string();
for _ in 0..2000000 {
eq.push_str("2 + ");
}
eq.push_str("1 +");
assert_eq!(4000003.0, rpn(&eq));
}
}
|
{
rpn("54 4 6 O + \\ /");
}
|
identifier_body
|
main.rs
|
use std::ops::{Add, Sub, Mul, Div};
fn do_operation<F, V>(f: F, v1: V, v2: V) -> V
where
F: Fn(V, V) -> V,
V: Add + Sub + Mul + Div {
f(v1, v2)
}
pub fn rpn(raw: &str) -> f64 {
let mut stack = Vec::new();
for c in raw.split(' ') {
if let Some(i) = c.parse::<f64>().ok() {
stack.push(i);
continue;
}
let r = stack.pop().expect("Invalid equation. No numbers left in stack for the right side of the operation");
let l = stack.pop().expect("Invalid equation. No numbers left in stack for the left side of the operation");
let result = match c {
"+" => do_operation(|l, r| l + r, l, r),
"-" => do_operation(|l, r| l - r, l, r),
"*" => do_operation(|l, r| l * r, l, r),
"/" =>
{
if r == 0.0
{
panic!("Division by zero not allowed");
}
do_operation(|l, r| l / r, l, r)
},
_ => panic!("Unknown character {:?}", c),
};
stack.push(result);
}
if stack.len()!= 1
{
panic!("Invalid equation. Wrong number of elements left in stack. Expected left: 1, actual: {:?}", stack.len());
}
stack.pop().unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic_integer() {
assert_eq!(0.25, rpn("14 4 6 8 + * /"));
assert_eq!(14.0, rpn("5 1 2 + 4 * + 3 -"));
assert_eq!(0.5, rpn("5 4 6 + /"));
assert_eq!(2.0, rpn("2 5 * 4 + 3 2 * 1 + /"));
}
#[test]
fn basic_floating_point() {
assert_eq!(20.04, rpn("5.5 1.3 2.3 + 4.9 * + 3.1 -"));
assert_eq!(11.25, rpn("1.5 3.0 4.5 + *"));
}
#[test]
fn negative() {
assert_eq!(-2503.0, rpn("-4 -9 -33 -76 * + -"));
assert_eq!(2653660.0, rpn("-56 -34 + -54 * 43 23 54 + * -800 * -"));
}
#[test]
#[should_panic]
fn
|
() {
assert_eq!(-2503.0, rpn("2 0 /"));
}
#[test]
#[should_panic]
fn invalid_input_1() {
rpn("");
}
#[test]
#[should_panic]
fn invalid_input_2() {
rpn("14 4 6 8 +. /");
}
#[test]
#[should_panic]
fn invalid_input_3() {
rpn("POTATO");
}
#[test]
#[should_panic]
fn invalid_input_4() {
rpn("54 4 6 O + \\ /");
}
#[test]
fn long_equation() {
let mut eq = "2 ".to_string();
for _ in 0..2000000 {
eq.push_str("2 + ");
}
eq.push_str("1 +");
assert_eq!(4000003.0, rpn(&eq));
}
}
|
divide_by_zero
|
identifier_name
|
main.rs
|
use std::ops::{Add, Sub, Mul, Div};
fn do_operation<F, V>(f: F, v1: V, v2: V) -> V
where
F: Fn(V, V) -> V,
V: Add + Sub + Mul + Div {
f(v1, v2)
}
pub fn rpn(raw: &str) -> f64 {
let mut stack = Vec::new();
for c in raw.split(' ') {
if let Some(i) = c.parse::<f64>().ok() {
stack.push(i);
continue;
}
let r = stack.pop().expect("Invalid equation. No numbers left in stack for the right side of the operation");
let l = stack.pop().expect("Invalid equation. No numbers left in stack for the left side of the operation");
let result = match c {
|
if r == 0.0
{
panic!("Division by zero not allowed");
}
do_operation(|l, r| l / r, l, r)
},
_ => panic!("Unknown character {:?}", c),
};
stack.push(result);
}
if stack.len()!= 1
{
panic!("Invalid equation. Wrong number of elements left in stack. Expected left: 1, actual: {:?}", stack.len());
}
stack.pop().unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic_integer() {
assert_eq!(0.25, rpn("14 4 6 8 + * /"));
assert_eq!(14.0, rpn("5 1 2 + 4 * + 3 -"));
assert_eq!(0.5, rpn("5 4 6 + /"));
assert_eq!(2.0, rpn("2 5 * 4 + 3 2 * 1 + /"));
}
#[test]
fn basic_floating_point() {
assert_eq!(20.04, rpn("5.5 1.3 2.3 + 4.9 * + 3.1 -"));
assert_eq!(11.25, rpn("1.5 3.0 4.5 + *"));
}
#[test]
fn negative() {
assert_eq!(-2503.0, rpn("-4 -9 -33 -76 * + -"));
assert_eq!(2653660.0, rpn("-56 -34 + -54 * 43 23 54 + * -800 * -"));
}
#[test]
#[should_panic]
fn divide_by_zero() {
assert_eq!(-2503.0, rpn("2 0 /"));
}
#[test]
#[should_panic]
fn invalid_input_1() {
rpn("");
}
#[test]
#[should_panic]
fn invalid_input_2() {
rpn("14 4 6 8 +. /");
}
#[test]
#[should_panic]
fn invalid_input_3() {
rpn("POTATO");
}
#[test]
#[should_panic]
fn invalid_input_4() {
rpn("54 4 6 O + \\ /");
}
#[test]
fn long_equation() {
let mut eq = "2 ".to_string();
for _ in 0..2000000 {
eq.push_str("2 + ");
}
eq.push_str("1 +");
assert_eq!(4000003.0, rpn(&eq));
}
}
|
"+" => do_operation(|l, r| l + r, l, r),
"-" => do_operation(|l, r| l - r, l, r),
"*" => do_operation(|l, r| l * r, l, r),
"/" =>
{
|
random_line_split
|
eth.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/>.
//! Eth rpc implementation.
use std::thread;
use std::time::{Instant, Duration};
use std::sync::Arc;
use rlp::{self, UntrustedRlp};
use time::get_time;
use bigint::prelude::U256;
use bigint::hash::{H64, H160, H256};
use util::Address;
use parking_lot::Mutex;
use ethash::SeedHashCompute;
use ethcore::account_provider::{AccountProvider, DappId};
use ethcore::block::IsBlock;
use ethcore::client::{MiningBlockChainClient, BlockId, TransactionId, UncleId};
use ethcore::ethereum::Ethash;
use ethcore::filter::Filter as EthcoreFilter;
use ethcore::header::{Header as BlockHeader, BlockNumber as EthBlockNumber};
use ethcore::log_entry::LogEntry;
use ethcore::miner::{MinerService, ExternalMinerService};
use ethcore::transaction::SignedTransaction;
use ethcore::snapshot::SnapshotService;
use ethsync::{SyncProvider};
use jsonrpc_core::{BoxFuture, Result};
use jsonrpc_core::futures::future;
use jsonrpc_macros::Trailing;
use v1::helpers::{errors, limit_logs, fake_sign};
use v1::helpers::dispatch::{FullDispatcher, default_gas_price};
use v1::helpers::block_import::is_major_importing;
use v1::helpers::accounts::unwrap_provider;
use v1::traits::Eth;
use v1::types::{
RichBlock, Block, BlockTransactions, BlockNumber, Bytes, SyncStatus, SyncInfo,
Transaction, CallRequest, Index, Filter, Log, Receipt, Work,
H64 as RpcH64, H256 as RpcH256, H160 as RpcH160, U256 as RpcU256,
};
use v1::metadata::Metadata;
const EXTRA_INFO_PROOF: &'static str = "Object exists in in blockchain (fetched earlier), extra_info is always available if object exists; qed";
/// Eth RPC options
pub struct EthClientOptions {
/// Return nonce from transaction queue when pending block not available.
pub pending_nonce_from_queue: bool,
/// Returns receipt from pending blocks
pub allow_pending_receipt_query: bool,
/// Send additional block number when asking for work
pub send_block_number_in_get_work: bool,
}
impl EthClientOptions {
/// Creates new default `EthClientOptions` and allows alterations
/// by provided function.
pub fn with<F: Fn(&mut Self)>(fun: F) -> Self {
let mut options = Self::default();
fun(&mut options);
options
}
}
impl Default for EthClientOptions {
fn default() -> Self {
EthClientOptions {
pending_nonce_from_queue: false,
allow_pending_receipt_query: true,
send_block_number_in_get_work: true,
}
}
}
/// Eth rpc implementation.
pub struct EthClient<C, SN:?Sized, S:?Sized, M, EM> where
C: MiningBlockChainClient,
SN: SnapshotService,
S: SyncProvider,
M: MinerService,
EM: ExternalMinerService {
client: Arc<C>,
snapshot: Arc<SN>,
sync: Arc<S>,
accounts: Option<Arc<AccountProvider>>,
miner: Arc<M>,
external_miner: Arc<EM>,
seed_compute: Mutex<SeedHashCompute>,
options: EthClientOptions,
eip86_transition: u64,
}
impl<C, SN:?Sized, S:?Sized, M, EM> EthClient<C, SN, S, M, EM> where
C: MiningBlockChainClient,
SN: SnapshotService,
S: SyncProvider,
M: MinerService,
EM: ExternalMinerService {
/// Creates new EthClient.
pub fn new(
client: &Arc<C>,
snapshot: &Arc<SN>,
sync: &Arc<S>,
accounts: &Option<Arc<AccountProvider>>,
miner: &Arc<M>,
em: &Arc<EM>,
options: EthClientOptions
) -> Self {
EthClient {
client: client.clone(),
snapshot: snapshot.clone(),
sync: sync.clone(),
miner: miner.clone(),
accounts: accounts.clone(),
external_miner: em.clone(),
seed_compute: Mutex::new(SeedHashCompute::new()),
options: options,
eip86_transition: client.eip86_transition(),
}
}
/// Attempt to get the `Arc<AccountProvider>`, errors if provider was not
/// set.
fn account_provider(&self) -> Result<Arc<AccountProvider>> {
unwrap_provider(&self.accounts)
}
fn block(&self, id: BlockId, include_txs: bool) -> Result<Option<RichBlock>> {
let client = &self.client;
match (client.block(id.clone()), client.block_total_difficulty(id)) {
(Some(block), Some(total_difficulty)) => {
let view = block.header_view();
Ok(Some(RichBlock {
inner: Block {
hash: Some(view.hash().into()),
size: Some(block.rlp().as_raw().len().into()),
parent_hash: view.parent_hash().into(),
uncles_hash: view.uncles_hash().into(),
author: view.author().into(),
miner: view.author().into(),
state_root: view.state_root().into(),
transactions_root: view.transactions_root().into(),
receipts_root: view.receipts_root().into(),
number: Some(view.number().into()),
gas_used: view.gas_used().into(),
gas_limit: view.gas_limit().into(),
logs_bloom: view.log_bloom().into(),
timestamp: view.timestamp().into(),
difficulty: view.difficulty().into(),
total_difficulty: Some(total_difficulty.into()),
seal_fields: view.seal().into_iter().map(Into::into).collect(),
uncles: block.uncle_hashes().into_iter().map(Into::into).collect(),
transactions: match include_txs {
true => BlockTransactions::Full(block.view().localized_transactions().into_iter().map(|t| Transaction::from_localized(t, self.eip86_transition)).collect()),
false => BlockTransactions::Hashes(block.transaction_hashes().into_iter().map(Into::into).collect()),
},
extra_data: Bytes::new(view.extra_data()),
},
extra_info: client.block_extra_info(id.clone()).expect(EXTRA_INFO_PROOF),
}))
},
_ => Ok(None)
}
}
fn transaction(&self, id: TransactionId) -> Result<Option<Transaction>> {
match self.client.transaction(id) {
Some(t) => Ok(Some(Transaction::from_localized(t, self.eip86_transition))),
None => Ok(None),
}
}
fn uncle(&self, id: UncleId) -> Result<Option<RichBlock>> {
let client = &self.client;
let uncle: BlockHeader = match client.uncle(id) {
Some(hdr) => hdr.decode(),
None => { return Ok(None); }
};
let parent_difficulty = match client.block_total_difficulty(BlockId::Hash(uncle.parent_hash().clone())) {
Some(difficulty) => difficulty,
None => { return Ok(None); }
};
let size = client.block(BlockId::Hash(uncle.hash()))
.map(|block| block.into_inner().len())
.map(U256::from)
.map(Into::into);
let block = RichBlock {
inner: Block {
hash: Some(uncle.hash().into()),
size: size,
parent_hash: uncle.parent_hash().clone().into(),
uncles_hash: uncle.uncles_hash().clone().into(),
author: uncle.author().clone().into(),
miner: uncle.author().clone().into(),
state_root: uncle.state_root().clone().into(),
transactions_root: uncle.transactions_root().clone().into(),
number: Some(uncle.number().into()),
gas_used: uncle.gas_used().clone().into(),
gas_limit: uncle.gas_limit().clone().into(),
logs_bloom: uncle.log_bloom().clone().into(),
timestamp: uncle.timestamp().into(),
difficulty: uncle.difficulty().clone().into(),
total_difficulty: Some((uncle.difficulty().clone() + parent_difficulty).into()),
receipts_root: uncle.receipts_root().clone().into(),
extra_data: uncle.extra_data().clone().into(),
seal_fields: uncle.seal().into_iter().cloned().map(Into::into).collect(),
uncles: vec![],
transactions: BlockTransactions::Hashes(vec![]),
},
extra_info: client.uncle_extra_info(id).expect(EXTRA_INFO_PROOF),
};
Ok(Some(block))
}
fn dapp_accounts(&self, dapp: DappId) -> Result<Vec<H160>> {
let store = self.account_provider()?;
store
.note_dapp_used(dapp.clone())
.and_then(|_| store.dapp_addresses(dapp))
.map_err(|e| errors::account("Could not fetch accounts.", e))
}
}
pub fn pending_logs<M>(miner: &M, best_block: EthBlockNumber, filter: &EthcoreFilter) -> Vec<Log> where M: MinerService {
let receipts = miner.pending_receipts(best_block);
let pending_logs = receipts.into_iter()
.flat_map(|(hash, r)| r.logs.into_iter().map(|l| (hash.clone(), l)).collect::<Vec<(H256, LogEntry)>>())
.collect::<Vec<(H256, LogEntry)>>();
let result = pending_logs.into_iter()
.filter(|pair| filter.matches(&pair.1))
.map(|pair| {
let mut log = Log::from(pair.1);
log.transaction_hash = Some(pair.0.into());
log
})
.collect();
result
}
fn check_known<C>(client: &C, number: BlockNumber) -> Result<()> where C: MiningBlockChainClient {
use ethcore::block_status::BlockStatus;
match client.block_status(number.into()) {
BlockStatus::InChain => Ok(()),
BlockStatus::Pending => Ok(()),
_ => Err(errors::unknown_block()),
}
}
const MAX_QUEUE_SIZE_TO_MINE_ON: usize = 4; // because uncles go back 6.
impl<C, SN:?Sized, S:?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
C: MiningBlockChainClient +'static,
SN: SnapshotService +'static,
S: SyncProvider +'static,
M: MinerService +'static,
EM: ExternalMinerService +'static,
{
type Metadata = Metadata;
fn protocol_version(&self) -> Result<String> {
let version = self.sync.status().protocol_version.to_owned();
Ok(format!("{}", version))
}
fn syncing(&self) -> Result<SyncStatus> {
use ethcore::snapshot::RestorationStatus;
let status = self.sync.status();
let client = &self.client;
let snapshot_status = self.snapshot.status();
let (warping, warp_chunks_amount, warp_chunks_processed) = match snapshot_status {
RestorationStatus::Ongoing { state_chunks, block_chunks, state_chunks_done, block_chunks_done } =>
(true, Some(block_chunks + state_chunks), Some(block_chunks_done + state_chunks_done)),
_ => (false, None, None),
};
if warping || is_major_importing(Some(status.state), client.queue_info()) {
let chain_info = client.chain_info();
let current_block = U256::from(chain_info.best_block_number);
let highest_block = U256::from(status.highest_block_number.unwrap_or(status.start_block_number));
let info = SyncInfo {
starting_block: status.start_block_number.into(),
current_block: current_block.into(),
highest_block: highest_block.into(),
warp_chunks_amount: warp_chunks_amount.map(|x| U256::from(x as u64)).map(Into::into),
warp_chunks_processed: warp_chunks_processed.map(|x| U256::from(x as u64)).map(Into::into),
};
Ok(SyncStatus::Info(info))
} else {
Ok(SyncStatus::None)
}
}
fn author(&self, meta: Metadata) -> Result<RpcH160> {
let dapp = meta.dapp_id();
let mut miner = self.miner.author();
if miner == 0.into() {
miner = self.dapp_accounts(dapp.into())?.get(0).cloned().unwrap_or_default();
}
Ok(RpcH160::from(miner))
}
fn is_mining(&self) -> Result<bool> {
Ok(self.miner.is_currently_sealing())
}
fn hashrate(&self) -> Result<RpcU256> {
Ok(RpcU256::from(self.external_miner.hashrate()))
}
fn gas_price(&self) -> Result<RpcU256> {
Ok(RpcU256::from(default_gas_price(&*self.client, &*self.miner)))
}
fn accounts(&self, meta: Metadata) -> Result<Vec<RpcH160>> {
let dapp = meta.dapp_id();
let accounts = self.dapp_accounts(dapp.into())?;
Ok(accounts.into_iter().map(Into::into).collect())
}
fn block_number(&self) -> Result<RpcU256> {
Ok(RpcU256::from(self.client.chain_info().best_block_number))
}
fn balance(&self, address: RpcH160, num: Trailing<BlockNumber>) -> BoxFuture<RpcU256> {
let address = address.into();
let id = num.unwrap_or_default();
try_bf!(check_known(&*self.client, id.clone()));
let res = match self.client.balance(&address, id.into()) {
Some(balance) => Ok(balance.into()),
None => Err(errors::state_pruned()),
};
Box::new(future::done(res))
}
fn storage_at(&self, address: RpcH160, pos: RpcU256, num: Trailing<BlockNumber>) -> BoxFuture<RpcH256> {
let address: Address = RpcH160::into(address);
let position: U256 = RpcU256::into(pos);
let id = num.unwrap_or_default();
try_bf!(check_known(&*self.client, id.clone()));
let res = match self.client.storage_at(&address, &H256::from(position), id.into()) {
Some(s) => Ok(s.into()),
None => Err(errors::state_pruned()),
};
Box::new(future::done(res))
}
fn transaction_count(&self, address: RpcH160, num: Trailing<BlockNumber>) -> BoxFuture<RpcU256> {
let address: Address = RpcH160::into(address);
let res = match num.unwrap_or_default() {
BlockNumber::Pending if self.options.pending_nonce_from_queue => {
let nonce = self.miner.last_nonce(&address)
.map(|n| n + 1.into())
.or_else(|| self.client.nonce(&address, BlockNumber::Pending.into()));
match nonce {
Some(nonce) => Ok(nonce.into()),
None => Err(errors::database("latest nonce missing"))
}
}
id => {
try_bf!(check_known(&*self.client, id.clone()));
match self.client.nonce(&address, id.into()) {
Some(nonce) => Ok(nonce.into()),
None => Err(errors::state_pruned()),
}
}
};
Box::new(future::done(res))
}
fn block_transaction_count_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(self.client.block(BlockId::Hash(hash.into()))
.map(|block| block.transactions_count().into())))
}
fn block_transaction_count_by_number(&self, num: BlockNumber) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(match num {
BlockNumber::Pending => Some(
self.miner.status().transactions_in_pending_block.into()
),
_ =>
self.client.block(num.into())
.map(|block| block.transactions_count().into())
}))
}
fn block_uncles_count_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(self.client.block(BlockId::Hash(hash.into()))
.map(|block| block.uncles_count().into())))
}
fn block_uncles_count_by_number(&self, num: BlockNumber) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(match num {
BlockNumber::Pending => Some(0.into()),
_ => self.client.block(num.into())
.map(|block| block.uncles_count().into()
),
}))
}
fn code_at(&self, address: RpcH160, num: Trailing<BlockNumber>) -> BoxFuture<Bytes> {
let address: Address = RpcH160::into(address);
let id = num.unwrap_or_default();
try_bf!(check_known(&*self.client, id.clone()));
let res = match self.client.code(&address, id.into()) {
Some(code) => Ok(code.map_or_else(Bytes::default, Bytes::new)),
None => Err(errors::state_pruned()),
};
Box::new(future::done(res))
}
fn block_by_hash(&self, hash: RpcH256, include_txs: bool) -> BoxFuture<Option<RichBlock>> {
Box::new(future::done(self.block(BlockId::Hash(hash.into()), include_txs)))
}
fn block_by_number(&self, num: BlockNumber, include_txs: bool) -> BoxFuture<Option<RichBlock>> {
Box::new(future::done(self.block(num.into(), include_txs)))
}
fn transaction_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<Transaction>> {
let hash: H256 = hash.into();
let block_number = self.client.chain_info().best_block_number;
let tx = try_bf!(self.transaction(TransactionId::Hash(hash))).or_else(|| {
self.miner.transaction(block_number, &hash)
.map(|t| Transaction::from_pending(t, block_number, self.eip86_transition))
});
Box::new(future::ok(tx))
}
fn transaction_by_block_hash_and_index(&self, hash: RpcH256, index: Index) -> BoxFuture<Option<Transaction>> {
Box::new(future::done(
self.transaction(TransactionId::Location(BlockId::Hash(hash.into()), index.value()))
))
}
fn transaction_by_block_number_and_index(&self, num: BlockNumber, index: Index) -> BoxFuture<Option<Transaction>> {
Box::new(future::done(
self.transaction(TransactionId::Location(num.into(), index.value()))
))
}
fn transaction_receipt(&self, hash: RpcH256) -> BoxFuture<Option<Receipt>> {
let best_block = self.client.chain_info().best_block_number;
let hash: H256 = hash.into();
match (self.miner.pending_receipt(best_block, &hash), self.options.allow_pending_receipt_query) {
(Some(receipt), true) => Box::new(future::ok(Some(receipt.into()))),
_ => {
let receipt = self.client.transaction_receipt(TransactionId::Hash(hash));
Box::new(future::ok(receipt.map(Into::into)))
}
}
}
fn uncle_by_block_hash_and_index(&self, hash: RpcH256, index: Index) -> BoxFuture<Option<RichBlock>> {
Box::new(future::done(self.uncle(UncleId {
block: BlockId::Hash(hash.into()),
position: index.value()
})))
}
fn uncle_by_block_number_and_index(&self, num: BlockNumber, index: Index) -> BoxFuture<Option<RichBlock>> {
Box::new(future::done(self.uncle(UncleId {
block: num.into(),
position: index.value()
})))
}
fn compilers(&self) -> Result<Vec<String>> {
Err(errors::deprecated("Compilation functionality is deprecated.".to_string()))
}
fn logs(&self, filter: Filter) -> BoxFuture<Vec<Log>> {
let include_pending = filter.to_block == Some(BlockNumber::Pending);
let filter: EthcoreFilter = filter.into();
let mut logs = self.client.logs(filter.clone())
.into_iter()
.map(From::from)
.collect::<Vec<Log>>();
if include_pending {
let best_block = self.client.chain_info().best_block_number;
let pending = pending_logs(&*self.miner, best_block, &filter);
logs.extend(pending);
}
let logs = limit_logs(logs, filter.limit);
Box::new(future::ok(logs))
}
fn work(&self, no_new_work_timeout: Trailing<u64>) -> Result<Work> {
if!self.miner.can_produce_work_package() {
warn!(target: "miner", "Cannot give work package - engine seals internally.");
return Err(errors::no_work_required())
}
let no_new_work_timeout = no_new_work_timeout.unwrap_or_default();
// check if we're still syncing and return empty strings in that case
{
//TODO: check if initial sync is complete here
//let sync = self.sync;
if /*sync.status().state!= SyncState::Idle ||*/ self.client.queue_info().total_queue_size() > MAX_QUEUE_SIZE_TO_MINE_ON {
trace!(target: "miner", "Syncing. Cannot give any work.");
return Err(errors::no_work());
}
// Otherwise spin until our submitted block has been included.
let timeout = Instant::now() + Duration::from_millis(1000);
while Instant::now() < timeout && self.client.queue_info().total_queue_size() > 0 {
thread::sleep(Duration::from_millis(1));
}
}
if self.miner.author().is_zero() {
warn!(target: "miner", "Cannot give work package - no author is configured. Use --author to configure!");
return Err(errors::no_author())
}
self.miner.map_sealing_work(&*self.client, |b| {
let pow_hash = b.hash();
let target = Ethash::difficulty_to_boundary(b.block().header().difficulty());
let seed_hash = self.seed_compute.lock().hash_block_number(b.block().header().number());
|
Ok(Work {
pow_hash: pow_hash.into(),
seed_hash: seed_hash.into(),
target: target.into(),
number: Some(block_number),
})
} else {
Ok(Work {
pow_hash: pow_hash.into(),
seed_hash: seed_hash.into(),
target: target.into(),
number: None
})
}
}).unwrap_or(Err(errors::internal("No work found.", "")))
}
fn submit_work(&self, nonce: RpcH64, pow_hash: RpcH256, mix_hash: RpcH256) -> Result<bool> {
if!self.miner.can_produce_work_package() {
warn!(target: "miner", "Cannot submit work - engine seals internally.");
return Err(errors::no_work_required())
}
let nonce: H64 = nonce.into();
let pow_hash: H256 = pow_hash.into();
let mix_hash: H256 = mix_hash.into();
trace!(target: "miner", "submit_work: Decoded: nonce={}, pow_hash={}, mix_hash={}", nonce, pow_hash, mix_hash);
let seal = vec![rlp::encode(&mix_hash).into_vec(), rlp::encode(&nonce).into_vec()];
Ok(self.miner.submit_seal(&*self.client, pow_hash, seal).is_ok())
}
fn submit_hashrate(&self, rate: RpcU256, id: RpcH256) -> Result<bool> {
self.external_miner.submit_hashrate(rate.into(), id.into());
Ok(true)
}
fn send_raw_transaction(&self, raw: Bytes) -> Result<RpcH256> {
UntrustedRlp::new(&raw.into_vec()).as_val()
.map_err(errors::rlp)
.and_then(|tx| SignedTransaction::new(tx).map_err(errors::transaction))
.and_then(|signed_transaction| {
FullDispatcher::dispatch_transaction(
&*self.client,
&*self.miner,
signed_transaction.into(),
)
})
.map(Into::into)
}
fn submit_transaction(&self, raw: Bytes) -> Result<RpcH256> {
self.send_raw_transaction(raw)
}
fn call(&self, meta: Self::Metadata, request: CallRequest, num: Trailing<BlockNumber>) -> BoxFuture<Bytes> {
let request = CallRequest::into(request);
let signed = try_bf!(fake_sign::sign_call(request, meta.is_dapp()));
let num = num.unwrap_or_default();
let result = self.client.call(&signed, Default::default(), num.into());
Box::new(future::done(result
.map(|b| b.output.into())
.map_err(errors::call)
))
}
fn estimate_gas(&self, meta: Self::Metadata, request: CallRequest, num: Trailing<BlockNumber>) -> BoxFuture<RpcU256> {
let request = CallRequest::into(request);
let signed = try_bf!(fake_sign::sign_call(request, meta.is_dapp()));
Box::new(future::done(self.client.estimate_gas(&signed, num.unwrap_or_default().into())
.map(Into::into)
.map_err(errors::call)
))
}
fn compile_lll(&self, _: String) -> Result<Bytes> {
Err(errors::deprecated("Compilation of LLL via RPC is deprecated".to_string()))
}
fn compile_serpent(&self, _: String) -> Result<Bytes> {
Err(errors::deprecated("Compilation of Serpent via RPC is deprecated".to_string()))
}
fn compile_solidity(&self, _: String) -> Result<Bytes> {
Err(errors::deprecated("Compilation of Solidity via RPC is deprecated".to_string()))
}
}
|
if no_new_work_timeout > 0 && b.block().header().timestamp() + no_new_work_timeout < get_time().sec as u64 {
Err(errors::no_new_work())
} else if self.options.send_block_number_in_get_work {
let block_number = b.block().header().number();
|
random_line_split
|
eth.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/>.
//! Eth rpc implementation.
use std::thread;
use std::time::{Instant, Duration};
use std::sync::Arc;
use rlp::{self, UntrustedRlp};
use time::get_time;
use bigint::prelude::U256;
use bigint::hash::{H64, H160, H256};
use util::Address;
use parking_lot::Mutex;
use ethash::SeedHashCompute;
use ethcore::account_provider::{AccountProvider, DappId};
use ethcore::block::IsBlock;
use ethcore::client::{MiningBlockChainClient, BlockId, TransactionId, UncleId};
use ethcore::ethereum::Ethash;
use ethcore::filter::Filter as EthcoreFilter;
use ethcore::header::{Header as BlockHeader, BlockNumber as EthBlockNumber};
use ethcore::log_entry::LogEntry;
use ethcore::miner::{MinerService, ExternalMinerService};
use ethcore::transaction::SignedTransaction;
use ethcore::snapshot::SnapshotService;
use ethsync::{SyncProvider};
use jsonrpc_core::{BoxFuture, Result};
use jsonrpc_core::futures::future;
use jsonrpc_macros::Trailing;
use v1::helpers::{errors, limit_logs, fake_sign};
use v1::helpers::dispatch::{FullDispatcher, default_gas_price};
use v1::helpers::block_import::is_major_importing;
use v1::helpers::accounts::unwrap_provider;
use v1::traits::Eth;
use v1::types::{
RichBlock, Block, BlockTransactions, BlockNumber, Bytes, SyncStatus, SyncInfo,
Transaction, CallRequest, Index, Filter, Log, Receipt, Work,
H64 as RpcH64, H256 as RpcH256, H160 as RpcH160, U256 as RpcU256,
};
use v1::metadata::Metadata;
const EXTRA_INFO_PROOF: &'static str = "Object exists in in blockchain (fetched earlier), extra_info is always available if object exists; qed";
/// Eth RPC options
pub struct EthClientOptions {
/// Return nonce from transaction queue when pending block not available.
pub pending_nonce_from_queue: bool,
/// Returns receipt from pending blocks
pub allow_pending_receipt_query: bool,
/// Send additional block number when asking for work
pub send_block_number_in_get_work: bool,
}
impl EthClientOptions {
/// Creates new default `EthClientOptions` and allows alterations
/// by provided function.
pub fn with<F: Fn(&mut Self)>(fun: F) -> Self {
let mut options = Self::default();
fun(&mut options);
options
}
}
impl Default for EthClientOptions {
fn default() -> Self {
EthClientOptions {
pending_nonce_from_queue: false,
allow_pending_receipt_query: true,
send_block_number_in_get_work: true,
}
}
}
/// Eth rpc implementation.
pub struct EthClient<C, SN:?Sized, S:?Sized, M, EM> where
C: MiningBlockChainClient,
SN: SnapshotService,
S: SyncProvider,
M: MinerService,
EM: ExternalMinerService {
client: Arc<C>,
snapshot: Arc<SN>,
sync: Arc<S>,
accounts: Option<Arc<AccountProvider>>,
miner: Arc<M>,
external_miner: Arc<EM>,
seed_compute: Mutex<SeedHashCompute>,
options: EthClientOptions,
eip86_transition: u64,
}
impl<C, SN:?Sized, S:?Sized, M, EM> EthClient<C, SN, S, M, EM> where
C: MiningBlockChainClient,
SN: SnapshotService,
S: SyncProvider,
M: MinerService,
EM: ExternalMinerService {
/// Creates new EthClient.
pub fn new(
client: &Arc<C>,
snapshot: &Arc<SN>,
sync: &Arc<S>,
accounts: &Option<Arc<AccountProvider>>,
miner: &Arc<M>,
em: &Arc<EM>,
options: EthClientOptions
) -> Self {
EthClient {
client: client.clone(),
snapshot: snapshot.clone(),
sync: sync.clone(),
miner: miner.clone(),
accounts: accounts.clone(),
external_miner: em.clone(),
seed_compute: Mutex::new(SeedHashCompute::new()),
options: options,
eip86_transition: client.eip86_transition(),
}
}
/// Attempt to get the `Arc<AccountProvider>`, errors if provider was not
/// set.
fn account_provider(&self) -> Result<Arc<AccountProvider>> {
unwrap_provider(&self.accounts)
}
fn block(&self, id: BlockId, include_txs: bool) -> Result<Option<RichBlock>> {
let client = &self.client;
match (client.block(id.clone()), client.block_total_difficulty(id)) {
(Some(block), Some(total_difficulty)) => {
let view = block.header_view();
Ok(Some(RichBlock {
inner: Block {
hash: Some(view.hash().into()),
size: Some(block.rlp().as_raw().len().into()),
parent_hash: view.parent_hash().into(),
uncles_hash: view.uncles_hash().into(),
author: view.author().into(),
miner: view.author().into(),
state_root: view.state_root().into(),
transactions_root: view.transactions_root().into(),
receipts_root: view.receipts_root().into(),
number: Some(view.number().into()),
gas_used: view.gas_used().into(),
gas_limit: view.gas_limit().into(),
logs_bloom: view.log_bloom().into(),
timestamp: view.timestamp().into(),
difficulty: view.difficulty().into(),
total_difficulty: Some(total_difficulty.into()),
seal_fields: view.seal().into_iter().map(Into::into).collect(),
uncles: block.uncle_hashes().into_iter().map(Into::into).collect(),
transactions: match include_txs {
true => BlockTransactions::Full(block.view().localized_transactions().into_iter().map(|t| Transaction::from_localized(t, self.eip86_transition)).collect()),
false => BlockTransactions::Hashes(block.transaction_hashes().into_iter().map(Into::into).collect()),
},
extra_data: Bytes::new(view.extra_data()),
},
extra_info: client.block_extra_info(id.clone()).expect(EXTRA_INFO_PROOF),
}))
},
_ => Ok(None)
}
}
fn transaction(&self, id: TransactionId) -> Result<Option<Transaction>> {
match self.client.transaction(id) {
Some(t) => Ok(Some(Transaction::from_localized(t, self.eip86_transition))),
None => Ok(None),
}
}
fn uncle(&self, id: UncleId) -> Result<Option<RichBlock>> {
let client = &self.client;
let uncle: BlockHeader = match client.uncle(id) {
Some(hdr) => hdr.decode(),
None => { return Ok(None); }
};
let parent_difficulty = match client.block_total_difficulty(BlockId::Hash(uncle.parent_hash().clone())) {
Some(difficulty) => difficulty,
None => { return Ok(None); }
};
let size = client.block(BlockId::Hash(uncle.hash()))
.map(|block| block.into_inner().len())
.map(U256::from)
.map(Into::into);
let block = RichBlock {
inner: Block {
hash: Some(uncle.hash().into()),
size: size,
parent_hash: uncle.parent_hash().clone().into(),
uncles_hash: uncle.uncles_hash().clone().into(),
author: uncle.author().clone().into(),
miner: uncle.author().clone().into(),
state_root: uncle.state_root().clone().into(),
transactions_root: uncle.transactions_root().clone().into(),
number: Some(uncle.number().into()),
gas_used: uncle.gas_used().clone().into(),
gas_limit: uncle.gas_limit().clone().into(),
logs_bloom: uncle.log_bloom().clone().into(),
timestamp: uncle.timestamp().into(),
difficulty: uncle.difficulty().clone().into(),
total_difficulty: Some((uncle.difficulty().clone() + parent_difficulty).into()),
receipts_root: uncle.receipts_root().clone().into(),
extra_data: uncle.extra_data().clone().into(),
seal_fields: uncle.seal().into_iter().cloned().map(Into::into).collect(),
uncles: vec![],
transactions: BlockTransactions::Hashes(vec![]),
},
extra_info: client.uncle_extra_info(id).expect(EXTRA_INFO_PROOF),
};
Ok(Some(block))
}
fn dapp_accounts(&self, dapp: DappId) -> Result<Vec<H160>> {
let store = self.account_provider()?;
store
.note_dapp_used(dapp.clone())
.and_then(|_| store.dapp_addresses(dapp))
.map_err(|e| errors::account("Could not fetch accounts.", e))
}
}
pub fn pending_logs<M>(miner: &M, best_block: EthBlockNumber, filter: &EthcoreFilter) -> Vec<Log> where M: MinerService {
let receipts = miner.pending_receipts(best_block);
let pending_logs = receipts.into_iter()
.flat_map(|(hash, r)| r.logs.into_iter().map(|l| (hash.clone(), l)).collect::<Vec<(H256, LogEntry)>>())
.collect::<Vec<(H256, LogEntry)>>();
let result = pending_logs.into_iter()
.filter(|pair| filter.matches(&pair.1))
.map(|pair| {
let mut log = Log::from(pair.1);
log.transaction_hash = Some(pair.0.into());
log
})
.collect();
result
}
fn check_known<C>(client: &C, number: BlockNumber) -> Result<()> where C: MiningBlockChainClient {
use ethcore::block_status::BlockStatus;
match client.block_status(number.into()) {
BlockStatus::InChain => Ok(()),
BlockStatus::Pending => Ok(()),
_ => Err(errors::unknown_block()),
}
}
const MAX_QUEUE_SIZE_TO_MINE_ON: usize = 4; // because uncles go back 6.
impl<C, SN:?Sized, S:?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
C: MiningBlockChainClient +'static,
SN: SnapshotService +'static,
S: SyncProvider +'static,
M: MinerService +'static,
EM: ExternalMinerService +'static,
{
type Metadata = Metadata;
fn protocol_version(&self) -> Result<String> {
let version = self.sync.status().protocol_version.to_owned();
Ok(format!("{}", version))
}
fn syncing(&self) -> Result<SyncStatus> {
use ethcore::snapshot::RestorationStatus;
let status = self.sync.status();
let client = &self.client;
let snapshot_status = self.snapshot.status();
let (warping, warp_chunks_amount, warp_chunks_processed) = match snapshot_status {
RestorationStatus::Ongoing { state_chunks, block_chunks, state_chunks_done, block_chunks_done } =>
(true, Some(block_chunks + state_chunks), Some(block_chunks_done + state_chunks_done)),
_ => (false, None, None),
};
if warping || is_major_importing(Some(status.state), client.queue_info()) {
let chain_info = client.chain_info();
let current_block = U256::from(chain_info.best_block_number);
let highest_block = U256::from(status.highest_block_number.unwrap_or(status.start_block_number));
let info = SyncInfo {
starting_block: status.start_block_number.into(),
current_block: current_block.into(),
highest_block: highest_block.into(),
warp_chunks_amount: warp_chunks_amount.map(|x| U256::from(x as u64)).map(Into::into),
warp_chunks_processed: warp_chunks_processed.map(|x| U256::from(x as u64)).map(Into::into),
};
Ok(SyncStatus::Info(info))
} else {
Ok(SyncStatus::None)
}
}
fn author(&self, meta: Metadata) -> Result<RpcH160> {
let dapp = meta.dapp_id();
let mut miner = self.miner.author();
if miner == 0.into() {
miner = self.dapp_accounts(dapp.into())?.get(0).cloned().unwrap_or_default();
}
Ok(RpcH160::from(miner))
}
fn is_mining(&self) -> Result<bool> {
Ok(self.miner.is_currently_sealing())
}
fn hashrate(&self) -> Result<RpcU256> {
Ok(RpcU256::from(self.external_miner.hashrate()))
}
fn gas_price(&self) -> Result<RpcU256> {
Ok(RpcU256::from(default_gas_price(&*self.client, &*self.miner)))
}
fn accounts(&self, meta: Metadata) -> Result<Vec<RpcH160>> {
let dapp = meta.dapp_id();
let accounts = self.dapp_accounts(dapp.into())?;
Ok(accounts.into_iter().map(Into::into).collect())
}
fn block_number(&self) -> Result<RpcU256> {
Ok(RpcU256::from(self.client.chain_info().best_block_number))
}
fn balance(&self, address: RpcH160, num: Trailing<BlockNumber>) -> BoxFuture<RpcU256> {
let address = address.into();
let id = num.unwrap_or_default();
try_bf!(check_known(&*self.client, id.clone()));
let res = match self.client.balance(&address, id.into()) {
Some(balance) => Ok(balance.into()),
None => Err(errors::state_pruned()),
};
Box::new(future::done(res))
}
fn storage_at(&self, address: RpcH160, pos: RpcU256, num: Trailing<BlockNumber>) -> BoxFuture<RpcH256> {
let address: Address = RpcH160::into(address);
let position: U256 = RpcU256::into(pos);
let id = num.unwrap_or_default();
try_bf!(check_known(&*self.client, id.clone()));
let res = match self.client.storage_at(&address, &H256::from(position), id.into()) {
Some(s) => Ok(s.into()),
None => Err(errors::state_pruned()),
};
Box::new(future::done(res))
}
fn transaction_count(&self, address: RpcH160, num: Trailing<BlockNumber>) -> BoxFuture<RpcU256> {
let address: Address = RpcH160::into(address);
let res = match num.unwrap_or_default() {
BlockNumber::Pending if self.options.pending_nonce_from_queue => {
let nonce = self.miner.last_nonce(&address)
.map(|n| n + 1.into())
.or_else(|| self.client.nonce(&address, BlockNumber::Pending.into()));
match nonce {
Some(nonce) => Ok(nonce.into()),
None => Err(errors::database("latest nonce missing"))
}
}
id => {
try_bf!(check_known(&*self.client, id.clone()));
match self.client.nonce(&address, id.into()) {
Some(nonce) => Ok(nonce.into()),
None => Err(errors::state_pruned()),
}
}
};
Box::new(future::done(res))
}
fn block_transaction_count_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(self.client.block(BlockId::Hash(hash.into()))
.map(|block| block.transactions_count().into())))
}
fn block_transaction_count_by_number(&self, num: BlockNumber) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(match num {
BlockNumber::Pending => Some(
self.miner.status().transactions_in_pending_block.into()
),
_ =>
self.client.block(num.into())
.map(|block| block.transactions_count().into())
}))
}
fn block_uncles_count_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(self.client.block(BlockId::Hash(hash.into()))
.map(|block| block.uncles_count().into())))
}
fn block_uncles_count_by_number(&self, num: BlockNumber) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(match num {
BlockNumber::Pending => Some(0.into()),
_ => self.client.block(num.into())
.map(|block| block.uncles_count().into()
),
}))
}
fn code_at(&self, address: RpcH160, num: Trailing<BlockNumber>) -> BoxFuture<Bytes> {
let address: Address = RpcH160::into(address);
let id = num.unwrap_or_default();
try_bf!(check_known(&*self.client, id.clone()));
let res = match self.client.code(&address, id.into()) {
Some(code) => Ok(code.map_or_else(Bytes::default, Bytes::new)),
None => Err(errors::state_pruned()),
};
Box::new(future::done(res))
}
fn block_by_hash(&self, hash: RpcH256, include_txs: bool) -> BoxFuture<Option<RichBlock>> {
Box::new(future::done(self.block(BlockId::Hash(hash.into()), include_txs)))
}
fn block_by_number(&self, num: BlockNumber, include_txs: bool) -> BoxFuture<Option<RichBlock>> {
Box::new(future::done(self.block(num.into(), include_txs)))
}
fn transaction_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<Transaction>> {
let hash: H256 = hash.into();
let block_number = self.client.chain_info().best_block_number;
let tx = try_bf!(self.transaction(TransactionId::Hash(hash))).or_else(|| {
self.miner.transaction(block_number, &hash)
.map(|t| Transaction::from_pending(t, block_number, self.eip86_transition))
});
Box::new(future::ok(tx))
}
fn transaction_by_block_hash_and_index(&self, hash: RpcH256, index: Index) -> BoxFuture<Option<Transaction>> {
Box::new(future::done(
self.transaction(TransactionId::Location(BlockId::Hash(hash.into()), index.value()))
))
}
fn transaction_by_block_number_and_index(&self, num: BlockNumber, index: Index) -> BoxFuture<Option<Transaction>> {
Box::new(future::done(
self.transaction(TransactionId::Location(num.into(), index.value()))
))
}
fn transaction_receipt(&self, hash: RpcH256) -> BoxFuture<Option<Receipt>> {
let best_block = self.client.chain_info().best_block_number;
let hash: H256 = hash.into();
match (self.miner.pending_receipt(best_block, &hash), self.options.allow_pending_receipt_query) {
(Some(receipt), true) => Box::new(future::ok(Some(receipt.into()))),
_ => {
let receipt = self.client.transaction_receipt(TransactionId::Hash(hash));
Box::new(future::ok(receipt.map(Into::into)))
}
}
}
fn uncle_by_block_hash_and_index(&self, hash: RpcH256, index: Index) -> BoxFuture<Option<RichBlock>> {
Box::new(future::done(self.uncle(UncleId {
block: BlockId::Hash(hash.into()),
position: index.value()
})))
}
fn uncle_by_block_number_and_index(&self, num: BlockNumber, index: Index) -> BoxFuture<Option<RichBlock>> {
Box::new(future::done(self.uncle(UncleId {
block: num.into(),
position: index.value()
})))
}
fn compilers(&self) -> Result<Vec<String>> {
Err(errors::deprecated("Compilation functionality is deprecated.".to_string()))
}
fn logs(&self, filter: Filter) -> BoxFuture<Vec<Log>> {
let include_pending = filter.to_block == Some(BlockNumber::Pending);
let filter: EthcoreFilter = filter.into();
let mut logs = self.client.logs(filter.clone())
.into_iter()
.map(From::from)
.collect::<Vec<Log>>();
if include_pending {
let best_block = self.client.chain_info().best_block_number;
let pending = pending_logs(&*self.miner, best_block, &filter);
logs.extend(pending);
}
let logs = limit_logs(logs, filter.limit);
Box::new(future::ok(logs))
}
fn work(&self, no_new_work_timeout: Trailing<u64>) -> Result<Work> {
if!self.miner.can_produce_work_package() {
warn!(target: "miner", "Cannot give work package - engine seals internally.");
return Err(errors::no_work_required())
}
let no_new_work_timeout = no_new_work_timeout.unwrap_or_default();
// check if we're still syncing and return empty strings in that case
{
//TODO: check if initial sync is complete here
//let sync = self.sync;
if /*sync.status().state!= SyncState::Idle ||*/ self.client.queue_info().total_queue_size() > MAX_QUEUE_SIZE_TO_MINE_ON {
trace!(target: "miner", "Syncing. Cannot give any work.");
return Err(errors::no_work());
}
// Otherwise spin until our submitted block has been included.
let timeout = Instant::now() + Duration::from_millis(1000);
while Instant::now() < timeout && self.client.queue_info().total_queue_size() > 0 {
thread::sleep(Duration::from_millis(1));
}
}
if self.miner.author().is_zero() {
warn!(target: "miner", "Cannot give work package - no author is configured. Use --author to configure!");
return Err(errors::no_author())
}
self.miner.map_sealing_work(&*self.client, |b| {
let pow_hash = b.hash();
let target = Ethash::difficulty_to_boundary(b.block().header().difficulty());
let seed_hash = self.seed_compute.lock().hash_block_number(b.block().header().number());
if no_new_work_timeout > 0 && b.block().header().timestamp() + no_new_work_timeout < get_time().sec as u64 {
Err(errors::no_new_work())
} else if self.options.send_block_number_in_get_work {
let block_number = b.block().header().number();
Ok(Work {
pow_hash: pow_hash.into(),
seed_hash: seed_hash.into(),
target: target.into(),
number: Some(block_number),
})
} else {
Ok(Work {
pow_hash: pow_hash.into(),
seed_hash: seed_hash.into(),
target: target.into(),
number: None
})
}
}).unwrap_or(Err(errors::internal("No work found.", "")))
}
fn submit_work(&self, nonce: RpcH64, pow_hash: RpcH256, mix_hash: RpcH256) -> Result<bool> {
if!self.miner.can_produce_work_package() {
warn!(target: "miner", "Cannot submit work - engine seals internally.");
return Err(errors::no_work_required())
}
let nonce: H64 = nonce.into();
let pow_hash: H256 = pow_hash.into();
let mix_hash: H256 = mix_hash.into();
trace!(target: "miner", "submit_work: Decoded: nonce={}, pow_hash={}, mix_hash={}", nonce, pow_hash, mix_hash);
let seal = vec![rlp::encode(&mix_hash).into_vec(), rlp::encode(&nonce).into_vec()];
Ok(self.miner.submit_seal(&*self.client, pow_hash, seal).is_ok())
}
fn submit_hashrate(&self, rate: RpcU256, id: RpcH256) -> Result<bool> {
self.external_miner.submit_hashrate(rate.into(), id.into());
Ok(true)
}
fn send_raw_transaction(&self, raw: Bytes) -> Result<RpcH256> {
UntrustedRlp::new(&raw.into_vec()).as_val()
.map_err(errors::rlp)
.and_then(|tx| SignedTransaction::new(tx).map_err(errors::transaction))
.and_then(|signed_transaction| {
FullDispatcher::dispatch_transaction(
&*self.client,
&*self.miner,
signed_transaction.into(),
)
})
.map(Into::into)
}
fn submit_transaction(&self, raw: Bytes) -> Result<RpcH256>
|
fn call(&self, meta: Self::Metadata, request: CallRequest, num: Trailing<BlockNumber>) -> BoxFuture<Bytes> {
let request = CallRequest::into(request);
let signed = try_bf!(fake_sign::sign_call(request, meta.is_dapp()));
let num = num.unwrap_or_default();
let result = self.client.call(&signed, Default::default(), num.into());
Box::new(future::done(result
.map(|b| b.output.into())
.map_err(errors::call)
))
}
fn estimate_gas(&self, meta: Self::Metadata, request: CallRequest, num: Trailing<BlockNumber>) -> BoxFuture<RpcU256> {
let request = CallRequest::into(request);
let signed = try_bf!(fake_sign::sign_call(request, meta.is_dapp()));
Box::new(future::done(self.client.estimate_gas(&signed, num.unwrap_or_default().into())
.map(Into::into)
.map_err(errors::call)
))
}
fn compile_lll(&self, _: String) -> Result<Bytes> {
Err(errors::deprecated("Compilation of LLL via RPC is deprecated".to_string()))
}
fn compile_serpent(&self, _: String) -> Result<Bytes> {
Err(errors::deprecated("Compilation of Serpent via RPC is deprecated".to_string()))
}
fn compile_solidity(&self, _: String) -> Result<Bytes> {
Err(errors::deprecated("Compilation of Solidity via RPC is deprecated".to_string()))
}
}
|
{
self.send_raw_transaction(raw)
}
|
identifier_body
|
eth.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/>.
//! Eth rpc implementation.
use std::thread;
use std::time::{Instant, Duration};
use std::sync::Arc;
use rlp::{self, UntrustedRlp};
use time::get_time;
use bigint::prelude::U256;
use bigint::hash::{H64, H160, H256};
use util::Address;
use parking_lot::Mutex;
use ethash::SeedHashCompute;
use ethcore::account_provider::{AccountProvider, DappId};
use ethcore::block::IsBlock;
use ethcore::client::{MiningBlockChainClient, BlockId, TransactionId, UncleId};
use ethcore::ethereum::Ethash;
use ethcore::filter::Filter as EthcoreFilter;
use ethcore::header::{Header as BlockHeader, BlockNumber as EthBlockNumber};
use ethcore::log_entry::LogEntry;
use ethcore::miner::{MinerService, ExternalMinerService};
use ethcore::transaction::SignedTransaction;
use ethcore::snapshot::SnapshotService;
use ethsync::{SyncProvider};
use jsonrpc_core::{BoxFuture, Result};
use jsonrpc_core::futures::future;
use jsonrpc_macros::Trailing;
use v1::helpers::{errors, limit_logs, fake_sign};
use v1::helpers::dispatch::{FullDispatcher, default_gas_price};
use v1::helpers::block_import::is_major_importing;
use v1::helpers::accounts::unwrap_provider;
use v1::traits::Eth;
use v1::types::{
RichBlock, Block, BlockTransactions, BlockNumber, Bytes, SyncStatus, SyncInfo,
Transaction, CallRequest, Index, Filter, Log, Receipt, Work,
H64 as RpcH64, H256 as RpcH256, H160 as RpcH160, U256 as RpcU256,
};
use v1::metadata::Metadata;
const EXTRA_INFO_PROOF: &'static str = "Object exists in in blockchain (fetched earlier), extra_info is always available if object exists; qed";
/// Eth RPC options
pub struct EthClientOptions {
/// Return nonce from transaction queue when pending block not available.
pub pending_nonce_from_queue: bool,
/// Returns receipt from pending blocks
pub allow_pending_receipt_query: bool,
/// Send additional block number when asking for work
pub send_block_number_in_get_work: bool,
}
impl EthClientOptions {
/// Creates new default `EthClientOptions` and allows alterations
/// by provided function.
pub fn with<F: Fn(&mut Self)>(fun: F) -> Self {
let mut options = Self::default();
fun(&mut options);
options
}
}
impl Default for EthClientOptions {
fn default() -> Self {
EthClientOptions {
pending_nonce_from_queue: false,
allow_pending_receipt_query: true,
send_block_number_in_get_work: true,
}
}
}
/// Eth rpc implementation.
pub struct EthClient<C, SN:?Sized, S:?Sized, M, EM> where
C: MiningBlockChainClient,
SN: SnapshotService,
S: SyncProvider,
M: MinerService,
EM: ExternalMinerService {
client: Arc<C>,
snapshot: Arc<SN>,
sync: Arc<S>,
accounts: Option<Arc<AccountProvider>>,
miner: Arc<M>,
external_miner: Arc<EM>,
seed_compute: Mutex<SeedHashCompute>,
options: EthClientOptions,
eip86_transition: u64,
}
impl<C, SN:?Sized, S:?Sized, M, EM> EthClient<C, SN, S, M, EM> where
C: MiningBlockChainClient,
SN: SnapshotService,
S: SyncProvider,
M: MinerService,
EM: ExternalMinerService {
/// Creates new EthClient.
pub fn new(
client: &Arc<C>,
snapshot: &Arc<SN>,
sync: &Arc<S>,
accounts: &Option<Arc<AccountProvider>>,
miner: &Arc<M>,
em: &Arc<EM>,
options: EthClientOptions
) -> Self {
EthClient {
client: client.clone(),
snapshot: snapshot.clone(),
sync: sync.clone(),
miner: miner.clone(),
accounts: accounts.clone(),
external_miner: em.clone(),
seed_compute: Mutex::new(SeedHashCompute::new()),
options: options,
eip86_transition: client.eip86_transition(),
}
}
/// Attempt to get the `Arc<AccountProvider>`, errors if provider was not
/// set.
fn account_provider(&self) -> Result<Arc<AccountProvider>> {
unwrap_provider(&self.accounts)
}
fn block(&self, id: BlockId, include_txs: bool) -> Result<Option<RichBlock>> {
let client = &self.client;
match (client.block(id.clone()), client.block_total_difficulty(id)) {
(Some(block), Some(total_difficulty)) => {
let view = block.header_view();
Ok(Some(RichBlock {
inner: Block {
hash: Some(view.hash().into()),
size: Some(block.rlp().as_raw().len().into()),
parent_hash: view.parent_hash().into(),
uncles_hash: view.uncles_hash().into(),
author: view.author().into(),
miner: view.author().into(),
state_root: view.state_root().into(),
transactions_root: view.transactions_root().into(),
receipts_root: view.receipts_root().into(),
number: Some(view.number().into()),
gas_used: view.gas_used().into(),
gas_limit: view.gas_limit().into(),
logs_bloom: view.log_bloom().into(),
timestamp: view.timestamp().into(),
difficulty: view.difficulty().into(),
total_difficulty: Some(total_difficulty.into()),
seal_fields: view.seal().into_iter().map(Into::into).collect(),
uncles: block.uncle_hashes().into_iter().map(Into::into).collect(),
transactions: match include_txs {
true => BlockTransactions::Full(block.view().localized_transactions().into_iter().map(|t| Transaction::from_localized(t, self.eip86_transition)).collect()),
false => BlockTransactions::Hashes(block.transaction_hashes().into_iter().map(Into::into).collect()),
},
extra_data: Bytes::new(view.extra_data()),
},
extra_info: client.block_extra_info(id.clone()).expect(EXTRA_INFO_PROOF),
}))
},
_ => Ok(None)
}
}
fn transaction(&self, id: TransactionId) -> Result<Option<Transaction>> {
match self.client.transaction(id) {
Some(t) => Ok(Some(Transaction::from_localized(t, self.eip86_transition))),
None => Ok(None),
}
}
fn uncle(&self, id: UncleId) -> Result<Option<RichBlock>> {
let client = &self.client;
let uncle: BlockHeader = match client.uncle(id) {
Some(hdr) => hdr.decode(),
None => { return Ok(None); }
};
let parent_difficulty = match client.block_total_difficulty(BlockId::Hash(uncle.parent_hash().clone())) {
Some(difficulty) => difficulty,
None => { return Ok(None); }
};
let size = client.block(BlockId::Hash(uncle.hash()))
.map(|block| block.into_inner().len())
.map(U256::from)
.map(Into::into);
let block = RichBlock {
inner: Block {
hash: Some(uncle.hash().into()),
size: size,
parent_hash: uncle.parent_hash().clone().into(),
uncles_hash: uncle.uncles_hash().clone().into(),
author: uncle.author().clone().into(),
miner: uncle.author().clone().into(),
state_root: uncle.state_root().clone().into(),
transactions_root: uncle.transactions_root().clone().into(),
number: Some(uncle.number().into()),
gas_used: uncle.gas_used().clone().into(),
gas_limit: uncle.gas_limit().clone().into(),
logs_bloom: uncle.log_bloom().clone().into(),
timestamp: uncle.timestamp().into(),
difficulty: uncle.difficulty().clone().into(),
total_difficulty: Some((uncle.difficulty().clone() + parent_difficulty).into()),
receipts_root: uncle.receipts_root().clone().into(),
extra_data: uncle.extra_data().clone().into(),
seal_fields: uncle.seal().into_iter().cloned().map(Into::into).collect(),
uncles: vec![],
transactions: BlockTransactions::Hashes(vec![]),
},
extra_info: client.uncle_extra_info(id).expect(EXTRA_INFO_PROOF),
};
Ok(Some(block))
}
fn dapp_accounts(&self, dapp: DappId) -> Result<Vec<H160>> {
let store = self.account_provider()?;
store
.note_dapp_used(dapp.clone())
.and_then(|_| store.dapp_addresses(dapp))
.map_err(|e| errors::account("Could not fetch accounts.", e))
}
}
pub fn pending_logs<M>(miner: &M, best_block: EthBlockNumber, filter: &EthcoreFilter) -> Vec<Log> where M: MinerService {
let receipts = miner.pending_receipts(best_block);
let pending_logs = receipts.into_iter()
.flat_map(|(hash, r)| r.logs.into_iter().map(|l| (hash.clone(), l)).collect::<Vec<(H256, LogEntry)>>())
.collect::<Vec<(H256, LogEntry)>>();
let result = pending_logs.into_iter()
.filter(|pair| filter.matches(&pair.1))
.map(|pair| {
let mut log = Log::from(pair.1);
log.transaction_hash = Some(pair.0.into());
log
})
.collect();
result
}
fn check_known<C>(client: &C, number: BlockNumber) -> Result<()> where C: MiningBlockChainClient {
use ethcore::block_status::BlockStatus;
match client.block_status(number.into()) {
BlockStatus::InChain => Ok(()),
BlockStatus::Pending => Ok(()),
_ => Err(errors::unknown_block()),
}
}
const MAX_QUEUE_SIZE_TO_MINE_ON: usize = 4; // because uncles go back 6.
impl<C, SN:?Sized, S:?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
C: MiningBlockChainClient +'static,
SN: SnapshotService +'static,
S: SyncProvider +'static,
M: MinerService +'static,
EM: ExternalMinerService +'static,
{
type Metadata = Metadata;
fn protocol_version(&self) -> Result<String> {
let version = self.sync.status().protocol_version.to_owned();
Ok(format!("{}", version))
}
fn syncing(&self) -> Result<SyncStatus> {
use ethcore::snapshot::RestorationStatus;
let status = self.sync.status();
let client = &self.client;
let snapshot_status = self.snapshot.status();
let (warping, warp_chunks_amount, warp_chunks_processed) = match snapshot_status {
RestorationStatus::Ongoing { state_chunks, block_chunks, state_chunks_done, block_chunks_done } =>
(true, Some(block_chunks + state_chunks), Some(block_chunks_done + state_chunks_done)),
_ => (false, None, None),
};
if warping || is_major_importing(Some(status.state), client.queue_info()) {
let chain_info = client.chain_info();
let current_block = U256::from(chain_info.best_block_number);
let highest_block = U256::from(status.highest_block_number.unwrap_or(status.start_block_number));
let info = SyncInfo {
starting_block: status.start_block_number.into(),
current_block: current_block.into(),
highest_block: highest_block.into(),
warp_chunks_amount: warp_chunks_amount.map(|x| U256::from(x as u64)).map(Into::into),
warp_chunks_processed: warp_chunks_processed.map(|x| U256::from(x as u64)).map(Into::into),
};
Ok(SyncStatus::Info(info))
} else {
Ok(SyncStatus::None)
}
}
fn author(&self, meta: Metadata) -> Result<RpcH160> {
let dapp = meta.dapp_id();
let mut miner = self.miner.author();
if miner == 0.into() {
miner = self.dapp_accounts(dapp.into())?.get(0).cloned().unwrap_or_default();
}
Ok(RpcH160::from(miner))
}
fn is_mining(&self) -> Result<bool> {
Ok(self.miner.is_currently_sealing())
}
fn hashrate(&self) -> Result<RpcU256> {
Ok(RpcU256::from(self.external_miner.hashrate()))
}
fn gas_price(&self) -> Result<RpcU256> {
Ok(RpcU256::from(default_gas_price(&*self.client, &*self.miner)))
}
fn accounts(&self, meta: Metadata) -> Result<Vec<RpcH160>> {
let dapp = meta.dapp_id();
let accounts = self.dapp_accounts(dapp.into())?;
Ok(accounts.into_iter().map(Into::into).collect())
}
fn block_number(&self) -> Result<RpcU256> {
Ok(RpcU256::from(self.client.chain_info().best_block_number))
}
fn balance(&self, address: RpcH160, num: Trailing<BlockNumber>) -> BoxFuture<RpcU256> {
let address = address.into();
let id = num.unwrap_or_default();
try_bf!(check_known(&*self.client, id.clone()));
let res = match self.client.balance(&address, id.into()) {
Some(balance) => Ok(balance.into()),
None => Err(errors::state_pruned()),
};
Box::new(future::done(res))
}
fn storage_at(&self, address: RpcH160, pos: RpcU256, num: Trailing<BlockNumber>) -> BoxFuture<RpcH256> {
let address: Address = RpcH160::into(address);
let position: U256 = RpcU256::into(pos);
let id = num.unwrap_or_default();
try_bf!(check_known(&*self.client, id.clone()));
let res = match self.client.storage_at(&address, &H256::from(position), id.into()) {
Some(s) => Ok(s.into()),
None => Err(errors::state_pruned()),
};
Box::new(future::done(res))
}
fn transaction_count(&self, address: RpcH160, num: Trailing<BlockNumber>) -> BoxFuture<RpcU256> {
let address: Address = RpcH160::into(address);
let res = match num.unwrap_or_default() {
BlockNumber::Pending if self.options.pending_nonce_from_queue => {
let nonce = self.miner.last_nonce(&address)
.map(|n| n + 1.into())
.or_else(|| self.client.nonce(&address, BlockNumber::Pending.into()));
match nonce {
Some(nonce) => Ok(nonce.into()),
None => Err(errors::database("latest nonce missing"))
}
}
id => {
try_bf!(check_known(&*self.client, id.clone()));
match self.client.nonce(&address, id.into()) {
Some(nonce) => Ok(nonce.into()),
None => Err(errors::state_pruned()),
}
}
};
Box::new(future::done(res))
}
fn block_transaction_count_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(self.client.block(BlockId::Hash(hash.into()))
.map(|block| block.transactions_count().into())))
}
fn block_transaction_count_by_number(&self, num: BlockNumber) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(match num {
BlockNumber::Pending => Some(
self.miner.status().transactions_in_pending_block.into()
),
_ =>
self.client.block(num.into())
.map(|block| block.transactions_count().into())
}))
}
fn block_uncles_count_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(self.client.block(BlockId::Hash(hash.into()))
.map(|block| block.uncles_count().into())))
}
fn block_uncles_count_by_number(&self, num: BlockNumber) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(match num {
BlockNumber::Pending => Some(0.into()),
_ => self.client.block(num.into())
.map(|block| block.uncles_count().into()
),
}))
}
fn code_at(&self, address: RpcH160, num: Trailing<BlockNumber>) -> BoxFuture<Bytes> {
let address: Address = RpcH160::into(address);
let id = num.unwrap_or_default();
try_bf!(check_known(&*self.client, id.clone()));
let res = match self.client.code(&address, id.into()) {
Some(code) => Ok(code.map_or_else(Bytes::default, Bytes::new)),
None => Err(errors::state_pruned()),
};
Box::new(future::done(res))
}
fn block_by_hash(&self, hash: RpcH256, include_txs: bool) -> BoxFuture<Option<RichBlock>> {
Box::new(future::done(self.block(BlockId::Hash(hash.into()), include_txs)))
}
fn block_by_number(&self, num: BlockNumber, include_txs: bool) -> BoxFuture<Option<RichBlock>> {
Box::new(future::done(self.block(num.into(), include_txs)))
}
fn transaction_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<Transaction>> {
let hash: H256 = hash.into();
let block_number = self.client.chain_info().best_block_number;
let tx = try_bf!(self.transaction(TransactionId::Hash(hash))).or_else(|| {
self.miner.transaction(block_number, &hash)
.map(|t| Transaction::from_pending(t, block_number, self.eip86_transition))
});
Box::new(future::ok(tx))
}
fn
|
(&self, hash: RpcH256, index: Index) -> BoxFuture<Option<Transaction>> {
Box::new(future::done(
self.transaction(TransactionId::Location(BlockId::Hash(hash.into()), index.value()))
))
}
fn transaction_by_block_number_and_index(&self, num: BlockNumber, index: Index) -> BoxFuture<Option<Transaction>> {
Box::new(future::done(
self.transaction(TransactionId::Location(num.into(), index.value()))
))
}
fn transaction_receipt(&self, hash: RpcH256) -> BoxFuture<Option<Receipt>> {
let best_block = self.client.chain_info().best_block_number;
let hash: H256 = hash.into();
match (self.miner.pending_receipt(best_block, &hash), self.options.allow_pending_receipt_query) {
(Some(receipt), true) => Box::new(future::ok(Some(receipt.into()))),
_ => {
let receipt = self.client.transaction_receipt(TransactionId::Hash(hash));
Box::new(future::ok(receipt.map(Into::into)))
}
}
}
fn uncle_by_block_hash_and_index(&self, hash: RpcH256, index: Index) -> BoxFuture<Option<RichBlock>> {
Box::new(future::done(self.uncle(UncleId {
block: BlockId::Hash(hash.into()),
position: index.value()
})))
}
fn uncle_by_block_number_and_index(&self, num: BlockNumber, index: Index) -> BoxFuture<Option<RichBlock>> {
Box::new(future::done(self.uncle(UncleId {
block: num.into(),
position: index.value()
})))
}
fn compilers(&self) -> Result<Vec<String>> {
Err(errors::deprecated("Compilation functionality is deprecated.".to_string()))
}
fn logs(&self, filter: Filter) -> BoxFuture<Vec<Log>> {
let include_pending = filter.to_block == Some(BlockNumber::Pending);
let filter: EthcoreFilter = filter.into();
let mut logs = self.client.logs(filter.clone())
.into_iter()
.map(From::from)
.collect::<Vec<Log>>();
if include_pending {
let best_block = self.client.chain_info().best_block_number;
let pending = pending_logs(&*self.miner, best_block, &filter);
logs.extend(pending);
}
let logs = limit_logs(logs, filter.limit);
Box::new(future::ok(logs))
}
fn work(&self, no_new_work_timeout: Trailing<u64>) -> Result<Work> {
if!self.miner.can_produce_work_package() {
warn!(target: "miner", "Cannot give work package - engine seals internally.");
return Err(errors::no_work_required())
}
let no_new_work_timeout = no_new_work_timeout.unwrap_or_default();
// check if we're still syncing and return empty strings in that case
{
//TODO: check if initial sync is complete here
//let sync = self.sync;
if /*sync.status().state!= SyncState::Idle ||*/ self.client.queue_info().total_queue_size() > MAX_QUEUE_SIZE_TO_MINE_ON {
trace!(target: "miner", "Syncing. Cannot give any work.");
return Err(errors::no_work());
}
// Otherwise spin until our submitted block has been included.
let timeout = Instant::now() + Duration::from_millis(1000);
while Instant::now() < timeout && self.client.queue_info().total_queue_size() > 0 {
thread::sleep(Duration::from_millis(1));
}
}
if self.miner.author().is_zero() {
warn!(target: "miner", "Cannot give work package - no author is configured. Use --author to configure!");
return Err(errors::no_author())
}
self.miner.map_sealing_work(&*self.client, |b| {
let pow_hash = b.hash();
let target = Ethash::difficulty_to_boundary(b.block().header().difficulty());
let seed_hash = self.seed_compute.lock().hash_block_number(b.block().header().number());
if no_new_work_timeout > 0 && b.block().header().timestamp() + no_new_work_timeout < get_time().sec as u64 {
Err(errors::no_new_work())
} else if self.options.send_block_number_in_get_work {
let block_number = b.block().header().number();
Ok(Work {
pow_hash: pow_hash.into(),
seed_hash: seed_hash.into(),
target: target.into(),
number: Some(block_number),
})
} else {
Ok(Work {
pow_hash: pow_hash.into(),
seed_hash: seed_hash.into(),
target: target.into(),
number: None
})
}
}).unwrap_or(Err(errors::internal("No work found.", "")))
}
fn submit_work(&self, nonce: RpcH64, pow_hash: RpcH256, mix_hash: RpcH256) -> Result<bool> {
if!self.miner.can_produce_work_package() {
warn!(target: "miner", "Cannot submit work - engine seals internally.");
return Err(errors::no_work_required())
}
let nonce: H64 = nonce.into();
let pow_hash: H256 = pow_hash.into();
let mix_hash: H256 = mix_hash.into();
trace!(target: "miner", "submit_work: Decoded: nonce={}, pow_hash={}, mix_hash={}", nonce, pow_hash, mix_hash);
let seal = vec![rlp::encode(&mix_hash).into_vec(), rlp::encode(&nonce).into_vec()];
Ok(self.miner.submit_seal(&*self.client, pow_hash, seal).is_ok())
}
fn submit_hashrate(&self, rate: RpcU256, id: RpcH256) -> Result<bool> {
self.external_miner.submit_hashrate(rate.into(), id.into());
Ok(true)
}
fn send_raw_transaction(&self, raw: Bytes) -> Result<RpcH256> {
UntrustedRlp::new(&raw.into_vec()).as_val()
.map_err(errors::rlp)
.and_then(|tx| SignedTransaction::new(tx).map_err(errors::transaction))
.and_then(|signed_transaction| {
FullDispatcher::dispatch_transaction(
&*self.client,
&*self.miner,
signed_transaction.into(),
)
})
.map(Into::into)
}
fn submit_transaction(&self, raw: Bytes) -> Result<RpcH256> {
self.send_raw_transaction(raw)
}
fn call(&self, meta: Self::Metadata, request: CallRequest, num: Trailing<BlockNumber>) -> BoxFuture<Bytes> {
let request = CallRequest::into(request);
let signed = try_bf!(fake_sign::sign_call(request, meta.is_dapp()));
let num = num.unwrap_or_default();
let result = self.client.call(&signed, Default::default(), num.into());
Box::new(future::done(result
.map(|b| b.output.into())
.map_err(errors::call)
))
}
fn estimate_gas(&self, meta: Self::Metadata, request: CallRequest, num: Trailing<BlockNumber>) -> BoxFuture<RpcU256> {
let request = CallRequest::into(request);
let signed = try_bf!(fake_sign::sign_call(request, meta.is_dapp()));
Box::new(future::done(self.client.estimate_gas(&signed, num.unwrap_or_default().into())
.map(Into::into)
.map_err(errors::call)
))
}
fn compile_lll(&self, _: String) -> Result<Bytes> {
Err(errors::deprecated("Compilation of LLL via RPC is deprecated".to_string()))
}
fn compile_serpent(&self, _: String) -> Result<Bytes> {
Err(errors::deprecated("Compilation of Serpent via RPC is deprecated".to_string()))
}
fn compile_solidity(&self, _: String) -> Result<Bytes> {
Err(errors::deprecated("Compilation of Solidity via RPC is deprecated".to_string()))
}
}
|
transaction_by_block_hash_and_index
|
identifier_name
|
basic_lib.rs
|
#![ warn( missing_docs ) ]
#![ warn( missing_debug_implementations ) ]
#![ allow( dead_code ) ]
// #![no_std]
//!
//! Tools for writing and runnint tests.
//!
//! # Sample
//! ``` rust
//! use wtest_basic::*;
//!
//! //
//!
//! fn _pass1()
//! {
//! assert_eq!( true, true );
//! }
//!
//! //
//!
//! fn _pass2()
//! {
//! assert_eq!( 1, 1 );
//! }
//!
//! //
//!
//! test_suite!
//! {
//! pass1,
//! pass2,
//! }
//!
//! ```
pub extern crate paste;
///
/// Dependencies.
///
pub mod dependencies
{
pub use paste;
// #[ cfg( test ) ]
pub use trybuild;
// #[ cfg( test ) ]
pub use anyhow;
// #[ cfg( test ) ]
// #[ cfg( debug_assertions ) ]
pub use rustversion;
}
/// Mechanism to define test suite. This macro encourages refactoring the code of the test in the most readable way, gathering a list of all test routines at the end of the test file.
#[ macro_export ]
macro_rules! test_suite
{
( $( $Name : ident ),* $(,)? ) =>
{
$( #[test] fn $Name() { $crate::paste::paste!([< _ $Name >])() } )*
// $( #[test] fn $Name() { concat_idents!( _, $Name )() } )*
}
// ( $( $Name : ident ),* $(,)? ) =>
// {
// // $( #[test] fn concat_idents!( $Name, _test )() { $Name() } )*
|
// $( #[test] fn paste!([< $Name _test >])() { $Name() } )*
// }
}
// /// Pass only if callback fails either returning error or panicing.
//
// pub fn should_throw< R, F : FnOnce() -> anyhow::Result< R > >( f : F ) -> anyhow::Result< R >
// {
// f()
// }
//
// #[panic_handler]
// fn panic( info : &core::panic::PanicInfo ) ->!
// {
// println!( "{:?}", info );
// loop {}
// }
|
random_line_split
|
|
basic_shape.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS handling for the computed value of
//! [`basic-shape`][basic-shape]s
//!
//! [basic-shape]: https://drafts.csswg.org/css-shapes/#typedef-basic-shape
use std::fmt;
use style_traits::ToCss;
use values::computed::{LengthOrPercentage, ComputedUrl, Image};
use values::generics::basic_shape::{BasicShape as GenericBasicShape};
use values::generics::basic_shape::{Circle as GenericCircle, ClippingShape as GenericClippingShape};
use values::generics::basic_shape::{Ellipse as GenericEllipse, FloatAreaShape as GenericFloatAreaShape};
use values::generics::basic_shape::{InsetRect as GenericInsetRect, ShapeRadius as GenericShapeRadius};
/// A computed clipping shape.
pub type ClippingShape = GenericClippingShape<BasicShape, ComputedUrl>;
/// A computed float area shape.
pub type FloatAreaShape = GenericFloatAreaShape<BasicShape, Image>;
/// A computed basic shape.
pub type BasicShape = GenericBasicShape<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// The computed value of `inset()`
pub type InsetRect = GenericInsetRect<LengthOrPercentage>;
/// A computed circle.
pub type Circle = GenericCircle<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// A computed ellipse.
pub type Ellipse = GenericEllipse<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// The computed value of `ShapeRadius`
pub type ShapeRadius = GenericShapeRadius<LengthOrPercentage>;
impl ToCss for Circle {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
dest.write_str("circle(")?;
self.radius.to_css(dest)?;
dest.write_str(" at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
impl ToCss for Ellipse {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
dest.write_str("ellipse(")?;
if (self.semiaxis_x, self.semiaxis_y)!= Default::default()
|
dest.write_str("at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
|
{
self.semiaxis_x.to_css(dest)?;
dest.write_str(" ")?;
self.semiaxis_y.to_css(dest)?;
dest.write_str(" ")?;
}
|
conditional_block
|
basic_shape.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS handling for the computed value of
//! [`basic-shape`][basic-shape]s
//!
//! [basic-shape]: https://drafts.csswg.org/css-shapes/#typedef-basic-shape
use std::fmt;
use style_traits::ToCss;
use values::computed::{LengthOrPercentage, ComputedUrl, Image};
use values::generics::basic_shape::{BasicShape as GenericBasicShape};
use values::generics::basic_shape::{Circle as GenericCircle, ClippingShape as GenericClippingShape};
use values::generics::basic_shape::{Ellipse as GenericEllipse, FloatAreaShape as GenericFloatAreaShape};
use values::generics::basic_shape::{InsetRect as GenericInsetRect, ShapeRadius as GenericShapeRadius};
/// A computed clipping shape.
pub type ClippingShape = GenericClippingShape<BasicShape, ComputedUrl>;
/// A computed float area shape.
pub type FloatAreaShape = GenericFloatAreaShape<BasicShape, Image>;
/// A computed basic shape.
pub type BasicShape = GenericBasicShape<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// The computed value of `inset()`
pub type InsetRect = GenericInsetRect<LengthOrPercentage>;
/// A computed circle.
pub type Circle = GenericCircle<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// A computed ellipse.
pub type Ellipse = GenericEllipse<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// The computed value of `ShapeRadius`
pub type ShapeRadius = GenericShapeRadius<LengthOrPercentage>;
impl ToCss for Circle {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
dest.write_str("circle(")?;
self.radius.to_css(dest)?;
dest.write_str(" at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
impl ToCss for Ellipse {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write
|
}
|
{
dest.write_str("ellipse(")?;
if (self.semiaxis_x, self.semiaxis_y) != Default::default() {
self.semiaxis_x.to_css(dest)?;
dest.write_str(" ")?;
self.semiaxis_y.to_css(dest)?;
dest.write_str(" ")?;
}
dest.write_str("at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
|
identifier_body
|
basic_shape.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS handling for the computed value of
//! [`basic-shape`][basic-shape]s
//!
//! [basic-shape]: https://drafts.csswg.org/css-shapes/#typedef-basic-shape
use std::fmt;
use style_traits::ToCss;
use values::computed::{LengthOrPercentage, ComputedUrl, Image};
use values::generics::basic_shape::{BasicShape as GenericBasicShape};
use values::generics::basic_shape::{Circle as GenericCircle, ClippingShape as GenericClippingShape};
use values::generics::basic_shape::{Ellipse as GenericEllipse, FloatAreaShape as GenericFloatAreaShape};
use values::generics::basic_shape::{InsetRect as GenericInsetRect, ShapeRadius as GenericShapeRadius};
/// A computed clipping shape.
pub type ClippingShape = GenericClippingShape<BasicShape, ComputedUrl>;
/// A computed float area shape.
pub type FloatAreaShape = GenericFloatAreaShape<BasicShape, Image>;
/// A computed basic shape.
|
pub type BasicShape = GenericBasicShape<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// The computed value of `inset()`
pub type InsetRect = GenericInsetRect<LengthOrPercentage>;
/// A computed circle.
pub type Circle = GenericCircle<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// A computed ellipse.
pub type Ellipse = GenericEllipse<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// The computed value of `ShapeRadius`
pub type ShapeRadius = GenericShapeRadius<LengthOrPercentage>;
impl ToCss for Circle {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
dest.write_str("circle(")?;
self.radius.to_css(dest)?;
dest.write_str(" at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
impl ToCss for Ellipse {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
dest.write_str("ellipse(")?;
if (self.semiaxis_x, self.semiaxis_y)!= Default::default() {
self.semiaxis_x.to_css(dest)?;
dest.write_str(" ")?;
self.semiaxis_y.to_css(dest)?;
dest.write_str(" ")?;
}
dest.write_str("at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
|
random_line_split
|
|
basic_shape.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS handling for the computed value of
//! [`basic-shape`][basic-shape]s
//!
//! [basic-shape]: https://drafts.csswg.org/css-shapes/#typedef-basic-shape
use std::fmt;
use style_traits::ToCss;
use values::computed::{LengthOrPercentage, ComputedUrl, Image};
use values::generics::basic_shape::{BasicShape as GenericBasicShape};
use values::generics::basic_shape::{Circle as GenericCircle, ClippingShape as GenericClippingShape};
use values::generics::basic_shape::{Ellipse as GenericEllipse, FloatAreaShape as GenericFloatAreaShape};
use values::generics::basic_shape::{InsetRect as GenericInsetRect, ShapeRadius as GenericShapeRadius};
/// A computed clipping shape.
pub type ClippingShape = GenericClippingShape<BasicShape, ComputedUrl>;
/// A computed float area shape.
pub type FloatAreaShape = GenericFloatAreaShape<BasicShape, Image>;
/// A computed basic shape.
pub type BasicShape = GenericBasicShape<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// The computed value of `inset()`
pub type InsetRect = GenericInsetRect<LengthOrPercentage>;
/// A computed circle.
pub type Circle = GenericCircle<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// A computed ellipse.
pub type Ellipse = GenericEllipse<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// The computed value of `ShapeRadius`
pub type ShapeRadius = GenericShapeRadius<LengthOrPercentage>;
impl ToCss for Circle {
fn
|
<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
dest.write_str("circle(")?;
self.radius.to_css(dest)?;
dest.write_str(" at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
impl ToCss for Ellipse {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
dest.write_str("ellipse(")?;
if (self.semiaxis_x, self.semiaxis_y)!= Default::default() {
self.semiaxis_x.to_css(dest)?;
dest.write_str(" ")?;
self.semiaxis_y.to_css(dest)?;
dest.write_str(" ")?;
}
dest.write_str("at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
|
to_css
|
identifier_name
|
selectors.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Parser, ParserInput, ToCss};
use selectors::parser::SelectorList;
use style::selector_parser::{SelectorImpl, SelectorParser};
use style::stylesheets::{Origin, Namespaces};
use style_traits::ParseError;
fn
|
<'i, 't>(input: &mut Parser<'i, 't>) -> Result<SelectorList<SelectorImpl>, ParseError<'i>> {
let mut ns = Namespaces::default();
ns.prefixes.insert("svg".into(), (ns!(svg), ()));
let parser = SelectorParser {
stylesheet_origin: Origin::UserAgent,
namespaces: &ns,
};
SelectorList::parse(&parser, input)
}
#[test]
fn test_selectors() {
assert_roundtrip!(parse_selector, "div");
assert_roundtrip!(parse_selector, "svg|circle");
assert_roundtrip!(parse_selector, "p:before", "p::before");
assert_roundtrip!(parse_selector, "[border=\"0\"]:-servo-nonzero-border ~ ::-servo-details-summary");
}
|
parse_selector
|
identifier_name
|
selectors.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Parser, ParserInput, ToCss};
use selectors::parser::SelectorList;
use style::selector_parser::{SelectorImpl, SelectorParser};
use style::stylesheets::{Origin, Namespaces};
use style_traits::ParseError;
fn parse_selector<'i, 't>(input: &mut Parser<'i, 't>) -> Result<SelectorList<SelectorImpl>, ParseError<'i>>
|
#[test]
fn test_selectors() {
assert_roundtrip!(parse_selector, "div");
assert_roundtrip!(parse_selector, "svg|circle");
assert_roundtrip!(parse_selector, "p:before", "p::before");
assert_roundtrip!(parse_selector, "[border=\"0\"]:-servo-nonzero-border ~ ::-servo-details-summary");
}
|
{
let mut ns = Namespaces::default();
ns.prefixes.insert("svg".into(), (ns!(svg), ()));
let parser = SelectorParser {
stylesheet_origin: Origin::UserAgent,
namespaces: &ns,
};
SelectorList::parse(&parser, input)
}
|
identifier_body
|
selectors.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Parser, ParserInput, ToCss};
use selectors::parser::SelectorList;
use style::selector_parser::{SelectorImpl, SelectorParser};
use style::stylesheets::{Origin, Namespaces};
use style_traits::ParseError;
fn parse_selector<'i, 't>(input: &mut Parser<'i, 't>) -> Result<SelectorList<SelectorImpl>, ParseError<'i>> {
let mut ns = Namespaces::default();
ns.prefixes.insert("svg".into(), (ns!(svg), ()));
let parser = SelectorParser {
stylesheet_origin: Origin::UserAgent,
namespaces: &ns,
};
SelectorList::parse(&parser, input)
}
#[test]
fn test_selectors() {
assert_roundtrip!(parse_selector, "div");
assert_roundtrip!(parse_selector, "svg|circle");
assert_roundtrip!(parse_selector, "p:before", "p::before");
assert_roundtrip!(parse_selector, "[border=\"0\"]:-servo-nonzero-border ~ ::-servo-details-summary");
}
|
random_line_split
|
|
stack.rs
|
// Copyright 2016 coroutine-rs Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
use std::error::Error;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::io;
use std::ops::Deref;
use std::os::raw::c_void;
use sys;
/// Error type returned by stack allocation methods.
#[derive(Debug)]
pub enum StackError {
/// Contains the maximum amount of memory allowed to be allocated as stack space.
ExceedsMaximumSize(usize),
/// Returned if some kind of I/O error happens during allocation.
IoError(io::Error),
}
impl Display for StackError {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
match *self {
StackError::ExceedsMaximumSize(size) => {
write!(fmt, "Requested more than max size of {} bytes for a stack", size)
},
StackError::IoError(ref e) => e.fmt(fmt),
}
}
}
impl Error for StackError {
fn description(&self) -> &str {
match *self {
StackError::ExceedsMaximumSize(_) => "exceeds maximum stack size",
StackError::IoError(ref e) => e.description(),
}
}
fn cause(&self) -> Option<&Error> {
match *self {
StackError::ExceedsMaximumSize(_) => None,
StackError::IoError(ref e) => Some(e),
}
}
}
/// Represents any kind of stack memory.
///
/// `FixedSizeStack` as well as `ProtectedFixedSizeStack`
/// can be used to allocate actual stack space.
#[derive(Debug)]
pub struct Stack {
top: *mut c_void,
bottom: *mut c_void,
}
impl Stack {
/// Creates a (non-owning) representation of some stack memory.
///
/// It is unsafe because it is your reponsibility to make sure that `top` and `buttom` are valid
/// addresses.
#[inline]
pub unsafe fn new(top: *mut c_void, bottom: *mut c_void) -> Stack {
debug_assert!(top >= bottom);
Stack {
top: top,
bottom: bottom,
}
}
/// Returns the top of the stack from which on it grows downwards towards bottom().
#[inline]
pub fn top(&self) -> *mut c_void {
self.top
}
/// Returns the bottom of the stack and thus it's end.
#[inline]
pub fn bottom(&self) -> *mut c_void {
self.bottom
}
/// Returns the size of the stack between top() and bottom().
#[inline]
pub fn len(&self) -> usize {
self.top as usize - self.bottom as usize
}
/// Returns the minimal stack size allowed by the current platform.
#[inline]
pub fn min_size() -> usize {
sys::min_stack_size()
}
/// Returns the maximum stack size allowed by the current platform.
#[inline]
pub fn max_size() -> usize {
sys::max_stack_size()
}
/// Returns a implementation defined default stack size.
///
/// This value can vary greatly between platforms, but is usually only a couple
/// memory pages in size and enough for most use-cases with little recursion.
/// It's usually a better idea to specifiy an explicit stack size instead.
#[inline]
pub fn default_size() -> usize {
sys::default_stack_size()
}
/// Allocates a new stack of `size`.
fn allocate(mut size: usize, protected: bool) -> Result<Stack, StackError> {
let page_size = sys::page_size();
let min_stack_size = sys::min_stack_size();
let max_stack_size = sys::max_stack_size();
let add_shift = if protected { 1 } else { 0 };
let add = page_size << add_shift;
if size < min_stack_size {
size = min_stack_size;
}
size = (size - 1) &!(page_size - 1);
if let Some(size) = size.checked_add(add) {
if size <= max_stack_size {
let mut ret = unsafe { sys::allocate_stack(size) };
if protected
|
return ret.map_err(StackError::IoError);
}
}
Err(StackError::ExceedsMaximumSize(max_stack_size - add))
}
}
unsafe impl Send for Stack {}
/// A very simple and straightforward implementation of `Stack`.
///
/// Allocates stack space using virtual memory, whose pages will
/// only be mapped to physical memory if they are used.
///
/// _As a general rule it is recommended to use `ProtectedFixedSizeStack` instead._
#[derive(Debug)]
pub struct FixedSizeStack(Stack);
impl FixedSizeStack {
/// Allocates a new stack of **at least** `size` bytes.
///
/// `size` is rounded up to a multiple of the size of a memory page.
pub fn new(size: usize) -> Result<FixedSizeStack, StackError> {
Stack::allocate(size, false).map(FixedSizeStack)
}
}
impl Deref for FixedSizeStack {
type Target = Stack;
fn deref(&self) -> &Stack {
&self.0
}
}
impl Default for FixedSizeStack {
fn default() -> FixedSizeStack {
FixedSizeStack::new(Stack::default_size())
.unwrap_or_else(|err| panic!("Failed to allocate FixedSizeStack with {:?}", err))
}
}
impl Drop for FixedSizeStack {
fn drop(&mut self) {
unsafe {
sys::deallocate_stack(self.0.bottom(), self.0.len());
}
}
}
/// A more secure, but slightly slower version of `FixedSizeStack`.
///
/// Allocates stack space using virtual memory, whose pages will
/// only be mapped to physical memory if they are used.
///
/// The additional guard page is made protected and inaccessible.
/// Now if a stack overflow occurs it should (hopefully) hit this guard page and
/// cause a segmentation fault instead letting the memory being overwritten silently.
///
/// _As a general rule it is recommended to use **this** struct to create stack memory._
#[derive(Debug)]
pub struct ProtectedFixedSizeStack(Stack);
impl ProtectedFixedSizeStack {
/// Allocates a new stack of **at least** `size` bytes + one additional guard page.
///
/// `size` is rounded up to a multiple of the size of a memory page and
/// does not include the size of the guard page itself.
pub fn new(size: usize) -> Result<ProtectedFixedSizeStack, StackError> {
Stack::allocate(size, true).map(ProtectedFixedSizeStack)
}
}
impl Deref for ProtectedFixedSizeStack {
type Target = Stack;
fn deref(&self) -> &Stack {
&self.0
}
}
impl Default for ProtectedFixedSizeStack {
fn default() -> ProtectedFixedSizeStack {
ProtectedFixedSizeStack::new(Stack::default_size()).unwrap_or_else(|err| {
panic!("Failed to allocate ProtectedFixedSizeStack with {:?}", err)
})
}
}
impl Drop for ProtectedFixedSizeStack {
fn drop(&mut self) {
let page_size = sys::page_size();
let guard = (self.0.bottom() as usize - page_size) as *mut c_void;
let size_with_guard = self.0.len() + page_size;
unsafe {
sys::deallocate_stack(guard, size_with_guard);
}
}
}
#[cfg(test)]
mod tests {
use std::ptr::write_bytes;
use super::*;
use sys;
#[test]
fn stack_size_too_small() {
let stack = FixedSizeStack::new(0).unwrap();
assert_eq!(stack.len(), sys::min_stack_size());
unsafe { write_bytes(stack.bottom() as *mut u8, 0x1d, stack.len()) };
let stack = ProtectedFixedSizeStack::new(0).unwrap();
assert_eq!(stack.len(), sys::min_stack_size());
unsafe { write_bytes(stack.bottom() as *mut u8, 0x1d, stack.len()) };
}
#[test]
fn stack_size_too_large() {
let stack_size = sys::max_stack_size() &!(sys::page_size() - 1);
match FixedSizeStack::new(stack_size) {
Err(StackError::ExceedsMaximumSize(..)) => panic!(),
_ => {}
}
let stack_size = stack_size + 1;
match FixedSizeStack::new(stack_size) {
Err(StackError::ExceedsMaximumSize(..)) => {}
_ => panic!(),
}
}
}
|
{
if let Ok(stack) = ret {
ret = unsafe { sys::protect_stack(&stack) };
}
}
|
conditional_block
|
stack.rs
|
// Copyright 2016 coroutine-rs Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
use std::error::Error;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::io;
use std::ops::Deref;
use std::os::raw::c_void;
use sys;
/// Error type returned by stack allocation methods.
#[derive(Debug)]
pub enum StackError {
/// Contains the maximum amount of memory allowed to be allocated as stack space.
ExceedsMaximumSize(usize),
/// Returned if some kind of I/O error happens during allocation.
IoError(io::Error),
}
impl Display for StackError {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
match *self {
StackError::ExceedsMaximumSize(size) => {
write!(fmt, "Requested more than max size of {} bytes for a stack", size)
},
StackError::IoError(ref e) => e.fmt(fmt),
}
}
}
impl Error for StackError {
fn description(&self) -> &str {
match *self {
StackError::ExceedsMaximumSize(_) => "exceeds maximum stack size",
StackError::IoError(ref e) => e.description(),
}
}
fn cause(&self) -> Option<&Error>
|
}
/// Represents any kind of stack memory.
///
/// `FixedSizeStack` as well as `ProtectedFixedSizeStack`
/// can be used to allocate actual stack space.
#[derive(Debug)]
pub struct Stack {
top: *mut c_void,
bottom: *mut c_void,
}
impl Stack {
/// Creates a (non-owning) representation of some stack memory.
///
/// It is unsafe because it is your reponsibility to make sure that `top` and `buttom` are valid
/// addresses.
#[inline]
pub unsafe fn new(top: *mut c_void, bottom: *mut c_void) -> Stack {
debug_assert!(top >= bottom);
Stack {
top: top,
bottom: bottom,
}
}
/// Returns the top of the stack from which on it grows downwards towards bottom().
#[inline]
pub fn top(&self) -> *mut c_void {
self.top
}
/// Returns the bottom of the stack and thus it's end.
#[inline]
pub fn bottom(&self) -> *mut c_void {
self.bottom
}
/// Returns the size of the stack between top() and bottom().
#[inline]
pub fn len(&self) -> usize {
self.top as usize - self.bottom as usize
}
/// Returns the minimal stack size allowed by the current platform.
#[inline]
pub fn min_size() -> usize {
sys::min_stack_size()
}
/// Returns the maximum stack size allowed by the current platform.
#[inline]
pub fn max_size() -> usize {
sys::max_stack_size()
}
/// Returns a implementation defined default stack size.
///
/// This value can vary greatly between platforms, but is usually only a couple
/// memory pages in size and enough for most use-cases with little recursion.
/// It's usually a better idea to specifiy an explicit stack size instead.
#[inline]
pub fn default_size() -> usize {
sys::default_stack_size()
}
/// Allocates a new stack of `size`.
fn allocate(mut size: usize, protected: bool) -> Result<Stack, StackError> {
let page_size = sys::page_size();
let min_stack_size = sys::min_stack_size();
let max_stack_size = sys::max_stack_size();
let add_shift = if protected { 1 } else { 0 };
let add = page_size << add_shift;
if size < min_stack_size {
size = min_stack_size;
}
size = (size - 1) &!(page_size - 1);
if let Some(size) = size.checked_add(add) {
if size <= max_stack_size {
let mut ret = unsafe { sys::allocate_stack(size) };
if protected {
if let Ok(stack) = ret {
ret = unsafe { sys::protect_stack(&stack) };
}
}
return ret.map_err(StackError::IoError);
}
}
Err(StackError::ExceedsMaximumSize(max_stack_size - add))
}
}
unsafe impl Send for Stack {}
/// A very simple and straightforward implementation of `Stack`.
///
/// Allocates stack space using virtual memory, whose pages will
/// only be mapped to physical memory if they are used.
///
/// _As a general rule it is recommended to use `ProtectedFixedSizeStack` instead._
#[derive(Debug)]
pub struct FixedSizeStack(Stack);
impl FixedSizeStack {
/// Allocates a new stack of **at least** `size` bytes.
///
/// `size` is rounded up to a multiple of the size of a memory page.
pub fn new(size: usize) -> Result<FixedSizeStack, StackError> {
Stack::allocate(size, false).map(FixedSizeStack)
}
}
impl Deref for FixedSizeStack {
type Target = Stack;
fn deref(&self) -> &Stack {
&self.0
}
}
impl Default for FixedSizeStack {
fn default() -> FixedSizeStack {
FixedSizeStack::new(Stack::default_size())
.unwrap_or_else(|err| panic!("Failed to allocate FixedSizeStack with {:?}", err))
}
}
impl Drop for FixedSizeStack {
fn drop(&mut self) {
unsafe {
sys::deallocate_stack(self.0.bottom(), self.0.len());
}
}
}
/// A more secure, but slightly slower version of `FixedSizeStack`.
///
/// Allocates stack space using virtual memory, whose pages will
/// only be mapped to physical memory if they are used.
///
/// The additional guard page is made protected and inaccessible.
/// Now if a stack overflow occurs it should (hopefully) hit this guard page and
/// cause a segmentation fault instead letting the memory being overwritten silently.
///
/// _As a general rule it is recommended to use **this** struct to create stack memory._
#[derive(Debug)]
pub struct ProtectedFixedSizeStack(Stack);
impl ProtectedFixedSizeStack {
/// Allocates a new stack of **at least** `size` bytes + one additional guard page.
///
/// `size` is rounded up to a multiple of the size of a memory page and
/// does not include the size of the guard page itself.
pub fn new(size: usize) -> Result<ProtectedFixedSizeStack, StackError> {
Stack::allocate(size, true).map(ProtectedFixedSizeStack)
}
}
impl Deref for ProtectedFixedSizeStack {
type Target = Stack;
fn deref(&self) -> &Stack {
&self.0
}
}
impl Default for ProtectedFixedSizeStack {
fn default() -> ProtectedFixedSizeStack {
ProtectedFixedSizeStack::new(Stack::default_size()).unwrap_or_else(|err| {
panic!("Failed to allocate ProtectedFixedSizeStack with {:?}", err)
})
}
}
impl Drop for ProtectedFixedSizeStack {
fn drop(&mut self) {
let page_size = sys::page_size();
let guard = (self.0.bottom() as usize - page_size) as *mut c_void;
let size_with_guard = self.0.len() + page_size;
unsafe {
sys::deallocate_stack(guard, size_with_guard);
}
}
}
#[cfg(test)]
mod tests {
use std::ptr::write_bytes;
use super::*;
use sys;
#[test]
fn stack_size_too_small() {
let stack = FixedSizeStack::new(0).unwrap();
assert_eq!(stack.len(), sys::min_stack_size());
unsafe { write_bytes(stack.bottom() as *mut u8, 0x1d, stack.len()) };
let stack = ProtectedFixedSizeStack::new(0).unwrap();
assert_eq!(stack.len(), sys::min_stack_size());
unsafe { write_bytes(stack.bottom() as *mut u8, 0x1d, stack.len()) };
}
#[test]
fn stack_size_too_large() {
let stack_size = sys::max_stack_size() &!(sys::page_size() - 1);
match FixedSizeStack::new(stack_size) {
Err(StackError::ExceedsMaximumSize(..)) => panic!(),
_ => {}
}
let stack_size = stack_size + 1;
match FixedSizeStack::new(stack_size) {
Err(StackError::ExceedsMaximumSize(..)) => {}
_ => panic!(),
}
}
}
|
{
match *self {
StackError::ExceedsMaximumSize(_) => None,
StackError::IoError(ref e) => Some(e),
}
}
|
identifier_body
|
stack.rs
|
// Copyright 2016 coroutine-rs Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
use std::error::Error;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::io;
use std::ops::Deref;
use std::os::raw::c_void;
use sys;
/// Error type returned by stack allocation methods.
#[derive(Debug)]
pub enum
|
{
/// Contains the maximum amount of memory allowed to be allocated as stack space.
ExceedsMaximumSize(usize),
/// Returned if some kind of I/O error happens during allocation.
IoError(io::Error),
}
impl Display for StackError {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
match *self {
StackError::ExceedsMaximumSize(size) => {
write!(fmt, "Requested more than max size of {} bytes for a stack", size)
},
StackError::IoError(ref e) => e.fmt(fmt),
}
}
}
impl Error for StackError {
fn description(&self) -> &str {
match *self {
StackError::ExceedsMaximumSize(_) => "exceeds maximum stack size",
StackError::IoError(ref e) => e.description(),
}
}
fn cause(&self) -> Option<&Error> {
match *self {
StackError::ExceedsMaximumSize(_) => None,
StackError::IoError(ref e) => Some(e),
}
}
}
/// Represents any kind of stack memory.
///
/// `FixedSizeStack` as well as `ProtectedFixedSizeStack`
/// can be used to allocate actual stack space.
#[derive(Debug)]
pub struct Stack {
top: *mut c_void,
bottom: *mut c_void,
}
impl Stack {
/// Creates a (non-owning) representation of some stack memory.
///
/// It is unsafe because it is your reponsibility to make sure that `top` and `buttom` are valid
/// addresses.
#[inline]
pub unsafe fn new(top: *mut c_void, bottom: *mut c_void) -> Stack {
debug_assert!(top >= bottom);
Stack {
top: top,
bottom: bottom,
}
}
/// Returns the top of the stack from which on it grows downwards towards bottom().
#[inline]
pub fn top(&self) -> *mut c_void {
self.top
}
/// Returns the bottom of the stack and thus it's end.
#[inline]
pub fn bottom(&self) -> *mut c_void {
self.bottom
}
/// Returns the size of the stack between top() and bottom().
#[inline]
pub fn len(&self) -> usize {
self.top as usize - self.bottom as usize
}
/// Returns the minimal stack size allowed by the current platform.
#[inline]
pub fn min_size() -> usize {
sys::min_stack_size()
}
/// Returns the maximum stack size allowed by the current platform.
#[inline]
pub fn max_size() -> usize {
sys::max_stack_size()
}
/// Returns a implementation defined default stack size.
///
/// This value can vary greatly between platforms, but is usually only a couple
/// memory pages in size and enough for most use-cases with little recursion.
/// It's usually a better idea to specifiy an explicit stack size instead.
#[inline]
pub fn default_size() -> usize {
sys::default_stack_size()
}
/// Allocates a new stack of `size`.
fn allocate(mut size: usize, protected: bool) -> Result<Stack, StackError> {
let page_size = sys::page_size();
let min_stack_size = sys::min_stack_size();
let max_stack_size = sys::max_stack_size();
let add_shift = if protected { 1 } else { 0 };
let add = page_size << add_shift;
if size < min_stack_size {
size = min_stack_size;
}
size = (size - 1) &!(page_size - 1);
if let Some(size) = size.checked_add(add) {
if size <= max_stack_size {
let mut ret = unsafe { sys::allocate_stack(size) };
if protected {
if let Ok(stack) = ret {
ret = unsafe { sys::protect_stack(&stack) };
}
}
return ret.map_err(StackError::IoError);
}
}
Err(StackError::ExceedsMaximumSize(max_stack_size - add))
}
}
unsafe impl Send for Stack {}
/// A very simple and straightforward implementation of `Stack`.
///
/// Allocates stack space using virtual memory, whose pages will
/// only be mapped to physical memory if they are used.
///
/// _As a general rule it is recommended to use `ProtectedFixedSizeStack` instead._
#[derive(Debug)]
pub struct FixedSizeStack(Stack);
impl FixedSizeStack {
/// Allocates a new stack of **at least** `size` bytes.
///
/// `size` is rounded up to a multiple of the size of a memory page.
pub fn new(size: usize) -> Result<FixedSizeStack, StackError> {
Stack::allocate(size, false).map(FixedSizeStack)
}
}
impl Deref for FixedSizeStack {
type Target = Stack;
fn deref(&self) -> &Stack {
&self.0
}
}
impl Default for FixedSizeStack {
fn default() -> FixedSizeStack {
FixedSizeStack::new(Stack::default_size())
.unwrap_or_else(|err| panic!("Failed to allocate FixedSizeStack with {:?}", err))
}
}
impl Drop for FixedSizeStack {
fn drop(&mut self) {
unsafe {
sys::deallocate_stack(self.0.bottom(), self.0.len());
}
}
}
/// A more secure, but slightly slower version of `FixedSizeStack`.
///
/// Allocates stack space using virtual memory, whose pages will
/// only be mapped to physical memory if they are used.
///
/// The additional guard page is made protected and inaccessible.
/// Now if a stack overflow occurs it should (hopefully) hit this guard page and
/// cause a segmentation fault instead letting the memory being overwritten silently.
///
/// _As a general rule it is recommended to use **this** struct to create stack memory._
#[derive(Debug)]
pub struct ProtectedFixedSizeStack(Stack);
impl ProtectedFixedSizeStack {
/// Allocates a new stack of **at least** `size` bytes + one additional guard page.
///
/// `size` is rounded up to a multiple of the size of a memory page and
/// does not include the size of the guard page itself.
pub fn new(size: usize) -> Result<ProtectedFixedSizeStack, StackError> {
Stack::allocate(size, true).map(ProtectedFixedSizeStack)
}
}
impl Deref for ProtectedFixedSizeStack {
type Target = Stack;
fn deref(&self) -> &Stack {
&self.0
}
}
impl Default for ProtectedFixedSizeStack {
fn default() -> ProtectedFixedSizeStack {
ProtectedFixedSizeStack::new(Stack::default_size()).unwrap_or_else(|err| {
panic!("Failed to allocate ProtectedFixedSizeStack with {:?}", err)
})
}
}
impl Drop for ProtectedFixedSizeStack {
fn drop(&mut self) {
let page_size = sys::page_size();
let guard = (self.0.bottom() as usize - page_size) as *mut c_void;
let size_with_guard = self.0.len() + page_size;
unsafe {
sys::deallocate_stack(guard, size_with_guard);
}
}
}
#[cfg(test)]
mod tests {
use std::ptr::write_bytes;
use super::*;
use sys;
#[test]
fn stack_size_too_small() {
let stack = FixedSizeStack::new(0).unwrap();
assert_eq!(stack.len(), sys::min_stack_size());
unsafe { write_bytes(stack.bottom() as *mut u8, 0x1d, stack.len()) };
let stack = ProtectedFixedSizeStack::new(0).unwrap();
assert_eq!(stack.len(), sys::min_stack_size());
unsafe { write_bytes(stack.bottom() as *mut u8, 0x1d, stack.len()) };
}
#[test]
fn stack_size_too_large() {
let stack_size = sys::max_stack_size() &!(sys::page_size() - 1);
match FixedSizeStack::new(stack_size) {
Err(StackError::ExceedsMaximumSize(..)) => panic!(),
_ => {}
}
let stack_size = stack_size + 1;
match FixedSizeStack::new(stack_size) {
Err(StackError::ExceedsMaximumSize(..)) => {}
_ => panic!(),
}
}
}
|
StackError
|
identifier_name
|
stack.rs
|
// Copyright 2016 coroutine-rs Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
use std::error::Error;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::io;
use std::ops::Deref;
use std::os::raw::c_void;
use sys;
/// Error type returned by stack allocation methods.
#[derive(Debug)]
pub enum StackError {
/// Contains the maximum amount of memory allowed to be allocated as stack space.
ExceedsMaximumSize(usize),
/// Returned if some kind of I/O error happens during allocation.
IoError(io::Error),
}
impl Display for StackError {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
match *self {
StackError::ExceedsMaximumSize(size) => {
write!(fmt, "Requested more than max size of {} bytes for a stack", size)
},
StackError::IoError(ref e) => e.fmt(fmt),
}
}
}
impl Error for StackError {
fn description(&self) -> &str {
match *self {
StackError::ExceedsMaximumSize(_) => "exceeds maximum stack size",
StackError::IoError(ref e) => e.description(),
}
}
fn cause(&self) -> Option<&Error> {
match *self {
StackError::ExceedsMaximumSize(_) => None,
StackError::IoError(ref e) => Some(e),
}
}
}
/// Represents any kind of stack memory.
///
/// `FixedSizeStack` as well as `ProtectedFixedSizeStack`
/// can be used to allocate actual stack space.
#[derive(Debug)]
pub struct Stack {
top: *mut c_void,
bottom: *mut c_void,
}
impl Stack {
/// Creates a (non-owning) representation of some stack memory.
///
/// It is unsafe because it is your reponsibility to make sure that `top` and `buttom` are valid
/// addresses.
#[inline]
pub unsafe fn new(top: *mut c_void, bottom: *mut c_void) -> Stack {
debug_assert!(top >= bottom);
Stack {
top: top,
bottom: bottom,
}
}
/// Returns the top of the stack from which on it grows downwards towards bottom().
#[inline]
pub fn top(&self) -> *mut c_void {
self.top
}
/// Returns the bottom of the stack and thus it's end.
#[inline]
pub fn bottom(&self) -> *mut c_void {
self.bottom
}
/// Returns the size of the stack between top() and bottom().
#[inline]
pub fn len(&self) -> usize {
self.top as usize - self.bottom as usize
}
/// Returns the minimal stack size allowed by the current platform.
#[inline]
pub fn min_size() -> usize {
sys::min_stack_size()
}
/// Returns the maximum stack size allowed by the current platform.
#[inline]
pub fn max_size() -> usize {
sys::max_stack_size()
}
/// Returns a implementation defined default stack size.
///
/// This value can vary greatly between platforms, but is usually only a couple
/// memory pages in size and enough for most use-cases with little recursion.
/// It's usually a better idea to specifiy an explicit stack size instead.
#[inline]
pub fn default_size() -> usize {
sys::default_stack_size()
}
/// Allocates a new stack of `size`.
fn allocate(mut size: usize, protected: bool) -> Result<Stack, StackError> {
let page_size = sys::page_size();
let min_stack_size = sys::min_stack_size();
let max_stack_size = sys::max_stack_size();
let add_shift = if protected { 1 } else { 0 };
let add = page_size << add_shift;
if size < min_stack_size {
size = min_stack_size;
}
size = (size - 1) &!(page_size - 1);
if let Some(size) = size.checked_add(add) {
if size <= max_stack_size {
let mut ret = unsafe { sys::allocate_stack(size) };
if protected {
if let Ok(stack) = ret {
ret = unsafe { sys::protect_stack(&stack) };
}
}
return ret.map_err(StackError::IoError);
}
}
Err(StackError::ExceedsMaximumSize(max_stack_size - add))
}
}
unsafe impl Send for Stack {}
/// A very simple and straightforward implementation of `Stack`.
///
/// Allocates stack space using virtual memory, whose pages will
/// only be mapped to physical memory if they are used.
///
/// _As a general rule it is recommended to use `ProtectedFixedSizeStack` instead._
#[derive(Debug)]
pub struct FixedSizeStack(Stack);
impl FixedSizeStack {
/// Allocates a new stack of **at least** `size` bytes.
///
/// `size` is rounded up to a multiple of the size of a memory page.
pub fn new(size: usize) -> Result<FixedSizeStack, StackError> {
Stack::allocate(size, false).map(FixedSizeStack)
}
}
impl Deref for FixedSizeStack {
type Target = Stack;
fn deref(&self) -> &Stack {
&self.0
}
}
impl Default for FixedSizeStack {
fn default() -> FixedSizeStack {
FixedSizeStack::new(Stack::default_size())
.unwrap_or_else(|err| panic!("Failed to allocate FixedSizeStack with {:?}", err))
}
}
impl Drop for FixedSizeStack {
fn drop(&mut self) {
unsafe {
sys::deallocate_stack(self.0.bottom(), self.0.len());
}
}
}
/// A more secure, but slightly slower version of `FixedSizeStack`.
///
/// Allocates stack space using virtual memory, whose pages will
/// only be mapped to physical memory if they are used.
///
/// The additional guard page is made protected and inaccessible.
/// Now if a stack overflow occurs it should (hopefully) hit this guard page and
/// cause a segmentation fault instead letting the memory being overwritten silently.
///
/// _As a general rule it is recommended to use **this** struct to create stack memory._
#[derive(Debug)]
pub struct ProtectedFixedSizeStack(Stack);
impl ProtectedFixedSizeStack {
/// Allocates a new stack of **at least** `size` bytes + one additional guard page.
///
/// `size` is rounded up to a multiple of the size of a memory page and
/// does not include the size of the guard page itself.
pub fn new(size: usize) -> Result<ProtectedFixedSizeStack, StackError> {
Stack::allocate(size, true).map(ProtectedFixedSizeStack)
}
}
impl Deref for ProtectedFixedSizeStack {
type Target = Stack;
fn deref(&self) -> &Stack {
&self.0
}
}
impl Default for ProtectedFixedSizeStack {
fn default() -> ProtectedFixedSizeStack {
ProtectedFixedSizeStack::new(Stack::default_size()).unwrap_or_else(|err| {
panic!("Failed to allocate ProtectedFixedSizeStack with {:?}", err)
})
}
}
impl Drop for ProtectedFixedSizeStack {
fn drop(&mut self) {
let page_size = sys::page_size();
let guard = (self.0.bottom() as usize - page_size) as *mut c_void;
let size_with_guard = self.0.len() + page_size;
unsafe {
sys::deallocate_stack(guard, size_with_guard);
}
}
}
#[cfg(test)]
mod tests {
use std::ptr::write_bytes;
use super::*;
use sys;
#[test]
fn stack_size_too_small() {
let stack = FixedSizeStack::new(0).unwrap();
assert_eq!(stack.len(), sys::min_stack_size());
|
assert_eq!(stack.len(), sys::min_stack_size());
unsafe { write_bytes(stack.bottom() as *mut u8, 0x1d, stack.len()) };
}
#[test]
fn stack_size_too_large() {
let stack_size = sys::max_stack_size() &!(sys::page_size() - 1);
match FixedSizeStack::new(stack_size) {
Err(StackError::ExceedsMaximumSize(..)) => panic!(),
_ => {}
}
let stack_size = stack_size + 1;
match FixedSizeStack::new(stack_size) {
Err(StackError::ExceedsMaximumSize(..)) => {}
_ => panic!(),
}
}
}
|
unsafe { write_bytes(stack.bottom() as *mut u8, 0x1d, stack.len()) };
let stack = ProtectedFixedSizeStack::new(0).unwrap();
|
random_line_split
|
build.rs
|
//! This tiny build script ensures that rocket_codegen is not compiled with an
//! incompatible version of rust.
extern crate yansi;
extern crate version_check;
use yansi::Color::{Red, Yellow, Blue, White};
use version_check::{supports_features, is_min_version, is_min_date};
// Specifies the minimum nightly version needed to compile Rocket's codegen.
const MIN_DATE: &'static str = "2017-07-09";
const MIN_VERSION: &'static str = "1.20.0-nightly";
fn
|
() {
let ok_channel = supports_features();
let ok_version = is_min_version(MIN_VERSION);
let ok_date = is_min_date(MIN_DATE);
let print_version_err = |version: &str, date: &str| {
eprintln!("{} {}. {} {}.",
White.paint("Installed version is:"),
Yellow.paint(format!("{} ({})", version, date)),
White.paint("Minimum required:"),
Yellow.paint(format!("{} ({})", MIN_VERSION, MIN_DATE)));
};
match (ok_channel, ok_version, ok_date) {
(Some(ok_channel), Some((ok_version, version)), Some((ok_date, date))) => {
if!ok_channel {
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket requires a nightly or dev version of Rust."));
print_version_err(&*version, &*date);
eprintln!("{}{}{}",
Blue.paint("See the getting started guide ("),
White.paint("https://rocket.rs/guide/getting-started/"),
Blue.paint(") for more information."));
panic!("Aborting compilation due to incompatible compiler.")
}
if!ok_version ||!ok_date {
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket codegen requires a more recent version of rustc."));
eprintln!("{}{}{}",
Blue.paint("Use `"),
White.paint("rustup update"),
Blue.paint("` or your preferred method to update Rust."));
print_version_err(&*version, &*date);
panic!("Aborting compilation due to incompatible compiler.")
}
},
_ => {
println!("cargo:warning={}", "Rocket was unable to check rustc compatibility.");
println!("cargo:warning={}", "Build may fail due to incompatible rustc version.");
}
}
}
|
main
|
identifier_name
|
build.rs
|
//! This tiny build script ensures that rocket_codegen is not compiled with an
//! incompatible version of rust.
extern crate yansi;
extern crate version_check;
use yansi::Color::{Red, Yellow, Blue, White};
use version_check::{supports_features, is_min_version, is_min_date};
// Specifies the minimum nightly version needed to compile Rocket's codegen.
const MIN_DATE: &'static str = "2017-07-09";
const MIN_VERSION: &'static str = "1.20.0-nightly";
fn main() {
let ok_channel = supports_features();
let ok_version = is_min_version(MIN_VERSION);
let ok_date = is_min_date(MIN_DATE);
let print_version_err = |version: &str, date: &str| {
eprintln!("{} {}. {} {}.",
White.paint("Installed version is:"),
Yellow.paint(format!("{} ({})", version, date)),
White.paint("Minimum required:"),
|
if!ok_channel {
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket requires a nightly or dev version of Rust."));
print_version_err(&*version, &*date);
eprintln!("{}{}{}",
Blue.paint("See the getting started guide ("),
White.paint("https://rocket.rs/guide/getting-started/"),
Blue.paint(") for more information."));
panic!("Aborting compilation due to incompatible compiler.")
}
if!ok_version ||!ok_date {
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket codegen requires a more recent version of rustc."));
eprintln!("{}{}{}",
Blue.paint("Use `"),
White.paint("rustup update"),
Blue.paint("` or your preferred method to update Rust."));
print_version_err(&*version, &*date);
panic!("Aborting compilation due to incompatible compiler.")
}
},
_ => {
println!("cargo:warning={}", "Rocket was unable to check rustc compatibility.");
println!("cargo:warning={}", "Build may fail due to incompatible rustc version.");
}
}
}
|
Yellow.paint(format!("{} ({})", MIN_VERSION, MIN_DATE)));
};
match (ok_channel, ok_version, ok_date) {
(Some(ok_channel), Some((ok_version, version)), Some((ok_date, date))) => {
|
random_line_split
|
build.rs
|
//! This tiny build script ensures that rocket_codegen is not compiled with an
//! incompatible version of rust.
extern crate yansi;
extern crate version_check;
use yansi::Color::{Red, Yellow, Blue, White};
use version_check::{supports_features, is_min_version, is_min_date};
// Specifies the minimum nightly version needed to compile Rocket's codegen.
const MIN_DATE: &'static str = "2017-07-09";
const MIN_VERSION: &'static str = "1.20.0-nightly";
fn main() {
let ok_channel = supports_features();
let ok_version = is_min_version(MIN_VERSION);
let ok_date = is_min_date(MIN_DATE);
let print_version_err = |version: &str, date: &str| {
eprintln!("{} {}. {} {}.",
White.paint("Installed version is:"),
Yellow.paint(format!("{} ({})", version, date)),
White.paint("Minimum required:"),
Yellow.paint(format!("{} ({})", MIN_VERSION, MIN_DATE)));
};
match (ok_channel, ok_version, ok_date) {
(Some(ok_channel), Some((ok_version, version)), Some((ok_date, date))) => {
if!ok_channel {
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket requires a nightly or dev version of Rust."));
print_version_err(&*version, &*date);
eprintln!("{}{}{}",
Blue.paint("See the getting started guide ("),
White.paint("https://rocket.rs/guide/getting-started/"),
Blue.paint(") for more information."));
panic!("Aborting compilation due to incompatible compiler.")
}
if!ok_version ||!ok_date
|
},
_ => {
println!("cargo:warning={}", "Rocket was unable to check rustc compatibility.");
println!("cargo:warning={}", "Build may fail due to incompatible rustc version.");
}
}
}
|
{
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket codegen requires a more recent version of rustc."));
eprintln!("{}{}{}",
Blue.paint("Use `"),
White.paint("rustup update"),
Blue.paint("` or your preferred method to update Rust."));
print_version_err(&*version, &*date);
panic!("Aborting compilation due to incompatible compiler.")
}
|
conditional_block
|
build.rs
|
//! This tiny build script ensures that rocket_codegen is not compiled with an
//! incompatible version of rust.
extern crate yansi;
extern crate version_check;
use yansi::Color::{Red, Yellow, Blue, White};
use version_check::{supports_features, is_min_version, is_min_date};
// Specifies the minimum nightly version needed to compile Rocket's codegen.
const MIN_DATE: &'static str = "2017-07-09";
const MIN_VERSION: &'static str = "1.20.0-nightly";
fn main()
|
eprintln!("{}{}{}",
Blue.paint("See the getting started guide ("),
White.paint("https://rocket.rs/guide/getting-started/"),
Blue.paint(") for more information."));
panic!("Aborting compilation due to incompatible compiler.")
}
if!ok_version ||!ok_date {
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket codegen requires a more recent version of rustc."));
eprintln!("{}{}{}",
Blue.paint("Use `"),
White.paint("rustup update"),
Blue.paint("` or your preferred method to update Rust."));
print_version_err(&*version, &*date);
panic!("Aborting compilation due to incompatible compiler.")
}
},
_ => {
println!("cargo:warning={}", "Rocket was unable to check rustc compatibility.");
println!("cargo:warning={}", "Build may fail due to incompatible rustc version.");
}
}
}
|
{
let ok_channel = supports_features();
let ok_version = is_min_version(MIN_VERSION);
let ok_date = is_min_date(MIN_DATE);
let print_version_err = |version: &str, date: &str| {
eprintln!("{} {}. {} {}.",
White.paint("Installed version is:"),
Yellow.paint(format!("{} ({})", version, date)),
White.paint("Minimum required:"),
Yellow.paint(format!("{} ({})", MIN_VERSION, MIN_DATE)));
};
match (ok_channel, ok_version, ok_date) {
(Some(ok_channel), Some((ok_version, version)), Some((ok_date, date))) => {
if !ok_channel {
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket requires a nightly or dev version of Rust."));
print_version_err(&*version, &*date);
|
identifier_body
|
app_chooser.rs
|
// This file is part of rgtk.
//
// rgtk 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, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk 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 rgtk. If not, see <http://www.gnu.org/licenses/>.
use glib::translate::{FromGlibPtr};
use gtk::{self, ffi};
use gtk::cast::GTK_APP_CHOOSER;
pub trait AppChooserTrait: gtk::WidgetTrait {
fn get_app_info(&self) -> Option<gtk::AppInfo> {
let tmp_pointer = unsafe { ffi::gtk_app_chooser_get_app_info(GTK_APP_CHOOSER(self.unwrap_widget())) };
|
} else {
Some(gtk::FFIWidget::wrap_widget(tmp_pointer as *mut ffi::C_GtkWidget))
}
}
fn get_content_info(&self) -> Option<String> {
unsafe {
FromGlibPtr::borrow(
ffi::gtk_app_chooser_get_content_type(GTK_APP_CHOOSER(self.unwrap_widget())))
}
}
fn refresh(&self) -> () {
unsafe { ffi::gtk_app_chooser_refresh(GTK_APP_CHOOSER(self.unwrap_widget())) }
}
}
|
if tmp_pointer.is_null() {
None
|
random_line_split
|
app_chooser.rs
|
// This file is part of rgtk.
//
// rgtk 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, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk 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 rgtk. If not, see <http://www.gnu.org/licenses/>.
use glib::translate::{FromGlibPtr};
use gtk::{self, ffi};
use gtk::cast::GTK_APP_CHOOSER;
pub trait AppChooserTrait: gtk::WidgetTrait {
fn get_app_info(&self) -> Option<gtk::AppInfo>
|
fn get_content_info(&self) -> Option<String> {
unsafe {
FromGlibPtr::borrow(
ffi::gtk_app_chooser_get_content_type(GTK_APP_CHOOSER(self.unwrap_widget())))
}
}
fn refresh(&self) -> () {
unsafe { ffi::gtk_app_chooser_refresh(GTK_APP_CHOOSER(self.unwrap_widget())) }
}
}
|
{
let tmp_pointer = unsafe { ffi::gtk_app_chooser_get_app_info(GTK_APP_CHOOSER(self.unwrap_widget())) };
if tmp_pointer.is_null() {
None
} else {
Some(gtk::FFIWidget::wrap_widget(tmp_pointer as *mut ffi::C_GtkWidget))
}
}
|
identifier_body
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.