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 |
---|---|---|---|---|
test.rs | text
/* this is a
/* nested
block */ comment.
And should stay a comment
even with "strings"
or 42 0x18 0b01011 // blah
or u32 as i16 if impl */
text
/** this is a
/*! nested
block */ doc comment */
text
/// test
/// *test*
/// **test**
/// ***test***
/// _test_
/// __test__
/// __***test***__
/// ___test___
/// # test
/// ## test
/// ### test
/// #### test
/// ##### test
/// ###### test
/// ####### test
/// # test **test**
/// # test _test_
/// [text]()
/// [test](http://test.com)
/// [test](#test)
///
/// [test]
/// [test]: http://test.com
/// `test code`
/// ```rust
/// test code block
/// ```
/// test
///
///
/// # Test
///
/// ```
/// assert!(true);
/// ```
///
fn test(&self) {
asdf
// test
asdf
}
/**
* Deprecated
*/
/*!
* Deprecated
*/
text /**/ text
text /***/ text
text /****/ text
text
text // line comment
text /// line doc comment
text //! line doc comment
text
text #![main] text
text #![allow(great_algorithms)] text
text #![!resolve_unexported] text
text #[deny(silly_comments)] text
#[doc = "This attribute contains ] an attribute ending character"] | text r##"This is ##"# also valid."## text
text r#"This is #"## not valid."# text //"
text b"This is a bytestring" text
text br"And a raw byte string" text
text rb"Invalid raw byte string" text
text br##"This is ##"# also valid."## text
text r##"Raw strings can
span multiple lines"## text
text "double-quote string" text
text "string\nwith\x20escaped\"characters" text
text "string with // comment /* inside" text
text "strings can
span multiple lines" text
text 'c' text
text 'cc' text
text '\n' text
text '\nf' text
text '\n\n' text
text '\x20' text
text '\'' text
text '\\' text
text b'b' text
text b'bb' text
text b'\x20' text
text 42i32 text
text 42is text
text 42int text
text 42f32 text
text 42e+18 text
text 42.1415 text
text 42.1415f32 text
text 42.1415e18 text
text 42.1415e+18 text
text 42.1415e-18f64 text
text 42 text
text 0xf00b text
text 0o755 text
text 0b101010 text
text bool text char text usize text isize text
text u8 text u16 text u32 text u64 text
text i8 text i16 text i32 text i64 text
text Self text
text str text &str text String text &String text
text true text false text
text break text continue text do text else text
text if text in text for text loop text
text match text return text while text
text as text crate text extern text mod text
text let text proc text ref text
text
extern crate foo;
text
use std::slice;
text
use std::{num, str};
text
use self::foo::{bar, baz};
text
use super::foo::{bar, baz};
text
x = 1+1;
y = 4-2;
x *= 3;
y++;
y += 1;
text
pub enum MyEnum {
One,
Two
}
text
pub struct MyStruct<'foo> {
pub one: u32,
two: Option<'a, MyEnum>,
three: &'foo i32,
}
text
pub struct MyTupleStruct(pub i32, u32);
text
text
type MyType = u32;
text
text
static MY_CONSTANT: &str = "hello";
text
text
pub trait MyTrait {
text
fn create_something (param: &str, mut other_param: u32) -> Option<Self>;
text
fn do_whatever<T: Send+Share+Whatever, U: Freeze> (param: &T, other_param: u32) -> Option<U>;
text
fn do_all_the_work (&mut self, param: &str, mut other_param: u32) -> bool;
text
fn do_even_more<'a, T: Send+Whatever, U: Something<T>+Freeze> (&'a mut self, param: &T) -> &'a U;
text
}
text
text
impl<'foo> MyTrait for MyStruct<'foo> {
text
fn create_something (param: &str, mut other_param: u32) -> Option<Self> {
text
return Some(cake);
text
}
text
fn do_whatever<T: Send+Share+Whatever, U: Freeze> (param: &T, other_param: u32) -> Option<U> {
assert!(1!= 2);
text
self.with_something(param, |arg1, arg2| {
text
}, other_param);
}
text
fn do_all_the_work (&mut self, param: &str, mut other_param: u32) -> bool {
announce!("There's no cake");
if!test_subject.under_control() {
text
let list: Vec<item> = some_iterator.map(|elem| elem.dosomething()).collect();
text
let boxed_list = box list;
text
self.announce_warning();
text
if test_subject.ignored_warnings > 3 {
text
test_subject.incinerate();
text
}
text
}
text
}
text
fn do_even_more<'a, T: Send+Whatever+'static, U: Something<T>+Freeze> (&'a mut self, param: &T) -> &'a U {
text
let foo: Option<'a u32> = Some(18);
text
if self.one < 1 {
text
self.complain(&foo);
text
}
}
text
}
text
text
impl MyStruct<'foo> {
text
pub fn with_something<T: Send> (param: &T, f: |i32, &str| -> T, other_param: u32) -> T {
text
f(123, "hello")
text
}
text
}
text
// Loop expression labels (#2)
'infinity: loop {
do_serious_stuff();
use_a_letter('Z');
break 'infinity;
}
// isize/usize suffixes (#22)
let x = 123usize;
// Float literals without +- after E (#30)
let x = 1.2345e6;
// Nested generic (#33, #37)
let x: Vec<Vec<u8>> = Vec::new();
// Correct detection of == (#40)
struct Foo { x: i32 }
if x == 1 { }
// const function parameter (#52)
fn foo(bar: *const i32) {
let _ = 1234 as *const u32;
}
// Keywords and known types in wrapper structs (#56)
pub struct Foobar(pub Option<bool>);
pub struct Foobar(pub Test<W=bool>);
pub struct Foobar(pub Test<W==bool>);
pub struct Foobar(pub Test<W = bool>);
struct Test(i32);
struct Test(String);
struct Test(Vec<i32>);
struct Test(BTreeMap<String, i32>);
// Lifetimes in associated type definitions
trait Foo {
type B: A +'static;
}
// where clause
impl Foo<A, B> where text { }
text
impl Foo<A, B> for C where text { }
text
impl Foo<A, B> for C {
fn foo<A, B> -> C where text { }
}
text
fn foo<A, B> -> C where text { }
text
struct Foo<A, B> where text { }
text
trait Foo<A, B> : C where { }
text
fn do_work<T: Any + Debug>(value: &T) {}
impl Cookie {}
impl<T> PrintInOption for T where Option<T>: Debug {}
impl<K,V> HashMap<K, V> where K : Hash + Eq {}
impl<A, D> MyTrait<A, D> for YourType where A: TraitB + TraitC, D: TraitE + TraitF {}
impl Debug for a where asdf {}
impl<Flavor> Eat where Cookie<Flavor>: Oatmeal {}
// Unsafe in function arguments
unsafe fn foo();
fn foo(f: unsafe fn());
// Format macros
format!("text");
format!("text{}text", 1);
format!("text{0}text", 1);
format!("text{named}text", named=1);
format!("text{:?}text", to_debug);
format!("text{0:?}text", to_debug);
format!("text{named:?}text", named=to_debug);
format!("text{:<}text", 1);
format!("text{:.>}text", 1);
format!("text{:+}text", pos_or_neg);
format!("text{:+0}text", pos_or_neg);
format!("text{:+04}text", pos_or_neg);
format!("text{:6}", "text");
format!("text{:1$}", "text", 6);
format!("text{1:6$}", 6, "text");
format!("text{:w$}", "text", w=6);
format!("text{:8b}text", byte);
format!("text{:08b}text", byte);
format!("text{:#010b}text", byte);
format!("text{:2x}text", byte);
format!("text{:#4x}text", byte);
format!("text{:.2}text", 0.5);
format!("text{:0.2}text", 0.5);
format!("text{:06.2}text", 0.5);
format!("text{named:.prec$}text", prec=0.5, named=2.0);
format!("text{}text{2:.*}text", "text", 6, 0.5);
format!("text{named:-^+#06.2e}text", named=0.5);
format!("text{named:-^+#0width$.prec$e}text", named=0.5, width=6, prec=2);
format!("text{{escaped}}text\n{0}text", "only {text} first {{text}}");
not_format!("text{}text");
format_args!("{}", "text");
write!("{}", "text");
writeln!("{}", "text");
print!("{}", "text");
println!("{}", "text");
log!("{}", "text");
error!("{}", "text");
warn!("{}", "text");
info!("{}", "text");
debug!("{}", "text");
trace!("{}", "text");
eprint!("{}", "text");
eprintln!("{}", "text");
// Unused reserved words
abstract fn do_thing();
final let MAX = 10us;
let i = 0;
do {
yield do_thing(i++);
} while(i < MAX);
impl Float for f32 {
fn infinity() -> Self {
f32::INFINITY
}
}
#[derive(Default)]
enum State {
/// Currently open in a sane state
Open,
/// Waiting to send a GO_AWAY frame
GoAway(frame::GoAway)
/// Waiting to send a GO_AWAY_ frame
GoAway(frame::GoAway)
/// Waiting to send a GO*AWAY frame
GoAway(frame::GoAway)
/// Waiting to send a GO*AWAY* frame
GoAway(frame::GoAway)
/// Waiting to send a GO__AWAY frame
GoAway(frame::GoAway)
/// Waiting to send a GO__AWAY__ frame
GoAway(frame::GoAway)
/// Waiting to send a GO**AWAY frame
GoAway(frame::GoAway)
/// Waiting to send a GO**AWAY** frame
GoAway(frame::GoAway)
}
Box<dyn MyTrait>
&dyn Foo
&mut dyn Foo |
text r"This is a raw string" text
text r"This raw string ends in \" text
text r#"This is also valid"# text | random_line_split |
sync.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) Alexander Fomin <[email protected]>
// *
// * For the full copyright and license information, please view the LICENSE
// * file that was distributed with this source code.
/* Last synced with: sync (GNU coreutils) 8.13 */
extern crate libc;
use clap::{crate_version, App, AppSettings, Arg};
use std::path::Path;
use uucore::display::Quotable;
use uucore::error::{UResult, USimpleError};
use uucore::format_usage;
static ABOUT: &str = "Synchronize cached writes to persistent storage";
const USAGE: &str = "{} [OPTION]... FILE...";
pub mod options {
pub static FILE_SYSTEM: &str = "file-system";
pub static DATA: &str = "data";
}
static ARG_FILES: &str = "files";
#[cfg(unix)]
mod platform {
use super::libc;
#[cfg(target_os = "linux")]
use std::fs::File;
#[cfg(target_os = "linux")]
use std::os::unix::io::AsRawFd;
pub unsafe fn do_sync() -> isize {
libc::sync();
0
}
#[cfg(target_os = "linux")]
pub unsafe fn do_syncfs(files: Vec<String>) -> isize {
for path in files {
let f = File::open(&path).unwrap();
let fd = f.as_raw_fd();
libc::syscall(libc::SYS_syncfs, fd);
}
0
}
#[cfg(target_os = "linux")]
pub unsafe fn do_fdatasync(files: Vec<String>) -> isize {
for path in files {
let f = File::open(&path).unwrap();
let fd = f.as_raw_fd();
libc::syscall(libc::SYS_fdatasync, fd);
}
0
}
}
#[cfg(windows)]
mod platform {
extern crate winapi;
use self::winapi::shared::minwindef;
use self::winapi::shared::winerror;
use self::winapi::um::handleapi;
use self::winapi::um::winbase;
use self::winapi::um::winnt;
use std::fs::OpenOptions;
use std::mem;
use std::os::windows::prelude::*;
use std::path::Path;
use uucore::crash;
use uucore::wide::{FromWide, ToWide};
unsafe fn flush_volume(name: &str) {
let name_wide = name.to_wide_null();
if winapi::um::fileapi::GetDriveTypeW(name_wide.as_ptr()) == winbase::DRIVE_FIXED {
let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash
match OpenOptions::new().write(true).open(sliced_name) {
Ok(file) => {
if winapi::um::fileapi::FlushFileBuffers(file.as_raw_handle()) == 0 {
crash!(
winapi::um::errhandlingapi::GetLastError() as i32,
"failed to flush file buffer"
);
}
}
Err(e) => crash!(
e.raw_os_error().unwrap_or(1),
"failed to create volume handle"
),
}
}
}
unsafe fn find_first_volume() -> (String, winnt::HANDLE) {
#[allow(deprecated)]
let mut name: [winnt::WCHAR; minwindef::MAX_PATH] = mem::uninitialized();
let handle = winapi::um::fileapi::FindFirstVolumeW(
name.as_mut_ptr(),
name.len() as minwindef::DWORD,
);
if handle == handleapi::INVALID_HANDLE_VALUE {
crash!(
winapi::um::errhandlingapi::GetLastError() as i32,
"failed to find first volume"
);
}
(String::from_wide_null(&name), handle)
} | #[allow(deprecated)]
let mut name: [winnt::WCHAR; minwindef::MAX_PATH] = mem::uninitialized();
if winapi::um::fileapi::FindNextVolumeW(
next_volume_handle,
name.as_mut_ptr(),
name.len() as minwindef::DWORD,
) == 0
{
match winapi::um::errhandlingapi::GetLastError() {
winerror::ERROR_NO_MORE_FILES => {
winapi::um::fileapi::FindVolumeClose(next_volume_handle);
return volumes;
}
err => crash!(err as i32, "failed to find next volume"),
}
} else {
volumes.push(String::from_wide_null(&name));
}
}
}
pub unsafe fn do_sync() -> isize {
let volumes = find_all_volumes();
for vol in &volumes {
flush_volume(vol);
}
0
}
pub unsafe fn do_syncfs(files: Vec<String>) -> isize {
for path in files {
flush_volume(
Path::new(&path)
.components()
.next()
.unwrap()
.as_os_str()
.to_str()
.unwrap(),
);
}
0
}
}
#[uucore::main]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().get_matches_from(args);
let files: Vec<String> = matches
.values_of(ARG_FILES)
.map(|v| v.map(ToString::to_string).collect())
.unwrap_or_default();
for f in &files {
if!Path::new(&f).exists() {
return Err(USimpleError::new(
1,
format!("cannot stat {}: No such file or directory", f.quote()),
));
}
}
#[allow(clippy::if_same_then_else)]
if matches.is_present(options::FILE_SYSTEM) {
#[cfg(any(target_os = "linux", target_os = "windows"))]
syncfs(files);
} else if matches.is_present(options::DATA) {
#[cfg(target_os = "linux")]
fdatasync(files);
} else {
sync();
}
Ok(())
}
pub fn uu_app<'a>() -> App<'a> {
App::new(uucore::util_name())
.version(crate_version!())
.about(ABOUT)
.override_usage(format_usage(USAGE))
.setting(AppSettings::InferLongArgs)
.arg(
Arg::new(options::FILE_SYSTEM)
.short('f')
.long(options::FILE_SYSTEM)
.conflicts_with(options::DATA)
.help("sync the file systems that contain the files (Linux and Windows only)"),
)
.arg(
Arg::new(options::DATA)
.short('d')
.long(options::DATA)
.conflicts_with(options::FILE_SYSTEM)
.help("sync only file data, no unneeded metadata (Linux only)"),
)
.arg(
Arg::new(ARG_FILES)
.multiple_occurrences(true)
.takes_value(true),
)
}
fn sync() -> isize {
unsafe { platform::do_sync() }
}
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn syncfs(files: Vec<String>) -> isize {
unsafe { platform::do_syncfs(files) }
}
#[cfg(target_os = "linux")]
fn fdatasync(files: Vec<String>) -> isize {
unsafe { platform::do_fdatasync(files) }
} |
unsafe fn find_all_volumes() -> Vec<String> {
let (first_volume, next_volume_handle) = find_first_volume();
let mut volumes = vec![first_volume];
loop { | random_line_split |
sync.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) Alexander Fomin <[email protected]>
// *
// * For the full copyright and license information, please view the LICENSE
// * file that was distributed with this source code.
/* Last synced with: sync (GNU coreutils) 8.13 */
extern crate libc;
use clap::{crate_version, App, AppSettings, Arg};
use std::path::Path;
use uucore::display::Quotable;
use uucore::error::{UResult, USimpleError};
use uucore::format_usage;
static ABOUT: &str = "Synchronize cached writes to persistent storage";
const USAGE: &str = "{} [OPTION]... FILE...";
pub mod options {
pub static FILE_SYSTEM: &str = "file-system";
pub static DATA: &str = "data";
}
static ARG_FILES: &str = "files";
#[cfg(unix)]
mod platform {
use super::libc;
#[cfg(target_os = "linux")]
use std::fs::File;
#[cfg(target_os = "linux")]
use std::os::unix::io::AsRawFd;
pub unsafe fn do_sync() -> isize {
libc::sync();
0
}
#[cfg(target_os = "linux")]
pub unsafe fn do_syncfs(files: Vec<String>) -> isize {
for path in files {
let f = File::open(&path).unwrap();
let fd = f.as_raw_fd();
libc::syscall(libc::SYS_syncfs, fd);
}
0
}
#[cfg(target_os = "linux")]
pub unsafe fn do_fdatasync(files: Vec<String>) -> isize {
for path in files {
let f = File::open(&path).unwrap();
let fd = f.as_raw_fd();
libc::syscall(libc::SYS_fdatasync, fd);
}
0
}
}
#[cfg(windows)]
mod platform {
extern crate winapi;
use self::winapi::shared::minwindef;
use self::winapi::shared::winerror;
use self::winapi::um::handleapi;
use self::winapi::um::winbase;
use self::winapi::um::winnt;
use std::fs::OpenOptions;
use std::mem;
use std::os::windows::prelude::*;
use std::path::Path;
use uucore::crash;
use uucore::wide::{FromWide, ToWide};
unsafe fn flush_volume(name: &str) {
let name_wide = name.to_wide_null();
if winapi::um::fileapi::GetDriveTypeW(name_wide.as_ptr()) == winbase::DRIVE_FIXED {
let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash
match OpenOptions::new().write(true).open(sliced_name) {
Ok(file) => {
if winapi::um::fileapi::FlushFileBuffers(file.as_raw_handle()) == 0 {
crash!(
winapi::um::errhandlingapi::GetLastError() as i32,
"failed to flush file buffer"
);
}
}
Err(e) => crash!(
e.raw_os_error().unwrap_or(1),
"failed to create volume handle"
),
}
}
}
unsafe fn find_first_volume() -> (String, winnt::HANDLE) {
#[allow(deprecated)]
let mut name: [winnt::WCHAR; minwindef::MAX_PATH] = mem::uninitialized();
let handle = winapi::um::fileapi::FindFirstVolumeW(
name.as_mut_ptr(),
name.len() as minwindef::DWORD,
);
if handle == handleapi::INVALID_HANDLE_VALUE {
crash!(
winapi::um::errhandlingapi::GetLastError() as i32,
"failed to find first volume"
);
}
(String::from_wide_null(&name), handle)
}
unsafe fn find_all_volumes() -> Vec<String> {
let (first_volume, next_volume_handle) = find_first_volume();
let mut volumes = vec![first_volume];
loop {
#[allow(deprecated)]
let mut name: [winnt::WCHAR; minwindef::MAX_PATH] = mem::uninitialized();
if winapi::um::fileapi::FindNextVolumeW(
next_volume_handle,
name.as_mut_ptr(),
name.len() as minwindef::DWORD,
) == 0
{
match winapi::um::errhandlingapi::GetLastError() {
winerror::ERROR_NO_MORE_FILES => {
winapi::um::fileapi::FindVolumeClose(next_volume_handle);
return volumes;
}
err => crash!(err as i32, "failed to find next volume"),
}
} else {
volumes.push(String::from_wide_null(&name));
}
}
}
pub unsafe fn do_sync() -> isize |
pub unsafe fn do_syncfs(files: Vec<String>) -> isize {
for path in files {
flush_volume(
Path::new(&path)
.components()
.next()
.unwrap()
.as_os_str()
.to_str()
.unwrap(),
);
}
0
}
}
#[uucore::main]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().get_matches_from(args);
let files: Vec<String> = matches
.values_of(ARG_FILES)
.map(|v| v.map(ToString::to_string).collect())
.unwrap_or_default();
for f in &files {
if!Path::new(&f).exists() {
return Err(USimpleError::new(
1,
format!("cannot stat {}: No such file or directory", f.quote()),
));
}
}
#[allow(clippy::if_same_then_else)]
if matches.is_present(options::FILE_SYSTEM) {
#[cfg(any(target_os = "linux", target_os = "windows"))]
syncfs(files);
} else if matches.is_present(options::DATA) {
#[cfg(target_os = "linux")]
fdatasync(files);
} else {
sync();
}
Ok(())
}
pub fn uu_app<'a>() -> App<'a> {
App::new(uucore::util_name())
.version(crate_version!())
.about(ABOUT)
.override_usage(format_usage(USAGE))
.setting(AppSettings::InferLongArgs)
.arg(
Arg::new(options::FILE_SYSTEM)
.short('f')
.long(options::FILE_SYSTEM)
.conflicts_with(options::DATA)
.help("sync the file systems that contain the files (Linux and Windows only)"),
)
.arg(
Arg::new(options::DATA)
.short('d')
.long(options::DATA)
.conflicts_with(options::FILE_SYSTEM)
.help("sync only file data, no unneeded metadata (Linux only)"),
)
.arg(
Arg::new(ARG_FILES)
.multiple_occurrences(true)
.takes_value(true),
)
}
fn sync() -> isize {
unsafe { platform::do_sync() }
}
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn syncfs(files: Vec<String>) -> isize {
unsafe { platform::do_syncfs(files) }
}
#[cfg(target_os = "linux")]
fn fdatasync(files: Vec<String>) -> isize {
unsafe { platform::do_fdatasync(files) }
}
| {
let volumes = find_all_volumes();
for vol in &volumes {
flush_volume(vol);
}
0
} | identifier_body |
sync.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) Alexander Fomin <[email protected]>
// *
// * For the full copyright and license information, please view the LICENSE
// * file that was distributed with this source code.
/* Last synced with: sync (GNU coreutils) 8.13 */
extern crate libc;
use clap::{crate_version, App, AppSettings, Arg};
use std::path::Path;
use uucore::display::Quotable;
use uucore::error::{UResult, USimpleError};
use uucore::format_usage;
static ABOUT: &str = "Synchronize cached writes to persistent storage";
const USAGE: &str = "{} [OPTION]... FILE...";
pub mod options {
pub static FILE_SYSTEM: &str = "file-system";
pub static DATA: &str = "data";
}
static ARG_FILES: &str = "files";
#[cfg(unix)]
mod platform {
use super::libc;
#[cfg(target_os = "linux")]
use std::fs::File;
#[cfg(target_os = "linux")]
use std::os::unix::io::AsRawFd;
pub unsafe fn do_sync() -> isize {
libc::sync();
0
}
#[cfg(target_os = "linux")]
pub unsafe fn do_syncfs(files: Vec<String>) -> isize {
for path in files {
let f = File::open(&path).unwrap();
let fd = f.as_raw_fd();
libc::syscall(libc::SYS_syncfs, fd);
}
0
}
#[cfg(target_os = "linux")]
pub unsafe fn do_fdatasync(files: Vec<String>) -> isize {
for path in files {
let f = File::open(&path).unwrap();
let fd = f.as_raw_fd();
libc::syscall(libc::SYS_fdatasync, fd);
}
0
}
}
#[cfg(windows)]
mod platform {
extern crate winapi;
use self::winapi::shared::minwindef;
use self::winapi::shared::winerror;
use self::winapi::um::handleapi;
use self::winapi::um::winbase;
use self::winapi::um::winnt;
use std::fs::OpenOptions;
use std::mem;
use std::os::windows::prelude::*;
use std::path::Path;
use uucore::crash;
use uucore::wide::{FromWide, ToWide};
unsafe fn | (name: &str) {
let name_wide = name.to_wide_null();
if winapi::um::fileapi::GetDriveTypeW(name_wide.as_ptr()) == winbase::DRIVE_FIXED {
let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash
match OpenOptions::new().write(true).open(sliced_name) {
Ok(file) => {
if winapi::um::fileapi::FlushFileBuffers(file.as_raw_handle()) == 0 {
crash!(
winapi::um::errhandlingapi::GetLastError() as i32,
"failed to flush file buffer"
);
}
}
Err(e) => crash!(
e.raw_os_error().unwrap_or(1),
"failed to create volume handle"
),
}
}
}
unsafe fn find_first_volume() -> (String, winnt::HANDLE) {
#[allow(deprecated)]
let mut name: [winnt::WCHAR; minwindef::MAX_PATH] = mem::uninitialized();
let handle = winapi::um::fileapi::FindFirstVolumeW(
name.as_mut_ptr(),
name.len() as minwindef::DWORD,
);
if handle == handleapi::INVALID_HANDLE_VALUE {
crash!(
winapi::um::errhandlingapi::GetLastError() as i32,
"failed to find first volume"
);
}
(String::from_wide_null(&name), handle)
}
unsafe fn find_all_volumes() -> Vec<String> {
let (first_volume, next_volume_handle) = find_first_volume();
let mut volumes = vec![first_volume];
loop {
#[allow(deprecated)]
let mut name: [winnt::WCHAR; minwindef::MAX_PATH] = mem::uninitialized();
if winapi::um::fileapi::FindNextVolumeW(
next_volume_handle,
name.as_mut_ptr(),
name.len() as minwindef::DWORD,
) == 0
{
match winapi::um::errhandlingapi::GetLastError() {
winerror::ERROR_NO_MORE_FILES => {
winapi::um::fileapi::FindVolumeClose(next_volume_handle);
return volumes;
}
err => crash!(err as i32, "failed to find next volume"),
}
} else {
volumes.push(String::from_wide_null(&name));
}
}
}
pub unsafe fn do_sync() -> isize {
let volumes = find_all_volumes();
for vol in &volumes {
flush_volume(vol);
}
0
}
pub unsafe fn do_syncfs(files: Vec<String>) -> isize {
for path in files {
flush_volume(
Path::new(&path)
.components()
.next()
.unwrap()
.as_os_str()
.to_str()
.unwrap(),
);
}
0
}
}
#[uucore::main]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().get_matches_from(args);
let files: Vec<String> = matches
.values_of(ARG_FILES)
.map(|v| v.map(ToString::to_string).collect())
.unwrap_or_default();
for f in &files {
if!Path::new(&f).exists() {
return Err(USimpleError::new(
1,
format!("cannot stat {}: No such file or directory", f.quote()),
));
}
}
#[allow(clippy::if_same_then_else)]
if matches.is_present(options::FILE_SYSTEM) {
#[cfg(any(target_os = "linux", target_os = "windows"))]
syncfs(files);
} else if matches.is_present(options::DATA) {
#[cfg(target_os = "linux")]
fdatasync(files);
} else {
sync();
}
Ok(())
}
pub fn uu_app<'a>() -> App<'a> {
App::new(uucore::util_name())
.version(crate_version!())
.about(ABOUT)
.override_usage(format_usage(USAGE))
.setting(AppSettings::InferLongArgs)
.arg(
Arg::new(options::FILE_SYSTEM)
.short('f')
.long(options::FILE_SYSTEM)
.conflicts_with(options::DATA)
.help("sync the file systems that contain the files (Linux and Windows only)"),
)
.arg(
Arg::new(options::DATA)
.short('d')
.long(options::DATA)
.conflicts_with(options::FILE_SYSTEM)
.help("sync only file data, no unneeded metadata (Linux only)"),
)
.arg(
Arg::new(ARG_FILES)
.multiple_occurrences(true)
.takes_value(true),
)
}
fn sync() -> isize {
unsafe { platform::do_sync() }
}
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn syncfs(files: Vec<String>) -> isize {
unsafe { platform::do_syncfs(files) }
}
#[cfg(target_os = "linux")]
fn fdatasync(files: Vec<String>) -> isize {
unsafe { platform::do_fdatasync(files) }
}
| flush_volume | identifier_name |
types.rs | extern crate serde_json;
extern crate rmp_serde;
use std::cmp::Eq;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use super::zmq;
use errors::common::CommonError;
use services::ledger::merkletree::merkletree::MerkleTree;
use utils::json::{JsonDecodable, JsonEncodable};
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct NodeData {
pub alias: String,
pub client_ip: String,
pub client_port: u32,
pub node_ip: String,
pub node_port: u32,
pub services: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct GenTransaction {
pub data: NodeData,
pub dest: String,
pub identifier: String,
#[serde(rename = "txnId")]
pub txn_id: Option<String>,
#[serde(rename = "type")]
pub txn_type: String,
}
impl JsonEncodable for GenTransaction {}
impl<'a> JsonDecodable<'a> for GenTransaction {}
impl GenTransaction {
pub fn to_msg_pack(&self) -> Result<Vec<u8>, rmp_serde::encode::Error> {
rmp_serde::to_vec_named(self)
}
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug)]
pub struct LedgerStatus {
pub txnSeqNo: usize,
pub merkleRoot: String,
pub ledgerId: u8,
pub ppSeqNo: Option<String>,
pub viewNo: Option<String>,
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug)]
pub struct ConsistencyProof {
//TODO almost all fields Option<> or find better approach
pub seqNoEnd: usize,
pub seqNoStart: usize,
pub ledgerId: usize,
pub hashes: Vec<String>,
pub oldMerkleRoot: String,
pub newMerkleRoot: String,
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct CatchupReq {
pub ledgerId: usize,
pub seqNoStart: usize,
pub seqNoEnd: usize,
pub catchupTill: usize,
}
impl<'a> JsonDecodable<'a> for CatchupReq {}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct CatchupRep {
pub ledgerId: usize,
pub consProof: Vec<String>,
pub txns: HashMap<String, serde_json::Value>,
}
impl CatchupRep {
pub fn min_tx(&self) -> Result<usize, CommonError> {
let mut min = None;
for (k, _) in self.txns.iter() {
let val = k.parse::<usize>()
.map_err(|err| CommonError::InvalidStructure(format!("{:?}", err)))?;
match min {
None => min = Some(val),
Some(m) => if val < m { min = Some(val) }
}
}
min.ok_or(CommonError::InvalidStructure(format!("Empty Map")))
}
}
| #[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Response {
pub req_id: u64,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct PoolLedgerTxns {
pub txn: Response,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SimpleRequest {
pub req_id: u64,
}
impl JsonEncodable for SimpleRequest {}
impl<'a> JsonDecodable<'a> for SimpleRequest {}
#[serde(tag = "op")]
#[derive(Serialize, Deserialize, Debug)]
pub enum Message {
#[serde(rename = "CONSISTENCY_PROOF")]
ConsistencyProof(ConsistencyProof),
#[serde(rename = "LEDGER_STATUS")]
LedgerStatus(LedgerStatus),
#[serde(rename = "CATCHUP_REQ")]
CatchupReq(CatchupReq),
#[serde(rename = "CATCHUP_REP")]
CatchupRep(CatchupRep),
#[serde(rename = "REQACK")]
ReqACK(Response),
#[serde(rename = "REQNACK")]
ReqNACK(Response),
#[serde(rename = "REPLY")]
Reply(Reply),
#[serde(rename = "REJECT")]
Reject(Response),
#[serde(rename = "POOL_LEDGER_TXNS")]
PoolLedgerTxns(PoolLedgerTxns),
Ping,
Pong,
}
impl Message {
pub fn from_raw_str(str: &str) -> Result<Message, serde_json::Error> {
match str {
"po" => Ok(Message::Pong),
"pi" => Ok(Message::Ping),
_ => Message::from_json(str),
}
}
}
impl JsonEncodable for Message {}
impl<'a> JsonDecodable<'a> for Message {}
#[derive(Serialize, Deserialize)]
pub struct PoolConfig {
pub genesis_txn: String
}
impl JsonEncodable for PoolConfig {}
impl<'a> JsonDecodable<'a> for PoolConfig {}
impl PoolConfig {
pub fn default_for_name(name: &str) -> PoolConfig {
let mut txn = name.to_string();
txn += ".txn";
PoolConfig { genesis_txn: txn }
}
}
pub struct RemoteNode {
pub name: String,
pub public_key: Vec<u8>,
pub zaddr: String,
pub zsock: Option<zmq::Socket>,
pub is_blacklisted: bool,
}
pub struct CatchUpProcess {
pub merkle_tree: MerkleTree,
pub pending_reps: Vec<(CatchupRep, usize)>,
}
pub trait MinValue {
fn get_min_index(&self) -> Result<usize, CommonError>;
}
impl MinValue for Vec<(CatchupRep, usize)> {
fn get_min_index(&self) -> Result<usize, CommonError> {
let mut res = None;
for (index, &(ref catchup_rep, _)) in self.iter().enumerate() {
match res {
None => { res = Some((catchup_rep, index)); }
Some((min_rep, i)) => if catchup_rep.min_tx()? < min_rep.min_tx()? {
res = Some((catchup_rep, index));
}
}
}
Ok(res.ok_or(CommonError::InvalidStructure("Element not Found".to_string()))?.1)
}
}
#[derive(Debug)]
pub struct HashableValue {
pub inner: serde_json::Value
}
impl Eq for HashableValue {}
impl Hash for HashableValue {
fn hash<H: Hasher>(&self, state: &mut H) {
serde_json::to_string(&self.inner).unwrap().hash(state); //TODO
}
}
impl PartialEq for HashableValue {
fn eq(&self, other: &HashableValue) -> bool {
self.inner.eq(&other.inner)
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct CommandProcess {
pub nack_cnt: usize,
pub replies: HashMap<HashableValue, usize>,
pub cmd_ids: Vec<i32>,
}
#[derive(Debug, PartialEq, Eq)]
pub enum ZMQLoopAction {
RequestToSend(RequestToSend),
MessageToProcess(MessageToProcess),
Terminate(i32),
Refresh(i32),
}
#[derive(Debug, PartialEq, Eq)]
pub struct RequestToSend {
pub request: String,
pub id: i32,
}
#[derive(Debug, PartialEq, Eq)]
pub struct MessageToProcess {
pub message: String,
pub node_idx: usize,
} | #[derive(Serialize, Deserialize, Debug)]
pub struct Reply {
pub result: Response,
}
| random_line_split |
types.rs | extern crate serde_json;
extern crate rmp_serde;
use std::cmp::Eq;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use super::zmq;
use errors::common::CommonError;
use services::ledger::merkletree::merkletree::MerkleTree;
use utils::json::{JsonDecodable, JsonEncodable};
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct NodeData {
pub alias: String,
pub client_ip: String,
pub client_port: u32,
pub node_ip: String,
pub node_port: u32,
pub services: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct GenTransaction {
pub data: NodeData,
pub dest: String,
pub identifier: String,
#[serde(rename = "txnId")]
pub txn_id: Option<String>,
#[serde(rename = "type")]
pub txn_type: String,
}
impl JsonEncodable for GenTransaction {}
impl<'a> JsonDecodable<'a> for GenTransaction {}
impl GenTransaction {
pub fn to_msg_pack(&self) -> Result<Vec<u8>, rmp_serde::encode::Error> {
rmp_serde::to_vec_named(self)
}
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug)]
pub struct LedgerStatus {
pub txnSeqNo: usize,
pub merkleRoot: String,
pub ledgerId: u8,
pub ppSeqNo: Option<String>,
pub viewNo: Option<String>,
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug)]
pub struct ConsistencyProof {
//TODO almost all fields Option<> or find better approach
pub seqNoEnd: usize,
pub seqNoStart: usize,
pub ledgerId: usize,
pub hashes: Vec<String>,
pub oldMerkleRoot: String,
pub newMerkleRoot: String,
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct CatchupReq {
pub ledgerId: usize,
pub seqNoStart: usize,
pub seqNoEnd: usize,
pub catchupTill: usize,
}
impl<'a> JsonDecodable<'a> for CatchupReq {}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct CatchupRep {
pub ledgerId: usize,
pub consProof: Vec<String>,
pub txns: HashMap<String, serde_json::Value>,
}
impl CatchupRep {
pub fn min_tx(&self) -> Result<usize, CommonError> {
let mut min = None;
for (k, _) in self.txns.iter() {
let val = k.parse::<usize>()
.map_err(|err| CommonError::InvalidStructure(format!("{:?}", err)))?;
match min {
None => min = Some(val),
Some(m) => if val < m { min = Some(val) }
}
}
min.ok_or(CommonError::InvalidStructure(format!("Empty Map")))
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Reply {
pub result: Response,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Response {
pub req_id: u64,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct PoolLedgerTxns {
pub txn: Response,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SimpleRequest {
pub req_id: u64,
}
impl JsonEncodable for SimpleRequest {}
impl<'a> JsonDecodable<'a> for SimpleRequest {}
#[serde(tag = "op")]
#[derive(Serialize, Deserialize, Debug)]
pub enum Message {
#[serde(rename = "CONSISTENCY_PROOF")]
ConsistencyProof(ConsistencyProof),
#[serde(rename = "LEDGER_STATUS")]
LedgerStatus(LedgerStatus),
#[serde(rename = "CATCHUP_REQ")]
CatchupReq(CatchupReq),
#[serde(rename = "CATCHUP_REP")]
CatchupRep(CatchupRep),
#[serde(rename = "REQACK")]
ReqACK(Response),
#[serde(rename = "REQNACK")]
ReqNACK(Response),
#[serde(rename = "REPLY")]
Reply(Reply),
#[serde(rename = "REJECT")]
Reject(Response),
#[serde(rename = "POOL_LEDGER_TXNS")]
PoolLedgerTxns(PoolLedgerTxns),
Ping,
Pong,
}
impl Message {
pub fn | (str: &str) -> Result<Message, serde_json::Error> {
match str {
"po" => Ok(Message::Pong),
"pi" => Ok(Message::Ping),
_ => Message::from_json(str),
}
}
}
impl JsonEncodable for Message {}
impl<'a> JsonDecodable<'a> for Message {}
#[derive(Serialize, Deserialize)]
pub struct PoolConfig {
pub genesis_txn: String
}
impl JsonEncodable for PoolConfig {}
impl<'a> JsonDecodable<'a> for PoolConfig {}
impl PoolConfig {
pub fn default_for_name(name: &str) -> PoolConfig {
let mut txn = name.to_string();
txn += ".txn";
PoolConfig { genesis_txn: txn }
}
}
pub struct RemoteNode {
pub name: String,
pub public_key: Vec<u8>,
pub zaddr: String,
pub zsock: Option<zmq::Socket>,
pub is_blacklisted: bool,
}
pub struct CatchUpProcess {
pub merkle_tree: MerkleTree,
pub pending_reps: Vec<(CatchupRep, usize)>,
}
pub trait MinValue {
fn get_min_index(&self) -> Result<usize, CommonError>;
}
impl MinValue for Vec<(CatchupRep, usize)> {
fn get_min_index(&self) -> Result<usize, CommonError> {
let mut res = None;
for (index, &(ref catchup_rep, _)) in self.iter().enumerate() {
match res {
None => { res = Some((catchup_rep, index)); }
Some((min_rep, i)) => if catchup_rep.min_tx()? < min_rep.min_tx()? {
res = Some((catchup_rep, index));
}
}
}
Ok(res.ok_or(CommonError::InvalidStructure("Element not Found".to_string()))?.1)
}
}
#[derive(Debug)]
pub struct HashableValue {
pub inner: serde_json::Value
}
impl Eq for HashableValue {}
impl Hash for HashableValue {
fn hash<H: Hasher>(&self, state: &mut H) {
serde_json::to_string(&self.inner).unwrap().hash(state); //TODO
}
}
impl PartialEq for HashableValue {
fn eq(&self, other: &HashableValue) -> bool {
self.inner.eq(&other.inner)
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct CommandProcess {
pub nack_cnt: usize,
pub replies: HashMap<HashableValue, usize>,
pub cmd_ids: Vec<i32>,
}
#[derive(Debug, PartialEq, Eq)]
pub enum ZMQLoopAction {
RequestToSend(RequestToSend),
MessageToProcess(MessageToProcess),
Terminate(i32),
Refresh(i32),
}
#[derive(Debug, PartialEq, Eq)]
pub struct RequestToSend {
pub request: String,
pub id: i32,
}
#[derive(Debug, PartialEq, Eq)]
pub struct MessageToProcess {
pub message: String,
pub node_idx: usize,
} | from_raw_str | identifier_name |
empty.rs | use crate::Stream;
use core::marker::PhantomData;
use core::pin::Pin;
use core::task::{Context, Poll};
/// Stream for the [`empty`](fn@empty) function.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Empty<T>(PhantomData<T>);
impl<T> Unpin for Empty<T> {}
unsafe impl<T> Send for Empty<T> {}
unsafe impl<T> Sync for Empty<T> {}
/// Creates a stream that yields nothing.
///
/// The returned stream is immediately ready and returns `None`. Use
/// [`stream::pending()`](super::pending()) to obtain a stream that is never
/// ready.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use tokio_stream::{self as stream, StreamExt};
///
/// #[tokio::main]
/// async fn main() {
/// let mut none = stream::empty::<i32>();
///
/// assert_eq!(None, none.next().await);
/// }
/// ``` | }
impl<T> Stream for Empty<T> {
type Item = T;
fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<T>> {
Poll::Ready(None)
}
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(0))
}
} | pub const fn empty<T>() -> Empty<T> {
Empty(PhantomData) | random_line_split |
empty.rs | use crate::Stream;
use core::marker::PhantomData;
use core::pin::Pin;
use core::task::{Context, Poll};
/// Stream for the [`empty`](fn@empty) function.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Empty<T>(PhantomData<T>);
impl<T> Unpin for Empty<T> {}
unsafe impl<T> Send for Empty<T> {}
unsafe impl<T> Sync for Empty<T> {}
/// Creates a stream that yields nothing.
///
/// The returned stream is immediately ready and returns `None`. Use
/// [`stream::pending()`](super::pending()) to obtain a stream that is never
/// ready.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use tokio_stream::{self as stream, StreamExt};
///
/// #[tokio::main]
/// async fn main() {
/// let mut none = stream::empty::<i32>();
///
/// assert_eq!(None, none.next().await);
/// }
/// ```
pub const fn empty<T>() -> Empty<T> {
Empty(PhantomData)
}
impl<T> Stream for Empty<T> {
type Item = T;
fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<T>> {
Poll::Ready(None)
}
fn | (&self) -> (usize, Option<usize>) {
(0, Some(0))
}
}
| size_hint | identifier_name |
mod.rs | //! Platform-specific extensions to `std` for Windows.
//!
//! Provides access to platform-level information for Windows, and exposes
//! Windows-specific idioms that would otherwise be inappropriate as part
//! the core `std` library. These extensions allow developers to use
//! `std` types and idioms with Windows in a way that the normal
//! platform-agnostic idioms would not normally support.
#![stable(feature = "rust1", since = "1.0.0")]
#![doc(cfg(windows))]
pub mod ffi;
pub mod fs;
pub mod io;
pub mod process;
pub mod raw;
pub mod thread;
/// A prelude for conveniently writing platform-specific code.
///
/// Includes all extension traits, and some important type definitions.
#[stable(feature = "rust1", since = "1.0.0")] | #[doc(no_inline)]
#[stable(feature = "file_offset", since = "1.15.0")]
pub use super::fs::FileExt;
#[doc(no_inline)]
#[stable(feature = "rust1", since = "1.0.0")]
pub use super::fs::{MetadataExt, OpenOptionsExt};
#[doc(no_inline)]
#[stable(feature = "rust1", since = "1.0.0")]
pub use super::io::{
AsHandle, AsSocket, BorrowedHandle, BorrowedSocket, FromRawHandle, FromRawSocket,
HandleOrInvalid, IntoRawHandle, IntoRawSocket, OwnedHandle, OwnedSocket,
};
#[doc(no_inline)]
#[stable(feature = "rust1", since = "1.0.0")]
pub use super::io::{AsRawHandle, AsRawSocket, RawHandle, RawSocket};
} | pub mod prelude {
#[doc(no_inline)]
#[stable(feature = "rust1", since = "1.0.0")]
pub use super::ffi::{OsStrExt, OsStringExt}; | random_line_split |
main.rs | extern crate itertools;
extern crate clap;
extern crate rand;
use itertools::Itertools;
use clap::{App, Arg};
use std::fs::File;
use rand::Rng;
use std::io::{Read, Write};
const DEFAULT_CROSSOVER_POINTS: usize = 3;
const DEFAULT_MUTATION_RATE: f64 = 0.001;
const DEFAULT_UNIT: usize = 1;
const DEFAULT_STRIDE: usize = 1;
fn main() {
let matches = App::new("matef")
.version("1.0")
.author("Geordon Worley <[email protected]>")
.about("Mates two files")
.arg(Arg::with_name("output")
.help("The output location")
.required(true)
.index(1))
.arg(Arg::with_name("file1")
.help("Input file 1")
.required(true)
.index(2))
.arg(Arg::with_name("file2")
.help("Input file 2")
.required(true)
.index(3))
.arg(Arg::with_name("mutation-rate")
.short("m")
.multiple(false)
.long("mutation-rate")
.value_name("RATE")
.help("Takes a RATE of mutation that randomizes UNIT bytes at a time")
.takes_value(true))
.arg(Arg::with_name("crossover-points")
.short("c")
.multiple(false)
.long("crossover-points")
.value_name("NUMBER")
.help("Takes a NUMBER of crossover points of 1 or greater")
.takes_value(true))
.arg(Arg::with_name("unit")
.short("u")
.multiple(false)
.long("unit")
.value_name("BYTES")
.help("Takes an amount of BYTES that are always mutated as a group")
.takes_value(true))
.arg(Arg::with_name("stride")
.short("s")
.multiple(false)
.long("stride")
.value_name("BYTES")
.help("Takes an amount of BYTES that define the alignment of mutated units")
.takes_value(true))
.get_matches();
let crossover_points = match matches.value_of("crossover-points") {
Some(c) => {
match c.parse::<usize>() {
Ok(0) => {
println!("Error: Cannot accept 0 crossover-points.");
return;
},
Ok(n) => n,
Err(e) => {
println!("Error: Failed to parse crossover-points: {}", e);
return;
},
}
},
None => DEFAULT_CROSSOVER_POINTS,
};
let mutation_rate = match matches.value_of("mutation-rate") {
Some(c) => {
match c.parse::<f64>() {
Ok(n) => n,
Err(e) => {
println!("Error: Failed to parse mutation-rate: {}", e);
return;
},
}
},
None => DEFAULT_MUTATION_RATE,
};
let mutation_size = match matches.value_of("unit") {
Some(c) => {
match c.parse::<usize>() {
Ok(0) => {
println!("Error: Cannot accept 0 bytes as the unit.");
return;
},
Ok(n) => n,
Err(e) => {
println!("Error: Failed to parse unit: {}", e);
return;
},
}
},
None => DEFAULT_UNIT,
};
let stride = match matches.value_of("stride") {
Some(c) => {
match c.parse::<usize>() {
Ok(0) => {
println!("Error: Cannot accept 0 bytes as the stride.");
return;
},
Ok(n) => n,
Err(e) => {
println!("Error: Failed to parse stride: {}", e);
return;
},
}
},
None => DEFAULT_STRIDE,
};
let output = matches.value_of("output").unwrap();
let filenames = (matches.value_of("file1").unwrap(), matches.value_of("file2").unwrap());
let files = (
match File::open(filenames.0) {
Ok(mut f) => {
let mut v = Vec::new();
match f.read_to_end(&mut v) {
Ok(_) => {},
Err(e) => {
println!("Could not read file \"{}\": {}", filenames.0, e);
return;
}, | }
v
},
Err(e) => {
println!("Could not open file \"{}\": {}", filenames.0, e);
return;
},
}, match File::open(filenames.1) {
Ok(mut f) => {
let mut v = Vec::new();
match f.read_to_end(&mut v) {
Ok(_) => {},
Err(e) => {
println!("Could not read file \"{}\": {}", filenames.1, e);
return;
},
}
v
},
Err(e) => {
println!("Could not open file \"{}\": {}", filenames.1, e);
return;
},
},
);
let len = std::cmp::min(files.0.len(), files.1.len());
let mut rng = rand::os::OsRng::new().ok().unwrap();
//Generate crossover file
let mut result =
(0..crossover_points)
//Map these to random crossover points
.map(|_| rng.gen_range(0, len))
//Add total_instructions at the end so we can generate a range with it
.chain(Some(len))
//Sort them by value into BTree, which removes duplicates and orders them
.fold(std::collections::BTreeSet::new(), |mut set, i| {set.insert(i); set})
//Iterate over the sorted values
.iter()
//Turn every copy of two, prepending a 0, into a range
.scan(0, |prev, x| {let out = Some(*prev..*x); *prev = *x; out})
//Enumerate by index to differentiate odd and even values
.enumerate()
//Map even pairs to ranges in parent 0 and odd ones to ranges in parent 1 and expand the ranges
.flat_map(|(index, range)| {
{if index % 2 == 0 {files.0[range].iter()} else {files.1[range].iter()}}.cloned()
})
//Collect all the instruction ranges from each parent
.collect_vec();
//Mutate result file
let strides =
//We can only stride the beginning of a mutation group up to this actual len
(result.len() - (mutation_size - 1))
//Divide by stride
/ stride;
for i in 0..strides {
if rng.next_f64() < mutation_rate {
for v in &mut result[(i * stride)..(i * stride + mutation_size)] {
*v = rng.gen();
}
}
}
let mut outfile = match File::create(output) {
Ok(f) => f,
Err(e) => {
println!("Could not create file \"{}\": {}", output, e);
return;
},
};
match outfile.write_all(&result[..]) {
Ok(_) => {},
Err(e) => {
println!("Could not write to \"{}\": {}", output, e);
return;
},
}
} | random_line_split |
|
main.rs | extern crate itertools;
extern crate clap;
extern crate rand;
use itertools::Itertools;
use clap::{App, Arg};
use std::fs::File;
use rand::Rng;
use std::io::{Read, Write};
const DEFAULT_CROSSOVER_POINTS: usize = 3;
const DEFAULT_MUTATION_RATE: f64 = 0.001;
const DEFAULT_UNIT: usize = 1;
const DEFAULT_STRIDE: usize = 1;
fn main() | .long("mutation-rate")
.value_name("RATE")
.help("Takes a RATE of mutation that randomizes UNIT bytes at a time")
.takes_value(true))
.arg(Arg::with_name("crossover-points")
.short("c")
.multiple(false)
.long("crossover-points")
.value_name("NUMBER")
.help("Takes a NUMBER of crossover points of 1 or greater")
.takes_value(true))
.arg(Arg::with_name("unit")
.short("u")
.multiple(false)
.long("unit")
.value_name("BYTES")
.help("Takes an amount of BYTES that are always mutated as a group")
.takes_value(true))
.arg(Arg::with_name("stride")
.short("s")
.multiple(false)
.long("stride")
.value_name("BYTES")
.help("Takes an amount of BYTES that define the alignment of mutated units")
.takes_value(true))
.get_matches();
let crossover_points = match matches.value_of("crossover-points") {
Some(c) => {
match c.parse::<usize>() {
Ok(0) => {
println!("Error: Cannot accept 0 crossover-points.");
return;
},
Ok(n) => n,
Err(e) => {
println!("Error: Failed to parse crossover-points: {}", e);
return;
},
}
},
None => DEFAULT_CROSSOVER_POINTS,
};
let mutation_rate = match matches.value_of("mutation-rate") {
Some(c) => {
match c.parse::<f64>() {
Ok(n) => n,
Err(e) => {
println!("Error: Failed to parse mutation-rate: {}", e);
return;
},
}
},
None => DEFAULT_MUTATION_RATE,
};
let mutation_size = match matches.value_of("unit") {
Some(c) => {
match c.parse::<usize>() {
Ok(0) => {
println!("Error: Cannot accept 0 bytes as the unit.");
return;
},
Ok(n) => n,
Err(e) => {
println!("Error: Failed to parse unit: {}", e);
return;
},
}
},
None => DEFAULT_UNIT,
};
let stride = match matches.value_of("stride") {
Some(c) => {
match c.parse::<usize>() {
Ok(0) => {
println!("Error: Cannot accept 0 bytes as the stride.");
return;
},
Ok(n) => n,
Err(e) => {
println!("Error: Failed to parse stride: {}", e);
return;
},
}
},
None => DEFAULT_STRIDE,
};
let output = matches.value_of("output").unwrap();
let filenames = (matches.value_of("file1").unwrap(), matches.value_of("file2").unwrap());
let files = (
match File::open(filenames.0) {
Ok(mut f) => {
let mut v = Vec::new();
match f.read_to_end(&mut v) {
Ok(_) => {},
Err(e) => {
println!("Could not read file \"{}\": {}", filenames.0, e);
return;
},
}
v
},
Err(e) => {
println!("Could not open file \"{}\": {}", filenames.0, e);
return;
},
}, match File::open(filenames.1) {
Ok(mut f) => {
let mut v = Vec::new();
match f.read_to_end(&mut v) {
Ok(_) => {},
Err(e) => {
println!("Could not read file \"{}\": {}", filenames.1, e);
return;
},
}
v
},
Err(e) => {
println!("Could not open file \"{}\": {}", filenames.1, e);
return;
},
},
);
let len = std::cmp::min(files.0.len(), files.1.len());
let mut rng = rand::os::OsRng::new().ok().unwrap();
//Generate crossover file
let mut result =
(0..crossover_points)
//Map these to random crossover points
.map(|_| rng.gen_range(0, len))
//Add total_instructions at the end so we can generate a range with it
.chain(Some(len))
//Sort them by value into BTree, which removes duplicates and orders them
.fold(std::collections::BTreeSet::new(), |mut set, i| {set.insert(i); set})
//Iterate over the sorted values
.iter()
//Turn every copy of two, prepending a 0, into a range
.scan(0, |prev, x| {let out = Some(*prev..*x); *prev = *x; out})
//Enumerate by index to differentiate odd and even values
.enumerate()
//Map even pairs to ranges in parent 0 and odd ones to ranges in parent 1 and expand the ranges
.flat_map(|(index, range)| {
{if index % 2 == 0 {files.0[range].iter()} else {files.1[range].iter()}}.cloned()
})
//Collect all the instruction ranges from each parent
.collect_vec();
//Mutate result file
let strides =
//We can only stride the beginning of a mutation group up to this actual len
(result.len() - (mutation_size - 1))
//Divide by stride
/ stride;
for i in 0..strides {
if rng.next_f64() < mutation_rate {
for v in &mut result[(i * stride)..(i * stride + mutation_size)] {
*v = rng.gen();
}
}
}
let mut outfile = match File::create(output) {
Ok(f) => f,
Err(e) => {
println!("Could not create file \"{}\": {}", output, e);
return;
},
};
match outfile.write_all(&result[..]) {
Ok(_) => {},
Err(e) => {
println!("Could not write to \"{}\": {}", output, e);
return;
},
}
}
| {
let matches = App::new("matef")
.version("1.0")
.author("Geordon Worley <[email protected]>")
.about("Mates two files")
.arg(Arg::with_name("output")
.help("The output location")
.required(true)
.index(1))
.arg(Arg::with_name("file1")
.help("Input file 1")
.required(true)
.index(2))
.arg(Arg::with_name("file2")
.help("Input file 2")
.required(true)
.index(3))
.arg(Arg::with_name("mutation-rate")
.short("m")
.multiple(false) | identifier_body |
main.rs | extern crate itertools;
extern crate clap;
extern crate rand;
use itertools::Itertools;
use clap::{App, Arg};
use std::fs::File;
use rand::Rng;
use std::io::{Read, Write};
const DEFAULT_CROSSOVER_POINTS: usize = 3;
const DEFAULT_MUTATION_RATE: f64 = 0.001;
const DEFAULT_UNIT: usize = 1;
const DEFAULT_STRIDE: usize = 1;
fn | () {
let matches = App::new("matef")
.version("1.0")
.author("Geordon Worley <[email protected]>")
.about("Mates two files")
.arg(Arg::with_name("output")
.help("The output location")
.required(true)
.index(1))
.arg(Arg::with_name("file1")
.help("Input file 1")
.required(true)
.index(2))
.arg(Arg::with_name("file2")
.help("Input file 2")
.required(true)
.index(3))
.arg(Arg::with_name("mutation-rate")
.short("m")
.multiple(false)
.long("mutation-rate")
.value_name("RATE")
.help("Takes a RATE of mutation that randomizes UNIT bytes at a time")
.takes_value(true))
.arg(Arg::with_name("crossover-points")
.short("c")
.multiple(false)
.long("crossover-points")
.value_name("NUMBER")
.help("Takes a NUMBER of crossover points of 1 or greater")
.takes_value(true))
.arg(Arg::with_name("unit")
.short("u")
.multiple(false)
.long("unit")
.value_name("BYTES")
.help("Takes an amount of BYTES that are always mutated as a group")
.takes_value(true))
.arg(Arg::with_name("stride")
.short("s")
.multiple(false)
.long("stride")
.value_name("BYTES")
.help("Takes an amount of BYTES that define the alignment of mutated units")
.takes_value(true))
.get_matches();
let crossover_points = match matches.value_of("crossover-points") {
Some(c) => {
match c.parse::<usize>() {
Ok(0) => {
println!("Error: Cannot accept 0 crossover-points.");
return;
},
Ok(n) => n,
Err(e) => {
println!("Error: Failed to parse crossover-points: {}", e);
return;
},
}
},
None => DEFAULT_CROSSOVER_POINTS,
};
let mutation_rate = match matches.value_of("mutation-rate") {
Some(c) => {
match c.parse::<f64>() {
Ok(n) => n,
Err(e) => {
println!("Error: Failed to parse mutation-rate: {}", e);
return;
},
}
},
None => DEFAULT_MUTATION_RATE,
};
let mutation_size = match matches.value_of("unit") {
Some(c) => {
match c.parse::<usize>() {
Ok(0) => {
println!("Error: Cannot accept 0 bytes as the unit.");
return;
},
Ok(n) => n,
Err(e) => {
println!("Error: Failed to parse unit: {}", e);
return;
},
}
},
None => DEFAULT_UNIT,
};
let stride = match matches.value_of("stride") {
Some(c) => {
match c.parse::<usize>() {
Ok(0) => {
println!("Error: Cannot accept 0 bytes as the stride.");
return;
},
Ok(n) => n,
Err(e) => {
println!("Error: Failed to parse stride: {}", e);
return;
},
}
},
None => DEFAULT_STRIDE,
};
let output = matches.value_of("output").unwrap();
let filenames = (matches.value_of("file1").unwrap(), matches.value_of("file2").unwrap());
let files = (
match File::open(filenames.0) {
Ok(mut f) => {
let mut v = Vec::new();
match f.read_to_end(&mut v) {
Ok(_) => {},
Err(e) => {
println!("Could not read file \"{}\": {}", filenames.0, e);
return;
},
}
v
},
Err(e) => {
println!("Could not open file \"{}\": {}", filenames.0, e);
return;
},
}, match File::open(filenames.1) {
Ok(mut f) => {
let mut v = Vec::new();
match f.read_to_end(&mut v) {
Ok(_) => {},
Err(e) => {
println!("Could not read file \"{}\": {}", filenames.1, e);
return;
},
}
v
},
Err(e) => {
println!("Could not open file \"{}\": {}", filenames.1, e);
return;
},
},
);
let len = std::cmp::min(files.0.len(), files.1.len());
let mut rng = rand::os::OsRng::new().ok().unwrap();
//Generate crossover file
let mut result =
(0..crossover_points)
//Map these to random crossover points
.map(|_| rng.gen_range(0, len))
//Add total_instructions at the end so we can generate a range with it
.chain(Some(len))
//Sort them by value into BTree, which removes duplicates and orders them
.fold(std::collections::BTreeSet::new(), |mut set, i| {set.insert(i); set})
//Iterate over the sorted values
.iter()
//Turn every copy of two, prepending a 0, into a range
.scan(0, |prev, x| {let out = Some(*prev..*x); *prev = *x; out})
//Enumerate by index to differentiate odd and even values
.enumerate()
//Map even pairs to ranges in parent 0 and odd ones to ranges in parent 1 and expand the ranges
.flat_map(|(index, range)| {
{if index % 2 == 0 {files.0[range].iter()} else {files.1[range].iter()}}.cloned()
})
//Collect all the instruction ranges from each parent
.collect_vec();
//Mutate result file
let strides =
//We can only stride the beginning of a mutation group up to this actual len
(result.len() - (mutation_size - 1))
//Divide by stride
/ stride;
for i in 0..strides {
if rng.next_f64() < mutation_rate {
for v in &mut result[(i * stride)..(i * stride + mutation_size)] {
*v = rng.gen();
}
}
}
let mut outfile = match File::create(output) {
Ok(f) => f,
Err(e) => {
println!("Could not create file \"{}\": {}", output, e);
return;
},
};
match outfile.write_all(&result[..]) {
Ok(_) => {},
Err(e) => {
println!("Could not write to \"{}\": {}", output, e);
return;
},
}
}
| main | identifier_name |
typeck-unsafe-always-share.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.
// Verify that UnsafeCell is *always* sync regardless if `T` is sync.
// ignore-tidy-linelength
use std::cell::UnsafeCell;
use std::kinds::marker;
struct MySync<T> {
u: UnsafeCell<T>
}
struct NoSync {
m: marker::NoSync
}
fn test<T: Sync>(s: T){
}
| test(uns);
let ms = MySync{u: uns};
test(ms);
let ns = NoSync{m: marker::NoSync};
test(ns);
//~^ ERROR `core::kinds::Sync` is not implemented
} | fn main() {
let us = UnsafeCell::new(MySync{u: UnsafeCell::new(0i)});
test(us);
let uns = UnsafeCell::new(NoSync{m: marker::NoSync}); | random_line_split |
typeck-unsafe-always-share.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.
// Verify that UnsafeCell is *always* sync regardless if `T` is sync.
// ignore-tidy-linelength
use std::cell::UnsafeCell;
use std::kinds::marker;
struct MySync<T> {
u: UnsafeCell<T>
}
struct NoSync {
m: marker::NoSync
}
fn test<T: Sync>(s: T) |
fn main() {
let us = UnsafeCell::new(MySync{u: UnsafeCell::new(0i)});
test(us);
let uns = UnsafeCell::new(NoSync{m: marker::NoSync});
test(uns);
let ms = MySync{u: uns};
test(ms);
let ns = NoSync{m: marker::NoSync};
test(ns);
//~^ ERROR `core::kinds::Sync` is not implemented
}
| {
} | identifier_body |
typeck-unsafe-always-share.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.
// Verify that UnsafeCell is *always* sync regardless if `T` is sync.
// ignore-tidy-linelength
use std::cell::UnsafeCell;
use std::kinds::marker;
struct | <T> {
u: UnsafeCell<T>
}
struct NoSync {
m: marker::NoSync
}
fn test<T: Sync>(s: T){
}
fn main() {
let us = UnsafeCell::new(MySync{u: UnsafeCell::new(0i)});
test(us);
let uns = UnsafeCell::new(NoSync{m: marker::NoSync});
test(uns);
let ms = MySync{u: uns};
test(ms);
let ns = NoSync{m: marker::NoSync};
test(ns);
//~^ ERROR `core::kinds::Sync` is not implemented
}
| MySync | identifier_name |
exec.rs | #![feature(test)]
extern crate rasen;
extern crate rasen_dsl;
extern crate test;
use rasen_dsl::prelude::*;
use std::f32::consts::PI;
use test::Bencher;
include!("../../tests/dsl.rs");
#[bench]
fn bench_run_basic_frag(b: &mut Bencher) {
b.iter(|| {
basic_frag(
vec3(0.0f32, 1.0f32, 0.0f32),
vec2(0.0f32, 0.0f32),
Value::of(Sampler(Vec4([0.25f32, 0.625f32, 1.0f32, 1.0f32]))),
);
});
}
#[bench]
fn bench_run_basic_vert(b: &mut Bencher) {
b.iter(|| {
let a_pos = vec3(1.0f32, 2.0f32, 3.0f32);
let a_normal = vec3(0.0f32, 1.0f32, 0.0f32);
let a_uv = vec2(0.5f32, 0.5f32);
#[rustfmt::skip]
let projection = Mat4([
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
]);
#[rustfmt::skip]
let view = Mat4([
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
]);
#[rustfmt::skip]
let model = Mat4([
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
]);
basic_vert(
a_pos,
a_normal,
a_uv,
Value::of(projection),
Value::of(view),
Value::of(model),
)
});
}
#[bench]
fn bench_run_functions(b: &mut Bencher) | {
b.iter(|| {
functions(Value::of(PI));
});
} | identifier_body |
|
exec.rs | #![feature(test)]
extern crate rasen;
extern crate rasen_dsl;
extern crate test;
use rasen_dsl::prelude::*;
use std::f32::consts::PI;
use test::Bencher;
include!("../../tests/dsl.rs");
#[bench]
fn | (b: &mut Bencher) {
b.iter(|| {
basic_frag(
vec3(0.0f32, 1.0f32, 0.0f32),
vec2(0.0f32, 0.0f32),
Value::of(Sampler(Vec4([0.25f32, 0.625f32, 1.0f32, 1.0f32]))),
);
});
}
#[bench]
fn bench_run_basic_vert(b: &mut Bencher) {
b.iter(|| {
let a_pos = vec3(1.0f32, 2.0f32, 3.0f32);
let a_normal = vec3(0.0f32, 1.0f32, 0.0f32);
let a_uv = vec2(0.5f32, 0.5f32);
#[rustfmt::skip]
let projection = Mat4([
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
]);
#[rustfmt::skip]
let view = Mat4([
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
]);
#[rustfmt::skip]
let model = Mat4([
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
]);
basic_vert(
a_pos,
a_normal,
a_uv,
Value::of(projection),
Value::of(view),
Value::of(model),
)
});
}
#[bench]
fn bench_run_functions(b: &mut Bencher) {
b.iter(|| {
functions(Value::of(PI));
});
}
| bench_run_basic_frag | identifier_name |
exec.rs | #![feature(test)]
extern crate rasen;
extern crate rasen_dsl;
extern crate test;
use rasen_dsl::prelude::*;
use std::f32::consts::PI;
use test::Bencher;
include!("../../tests/dsl.rs");
#[bench]
fn bench_run_basic_frag(b: &mut Bencher) {
b.iter(|| {
basic_frag(
vec3(0.0f32, 1.0f32, 0.0f32),
vec2(0.0f32, 0.0f32),
Value::of(Sampler(Vec4([0.25f32, 0.625f32, 1.0f32, 1.0f32]))),
);
});
}
#[bench]
fn bench_run_basic_vert(b: &mut Bencher) {
b.iter(|| {
let a_pos = vec3(1.0f32, 2.0f32, 3.0f32);
let a_normal = vec3(0.0f32, 1.0f32, 0.0f32); | 1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
]);
#[rustfmt::skip]
let view = Mat4([
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
]);
#[rustfmt::skip]
let model = Mat4([
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
]);
basic_vert(
a_pos,
a_normal,
a_uv,
Value::of(projection),
Value::of(view),
Value::of(model),
)
});
}
#[bench]
fn bench_run_functions(b: &mut Bencher) {
b.iter(|| {
functions(Value::of(PI));
});
} | let a_uv = vec2(0.5f32, 0.5f32);
#[rustfmt::skip]
let projection = Mat4([ | random_line_split |
init.rs | use disk::ahci::Ahci;
use disk::ide::Ide;
use env::Environment;
use schemes::file::FileScheme;
use super::config::PciConfig;
use super::common::class::*;
use super::common::subclass::*;
use super::common::programming_interface::*;
/*
use super::common::vendorid::*;
use super::common::deviceid::*;
use audio::ac97::Ac97;
use audio::intelhda::IntelHda;
use network::rtl8139::Rtl8139;
use network::intel8254x::Intel8254x;
use usb::uhci::Uhci;
use usb::ohci::Ohci;
use usb::ehci::Ehci;
use usb::xhci::Xhci;
*/
/// PCI device
pub unsafe fn pci_device(env: &mut Environment,
pci: PciConfig,
class_id: u8,
subclass_id: u8,
interface_id: u8,
vendor_code: u16,
device_code: u16) {
match (class_id, subclass_id, interface_id) {
(MASS_STORAGE, IDE, _) => {
if let Some(module) = FileScheme::new(Ide::disks(pci)) {
env.schemes.lock().push(module);
}
}
(MASS_STORAGE, SATA, AHCI) => {
if let Some(module) = FileScheme::new(Ahci::disks(pci)) {
env.schemes.lock().push(module);
}
}
/*
(SERIAL_BUS, USB, UHCI) => env.schemes.lock().push(Uhci::new(pci)),
(SERIAL_BUS, USB, OHCI) => env.schemes.lock().push(Ohci::new(pci)),
(SERIAL_BUS, USB, EHCI) => env.schemes.lock().push(Ehci::new(pci)),
(SERIAL_BUS, USB, XHCI) => env.schemes.lock().push(Xhci::new(pci)),
*/
_ => match (vendor_code, device_code) {
//(REALTEK, RTL8139) => env.schemes.lock().push(Rtl8139::new(pci)),
//(INTEL, GBE_82540EM) => env.schemes.lock().push(Intel8254x::new(pci)),
//(INTEL, AC97_82801AA) => env.schemes.lock().push(Ac97::new(pci)),
//(INTEL, AC97_ICH4) => env.schemes.lock().push(Ac97::new(pci)),
//(INTEL, INTELHDA_ICH6) => env.schemes.lock().push(IntelHda::new(pci)),
_ => (),
}
}
}
/// Initialize PCI session
pub unsafe fn pci_init(env: &mut Environment) {
for bus in 0..256 {
for slot in 0..32 {
for func in 0..8 {
let mut pci = PciConfig::new(bus as u8, slot as u8, func as u8);
let id = pci.read(0);
if (id & 0xFFFF)!= 0xFFFF {
let class_id = pci.read(8);
/*
debug!(" * PCI {}, {}, {}: ID {:X} CL {:X}",
bus,
slot,
func,
id,
class_id);
for i in 0..6 {
let bar = pci.read(i * 4 + 0x10);
if bar > 0 {
debug!(" BAR{}: {:X}", i, bar);
pci.write(i * 4 + 0x10, 0xFFFFFFFF);
let size = (0xFFFFFFFF - (pci.read(i * 4 + 0x10) & 0xFFFFFFF0)) + 1;
pci.write(i * 4 + 0x10, bar);
if size > 0 {
debug!(" {}", size);
}
}
}
debugln!("");
*/
pci_device(env,
pci,
((class_id >> 24) & 0xFF) as u8,
((class_id >> 16) & 0xFF) as u8,
((class_id >> 8) & 0xFF) as u8,
(id & 0xFFFF) as u16, | }
}
}
}
} | ((id >> 16) & 0xFFFF) as u16); | random_line_split |
init.rs | use disk::ahci::Ahci;
use disk::ide::Ide;
use env::Environment;
use schemes::file::FileScheme;
use super::config::PciConfig;
use super::common::class::*;
use super::common::subclass::*;
use super::common::programming_interface::*;
/*
use super::common::vendorid::*;
use super::common::deviceid::*;
use audio::ac97::Ac97;
use audio::intelhda::IntelHda;
use network::rtl8139::Rtl8139;
use network::intel8254x::Intel8254x;
use usb::uhci::Uhci;
use usb::ohci::Ohci;
use usb::ehci::Ehci;
use usb::xhci::Xhci;
*/
/// PCI device
pub unsafe fn pci_device(env: &mut Environment,
pci: PciConfig,
class_id: u8,
subclass_id: u8,
interface_id: u8,
vendor_code: u16,
device_code: u16) {
match (class_id, subclass_id, interface_id) {
(MASS_STORAGE, IDE, _) => |
(MASS_STORAGE, SATA, AHCI) => {
if let Some(module) = FileScheme::new(Ahci::disks(pci)) {
env.schemes.lock().push(module);
}
}
/*
(SERIAL_BUS, USB, UHCI) => env.schemes.lock().push(Uhci::new(pci)),
(SERIAL_BUS, USB, OHCI) => env.schemes.lock().push(Ohci::new(pci)),
(SERIAL_BUS, USB, EHCI) => env.schemes.lock().push(Ehci::new(pci)),
(SERIAL_BUS, USB, XHCI) => env.schemes.lock().push(Xhci::new(pci)),
*/
_ => match (vendor_code, device_code) {
//(REALTEK, RTL8139) => env.schemes.lock().push(Rtl8139::new(pci)),
//(INTEL, GBE_82540EM) => env.schemes.lock().push(Intel8254x::new(pci)),
//(INTEL, AC97_82801AA) => env.schemes.lock().push(Ac97::new(pci)),
//(INTEL, AC97_ICH4) => env.schemes.lock().push(Ac97::new(pci)),
//(INTEL, INTELHDA_ICH6) => env.schemes.lock().push(IntelHda::new(pci)),
_ => (),
}
}
}
/// Initialize PCI session
pub unsafe fn pci_init(env: &mut Environment) {
for bus in 0..256 {
for slot in 0..32 {
for func in 0..8 {
let mut pci = PciConfig::new(bus as u8, slot as u8, func as u8);
let id = pci.read(0);
if (id & 0xFFFF)!= 0xFFFF {
let class_id = pci.read(8);
/*
debug!(" * PCI {}, {}, {}: ID {:X} CL {:X}",
bus,
slot,
func,
id,
class_id);
for i in 0..6 {
let bar = pci.read(i * 4 + 0x10);
if bar > 0 {
debug!(" BAR{}: {:X}", i, bar);
pci.write(i * 4 + 0x10, 0xFFFFFFFF);
let size = (0xFFFFFFFF - (pci.read(i * 4 + 0x10) & 0xFFFFFFF0)) + 1;
pci.write(i * 4 + 0x10, bar);
if size > 0 {
debug!(" {}", size);
}
}
}
debugln!("");
*/
pci_device(env,
pci,
((class_id >> 24) & 0xFF) as u8,
((class_id >> 16) & 0xFF) as u8,
((class_id >> 8) & 0xFF) as u8,
(id & 0xFFFF) as u16,
((id >> 16) & 0xFFFF) as u16);
}
}
}
}
}
| {
if let Some(module) = FileScheme::new(Ide::disks(pci)) {
env.schemes.lock().push(module);
}
} | conditional_block |
init.rs | use disk::ahci::Ahci;
use disk::ide::Ide;
use env::Environment;
use schemes::file::FileScheme;
use super::config::PciConfig;
use super::common::class::*;
use super::common::subclass::*;
use super::common::programming_interface::*;
/*
use super::common::vendorid::*;
use super::common::deviceid::*;
use audio::ac97::Ac97;
use audio::intelhda::IntelHda;
use network::rtl8139::Rtl8139;
use network::intel8254x::Intel8254x;
use usb::uhci::Uhci;
use usb::ohci::Ohci;
use usb::ehci::Ehci;
use usb::xhci::Xhci;
*/
/// PCI device
pub unsafe fn | (env: &mut Environment,
pci: PciConfig,
class_id: u8,
subclass_id: u8,
interface_id: u8,
vendor_code: u16,
device_code: u16) {
match (class_id, subclass_id, interface_id) {
(MASS_STORAGE, IDE, _) => {
if let Some(module) = FileScheme::new(Ide::disks(pci)) {
env.schemes.lock().push(module);
}
}
(MASS_STORAGE, SATA, AHCI) => {
if let Some(module) = FileScheme::new(Ahci::disks(pci)) {
env.schemes.lock().push(module);
}
}
/*
(SERIAL_BUS, USB, UHCI) => env.schemes.lock().push(Uhci::new(pci)),
(SERIAL_BUS, USB, OHCI) => env.schemes.lock().push(Ohci::new(pci)),
(SERIAL_BUS, USB, EHCI) => env.schemes.lock().push(Ehci::new(pci)),
(SERIAL_BUS, USB, XHCI) => env.schemes.lock().push(Xhci::new(pci)),
*/
_ => match (vendor_code, device_code) {
//(REALTEK, RTL8139) => env.schemes.lock().push(Rtl8139::new(pci)),
//(INTEL, GBE_82540EM) => env.schemes.lock().push(Intel8254x::new(pci)),
//(INTEL, AC97_82801AA) => env.schemes.lock().push(Ac97::new(pci)),
//(INTEL, AC97_ICH4) => env.schemes.lock().push(Ac97::new(pci)),
//(INTEL, INTELHDA_ICH6) => env.schemes.lock().push(IntelHda::new(pci)),
_ => (),
}
}
}
/// Initialize PCI session
pub unsafe fn pci_init(env: &mut Environment) {
for bus in 0..256 {
for slot in 0..32 {
for func in 0..8 {
let mut pci = PciConfig::new(bus as u8, slot as u8, func as u8);
let id = pci.read(0);
if (id & 0xFFFF)!= 0xFFFF {
let class_id = pci.read(8);
/*
debug!(" * PCI {}, {}, {}: ID {:X} CL {:X}",
bus,
slot,
func,
id,
class_id);
for i in 0..6 {
let bar = pci.read(i * 4 + 0x10);
if bar > 0 {
debug!(" BAR{}: {:X}", i, bar);
pci.write(i * 4 + 0x10, 0xFFFFFFFF);
let size = (0xFFFFFFFF - (pci.read(i * 4 + 0x10) & 0xFFFFFFF0)) + 1;
pci.write(i * 4 + 0x10, bar);
if size > 0 {
debug!(" {}", size);
}
}
}
debugln!("");
*/
pci_device(env,
pci,
((class_id >> 24) & 0xFF) as u8,
((class_id >> 16) & 0xFF) as u8,
((class_id >> 8) & 0xFF) as u8,
(id & 0xFFFF) as u16,
((id >> 16) & 0xFFFF) as u16);
}
}
}
}
}
| pci_device | identifier_name |
init.rs | use disk::ahci::Ahci;
use disk::ide::Ide;
use env::Environment;
use schemes::file::FileScheme;
use super::config::PciConfig;
use super::common::class::*;
use super::common::subclass::*;
use super::common::programming_interface::*;
/*
use super::common::vendorid::*;
use super::common::deviceid::*;
use audio::ac97::Ac97;
use audio::intelhda::IntelHda;
use network::rtl8139::Rtl8139;
use network::intel8254x::Intel8254x;
use usb::uhci::Uhci;
use usb::ohci::Ohci;
use usb::ehci::Ehci;
use usb::xhci::Xhci;
*/
/// PCI device
pub unsafe fn pci_device(env: &mut Environment,
pci: PciConfig,
class_id: u8,
subclass_id: u8,
interface_id: u8,
vendor_code: u16,
device_code: u16) {
match (class_id, subclass_id, interface_id) {
(MASS_STORAGE, IDE, _) => {
if let Some(module) = FileScheme::new(Ide::disks(pci)) {
env.schemes.lock().push(module);
}
}
(MASS_STORAGE, SATA, AHCI) => {
if let Some(module) = FileScheme::new(Ahci::disks(pci)) {
env.schemes.lock().push(module);
}
}
/*
(SERIAL_BUS, USB, UHCI) => env.schemes.lock().push(Uhci::new(pci)),
(SERIAL_BUS, USB, OHCI) => env.schemes.lock().push(Ohci::new(pci)),
(SERIAL_BUS, USB, EHCI) => env.schemes.lock().push(Ehci::new(pci)),
(SERIAL_BUS, USB, XHCI) => env.schemes.lock().push(Xhci::new(pci)),
*/
_ => match (vendor_code, device_code) {
//(REALTEK, RTL8139) => env.schemes.lock().push(Rtl8139::new(pci)),
//(INTEL, GBE_82540EM) => env.schemes.lock().push(Intel8254x::new(pci)),
//(INTEL, AC97_82801AA) => env.schemes.lock().push(Ac97::new(pci)),
//(INTEL, AC97_ICH4) => env.schemes.lock().push(Ac97::new(pci)),
//(INTEL, INTELHDA_ICH6) => env.schemes.lock().push(IntelHda::new(pci)),
_ => (),
}
}
}
/// Initialize PCI session
pub unsafe fn pci_init(env: &mut Environment) | if bar > 0 {
debug!(" BAR{}: {:X}", i, bar);
pci.write(i * 4 + 0x10, 0xFFFFFFFF);
let size = (0xFFFFFFFF - (pci.read(i * 4 + 0x10) & 0xFFFFFFF0)) + 1;
pci.write(i * 4 + 0x10, bar);
if size > 0 {
debug!(" {}", size);
}
}
}
debugln!("");
*/
pci_device(env,
pci,
((class_id >> 24) & 0xFF) as u8,
((class_id >> 16) & 0xFF) as u8,
((class_id >> 8) & 0xFF) as u8,
(id & 0xFFFF) as u16,
((id >> 16) & 0xFFFF) as u16);
}
}
}
}
}
| {
for bus in 0..256 {
for slot in 0..32 {
for func in 0..8 {
let mut pci = PciConfig::new(bus as u8, slot as u8, func as u8);
let id = pci.read(0);
if (id & 0xFFFF) != 0xFFFF {
let class_id = pci.read(8);
/*
debug!(" * PCI {}, {}, {}: ID {:X} CL {:X}",
bus,
slot,
func,
id,
class_id);
for i in 0..6 {
let bar = pci.read(i * 4 + 0x10); | identifier_body |
main.rs | // Copyright (c) 2015 Sergey "SnakE" Gromov
//
// See the file license.txt for copying permission.
//! # Radix Conversion Utility
extern crate num;
mod table;
mod convtable;
use std::{env, path};
use num::BigInt;
use convtable::ConvTable;
use std::error::Error;
use num::traits::Num;
fn main() {
let mut table = ConvTable::new();
let args: Vec<String> = env::args().collect();
if args.len() == 1 {
usage(path::Path::new(&args[0]).file_name().unwrap().to_str().unwrap());
return;
}
for arg in args.into_iter().skip(1) {
let arg = arg.trim();
let (v, radix) = if let Some(s) = strip_prefix(&arg, "0x") {
(s, 16)
} else if let Some(s) = strip_prefix(&arg, "0b") {
(s, 2)
} else if let Some(s) = strip_prefix(&arg, "0o") {
(s, 8)
} else {
(&*arg, 10)
};
match BigInt::from_str_radix(&v, radix) {
Ok(x) => table.push_result(&arg, &x),
Err(e) => table.push_error(&arg, e.description()),
};
}
table.print();
}
/// Return input string without prefix if prefix matches.
fn | <'a>(s: &'a str, prefix: &str) -> Option<&'a str> {
if s.starts_with(prefix) {
Some(&s[prefix.len()..])
} else {
None
}
}
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
fn usage(tool: &str) {
println!("\
Display numbers in multiple radii
(c) 2015 Sergey \"SnakE\" Gromov
Version {}
Usage: {} num [num...]
num decimal, hex, octal, or binary number
decimal start with a digit
hex start with `0x`
octal start with `0o`
binary start with `0b`", VERSION, tool);
}
| strip_prefix | identifier_name |
main.rs | // Copyright (c) 2015 Sergey "SnakE" Gromov
//
// See the file license.txt for copying permission.
//! # Radix Conversion Utility
extern crate num;
mod table;
mod convtable;
use std::{env, path};
use num::BigInt;
use convtable::ConvTable;
use std::error::Error;
use num::traits::Num;
fn main() {
let mut table = ConvTable::new();
let args: Vec<String> = env::args().collect();
if args.len() == 1 {
usage(path::Path::new(&args[0]).file_name().unwrap().to_str().unwrap());
return;
}
for arg in args.into_iter().skip(1) {
let arg = arg.trim();
let (v, radix) = if let Some(s) = strip_prefix(&arg, "0x") {
(s, 16)
} else if let Some(s) = strip_prefix(&arg, "0b") {
(s, 2)
} else if let Some(s) = strip_prefix(&arg, "0o") {
(s, 8)
} else {
(&*arg, 10)
};
match BigInt::from_str_radix(&v, radix) {
Ok(x) => table.push_result(&arg, &x),
Err(e) => table.push_error(&arg, e.description()),
};
}
table.print();
}
/// Return input string without prefix if prefix matches.
fn strip_prefix<'a>(s: &'a str, prefix: &str) -> Option<&'a str> |
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
fn usage(tool: &str) {
println!("\
Display numbers in multiple radii
(c) 2015 Sergey \"SnakE\" Gromov
Version {}
Usage: {} num [num...]
num decimal, hex, octal, or binary number
decimal start with a digit
hex start with `0x`
octal start with `0o`
binary start with `0b`", VERSION, tool);
}
| {
if s.starts_with(prefix) {
Some(&s[prefix.len()..])
} else {
None
}
} | identifier_body |
main.rs | // Copyright (c) 2015 Sergey "SnakE" Gromov
//
// See the file license.txt for copying permission.
//! # Radix Conversion Utility
extern crate num;
mod table;
mod convtable;
use std::{env, path};
use num::BigInt;
use convtable::ConvTable;
use std::error::Error;
use num::traits::Num;
fn main() {
let mut table = ConvTable::new();
let args: Vec<String> = env::args().collect();
if args.len() == 1 {
usage(path::Path::new(&args[0]).file_name().unwrap().to_str().unwrap());
return;
}
for arg in args.into_iter().skip(1) {
let arg = arg.trim();
let (v, radix) = if let Some(s) = strip_prefix(&arg, "0x") {
(s, 16)
} else if let Some(s) = strip_prefix(&arg, "0b") {
(s, 2)
} else if let Some(s) = strip_prefix(&arg, "0o") {
(s, 8) | match BigInt::from_str_radix(&v, radix) {
Ok(x) => table.push_result(&arg, &x),
Err(e) => table.push_error(&arg, e.description()),
};
}
table.print();
}
/// Return input string without prefix if prefix matches.
fn strip_prefix<'a>(s: &'a str, prefix: &str) -> Option<&'a str> {
if s.starts_with(prefix) {
Some(&s[prefix.len()..])
} else {
None
}
}
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
fn usage(tool: &str) {
println!("\
Display numbers in multiple radii
(c) 2015 Sergey \"SnakE\" Gromov
Version {}
Usage: {} num [num...]
num decimal, hex, octal, or binary number
decimal start with a digit
hex start with `0x`
octal start with `0o`
binary start with `0b`", VERSION, tool);
} | } else {
(&*arg, 10)
};
| random_line_split |
view.rs | /*!
PE view.
*/
use std::prelude::v1::*;
use std::{cmp, slice};
use crate::Result;
use super::image::*;
use super::pe::validate_headers;
use super::{Align, Pe, PeObject};
/// View into a mapped PE image.
#[derive(Copy, Clone)]
pub struct PeView<'a> {
image: &'a [u8],
}
current_target! {
impl PeView<'static> {
/// Constructs a view of the module this code is executing in.
#[inline]
pub unsafe fn new() -> PeView<'static> {
Self::module(image_base() as *const _ as *const u8)
}
}
}
impl<'a> PeView<'a> {
/// Constructs a view from a byte slice.
///
/// # Errors
///
/// * [`Bounds`](../enum.Error.html#variant.Bounds):
/// The byte slice is too small to fit the PE headers.
///
/// * [`Misaligned`](../enum.Error.html#variant.Misaligned):
/// The minimum alignment of 4 is not satisfied.
///
/// * [`BadMagic`](../enum.Error.html#variant.BadMagic):
/// This is not a PE file.
///
/// * [`PeMagic`](../enum.Error.html#variant.PeMagic):
/// Trying to parse a PE32 file with the PE32+ parser and vice versa.
///
/// * [`Insanity`](../enum.Error.html#variant.Insanity):
/// Reasonable limits on `e_lfanew`, `SizeOfHeaders` or `NumberOfSections` are exceeded.
pub fn from_bytes<T: AsRef<[u8]> +?Sized>(image: &'a T) -> Result<PeView<'a>> {
let image = image.as_ref();
let _ = validate_headers(image)?;
Ok(PeView { image })
}
/// Constructs a new view from module handle.
///
/// # Safety
///
/// The underlying memory is borrowed and an unbounded lifetime is returned.
/// Ensure the lifetime outlives this view instance!
///
/// No sanity or safety checks are done to make sure this is really PE32(+) image.
/// When using this with a `HMODULE` from the system the caller must be sure this is a PE32(+) image.
#[inline]
pub unsafe fn module(base: *const u8) -> PeView<'a> {
let dos = &*(base as *const IMAGE_DOS_HEADER);
let nt = &*(base.offset(dos.e_lfanew as isize) as *const IMAGE_NT_HEADERS);
PeView {
image: slice::from_raw_parts(base, nt.OptionalHeader.SizeOfImage as usize),
}
}
/// Converts the view to file alignment.
pub fn to_file(self) -> Vec<u8> {
let (sizeof_headers, sizeof_image) = {
let optional_header = self.optional_header();
(optional_header.SizeOfHeaders, optional_header.SizeOfImage)
};
// Figure out the size of the file image | }
// Clamp to the actual image size...
file_size = cmp::min(file_size, sizeof_image);
// Zero fill the underlying file
let mut vec = vec![0u8; file_size as usize];
// Start by copying the headers
let image = self.image();
unsafe {
// Validated by constructor
let dest_headers = vec.get_unchecked_mut(..sizeof_headers as usize);
let src_headers = image.get_unchecked(..sizeof_headers as usize);
dest_headers.copy_from_slice(src_headers);
}
// Copy the section image data
for section in self.section_headers() {
let dest = vec.get_mut(section.PointerToRawData as usize..u32::wrapping_add(section.PointerToRawData, section.SizeOfRawData) as usize);
let src = image.get(section.VirtualAddress as usize..u32::wrapping_add(section.VirtualAddress, section.VirtualSize) as usize);
// Skip invalid sections...
if let (Some(dest), Some(src)) = (dest, src) {
dest.copy_from_slice(src);
}
}
vec
}
}
//----------------------------------------------------------------
unsafe impl<'a> Pe<'a> for PeView<'a> {}
unsafe impl<'a> PeObject<'a> for PeView<'a> {
fn image(&self) -> &'a [u8] {
self.image
}
fn align(&self) -> Align {
Align::Section
}
#[cfg(feature = "serde")]
fn serde_name(&self) -> &'static str {
"PeView"
}
}
//----------------------------------------------------------------
#[cfg(feature = "serde")]
impl<'a> serde::Serialize for PeView<'a> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
super::pe::serialize_pe(*self, serializer)
}
}
//----------------------------------------------------------------
#[cfg(test)]
mod tests {
use crate::Error;
use super::PeView;
#[test]
fn from_byte_slice() {
assert!(match PeView::from_bytes(&[]) { Err(Error::Bounds) => true, _ => false });
}
} | let mut file_size = sizeof_headers;
for section in self.section_headers() {
file_size = cmp::max(file_size, u32::wrapping_add(section.PointerToRawData, section.SizeOfRawData)); | random_line_split |
view.rs | /*!
PE view.
*/
use std::prelude::v1::*;
use std::{cmp, slice};
use crate::Result;
use super::image::*;
use super::pe::validate_headers;
use super::{Align, Pe, PeObject};
/// View into a mapped PE image.
#[derive(Copy, Clone)]
pub struct PeView<'a> {
image: &'a [u8],
}
current_target! {
impl PeView<'static> {
/// Constructs a view of the module this code is executing in.
#[inline]
pub unsafe fn new() -> PeView<'static> {
Self::module(image_base() as *const _ as *const u8)
}
}
}
impl<'a> PeView<'a> {
/// Constructs a view from a byte slice.
///
/// # Errors
///
/// * [`Bounds`](../enum.Error.html#variant.Bounds):
/// The byte slice is too small to fit the PE headers.
///
/// * [`Misaligned`](../enum.Error.html#variant.Misaligned):
/// The minimum alignment of 4 is not satisfied.
///
/// * [`BadMagic`](../enum.Error.html#variant.BadMagic):
/// This is not a PE file.
///
/// * [`PeMagic`](../enum.Error.html#variant.PeMagic):
/// Trying to parse a PE32 file with the PE32+ parser and vice versa.
///
/// * [`Insanity`](../enum.Error.html#variant.Insanity):
/// Reasonable limits on `e_lfanew`, `SizeOfHeaders` or `NumberOfSections` are exceeded.
pub fn from_bytes<T: AsRef<[u8]> +?Sized>(image: &'a T) -> Result<PeView<'a>> {
let image = image.as_ref();
let _ = validate_headers(image)?;
Ok(PeView { image })
}
/// Constructs a new view from module handle.
///
/// # Safety
///
/// The underlying memory is borrowed and an unbounded lifetime is returned.
/// Ensure the lifetime outlives this view instance!
///
/// No sanity or safety checks are done to make sure this is really PE32(+) image.
/// When using this with a `HMODULE` from the system the caller must be sure this is a PE32(+) image.
#[inline]
pub unsafe fn module(base: *const u8) -> PeView<'a> {
let dos = &*(base as *const IMAGE_DOS_HEADER);
let nt = &*(base.offset(dos.e_lfanew as isize) as *const IMAGE_NT_HEADERS);
PeView {
image: slice::from_raw_parts(base, nt.OptionalHeader.SizeOfImage as usize),
}
}
/// Converts the view to file alignment.
pub fn to_file(self) -> Vec<u8> {
let (sizeof_headers, sizeof_image) = {
let optional_header = self.optional_header();
(optional_header.SizeOfHeaders, optional_header.SizeOfImage)
};
// Figure out the size of the file image
let mut file_size = sizeof_headers;
for section in self.section_headers() {
file_size = cmp::max(file_size, u32::wrapping_add(section.PointerToRawData, section.SizeOfRawData));
}
// Clamp to the actual image size...
file_size = cmp::min(file_size, sizeof_image);
// Zero fill the underlying file
let mut vec = vec![0u8; file_size as usize];
// Start by copying the headers
let image = self.image();
unsafe {
// Validated by constructor
let dest_headers = vec.get_unchecked_mut(..sizeof_headers as usize);
let src_headers = image.get_unchecked(..sizeof_headers as usize);
dest_headers.copy_from_slice(src_headers);
}
// Copy the section image data
for section in self.section_headers() {
let dest = vec.get_mut(section.PointerToRawData as usize..u32::wrapping_add(section.PointerToRawData, section.SizeOfRawData) as usize);
let src = image.get(section.VirtualAddress as usize..u32::wrapping_add(section.VirtualAddress, section.VirtualSize) as usize);
// Skip invalid sections...
if let (Some(dest), Some(src)) = (dest, src) |
}
vec
}
}
//----------------------------------------------------------------
unsafe impl<'a> Pe<'a> for PeView<'a> {}
unsafe impl<'a> PeObject<'a> for PeView<'a> {
fn image(&self) -> &'a [u8] {
self.image
}
fn align(&self) -> Align {
Align::Section
}
#[cfg(feature = "serde")]
fn serde_name(&self) -> &'static str {
"PeView"
}
}
//----------------------------------------------------------------
#[cfg(feature = "serde")]
impl<'a> serde::Serialize for PeView<'a> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
super::pe::serialize_pe(*self, serializer)
}
}
//----------------------------------------------------------------
#[cfg(test)]
mod tests {
use crate::Error;
use super::PeView;
#[test]
fn from_byte_slice() {
assert!(match PeView::from_bytes(&[]) { Err(Error::Bounds) => true, _ => false });
}
}
| {
dest.copy_from_slice(src);
} | conditional_block |
view.rs | /*!
PE view.
*/
use std::prelude::v1::*;
use std::{cmp, slice};
use crate::Result;
use super::image::*;
use super::pe::validate_headers;
use super::{Align, Pe, PeObject};
/// View into a mapped PE image.
#[derive(Copy, Clone)]
pub struct PeView<'a> {
image: &'a [u8],
}
current_target! {
impl PeView<'static> {
/// Constructs a view of the module this code is executing in.
#[inline]
pub unsafe fn new() -> PeView<'static> {
Self::module(image_base() as *const _ as *const u8)
}
}
}
impl<'a> PeView<'a> {
/// Constructs a view from a byte slice.
///
/// # Errors
///
/// * [`Bounds`](../enum.Error.html#variant.Bounds):
/// The byte slice is too small to fit the PE headers.
///
/// * [`Misaligned`](../enum.Error.html#variant.Misaligned):
/// The minimum alignment of 4 is not satisfied.
///
/// * [`BadMagic`](../enum.Error.html#variant.BadMagic):
/// This is not a PE file.
///
/// * [`PeMagic`](../enum.Error.html#variant.PeMagic):
/// Trying to parse a PE32 file with the PE32+ parser and vice versa.
///
/// * [`Insanity`](../enum.Error.html#variant.Insanity):
/// Reasonable limits on `e_lfanew`, `SizeOfHeaders` or `NumberOfSections` are exceeded.
pub fn from_bytes<T: AsRef<[u8]> +?Sized>(image: &'a T) -> Result<PeView<'a>> {
let image = image.as_ref();
let _ = validate_headers(image)?;
Ok(PeView { image })
}
/// Constructs a new view from module handle.
///
/// # Safety
///
/// The underlying memory is borrowed and an unbounded lifetime is returned.
/// Ensure the lifetime outlives this view instance!
///
/// No sanity or safety checks are done to make sure this is really PE32(+) image.
/// When using this with a `HMODULE` from the system the caller must be sure this is a PE32(+) image.
#[inline]
pub unsafe fn module(base: *const u8) -> PeView<'a> {
let dos = &*(base as *const IMAGE_DOS_HEADER);
let nt = &*(base.offset(dos.e_lfanew as isize) as *const IMAGE_NT_HEADERS);
PeView {
image: slice::from_raw_parts(base, nt.OptionalHeader.SizeOfImage as usize),
}
}
/// Converts the view to file alignment.
pub fn to_file(self) -> Vec<u8> {
let (sizeof_headers, sizeof_image) = {
let optional_header = self.optional_header();
(optional_header.SizeOfHeaders, optional_header.SizeOfImage)
};
// Figure out the size of the file image
let mut file_size = sizeof_headers;
for section in self.section_headers() {
file_size = cmp::max(file_size, u32::wrapping_add(section.PointerToRawData, section.SizeOfRawData));
}
// Clamp to the actual image size...
file_size = cmp::min(file_size, sizeof_image);
// Zero fill the underlying file
let mut vec = vec![0u8; file_size as usize];
// Start by copying the headers
let image = self.image();
unsafe {
// Validated by constructor
let dest_headers = vec.get_unchecked_mut(..sizeof_headers as usize);
let src_headers = image.get_unchecked(..sizeof_headers as usize);
dest_headers.copy_from_slice(src_headers);
}
// Copy the section image data
for section in self.section_headers() {
let dest = vec.get_mut(section.PointerToRawData as usize..u32::wrapping_add(section.PointerToRawData, section.SizeOfRawData) as usize);
let src = image.get(section.VirtualAddress as usize..u32::wrapping_add(section.VirtualAddress, section.VirtualSize) as usize);
// Skip invalid sections...
if let (Some(dest), Some(src)) = (dest, src) {
dest.copy_from_slice(src);
}
}
vec
}
}
//----------------------------------------------------------------
unsafe impl<'a> Pe<'a> for PeView<'a> {}
unsafe impl<'a> PeObject<'a> for PeView<'a> {
fn image(&self) -> &'a [u8] {
self.image
}
fn align(&self) -> Align {
Align::Section
}
#[cfg(feature = "serde")]
fn serde_name(&self) -> &'static str |
}
//----------------------------------------------------------------
#[cfg(feature = "serde")]
impl<'a> serde::Serialize for PeView<'a> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
super::pe::serialize_pe(*self, serializer)
}
}
//----------------------------------------------------------------
#[cfg(test)]
mod tests {
use crate::Error;
use super::PeView;
#[test]
fn from_byte_slice() {
assert!(match PeView::from_bytes(&[]) { Err(Error::Bounds) => true, _ => false });
}
}
| {
"PeView"
} | identifier_body |
view.rs | /*!
PE view.
*/
use std::prelude::v1::*;
use std::{cmp, slice};
use crate::Result;
use super::image::*;
use super::pe::validate_headers;
use super::{Align, Pe, PeObject};
/// View into a mapped PE image.
#[derive(Copy, Clone)]
pub struct PeView<'a> {
image: &'a [u8],
}
current_target! {
impl PeView<'static> {
/// Constructs a view of the module this code is executing in.
#[inline]
pub unsafe fn new() -> PeView<'static> {
Self::module(image_base() as *const _ as *const u8)
}
}
}
impl<'a> PeView<'a> {
/// Constructs a view from a byte slice.
///
/// # Errors
///
/// * [`Bounds`](../enum.Error.html#variant.Bounds):
/// The byte slice is too small to fit the PE headers.
///
/// * [`Misaligned`](../enum.Error.html#variant.Misaligned):
/// The minimum alignment of 4 is not satisfied.
///
/// * [`BadMagic`](../enum.Error.html#variant.BadMagic):
/// This is not a PE file.
///
/// * [`PeMagic`](../enum.Error.html#variant.PeMagic):
/// Trying to parse a PE32 file with the PE32+ parser and vice versa.
///
/// * [`Insanity`](../enum.Error.html#variant.Insanity):
/// Reasonable limits on `e_lfanew`, `SizeOfHeaders` or `NumberOfSections` are exceeded.
pub fn from_bytes<T: AsRef<[u8]> +?Sized>(image: &'a T) -> Result<PeView<'a>> {
let image = image.as_ref();
let _ = validate_headers(image)?;
Ok(PeView { image })
}
/// Constructs a new view from module handle.
///
/// # Safety
///
/// The underlying memory is borrowed and an unbounded lifetime is returned.
/// Ensure the lifetime outlives this view instance!
///
/// No sanity or safety checks are done to make sure this is really PE32(+) image.
/// When using this with a `HMODULE` from the system the caller must be sure this is a PE32(+) image.
#[inline]
pub unsafe fn module(base: *const u8) -> PeView<'a> {
let dos = &*(base as *const IMAGE_DOS_HEADER);
let nt = &*(base.offset(dos.e_lfanew as isize) as *const IMAGE_NT_HEADERS);
PeView {
image: slice::from_raw_parts(base, nt.OptionalHeader.SizeOfImage as usize),
}
}
/// Converts the view to file alignment.
pub fn to_file(self) -> Vec<u8> {
let (sizeof_headers, sizeof_image) = {
let optional_header = self.optional_header();
(optional_header.SizeOfHeaders, optional_header.SizeOfImage)
};
// Figure out the size of the file image
let mut file_size = sizeof_headers;
for section in self.section_headers() {
file_size = cmp::max(file_size, u32::wrapping_add(section.PointerToRawData, section.SizeOfRawData));
}
// Clamp to the actual image size...
file_size = cmp::min(file_size, sizeof_image);
// Zero fill the underlying file
let mut vec = vec![0u8; file_size as usize];
// Start by copying the headers
let image = self.image();
unsafe {
// Validated by constructor
let dest_headers = vec.get_unchecked_mut(..sizeof_headers as usize);
let src_headers = image.get_unchecked(..sizeof_headers as usize);
dest_headers.copy_from_slice(src_headers);
}
// Copy the section image data
for section in self.section_headers() {
let dest = vec.get_mut(section.PointerToRawData as usize..u32::wrapping_add(section.PointerToRawData, section.SizeOfRawData) as usize);
let src = image.get(section.VirtualAddress as usize..u32::wrapping_add(section.VirtualAddress, section.VirtualSize) as usize);
// Skip invalid sections...
if let (Some(dest), Some(src)) = (dest, src) {
dest.copy_from_slice(src);
}
}
vec
}
}
//----------------------------------------------------------------
unsafe impl<'a> Pe<'a> for PeView<'a> {}
unsafe impl<'a> PeObject<'a> for PeView<'a> {
fn image(&self) -> &'a [u8] {
self.image
}
fn align(&self) -> Align {
Align::Section
}
#[cfg(feature = "serde")]
fn serde_name(&self) -> &'static str {
"PeView"
}
}
//----------------------------------------------------------------
#[cfg(feature = "serde")]
impl<'a> serde::Serialize for PeView<'a> {
fn | <S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
super::pe::serialize_pe(*self, serializer)
}
}
//----------------------------------------------------------------
#[cfg(test)]
mod tests {
use crate::Error;
use super::PeView;
#[test]
fn from_byte_slice() {
assert!(match PeView::from_bytes(&[]) { Err(Error::Bounds) => true, _ => false });
}
}
| serialize | identifier_name |
xrwebglsubimage.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::XRWebGLSubImageBinding::XRWebGLSubImageBinding::XRWebGLSubImageMethods;
use crate::dom::bindings::root::Dom;
use crate::dom::bindings::root::DomRoot;
use crate::dom::webgltexture::WebGLTexture;
use crate::dom::xrsubimage::XRSubImage;
use dom_struct::dom_struct;
#[dom_struct]
pub struct XRWebGLSubImage {
xr_sub_image: XRSubImage,
color_texture: Dom<WebGLTexture>,
depth_stencil_texture: Option<Dom<WebGLTexture>>,
image_index: Option<u32>,
}
impl XRWebGLSubImageMethods for XRWebGLSubImage {
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-colortexture
fn ColorTexture(&self) -> DomRoot<WebGLTexture> {
DomRoot::from_ref(&self.color_texture)
}
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-depthstenciltexture
fn GetDepthStencilTexture(&self) -> Option<DomRoot<WebGLTexture>> {
self.depth_stencil_texture.as_deref().map(DomRoot::from_ref)
}
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-imageindex | fn GetImageIndex(&self) -> Option<u32> {
self.image_index
}
} | random_line_split |
|
xrwebglsubimage.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::XRWebGLSubImageBinding::XRWebGLSubImageBinding::XRWebGLSubImageMethods;
use crate::dom::bindings::root::Dom;
use crate::dom::bindings::root::DomRoot;
use crate::dom::webgltexture::WebGLTexture;
use crate::dom::xrsubimage::XRSubImage;
use dom_struct::dom_struct;
#[dom_struct]
pub struct XRWebGLSubImage {
xr_sub_image: XRSubImage,
color_texture: Dom<WebGLTexture>,
depth_stencil_texture: Option<Dom<WebGLTexture>>,
image_index: Option<u32>,
}
impl XRWebGLSubImageMethods for XRWebGLSubImage {
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-colortexture
fn ColorTexture(&self) -> DomRoot<WebGLTexture> {
DomRoot::from_ref(&self.color_texture)
}
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-depthstenciltexture
fn GetDepthStencilTexture(&self) -> Option<DomRoot<WebGLTexture>> {
self.depth_stencil_texture.as_deref().map(DomRoot::from_ref)
}
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-imageindex
fn | (&self) -> Option<u32> {
self.image_index
}
}
| GetImageIndex | identifier_name |
xrwebglsubimage.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::XRWebGLSubImageBinding::XRWebGLSubImageBinding::XRWebGLSubImageMethods;
use crate::dom::bindings::root::Dom;
use crate::dom::bindings::root::DomRoot;
use crate::dom::webgltexture::WebGLTexture;
use crate::dom::xrsubimage::XRSubImage;
use dom_struct::dom_struct;
#[dom_struct]
pub struct XRWebGLSubImage {
xr_sub_image: XRSubImage,
color_texture: Dom<WebGLTexture>,
depth_stencil_texture: Option<Dom<WebGLTexture>>,
image_index: Option<u32>,
}
impl XRWebGLSubImageMethods for XRWebGLSubImage {
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-colortexture
fn ColorTexture(&self) -> DomRoot<WebGLTexture> {
DomRoot::from_ref(&self.color_texture)
}
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-depthstenciltexture
fn GetDepthStencilTexture(&self) -> Option<DomRoot<WebGLTexture>> |
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-imageindex
fn GetImageIndex(&self) -> Option<u32> {
self.image_index
}
}
| {
self.depth_stencil_texture.as_deref().map(DomRoot::from_ref)
} | identifier_body |
thread.rs | use alloc::boxed::Box;
use core::mem;
use system::syscall::{sys_clone, sys_exit, sys_yield, sys_nanosleep, sys_waitpid, CLONE_VM, CLONE_FS, CLONE_FILES,
TimeSpec};
use time::Duration;
/// An owned permission to join on a thread (block on its termination).
///
/// A `JoinHandle` *detaches* the child thread when it is dropped.
///
/// Due to platform restrictions, it is not possible to `Clone` this
/// handle: the ability to join a child thread is a uniquely-owned
/// permission.
// TODO: Mutex the result
pub struct JoinHandle<T> {
pid: usize,
result_ptr: *mut Option<T>,
}
impl<T> JoinHandle<T> {
/// Waits for the associated thread to finish.
pub fn join(self) -> Option<T> where T: ::core::fmt::Debug |
}
/// Sleep for a duration
pub fn sleep(duration: Duration) {
let req = TimeSpec {
tv_sec: duration.as_secs() as i64,
tv_nsec: duration.subsec_nanos() as i32,
};
let mut rem = TimeSpec {
tv_sec: 0,
tv_nsec: 0,
};
let _ = sys_nanosleep(&req, &mut rem);
}
/// Sleep for a number of milliseconds
pub fn sleep_ms(ms: u32) {
let secs = ms as u64 / 1000;
let nanos = (ms % 1000) * 1000000;
sleep(Duration::new(secs, nanos))
}
/// Spawns a new thread, returning a `JoinHandle` for it.
///
/// The join handle will implicitly *detach* the child thread upon being
/// dropped. In this case, the child thread may outlive the parent (unless
/// the parent thread is the main thread; the whole process is terminated when
/// the main thread finishes.) Additionally, the join handle provides a `join`
/// method that can be used to join the child thread. If the child thread
/// panics, `join` will return an `Err` containing the argument given to
/// `panic`.
///
/// # Panics
///
/// Panics if the OS fails to create a thread; use `Builder::spawn`
/// to recover from such errors.
// TODO: Catch panic
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where F: FnOnce() -> T,
F: Send +'static,
T: Send +'static
{
let result_ptr: *mut Option<T> = Box::into_raw(box None);
//This must only be used by the child
let boxed_f = Box::new(f);
match unsafe { sys_clone(CLONE_VM | CLONE_FS | CLONE_FILES).unwrap() } {
0 => {
unsafe { *result_ptr = Some(boxed_f()) };
loop {
let _ = sys_exit(0);
}
},
pid => {
//Forget so that the parent will not drop while the child is using
mem::forget(boxed_f);
JoinHandle {
pid: pid,
result_ptr: result_ptr
}
}
}
}
pub fn yield_now() {
let _ = sys_yield();
}
| {
let mut status = 0;
match sys_waitpid(self.pid, &mut status, 0) {
Ok(_) => unsafe { *Box::from_raw(self.result_ptr) },
Err(_) => None
}
} | identifier_body |
thread.rs | use alloc::boxed::Box;
use core::mem;
use system::syscall::{sys_clone, sys_exit, sys_yield, sys_nanosleep, sys_waitpid, CLONE_VM, CLONE_FS, CLONE_FILES,
TimeSpec};
use time::Duration;
/// An owned permission to join on a thread (block on its termination).
///
/// A `JoinHandle` *detaches* the child thread when it is dropped.
///
/// Due to platform restrictions, it is not possible to `Clone` this
/// handle: the ability to join a child thread is a uniquely-owned
/// permission.
// TODO: Mutex the result
pub struct JoinHandle<T> {
pid: usize,
result_ptr: *mut Option<T>,
}
impl<T> JoinHandle<T> {
/// Waits for the associated thread to finish.
pub fn join(self) -> Option<T> where T: ::core::fmt::Debug {
let mut status = 0;
match sys_waitpid(self.pid, &mut status, 0) {
Ok(_) => unsafe { *Box::from_raw(self.result_ptr) },
Err(_) => None
}
}
}
/// Sleep for a duration
pub fn sleep(duration: Duration) {
let req = TimeSpec {
tv_sec: duration.as_secs() as i64,
tv_nsec: duration.subsec_nanos() as i32,
};
let mut rem = TimeSpec {
tv_sec: 0,
tv_nsec: 0,
};
let _ = sys_nanosleep(&req, &mut rem);
}
/// Sleep for a number of milliseconds
pub fn sleep_ms(ms: u32) {
let secs = ms as u64 / 1000;
let nanos = (ms % 1000) * 1000000;
sleep(Duration::new(secs, nanos))
}
/// Spawns a new thread, returning a `JoinHandle` for it.
///
/// The join handle will implicitly *detach* the child thread upon being
/// dropped. In this case, the child thread may outlive the parent (unless
/// the parent thread is the main thread; the whole process is terminated when
/// the main thread finishes.) Additionally, the join handle provides a `join`
/// method that can be used to join the child thread. If the child thread
/// panics, `join` will return an `Err` containing the argument given to
/// `panic`.
///
/// # Panics
///
/// Panics if the OS fails to create a thread; use `Builder::spawn`
/// to recover from such errors.
// TODO: Catch panic
pub fn | <F, T>(f: F) -> JoinHandle<T>
where F: FnOnce() -> T,
F: Send +'static,
T: Send +'static
{
let result_ptr: *mut Option<T> = Box::into_raw(box None);
//This must only be used by the child
let boxed_f = Box::new(f);
match unsafe { sys_clone(CLONE_VM | CLONE_FS | CLONE_FILES).unwrap() } {
0 => {
unsafe { *result_ptr = Some(boxed_f()) };
loop {
let _ = sys_exit(0);
}
},
pid => {
//Forget so that the parent will not drop while the child is using
mem::forget(boxed_f);
JoinHandle {
pid: pid,
result_ptr: result_ptr
}
}
}
}
pub fn yield_now() {
let _ = sys_yield();
}
| spawn | identifier_name |
thread.rs | use alloc::boxed::Box;
use core::mem;
use system::syscall::{sys_clone, sys_exit, sys_yield, sys_nanosleep, sys_waitpid, CLONE_VM, CLONE_FS, CLONE_FILES,
TimeSpec};
use time::Duration;
/// An owned permission to join on a thread (block on its termination).
///
/// A `JoinHandle` *detaches* the child thread when it is dropped.
///
/// Due to platform restrictions, it is not possible to `Clone` this
/// handle: the ability to join a child thread is a uniquely-owned
/// permission.
// TODO: Mutex the result
pub struct JoinHandle<T> {
pid: usize,
result_ptr: *mut Option<T>,
}
impl<T> JoinHandle<T> {
/// Waits for the associated thread to finish.
pub fn join(self) -> Option<T> where T: ::core::fmt::Debug {
let mut status = 0;
match sys_waitpid(self.pid, &mut status, 0) {
Ok(_) => unsafe { *Box::from_raw(self.result_ptr) },
Err(_) => None
}
}
}
/// Sleep for a duration
pub fn sleep(duration: Duration) {
let req = TimeSpec {
tv_sec: duration.as_secs() as i64,
tv_nsec: duration.subsec_nanos() as i32,
};
| let _ = sys_nanosleep(&req, &mut rem);
}
/// Sleep for a number of milliseconds
pub fn sleep_ms(ms: u32) {
let secs = ms as u64 / 1000;
let nanos = (ms % 1000) * 1000000;
sleep(Duration::new(secs, nanos))
}
/// Spawns a new thread, returning a `JoinHandle` for it.
///
/// The join handle will implicitly *detach* the child thread upon being
/// dropped. In this case, the child thread may outlive the parent (unless
/// the parent thread is the main thread; the whole process is terminated when
/// the main thread finishes.) Additionally, the join handle provides a `join`
/// method that can be used to join the child thread. If the child thread
/// panics, `join` will return an `Err` containing the argument given to
/// `panic`.
///
/// # Panics
///
/// Panics if the OS fails to create a thread; use `Builder::spawn`
/// to recover from such errors.
// TODO: Catch panic
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where F: FnOnce() -> T,
F: Send +'static,
T: Send +'static
{
let result_ptr: *mut Option<T> = Box::into_raw(box None);
//This must only be used by the child
let boxed_f = Box::new(f);
match unsafe { sys_clone(CLONE_VM | CLONE_FS | CLONE_FILES).unwrap() } {
0 => {
unsafe { *result_ptr = Some(boxed_f()) };
loop {
let _ = sys_exit(0);
}
},
pid => {
//Forget so that the parent will not drop while the child is using
mem::forget(boxed_f);
JoinHandle {
pid: pid,
result_ptr: result_ptr
}
}
}
}
pub fn yield_now() {
let _ = sys_yield();
} | let mut rem = TimeSpec {
tv_sec: 0,
tv_nsec: 0,
};
| random_line_split |
sequence.rs | use io::fai::FaiRecord;
use sequence::*;
use std::fmt;
use std::fs::File;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::path::Path;
use std::path::PathBuf;
#[derive(Clone, Debug)]
pub struct FaiSequence {
record: FaiRecord,
filename: PathBuf,
}
impl FaiSequence {
pub fn new<P: AsRef<Path>>(record: FaiRecord, filename: &P) -> FaiSequence {
FaiSequence {
record: record,
filename: filename.as_ref().to_path_buf(),
} |
fn length(&self) -> usize {
self.record.length()
}
fn vec(&self) -> Vec<DnaNucleotide> {
self.subsequence(0, self.length()).vec()
}
fn subsequence(&self, offset: usize, length: usize) -> DnaSequence {
let n_lines = offset / self.record.linebases();
let n_bases = offset - (n_lines * self.record.linebases());
let file_offset = self.record.offset() + n_lines * self.record.linewidth() + n_bases;
let mut fh = match File::open(&self.filename) {
Err(_) => return DnaSequence::default(),
Ok(fh) => fh,
};
if! fh.seek(SeekFrom::Start(file_offset as u64)).is_ok() {
return DnaSequence::default();
}
let sequence: Vec<DnaNucleotide> = fh.bytes()
.map(|b| b.unwrap() as char)
.take_while(|c| *c!= '>') // Break at new record
.filter(|c|! c.is_whitespace() ) // drop whitespaces
.take(length)
.map(|c| DnaNucleotide::from(c))
.collect();
DnaSequence::from(sequence)
}
}
impl fmt::Display for FaiSequence {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"FaiSequence[{}:{}bp]",
self.record.name(),
self.record.length()
)
}
}
#[cfg(test)]
mod tests {
use io::fai::*;
use sequence::*;
#[test]
fn test_a(){
let index_result = FaiIndex::read_fai(&"testdata/toy.fasta.fai");
assert!(index_result.is_ok());
let index = index_result.unwrap();
let record = index.find_record(&"ref").expect(&"Expected to find a record with name'ref'");
let chrom = FaiSequence::new(record, &"testdata/toy.fasta");
assert_eq!(chrom.subsequence(0,4).to_string(), "AGCA");
assert_eq!(chrom.subsequence(1,3).to_string(), "GCA");
}
} | }
}
impl Sequence<DnaNucleotide> for FaiSequence {
type SubsequenceType = DnaSequence; | random_line_split |
sequence.rs |
use io::fai::FaiRecord;
use sequence::*;
use std::fmt;
use std::fs::File;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::path::Path;
use std::path::PathBuf;
#[derive(Clone, Debug)]
pub struct FaiSequence {
record: FaiRecord,
filename: PathBuf,
}
impl FaiSequence {
pub fn new<P: AsRef<Path>>(record: FaiRecord, filename: &P) -> FaiSequence {
FaiSequence {
record: record,
filename: filename.as_ref().to_path_buf(),
}
}
}
impl Sequence<DnaNucleotide> for FaiSequence {
type SubsequenceType = DnaSequence;
fn length(&self) -> usize |
fn vec(&self) -> Vec<DnaNucleotide> {
self.subsequence(0, self.length()).vec()
}
fn subsequence(&self, offset: usize, length: usize) -> DnaSequence {
let n_lines = offset / self.record.linebases();
let n_bases = offset - (n_lines * self.record.linebases());
let file_offset = self.record.offset() + n_lines * self.record.linewidth() + n_bases;
let mut fh = match File::open(&self.filename) {
Err(_) => return DnaSequence::default(),
Ok(fh) => fh,
};
if! fh.seek(SeekFrom::Start(file_offset as u64)).is_ok() {
return DnaSequence::default();
}
let sequence: Vec<DnaNucleotide> = fh.bytes()
.map(|b| b.unwrap() as char)
.take_while(|c| *c!= '>') // Break at new record
.filter(|c|! c.is_whitespace() ) // drop whitespaces
.take(length)
.map(|c| DnaNucleotide::from(c))
.collect();
DnaSequence::from(sequence)
}
}
impl fmt::Display for FaiSequence {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"FaiSequence[{}:{}bp]",
self.record.name(),
self.record.length()
)
}
}
#[cfg(test)]
mod tests {
use io::fai::*;
use sequence::*;
#[test]
fn test_a(){
let index_result = FaiIndex::read_fai(&"testdata/toy.fasta.fai");
assert!(index_result.is_ok());
let index = index_result.unwrap();
let record = index.find_record(&"ref").expect(&"Expected to find a record with name'ref'");
let chrom = FaiSequence::new(record, &"testdata/toy.fasta");
assert_eq!(chrom.subsequence(0,4).to_string(), "AGCA");
assert_eq!(chrom.subsequence(1,3).to_string(), "GCA");
}
} | {
self.record.length()
} | identifier_body |
sequence.rs |
use io::fai::FaiRecord;
use sequence::*;
use std::fmt;
use std::fs::File;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::path::Path;
use std::path::PathBuf;
#[derive(Clone, Debug)]
pub struct | {
record: FaiRecord,
filename: PathBuf,
}
impl FaiSequence {
pub fn new<P: AsRef<Path>>(record: FaiRecord, filename: &P) -> FaiSequence {
FaiSequence {
record: record,
filename: filename.as_ref().to_path_buf(),
}
}
}
impl Sequence<DnaNucleotide> for FaiSequence {
type SubsequenceType = DnaSequence;
fn length(&self) -> usize {
self.record.length()
}
fn vec(&self) -> Vec<DnaNucleotide> {
self.subsequence(0, self.length()).vec()
}
fn subsequence(&self, offset: usize, length: usize) -> DnaSequence {
let n_lines = offset / self.record.linebases();
let n_bases = offset - (n_lines * self.record.linebases());
let file_offset = self.record.offset() + n_lines * self.record.linewidth() + n_bases;
let mut fh = match File::open(&self.filename) {
Err(_) => return DnaSequence::default(),
Ok(fh) => fh,
};
if! fh.seek(SeekFrom::Start(file_offset as u64)).is_ok() {
return DnaSequence::default();
}
let sequence: Vec<DnaNucleotide> = fh.bytes()
.map(|b| b.unwrap() as char)
.take_while(|c| *c!= '>') // Break at new record
.filter(|c|! c.is_whitespace() ) // drop whitespaces
.take(length)
.map(|c| DnaNucleotide::from(c))
.collect();
DnaSequence::from(sequence)
}
}
impl fmt::Display for FaiSequence {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"FaiSequence[{}:{}bp]",
self.record.name(),
self.record.length()
)
}
}
#[cfg(test)]
mod tests {
use io::fai::*;
use sequence::*;
#[test]
fn test_a(){
let index_result = FaiIndex::read_fai(&"testdata/toy.fasta.fai");
assert!(index_result.is_ok());
let index = index_result.unwrap();
let record = index.find_record(&"ref").expect(&"Expected to find a record with name'ref'");
let chrom = FaiSequence::new(record, &"testdata/toy.fasta");
assert_eq!(chrom.subsequence(0,4).to_string(), "AGCA");
assert_eq!(chrom.subsequence(1,3).to_string(), "GCA");
}
} | FaiSequence | identifier_name |
non_ts_pseudo_class_list.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/. */
/*
* This file contains a helper macro includes all supported non-tree-structural
* pseudo-classes.
*
* FIXME: Find a way to autogenerate this file.
*
* Expected usage is as follows:
* ```
* macro_rules! pseudo_class_macro{
* (bare: [$(($css:expr, $name:ident, $gecko_type:tt, $state:tt, $flags:tt),)*],
* string: [$(($s_css:expr, $s_name:ident, $s_gecko_type:tt, $s_state:tt, $s_flags:tt),)*]) => {
* keyword: [$(($k_css:expr, $k_name:ident, $k_gecko_type:tt, $k_state:tt, $k_flags:tt),)*]) => {
* // do stuff
* }
* }
* apply_non_ts_list!(pseudo_class_macro)
* ```
*
* The `string` and `keyword` variables will be applied to pseudoclasses that are of the form of
* functions with string or keyword arguments.
*
* Pending pseudo-classes:
*
* :scope -> <style scoped>, pending discussion.
*
* This follows the order defined in layout/style/nsCSSPseudoClassList.h when
* possible.
*
* $gecko_type can be either "_" or an ident in Gecko's CSSPseudoClassType.
* $state can be either "_" or an expression of type ElementState. If present,
* the semantics are that the pseudo-class matches if any of the bits in
* $state are set on the element.
* $flags can be either "_" or an expression of type NonTSPseudoClassFlag,
* see selector_parser.rs for more details.
*/
macro_rules! apply_non_ts_list {
($apply_macro:ident) => {
$apply_macro! {
bare: [
("-moz-table-border-nonzero", MozTableBorderNonzero, mozTableBorderNonzero, _, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS),
("-moz-browser-frame", MozBrowserFrame, mozBrowserFrame, _, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME),
("link", Link, link, IN_UNVISITED_STATE, _),
("any-link", AnyLink, anyLink, IN_VISITED_OR_UNVISITED_STATE, _), | ("focus", Focus, focus, IN_FOCUS_STATE, _),
("focus-within", FocusWithin, focusWithin, IN_FOCUS_WITHIN_STATE, _),
("hover", Hover, hover, IN_HOVER_STATE, _),
("-moz-drag-over", MozDragOver, mozDragOver, IN_DRAGOVER_STATE, _),
("target", Target, target, IN_TARGET_STATE, _),
("indeterminate", Indeterminate, indeterminate, IN_INDETERMINATE_STATE, _),
("-moz-devtools-highlighted", MozDevtoolsHighlighted, mozDevtoolsHighlighted, IN_DEVTOOLS_HIGHLIGHTED_STATE, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS),
("-moz-styleeditor-transitioning", MozStyleeditorTransitioning, mozStyleeditorTransitioning, IN_STYLEEDITOR_TRANSITIONING_STATE, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS),
("fullscreen", Fullscreen, fullscreen, IN_FULLSCREEN_STATE, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME),
("-moz-full-screen", MozFullScreen, mozFullScreen, IN_FULLSCREEN_STATE, _),
// TODO(emilio): This is inconsistently named (the capital R).
("-moz-focusring", MozFocusRing, mozFocusRing, IN_FOCUSRING_STATE, _),
("-moz-broken", MozBroken, mozBroken, IN_BROKEN_STATE, _),
("-moz-loading", MozLoading, mozLoading, IN_LOADING_STATE, _),
("-moz-suppressed", MozSuppressed, mozSuppressed, IN_SUPPRESSED_STATE, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME),
("-moz-has-dir-attr", MozHasDirAttr, mozHasDirAttr, IN_HAS_DIR_ATTR_STATE, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS),
("-moz-dir-attr-ltr", MozDirAttrLTR, mozDirAttrLTR, IN_HAS_DIR_ATTR_LTR_STATE, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS),
("-moz-dir-attr-rtl", MozDirAttrRTL, mozDirAttrRTL, IN_HAS_DIR_ATTR_RTL_STATE, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS),
("-moz-dir-attr-like-auto", MozDirAttrLikeAuto, mozDirAttrLikeAuto, IN_HAS_DIR_ATTR_LIKE_AUTO_STATE, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS),
("-moz-autofill", MozAutofill, mozAutofill, IN_AUTOFILL_STATE, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME),
("-moz-autofill-preview", MozAutofillPreview, mozAutofillPreview, IN_AUTOFILL_PREVIEW_STATE, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME),
("-moz-handler-clicktoplay", MozHandlerClickToPlay, mozHandlerClickToPlay, IN_HANDLER_CLICK_TO_PLAY_STATE, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME),
("-moz-handler-vulnerable-updatable", MozHandlerVulnerableUpdatable, mozHandlerVulnerableUpdatable, IN_HANDLER_VULNERABLE_UPDATABLE_STATE, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME),
("-moz-handler-vulnerable-no-update", MozHandlerVulnerableNoUpdate, mozHandlerVulnerableNoUpdate, IN_HANDLER_VULNERABLE_NO_UPDATE_STATE, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME),
("-moz-handler-disabled", MozHandlerDisabled, mozHandlerDisabled, IN_HANDLER_DISABLED_STATE, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME),
("-moz-handler-blocked", MozHandlerBlocked, mozHandlerBlocked, IN_HANDLER_BLOCKED_STATE, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME),
("-moz-handler-crashed", MozHandlerCrashed, mozHandlerCrashed, IN_HANDLER_CRASHED_STATE, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME),
("-moz-math-increment-script-level", MozMathIncrementScriptLevel, mozMathIncrementScriptLevel, IN_INCREMENT_SCRIPT_LEVEL_STATE, _),
("required", Required, required, IN_REQUIRED_STATE, _),
("optional", Optional, optional, IN_OPTIONAL_STATE, _),
("valid", Valid, valid, IN_VALID_STATE, _),
("invalid", Invalid, invalid, IN_INVALID_STATE, _),
("in-range", InRange, inRange, IN_INRANGE_STATE, _),
("out-of-range", OutOfRange, outOfRange, IN_OUTOFRANGE_STATE, _),
("default", Default, defaultPseudo, IN_DEFAULT_STATE, _),
("placeholder-shown", PlaceholderShown, placeholderShown, IN_PLACEHOLDER_SHOWN_STATE, _),
("-moz-read-only", MozReadOnly, mozReadOnly, IN_MOZ_READONLY_STATE, _),
("-moz-read-write", MozReadWrite, mozReadWrite, IN_MOZ_READWRITE_STATE, _),
("-moz-submit-invalid", MozSubmitInvalid, mozSubmitInvalid, IN_MOZ_SUBMITINVALID_STATE, _),
("-moz-ui-valid", MozUIValid, mozUIValid, IN_MOZ_UI_VALID_STATE, _),
("-moz-ui-invalid", MozUIInvalid, mozUIInvalid, IN_MOZ_UI_INVALID_STATE, _),
("-moz-meter-optimum", MozMeterOptimum, mozMeterOptimum, IN_OPTIMUM_STATE, _),
("-moz-meter-sub-optimum", MozMeterSubOptimum, mozMeterSubOptimum, IN_SUB_OPTIMUM_STATE, _),
("-moz-meter-sub-sub-optimum", MozMeterSubSubOptimum, mozMeterSubSubOptimum, IN_SUB_SUB_OPTIMUM_STATE, _),
("-moz-user-disabled", MozUserDisabled, mozUserDisabled, IN_USER_DISABLED_STATE, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS_AND_CHROME),
("-moz-first-node", MozFirstNode, firstNode, _, _),
("-moz-last-node", MozLastNode, lastNode, _, _),
("-moz-only-whitespace", MozOnlyWhitespace, mozOnlyWhitespace, _, _),
("-moz-native-anonymous", MozNativeAnonymous, mozNativeAnonymous, _, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS),
("-moz-use-shadow-tree-root", MozUseShadowTreeRoot, mozUseShadowTreeRoot, _, PSEUDO_CLASS_ENABLED_IN_UA_SHEETS),
("-moz-is-html", MozIsHTML, mozIsHTML, _, _),
("-moz-placeholder", MozPlaceholder, mozPlaceholder, _, _),
("-moz-lwtheme", MozLWTheme, mozLWTheme, _, _),
("-moz-lwtheme-brighttext", MozLWThemeBrightText, mozLWThemeBrightText, _, _),
("-moz-lwtheme-darktext", MozLWThemeDarkText, mozLWThemeDarkText, _, _),
("-moz-window-inactive", MozWindowInactive, mozWindowInactive, _, _),
],
string: [
("lang", Lang, lang, _, _),
]
}
}
} | ("visited", Visited, visited, IN_VISITED_STATE, _),
("active", Active, active, IN_ACTIVE_STATE, _),
("checked", Checked, checked, IN_CHECKED_STATE, _),
("disabled", Disabled, disabled, IN_DISABLED_STATE, _),
("enabled", Enabled, enabled, IN_ENABLED_STATE, _), | random_line_split |
update.rs | #![feature(test)]
extern crate protocoll;
extern crate test;
use test::Bencher;
use protocoll::Map;
use std::collections::HashMap;
#[bench]
fn imperative(b: &mut Bencher) {
let sent = "a short treatise on fungi";
b.iter(|| {
let mut letters = HashMap::new();
for ch in sent.chars() {
let counter = letters.entry(ch).or_insert(0);
*counter += 1;
}
letters
})
}
#[bench]
fn functional(b: &mut Bencher) {
let sent = "a short treatise on fungi";
b.iter(|| sent.chars().fold(HashMap::new(), |m,c| m.update(c, |n| 1 + n.unwrap_or(0))))
} | let sent = "a short treatise on fungi";
b.iter(|| sent.chars().fold(HashMap::new(), |m,c| m.update_in_place(c, 0, |n| *n += 1)))
} |
#[bench]
fn in_place(b: &mut Bencher) { | random_line_split |
update.rs | #![feature(test)]
extern crate protocoll;
extern crate test;
use test::Bencher;
use protocoll::Map;
use std::collections::HashMap;
#[bench]
fn imperative(b: &mut Bencher) {
let sent = "a short treatise on fungi";
b.iter(|| {
let mut letters = HashMap::new();
for ch in sent.chars() {
let counter = letters.entry(ch).or_insert(0);
*counter += 1;
}
letters
})
}
#[bench]
fn functional(b: &mut Bencher) |
#[bench]
fn in_place(b: &mut Bencher) {
let sent = "a short treatise on fungi";
b.iter(|| sent.chars().fold(HashMap::new(), |m,c| m.update_in_place(c, 0, |n| *n += 1)))
}
| {
let sent = "a short treatise on fungi";
b.iter(|| sent.chars().fold(HashMap::new(), |m,c| m.update(c, |n| 1 + n.unwrap_or(0))))
} | identifier_body |
update.rs | #![feature(test)]
extern crate protocoll;
extern crate test;
use test::Bencher;
use protocoll::Map;
use std::collections::HashMap;
#[bench]
fn imperative(b: &mut Bencher) {
let sent = "a short treatise on fungi";
b.iter(|| {
let mut letters = HashMap::new();
for ch in sent.chars() {
let counter = letters.entry(ch).or_insert(0);
*counter += 1;
}
letters
})
}
#[bench]
fn | (b: &mut Bencher) {
let sent = "a short treatise on fungi";
b.iter(|| sent.chars().fold(HashMap::new(), |m,c| m.update(c, |n| 1 + n.unwrap_or(0))))
}
#[bench]
fn in_place(b: &mut Bencher) {
let sent = "a short treatise on fungi";
b.iter(|| sent.chars().fold(HashMap::new(), |m,c| m.update_in_place(c, 0, |n| *n += 1)))
}
| functional | identifier_name |
unwind.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Implementation of Rust stack unwinding
//
// For background on exception handling and stack unwinding please see
// "Exception Handling in LLVM" (llvm.org/docs/ExceptionHandling.html) and
// documents linked from it.
// These are also good reads:
// http://theofilos.cs.columbia.edu/blog/2013/09/22/base_abi/
// http://monoinfinito.wordpress.com/series/exception-handling-in-c/
// http://www.airs.com/blog/index.php?s=exception+frames
//
// ~~~ A brief summary ~~~
// Exception handling happens in two phases: a search phase and a cleanup phase.
//
// In both phases the unwinder walks stack frames from top to bottom using
// information from the stack frame unwind sections of the current process's
// modules ("module" here refers to an OS module, i.e. an executable or a
// dynamic library).
//
// For each stack frame, it invokes the associated "personality routine", whose
// address is also stored in the unwind info section.
//
// In the search phase, the job of a personality routine is to examine exception
// object being thrown, and to decide whether it should be caught at that stack
// frame. Once the handler frame has been identified, cleanup phase begins.
//
// In the cleanup phase, personality routines invoke cleanup code associated
// with their stack frames (i.e. destructors). Once stack has been unwound down
// to the handler frame level, unwinding stops and the last personality routine
// transfers control to its' catch block.
//
// ~~~ Frame unwind info registration ~~~
// Each module has its' own frame unwind info section (usually ".eh_frame"), and
// unwinder needs to know about all of them in order for unwinding to be able to
// cross module boundaries.
//
// On some platforms, like Linux, this is achieved by dynamically enumerating
// currently loaded modules via the dl_iterate_phdr() API and finding all
//.eh_frame sections.
//
// Others, like Windows, require modules to actively register their unwind info
// sections by calling __register_frame_info() API at startup. In the latter
// case it is essential that there is only one copy of the unwinder runtime in
// the process. This is usually achieved by linking to the dynamic version of
// the unwind runtime.
//
// Currently Rust uses unwind runtime provided by libgcc.
use any::{Any, AnyRefExt};
use c_str::CString;
use cast;
use fmt;
use kinds::Send;
use mem;
use option::{Some, None, Option};
use prelude::drop;
use ptr::RawPtr;
use result::{Err, Ok};
use rt::backtrace;
use rt::local::Local;
use rt::task::Task;
use str::Str;
use task::TaskResult;
use intrinsics;
use uw = rt::libunwind;
pub struct Unwinder {
priv unwinding: bool,
priv cause: Option<~Any:Send>
}
impl Unwinder {
pub fn new() -> Unwinder {
Unwinder {
unwinding: false,
cause: None,
}
}
pub fn unwinding(&self) -> bool {
self.unwinding
}
pub fn try(&mut self, f: ||) {
use raw::Closure; |
unsafe {
let closure: Closure = cast::transmute(f);
let ep = rust_try(try_fn, closure.code as *c_void,
closure.env as *c_void);
if!ep.is_null() {
rtdebug!("caught {}", (*ep).exception_class);
uw::_Unwind_DeleteException(ep);
}
}
extern fn try_fn(code: *c_void, env: *c_void) {
unsafe {
let closure: || = cast::transmute(Closure {
code: code as *(),
env: env as *(),
});
closure();
}
}
extern {
// Rust's try-catch
// When f(...) returns normally, the return value is null.
// When f(...) throws, the return value is a pointer to the caught
// exception object.
fn rust_try(f: extern "C" fn(*c_void, *c_void),
code: *c_void,
data: *c_void) -> *uw::_Unwind_Exception;
}
}
pub fn begin_unwind(&mut self, cause: ~Any:Send) ->! {
rtdebug!("begin_unwind()");
self.unwinding = true;
self.cause = Some(cause);
rust_fail();
// An uninlined, unmangled function upon which to slap yer breakpoints
#[inline(never)]
#[no_mangle]
fn rust_fail() ->! {
unsafe {
let exception = ~uw::_Unwind_Exception {
exception_class: rust_exception_class(),
exception_cleanup: exception_cleanup,
private: [0,..uw::unwinder_private_data_size],
};
let error = uw::_Unwind_RaiseException(cast::transmute(exception));
rtabort!("Could not unwind stack, error = {}", error as int)
}
extern "C" fn exception_cleanup(_unwind_code: uw::_Unwind_Reason_Code,
exception: *uw::_Unwind_Exception) {
rtdebug!("exception_cleanup()");
unsafe {
let _: ~uw::_Unwind_Exception = cast::transmute(exception);
}
}
}
}
pub fn result(&mut self) -> TaskResult {
if self.unwinding {
Err(self.cause.take().unwrap())
} else {
Ok(())
}
}
}
// Rust's exception class identifier. This is used by personality routines to
// determine whether the exception was thrown by their own runtime.
fn rust_exception_class() -> uw::_Unwind_Exception_Class {
// M O Z \0 R U S T -- vendor, language
0x4d4f5a_00_52555354
}
// We could implement our personality routine in pure Rust, however exception
// info decoding is tedious. More importantly, personality routines have to
// handle various platform quirks, which are not fun to maintain. For this
// reason, we attempt to reuse personality routine of the C language:
// __gcc_personality_v0.
//
// Since C does not support exception catching, __gcc_personality_v0 simply
// always returns _URC_CONTINUE_UNWIND in search phase, and always returns
// _URC_INSTALL_CONTEXT (i.e. "invoke cleanup code") in cleanup phase.
//
// This is pretty close to Rust's exception handling approach, except that Rust
// does have a single "catch-all" handler at the bottom of each task's stack.
// So we have two versions:
// - rust_eh_personality, used by all cleanup landing pads, which never catches,
// so the behavior of __gcc_personality_v0 is perfectly adequate there, and
// - rust_eh_personality_catch, used only by rust_try(), which always catches.
// This is achieved by overriding the return value in search phase to always
// say "catch!".
#[cfg(not(target_arch = "arm"), not(test))]
#[doc(hidden)]
#[allow(visible_private_types)]
pub mod eabi {
use uw = rt::libunwind;
use libc::c_int;
extern "C" {
fn __gcc_personality_v0(version: c_int,
actions: uw::_Unwind_Action,
exception_class: uw::_Unwind_Exception_Class,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context)
-> uw::_Unwind_Reason_Code;
}
#[lang="eh_personality"]
#[no_mangle] // so we can reference it by name from middle/trans/base.rs
pub extern "C" fn rust_eh_personality(
version: c_int,
actions: uw::_Unwind_Action,
exception_class: uw::_Unwind_Exception_Class,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context
) -> uw::_Unwind_Reason_Code
{
unsafe {
__gcc_personality_v0(version, actions, exception_class, ue_header,
context)
}
}
#[no_mangle] // referenced from rust_try.ll
pub extern "C" fn rust_eh_personality_catch(
version: c_int,
actions: uw::_Unwind_Action,
exception_class: uw::_Unwind_Exception_Class,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context
) -> uw::_Unwind_Reason_Code
{
if (actions as c_int & uw::_UA_SEARCH_PHASE as c_int)!= 0 { // search phase
uw::_URC_HANDLER_FOUND // catch!
}
else { // cleanup phase
unsafe {
__gcc_personality_v0(version, actions, exception_class, ue_header,
context)
}
}
}
}
// ARM EHABI uses a slightly different personality routine signature,
// but otherwise works the same.
#[cfg(target_arch = "arm", not(test))]
#[allow(visible_private_types)]
pub mod eabi {
use uw = rt::libunwind;
use libc::c_int;
extern "C" {
fn __gcc_personality_v0(state: uw::_Unwind_State,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context)
-> uw::_Unwind_Reason_Code;
}
#[lang="eh_personality"]
#[no_mangle] // so we can reference it by name from middle/trans/base.rs
pub extern "C" fn rust_eh_personality(
state: uw::_Unwind_State,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context
) -> uw::_Unwind_Reason_Code
{
unsafe {
__gcc_personality_v0(state, ue_header, context)
}
}
#[no_mangle] // referenced from rust_try.ll
pub extern "C" fn rust_eh_personality_catch(
state: uw::_Unwind_State,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context
) -> uw::_Unwind_Reason_Code
{
if (state as c_int & uw::_US_ACTION_MASK as c_int)
== uw::_US_VIRTUAL_UNWIND_FRAME as c_int { // search phase
uw::_URC_HANDLER_FOUND // catch!
}
else { // cleanup phase
unsafe {
__gcc_personality_v0(state, ue_header, context)
}
}
}
}
#[cold]
#[lang="fail_"]
#[cfg(not(test))]
pub fn fail_(expr: *u8, file: *u8, line: uint) ->! {
begin_unwind_raw(expr, file, line);
}
#[cold]
#[lang="fail_bounds_check"]
#[cfg(not(test))]
pub fn fail_bounds_check(file: *u8, line: uint, index: uint, len: uint) ->! {
use c_str::ToCStr;
let msg = format!("index out of bounds: the len is {} but the index is {}",
len as uint, index as uint);
msg.with_c_str(|buf| fail_(buf as *u8, file, line))
}
/// This is the entry point of unwinding for things like lang items and such.
/// The arguments are normally generated by the compiler, and need to
/// have static lifetimes.
#[inline(never)] #[cold] // this is the slow path, please never inline this
pub fn begin_unwind_raw(msg: *u8, file: *u8, line: uint) ->! {
use libc::c_char;
#[inline]
fn static_char_ptr(p: *u8) -> &'static str {
let s = unsafe { CString::new(p as *c_char, false) };
match s.as_str() {
Some(s) => unsafe { cast::transmute::<&str, &'static str>(s) },
None => rtabort!("message wasn't utf8?")
}
}
let msg = static_char_ptr(msg);
let file = static_char_ptr(file);
begin_unwind(msg, file, line as uint)
}
/// The entry point for unwinding with a formatted message.
///
/// This is designed to reduce the amount of code required at the call
/// site as much as possible (so that `fail!()` has as low an impact
/// on (e.g.) the inlining of other functions as possible), by moving
/// the actual formatting into this shared place.
#[inline(never)] #[cold]
pub fn begin_unwind_fmt(msg: &fmt::Arguments, file: &'static str, line: uint) ->! {
// We do two allocations here, unfortunately. But (a) they're
// required with the current scheme, and (b) we don't handle
// failure + OOM properly anyway (see comment in begin_unwind
// below).
begin_unwind_inner(~fmt::format(msg), file, line)
}
/// This is the entry point of unwinding for fail!() and assert!().
#[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible
pub fn begin_unwind<M: Any + Send>(msg: M, file: &'static str, line: uint) ->! {
// Note that this should be the only allocation performed in this code path.
// Currently this means that fail!() on OOM will invoke this code path,
// but then again we're not really ready for failing on OOM anyway. If
// we do start doing this, then we should propagate this allocation to
// be performed in the parent of this task instead of the task that's
// failing.
// see below for why we do the `Any` coercion here.
begin_unwind_inner(~msg, file, line)
}
/// The core of the unwinding.
///
/// This is non-generic to avoid instantiation bloat in other crates
/// (which makes compilation of small crates noticably slower). (Note:
/// we need the `Any` object anyway, we're not just creating it to
/// avoid being generic.)
///
/// Do this split took the LLVM IR line counts of `fn main() { fail!()
/// }` from ~1900/3700 (-O/no opts) to 180/590.
#[inline(never)] #[cold] // this is the slow path, please never inline this
fn begin_unwind_inner(msg: ~Any:Send, file: &'static str, line: uint) ->! {
let mut task;
{
let msg_s = match msg.as_ref::<&'static str>() {
Some(s) => *s,
None => match msg.as_ref::<~str>() {
Some(s) => s.as_slice(),
None => "~Any",
}
};
// It is assumed that all reasonable rust code will have a local task at
// all times. This means that this `try_take` will succeed almost all of
// the time. There are border cases, however, when the runtime has
// *almost* set up the local task, but hasn't quite gotten there yet. In
// order to get some better diagnostics, we print on failure and
// immediately abort the whole process if there is no local task
// available.
let opt_task: Option<~Task> = Local::try_take();
task = match opt_task {
Some(t) => t,
None => {
rterrln!("failed at '{}', {}:{}", msg_s, file, line);
if backtrace::log_enabled() {
let mut err = ::rt::util::Stderr;
let _err = backtrace::write(&mut err);
} else {
rterrln!("run with `RUST_BACKTRACE=1` to see a backtrace");
}
unsafe { intrinsics::abort() }
}
};
// See comments in io::stdio::with_task_stdout as to why we have to be
// careful when using an arbitrary I/O handle from the task. We
// essentially need to dance to make sure when a task is in TLS when
// running user code.
let name = task.name.take();
{
let n = name.as_ref().map(|n| n.as_slice()).unwrap_or("<unnamed>");
match task.stderr.take() {
Some(mut stderr) => {
Local::put(task);
// FIXME: what to do when the task printing fails?
let _err = format_args!(|args| ::fmt::writeln(stderr, args),
"task '{}' failed at '{}', {}:{}",
n, msg_s, file, line);
if backtrace::log_enabled() {
let _err = backtrace::write(stderr);
}
task = Local::take();
match mem::replace(&mut task.stderr, Some(stderr)) {
Some(prev) => {
Local::put(task);
drop(prev);
task = Local::take();
}
None => {}
}
}
None => {
rterrln!("task '{}' failed at '{}', {}:{}", n, msg_s,
file, line);
if backtrace::log_enabled() {
let mut err = ::rt::util::Stderr;
let _err = backtrace::write(&mut err);
}
}
}
}
task.name = name;
if task.unwinder.unwinding {
// If a task fails while it's already unwinding then we
// have limited options. Currently our preference is to
// just abort. In the future we may consider resuming
// unwinding or otherwise exiting the task cleanly.
rterrln!("task failed during unwinding (double-failure - total drag!)")
rterrln!("rust must abort now. so sorry.");
// Don't print the backtrace twice (it would have already been
// printed if logging was enabled).
if!backtrace::log_enabled() {
let mut err = ::rt::util::Stderr;
let _err = backtrace::write(&mut err);
}
unsafe { intrinsics::abort() }
}
}
// The unwinder won't actually use the task at all, so we put the task back
// into TLS right before we invoke the unwinder, but this means we need an
// unsafe reference back to the unwinder once it's in TLS.
Local::put(task);
unsafe {
let task: *mut Task = Local::unsafe_borrow();
(*task).unwinder.begin_unwind(msg);
}
} | use libc::{c_void}; | random_line_split |
unwind.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Implementation of Rust stack unwinding
//
// For background on exception handling and stack unwinding please see
// "Exception Handling in LLVM" (llvm.org/docs/ExceptionHandling.html) and
// documents linked from it.
// These are also good reads:
// http://theofilos.cs.columbia.edu/blog/2013/09/22/base_abi/
// http://monoinfinito.wordpress.com/series/exception-handling-in-c/
// http://www.airs.com/blog/index.php?s=exception+frames
//
// ~~~ A brief summary ~~~
// Exception handling happens in two phases: a search phase and a cleanup phase.
//
// In both phases the unwinder walks stack frames from top to bottom using
// information from the stack frame unwind sections of the current process's
// modules ("module" here refers to an OS module, i.e. an executable or a
// dynamic library).
//
// For each stack frame, it invokes the associated "personality routine", whose
// address is also stored in the unwind info section.
//
// In the search phase, the job of a personality routine is to examine exception
// object being thrown, and to decide whether it should be caught at that stack
// frame. Once the handler frame has been identified, cleanup phase begins.
//
// In the cleanup phase, personality routines invoke cleanup code associated
// with their stack frames (i.e. destructors). Once stack has been unwound down
// to the handler frame level, unwinding stops and the last personality routine
// transfers control to its' catch block.
//
// ~~~ Frame unwind info registration ~~~
// Each module has its' own frame unwind info section (usually ".eh_frame"), and
// unwinder needs to know about all of them in order for unwinding to be able to
// cross module boundaries.
//
// On some platforms, like Linux, this is achieved by dynamically enumerating
// currently loaded modules via the dl_iterate_phdr() API and finding all
//.eh_frame sections.
//
// Others, like Windows, require modules to actively register their unwind info
// sections by calling __register_frame_info() API at startup. In the latter
// case it is essential that there is only one copy of the unwinder runtime in
// the process. This is usually achieved by linking to the dynamic version of
// the unwind runtime.
//
// Currently Rust uses unwind runtime provided by libgcc.
use any::{Any, AnyRefExt};
use c_str::CString;
use cast;
use fmt;
use kinds::Send;
use mem;
use option::{Some, None, Option};
use prelude::drop;
use ptr::RawPtr;
use result::{Err, Ok};
use rt::backtrace;
use rt::local::Local;
use rt::task::Task;
use str::Str;
use task::TaskResult;
use intrinsics;
use uw = rt::libunwind;
pub struct Unwinder {
priv unwinding: bool,
priv cause: Option<~Any:Send>
}
impl Unwinder {
pub fn new() -> Unwinder {
Unwinder {
unwinding: false,
cause: None,
}
}
pub fn unwinding(&self) -> bool {
self.unwinding
}
pub fn try(&mut self, f: ||) {
use raw::Closure;
use libc::{c_void};
unsafe {
let closure: Closure = cast::transmute(f);
let ep = rust_try(try_fn, closure.code as *c_void,
closure.env as *c_void);
if!ep.is_null() {
rtdebug!("caught {}", (*ep).exception_class);
uw::_Unwind_DeleteException(ep);
}
}
extern fn | (code: *c_void, env: *c_void) {
unsafe {
let closure: || = cast::transmute(Closure {
code: code as *(),
env: env as *(),
});
closure();
}
}
extern {
// Rust's try-catch
// When f(...) returns normally, the return value is null.
// When f(...) throws, the return value is a pointer to the caught
// exception object.
fn rust_try(f: extern "C" fn(*c_void, *c_void),
code: *c_void,
data: *c_void) -> *uw::_Unwind_Exception;
}
}
pub fn begin_unwind(&mut self, cause: ~Any:Send) ->! {
rtdebug!("begin_unwind()");
self.unwinding = true;
self.cause = Some(cause);
rust_fail();
// An uninlined, unmangled function upon which to slap yer breakpoints
#[inline(never)]
#[no_mangle]
fn rust_fail() ->! {
unsafe {
let exception = ~uw::_Unwind_Exception {
exception_class: rust_exception_class(),
exception_cleanup: exception_cleanup,
private: [0,..uw::unwinder_private_data_size],
};
let error = uw::_Unwind_RaiseException(cast::transmute(exception));
rtabort!("Could not unwind stack, error = {}", error as int)
}
extern "C" fn exception_cleanup(_unwind_code: uw::_Unwind_Reason_Code,
exception: *uw::_Unwind_Exception) {
rtdebug!("exception_cleanup()");
unsafe {
let _: ~uw::_Unwind_Exception = cast::transmute(exception);
}
}
}
}
pub fn result(&mut self) -> TaskResult {
if self.unwinding {
Err(self.cause.take().unwrap())
} else {
Ok(())
}
}
}
// Rust's exception class identifier. This is used by personality routines to
// determine whether the exception was thrown by their own runtime.
fn rust_exception_class() -> uw::_Unwind_Exception_Class {
// M O Z \0 R U S T -- vendor, language
0x4d4f5a_00_52555354
}
// We could implement our personality routine in pure Rust, however exception
// info decoding is tedious. More importantly, personality routines have to
// handle various platform quirks, which are not fun to maintain. For this
// reason, we attempt to reuse personality routine of the C language:
// __gcc_personality_v0.
//
// Since C does not support exception catching, __gcc_personality_v0 simply
// always returns _URC_CONTINUE_UNWIND in search phase, and always returns
// _URC_INSTALL_CONTEXT (i.e. "invoke cleanup code") in cleanup phase.
//
// This is pretty close to Rust's exception handling approach, except that Rust
// does have a single "catch-all" handler at the bottom of each task's stack.
// So we have two versions:
// - rust_eh_personality, used by all cleanup landing pads, which never catches,
// so the behavior of __gcc_personality_v0 is perfectly adequate there, and
// - rust_eh_personality_catch, used only by rust_try(), which always catches.
// This is achieved by overriding the return value in search phase to always
// say "catch!".
#[cfg(not(target_arch = "arm"), not(test))]
#[doc(hidden)]
#[allow(visible_private_types)]
pub mod eabi {
use uw = rt::libunwind;
use libc::c_int;
extern "C" {
fn __gcc_personality_v0(version: c_int,
actions: uw::_Unwind_Action,
exception_class: uw::_Unwind_Exception_Class,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context)
-> uw::_Unwind_Reason_Code;
}
#[lang="eh_personality"]
#[no_mangle] // so we can reference it by name from middle/trans/base.rs
pub extern "C" fn rust_eh_personality(
version: c_int,
actions: uw::_Unwind_Action,
exception_class: uw::_Unwind_Exception_Class,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context
) -> uw::_Unwind_Reason_Code
{
unsafe {
__gcc_personality_v0(version, actions, exception_class, ue_header,
context)
}
}
#[no_mangle] // referenced from rust_try.ll
pub extern "C" fn rust_eh_personality_catch(
version: c_int,
actions: uw::_Unwind_Action,
exception_class: uw::_Unwind_Exception_Class,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context
) -> uw::_Unwind_Reason_Code
{
if (actions as c_int & uw::_UA_SEARCH_PHASE as c_int)!= 0 { // search phase
uw::_URC_HANDLER_FOUND // catch!
}
else { // cleanup phase
unsafe {
__gcc_personality_v0(version, actions, exception_class, ue_header,
context)
}
}
}
}
// ARM EHABI uses a slightly different personality routine signature,
// but otherwise works the same.
#[cfg(target_arch = "arm", not(test))]
#[allow(visible_private_types)]
pub mod eabi {
use uw = rt::libunwind;
use libc::c_int;
extern "C" {
fn __gcc_personality_v0(state: uw::_Unwind_State,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context)
-> uw::_Unwind_Reason_Code;
}
#[lang="eh_personality"]
#[no_mangle] // so we can reference it by name from middle/trans/base.rs
pub extern "C" fn rust_eh_personality(
state: uw::_Unwind_State,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context
) -> uw::_Unwind_Reason_Code
{
unsafe {
__gcc_personality_v0(state, ue_header, context)
}
}
#[no_mangle] // referenced from rust_try.ll
pub extern "C" fn rust_eh_personality_catch(
state: uw::_Unwind_State,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context
) -> uw::_Unwind_Reason_Code
{
if (state as c_int & uw::_US_ACTION_MASK as c_int)
== uw::_US_VIRTUAL_UNWIND_FRAME as c_int { // search phase
uw::_URC_HANDLER_FOUND // catch!
}
else { // cleanup phase
unsafe {
__gcc_personality_v0(state, ue_header, context)
}
}
}
}
#[cold]
#[lang="fail_"]
#[cfg(not(test))]
pub fn fail_(expr: *u8, file: *u8, line: uint) ->! {
begin_unwind_raw(expr, file, line);
}
#[cold]
#[lang="fail_bounds_check"]
#[cfg(not(test))]
pub fn fail_bounds_check(file: *u8, line: uint, index: uint, len: uint) ->! {
use c_str::ToCStr;
let msg = format!("index out of bounds: the len is {} but the index is {}",
len as uint, index as uint);
msg.with_c_str(|buf| fail_(buf as *u8, file, line))
}
/// This is the entry point of unwinding for things like lang items and such.
/// The arguments are normally generated by the compiler, and need to
/// have static lifetimes.
#[inline(never)] #[cold] // this is the slow path, please never inline this
pub fn begin_unwind_raw(msg: *u8, file: *u8, line: uint) ->! {
use libc::c_char;
#[inline]
fn static_char_ptr(p: *u8) -> &'static str {
let s = unsafe { CString::new(p as *c_char, false) };
match s.as_str() {
Some(s) => unsafe { cast::transmute::<&str, &'static str>(s) },
None => rtabort!("message wasn't utf8?")
}
}
let msg = static_char_ptr(msg);
let file = static_char_ptr(file);
begin_unwind(msg, file, line as uint)
}
/// The entry point for unwinding with a formatted message.
///
/// This is designed to reduce the amount of code required at the call
/// site as much as possible (so that `fail!()` has as low an impact
/// on (e.g.) the inlining of other functions as possible), by moving
/// the actual formatting into this shared place.
#[inline(never)] #[cold]
pub fn begin_unwind_fmt(msg: &fmt::Arguments, file: &'static str, line: uint) ->! {
// We do two allocations here, unfortunately. But (a) they're
// required with the current scheme, and (b) we don't handle
// failure + OOM properly anyway (see comment in begin_unwind
// below).
begin_unwind_inner(~fmt::format(msg), file, line)
}
/// This is the entry point of unwinding for fail!() and assert!().
#[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible
pub fn begin_unwind<M: Any + Send>(msg: M, file: &'static str, line: uint) ->! {
// Note that this should be the only allocation performed in this code path.
// Currently this means that fail!() on OOM will invoke this code path,
// but then again we're not really ready for failing on OOM anyway. If
// we do start doing this, then we should propagate this allocation to
// be performed in the parent of this task instead of the task that's
// failing.
// see below for why we do the `Any` coercion here.
begin_unwind_inner(~msg, file, line)
}
/// The core of the unwinding.
///
/// This is non-generic to avoid instantiation bloat in other crates
/// (which makes compilation of small crates noticably slower). (Note:
/// we need the `Any` object anyway, we're not just creating it to
/// avoid being generic.)
///
/// Do this split took the LLVM IR line counts of `fn main() { fail!()
/// }` from ~1900/3700 (-O/no opts) to 180/590.
#[inline(never)] #[cold] // this is the slow path, please never inline this
fn begin_unwind_inner(msg: ~Any:Send, file: &'static str, line: uint) ->! {
let mut task;
{
let msg_s = match msg.as_ref::<&'static str>() {
Some(s) => *s,
None => match msg.as_ref::<~str>() {
Some(s) => s.as_slice(),
None => "~Any",
}
};
// It is assumed that all reasonable rust code will have a local task at
// all times. This means that this `try_take` will succeed almost all of
// the time. There are border cases, however, when the runtime has
// *almost* set up the local task, but hasn't quite gotten there yet. In
// order to get some better diagnostics, we print on failure and
// immediately abort the whole process if there is no local task
// available.
let opt_task: Option<~Task> = Local::try_take();
task = match opt_task {
Some(t) => t,
None => {
rterrln!("failed at '{}', {}:{}", msg_s, file, line);
if backtrace::log_enabled() {
let mut err = ::rt::util::Stderr;
let _err = backtrace::write(&mut err);
} else {
rterrln!("run with `RUST_BACKTRACE=1` to see a backtrace");
}
unsafe { intrinsics::abort() }
}
};
// See comments in io::stdio::with_task_stdout as to why we have to be
// careful when using an arbitrary I/O handle from the task. We
// essentially need to dance to make sure when a task is in TLS when
// running user code.
let name = task.name.take();
{
let n = name.as_ref().map(|n| n.as_slice()).unwrap_or("<unnamed>");
match task.stderr.take() {
Some(mut stderr) => {
Local::put(task);
// FIXME: what to do when the task printing fails?
let _err = format_args!(|args| ::fmt::writeln(stderr, args),
"task '{}' failed at '{}', {}:{}",
n, msg_s, file, line);
if backtrace::log_enabled() {
let _err = backtrace::write(stderr);
}
task = Local::take();
match mem::replace(&mut task.stderr, Some(stderr)) {
Some(prev) => {
Local::put(task);
drop(prev);
task = Local::take();
}
None => {}
}
}
None => {
rterrln!("task '{}' failed at '{}', {}:{}", n, msg_s,
file, line);
if backtrace::log_enabled() {
let mut err = ::rt::util::Stderr;
let _err = backtrace::write(&mut err);
}
}
}
}
task.name = name;
if task.unwinder.unwinding {
// If a task fails while it's already unwinding then we
// have limited options. Currently our preference is to
// just abort. In the future we may consider resuming
// unwinding or otherwise exiting the task cleanly.
rterrln!("task failed during unwinding (double-failure - total drag!)")
rterrln!("rust must abort now. so sorry.");
// Don't print the backtrace twice (it would have already been
// printed if logging was enabled).
if!backtrace::log_enabled() {
let mut err = ::rt::util::Stderr;
let _err = backtrace::write(&mut err);
}
unsafe { intrinsics::abort() }
}
}
// The unwinder won't actually use the task at all, so we put the task back
// into TLS right before we invoke the unwinder, but this means we need an
// unsafe reference back to the unwinder once it's in TLS.
Local::put(task);
unsafe {
let task: *mut Task = Local::unsafe_borrow();
(*task).unwinder.begin_unwind(msg);
}
}
| try_fn | identifier_name |
unwind.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Implementation of Rust stack unwinding
//
// For background on exception handling and stack unwinding please see
// "Exception Handling in LLVM" (llvm.org/docs/ExceptionHandling.html) and
// documents linked from it.
// These are also good reads:
// http://theofilos.cs.columbia.edu/blog/2013/09/22/base_abi/
// http://monoinfinito.wordpress.com/series/exception-handling-in-c/
// http://www.airs.com/blog/index.php?s=exception+frames
//
// ~~~ A brief summary ~~~
// Exception handling happens in two phases: a search phase and a cleanup phase.
//
// In both phases the unwinder walks stack frames from top to bottom using
// information from the stack frame unwind sections of the current process's
// modules ("module" here refers to an OS module, i.e. an executable or a
// dynamic library).
//
// For each stack frame, it invokes the associated "personality routine", whose
// address is also stored in the unwind info section.
//
// In the search phase, the job of a personality routine is to examine exception
// object being thrown, and to decide whether it should be caught at that stack
// frame. Once the handler frame has been identified, cleanup phase begins.
//
// In the cleanup phase, personality routines invoke cleanup code associated
// with their stack frames (i.e. destructors). Once stack has been unwound down
// to the handler frame level, unwinding stops and the last personality routine
// transfers control to its' catch block.
//
// ~~~ Frame unwind info registration ~~~
// Each module has its' own frame unwind info section (usually ".eh_frame"), and
// unwinder needs to know about all of them in order for unwinding to be able to
// cross module boundaries.
//
// On some platforms, like Linux, this is achieved by dynamically enumerating
// currently loaded modules via the dl_iterate_phdr() API and finding all
//.eh_frame sections.
//
// Others, like Windows, require modules to actively register their unwind info
// sections by calling __register_frame_info() API at startup. In the latter
// case it is essential that there is only one copy of the unwinder runtime in
// the process. This is usually achieved by linking to the dynamic version of
// the unwind runtime.
//
// Currently Rust uses unwind runtime provided by libgcc.
use any::{Any, AnyRefExt};
use c_str::CString;
use cast;
use fmt;
use kinds::Send;
use mem;
use option::{Some, None, Option};
use prelude::drop;
use ptr::RawPtr;
use result::{Err, Ok};
use rt::backtrace;
use rt::local::Local;
use rt::task::Task;
use str::Str;
use task::TaskResult;
use intrinsics;
use uw = rt::libunwind;
pub struct Unwinder {
priv unwinding: bool,
priv cause: Option<~Any:Send>
}
impl Unwinder {
pub fn new() -> Unwinder {
Unwinder {
unwinding: false,
cause: None,
}
}
pub fn unwinding(&self) -> bool {
self.unwinding
}
pub fn try(&mut self, f: ||) {
use raw::Closure;
use libc::{c_void};
unsafe {
let closure: Closure = cast::transmute(f);
let ep = rust_try(try_fn, closure.code as *c_void,
closure.env as *c_void);
if!ep.is_null() {
rtdebug!("caught {}", (*ep).exception_class);
uw::_Unwind_DeleteException(ep);
}
}
extern fn try_fn(code: *c_void, env: *c_void) {
unsafe {
let closure: || = cast::transmute(Closure {
code: code as *(),
env: env as *(),
});
closure();
}
}
extern {
// Rust's try-catch
// When f(...) returns normally, the return value is null.
// When f(...) throws, the return value is a pointer to the caught
// exception object.
fn rust_try(f: extern "C" fn(*c_void, *c_void),
code: *c_void,
data: *c_void) -> *uw::_Unwind_Exception;
}
}
pub fn begin_unwind(&mut self, cause: ~Any:Send) ->! | }
extern "C" fn exception_cleanup(_unwind_code: uw::_Unwind_Reason_Code,
exception: *uw::_Unwind_Exception) {
rtdebug!("exception_cleanup()");
unsafe {
let _: ~uw::_Unwind_Exception = cast::transmute(exception);
}
}
}
}
pub fn result(&mut self) -> TaskResult {
if self.unwinding {
Err(self.cause.take().unwrap())
} else {
Ok(())
}
}
}
// Rust's exception class identifier. This is used by personality routines to
// determine whether the exception was thrown by their own runtime.
fn rust_exception_class() -> uw::_Unwind_Exception_Class {
// M O Z \0 R U S T -- vendor, language
0x4d4f5a_00_52555354
}
// We could implement our personality routine in pure Rust, however exception
// info decoding is tedious. More importantly, personality routines have to
// handle various platform quirks, which are not fun to maintain. For this
// reason, we attempt to reuse personality routine of the C language:
// __gcc_personality_v0.
//
// Since C does not support exception catching, __gcc_personality_v0 simply
// always returns _URC_CONTINUE_UNWIND in search phase, and always returns
// _URC_INSTALL_CONTEXT (i.e. "invoke cleanup code") in cleanup phase.
//
// This is pretty close to Rust's exception handling approach, except that Rust
// does have a single "catch-all" handler at the bottom of each task's stack.
// So we have two versions:
// - rust_eh_personality, used by all cleanup landing pads, which never catches,
// so the behavior of __gcc_personality_v0 is perfectly adequate there, and
// - rust_eh_personality_catch, used only by rust_try(), which always catches.
// This is achieved by overriding the return value in search phase to always
// say "catch!".
#[cfg(not(target_arch = "arm"), not(test))]
#[doc(hidden)]
#[allow(visible_private_types)]
pub mod eabi {
use uw = rt::libunwind;
use libc::c_int;
extern "C" {
fn __gcc_personality_v0(version: c_int,
actions: uw::_Unwind_Action,
exception_class: uw::_Unwind_Exception_Class,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context)
-> uw::_Unwind_Reason_Code;
}
#[lang="eh_personality"]
#[no_mangle] // so we can reference it by name from middle/trans/base.rs
pub extern "C" fn rust_eh_personality(
version: c_int,
actions: uw::_Unwind_Action,
exception_class: uw::_Unwind_Exception_Class,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context
) -> uw::_Unwind_Reason_Code
{
unsafe {
__gcc_personality_v0(version, actions, exception_class, ue_header,
context)
}
}
#[no_mangle] // referenced from rust_try.ll
pub extern "C" fn rust_eh_personality_catch(
version: c_int,
actions: uw::_Unwind_Action,
exception_class: uw::_Unwind_Exception_Class,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context
) -> uw::_Unwind_Reason_Code
{
if (actions as c_int & uw::_UA_SEARCH_PHASE as c_int)!= 0 { // search phase
uw::_URC_HANDLER_FOUND // catch!
}
else { // cleanup phase
unsafe {
__gcc_personality_v0(version, actions, exception_class, ue_header,
context)
}
}
}
}
// ARM EHABI uses a slightly different personality routine signature,
// but otherwise works the same.
#[cfg(target_arch = "arm", not(test))]
#[allow(visible_private_types)]
pub mod eabi {
use uw = rt::libunwind;
use libc::c_int;
extern "C" {
fn __gcc_personality_v0(state: uw::_Unwind_State,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context)
-> uw::_Unwind_Reason_Code;
}
#[lang="eh_personality"]
#[no_mangle] // so we can reference it by name from middle/trans/base.rs
pub extern "C" fn rust_eh_personality(
state: uw::_Unwind_State,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context
) -> uw::_Unwind_Reason_Code
{
unsafe {
__gcc_personality_v0(state, ue_header, context)
}
}
#[no_mangle] // referenced from rust_try.ll
pub extern "C" fn rust_eh_personality_catch(
state: uw::_Unwind_State,
ue_header: *uw::_Unwind_Exception,
context: *uw::_Unwind_Context
) -> uw::_Unwind_Reason_Code
{
if (state as c_int & uw::_US_ACTION_MASK as c_int)
== uw::_US_VIRTUAL_UNWIND_FRAME as c_int { // search phase
uw::_URC_HANDLER_FOUND // catch!
}
else { // cleanup phase
unsafe {
__gcc_personality_v0(state, ue_header, context)
}
}
}
}
#[cold]
#[lang="fail_"]
#[cfg(not(test))]
pub fn fail_(expr: *u8, file: *u8, line: uint) ->! {
begin_unwind_raw(expr, file, line);
}
#[cold]
#[lang="fail_bounds_check"]
#[cfg(not(test))]
pub fn fail_bounds_check(file: *u8, line: uint, index: uint, len: uint) ->! {
use c_str::ToCStr;
let msg = format!("index out of bounds: the len is {} but the index is {}",
len as uint, index as uint);
msg.with_c_str(|buf| fail_(buf as *u8, file, line))
}
/// This is the entry point of unwinding for things like lang items and such.
/// The arguments are normally generated by the compiler, and need to
/// have static lifetimes.
#[inline(never)] #[cold] // this is the slow path, please never inline this
pub fn begin_unwind_raw(msg: *u8, file: *u8, line: uint) ->! {
use libc::c_char;
#[inline]
fn static_char_ptr(p: *u8) -> &'static str {
let s = unsafe { CString::new(p as *c_char, false) };
match s.as_str() {
Some(s) => unsafe { cast::transmute::<&str, &'static str>(s) },
None => rtabort!("message wasn't utf8?")
}
}
let msg = static_char_ptr(msg);
let file = static_char_ptr(file);
begin_unwind(msg, file, line as uint)
}
/// The entry point for unwinding with a formatted message.
///
/// This is designed to reduce the amount of code required at the call
/// site as much as possible (so that `fail!()` has as low an impact
/// on (e.g.) the inlining of other functions as possible), by moving
/// the actual formatting into this shared place.
#[inline(never)] #[cold]
pub fn begin_unwind_fmt(msg: &fmt::Arguments, file: &'static str, line: uint) ->! {
// We do two allocations here, unfortunately. But (a) they're
// required with the current scheme, and (b) we don't handle
// failure + OOM properly anyway (see comment in begin_unwind
// below).
begin_unwind_inner(~fmt::format(msg), file, line)
}
/// This is the entry point of unwinding for fail!() and assert!().
#[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible
pub fn begin_unwind<M: Any + Send>(msg: M, file: &'static str, line: uint) ->! {
// Note that this should be the only allocation performed in this code path.
// Currently this means that fail!() on OOM will invoke this code path,
// but then again we're not really ready for failing on OOM anyway. If
// we do start doing this, then we should propagate this allocation to
// be performed in the parent of this task instead of the task that's
// failing.
// see below for why we do the `Any` coercion here.
begin_unwind_inner(~msg, file, line)
}
/// The core of the unwinding.
///
/// This is non-generic to avoid instantiation bloat in other crates
/// (which makes compilation of small crates noticably slower). (Note:
/// we need the `Any` object anyway, we're not just creating it to
/// avoid being generic.)
///
/// Do this split took the LLVM IR line counts of `fn main() { fail!()
/// }` from ~1900/3700 (-O/no opts) to 180/590.
#[inline(never)] #[cold] // this is the slow path, please never inline this
fn begin_unwind_inner(msg: ~Any:Send, file: &'static str, line: uint) ->! {
let mut task;
{
let msg_s = match msg.as_ref::<&'static str>() {
Some(s) => *s,
None => match msg.as_ref::<~str>() {
Some(s) => s.as_slice(),
None => "~Any",
}
};
// It is assumed that all reasonable rust code will have a local task at
// all times. This means that this `try_take` will succeed almost all of
// the time. There are border cases, however, when the runtime has
// *almost* set up the local task, but hasn't quite gotten there yet. In
// order to get some better diagnostics, we print on failure and
// immediately abort the whole process if there is no local task
// available.
let opt_task: Option<~Task> = Local::try_take();
task = match opt_task {
Some(t) => t,
None => {
rterrln!("failed at '{}', {}:{}", msg_s, file, line);
if backtrace::log_enabled() {
let mut err = ::rt::util::Stderr;
let _err = backtrace::write(&mut err);
} else {
rterrln!("run with `RUST_BACKTRACE=1` to see a backtrace");
}
unsafe { intrinsics::abort() }
}
};
// See comments in io::stdio::with_task_stdout as to why we have to be
// careful when using an arbitrary I/O handle from the task. We
// essentially need to dance to make sure when a task is in TLS when
// running user code.
let name = task.name.take();
{
let n = name.as_ref().map(|n| n.as_slice()).unwrap_or("<unnamed>");
match task.stderr.take() {
Some(mut stderr) => {
Local::put(task);
// FIXME: what to do when the task printing fails?
let _err = format_args!(|args| ::fmt::writeln(stderr, args),
"task '{}' failed at '{}', {}:{}",
n, msg_s, file, line);
if backtrace::log_enabled() {
let _err = backtrace::write(stderr);
}
task = Local::take();
match mem::replace(&mut task.stderr, Some(stderr)) {
Some(prev) => {
Local::put(task);
drop(prev);
task = Local::take();
}
None => {}
}
}
None => {
rterrln!("task '{}' failed at '{}', {}:{}", n, msg_s,
file, line);
if backtrace::log_enabled() {
let mut err = ::rt::util::Stderr;
let _err = backtrace::write(&mut err);
}
}
}
}
task.name = name;
if task.unwinder.unwinding {
// If a task fails while it's already unwinding then we
// have limited options. Currently our preference is to
// just abort. In the future we may consider resuming
// unwinding or otherwise exiting the task cleanly.
rterrln!("task failed during unwinding (double-failure - total drag!)")
rterrln!("rust must abort now. so sorry.");
// Don't print the backtrace twice (it would have already been
// printed if logging was enabled).
if!backtrace::log_enabled() {
let mut err = ::rt::util::Stderr;
let _err = backtrace::write(&mut err);
}
unsafe { intrinsics::abort() }
}
}
// The unwinder won't actually use the task at all, so we put the task back
// into TLS right before we invoke the unwinder, but this means we need an
// unsafe reference back to the unwinder once it's in TLS.
Local::put(task);
unsafe {
let task: *mut Task = Local::unsafe_borrow();
(*task).unwinder.begin_unwind(msg);
}
}
| {
rtdebug!("begin_unwind()");
self.unwinding = true;
self.cause = Some(cause);
rust_fail();
// An uninlined, unmangled function upon which to slap yer breakpoints
#[inline(never)]
#[no_mangle]
fn rust_fail() -> ! {
unsafe {
let exception = ~uw::_Unwind_Exception {
exception_class: rust_exception_class(),
exception_cleanup: exception_cleanup,
private: [0, ..uw::unwinder_private_data_size],
};
let error = uw::_Unwind_RaiseException(cast::transmute(exception));
rtabort!("Could not unwind stack, error = {}", error as int) | identifier_body |
addresses.rs | use postgres;
use ipm::PostgresReqExt;
use rustc_serialize::json::{Json, ToJson};
#[derive(ToJson)]
pub struct Address {
address_id: i32,
address: String,
postal_code: String,
city: String,
state: String,
country: String,
geospot: Json | pub fn get_by_contact_id(req: &PostgresReqExt, contact_id: i32) -> Vec<Address> {
let mut vec = Vec::new();
let conn = req.db_conn();
let stmt = conn.prepare(
"SELECT * FROM addresses a \
WHERE EXISTS(SELECT * \
FROM many_contacts_has_many_addresses b \
WHERE b.address_id_addresses=a.address_id \
AND b.contact_id_contacts=$1) "
).unwrap();
let rows = stmt.query(&[&contact_id]).unwrap();
for row in rows {
vec.push(Address {
address_id: row.get(0),
address: row.get(1),
postal_code: row.get(2),
city: row.get(3),
state: row.get(4),
country: row.get(5),
geospot: row.get(6)
});
}
vec
}
pub fn commit(&self, req: &PostgresReqExt) -> postgres::Result<u64> {
let conn = req.db_conn();
//TODO: trigger for INSERT or UPDATE to remove duplicates.
// if address_id is 0, then INSERT else UPDATE.
conn.execute(
"INSERT INTO addresses \
VALUES($1, $2, $3, $4, $5, $6, $7) ",
&[&self.address_id,
&self.address,
&self.postal_code,
&self.city,
&self.state,
&self.country,
&self.geospot
])
}
} | }
impl Address { | random_line_split |
addresses.rs |
use postgres;
use ipm::PostgresReqExt;
use rustc_serialize::json::{Json, ToJson};
#[derive(ToJson)]
pub struct Address {
address_id: i32,
address: String,
postal_code: String,
city: String,
state: String,
country: String,
geospot: Json
}
impl Address {
pub fn get_by_contact_id(req: &PostgresReqExt, contact_id: i32) -> Vec<Address> {
let mut vec = Vec::new();
let conn = req.db_conn();
let stmt = conn.prepare(
"SELECT * FROM addresses a \
WHERE EXISTS(SELECT * \
FROM many_contacts_has_many_addresses b \
WHERE b.address_id_addresses=a.address_id \
AND b.contact_id_contacts=$1) "
).unwrap();
let rows = stmt.query(&[&contact_id]).unwrap();
for row in rows {
vec.push(Address {
address_id: row.get(0),
address: row.get(1),
postal_code: row.get(2),
city: row.get(3),
state: row.get(4),
country: row.get(5),
geospot: row.get(6)
});
}
vec
}
pub fn | (&self, req: &PostgresReqExt) -> postgres::Result<u64> {
let conn = req.db_conn();
//TODO: trigger for INSERT or UPDATE to remove duplicates.
// if address_id is 0, then INSERT else UPDATE.
conn.execute(
"INSERT INTO addresses \
VALUES($1, $2, $3, $4, $5, $6, $7) ",
&[&self.address_id,
&self.address,
&self.postal_code,
&self.city,
&self.state,
&self.country,
&self.geospot
])
}
}
| commit | identifier_name |
fuse.rs | use core::pin::Pin;
use futures_core::stream::{FusedStream, Stream};
use futures_core::task::{Context, Poll};
#[cfg(feature = "sink")]
use futures_sink::Sink;
use pin_utils::{unsafe_pinned, unsafe_unpinned};
/// Stream for the [`fuse`](super::StreamExt::fuse) method.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Fuse<St> {
stream: St,
done: bool,
}
impl<St: Unpin> Unpin for Fuse<St> {}
impl<St> Fuse<St> {
unsafe_pinned!(stream: St);
unsafe_unpinned!(done: bool);
pub(super) fn new(stream: St) -> Fuse<St> {
Fuse { stream, done: false }
}
/// Returns whether the underlying stream has finished or not.
///
/// If this method returns `true`, then all future calls to poll are
/// guaranteed to return `None`. If this returns `false`, then the
/// underlying stream is still in use.
pub fn is_done(&self) -> bool {
self.done
}
/// Acquires a reference to the underlying stream that this combinator is
/// pulling from.
pub fn get_ref(&self) -> &St {
&self.stream
}
/// Acquires a mutable reference to the underlying stream that this
/// combinator is pulling from.
///
/// Note that care must be taken to avoid tampering with the state of the
/// stream which may otherwise confuse this combinator.
pub fn get_mut(&mut self) -> &mut St {
&mut self.stream
}
/// Acquires a pinned mutable reference to the underlying stream that this
/// combinator is pulling from.
///
/// Note that care must be taken to avoid tampering with the state of the
/// stream which may otherwise confuse this combinator.
pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut St> {
self.stream()
}
/// Consumes this combinator, returning the underlying stream.
///
/// Note that this may discard intermediate state of this combinator, so
/// care should be taken to avoid losing resources when this is called.
pub fn into_inner(self) -> St {
self.stream
}
}
impl<S: Stream> FusedStream for Fuse<S> {
fn is_terminated(&self) -> bool {
self.done
}
}
impl<S: Stream> Stream for Fuse<S> {
type Item = S::Item;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<S::Item>> {
if self.done {
return Poll::Ready(None);
}
let item = ready!(self.as_mut().stream().poll_next(cx));
if item.is_none() {
*self.as_mut().done() = true;
}
Poll::Ready(item)
}
fn | (&self) -> (usize, Option<usize>) {
if self.done {
(0, Some(0))
} else {
self.stream.size_hint()
}
}
}
// Forwarding impl of Sink from the underlying stream
#[cfg(feature = "sink")]
impl<S: Stream + Sink<Item>, Item> Sink<Item> for Fuse<S> {
type Error = S::Error;
delegate_sink!(stream, Item);
}
| size_hint | identifier_name |
fuse.rs | use core::pin::Pin;
use futures_core::stream::{FusedStream, Stream};
use futures_core::task::{Context, Poll};
#[cfg(feature = "sink")]
use futures_sink::Sink;
use pin_utils::{unsafe_pinned, unsafe_unpinned};
/// Stream for the [`fuse`](super::StreamExt::fuse) method.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Fuse<St> {
stream: St,
done: bool,
}
impl<St: Unpin> Unpin for Fuse<St> {}
impl<St> Fuse<St> {
unsafe_pinned!(stream: St);
unsafe_unpinned!(done: bool);
pub(super) fn new(stream: St) -> Fuse<St> {
Fuse { stream, done: false }
}
/// Returns whether the underlying stream has finished or not.
///
/// If this method returns `true`, then all future calls to poll are
/// guaranteed to return `None`. If this returns `false`, then the
/// underlying stream is still in use.
pub fn is_done(&self) -> bool {
self.done
}
/// Acquires a reference to the underlying stream that this combinator is
/// pulling from.
pub fn get_ref(&self) -> &St {
&self.stream
}
/// Acquires a mutable reference to the underlying stream that this
/// combinator is pulling from.
///
/// Note that care must be taken to avoid tampering with the state of the
/// stream which may otherwise confuse this combinator.
pub fn get_mut(&mut self) -> &mut St |
/// Acquires a pinned mutable reference to the underlying stream that this
/// combinator is pulling from.
///
/// Note that care must be taken to avoid tampering with the state of the
/// stream which may otherwise confuse this combinator.
pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut St> {
self.stream()
}
/// Consumes this combinator, returning the underlying stream.
///
/// Note that this may discard intermediate state of this combinator, so
/// care should be taken to avoid losing resources when this is called.
pub fn into_inner(self) -> St {
self.stream
}
}
impl<S: Stream> FusedStream for Fuse<S> {
fn is_terminated(&self) -> bool {
self.done
}
}
impl<S: Stream> Stream for Fuse<S> {
type Item = S::Item;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<S::Item>> {
if self.done {
return Poll::Ready(None);
}
let item = ready!(self.as_mut().stream().poll_next(cx));
if item.is_none() {
*self.as_mut().done() = true;
}
Poll::Ready(item)
}
fn size_hint(&self) -> (usize, Option<usize>) {
if self.done {
(0, Some(0))
} else {
self.stream.size_hint()
}
}
}
// Forwarding impl of Sink from the underlying stream
#[cfg(feature = "sink")]
impl<S: Stream + Sink<Item>, Item> Sink<Item> for Fuse<S> {
type Error = S::Error;
delegate_sink!(stream, Item);
}
| {
&mut self.stream
} | identifier_body |
fuse.rs | use core::pin::Pin;
use futures_core::stream::{FusedStream, Stream};
use futures_core::task::{Context, Poll};
#[cfg(feature = "sink")]
use futures_sink::Sink;
use pin_utils::{unsafe_pinned, unsafe_unpinned};
/// Stream for the [`fuse`](super::StreamExt::fuse) method.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Fuse<St> {
stream: St,
done: bool,
}
impl<St: Unpin> Unpin for Fuse<St> {}
impl<St> Fuse<St> {
unsafe_pinned!(stream: St);
unsafe_unpinned!(done: bool);
pub(super) fn new(stream: St) -> Fuse<St> {
Fuse { stream, done: false }
}
/// Returns whether the underlying stream has finished or not.
///
/// If this method returns `true`, then all future calls to poll are
/// guaranteed to return `None`. If this returns `false`, then the
/// underlying stream is still in use.
pub fn is_done(&self) -> bool {
self.done
}
/// Acquires a reference to the underlying stream that this combinator is
/// pulling from.
pub fn get_ref(&self) -> &St {
&self.stream
}
/// Acquires a mutable reference to the underlying stream that this
/// combinator is pulling from.
///
/// Note that care must be taken to avoid tampering with the state of the
/// stream which may otherwise confuse this combinator.
pub fn get_mut(&mut self) -> &mut St {
&mut self.stream
}
/// Acquires a pinned mutable reference to the underlying stream that this
/// combinator is pulling from.
///
/// Note that care must be taken to avoid tampering with the state of the
/// stream which may otherwise confuse this combinator.
pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut St> {
self.stream()
}
/// Consumes this combinator, returning the underlying stream.
///
/// Note that this may discard intermediate state of this combinator, so
/// care should be taken to avoid losing resources when this is called.
pub fn into_inner(self) -> St {
self.stream
}
}
impl<S: Stream> FusedStream for Fuse<S> {
fn is_terminated(&self) -> bool {
self.done
}
}
impl<S: Stream> Stream for Fuse<S> {
type Item = S::Item;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<S::Item>> {
if self.done {
return Poll::Ready(None);
}
let item = ready!(self.as_mut().stream().poll_next(cx));
if item.is_none() {
*self.as_mut().done() = true;
}
Poll::Ready(item)
}
fn size_hint(&self) -> (usize, Option<usize>) {
if self.done | else {
self.stream.size_hint()
}
}
}
// Forwarding impl of Sink from the underlying stream
#[cfg(feature = "sink")]
impl<S: Stream + Sink<Item>, Item> Sink<Item> for Fuse<S> {
type Error = S::Error;
delegate_sink!(stream, Item);
}
| {
(0, Some(0))
} | conditional_block |
fuse.rs | use core::pin::Pin;
use futures_core::stream::{FusedStream, Stream};
use futures_core::task::{Context, Poll};
#[cfg(feature = "sink")]
use futures_sink::Sink;
use pin_utils::{unsafe_pinned, unsafe_unpinned};
/// Stream for the [`fuse`](super::StreamExt::fuse) method.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Fuse<St> {
stream: St,
done: bool,
}
impl<St: Unpin> Unpin for Fuse<St> {} | impl<St> Fuse<St> {
unsafe_pinned!(stream: St);
unsafe_unpinned!(done: bool);
pub(super) fn new(stream: St) -> Fuse<St> {
Fuse { stream, done: false }
}
/// Returns whether the underlying stream has finished or not.
///
/// If this method returns `true`, then all future calls to poll are
/// guaranteed to return `None`. If this returns `false`, then the
/// underlying stream is still in use.
pub fn is_done(&self) -> bool {
self.done
}
/// Acquires a reference to the underlying stream that this combinator is
/// pulling from.
pub fn get_ref(&self) -> &St {
&self.stream
}
/// Acquires a mutable reference to the underlying stream that this
/// combinator is pulling from.
///
/// Note that care must be taken to avoid tampering with the state of the
/// stream which may otherwise confuse this combinator.
pub fn get_mut(&mut self) -> &mut St {
&mut self.stream
}
/// Acquires a pinned mutable reference to the underlying stream that this
/// combinator is pulling from.
///
/// Note that care must be taken to avoid tampering with the state of the
/// stream which may otherwise confuse this combinator.
pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut St> {
self.stream()
}
/// Consumes this combinator, returning the underlying stream.
///
/// Note that this may discard intermediate state of this combinator, so
/// care should be taken to avoid losing resources when this is called.
pub fn into_inner(self) -> St {
self.stream
}
}
impl<S: Stream> FusedStream for Fuse<S> {
fn is_terminated(&self) -> bool {
self.done
}
}
impl<S: Stream> Stream for Fuse<S> {
type Item = S::Item;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<S::Item>> {
if self.done {
return Poll::Ready(None);
}
let item = ready!(self.as_mut().stream().poll_next(cx));
if item.is_none() {
*self.as_mut().done() = true;
}
Poll::Ready(item)
}
fn size_hint(&self) -> (usize, Option<usize>) {
if self.done {
(0, Some(0))
} else {
self.stream.size_hint()
}
}
}
// Forwarding impl of Sink from the underlying stream
#[cfg(feature = "sink")]
impl<S: Stream + Sink<Item>, Item> Sink<Item> for Fuse<S> {
type Error = S::Error;
delegate_sink!(stream, Item);
} | random_line_split |
|
server.rs | use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::env;
use std::thread;
fn main() {
let args: Vec<String> = env::args().map(|x| x.to_string())
.collect();
let program = &args[0];
if args.len()!= 3 {
print_usage(program);
return;
}
let address = &args[1];
let port = &args[2];
let connection_string = format!("{}:{}", address, port);
start_server(&connection_string);
}
fn start_server(addr: &str) {
let listener = match TcpListener::bind(addr) {
Ok(listener) => {
listener
}
Err(e) => {
println!("Error creating TCP Connection listener: {}", e);
return;
}
};
fn handle_client(mut stream: TcpStream) {
let mut buf = [0u8; 128];
// we could use read_to_end into vector and then write_all
// instead of repeated read / writes but creating heap
// based vector for each connection feels like an overkill
loop {
// read some incoming bytes into buffer
let read_bytes = match stream.read(&mut buf) {
Ok(bytes) => bytes,
Err(e) => {
println!("Error reading the input: {}", e);
return;
}
};
// if nothing was read, bail out
if read_bytes == 0 {
break;
} | Ok(_) => { /* the operation has succeed */ }
Err(e) => {
println!("Error echoing back: {}", e);
return;
}
};
}
}
// accept connections and process them, spawning a new thread for each one
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(move|| {
// connection succeeded
handle_client(stream)
});
}
Err(e) => {
println!("Failed to accept connection: {}", e);
return;
}
}
}
}
fn print_usage(program: &str) {
println!("Usage: {} <address> <port>", program);
} |
// echo incoming bytes back
match stream.write(&mut buf) { | random_line_split |
server.rs | use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::env;
use std::thread;
fn main() |
fn start_server(addr: &str) {
let listener = match TcpListener::bind(addr) {
Ok(listener) => {
listener
}
Err(e) => {
println!("Error creating TCP Connection listener: {}", e);
return;
}
};
fn handle_client(mut stream: TcpStream) {
let mut buf = [0u8; 128];
// we could use read_to_end into vector and then write_all
// instead of repeated read / writes but creating heap
// based vector for each connection feels like an overkill
loop {
// read some incoming bytes into buffer
let read_bytes = match stream.read(&mut buf) {
Ok(bytes) => bytes,
Err(e) => {
println!("Error reading the input: {}", e);
return;
}
};
// if nothing was read, bail out
if read_bytes == 0 {
break;
}
// echo incoming bytes back
match stream.write(&mut buf) {
Ok(_) => { /* the operation has succeed */ }
Err(e) => {
println!("Error echoing back: {}", e);
return;
}
};
}
}
// accept connections and process them, spawning a new thread for each one
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(move|| {
// connection succeeded
handle_client(stream)
});
}
Err(e) => {
println!("Failed to accept connection: {}", e);
return;
}
}
}
}
fn print_usage(program: &str) {
println!("Usage: {} <address> <port>", program);
}
| {
let args: Vec<String> = env::args().map(|x| x.to_string())
.collect();
let program = &args[0];
if args.len() != 3 {
print_usage(program);
return;
}
let address = &args[1];
let port = &args[2];
let connection_string = format!("{}:{}", address, port);
start_server(&connection_string);
} | identifier_body |
server.rs | use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::env;
use std::thread;
fn main() {
let args: Vec<String> = env::args().map(|x| x.to_string())
.collect();
let program = &args[0];
if args.len()!= 3 {
print_usage(program);
return;
}
let address = &args[1];
let port = &args[2];
let connection_string = format!("{}:{}", address, port);
start_server(&connection_string);
}
fn start_server(addr: &str) {
let listener = match TcpListener::bind(addr) {
Ok(listener) => {
listener
}
Err(e) => {
println!("Error creating TCP Connection listener: {}", e);
return;
}
};
fn | (mut stream: TcpStream) {
let mut buf = [0u8; 128];
// we could use read_to_end into vector and then write_all
// instead of repeated read / writes but creating heap
// based vector for each connection feels like an overkill
loop {
// read some incoming bytes into buffer
let read_bytes = match stream.read(&mut buf) {
Ok(bytes) => bytes,
Err(e) => {
println!("Error reading the input: {}", e);
return;
}
};
// if nothing was read, bail out
if read_bytes == 0 {
break;
}
// echo incoming bytes back
match stream.write(&mut buf) {
Ok(_) => { /* the operation has succeed */ }
Err(e) => {
println!("Error echoing back: {}", e);
return;
}
};
}
}
// accept connections and process them, spawning a new thread for each one
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(move|| {
// connection succeeded
handle_client(stream)
});
}
Err(e) => {
println!("Failed to accept connection: {}", e);
return;
}
}
}
}
fn print_usage(program: &str) {
println!("Usage: {} <address> <port>", program);
}
| handle_client | identifier_name |
server.rs | use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::env;
use std::thread;
fn main() {
let args: Vec<String> = env::args().map(|x| x.to_string())
.collect();
let program = &args[0];
if args.len()!= 3 {
print_usage(program);
return;
}
let address = &args[1];
let port = &args[2];
let connection_string = format!("{}:{}", address, port);
start_server(&connection_string);
}
fn start_server(addr: &str) {
let listener = match TcpListener::bind(addr) {
Ok(listener) => {
listener
}
Err(e) => {
println!("Error creating TCP Connection listener: {}", e);
return;
}
};
fn handle_client(mut stream: TcpStream) {
let mut buf = [0u8; 128];
// we could use read_to_end into vector and then write_all
// instead of repeated read / writes but creating heap
// based vector for each connection feels like an overkill
loop {
// read some incoming bytes into buffer
let read_bytes = match stream.read(&mut buf) {
Ok(bytes) => bytes,
Err(e) => {
println!("Error reading the input: {}", e);
return;
}
};
// if nothing was read, bail out
if read_bytes == 0 {
break;
}
// echo incoming bytes back
match stream.write(&mut buf) {
Ok(_) => { /* the operation has succeed */ }
Err(e) => {
println!("Error echoing back: {}", e);
return;
}
};
}
}
// accept connections and process them, spawning a new thread for each one
for stream in listener.incoming() {
match stream {
Ok(stream) => |
Err(e) => {
println!("Failed to accept connection: {}", e);
return;
}
}
}
}
fn print_usage(program: &str) {
println!("Usage: {} <address> <port>", program);
}
| {
thread::spawn(move|| {
// connection succeeded
handle_client(stream)
});
} | conditional_block |
p12.rs | use rand::{Rng, weak_rng};
use serialize::base64::FromBase64;
use ssl::symm::{self, encrypt};
fn | (input: &[u8], unknown: &[u8], key: &[u8]) -> Vec<u8> {
let mut data: Vec<u8> = Vec::with_capacity(input.len() + unknown.len());
data.extend_from_slice(input);
data.extend_from_slice(unknown);
encrypt(symm::Cipher::aes_128_ecb(), key, None, &data).unwrap()
}
#[test]
fn run() {
// unknown text we will attempt to decode with attacker controlled input
// to the encryption oracle
let unknown = "Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg\
aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq\
dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg\
YnkK".from_base64().unwrap();
let mut rng = weak_rng();
let mut key = [0_u8; 16];
rng.fill_bytes(&mut key);
// Determine blocksize
let mut i = 1;
let blocksize;
loop {
let input = vec!['A' as u8; 2*i];
let out = encryption_oracle(&input, &unknown, &key);
let block1 = &out[0..i];
let block2 = &out[i..2*i];
if block1 == block2 {
blocksize = i;
break;
}
i += 1;
}
// Determine ciphertext length
let len = encryption_oracle("".as_bytes(), &unknown, &key).len();
let mut ctxt_len = 0;
for i in 1..blocksize+1 {
let input = vec!['A' as u8; i];
let new_len = encryption_oracle(&input, &unknown, &key).len();
if new_len!= len {
ctxt_len = new_len - blocksize - i;
break;
}
}
println!("blocksize = {}", blocksize);
println!("ciphertext length = {}", ctxt_len);
// Decrypt ciphertext byte-by-byte
let mut plaintext: Vec<u8> = Vec::with_capacity(ctxt_len);
for i in 0..ctxt_len {
let mut input: Vec<u8> = Vec::new();
for char_guess_ in 0..255+1 {
let char_guess = char_guess_ as u8;
let k = (i as i32) - (blocksize as i32) + 1;
for j in k..(i as i32) {
if j < 0 {
input.push('A' as u8);
} else {
input.push(plaintext[j as usize]);
}
}
input.push(char_guess);
}
for _ in 0..(blocksize - (i % blocksize)) - 1 {
input.push('A' as u8);
}
let out = encryption_oracle(&input, &unknown, &key);
let b_i = (i / blocksize) + 256;
let cipher_block = &out[b_i*blocksize..(b_i+1)*blocksize];
// search for input block with same AES ECB output
for char_guess_ in 0..255+1 {
let char_guess = char_guess_ as u8;
let j = char_guess as usize;
let guess_block = &out[j*blocksize..(j+1)*blocksize];
if guess_block == cipher_block {
plaintext.push(char_guess);
break;
}
}
}
let expected = "Rollin' in my 5.0\n\
With my rag-top down so my hair can blow\n\
The girlies on standby waving just to say hi\n\
Did you stop? No, I just drove by";
assert_eq!(String::from_utf8_lossy(&plaintext).trim(), expected);
}
| encryption_oracle | identifier_name |
p12.rs | use rand::{Rng, weak_rng};
use serialize::base64::FromBase64;
use ssl::symm::{self, encrypt};
fn encryption_oracle(input: &[u8], unknown: &[u8], key: &[u8]) -> Vec<u8> {
let mut data: Vec<u8> = Vec::with_capacity(input.len() + unknown.len());
data.extend_from_slice(input);
data.extend_from_slice(unknown);
encrypt(symm::Cipher::aes_128_ecb(), key, None, &data).unwrap()
}
#[test]
fn run() | if block1 == block2 {
blocksize = i;
break;
}
i += 1;
}
// Determine ciphertext length
let len = encryption_oracle("".as_bytes(), &unknown, &key).len();
let mut ctxt_len = 0;
for i in 1..blocksize+1 {
let input = vec!['A' as u8; i];
let new_len = encryption_oracle(&input, &unknown, &key).len();
if new_len!= len {
ctxt_len = new_len - blocksize - i;
break;
}
}
println!("blocksize = {}", blocksize);
println!("ciphertext length = {}", ctxt_len);
// Decrypt ciphertext byte-by-byte
let mut plaintext: Vec<u8> = Vec::with_capacity(ctxt_len);
for i in 0..ctxt_len {
let mut input: Vec<u8> = Vec::new();
for char_guess_ in 0..255+1 {
let char_guess = char_guess_ as u8;
let k = (i as i32) - (blocksize as i32) + 1;
for j in k..(i as i32) {
if j < 0 {
input.push('A' as u8);
} else {
input.push(plaintext[j as usize]);
}
}
input.push(char_guess);
}
for _ in 0..(blocksize - (i % blocksize)) - 1 {
input.push('A' as u8);
}
let out = encryption_oracle(&input, &unknown, &key);
let b_i = (i / blocksize) + 256;
let cipher_block = &out[b_i*blocksize..(b_i+1)*blocksize];
// search for input block with same AES ECB output
for char_guess_ in 0..255+1 {
let char_guess = char_guess_ as u8;
let j = char_guess as usize;
let guess_block = &out[j*blocksize..(j+1)*blocksize];
if guess_block == cipher_block {
plaintext.push(char_guess);
break;
}
}
}
let expected = "Rollin' in my 5.0\n\
With my rag-top down so my hair can blow\n\
The girlies on standby waving just to say hi\n\
Did you stop? No, I just drove by";
assert_eq!(String::from_utf8_lossy(&plaintext).trim(), expected);
}
| {
// unknown text we will attempt to decode with attacker controlled input
// to the encryption oracle
let unknown = "Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg\
aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq\
dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg\
YnkK".from_base64().unwrap();
let mut rng = weak_rng();
let mut key = [0_u8; 16];
rng.fill_bytes(&mut key);
// Determine blocksize
let mut i = 1;
let blocksize;
loop {
let input = vec!['A' as u8; 2*i];
let out = encryption_oracle(&input, &unknown, &key);
let block1 = &out[0..i];
let block2 = &out[i..2*i]; | identifier_body |
p12.rs | use rand::{Rng, weak_rng};
use serialize::base64::FromBase64;
use ssl::symm::{self, encrypt};
fn encryption_oracle(input: &[u8], unknown: &[u8], key: &[u8]) -> Vec<u8> {
let mut data: Vec<u8> = Vec::with_capacity(input.len() + unknown.len());
data.extend_from_slice(input);
data.extend_from_slice(unknown);
encrypt(symm::Cipher::aes_128_ecb(), key, None, &data).unwrap()
}
#[test]
fn run() {
// unknown text we will attempt to decode with attacker controlled input
// to the encryption oracle
let unknown = "Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg\
aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq\
dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg\
YnkK".from_base64().unwrap();
let mut rng = weak_rng();
let mut key = [0_u8; 16];
rng.fill_bytes(&mut key);
// Determine blocksize
let mut i = 1;
let blocksize;
loop {
let input = vec!['A' as u8; 2*i];
let out = encryption_oracle(&input, &unknown, &key);
let block1 = &out[0..i];
let block2 = &out[i..2*i];
if block1 == block2 {
blocksize = i;
break;
}
i += 1;
}
// Determine ciphertext length
let len = encryption_oracle("".as_bytes(), &unknown, &key).len();
let mut ctxt_len = 0;
for i in 1..blocksize+1 {
let input = vec!['A' as u8; i];
let new_len = encryption_oracle(&input, &unknown, &key).len();
if new_len!= len {
ctxt_len = new_len - blocksize - i;
break;
}
}
println!("blocksize = {}", blocksize);
println!("ciphertext length = {}", ctxt_len);
// Decrypt ciphertext byte-by-byte
let mut plaintext: Vec<u8> = Vec::with_capacity(ctxt_len);
for i in 0..ctxt_len {
let mut input: Vec<u8> = Vec::new();
for char_guess_ in 0..255+1 {
let char_guess = char_guess_ as u8;
let k = (i as i32) - (blocksize as i32) + 1;
for j in k..(i as i32) {
if j < 0 | else {
input.push(plaintext[j as usize]);
}
}
input.push(char_guess);
}
for _ in 0..(blocksize - (i % blocksize)) - 1 {
input.push('A' as u8);
}
let out = encryption_oracle(&input, &unknown, &key);
let b_i = (i / blocksize) + 256;
let cipher_block = &out[b_i*blocksize..(b_i+1)*blocksize];
// search for input block with same AES ECB output
for char_guess_ in 0..255+1 {
let char_guess = char_guess_ as u8;
let j = char_guess as usize;
let guess_block = &out[j*blocksize..(j+1)*blocksize];
if guess_block == cipher_block {
plaintext.push(char_guess);
break;
}
}
}
let expected = "Rollin' in my 5.0\n\
With my rag-top down so my hair can blow\n\
The girlies on standby waving just to say hi\n\
Did you stop? No, I just drove by";
assert_eq!(String::from_utf8_lossy(&plaintext).trim(), expected);
}
| {
input.push('A' as u8);
} | conditional_block |
p12.rs | use rand::{Rng, weak_rng};
use serialize::base64::FromBase64;
use ssl::symm::{self, encrypt};
fn encryption_oracle(input: &[u8], unknown: &[u8], key: &[u8]) -> Vec<u8> {
let mut data: Vec<u8> = Vec::with_capacity(input.len() + unknown.len());
data.extend_from_slice(input);
data.extend_from_slice(unknown);
encrypt(symm::Cipher::aes_128_ecb(), key, None, &data).unwrap()
}
#[test]
fn run() {
// unknown text we will attempt to decode with attacker controlled input
// to the encryption oracle
let unknown = "Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg\
aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq\
dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg\
YnkK".from_base64().unwrap();
let mut rng = weak_rng();
let mut key = [0_u8; 16];
rng.fill_bytes(&mut key);
// Determine blocksize
let mut i = 1;
let blocksize;
loop {
let input = vec!['A' as u8; 2*i];
let out = encryption_oracle(&input, &unknown, &key);
let block1 = &out[0..i];
let block2 = &out[i..2*i];
if block1 == block2 {
blocksize = i;
break;
}
i += 1;
}
// Determine ciphertext length
let len = encryption_oracle("".as_bytes(), &unknown, &key).len();
let mut ctxt_len = 0;
for i in 1..blocksize+1 {
let input = vec!['A' as u8; i];
let new_len = encryption_oracle(&input, &unknown, &key).len();
if new_len!= len {
ctxt_len = new_len - blocksize - i;
break;
}
}
println!("blocksize = {}", blocksize);
println!("ciphertext length = {}", ctxt_len);
// Decrypt ciphertext byte-by-byte
let mut plaintext: Vec<u8> = Vec::with_capacity(ctxt_len);
for i in 0..ctxt_len {
let mut input: Vec<u8> = Vec::new();
for char_guess_ in 0..255+1 {
let char_guess = char_guess_ as u8;
let k = (i as i32) - (blocksize as i32) + 1;
for j in k..(i as i32) {
if j < 0 {
input.push('A' as u8);
} else {
input.push(plaintext[j as usize]);
}
}
input.push(char_guess);
}
for _ in 0..(blocksize - (i % blocksize)) - 1 {
input.push('A' as u8);
} | let b_i = (i / blocksize) + 256;
let cipher_block = &out[b_i*blocksize..(b_i+1)*blocksize];
// search for input block with same AES ECB output
for char_guess_ in 0..255+1 {
let char_guess = char_guess_ as u8;
let j = char_guess as usize;
let guess_block = &out[j*blocksize..(j+1)*blocksize];
if guess_block == cipher_block {
plaintext.push(char_guess);
break;
}
}
}
let expected = "Rollin' in my 5.0\n\
With my rag-top down so my hair can blow\n\
The girlies on standby waving just to say hi\n\
Did you stop? No, I just drove by";
assert_eq!(String::from_utf8_lossy(&plaintext).trim(), expected);
} |
let out = encryption_oracle(&input, &unknown, &key);
| random_line_split |
general_tests.rs |
#[macro_use]
extern crate ecs;
use ecs::{BuildData, ModifyData};
use ecs::{World, DataHelper};
use ecs::{Process, System};
use ecs::system::{EntityProcess, EntitySystem};
use ecs::EntityIter;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Position
{
pub x: f32,
pub y: f32,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Team(u8);
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct SomeFeature;
components! {
TestComponents {
#[hot] blank_data: (),
#[hot] position: Position,
#[cold] team: Team,
#[hot] feature: SomeFeature
}
}
systems! {
TestSystems<TestComponents, ()> {
hello_world: HelloWorld = HelloWorld("Hello, World!"),
print_position: EntitySystem<PrintPosition> = EntitySystem::new(PrintPosition,
aspect!(<TestComponents>
all: [position, feature]
)
)
}
}
pub struct HelloWorld(&'static str);
impl Process for HelloWorld
{
fn process(&mut self, _: &mut DataHelper<TestComponents, ()>)
{
println!("{}", self.0);
}
}
impl System for HelloWorld { type Components = TestComponents; type Services = (); }
pub struct PrintPosition;
impl EntityProcess for PrintPosition
{
fn process(&mut self, en: EntityIter<TestComponents>, co: &mut DataHelper<TestComponents, ()>)
{
for e in en
{
println!("{:?}", co.position.borrow(&e));
}
}
}
impl System for PrintPosition {
type Components = TestComponents;
type Services = ();
fn is_active(&self) -> bool { false }
}
#[test]
fn test_general_1()
| assert_eq!(Some(Team(4)), c.team.remove(&e));
assert!(!c.feature.has(&e));
assert!(c.feature.insert(&e, SomeFeature).is_none());
});
process!(world, print_position);
world.modify_entity(entity, |e: ModifyData<TestComponents>, c: &mut TestComponents| {
assert_eq!(Position { x: -2.5, y: 7.6 }, c.position[e]);
assert_eq!(None, c.team.remove(&e));
assert!(c.feature.insert(&e, SomeFeature).is_some());
});
// Test external entity iterator
for e in world.entities()
{
assert!(world.position.has(&e));
}
// Test external entity iterator with aspect filtering
for e in world.entities().filter(aspect!(<TestComponents> all: [team]), &world)
{
assert!(world.team.has(&e));
}
// Test active systems
world.update();
// Test system modification
world.systems.hello_world.0 = "Goodbye, World!";
world.update();
}
| {
let mut world = World::<TestSystems>::new();
// Test entity builders
let entity = world.create_entity(|e: BuildData<TestComponents>, c: &mut TestComponents| {
c.position.add(&e, Position { x: 0.5, y: 0.7 });
c.team.add(&e, Team(4));
});
world.create_entity(|e: BuildData<TestComponents>, c: &mut TestComponents| {
c.position.add(&e, Position { x: 0.6, y: 0.8 });
c.team.add(&e, Team(3));
c.feature.add(&e, SomeFeature);
});
// Test passive systems
world.systems.print_position.process(&mut world.data);
// Test entity modifiers
world.modify_entity(entity, |e: ModifyData<TestComponents>, c: &mut TestComponents| {
assert_eq!(Some(Position { x: 0.5, y: 0.7 }), c.position.insert(&e, Position { x: -2.5, y: 7.6 })); | identifier_body |
general_tests.rs | #[macro_use]
extern crate ecs;
use ecs::{BuildData, ModifyData};
use ecs::{World, DataHelper};
use ecs::{Process, System};
use ecs::system::{EntityProcess, EntitySystem};
use ecs::EntityIter;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Position
{
pub x: f32,
pub y: f32,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Team(u8);
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct SomeFeature;
components! {
TestComponents {
#[hot] blank_data: (),
#[hot] position: Position,
#[cold] team: Team,
#[hot] feature: SomeFeature
}
}
systems! {
TestSystems<TestComponents, ()> { | )
}
}
pub struct HelloWorld(&'static str);
impl Process for HelloWorld
{
fn process(&mut self, _: &mut DataHelper<TestComponents, ()>)
{
println!("{}", self.0);
}
}
impl System for HelloWorld { type Components = TestComponents; type Services = (); }
pub struct PrintPosition;
impl EntityProcess for PrintPosition
{
fn process(&mut self, en: EntityIter<TestComponents>, co: &mut DataHelper<TestComponents, ()>)
{
for e in en
{
println!("{:?}", co.position.borrow(&e));
}
}
}
impl System for PrintPosition {
type Components = TestComponents;
type Services = ();
fn is_active(&self) -> bool { false }
}
#[test]
fn test_general_1()
{
let mut world = World::<TestSystems>::new();
// Test entity builders
let entity = world.create_entity(|e: BuildData<TestComponents>, c: &mut TestComponents| {
c.position.add(&e, Position { x: 0.5, y: 0.7 });
c.team.add(&e, Team(4));
});
world.create_entity(|e: BuildData<TestComponents>, c: &mut TestComponents| {
c.position.add(&e, Position { x: 0.6, y: 0.8 });
c.team.add(&e, Team(3));
c.feature.add(&e, SomeFeature);
});
// Test passive systems
world.systems.print_position.process(&mut world.data);
// Test entity modifiers
world.modify_entity(entity, |e: ModifyData<TestComponents>, c: &mut TestComponents| {
assert_eq!(Some(Position { x: 0.5, y: 0.7 }), c.position.insert(&e, Position { x: -2.5, y: 7.6 }));
assert_eq!(Some(Team(4)), c.team.remove(&e));
assert!(!c.feature.has(&e));
assert!(c.feature.insert(&e, SomeFeature).is_none());
});
process!(world, print_position);
world.modify_entity(entity, |e: ModifyData<TestComponents>, c: &mut TestComponents| {
assert_eq!(Position { x: -2.5, y: 7.6 }, c.position[e]);
assert_eq!(None, c.team.remove(&e));
assert!(c.feature.insert(&e, SomeFeature).is_some());
});
// Test external entity iterator
for e in world.entities()
{
assert!(world.position.has(&e));
}
// Test external entity iterator with aspect filtering
for e in world.entities().filter(aspect!(<TestComponents> all: [team]), &world)
{
assert!(world.team.has(&e));
}
// Test active systems
world.update();
// Test system modification
world.systems.hello_world.0 = "Goodbye, World!";
world.update();
} | hello_world: HelloWorld = HelloWorld("Hello, World!"),
print_position: EntitySystem<PrintPosition> = EntitySystem::new(PrintPosition,
aspect!(<TestComponents>
all: [position, feature]
) | random_line_split |
general_tests.rs |
#[macro_use]
extern crate ecs;
use ecs::{BuildData, ModifyData};
use ecs::{World, DataHelper};
use ecs::{Process, System};
use ecs::system::{EntityProcess, EntitySystem};
use ecs::EntityIter;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Position
{
pub x: f32,
pub y: f32,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Team(u8);
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct SomeFeature;
components! {
TestComponents {
#[hot] blank_data: (),
#[hot] position: Position,
#[cold] team: Team,
#[hot] feature: SomeFeature
}
}
systems! {
TestSystems<TestComponents, ()> {
hello_world: HelloWorld = HelloWorld("Hello, World!"),
print_position: EntitySystem<PrintPosition> = EntitySystem::new(PrintPosition,
aspect!(<TestComponents>
all: [position, feature]
)
)
}
}
pub struct HelloWorld(&'static str);
impl Process for HelloWorld
{
fn | (&mut self, _: &mut DataHelper<TestComponents, ()>)
{
println!("{}", self.0);
}
}
impl System for HelloWorld { type Components = TestComponents; type Services = (); }
pub struct PrintPosition;
impl EntityProcess for PrintPosition
{
fn process(&mut self, en: EntityIter<TestComponents>, co: &mut DataHelper<TestComponents, ()>)
{
for e in en
{
println!("{:?}", co.position.borrow(&e));
}
}
}
impl System for PrintPosition {
type Components = TestComponents;
type Services = ();
fn is_active(&self) -> bool { false }
}
#[test]
fn test_general_1()
{
let mut world = World::<TestSystems>::new();
// Test entity builders
let entity = world.create_entity(|e: BuildData<TestComponents>, c: &mut TestComponents| {
c.position.add(&e, Position { x: 0.5, y: 0.7 });
c.team.add(&e, Team(4));
});
world.create_entity(|e: BuildData<TestComponents>, c: &mut TestComponents| {
c.position.add(&e, Position { x: 0.6, y: 0.8 });
c.team.add(&e, Team(3));
c.feature.add(&e, SomeFeature);
});
// Test passive systems
world.systems.print_position.process(&mut world.data);
// Test entity modifiers
world.modify_entity(entity, |e: ModifyData<TestComponents>, c: &mut TestComponents| {
assert_eq!(Some(Position { x: 0.5, y: 0.7 }), c.position.insert(&e, Position { x: -2.5, y: 7.6 }));
assert_eq!(Some(Team(4)), c.team.remove(&e));
assert!(!c.feature.has(&e));
assert!(c.feature.insert(&e, SomeFeature).is_none());
});
process!(world, print_position);
world.modify_entity(entity, |e: ModifyData<TestComponents>, c: &mut TestComponents| {
assert_eq!(Position { x: -2.5, y: 7.6 }, c.position[e]);
assert_eq!(None, c.team.remove(&e));
assert!(c.feature.insert(&e, SomeFeature).is_some());
});
// Test external entity iterator
for e in world.entities()
{
assert!(world.position.has(&e));
}
// Test external entity iterator with aspect filtering
for e in world.entities().filter(aspect!(<TestComponents> all: [team]), &world)
{
assert!(world.team.has(&e));
}
// Test active systems
world.update();
// Test system modification
world.systems.hello_world.0 = "Goodbye, World!";
world.update();
}
| process | identifier_name |
htmltabledatacellelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTableDataCellElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTableDataCellElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::HTMLElementTypeId;
use dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementTypeId};
use dom::node::{Node, NodeTypeId};
use servo_util::str::DOMString;
#[dom_struct]
pub struct HTMLTableDataCellElement {
htmltablecellelement: HTMLTableCellElement,
}
impl HTMLTableDataCellElementDerived for EventTarget {
fn is_htmltabledatacellelement(&self) -> bool |
}
impl HTMLTableDataCellElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableDataCellElement {
HTMLTableDataCellElement {
htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableCellElementTypeId::HTMLTableDataCellElement,
localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>)
-> Temporary<HTMLTableDataCellElement> {
Node::reflect_node(box HTMLTableDataCellElement::new_inherited(localName,
prefix,
document),
document,
HTMLTableDataCellElementBinding::Wrap)
}
}
| {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLTableCellElement(
HTMLTableCellElementTypeId::HTMLTableDataCellElement))))
} | identifier_body |
htmltabledatacellelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTableDataCellElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTableDataCellElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::HTMLElementTypeId;
use dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementTypeId};
use dom::node::{Node, NodeTypeId};
use servo_util::str::DOMString;
#[dom_struct]
pub struct HTMLTableDataCellElement {
htmltablecellelement: HTMLTableCellElement,
}
impl HTMLTableDataCellElementDerived for EventTarget {
fn is_htmltabledatacellelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLTableCellElement(
HTMLTableCellElementTypeId::HTMLTableDataCellElement))))
}
}
impl HTMLTableDataCellElement { | }
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>)
-> Temporary<HTMLTableDataCellElement> {
Node::reflect_node(box HTMLTableDataCellElement::new_inherited(localName,
prefix,
document),
document,
HTMLTableDataCellElementBinding::Wrap)
}
} | fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableDataCellElement {
HTMLTableDataCellElement {
htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableCellElementTypeId::HTMLTableDataCellElement,
localName, prefix, document)
} | random_line_split |
htmltabledatacellelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTableDataCellElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTableDataCellElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::HTMLElementTypeId;
use dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementTypeId};
use dom::node::{Node, NodeTypeId};
use servo_util::str::DOMString;
#[dom_struct]
pub struct HTMLTableDataCellElement {
htmltablecellelement: HTMLTableCellElement,
}
impl HTMLTableDataCellElementDerived for EventTarget {
fn is_htmltabledatacellelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLTableCellElement(
HTMLTableCellElementTypeId::HTMLTableDataCellElement))))
}
}
impl HTMLTableDataCellElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableDataCellElement {
HTMLTableDataCellElement {
htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableCellElementTypeId::HTMLTableDataCellElement,
localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn | (localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>)
-> Temporary<HTMLTableDataCellElement> {
Node::reflect_node(box HTMLTableDataCellElement::new_inherited(localName,
prefix,
document),
document,
HTMLTableDataCellElementBinding::Wrap)
}
}
| new | identifier_name |
challenge1.rs | use bitwise::base64;
use bitwise::hex_rep::ToHexRep;
use challengeinfo::challenge::{Challenge, ChallengeInfo};
pub const INFO1: ChallengeInfo<'static> = ChallengeInfo {
set_number: 1,
challenge_number: 1,
title: "Convert hex to base64",
description: "",
url: "http://cryptopals.com/sets/1/challenges/1",
};
pub const CHALLENGE1: Challenge<'static> = Challenge {
info: INFO1,
func: execute,
};
fn execute() -> String { | let hex_str = String::from("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d");
base64::to_base64(&String::from_utf8(hex_str.to_hex().unwrap()).unwrap())
} | random_line_split |
|
challenge1.rs | use bitwise::base64;
use bitwise::hex_rep::ToHexRep;
use challengeinfo::challenge::{Challenge, ChallengeInfo};
pub const INFO1: ChallengeInfo<'static> = ChallengeInfo {
set_number: 1,
challenge_number: 1,
title: "Convert hex to base64",
description: "",
url: "http://cryptopals.com/sets/1/challenges/1",
};
pub const CHALLENGE1: Challenge<'static> = Challenge {
info: INFO1,
func: execute,
};
fn | () -> String {
let hex_str = String::from("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d");
base64::to_base64(&String::from_utf8(hex_str.to_hex().unwrap()).unwrap())
}
| execute | identifier_name |
challenge1.rs | use bitwise::base64;
use bitwise::hex_rep::ToHexRep;
use challengeinfo::challenge::{Challenge, ChallengeInfo};
pub const INFO1: ChallengeInfo<'static> = ChallengeInfo {
set_number: 1,
challenge_number: 1,
title: "Convert hex to base64",
description: "",
url: "http://cryptopals.com/sets/1/challenges/1",
};
pub const CHALLENGE1: Challenge<'static> = Challenge {
info: INFO1,
func: execute,
};
fn execute() -> String | {
let hex_str = String::from("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d");
base64::to_base64(&String::from_utf8(hex_str.to_hex().unwrap()).unwrap())
} | identifier_body |
|
import.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 | //~^ no `baz` in `zed`. Did you mean to use `bar`?
mod zed {
pub fn bar() { println!("bar"); }
use foo; //~ ERROR unresolved import `foo` [E0432]
//~^ no `foo` in the root
}
fn main() {
zed::foo(); //~ ERROR `foo` is private
bar();
} | // option. This file may not be copied, modified, or distributed
// except according to those terms.
use zed::bar;
use zed::baz; //~ ERROR unresolved import `zed::baz` [E0432] | random_line_split |
import.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.
use zed::bar;
use zed::baz; //~ ERROR unresolved import `zed::baz` [E0432]
//~^ no `baz` in `zed`. Did you mean to use `bar`?
mod zed {
pub fn bar() { println!("bar"); }
use foo; //~ ERROR unresolved import `foo` [E0432]
//~^ no `foo` in the root
}
fn main() | {
zed::foo(); //~ ERROR `foo` is private
bar();
} | identifier_body |
|
import.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.
use zed::bar;
use zed::baz; //~ ERROR unresolved import `zed::baz` [E0432]
//~^ no `baz` in `zed`. Did you mean to use `bar`?
mod zed {
pub fn | () { println!("bar"); }
use foo; //~ ERROR unresolved import `foo` [E0432]
//~^ no `foo` in the root
}
fn main() {
zed::foo(); //~ ERROR `foo` is private
bar();
}
| bar | identifier_name |
headless.rs | extern crate glutin;
extern crate libc;
use std::ptr;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
} | use gl::types::*;
use glutin::GlContext;
#[cfg(target_os = "macos")]
#[test]
fn test_headless() {
let width: i32 = 256;
let height: i32 = 256;
let window = glutin::HeadlessRendererBuilder::new(width as u32, height as u32).build().unwrap();
unsafe { window.make_current().expect("Couldn't make window current") };
let gl = gl::Gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);
unsafe {
let mut framebuffer = 0;
let mut texture = 0;
gl.GenFramebuffers(1, &mut framebuffer);
gl.BindFramebuffer(gl::FRAMEBUFFER, framebuffer);
gl.GenTextures(1, &mut texture);
gl.BindTexture(gl::TEXTURE_2D, texture);
gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl.TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA as i32, width, height,
0, gl::RGBA, gl::UNSIGNED_BYTE, ptr::null());
gl.FramebufferTexture2D(gl::FRAMEBUFFER, gl::COLOR_ATTACHMENT0, gl::TEXTURE_2D, texture, 0);
let status = gl.CheckFramebufferStatus(gl::FRAMEBUFFER);
if status!= gl::FRAMEBUFFER_COMPLETE {
panic!("Error while creating the framebuffer");
}
gl.ClearColor(0.0, 1.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
gl.Enable(gl::SCISSOR_TEST);
gl.Scissor(1, 0, 1, 1);
gl.ClearColor(1.0, 0.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
let mut values: Vec<u8> = vec![0;(width*height*4) as usize];
gl.ReadPixels(0, 0, width, height, gl::RGBA, gl::UNSIGNED_BYTE, values.as_mut_ptr() as *mut GLvoid);
assert_eq!(values[0], 0);
assert_eq!(values[1], 255);
assert_eq!(values[2], 0);
assert_eq!(values[3], 255);
assert_eq!(values[4], 255);
assert_eq!(values[5], 0);
assert_eq!(values[6], 0);
assert_eq!(values[7], 255);
}
} | random_line_split |
|
headless.rs | extern crate glutin;
extern crate libc;
use std::ptr;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
}
use gl::types::*;
use glutin::GlContext;
#[cfg(target_os = "macos")]
#[test]
fn | () {
let width: i32 = 256;
let height: i32 = 256;
let window = glutin::HeadlessRendererBuilder::new(width as u32, height as u32).build().unwrap();
unsafe { window.make_current().expect("Couldn't make window current") };
let gl = gl::Gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);
unsafe {
let mut framebuffer = 0;
let mut texture = 0;
gl.GenFramebuffers(1, &mut framebuffer);
gl.BindFramebuffer(gl::FRAMEBUFFER, framebuffer);
gl.GenTextures(1, &mut texture);
gl.BindTexture(gl::TEXTURE_2D, texture);
gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl.TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA as i32, width, height,
0, gl::RGBA, gl::UNSIGNED_BYTE, ptr::null());
gl.FramebufferTexture2D(gl::FRAMEBUFFER, gl::COLOR_ATTACHMENT0, gl::TEXTURE_2D, texture, 0);
let status = gl.CheckFramebufferStatus(gl::FRAMEBUFFER);
if status!= gl::FRAMEBUFFER_COMPLETE {
panic!("Error while creating the framebuffer");
}
gl.ClearColor(0.0, 1.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
gl.Enable(gl::SCISSOR_TEST);
gl.Scissor(1, 0, 1, 1);
gl.ClearColor(1.0, 0.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
let mut values: Vec<u8> = vec![0;(width*height*4) as usize];
gl.ReadPixels(0, 0, width, height, gl::RGBA, gl::UNSIGNED_BYTE, values.as_mut_ptr() as *mut GLvoid);
assert_eq!(values[0], 0);
assert_eq!(values[1], 255);
assert_eq!(values[2], 0);
assert_eq!(values[3], 255);
assert_eq!(values[4], 255);
assert_eq!(values[5], 0);
assert_eq!(values[6], 0);
assert_eq!(values[7], 255);
}
}
| test_headless | identifier_name |
headless.rs | extern crate glutin;
extern crate libc;
use std::ptr;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
}
use gl::types::*;
use glutin::GlContext;
#[cfg(target_os = "macos")]
#[test]
fn test_headless() | gl.FramebufferTexture2D(gl::FRAMEBUFFER, gl::COLOR_ATTACHMENT0, gl::TEXTURE_2D, texture, 0);
let status = gl.CheckFramebufferStatus(gl::FRAMEBUFFER);
if status!= gl::FRAMEBUFFER_COMPLETE {
panic!("Error while creating the framebuffer");
}
gl.ClearColor(0.0, 1.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
gl.Enable(gl::SCISSOR_TEST);
gl.Scissor(1, 0, 1, 1);
gl.ClearColor(1.0, 0.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
let mut values: Vec<u8> = vec![0;(width*height*4) as usize];
gl.ReadPixels(0, 0, width, height, gl::RGBA, gl::UNSIGNED_BYTE, values.as_mut_ptr() as *mut GLvoid);
assert_eq!(values[0], 0);
assert_eq!(values[1], 255);
assert_eq!(values[2], 0);
assert_eq!(values[3], 255);
assert_eq!(values[4], 255);
assert_eq!(values[5], 0);
assert_eq!(values[6], 0);
assert_eq!(values[7], 255);
}
}
| {
let width: i32 = 256;
let height: i32 = 256;
let window = glutin::HeadlessRendererBuilder::new(width as u32, height as u32).build().unwrap();
unsafe { window.make_current().expect("Couldn't make window current") };
let gl = gl::Gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);
unsafe {
let mut framebuffer = 0;
let mut texture = 0;
gl.GenFramebuffers(1, &mut framebuffer);
gl.BindFramebuffer(gl::FRAMEBUFFER, framebuffer);
gl.GenTextures(1, &mut texture);
gl.BindTexture(gl::TEXTURE_2D, texture);
gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl.TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA as i32, width, height,
0, gl::RGBA, gl::UNSIGNED_BYTE, ptr::null()); | identifier_body |
headless.rs | extern crate glutin;
extern crate libc;
use std::ptr;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
}
use gl::types::*;
use glutin::GlContext;
#[cfg(target_os = "macos")]
#[test]
fn test_headless() {
let width: i32 = 256;
let height: i32 = 256;
let window = glutin::HeadlessRendererBuilder::new(width as u32, height as u32).build().unwrap();
unsafe { window.make_current().expect("Couldn't make window current") };
let gl = gl::Gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);
unsafe {
let mut framebuffer = 0;
let mut texture = 0;
gl.GenFramebuffers(1, &mut framebuffer);
gl.BindFramebuffer(gl::FRAMEBUFFER, framebuffer);
gl.GenTextures(1, &mut texture);
gl.BindTexture(gl::TEXTURE_2D, texture);
gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl.TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA as i32, width, height,
0, gl::RGBA, gl::UNSIGNED_BYTE, ptr::null());
gl.FramebufferTexture2D(gl::FRAMEBUFFER, gl::COLOR_ATTACHMENT0, gl::TEXTURE_2D, texture, 0);
let status = gl.CheckFramebufferStatus(gl::FRAMEBUFFER);
if status!= gl::FRAMEBUFFER_COMPLETE |
gl.ClearColor(0.0, 1.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
gl.Enable(gl::SCISSOR_TEST);
gl.Scissor(1, 0, 1, 1);
gl.ClearColor(1.0, 0.0, 0.0, 1.0);
gl.Clear(gl::COLOR_BUFFER_BIT);
let mut values: Vec<u8> = vec![0;(width*height*4) as usize];
gl.ReadPixels(0, 0, width, height, gl::RGBA, gl::UNSIGNED_BYTE, values.as_mut_ptr() as *mut GLvoid);
assert_eq!(values[0], 0);
assert_eq!(values[1], 255);
assert_eq!(values[2], 0);
assert_eq!(values[3], 255);
assert_eq!(values[4], 255);
assert_eq!(values[5], 0);
assert_eq!(values[6], 0);
assert_eq!(values[7], 255);
}
}
| {
panic!("Error while creating the framebuffer");
} | conditional_block |
main.rs | #![feature(mpsc_select)]
extern crate time;
use std::thread;
use std::sync::mpsc;
use std::sync::mpsc::{SyncSender, Receiver};
use std::sync::mpsc::Select;
use std::io::prelude::*;
use std::fs::File;
use std::vec::Vec;
use time::PreciseTime;
struct | {
writer : i32,
n : i32,
}
fn writer(out : SyncSender<StressedPacket>, writer : i32, writes : i32) {
for i in 0..writes {
out.send(StressedPacket{writer : writer, n : i}).unwrap();
}
}
fn save_results(N : usize, results : Vec<u64>) {
let mut buffer = File::create(format!("st-rust-{}.csv", N)).unwrap();
for r in results {
write!(buffer, "{}\n", r);
}
buffer.flush();
}
fn do_select1(in0 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => println!("")
}
}
fn do_select2(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => ()
}
}
fn do_select4(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>, in2 : &Receiver<StressedPacket>, in3 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => (),
_ = in2.recv() => (),
_ = in3.recv() => ()
}
}
fn do_select8(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>, in2 : &Receiver<StressedPacket>, in3 : &Receiver<StressedPacket>,
in4 : &Receiver<StressedPacket>, in5 : &Receiver<StressedPacket>, in6 : &Receiver<StressedPacket>, in7 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => (),
_ = in2.recv() => (),
_ = in3.recv() => (),
_ = in4.recv() => (),
_ = in5.recv() => (),
_ = in6.recv() => (),
_ = in7.recv() => ()
}
}
fn do_select(N : i32, input : &Vec<Receiver<StressedPacket>>) {
match N {
1 => do_select1(&input[0]),
2 => do_select2(&input[0], &input[1]),
4 => do_select4(&input[0], &input[1], &input[2], &input[3]),
8 => do_select8(&input[0], &input[1], &input[2], &input[3], &input[4], &input[5], &input[6], &input[7]),
_ => ()
}
}
fn reader(N : i32, input : Vec<Receiver<StressedPacket>>, total : i32) {
let mut results = Vec::new();
let mut start = time::precise_time_ns();
let mut i = 0;
for count in 0..total {
if count % 65536 == 0 {
let total = (time::precise_time_ns() - start) / 65536;
results.push(total);
println!("{}", i);
println!("{} ns", total);
start = time::precise_time_ns();
i += 1;
}
do_select(N, &input);
}
save_results(input.len(), results);
}
fn experiment(iterations : i32, threads : i32) {
let mut chans = Vec::new();
for i in 0..threads {
let (tx, rx) : (SyncSender<StressedPacket>, Receiver<StressedPacket>) = mpsc::sync_channel(0);
chans.push(rx);
thread::spawn(move || { writer(tx, i, iterations / threads); } );
}
reader(threads, chans, iterations);
}
fn main() {
let x : i32 = 2;
experiment(x.pow(24), 1);
experiment(x.pow(24), 2);
experiment(x.pow(24), 4);
experiment(x.pow(24), 8);
}
| StressedPacket | identifier_name |
main.rs | #![feature(mpsc_select)]
extern crate time;
use std::thread;
use std::sync::mpsc;
use std::sync::mpsc::{SyncSender, Receiver};
use std::sync::mpsc::Select;
use std::io::prelude::*;
use std::fs::File;
use std::vec::Vec;
use time::PreciseTime;
struct StressedPacket {
writer : i32,
n : i32,
}
fn writer(out : SyncSender<StressedPacket>, writer : i32, writes : i32) |
fn save_results(N : usize, results : Vec<u64>) {
let mut buffer = File::create(format!("st-rust-{}.csv", N)).unwrap();
for r in results {
write!(buffer, "{}\n", r);
}
buffer.flush();
}
fn do_select1(in0 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => println!("")
}
}
fn do_select2(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => ()
}
}
fn do_select4(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>, in2 : &Receiver<StressedPacket>, in3 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => (),
_ = in2.recv() => (),
_ = in3.recv() => ()
}
}
fn do_select8(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>, in2 : &Receiver<StressedPacket>, in3 : &Receiver<StressedPacket>,
in4 : &Receiver<StressedPacket>, in5 : &Receiver<StressedPacket>, in6 : &Receiver<StressedPacket>, in7 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => (),
_ = in2.recv() => (),
_ = in3.recv() => (),
_ = in4.recv() => (),
_ = in5.recv() => (),
_ = in6.recv() => (),
_ = in7.recv() => ()
}
}
fn do_select(N : i32, input : &Vec<Receiver<StressedPacket>>) {
match N {
1 => do_select1(&input[0]),
2 => do_select2(&input[0], &input[1]),
4 => do_select4(&input[0], &input[1], &input[2], &input[3]),
8 => do_select8(&input[0], &input[1], &input[2], &input[3], &input[4], &input[5], &input[6], &input[7]),
_ => ()
}
}
fn reader(N : i32, input : Vec<Receiver<StressedPacket>>, total : i32) {
let mut results = Vec::new();
let mut start = time::precise_time_ns();
let mut i = 0;
for count in 0..total {
if count % 65536 == 0 {
let total = (time::precise_time_ns() - start) / 65536;
results.push(total);
println!("{}", i);
println!("{} ns", total);
start = time::precise_time_ns();
i += 1;
}
do_select(N, &input);
}
save_results(input.len(), results);
}
fn experiment(iterations : i32, threads : i32) {
let mut chans = Vec::new();
for i in 0..threads {
let (tx, rx) : (SyncSender<StressedPacket>, Receiver<StressedPacket>) = mpsc::sync_channel(0);
chans.push(rx);
thread::spawn(move || { writer(tx, i, iterations / threads); } );
}
reader(threads, chans, iterations);
}
fn main() {
let x : i32 = 2;
experiment(x.pow(24), 1);
experiment(x.pow(24), 2);
experiment(x.pow(24), 4);
experiment(x.pow(24), 8);
}
| {
for i in 0..writes {
out.send(StressedPacket{writer : writer, n : i}).unwrap();
}
} | identifier_body |
main.rs | #![feature(mpsc_select)]
extern crate time;
use std::thread;
use std::sync::mpsc;
use std::sync::mpsc::{SyncSender, Receiver};
use std::sync::mpsc::Select;
use std::io::prelude::*;
use std::fs::File;
use std::vec::Vec;
use time::PreciseTime;
struct StressedPacket {
writer : i32,
n : i32,
}
fn writer(out : SyncSender<StressedPacket>, writer : i32, writes : i32) {
for i in 0..writes {
out.send(StressedPacket{writer : writer, n : i}).unwrap();
}
}
fn save_results(N : usize, results : Vec<u64>) {
let mut buffer = File::create(format!("st-rust-{}.csv", N)).unwrap();
for r in results {
write!(buffer, "{}\n", r);
}
buffer.flush();
}
fn do_select1(in0 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => println!("")
}
}
fn do_select2(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => ()
}
}
fn do_select4(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>, in2 : &Receiver<StressedPacket>, in3 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => (),
_ = in2.recv() => (),
_ = in3.recv() => ()
}
}
fn do_select8(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>, in2 : &Receiver<StressedPacket>, in3 : &Receiver<StressedPacket>,
in4 : &Receiver<StressedPacket>, in5 : &Receiver<StressedPacket>, in6 : &Receiver<StressedPacket>, in7 : &Receiver<StressedPacket>) {
select! {
_ = in0.recv() => (),
_ = in1.recv() => (),
_ = in2.recv() => (),
_ = in3.recv() => (),
_ = in4.recv() => (), | }
}
fn do_select(N : i32, input : &Vec<Receiver<StressedPacket>>) {
match N {
1 => do_select1(&input[0]),
2 => do_select2(&input[0], &input[1]),
4 => do_select4(&input[0], &input[1], &input[2], &input[3]),
8 => do_select8(&input[0], &input[1], &input[2], &input[3], &input[4], &input[5], &input[6], &input[7]),
_ => ()
}
}
fn reader(N : i32, input : Vec<Receiver<StressedPacket>>, total : i32) {
let mut results = Vec::new();
let mut start = time::precise_time_ns();
let mut i = 0;
for count in 0..total {
if count % 65536 == 0 {
let total = (time::precise_time_ns() - start) / 65536;
results.push(total);
println!("{}", i);
println!("{} ns", total);
start = time::precise_time_ns();
i += 1;
}
do_select(N, &input);
}
save_results(input.len(), results);
}
fn experiment(iterations : i32, threads : i32) {
let mut chans = Vec::new();
for i in 0..threads {
let (tx, rx) : (SyncSender<StressedPacket>, Receiver<StressedPacket>) = mpsc::sync_channel(0);
chans.push(rx);
thread::spawn(move || { writer(tx, i, iterations / threads); } );
}
reader(threads, chans, iterations);
}
fn main() {
let x : i32 = 2;
experiment(x.pow(24), 1);
experiment(x.pow(24), 2);
experiment(x.pow(24), 4);
experiment(x.pow(24), 8);
} | _ = in5.recv() => (),
_ = in6.recv() => (),
_ = in7.recv() => () | random_line_split |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern mod glfw;
use std::libc;
#[link(name="glfw")]
extern {}
#[start]
fn start(argc: int, argv: **u8) -> int {
std::rt::start_on_main_thread(argc, argv, main)
}
fn main() {
glfw::set_error_callback(~ErrorContext);
do glfw::start {
glfw::window_hint::resizable(true);
let window = glfw::Window::create(800, 600, "Hello, I am a window.", glfw::Windowed)
.expect("Failed to create GLFW window.");
window.set_sticky_keys(true);
// Register event callbacks
window.set_pos_callback(~WindowPosContext);
window.set_size_callback(~WindowSizeContext);
window.set_close_callback(~WindowCloseContext);
window.set_refresh_callback(~WindowRefreshContext); |
window.set_key_callback(~KeyContext);
window.set_char_callback(~CharContext);
window.set_mouse_button_callback(~MouseButtonContext);
window.set_cursor_pos_callback(~CursorPosContext);
window.set_cursor_enter_callback(~CursorEnterContext);
window.set_scroll_callback(~ScrollContext);
window.make_context_current();
while!window.should_close() {
glfw::poll_events();
}
}
}
struct ErrorContext;
impl glfw::ErrorCallback for ErrorContext {
fn call(&self, _: glfw::Error, description: ~str) {
println!("GLFW Error: {:s}", description);
}
}
struct WindowPosContext;
impl glfw::WindowPosCallback for WindowPosContext {
fn call(&self, window: &glfw::Window, x: i32, y: i32) {
window.set_title(format!("Window pos: ({}, {})", x, y));
}
}
struct WindowSizeContext;
impl glfw::WindowSizeCallback for WindowSizeContext {
fn call(&self, window: &glfw::Window, width: i32, height: i32) {
window.set_title(format!("Window size: ({}, {})", width, height));
}
}
struct WindowCloseContext;
impl glfw::WindowCloseCallback for WindowCloseContext {
fn call(&self, _: &glfw::Window) {
println("Window close requested.");
}
}
struct WindowRefreshContext;
impl glfw::WindowRefreshCallback for WindowRefreshContext {
fn call(&self, _: &glfw::Window) {
println("Window refresh callback triggered.");
}
}
struct WindowFocusContext;
impl glfw::WindowFocusCallback for WindowFocusContext {
fn call(&self, _: &glfw::Window, activated: bool) {
if activated { println("Window focus gained."); }
else { println("Window focus lost."); }
}
}
struct WindowIconifyContext;
impl glfw::WindowIconifyCallback for WindowIconifyContext {
fn call(&self, _: &glfw::Window, iconified: bool) {
if iconified { println("Window was minimised"); }
else { println("Window was maximised."); }
}
}
struct FramebufferSizeContext;
impl glfw::FramebufferSizeCallback for FramebufferSizeContext {
fn call(&self, _: &glfw::Window, width: i32, height: i32) {
println!("Framebuffer size: {} {}", width, height);
}
}
struct KeyContext;
impl glfw::KeyCallback for KeyContext {
fn call(&self, window: &glfw::Window, key: glfw::Key, scancode: libc::c_int, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s} (scan code : {})",
key.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
},
scancode);
match (key, action) {
(glfw::KeyEscape, glfw::Press) => {
window.set_should_close(true);
}
(glfw::KeyR, glfw::Press) => {
// Resize should cause the window to "refresh"
let (window_width, window_height) = window.get_size();
window.set_size(window_width + 1, window_height);
window.set_size(window_width, window_height);
}
_ => ()
}
}
}
struct CharContext;
impl glfw::CharCallback for CharContext {
fn call(&self, _: &glfw::Window, character: char) {
println!("Character: {}", character);
}
}
struct MouseButtonContext;
impl glfw::MouseButtonCallback for MouseButtonContext {
fn call(&self, _: &glfw::Window, button: glfw::MouseButton, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s}",
button.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
});
}
}
struct CursorPosContext;
impl glfw::CursorPosCallback for CursorPosContext {
fn call(&self, window: &glfw::Window, xpos: f64, ypos: f64) {
window.set_title(format!("Cursor position: ({}, {})", xpos, ypos));
}
}
struct CursorEnterContext;
impl glfw::CursorEnterCallback for CursorEnterContext {
fn call(&self, _: &glfw::Window, entered: bool) {
if entered { println("Cursor entered window."); }
else { println("Cursor left window."); }
}
}
struct ScrollContext;
impl glfw::ScrollCallback for ScrollContext {
fn call(&self, window: &glfw::Window, x: f64, y: f64) {
window.set_title(format!("Scroll offset: ({}, {})", x, y));
}
} | window.set_focus_callback(~WindowFocusContext);
window.set_iconify_callback(~WindowIconifyContext);
window.set_framebuffer_size_callback(~FramebufferSizeContext); | random_line_split |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern mod glfw;
use std::libc;
#[link(name="glfw")]
extern {}
#[start]
fn start(argc: int, argv: **u8) -> int {
std::rt::start_on_main_thread(argc, argv, main)
}
fn main() {
glfw::set_error_callback(~ErrorContext);
do glfw::start {
glfw::window_hint::resizable(true);
let window = glfw::Window::create(800, 600, "Hello, I am a window.", glfw::Windowed)
.expect("Failed to create GLFW window.");
window.set_sticky_keys(true);
// Register event callbacks
window.set_pos_callback(~WindowPosContext);
window.set_size_callback(~WindowSizeContext);
window.set_close_callback(~WindowCloseContext);
window.set_refresh_callback(~WindowRefreshContext);
window.set_focus_callback(~WindowFocusContext);
window.set_iconify_callback(~WindowIconifyContext);
window.set_framebuffer_size_callback(~FramebufferSizeContext);
window.set_key_callback(~KeyContext);
window.set_char_callback(~CharContext);
window.set_mouse_button_callback(~MouseButtonContext);
window.set_cursor_pos_callback(~CursorPosContext);
window.set_cursor_enter_callback(~CursorEnterContext);
window.set_scroll_callback(~ScrollContext);
window.make_context_current();
while!window.should_close() {
glfw::poll_events();
}
}
}
struct ErrorContext;
impl glfw::ErrorCallback for ErrorContext {
fn call(&self, _: glfw::Error, description: ~str) {
println!("GLFW Error: {:s}", description);
}
}
struct WindowPosContext;
impl glfw::WindowPosCallback for WindowPosContext {
fn call(&self, window: &glfw::Window, x: i32, y: i32) {
window.set_title(format!("Window pos: ({}, {})", x, y));
}
}
struct WindowSizeContext;
impl glfw::WindowSizeCallback for WindowSizeContext {
fn call(&self, window: &glfw::Window, width: i32, height: i32) {
window.set_title(format!("Window size: ({}, {})", width, height));
}
}
struct WindowCloseContext;
impl glfw::WindowCloseCallback for WindowCloseContext {
fn call(&self, _: &glfw::Window) {
println("Window close requested.");
}
}
struct WindowRefreshContext;
impl glfw::WindowRefreshCallback for WindowRefreshContext {
fn call(&self, _: &glfw::Window) {
println("Window refresh callback triggered.");
}
}
struct WindowFocusContext;
impl glfw::WindowFocusCallback for WindowFocusContext {
fn call(&self, _: &glfw::Window, activated: bool) {
if activated { println("Window focus gained."); }
else { println("Window focus lost."); }
}
}
struct WindowIconifyContext;
impl glfw::WindowIconifyCallback for WindowIconifyContext {
fn call(&self, _: &glfw::Window, iconified: bool) |
}
struct FramebufferSizeContext;
impl glfw::FramebufferSizeCallback for FramebufferSizeContext {
fn call(&self, _: &glfw::Window, width: i32, height: i32) {
println!("Framebuffer size: {} {}", width, height);
}
}
struct KeyContext;
impl glfw::KeyCallback for KeyContext {
fn call(&self, window: &glfw::Window, key: glfw::Key, scancode: libc::c_int, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s} (scan code : {})",
key.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
},
scancode);
match (key, action) {
(glfw::KeyEscape, glfw::Press) => {
window.set_should_close(true);
}
(glfw::KeyR, glfw::Press) => {
// Resize should cause the window to "refresh"
let (window_width, window_height) = window.get_size();
window.set_size(window_width + 1, window_height);
window.set_size(window_width, window_height);
}
_ => ()
}
}
}
struct CharContext;
impl glfw::CharCallback for CharContext {
fn call(&self, _: &glfw::Window, character: char) {
println!("Character: {}", character);
}
}
struct MouseButtonContext;
impl glfw::MouseButtonCallback for MouseButtonContext {
fn call(&self, _: &glfw::Window, button: glfw::MouseButton, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s}",
button.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
});
}
}
struct CursorPosContext;
impl glfw::CursorPosCallback for CursorPosContext {
fn call(&self, window: &glfw::Window, xpos: f64, ypos: f64) {
window.set_title(format!("Cursor position: ({}, {})", xpos, ypos));
}
}
struct CursorEnterContext;
impl glfw::CursorEnterCallback for CursorEnterContext {
fn call(&self, _: &glfw::Window, entered: bool) {
if entered { println("Cursor entered window."); }
else { println("Cursor left window."); }
}
}
struct ScrollContext;
impl glfw::ScrollCallback for ScrollContext {
fn call(&self, window: &glfw::Window, x: f64, y: f64) {
window.set_title(format!("Scroll offset: ({}, {})", x, y));
}
}
| {
if iconified { println("Window was minimised"); }
else { println("Window was maximised."); }
} | identifier_body |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern mod glfw;
use std::libc;
#[link(name="glfw")]
extern {}
#[start]
fn start(argc: int, argv: **u8) -> int {
std::rt::start_on_main_thread(argc, argv, main)
}
fn main() {
glfw::set_error_callback(~ErrorContext);
do glfw::start {
glfw::window_hint::resizable(true);
let window = glfw::Window::create(800, 600, "Hello, I am a window.", glfw::Windowed)
.expect("Failed to create GLFW window.");
window.set_sticky_keys(true);
// Register event callbacks
window.set_pos_callback(~WindowPosContext);
window.set_size_callback(~WindowSizeContext);
window.set_close_callback(~WindowCloseContext);
window.set_refresh_callback(~WindowRefreshContext);
window.set_focus_callback(~WindowFocusContext);
window.set_iconify_callback(~WindowIconifyContext);
window.set_framebuffer_size_callback(~FramebufferSizeContext);
window.set_key_callback(~KeyContext);
window.set_char_callback(~CharContext);
window.set_mouse_button_callback(~MouseButtonContext);
window.set_cursor_pos_callback(~CursorPosContext);
window.set_cursor_enter_callback(~CursorEnterContext);
window.set_scroll_callback(~ScrollContext);
window.make_context_current();
while!window.should_close() {
glfw::poll_events();
}
}
}
struct ErrorContext;
impl glfw::ErrorCallback for ErrorContext {
fn | (&self, _: glfw::Error, description: ~str) {
println!("GLFW Error: {:s}", description);
}
}
struct WindowPosContext;
impl glfw::WindowPosCallback for WindowPosContext {
fn call(&self, window: &glfw::Window, x: i32, y: i32) {
window.set_title(format!("Window pos: ({}, {})", x, y));
}
}
struct WindowSizeContext;
impl glfw::WindowSizeCallback for WindowSizeContext {
fn call(&self, window: &glfw::Window, width: i32, height: i32) {
window.set_title(format!("Window size: ({}, {})", width, height));
}
}
struct WindowCloseContext;
impl glfw::WindowCloseCallback for WindowCloseContext {
fn call(&self, _: &glfw::Window) {
println("Window close requested.");
}
}
struct WindowRefreshContext;
impl glfw::WindowRefreshCallback for WindowRefreshContext {
fn call(&self, _: &glfw::Window) {
println("Window refresh callback triggered.");
}
}
struct WindowFocusContext;
impl glfw::WindowFocusCallback for WindowFocusContext {
fn call(&self, _: &glfw::Window, activated: bool) {
if activated { println("Window focus gained."); }
else { println("Window focus lost."); }
}
}
struct WindowIconifyContext;
impl glfw::WindowIconifyCallback for WindowIconifyContext {
fn call(&self, _: &glfw::Window, iconified: bool) {
if iconified { println("Window was minimised"); }
else { println("Window was maximised."); }
}
}
struct FramebufferSizeContext;
impl glfw::FramebufferSizeCallback for FramebufferSizeContext {
fn call(&self, _: &glfw::Window, width: i32, height: i32) {
println!("Framebuffer size: {} {}", width, height);
}
}
struct KeyContext;
impl glfw::KeyCallback for KeyContext {
fn call(&self, window: &glfw::Window, key: glfw::Key, scancode: libc::c_int, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s} (scan code : {})",
key.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
},
scancode);
match (key, action) {
(glfw::KeyEscape, glfw::Press) => {
window.set_should_close(true);
}
(glfw::KeyR, glfw::Press) => {
// Resize should cause the window to "refresh"
let (window_width, window_height) = window.get_size();
window.set_size(window_width + 1, window_height);
window.set_size(window_width, window_height);
}
_ => ()
}
}
}
struct CharContext;
impl glfw::CharCallback for CharContext {
fn call(&self, _: &glfw::Window, character: char) {
println!("Character: {}", character);
}
}
struct MouseButtonContext;
impl glfw::MouseButtonCallback for MouseButtonContext {
fn call(&self, _: &glfw::Window, button: glfw::MouseButton, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s}",
button.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
});
}
}
struct CursorPosContext;
impl glfw::CursorPosCallback for CursorPosContext {
fn call(&self, window: &glfw::Window, xpos: f64, ypos: f64) {
window.set_title(format!("Cursor position: ({}, {})", xpos, ypos));
}
}
struct CursorEnterContext;
impl glfw::CursorEnterCallback for CursorEnterContext {
fn call(&self, _: &glfw::Window, entered: bool) {
if entered { println("Cursor entered window."); }
else { println("Cursor left window."); }
}
}
struct ScrollContext;
impl glfw::ScrollCallback for ScrollContext {
fn call(&self, window: &glfw::Window, x: f64, y: f64) {
window.set_title(format!("Scroll offset: ({}, {})", x, y));
}
}
| call | identifier_name |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern mod glfw;
use std::libc;
#[link(name="glfw")]
extern {}
#[start]
fn start(argc: int, argv: **u8) -> int {
std::rt::start_on_main_thread(argc, argv, main)
}
fn main() {
glfw::set_error_callback(~ErrorContext);
do glfw::start {
glfw::window_hint::resizable(true);
let window = glfw::Window::create(800, 600, "Hello, I am a window.", glfw::Windowed)
.expect("Failed to create GLFW window.");
window.set_sticky_keys(true);
// Register event callbacks
window.set_pos_callback(~WindowPosContext);
window.set_size_callback(~WindowSizeContext);
window.set_close_callback(~WindowCloseContext);
window.set_refresh_callback(~WindowRefreshContext);
window.set_focus_callback(~WindowFocusContext);
window.set_iconify_callback(~WindowIconifyContext);
window.set_framebuffer_size_callback(~FramebufferSizeContext);
window.set_key_callback(~KeyContext);
window.set_char_callback(~CharContext);
window.set_mouse_button_callback(~MouseButtonContext);
window.set_cursor_pos_callback(~CursorPosContext);
window.set_cursor_enter_callback(~CursorEnterContext);
window.set_scroll_callback(~ScrollContext);
window.make_context_current();
while!window.should_close() {
glfw::poll_events();
}
}
}
struct ErrorContext;
impl glfw::ErrorCallback for ErrorContext {
fn call(&self, _: glfw::Error, description: ~str) {
println!("GLFW Error: {:s}", description);
}
}
struct WindowPosContext;
impl glfw::WindowPosCallback for WindowPosContext {
fn call(&self, window: &glfw::Window, x: i32, y: i32) {
window.set_title(format!("Window pos: ({}, {})", x, y));
}
}
struct WindowSizeContext;
impl glfw::WindowSizeCallback for WindowSizeContext {
fn call(&self, window: &glfw::Window, width: i32, height: i32) {
window.set_title(format!("Window size: ({}, {})", width, height));
}
}
struct WindowCloseContext;
impl glfw::WindowCloseCallback for WindowCloseContext {
fn call(&self, _: &glfw::Window) {
println("Window close requested.");
}
}
struct WindowRefreshContext;
impl glfw::WindowRefreshCallback for WindowRefreshContext {
fn call(&self, _: &glfw::Window) {
println("Window refresh callback triggered.");
}
}
struct WindowFocusContext;
impl glfw::WindowFocusCallback for WindowFocusContext {
fn call(&self, _: &glfw::Window, activated: bool) {
if activated { println("Window focus gained."); }
else { println("Window focus lost."); }
}
}
struct WindowIconifyContext;
impl glfw::WindowIconifyCallback for WindowIconifyContext {
fn call(&self, _: &glfw::Window, iconified: bool) {
if iconified { println("Window was minimised"); }
else { println("Window was maximised."); }
}
}
struct FramebufferSizeContext;
impl glfw::FramebufferSizeCallback for FramebufferSizeContext {
fn call(&self, _: &glfw::Window, width: i32, height: i32) {
println!("Framebuffer size: {} {}", width, height);
}
}
struct KeyContext;
impl glfw::KeyCallback for KeyContext {
fn call(&self, window: &glfw::Window, key: glfw::Key, scancode: libc::c_int, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s} (scan code : {})",
key.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
},
scancode);
match (key, action) {
(glfw::KeyEscape, glfw::Press) => {
window.set_should_close(true);
}
(glfw::KeyR, glfw::Press) => {
// Resize should cause the window to "refresh"
let (window_width, window_height) = window.get_size();
window.set_size(window_width + 1, window_height);
window.set_size(window_width, window_height);
}
_ => ()
}
}
}
struct CharContext;
impl glfw::CharCallback for CharContext {
fn call(&self, _: &glfw::Window, character: char) {
println!("Character: {}", character);
}
}
struct MouseButtonContext;
impl glfw::MouseButtonCallback for MouseButtonContext {
fn call(&self, _: &glfw::Window, button: glfw::MouseButton, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s}",
button.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
});
}
}
struct CursorPosContext;
impl glfw::CursorPosCallback for CursorPosContext {
fn call(&self, window: &glfw::Window, xpos: f64, ypos: f64) {
window.set_title(format!("Cursor position: ({}, {})", xpos, ypos));
}
}
struct CursorEnterContext;
impl glfw::CursorEnterCallback for CursorEnterContext {
fn call(&self, _: &glfw::Window, entered: bool) {
if entered { println("Cursor entered window."); }
else |
}
}
struct ScrollContext;
impl glfw::ScrollCallback for ScrollContext {
fn call(&self, window: &glfw::Window, x: f64, y: f64) {
window.set_title(format!("Scroll offset: ({}, {})", x, y));
}
}
| { println("Cursor left window."); } | conditional_block |
accept_language.rs | use header::{Language, QualityItem};
header! {
#[doc="`Accept-Language` header, defined in"]
#[doc="[RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.5)"]
#[doc=""]
#[doc="The `Accept-Language` header field can be used by user agents to"]
#[doc="indicate the set of natural languages that are preferred in the"]
#[doc="response."]
#[doc=""]
#[doc="# ABNF"]
#[doc="```plain"]
#[doc="Accept-Language = 1#( language-range [ weight ] )"] | #[doc="* `da, en-gb;q=0.8, en;q=0.7`"]
#[doc="* `en-us;q=1.0, en;q=0.5, fr`"]
(AcceptLanguage, "Accept-Language") => (QualityItem<Language>)+
test_accept_language {
// From the RFC
test_header!(test1, vec![b"da, en-gb;q=0.8, en;q=0.7"]);
// Own test
test_header!(
test2, vec![b"en-us, en; q=0.5, fr"],
Some(AcceptLanguage(vec![
qitem(Language {primary: "en".to_string(), sub: Some("us".to_string())}),
QualityItem::new(Language{primary: "en".to_string(), sub: None}, Quality(500)),
qitem(Language {primary: "fr".to_string(), sub: None}),
])));
}
}
bench_header!(bench, AcceptLanguage,
{ vec![b"en-us;q=1.0, en;q=0.5, fr".to_vec()] }); | #[doc="language-range = <language-range, see [RFC4647], Section 2.1>"]
#[doc="```"]
#[doc=""]
#[doc="# Example values"] | random_line_split |
manticore_protocol_cerberus_GetCert__req_to_wire.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//!! DO NOT EDIT!!
// To regenerate this file, run `fuzz/generate_proto_tests.py`.
#![no_main]
#![allow(non_snake_case)]
use libfuzzer_sys::fuzz_target;
use manticore::protocol::Command;
use manticore::protocol::wire::ToWire;
use manticore::protocol::borrowed::AsStatic;
use manticore::protocol::borrowed::Borrowed;
use manticore::protocol::cerberus::GetCert as C;
type Req<'a> = <C as Command<'a>>::Req;
fuzz_target!(|data: AsStatic<'static, Req<'static>>| {
let mut out = [0u8; 1024]; | let _ = Req::borrow(&data).to_wire(&mut &mut out[..]);
}); | random_line_split |
|
boxed.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A pointer type for heap allocation.
//!
//! `Box<T>`, casually referred to as a 'box', provides the simplest form of
//! heap allocation in Rust. Boxes provide ownership for this allocation, and
//! drop their contents when they go out of scope.
//!
//! # Examples
//!
//! Creating a box:
//!
//! ```
//! let x = Box::new(5);
//! ```
//!
//! Creating a recursive data structure:
//!
//! ```
//! #[derive(Debug)]
//! enum List<T> {
//! Cons(T, Box<List<T>>),
//! Nil,
//! }
//!
//! fn main() {
//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
//! println!("{:?}", list);
//! }
//! ```
//!
//! This will print `Cons(1, Cons(2, Nil))`.
//!
//! Recursive structures must be boxed, because if the definition of `Cons`
//! looked like this:
//!
//! ```rust,ignore
//! Cons(T, List<T>),
//! ```
//!
//! It wouldn't work. This is because the size of a `List` depends on how many
//! elements are in the list, and so we don't know how much memory to allocate
//! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
//! big `Cons` needs to be.
#![stable(feature = "rust1", since = "1.0.0")]
use core::prelude::*;
use core::any::Any;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{self, Hash};
use core::marker::Unsize;
use core::mem;
use core::ops::{CoerceUnsized, Deref, DerefMut};
use core::ptr::Unique;
use core::raw::{TraitObject};
/// A value that represents the heap. This is the default place that the `box`
/// keyword allocates into when no place is supplied.
///
/// The following two examples are equivalent:
///
/// ```
/// # #![feature(box_heap)]
/// #![feature(box_syntax)]
/// use std::boxed::HEAP;
///
/// fn main() {
/// let foo = box(HEAP) 5;
/// let foo = box 5;
/// }
/// ```
#[lang = "exchange_heap"]
#[unstable(feature = "box_heap",
reason = "may be renamed; uncertain about custom allocator design")]
pub const HEAP: () = ();
/// A pointer type for heap allocation.
///
/// See the [module-level documentation](../../std/boxed/index.html) for more.
#[lang = "owned_box"]
#[stable(feature = "rust1", since = "1.0.0")]
#[fundamental]
pub struct Box<T>(Unique<T>);
impl<T> Box<T> {
/// Allocates memory on the heap and then moves `x` into it.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
pub fn new(x: T) -> Box<T> {
box x
}
}
impl<T :?Sized> Box<T> {
/// Constructs a box from the raw pointer.
///
/// After this function call, pointer is owned by resulting box.
/// In particular, it means that `Box` destructor calls destructor
/// of `T` and releases memory. Since the way `Box` allocates and
/// releases memory is unspecified, the only valid pointer to pass
/// to this function is the one taken from another `Box` with
/// `Box::into_raw` function.
///
/// Function is unsafe, because improper use of this function may
/// lead to memory problems like double-free, for example if the
/// function is called twice on the same raw pointer.
#[unstable(feature = "box_raw",
reason = "may be renamed or moved out of Box scope")]
#[inline]
// NB: may want to be called from_ptr, see comments on CStr::from_ptr
pub unsafe fn from_raw(raw: *mut T) -> Self {
mem::transmute(raw)
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// # Examples
/// ```
/// # #![feature(box_raw)]
/// let seventeen = Box::new(17u32);
/// let raw = Box::into_raw(seventeen);
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "box_raw", reason = "may be renamed")]
#[inline]
// NB: may want to be called into_ptr, see comments on CStr::from_ptr
pub fn into_raw(b: Box<T>) -> *mut T {
unsafe { mem::transmute(b) }
}
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// # Examples
/// ```
/// # #![feature(box_raw)]
/// use std::boxed;
///
/// let seventeen = Box::new(17u32);
/// let raw = boxed::into_raw(seventeen);
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "box_raw", reason = "may be renamed")]
#[deprecated(since = "1.2.0", reason = "renamed to Box::into_raw")]
#[inline]
pub fn into_raw<T :?Sized>(b: Box<T>) -> *mut T {
Box::into_raw(b)
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Default> Default for Box<T> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<T> { box Default::default() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for Box<[T]> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for Box<T> {
/// Returns a new box with a `clone()` of this box's contents.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// let y = x.clone();
/// ```
#[inline]
fn clone(&self) -> Box<T> { box {(**self).clone()} }
/// Copies `source`'s contents into `self` without creating a new allocation.
///
/// # Examples
///
/// ```
/// # #![feature(box_raw)]
/// let x = Box::new(5);
/// let mut y = Box::new(10);
///
/// y.clone_from(&x);
///
/// assert_eq!(*y, 5);
/// ```
#[inline]
fn clone_from(&mut self, source: &Box<T>) {
(**self).clone_from(&(**source));
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialEq> PartialEq for Box<T> {
#[inline]
fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialOrd> PartialOrd for Box<T> {
#[inline]
fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
PartialOrd::partial_cmp(&**self, &**other)
}
#[inline]
fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
#[inline]
fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
#[inline]
fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
#[inline]
fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Ord> Ord for Box<T> {
#[inline]
fn cmp(&self, other: &Box<T>) -> Ordering {
Ord::cmp(&**self, &**other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Eq> Eq for Box<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Hash> Hash for Box<T> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
| pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let raw = Box::into_raw(self);
let to: TraitObject =
mem::transmute::<*mut Any, TraitObject>(raw);
// Extract the data pointer
Ok(Box::from_raw(to.data as *mut T))
}
} else {
Err(self)
}
}
}
impl Box<Any + Send> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type.
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any + Send>> {
<Box<Any>>::downcast(self).map_err(|s| unsafe {
// reapply the Send marker
mem::transmute::<Box<Any>, Box<Any + Send>>(s)
})
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display +?Sized> fmt::Display for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug +?Sized> fmt::Debug for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Pointer for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// It's not possible to extract the inner Uniq directly from the Box,
// instead we cast it to a *const which aliases the Unique
let ptr: *const T = &**self;
fmt::Pointer::fmt(&ptr, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Deref for Box<T> {
type Target = T;
fn deref(&self) -> &T { &**self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> DerefMut for Box<T> {
fn deref_mut(&mut self) -> &mut T { &mut **self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator +?Sized> Iterator for Box<I> {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> { (**self).next() }
fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator +?Sized> DoubleEndedIterator for Box<I> {
fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: ExactSizeIterator +?Sized> ExactSizeIterator for Box<I> {}
/// `FnBox` is a version of the `FnOnce` intended for use with boxed
/// closure objects. The idea is that where one would normally store a
/// `Box<FnOnce()>` in a data structure, you should use
/// `Box<FnBox()>`. The two traits behave essentially the same, except
/// that a `FnBox` closure can only be called if it is boxed. (Note
/// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
/// closures become directly usable.)
///
/// ### Example
///
/// Here is a snippet of code which creates a hashmap full of boxed
/// once closures and then removes them one by one, calling each
/// closure as it is removed. Note that the type of the closures
/// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
/// -> i32>`.
///
/// ```
/// #![feature(fnbox)]
///
/// use std::boxed::FnBox;
/// use std::collections::HashMap;
///
/// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
/// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
/// map.insert(1, Box::new(|| 22));
/// map.insert(2, Box::new(|| 44));
/// map
/// }
///
/// fn main() {
/// let mut map = make_map();
/// for i in &[1, 2] {
/// let f = map.remove(&i).unwrap();
/// assert_eq!(f(), i * 22);
/// }
/// }
/// ```
#[rustc_paren_sugar]
#[unstable(feature = "fnbox", reason = "Newly introduced")]
pub trait FnBox<A> {
type Output;
fn call_box(self: Box<Self>, args: A) -> Self::Output;
}
impl<A,F> FnBox<A> for F
where F: FnOnce<A>
{
type Output = F::Output;
fn call_box(self: Box<F>, args: A) -> F::Output {
self.call_once(args)
}
}
impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+'a> {
type Output = R;
extern "rust-call" fn call_once(self, args: A) -> R {
self.call_box(args)
}
}
impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+Send+'a> {
type Output = R;
extern "rust-call" fn call_once(self, args: A) -> R {
self.call_box(args)
}
}
impl<T:?Sized+Unsize<U>, U:?Sized> CoerceUnsized<Box<U>> for Box<T> {} | impl Box<Any> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type. | random_line_split |
boxed.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A pointer type for heap allocation.
//!
//! `Box<T>`, casually referred to as a 'box', provides the simplest form of
//! heap allocation in Rust. Boxes provide ownership for this allocation, and
//! drop their contents when they go out of scope.
//!
//! # Examples
//!
//! Creating a box:
//!
//! ```
//! let x = Box::new(5);
//! ```
//!
//! Creating a recursive data structure:
//!
//! ```
//! #[derive(Debug)]
//! enum List<T> {
//! Cons(T, Box<List<T>>),
//! Nil,
//! }
//!
//! fn main() {
//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
//! println!("{:?}", list);
//! }
//! ```
//!
//! This will print `Cons(1, Cons(2, Nil))`.
//!
//! Recursive structures must be boxed, because if the definition of `Cons`
//! looked like this:
//!
//! ```rust,ignore
//! Cons(T, List<T>),
//! ```
//!
//! It wouldn't work. This is because the size of a `List` depends on how many
//! elements are in the list, and so we don't know how much memory to allocate
//! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
//! big `Cons` needs to be.
#![stable(feature = "rust1", since = "1.0.0")]
use core::prelude::*;
use core::any::Any;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{self, Hash};
use core::marker::Unsize;
use core::mem;
use core::ops::{CoerceUnsized, Deref, DerefMut};
use core::ptr::Unique;
use core::raw::{TraitObject};
/// A value that represents the heap. This is the default place that the `box`
/// keyword allocates into when no place is supplied.
///
/// The following two examples are equivalent:
///
/// ```
/// # #![feature(box_heap)]
/// #![feature(box_syntax)]
/// use std::boxed::HEAP;
///
/// fn main() {
/// let foo = box(HEAP) 5;
/// let foo = box 5;
/// }
/// ```
#[lang = "exchange_heap"]
#[unstable(feature = "box_heap",
reason = "may be renamed; uncertain about custom allocator design")]
pub const HEAP: () = ();
/// A pointer type for heap allocation.
///
/// See the [module-level documentation](../../std/boxed/index.html) for more.
#[lang = "owned_box"]
#[stable(feature = "rust1", since = "1.0.0")]
#[fundamental]
pub struct Box<T>(Unique<T>);
impl<T> Box<T> {
/// Allocates memory on the heap and then moves `x` into it.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
pub fn new(x: T) -> Box<T> {
box x
}
}
impl<T :?Sized> Box<T> {
/// Constructs a box from the raw pointer.
///
/// After this function call, pointer is owned by resulting box.
/// In particular, it means that `Box` destructor calls destructor
/// of `T` and releases memory. Since the way `Box` allocates and
/// releases memory is unspecified, the only valid pointer to pass
/// to this function is the one taken from another `Box` with
/// `Box::into_raw` function.
///
/// Function is unsafe, because improper use of this function may
/// lead to memory problems like double-free, for example if the
/// function is called twice on the same raw pointer.
#[unstable(feature = "box_raw",
reason = "may be renamed or moved out of Box scope")]
#[inline]
// NB: may want to be called from_ptr, see comments on CStr::from_ptr
pub unsafe fn from_raw(raw: *mut T) -> Self {
mem::transmute(raw)
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// # Examples
/// ```
/// # #![feature(box_raw)]
/// let seventeen = Box::new(17u32);
/// let raw = Box::into_raw(seventeen);
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "box_raw", reason = "may be renamed")]
#[inline]
// NB: may want to be called into_ptr, see comments on CStr::from_ptr
pub fn into_raw(b: Box<T>) -> *mut T {
unsafe { mem::transmute(b) }
}
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// # Examples
/// ```
/// # #![feature(box_raw)]
/// use std::boxed;
///
/// let seventeen = Box::new(17u32);
/// let raw = boxed::into_raw(seventeen);
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "box_raw", reason = "may be renamed")]
#[deprecated(since = "1.2.0", reason = "renamed to Box::into_raw")]
#[inline]
pub fn into_raw<T :?Sized>(b: Box<T>) -> *mut T {
Box::into_raw(b)
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Default> Default for Box<T> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<T> { box Default::default() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for Box<[T]> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<[T]> |
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for Box<T> {
/// Returns a new box with a `clone()` of this box's contents.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// let y = x.clone();
/// ```
#[inline]
fn clone(&self) -> Box<T> { box {(**self).clone()} }
/// Copies `source`'s contents into `self` without creating a new allocation.
///
/// # Examples
///
/// ```
/// # #![feature(box_raw)]
/// let x = Box::new(5);
/// let mut y = Box::new(10);
///
/// y.clone_from(&x);
///
/// assert_eq!(*y, 5);
/// ```
#[inline]
fn clone_from(&mut self, source: &Box<T>) {
(**self).clone_from(&(**source));
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialEq> PartialEq for Box<T> {
#[inline]
fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialOrd> PartialOrd for Box<T> {
#[inline]
fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
PartialOrd::partial_cmp(&**self, &**other)
}
#[inline]
fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
#[inline]
fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
#[inline]
fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
#[inline]
fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Ord> Ord for Box<T> {
#[inline]
fn cmp(&self, other: &Box<T>) -> Ordering {
Ord::cmp(&**self, &**other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Eq> Eq for Box<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Hash> Hash for Box<T> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
impl Box<Any> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type.
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let raw = Box::into_raw(self);
let to: TraitObject =
mem::transmute::<*mut Any, TraitObject>(raw);
// Extract the data pointer
Ok(Box::from_raw(to.data as *mut T))
}
} else {
Err(self)
}
}
}
impl Box<Any + Send> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type.
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any + Send>> {
<Box<Any>>::downcast(self).map_err(|s| unsafe {
// reapply the Send marker
mem::transmute::<Box<Any>, Box<Any + Send>>(s)
})
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display +?Sized> fmt::Display for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug +?Sized> fmt::Debug for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Pointer for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// It's not possible to extract the inner Uniq directly from the Box,
// instead we cast it to a *const which aliases the Unique
let ptr: *const T = &**self;
fmt::Pointer::fmt(&ptr, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Deref for Box<T> {
type Target = T;
fn deref(&self) -> &T { &**self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> DerefMut for Box<T> {
fn deref_mut(&mut self) -> &mut T { &mut **self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator +?Sized> Iterator for Box<I> {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> { (**self).next() }
fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator +?Sized> DoubleEndedIterator for Box<I> {
fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: ExactSizeIterator +?Sized> ExactSizeIterator for Box<I> {}
/// `FnBox` is a version of the `FnOnce` intended for use with boxed
/// closure objects. The idea is that where one would normally store a
/// `Box<FnOnce()>` in a data structure, you should use
/// `Box<FnBox()>`. The two traits behave essentially the same, except
/// that a `FnBox` closure can only be called if it is boxed. (Note
/// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
/// closures become directly usable.)
///
/// ### Example
///
/// Here is a snippet of code which creates a hashmap full of boxed
/// once closures and then removes them one by one, calling each
/// closure as it is removed. Note that the type of the closures
/// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
/// -> i32>`.
///
/// ```
/// #![feature(fnbox)]
///
/// use std::boxed::FnBox;
/// use std::collections::HashMap;
///
/// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
/// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
/// map.insert(1, Box::new(|| 22));
/// map.insert(2, Box::new(|| 44));
/// map
/// }
///
/// fn main() {
/// let mut map = make_map();
/// for i in &[1, 2] {
/// let f = map.remove(&i).unwrap();
/// assert_eq!(f(), i * 22);
/// }
/// }
/// ```
#[rustc_paren_sugar]
#[unstable(feature = "fnbox", reason = "Newly introduced")]
pub trait FnBox<A> {
type Output;
fn call_box(self: Box<Self>, args: A) -> Self::Output;
}
impl<A,F> FnBox<A> for F
where F: FnOnce<A>
{
type Output = F::Output;
fn call_box(self: Box<F>, args: A) -> F::Output {
self.call_once(args)
}
}
impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+'a> {
type Output = R;
extern "rust-call" fn call_once(self, args: A) -> R {
self.call_box(args)
}
}
impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+Send+'a> {
type Output = R;
extern "rust-call" fn call_once(self, args: A) -> R {
self.call_box(args)
}
}
impl<T:?Sized+Unsize<U>, U:?Sized> CoerceUnsized<Box<U>> for Box<T> {}
| { Box::<[T; 0]>::new([]) } | identifier_body |
boxed.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A pointer type for heap allocation.
//!
//! `Box<T>`, casually referred to as a 'box', provides the simplest form of
//! heap allocation in Rust. Boxes provide ownership for this allocation, and
//! drop their contents when they go out of scope.
//!
//! # Examples
//!
//! Creating a box:
//!
//! ```
//! let x = Box::new(5);
//! ```
//!
//! Creating a recursive data structure:
//!
//! ```
//! #[derive(Debug)]
//! enum List<T> {
//! Cons(T, Box<List<T>>),
//! Nil,
//! }
//!
//! fn main() {
//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
//! println!("{:?}", list);
//! }
//! ```
//!
//! This will print `Cons(1, Cons(2, Nil))`.
//!
//! Recursive structures must be boxed, because if the definition of `Cons`
//! looked like this:
//!
//! ```rust,ignore
//! Cons(T, List<T>),
//! ```
//!
//! It wouldn't work. This is because the size of a `List` depends on how many
//! elements are in the list, and so we don't know how much memory to allocate
//! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
//! big `Cons` needs to be.
#![stable(feature = "rust1", since = "1.0.0")]
use core::prelude::*;
use core::any::Any;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{self, Hash};
use core::marker::Unsize;
use core::mem;
use core::ops::{CoerceUnsized, Deref, DerefMut};
use core::ptr::Unique;
use core::raw::{TraitObject};
/// A value that represents the heap. This is the default place that the `box`
/// keyword allocates into when no place is supplied.
///
/// The following two examples are equivalent:
///
/// ```
/// # #![feature(box_heap)]
/// #![feature(box_syntax)]
/// use std::boxed::HEAP;
///
/// fn main() {
/// let foo = box(HEAP) 5;
/// let foo = box 5;
/// }
/// ```
#[lang = "exchange_heap"]
#[unstable(feature = "box_heap",
reason = "may be renamed; uncertain about custom allocator design")]
pub const HEAP: () = ();
/// A pointer type for heap allocation.
///
/// See the [module-level documentation](../../std/boxed/index.html) for more.
#[lang = "owned_box"]
#[stable(feature = "rust1", since = "1.0.0")]
#[fundamental]
pub struct Box<T>(Unique<T>);
impl<T> Box<T> {
/// Allocates memory on the heap and then moves `x` into it.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
pub fn new(x: T) -> Box<T> {
box x
}
}
impl<T :?Sized> Box<T> {
/// Constructs a box from the raw pointer.
///
/// After this function call, pointer is owned by resulting box.
/// In particular, it means that `Box` destructor calls destructor
/// of `T` and releases memory. Since the way `Box` allocates and
/// releases memory is unspecified, the only valid pointer to pass
/// to this function is the one taken from another `Box` with
/// `Box::into_raw` function.
///
/// Function is unsafe, because improper use of this function may
/// lead to memory problems like double-free, for example if the
/// function is called twice on the same raw pointer.
#[unstable(feature = "box_raw",
reason = "may be renamed or moved out of Box scope")]
#[inline]
// NB: may want to be called from_ptr, see comments on CStr::from_ptr
pub unsafe fn from_raw(raw: *mut T) -> Self {
mem::transmute(raw)
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// # Examples
/// ```
/// # #![feature(box_raw)]
/// let seventeen = Box::new(17u32);
/// let raw = Box::into_raw(seventeen);
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "box_raw", reason = "may be renamed")]
#[inline]
// NB: may want to be called into_ptr, see comments on CStr::from_ptr
pub fn into_raw(b: Box<T>) -> *mut T {
unsafe { mem::transmute(b) }
}
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// # Examples
/// ```
/// # #![feature(box_raw)]
/// use std::boxed;
///
/// let seventeen = Box::new(17u32);
/// let raw = boxed::into_raw(seventeen);
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "box_raw", reason = "may be renamed")]
#[deprecated(since = "1.2.0", reason = "renamed to Box::into_raw")]
#[inline]
pub fn into_raw<T :?Sized>(b: Box<T>) -> *mut T {
Box::into_raw(b)
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Default> Default for Box<T> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<T> { box Default::default() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for Box<[T]> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for Box<T> {
/// Returns a new box with a `clone()` of this box's contents.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// let y = x.clone();
/// ```
#[inline]
fn clone(&self) -> Box<T> { box {(**self).clone()} }
/// Copies `source`'s contents into `self` without creating a new allocation.
///
/// # Examples
///
/// ```
/// # #![feature(box_raw)]
/// let x = Box::new(5);
/// let mut y = Box::new(10);
///
/// y.clone_from(&x);
///
/// assert_eq!(*y, 5);
/// ```
#[inline]
fn clone_from(&mut self, source: &Box<T>) {
(**self).clone_from(&(**source));
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialEq> PartialEq for Box<T> {
#[inline]
fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialOrd> PartialOrd for Box<T> {
#[inline]
fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
PartialOrd::partial_cmp(&**self, &**other)
}
#[inline]
fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
#[inline]
fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
#[inline]
fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
#[inline]
fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Ord> Ord for Box<T> {
#[inline]
fn cmp(&self, other: &Box<T>) -> Ordering {
Ord::cmp(&**self, &**other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Eq> Eq for Box<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Hash> Hash for Box<T> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
impl Box<Any> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type.
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
if self.is::<T>() | else {
Err(self)
}
}
}
impl Box<Any + Send> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type.
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any + Send>> {
<Box<Any>>::downcast(self).map_err(|s| unsafe {
// reapply the Send marker
mem::transmute::<Box<Any>, Box<Any + Send>>(s)
})
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display +?Sized> fmt::Display for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug +?Sized> fmt::Debug for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Pointer for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// It's not possible to extract the inner Uniq directly from the Box,
// instead we cast it to a *const which aliases the Unique
let ptr: *const T = &**self;
fmt::Pointer::fmt(&ptr, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Deref for Box<T> {
type Target = T;
fn deref(&self) -> &T { &**self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> DerefMut for Box<T> {
fn deref_mut(&mut self) -> &mut T { &mut **self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator +?Sized> Iterator for Box<I> {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> { (**self).next() }
fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator +?Sized> DoubleEndedIterator for Box<I> {
fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: ExactSizeIterator +?Sized> ExactSizeIterator for Box<I> {}
/// `FnBox` is a version of the `FnOnce` intended for use with boxed
/// closure objects. The idea is that where one would normally store a
/// `Box<FnOnce()>` in a data structure, you should use
/// `Box<FnBox()>`. The two traits behave essentially the same, except
/// that a `FnBox` closure can only be called if it is boxed. (Note
/// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
/// closures become directly usable.)
///
/// ### Example
///
/// Here is a snippet of code which creates a hashmap full of boxed
/// once closures and then removes them one by one, calling each
/// closure as it is removed. Note that the type of the closures
/// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
/// -> i32>`.
///
/// ```
/// #![feature(fnbox)]
///
/// use std::boxed::FnBox;
/// use std::collections::HashMap;
///
/// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
/// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
/// map.insert(1, Box::new(|| 22));
/// map.insert(2, Box::new(|| 44));
/// map
/// }
///
/// fn main() {
/// let mut map = make_map();
/// for i in &[1, 2] {
/// let f = map.remove(&i).unwrap();
/// assert_eq!(f(), i * 22);
/// }
/// }
/// ```
#[rustc_paren_sugar]
#[unstable(feature = "fnbox", reason = "Newly introduced")]
pub trait FnBox<A> {
type Output;
fn call_box(self: Box<Self>, args: A) -> Self::Output;
}
impl<A,F> FnBox<A> for F
where F: FnOnce<A>
{
type Output = F::Output;
fn call_box(self: Box<F>, args: A) -> F::Output {
self.call_once(args)
}
}
impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+'a> {
type Output = R;
extern "rust-call" fn call_once(self, args: A) -> R {
self.call_box(args)
}
}
impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+Send+'a> {
type Output = R;
extern "rust-call" fn call_once(self, args: A) -> R {
self.call_box(args)
}
}
impl<T:?Sized+Unsize<U>, U:?Sized> CoerceUnsized<Box<U>> for Box<T> {}
| {
unsafe {
// Get the raw representation of the trait object
let raw = Box::into_raw(self);
let to: TraitObject =
mem::transmute::<*mut Any, TraitObject>(raw);
// Extract the data pointer
Ok(Box::from_raw(to.data as *mut T))
}
} | conditional_block |
boxed.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A pointer type for heap allocation.
//!
//! `Box<T>`, casually referred to as a 'box', provides the simplest form of
//! heap allocation in Rust. Boxes provide ownership for this allocation, and
//! drop their contents when they go out of scope.
//!
//! # Examples
//!
//! Creating a box:
//!
//! ```
//! let x = Box::new(5);
//! ```
//!
//! Creating a recursive data structure:
//!
//! ```
//! #[derive(Debug)]
//! enum List<T> {
//! Cons(T, Box<List<T>>),
//! Nil,
//! }
//!
//! fn main() {
//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
//! println!("{:?}", list);
//! }
//! ```
//!
//! This will print `Cons(1, Cons(2, Nil))`.
//!
//! Recursive structures must be boxed, because if the definition of `Cons`
//! looked like this:
//!
//! ```rust,ignore
//! Cons(T, List<T>),
//! ```
//!
//! It wouldn't work. This is because the size of a `List` depends on how many
//! elements are in the list, and so we don't know how much memory to allocate
//! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
//! big `Cons` needs to be.
#![stable(feature = "rust1", since = "1.0.0")]
use core::prelude::*;
use core::any::Any;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{self, Hash};
use core::marker::Unsize;
use core::mem;
use core::ops::{CoerceUnsized, Deref, DerefMut};
use core::ptr::Unique;
use core::raw::{TraitObject};
/// A value that represents the heap. This is the default place that the `box`
/// keyword allocates into when no place is supplied.
///
/// The following two examples are equivalent:
///
/// ```
/// # #![feature(box_heap)]
/// #![feature(box_syntax)]
/// use std::boxed::HEAP;
///
/// fn main() {
/// let foo = box(HEAP) 5;
/// let foo = box 5;
/// }
/// ```
#[lang = "exchange_heap"]
#[unstable(feature = "box_heap",
reason = "may be renamed; uncertain about custom allocator design")]
pub const HEAP: () = ();
/// A pointer type for heap allocation.
///
/// See the [module-level documentation](../../std/boxed/index.html) for more.
#[lang = "owned_box"]
#[stable(feature = "rust1", since = "1.0.0")]
#[fundamental]
pub struct Box<T>(Unique<T>);
impl<T> Box<T> {
/// Allocates memory on the heap and then moves `x` into it.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
pub fn new(x: T) -> Box<T> {
box x
}
}
impl<T :?Sized> Box<T> {
/// Constructs a box from the raw pointer.
///
/// After this function call, pointer is owned by resulting box.
/// In particular, it means that `Box` destructor calls destructor
/// of `T` and releases memory. Since the way `Box` allocates and
/// releases memory is unspecified, the only valid pointer to pass
/// to this function is the one taken from another `Box` with
/// `Box::into_raw` function.
///
/// Function is unsafe, because improper use of this function may
/// lead to memory problems like double-free, for example if the
/// function is called twice on the same raw pointer.
#[unstable(feature = "box_raw",
reason = "may be renamed or moved out of Box scope")]
#[inline]
// NB: may want to be called from_ptr, see comments on CStr::from_ptr
pub unsafe fn from_raw(raw: *mut T) -> Self {
mem::transmute(raw)
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// # Examples
/// ```
/// # #![feature(box_raw)]
/// let seventeen = Box::new(17u32);
/// let raw = Box::into_raw(seventeen);
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "box_raw", reason = "may be renamed")]
#[inline]
// NB: may want to be called into_ptr, see comments on CStr::from_ptr
pub fn into_raw(b: Box<T>) -> *mut T {
unsafe { mem::transmute(b) }
}
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// # Examples
/// ```
/// # #![feature(box_raw)]
/// use std::boxed;
///
/// let seventeen = Box::new(17u32);
/// let raw = boxed::into_raw(seventeen);
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "box_raw", reason = "may be renamed")]
#[deprecated(since = "1.2.0", reason = "renamed to Box::into_raw")]
#[inline]
pub fn into_raw<T :?Sized>(b: Box<T>) -> *mut T {
Box::into_raw(b)
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Default> Default for Box<T> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<T> { box Default::default() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for Box<[T]> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for Box<T> {
/// Returns a new box with a `clone()` of this box's contents.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// let y = x.clone();
/// ```
#[inline]
fn clone(&self) -> Box<T> { box {(**self).clone()} }
/// Copies `source`'s contents into `self` without creating a new allocation.
///
/// # Examples
///
/// ```
/// # #![feature(box_raw)]
/// let x = Box::new(5);
/// let mut y = Box::new(10);
///
/// y.clone_from(&x);
///
/// assert_eq!(*y, 5);
/// ```
#[inline]
fn clone_from(&mut self, source: &Box<T>) {
(**self).clone_from(&(**source));
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialEq> PartialEq for Box<T> {
#[inline]
fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialOrd> PartialOrd for Box<T> {
#[inline]
fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
PartialOrd::partial_cmp(&**self, &**other)
}
#[inline]
fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
#[inline]
fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
#[inline]
fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
#[inline]
fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Ord> Ord for Box<T> {
#[inline]
fn cmp(&self, other: &Box<T>) -> Ordering {
Ord::cmp(&**self, &**other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Eq> Eq for Box<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Hash> Hash for Box<T> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
impl Box<Any> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type.
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let raw = Box::into_raw(self);
let to: TraitObject =
mem::transmute::<*mut Any, TraitObject>(raw);
// Extract the data pointer
Ok(Box::from_raw(to.data as *mut T))
}
} else {
Err(self)
}
}
}
impl Box<Any + Send> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
/// Attempt to downcast the box to a concrete type.
pub fn | <T: Any>(self) -> Result<Box<T>, Box<Any + Send>> {
<Box<Any>>::downcast(self).map_err(|s| unsafe {
// reapply the Send marker
mem::transmute::<Box<Any>, Box<Any + Send>>(s)
})
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display +?Sized> fmt::Display for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug +?Sized> fmt::Debug for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Pointer for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// It's not possible to extract the inner Uniq directly from the Box,
// instead we cast it to a *const which aliases the Unique
let ptr: *const T = &**self;
fmt::Pointer::fmt(&ptr, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Deref for Box<T> {
type Target = T;
fn deref(&self) -> &T { &**self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> DerefMut for Box<T> {
fn deref_mut(&mut self) -> &mut T { &mut **self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator +?Sized> Iterator for Box<I> {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> { (**self).next() }
fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator +?Sized> DoubleEndedIterator for Box<I> {
fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: ExactSizeIterator +?Sized> ExactSizeIterator for Box<I> {}
/// `FnBox` is a version of the `FnOnce` intended for use with boxed
/// closure objects. The idea is that where one would normally store a
/// `Box<FnOnce()>` in a data structure, you should use
/// `Box<FnBox()>`. The two traits behave essentially the same, except
/// that a `FnBox` closure can only be called if it is boxed. (Note
/// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
/// closures become directly usable.)
///
/// ### Example
///
/// Here is a snippet of code which creates a hashmap full of boxed
/// once closures and then removes them one by one, calling each
/// closure as it is removed. Note that the type of the closures
/// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
/// -> i32>`.
///
/// ```
/// #![feature(fnbox)]
///
/// use std::boxed::FnBox;
/// use std::collections::HashMap;
///
/// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
/// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
/// map.insert(1, Box::new(|| 22));
/// map.insert(2, Box::new(|| 44));
/// map
/// }
///
/// fn main() {
/// let mut map = make_map();
/// for i in &[1, 2] {
/// let f = map.remove(&i).unwrap();
/// assert_eq!(f(), i * 22);
/// }
/// }
/// ```
#[rustc_paren_sugar]
#[unstable(feature = "fnbox", reason = "Newly introduced")]
pub trait FnBox<A> {
type Output;
fn call_box(self: Box<Self>, args: A) -> Self::Output;
}
impl<A,F> FnBox<A> for F
where F: FnOnce<A>
{
type Output = F::Output;
fn call_box(self: Box<F>, args: A) -> F::Output {
self.call_once(args)
}
}
impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+'a> {
type Output = R;
extern "rust-call" fn call_once(self, args: A) -> R {
self.call_box(args)
}
}
impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+Send+'a> {
type Output = R;
extern "rust-call" fn call_once(self, args: A) -> R {
self.call_box(args)
}
}
impl<T:?Sized+Unsize<U>, U:?Sized> CoerceUnsized<Box<U>> for Box<T> {}
| downcast | identifier_name |
gash.rs | //
// gash.rs
//
// Starting code for PS2
// Running on Rust 0.9
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu, David Evans
// Version 0.4
//
extern mod extra;
use std::{io, run, os};
use std::io::buffered::BufferedReader;
use std::io::stdin;
use extra::getopts;
use std::io::File;
use std::io::signal::{Listener, Interrupt};
use std::libc;
struct Shell {
cmd_prompt: ~str,
log: ~[~str],
}
impl Shell {
fn new(prompt_str: &str) -> Shell {
Shell {
cmd_prompt: prompt_str.to_owned(),
log: ~[],
}
}
fn run(&mut self) {
let mut stdin = BufferedReader::new(stdin());
loop {
print(self.cmd_prompt); // prints 'gash >'
io::stdio::flush();
let line = stdin.read_line().unwrap(); // reads whats on the line
let cmd_line = line.trim().to_owned(); // removes leading and trailing whitespace
let user_input: ~[&str] = cmd_line.split(' ').collect();
let mut line: ~str = ~"";
let length: uint = user_input.len();
let mut i : uint = 0;
while (i < length){
let string = user_input[i].clone();
let mut input = ~"";
match string {
"<" => {
if!(i < length-1)
{println!("invalid command");}
let file = user_input[i+1].to_owned(); // get file name
let command = line.trim().to_owned();
line = command + " " + file;
i += 1;
}
">" => {
if!(i < length-1)
{println!("invalid command");}
let file = user_input[i + 1].to_owned();
let command = line.trim().to_owned();
let message = self.find_prog(command, true).to_owned();
if message == ~"none"{
i = length;
}
write_file(file,message);
line = ~"";
i += 1;
}
"|" => {
let command = line.trim().to_owned();
let mut command2: ~str = ~"";
for k in range(i + 1,length){
match user_input[k]{
"<" => {break;}
">" =>{break;}
"|" => {break;}
_ => {command2 = command2 + " " + user_input[k];}
}
i = k;
}
command2 = command2.trim().to_owned();
let mut message = self.find_prog(command, true).to_owned();
if message == ~"none"{
i = length;
}
match File::create(&Path::new("f.md")) {
Some(mut file) => {
file.write_str(message);
}
None =>{
println("Opening file failed!");
}
}
//println(command2);
message = self.find_prog(command2 + " " + "f.md", true).to_owned();
self.find_prog("rm f.md", true);
println!("{}", message);
line = ~"";
}
_ => {
line = line + " " + string;
}
}
i += 1;
}
let result = self.find_prog(line.trim(),false);
match result {
~"return" => {unsafe{libc::exit(1 as libc::c_int)}}
//~"continue" => {continue;}
_ => {}
}
}
}
fn find_prog(&mut self, cmd_line : &str, output: bool) -> ~str{
let program = cmd_line.splitn(' ', 1).nth(0).expect("no program"); // get command
match program {
"" => { return ~"continue"; }
"exit" => { return ~"return"; }
"history" => {
self.log.push(cmd_line.to_owned());
return self.run_history(output);
}
"cd" => {
self.log.push(cmd_line.to_owned());
self.run_cd(cmd_line);
}
_ => {
self.log.push(cmd_line.to_owned());
return self.run_cmdline(cmd_line, output);
} |
fn run_cmdline(&mut self, cmd_line: &str, output: bool) -> ~str {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x!= "" { Some(x.to_owned()) } else { None }).to_owned_vec();
let length = argv.len()-1;
if argv[length] == ~"&" {
argv.remove(length);
let program: ~str = argv.remove(0);
let argv2 = argv.clone();
if self.cmd_exists(program){
spawn(proc() {run::process_status(program, argv2);});
}
else {
println!("{:s}: command not found", program);
}
return ~"none";
}
else{
if argv.len() > 0 {
let program: ~str = argv.remove(0);
return self.run_cmd(program, argv, output);
}
}
return ~"none";
}
fn run_cmd(&mut self, program: &str, argv: &[~str], output: bool)->~str {
if self.cmd_exists(program) {
if output == false {
run::process_status(program, argv);
return ~"none";
}
else {
let output = run::process_output(program, argv);
let output_str = output.unwrap().output;
return std::str::from_utf8(output_str).to_owned();
}
} else {
println!("{:s}: command not found", program);
}
return ~"none";
}
fn cmd_exists(&mut self, cmd_path: &str) -> bool {
let ret = run::process_output("which", [cmd_path.to_owned()]);
return ret.expect("exit code error.").status.success();
}
fn run_history(&mut self, output: bool)-> ~str{
if output == false{
for i in range(0, self.log.len()) {
println!("{}", self.log[i]);
}
return ~"none";
}
else {
let mut out: ~str = ~"";
for i in range(0, self.log.len()){
out = out + self.log[i].to_owned();
}
return out;
}
}
fn run_cd(&mut self, cmd_line: &str) {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x!= "" { Some(x.to_owned()) } else { None }).to_owned_vec();
if argv.len() > 0 {
if argv.len() == 1 {
self.go_to_home_dir();
return ;
}
let string: ~str = argv.remove(1);
if string == ~"$HOME" || string == ~"$home"{
self.go_to_home_dir();
return ;
}
let path = ~Path::new(string);
if (path.exists()){
let success = std::os::change_dir(path);
if!success {
println("Invalid path");
}
}
}
else {
println("Invalid input");
}
}
fn go_to_home_dir(&mut self){
match std::os::homedir() {
Some(path) => {
std::os::change_dir(&path);
}
None => {
println("$HOME is not set");
}
}
}
}
fn write_file(filename: ~str, message: ~str){
match File::create(&Path::new(filename)) {
Some(mut file) => {
file.write_str(message);
}
None =>{
println("Opening file failed!");
}
}
}
/*
fn read_file(filename: ~str) -> ~str{
let path = Path::new(filename);
match File::open(&path) {
Some(file) => {
let mut reader = BufferedReader::new(file);
let input = reader.read_to_str();
return input;
}
None =>{
println("Opening file failed");
return ~"";
}
}
}
*/
fn get_cmdline_from_args() -> Option<~str> {
/* Begin processing program arguments and initiate the parameters. */
let args = os::args();
let opts = ~[
getopts::optopt("c")
];
let matches = match getopts::getopts(args.tail(), opts) {
Ok(m) => { m }
Err(f) => { fail!(f.to_err_msg()) }
};
if matches.opt_present("c") {
let cmd_str = match matches.opt_str("c") {
Some(cmd_str) => {cmd_str.to_owned()},
None => {~""}
};
return Some(cmd_str);
} else {
return None;
}
}
fn main() {
let opt_cmd_line = get_cmdline_from_args();
spawn(proc () {
let mut listener = Listener::new();
listener.register(Interrupt);
loop{
match listener.port.recv() {
Interrupt => print!(""),
_ => (),
}
}
});
match opt_cmd_line {
Some(cmd_line) => {Shell::new("").run_cmdline(cmd_line, false);}
None => {Shell::new("gash > ").run();}
}
} | }
~"fine"
} | random_line_split |
gash.rs | //
// gash.rs
//
// Starting code for PS2
// Running on Rust 0.9
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu, David Evans
// Version 0.4
//
extern mod extra;
use std::{io, run, os};
use std::io::buffered::BufferedReader;
use std::io::stdin;
use extra::getopts;
use std::io::File;
use std::io::signal::{Listener, Interrupt};
use std::libc;
struct Shell {
cmd_prompt: ~str,
log: ~[~str],
}
impl Shell {
fn new(prompt_str: &str) -> Shell {
Shell {
cmd_prompt: prompt_str.to_owned(),
log: ~[],
}
}
fn run(&mut self) {
let mut stdin = BufferedReader::new(stdin());
loop {
print(self.cmd_prompt); // prints 'gash >'
io::stdio::flush();
let line = stdin.read_line().unwrap(); // reads whats on the line
let cmd_line = line.trim().to_owned(); // removes leading and trailing whitespace
let user_input: ~[&str] = cmd_line.split(' ').collect();
let mut line: ~str = ~"";
let length: uint = user_input.len();
let mut i : uint = 0;
while (i < length){
let string = user_input[i].clone();
let mut input = ~"";
match string {
"<" => {
if!(i < length-1)
{println!("invalid command");}
let file = user_input[i+1].to_owned(); // get file name
let command = line.trim().to_owned();
line = command + " " + file;
i += 1;
}
">" => {
if!(i < length-1)
{println!("invalid command");}
let file = user_input[i + 1].to_owned();
let command = line.trim().to_owned();
let message = self.find_prog(command, true).to_owned();
if message == ~"none"{
i = length;
}
write_file(file,message);
line = ~"";
i += 1;
}
"|" => {
let command = line.trim().to_owned();
let mut command2: ~str = ~"";
for k in range(i + 1,length){
match user_input[k]{
"<" => {break;}
">" =>{break;}
"|" => {break;}
_ => {command2 = command2 + " " + user_input[k];}
}
i = k;
}
command2 = command2.trim().to_owned();
let mut message = self.find_prog(command, true).to_owned();
if message == ~"none"{
i = length;
}
match File::create(&Path::new("f.md")) {
Some(mut file) => {
file.write_str(message);
}
None =>{
println("Opening file failed!");
}
}
//println(command2);
message = self.find_prog(command2 + " " + "f.md", true).to_owned();
self.find_prog("rm f.md", true);
println!("{}", message);
line = ~"";
}
_ => {
line = line + " " + string;
}
}
i += 1;
}
let result = self.find_prog(line.trim(),false);
match result {
~"return" => {unsafe{libc::exit(1 as libc::c_int)}}
//~"continue" => {continue;}
_ => {}
}
}
}
fn find_prog(&mut self, cmd_line : &str, output: bool) -> ~str{
let program = cmd_line.splitn(' ', 1).nth(0).expect("no program"); // get command
match program {
"" => { return ~"continue"; }
"exit" => { return ~"return"; }
"history" => {
self.log.push(cmd_line.to_owned());
return self.run_history(output);
}
"cd" => {
self.log.push(cmd_line.to_owned());
self.run_cd(cmd_line);
}
_ => {
self.log.push(cmd_line.to_owned());
return self.run_cmdline(cmd_line, output);
}
}
~"fine"
}
fn run_cmdline(&mut self, cmd_line: &str, output: bool) -> ~str {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x!= "" { Some(x.to_owned()) } else { None }).to_owned_vec();
let length = argv.len()-1;
if argv[length] == ~"&" {
argv.remove(length);
let program: ~str = argv.remove(0);
let argv2 = argv.clone();
if self.cmd_exists(program){
spawn(proc() {run::process_status(program, argv2);});
}
else {
println!("{:s}: command not found", program);
}
return ~"none";
}
else{
if argv.len() > 0 {
let program: ~str = argv.remove(0);
return self.run_cmd(program, argv, output);
}
}
return ~"none";
}
fn run_cmd(&mut self, program: &str, argv: &[~str], output: bool)->~str {
if self.cmd_exists(program) {
if output == false {
run::process_status(program, argv);
return ~"none";
}
else {
let output = run::process_output(program, argv);
let output_str = output.unwrap().output;
return std::str::from_utf8(output_str).to_owned();
}
} else {
println!("{:s}: command not found", program);
}
return ~"none";
}
fn cmd_exists(&mut self, cmd_path: &str) -> bool {
let ret = run::process_output("which", [cmd_path.to_owned()]);
return ret.expect("exit code error.").status.success();
}
fn run_history(&mut self, output: bool)-> ~str |
fn run_cd(&mut self, cmd_line: &str) {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x!= "" { Some(x.to_owned()) } else { None }).to_owned_vec();
if argv.len() > 0 {
if argv.len() == 1 {
self.go_to_home_dir();
return ;
}
let string: ~str = argv.remove(1);
if string == ~"$HOME" || string == ~"$home"{
self.go_to_home_dir();
return ;
}
let path = ~Path::new(string);
if (path.exists()){
let success = std::os::change_dir(path);
if!success {
println("Invalid path");
}
}
}
else {
println("Invalid input");
}
}
fn go_to_home_dir(&mut self){
match std::os::homedir() {
Some(path) => {
std::os::change_dir(&path);
}
None => {
println("$HOME is not set");
}
}
}
}
fn write_file(filename: ~str, message: ~str){
match File::create(&Path::new(filename)) {
Some(mut file) => {
file.write_str(message);
}
None =>{
println("Opening file failed!");
}
}
}
/*
fn read_file(filename: ~str) -> ~str{
let path = Path::new(filename);
match File::open(&path) {
Some(file) => {
let mut reader = BufferedReader::new(file);
let input = reader.read_to_str();
return input;
}
None =>{
println("Opening file failed");
return ~"";
}
}
}
*/
fn get_cmdline_from_args() -> Option<~str> {
/* Begin processing program arguments and initiate the parameters. */
let args = os::args();
let opts = ~[
getopts::optopt("c")
];
let matches = match getopts::getopts(args.tail(), opts) {
Ok(m) => { m }
Err(f) => { fail!(f.to_err_msg()) }
};
if matches.opt_present("c") {
let cmd_str = match matches.opt_str("c") {
Some(cmd_str) => {cmd_str.to_owned()},
None => {~""}
};
return Some(cmd_str);
} else {
return None;
}
}
fn main() {
let opt_cmd_line = get_cmdline_from_args();
spawn(proc () {
let mut listener = Listener::new();
listener.register(Interrupt);
loop{
match listener.port.recv() {
Interrupt => print!(""),
_ => (),
}
}
});
match opt_cmd_line {
Some(cmd_line) => {Shell::new("").run_cmdline(cmd_line, false);}
None => {Shell::new("gash > ").run();}
}
}
| {
if output == false{
for i in range(0, self.log.len()) {
println!("{}", self.log[i]);
}
return ~"none";
}
else {
let mut out: ~str = ~"";
for i in range(0, self.log.len()){
out = out + self.log[i].to_owned();
}
return out;
}
} | identifier_body |
gash.rs | //
// gash.rs
//
// Starting code for PS2
// Running on Rust 0.9
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu, David Evans
// Version 0.4
//
extern mod extra;
use std::{io, run, os};
use std::io::buffered::BufferedReader;
use std::io::stdin;
use extra::getopts;
use std::io::File;
use std::io::signal::{Listener, Interrupt};
use std::libc;
struct Shell {
cmd_prompt: ~str,
log: ~[~str],
}
impl Shell {
fn new(prompt_str: &str) -> Shell {
Shell {
cmd_prompt: prompt_str.to_owned(),
log: ~[],
}
}
fn run(&mut self) {
let mut stdin = BufferedReader::new(stdin());
loop {
print(self.cmd_prompt); // prints 'gash >'
io::stdio::flush();
let line = stdin.read_line().unwrap(); // reads whats on the line
let cmd_line = line.trim().to_owned(); // removes leading and trailing whitespace
let user_input: ~[&str] = cmd_line.split(' ').collect();
let mut line: ~str = ~"";
let length: uint = user_input.len();
let mut i : uint = 0;
while (i < length){
let string = user_input[i].clone();
let mut input = ~"";
match string {
"<" => {
if!(i < length-1)
{println!("invalid command");}
let file = user_input[i+1].to_owned(); // get file name
let command = line.trim().to_owned();
line = command + " " + file;
i += 1;
}
">" => {
if!(i < length-1)
{println!("invalid command");}
let file = user_input[i + 1].to_owned();
let command = line.trim().to_owned();
let message = self.find_prog(command, true).to_owned();
if message == ~"none"{
i = length;
}
write_file(file,message);
line = ~"";
i += 1;
}
"|" => {
let command = line.trim().to_owned();
let mut command2: ~str = ~"";
for k in range(i + 1,length){
match user_input[k]{
"<" => {break;}
">" =>{break;}
"|" => {break;}
_ => {command2 = command2 + " " + user_input[k];}
}
i = k;
}
command2 = command2.trim().to_owned();
let mut message = self.find_prog(command, true).to_owned();
if message == ~"none"{
i = length;
}
match File::create(&Path::new("f.md")) {
Some(mut file) => {
file.write_str(message);
}
None =>{
println("Opening file failed!");
}
}
//println(command2);
message = self.find_prog(command2 + " " + "f.md", true).to_owned();
self.find_prog("rm f.md", true);
println!("{}", message);
line = ~"";
}
_ => {
line = line + " " + string;
}
}
i += 1;
}
let result = self.find_prog(line.trim(),false);
match result {
~"return" => {unsafe{libc::exit(1 as libc::c_int)}}
//~"continue" => {continue;}
_ => {}
}
}
}
fn | (&mut self, cmd_line : &str, output: bool) -> ~str{
let program = cmd_line.splitn(' ', 1).nth(0).expect("no program"); // get command
match program {
"" => { return ~"continue"; }
"exit" => { return ~"return"; }
"history" => {
self.log.push(cmd_line.to_owned());
return self.run_history(output);
}
"cd" => {
self.log.push(cmd_line.to_owned());
self.run_cd(cmd_line);
}
_ => {
self.log.push(cmd_line.to_owned());
return self.run_cmdline(cmd_line, output);
}
}
~"fine"
}
fn run_cmdline(&mut self, cmd_line: &str, output: bool) -> ~str {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x!= "" { Some(x.to_owned()) } else { None }).to_owned_vec();
let length = argv.len()-1;
if argv[length] == ~"&" {
argv.remove(length);
let program: ~str = argv.remove(0);
let argv2 = argv.clone();
if self.cmd_exists(program){
spawn(proc() {run::process_status(program, argv2);});
}
else {
println!("{:s}: command not found", program);
}
return ~"none";
}
else{
if argv.len() > 0 {
let program: ~str = argv.remove(0);
return self.run_cmd(program, argv, output);
}
}
return ~"none";
}
fn run_cmd(&mut self, program: &str, argv: &[~str], output: bool)->~str {
if self.cmd_exists(program) {
if output == false {
run::process_status(program, argv);
return ~"none";
}
else {
let output = run::process_output(program, argv);
let output_str = output.unwrap().output;
return std::str::from_utf8(output_str).to_owned();
}
} else {
println!("{:s}: command not found", program);
}
return ~"none";
}
fn cmd_exists(&mut self, cmd_path: &str) -> bool {
let ret = run::process_output("which", [cmd_path.to_owned()]);
return ret.expect("exit code error.").status.success();
}
fn run_history(&mut self, output: bool)-> ~str{
if output == false{
for i in range(0, self.log.len()) {
println!("{}", self.log[i]);
}
return ~"none";
}
else {
let mut out: ~str = ~"";
for i in range(0, self.log.len()){
out = out + self.log[i].to_owned();
}
return out;
}
}
fn run_cd(&mut self, cmd_line: &str) {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x!= "" { Some(x.to_owned()) } else { None }).to_owned_vec();
if argv.len() > 0 {
if argv.len() == 1 {
self.go_to_home_dir();
return ;
}
let string: ~str = argv.remove(1);
if string == ~"$HOME" || string == ~"$home"{
self.go_to_home_dir();
return ;
}
let path = ~Path::new(string);
if (path.exists()){
let success = std::os::change_dir(path);
if!success {
println("Invalid path");
}
}
}
else {
println("Invalid input");
}
}
fn go_to_home_dir(&mut self){
match std::os::homedir() {
Some(path) => {
std::os::change_dir(&path);
}
None => {
println("$HOME is not set");
}
}
}
}
fn write_file(filename: ~str, message: ~str){
match File::create(&Path::new(filename)) {
Some(mut file) => {
file.write_str(message);
}
None =>{
println("Opening file failed!");
}
}
}
/*
fn read_file(filename: ~str) -> ~str{
let path = Path::new(filename);
match File::open(&path) {
Some(file) => {
let mut reader = BufferedReader::new(file);
let input = reader.read_to_str();
return input;
}
None =>{
println("Opening file failed");
return ~"";
}
}
}
*/
fn get_cmdline_from_args() -> Option<~str> {
/* Begin processing program arguments and initiate the parameters. */
let args = os::args();
let opts = ~[
getopts::optopt("c")
];
let matches = match getopts::getopts(args.tail(), opts) {
Ok(m) => { m }
Err(f) => { fail!(f.to_err_msg()) }
};
if matches.opt_present("c") {
let cmd_str = match matches.opt_str("c") {
Some(cmd_str) => {cmd_str.to_owned()},
None => {~""}
};
return Some(cmd_str);
} else {
return None;
}
}
fn main() {
let opt_cmd_line = get_cmdline_from_args();
spawn(proc () {
let mut listener = Listener::new();
listener.register(Interrupt);
loop{
match listener.port.recv() {
Interrupt => print!(""),
_ => (),
}
}
});
match opt_cmd_line {
Some(cmd_line) => {Shell::new("").run_cmdline(cmd_line, false);}
None => {Shell::new("gash > ").run();}
}
}
| find_prog | identifier_name |
gash.rs | //
// gash.rs
//
// Starting code for PS2
// Running on Rust 0.9
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu, David Evans
// Version 0.4
//
extern mod extra;
use std::{io, run, os};
use std::io::buffered::BufferedReader;
use std::io::stdin;
use extra::getopts;
use std::io::File;
use std::io::signal::{Listener, Interrupt};
use std::libc;
struct Shell {
cmd_prompt: ~str,
log: ~[~str],
}
impl Shell {
fn new(prompt_str: &str) -> Shell {
Shell {
cmd_prompt: prompt_str.to_owned(),
log: ~[],
}
}
fn run(&mut self) {
let mut stdin = BufferedReader::new(stdin());
loop {
print(self.cmd_prompt); // prints 'gash >'
io::stdio::flush();
let line = stdin.read_line().unwrap(); // reads whats on the line
let cmd_line = line.trim().to_owned(); // removes leading and trailing whitespace
let user_input: ~[&str] = cmd_line.split(' ').collect();
let mut line: ~str = ~"";
let length: uint = user_input.len();
let mut i : uint = 0;
while (i < length){
let string = user_input[i].clone();
let mut input = ~"";
match string {
"<" => {
if!(i < length-1)
{println!("invalid command");}
let file = user_input[i+1].to_owned(); // get file name
let command = line.trim().to_owned();
line = command + " " + file;
i += 1;
}
">" => {
if!(i < length-1)
{println!("invalid command");}
let file = user_input[i + 1].to_owned();
let command = line.trim().to_owned();
let message = self.find_prog(command, true).to_owned();
if message == ~"none"{
i = length;
}
write_file(file,message);
line = ~"";
i += 1;
}
"|" => {
let command = line.trim().to_owned();
let mut command2: ~str = ~"";
for k in range(i + 1,length){
match user_input[k]{
"<" => {break;}
">" =>{break;}
"|" => {break;}
_ => {command2 = command2 + " " + user_input[k];}
}
i = k;
}
command2 = command2.trim().to_owned();
let mut message = self.find_prog(command, true).to_owned();
if message == ~"none"{
i = length;
}
match File::create(&Path::new("f.md")) {
Some(mut file) => {
file.write_str(message);
}
None =>{
println("Opening file failed!");
}
}
//println(command2);
message = self.find_prog(command2 + " " + "f.md", true).to_owned();
self.find_prog("rm f.md", true);
println!("{}", message);
line = ~"";
}
_ => {
line = line + " " + string;
}
}
i += 1;
}
let result = self.find_prog(line.trim(),false);
match result {
~"return" => {unsafe{libc::exit(1 as libc::c_int)}}
//~"continue" => {continue;}
_ => {}
}
}
}
fn find_prog(&mut self, cmd_line : &str, output: bool) -> ~str{
let program = cmd_line.splitn(' ', 1).nth(0).expect("no program"); // get command
match program {
"" => { return ~"continue"; }
"exit" => { return ~"return"; }
"history" => {
self.log.push(cmd_line.to_owned());
return self.run_history(output);
}
"cd" => {
self.log.push(cmd_line.to_owned());
self.run_cd(cmd_line);
}
_ => {
self.log.push(cmd_line.to_owned());
return self.run_cmdline(cmd_line, output);
}
}
~"fine"
}
fn run_cmdline(&mut self, cmd_line: &str, output: bool) -> ~str {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x!= "" { Some(x.to_owned()) } else { None }).to_owned_vec();
let length = argv.len()-1;
if argv[length] == ~"&" {
argv.remove(length);
let program: ~str = argv.remove(0);
let argv2 = argv.clone();
if self.cmd_exists(program){
spawn(proc() {run::process_status(program, argv2);});
}
else {
println!("{:s}: command not found", program);
}
return ~"none";
}
else{
if argv.len() > 0 {
let program: ~str = argv.remove(0);
return self.run_cmd(program, argv, output);
}
}
return ~"none";
}
fn run_cmd(&mut self, program: &str, argv: &[~str], output: bool)->~str {
if self.cmd_exists(program) {
if output == false {
run::process_status(program, argv);
return ~"none";
}
else {
let output = run::process_output(program, argv);
let output_str = output.unwrap().output;
return std::str::from_utf8(output_str).to_owned();
}
} else {
println!("{:s}: command not found", program);
}
return ~"none";
}
fn cmd_exists(&mut self, cmd_path: &str) -> bool {
let ret = run::process_output("which", [cmd_path.to_owned()]);
return ret.expect("exit code error.").status.success();
}
fn run_history(&mut self, output: bool)-> ~str{
if output == false{
for i in range(0, self.log.len()) {
println!("{}", self.log[i]);
}
return ~"none";
}
else {
let mut out: ~str = ~"";
for i in range(0, self.log.len()){
out = out + self.log[i].to_owned();
}
return out;
}
}
fn run_cd(&mut self, cmd_line: &str) {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x!= "" { Some(x.to_owned()) } else { None }).to_owned_vec();
if argv.len() > 0 {
if argv.len() == 1 {
self.go_to_home_dir();
return ;
}
let string: ~str = argv.remove(1);
if string == ~"$HOME" || string == ~"$home"{
self.go_to_home_dir();
return ;
}
let path = ~Path::new(string);
if (path.exists()){
let success = std::os::change_dir(path);
if!success {
println("Invalid path");
}
}
}
else |
}
fn go_to_home_dir(&mut self){
match std::os::homedir() {
Some(path) => {
std::os::change_dir(&path);
}
None => {
println("$HOME is not set");
}
}
}
}
fn write_file(filename: ~str, message: ~str){
match File::create(&Path::new(filename)) {
Some(mut file) => {
file.write_str(message);
}
None =>{
println("Opening file failed!");
}
}
}
/*
fn read_file(filename: ~str) -> ~str{
let path = Path::new(filename);
match File::open(&path) {
Some(file) => {
let mut reader = BufferedReader::new(file);
let input = reader.read_to_str();
return input;
}
None =>{
println("Opening file failed");
return ~"";
}
}
}
*/
fn get_cmdline_from_args() -> Option<~str> {
/* Begin processing program arguments and initiate the parameters. */
let args = os::args();
let opts = ~[
getopts::optopt("c")
];
let matches = match getopts::getopts(args.tail(), opts) {
Ok(m) => { m }
Err(f) => { fail!(f.to_err_msg()) }
};
if matches.opt_present("c") {
let cmd_str = match matches.opt_str("c") {
Some(cmd_str) => {cmd_str.to_owned()},
None => {~""}
};
return Some(cmd_str);
} else {
return None;
}
}
fn main() {
let opt_cmd_line = get_cmdline_from_args();
spawn(proc () {
let mut listener = Listener::new();
listener.register(Interrupt);
loop{
match listener.port.recv() {
Interrupt => print!(""),
_ => (),
}
}
});
match opt_cmd_line {
Some(cmd_line) => {Shell::new("").run_cmdline(cmd_line, false);}
None => {Shell::new("gash > ").run();}
}
}
| {
println("Invalid input");
} | conditional_block |
issue-10806.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
| 3
}
pub fn bar() -> int {
4
}
pub mod baz {
use {foo, bar};
pub fn quux() -> int {
foo() + bar()
}
}
pub mod grault {
use {foo};
pub fn garply() -> int {
foo()
}
}
pub mod waldo {
use {};
pub fn plugh() -> int {
0
}
}
pub fn main() {
let _x = baz::quux();
let _y = grault::garply();
let _z = waldo::plugh();
} | pub fn foo() -> int { | random_line_split |
issue-10806.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub fn foo() -> int {
3
}
pub fn bar() -> int {
4
}
pub mod baz {
use {foo, bar};
pub fn | () -> int {
foo() + bar()
}
}
pub mod grault {
use {foo};
pub fn garply() -> int {
foo()
}
}
pub mod waldo {
use {};
pub fn plugh() -> int {
0
}
}
pub fn main() {
let _x = baz::quux();
let _y = grault::garply();
let _z = waldo::plugh();
}
| quux | identifier_name |
issue-10806.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub fn foo() -> int {
3
}
pub fn bar() -> int {
4
}
pub mod baz {
use {foo, bar};
pub fn quux() -> int {
foo() + bar()
}
}
pub mod grault {
use {foo};
pub fn garply() -> int |
}
pub mod waldo {
use {};
pub fn plugh() -> int {
0
}
}
pub fn main() {
let _x = baz::quux();
let _y = grault::garply();
let _z = waldo::plugh();
}
| {
foo()
} | identifier_body |
mod.rs | /*
copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation.
This file is part of Blockstack.
Blockstack is free software. You may redistribute 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.
Blockstack is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY, including without 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 Blockstack. If not, see <http://www.gnu.org/licenses/>.
*/
#[macro_use] pub mod log;
#[macro_use] pub mod macros;
#[macro_use] pub mod db;
pub mod hash;
pub mod pair;
pub mod pipe;
pub mod retry;
pub mod secp256k1;
pub mod uint;
pub mod strings;
pub mod vrf;
use std::time;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
use std::fmt;
use std::error;
pub fn get_epoch_time_secs() -> u64 {
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
return since_the_epoch.as_secs();
}
pub fn get_epoch_time_ms() -> u128 {
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
return since_the_epoch.as_millis();
}
pub fn sleep_ms(millis: u64) -> () {
let t = time::Duration::from_millis(millis);
thread::sleep(t);
}
/// Hex deserialization error
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum HexError {
/// Length was not 64 characters
BadLength(usize),
/// Non-hex character in string
BadCharacter(char)
}
impl fmt::Display for HexError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
HexError::BadLength(n) => write!(f, "bad length {} for sha256d hex string", n),
HexError::BadCharacter(c) => write!(f, "bad character {} in sha256d hex string", c)
}
}
}
impl error::Error for HexError {
fn cause(&self) -> Option<&dyn error::Error> |
fn description(&self) -> &str {
match *self {
HexError::BadLength(_) => "sha256d hex string non-64 length",
HexError::BadCharacter(_) => "sha256d bad hex character"
}
}
}
| { None } | identifier_body |
mod.rs | /*
copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation.
This file is part of Blockstack.
Blockstack is free software. You may redistribute 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.
Blockstack is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY, including without 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 Blockstack. If not, see <http://www.gnu.org/licenses/>.
*/
#[macro_use] pub mod log;
#[macro_use] pub mod macros;
#[macro_use] pub mod db;
pub mod hash;
pub mod pair;
pub mod pipe;
pub mod retry;
pub mod secp256k1;
pub mod uint; | pub mod strings;
pub mod vrf;
use std::time;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
use std::fmt;
use std::error;
pub fn get_epoch_time_secs() -> u64 {
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
return since_the_epoch.as_secs();
}
pub fn get_epoch_time_ms() -> u128 {
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
return since_the_epoch.as_millis();
}
pub fn sleep_ms(millis: u64) -> () {
let t = time::Duration::from_millis(millis);
thread::sleep(t);
}
/// Hex deserialization error
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum HexError {
/// Length was not 64 characters
BadLength(usize),
/// Non-hex character in string
BadCharacter(char)
}
impl fmt::Display for HexError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
HexError::BadLength(n) => write!(f, "bad length {} for sha256d hex string", n),
HexError::BadCharacter(c) => write!(f, "bad character {} in sha256d hex string", c)
}
}
}
impl error::Error for HexError {
fn cause(&self) -> Option<&dyn error::Error> { None }
fn description(&self) -> &str {
match *self {
HexError::BadLength(_) => "sha256d hex string non-64 length",
HexError::BadCharacter(_) => "sha256d bad hex character"
}
}
} | random_line_split |
|
mod.rs | /*
copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation.
This file is part of Blockstack.
Blockstack is free software. You may redistribute 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.
Blockstack is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY, including without 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 Blockstack. If not, see <http://www.gnu.org/licenses/>.
*/
#[macro_use] pub mod log;
#[macro_use] pub mod macros;
#[macro_use] pub mod db;
pub mod hash;
pub mod pair;
pub mod pipe;
pub mod retry;
pub mod secp256k1;
pub mod uint;
pub mod strings;
pub mod vrf;
use std::time;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
use std::fmt;
use std::error;
pub fn get_epoch_time_secs() -> u64 {
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
return since_the_epoch.as_secs();
}
pub fn get_epoch_time_ms() -> u128 {
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
return since_the_epoch.as_millis();
}
pub fn sleep_ms(millis: u64) -> () {
let t = time::Duration::from_millis(millis);
thread::sleep(t);
}
/// Hex deserialization error
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum HexError {
/// Length was not 64 characters
BadLength(usize),
/// Non-hex character in string
BadCharacter(char)
}
impl fmt::Display for HexError {
fn | (&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
HexError::BadLength(n) => write!(f, "bad length {} for sha256d hex string", n),
HexError::BadCharacter(c) => write!(f, "bad character {} in sha256d hex string", c)
}
}
}
impl error::Error for HexError {
fn cause(&self) -> Option<&dyn error::Error> { None }
fn description(&self) -> &str {
match *self {
HexError::BadLength(_) => "sha256d hex string non-64 length",
HexError::BadCharacter(_) => "sha256d bad hex character"
}
}
}
| fmt | identifier_name |
parsing.rs | //! Utility functions for Header implementations.
use std::str;
use std::fmt::{self, Display};
/// Reads a single raw string when parsing a header
pub fn from_one_raw_str<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<T> {
if raw.len()!= 1 {
return None;
}
// we JUST checked that raw.len() == 1, so raw[0] WILL exist.
if let Ok(s) = str::from_utf8(& unsafe { raw.get_unchecked(0) }[..]) {
if s!= "" {
return str::FromStr::from_str(s).ok();
} | }
None
}
/// Reads a comma-delimited raw header into a Vec.
#[inline]
pub fn from_comma_delimited<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<Vec<T>> {
if raw.len()!= 1 {
return None;
}
// we JUST checked that raw.len() == 1, so raw[0] WILL exist.
from_one_comma_delimited(& unsafe { raw.get_unchecked(0) }[..])
}
/// Reads a comma-delimited raw string into a Vec.
pub fn from_one_comma_delimited<T: str::FromStr>(raw: &[u8]) -> Option<Vec<T>> {
match str::from_utf8(raw) {
Ok(s) => {
Some(s
.split(',')
.filter_map(|x| match x.trim() {
"" => None,
y => Some(y)
})
.filter_map(|x| x.parse().ok())
.collect())
}
Err(_) => None
}
}
/// Format an array into a comma-delimited string.
pub fn fmt_comma_delimited<T: Display>(f: &mut fmt::Formatter, parts: &[T]) -> fmt::Result {
for (i, part) in parts.iter().enumerate() {
if i!= 0 {
try!(f.write_str(", "));
}
try!(Display::fmt(part, f));
}
Ok(())
} | random_line_split |
|
parsing.rs | //! Utility functions for Header implementations.
use std::str;
use std::fmt::{self, Display};
/// Reads a single raw string when parsing a header
pub fn from_one_raw_str<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<T> {
if raw.len()!= 1 {
return None;
}
// we JUST checked that raw.len() == 1, so raw[0] WILL exist.
if let Ok(s) = str::from_utf8(& unsafe { raw.get_unchecked(0) }[..]) {
if s!= "" {
return str::FromStr::from_str(s).ok();
}
}
None
}
/// Reads a comma-delimited raw header into a Vec.
#[inline]
pub fn from_comma_delimited<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<Vec<T>> |
/// Reads a comma-delimited raw string into a Vec.
pub fn from_one_comma_delimited<T: str::FromStr>(raw: &[u8]) -> Option<Vec<T>> {
match str::from_utf8(raw) {
Ok(s) => {
Some(s
.split(',')
.filter_map(|x| match x.trim() {
"" => None,
y => Some(y)
})
.filter_map(|x| x.parse().ok())
.collect())
}
Err(_) => None
}
}
/// Format an array into a comma-delimited string.
pub fn fmt_comma_delimited<T: Display>(f: &mut fmt::Formatter, parts: &[T]) -> fmt::Result {
for (i, part) in parts.iter().enumerate() {
if i!= 0 {
try!(f.write_str(", "));
}
try!(Display::fmt(part, f));
}
Ok(())
}
| {
if raw.len() != 1 {
return None;
}
// we JUST checked that raw.len() == 1, so raw[0] WILL exist.
from_one_comma_delimited(& unsafe { raw.get_unchecked(0) }[..])
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.