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 |
---|---|---|---|---|
enum-headings.rs
|
#![crate_name = "foo"]
// @has foo/enum.Token.html
/// A token!
/// # First
/// Some following text...
// @has - '//h2[@id="first"]' "First"
pub enum
|
{
/// A declaration!
/// # Variant-First
/// Some following text...
// @has - '//h4[@id="variant-first"]' "Variant-First"
Declaration {
/// A version!
/// # Variant-Field-First
/// Some following text...
// @has - '//h5[@id="variant-field-first"]' "Variant-Field-First"
version: String,
},
/// A Zoople!
/// # Variant-First
Zoople(
// @has - '//h5[@id="variant-tuple-field-first"]' "Variant-Tuple-Field-First"
/// Zoople's first variant!
/// # Variant-Tuple-Field-First
/// Some following text...
usize,
),
/// Unfinished business!
/// # Non-Exhaustive-First
/// Some following text...
// @has - '//h4[@id="non-exhaustive-first"]' "Non-Exhaustive-First"
#[non_exhaustive]
Unfinished {
/// This is x.
/// # X-First
/// Some following text...
// @has - '//h5[@id="x-first"]' "X-First"
x: usize,
},
}
|
Token
|
identifier_name
|
union_dtor_1_0.rs
|
/* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
pub struct __BindgenUnionField<T>(::std::marker::PhantomData<T>);
impl<T> __BindgenUnionField<T> {
#[inline]
pub fn new() -> Self {
__BindgenUnionField(::std::marker::PhantomData)
}
#[inline]
pub unsafe fn as_ref(&self) -> &T {
::std::mem::transmute(self)
}
#[inline]
pub unsafe fn as_mut(&mut self) -> &mut T {
::std::mem::transmute(self)
}
}
impl<T> ::std::default::Default for __BindgenUnionField<T> {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<T> ::std::clone::Clone for __BindgenUnionField<T> {
#[inline]
fn clone(&self) -> Self {
Self::new()
}
}
impl<T> ::std::marker::Copy for __BindgenUnionField<T> {}
impl<T> ::std::fmt::Debug for __BindgenUnionField<T> {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_str("__BindgenUnionField")
}
}
impl<T> ::std::hash::Hash for __BindgenUnionField<T> {
fn hash<H: ::std::hash::Hasher>(&self, _state: &mut H) {}
}
impl<T> ::std::cmp::PartialEq for __BindgenUnionField<T> {
fn eq(&self, _other: &__BindgenUnionField<T>) -> bool
|
}
impl<T> ::std::cmp::Eq for __BindgenUnionField<T> {}
#[repr(C)]
#[derive(Debug, Default)]
pub struct UnionWithDtor {
pub mFoo: __BindgenUnionField<::std::os::raw::c_int>,
pub mBar: __BindgenUnionField<*mut ::std::os::raw::c_void>,
pub bindgen_union_field: u64,
}
#[test]
fn bindgen_test_layout_UnionWithDtor() {
assert_eq!(
::std::mem::size_of::<UnionWithDtor>(),
8usize,
concat!("Size of: ", stringify!(UnionWithDtor))
);
assert_eq!(
::std::mem::align_of::<UnionWithDtor>(),
8usize,
concat!("Alignment of ", stringify!(UnionWithDtor))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<UnionWithDtor>())).mFoo as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(UnionWithDtor),
"::",
stringify!(mFoo)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<UnionWithDtor>())).mBar as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(UnionWithDtor),
"::",
stringify!(mBar)
)
);
}
extern "C" {
#[link_name = "\u{1}_ZN13UnionWithDtorD1Ev"]
pub fn UnionWithDtor_UnionWithDtor_destructor(this: *mut UnionWithDtor);
}
impl UnionWithDtor {
#[inline]
pub unsafe fn destruct(&mut self) {
UnionWithDtor_UnionWithDtor_destructor(self)
}
}
|
{
true
}
|
identifier_body
|
union_dtor_1_0.rs
|
/* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
pub struct __BindgenUnionField<T>(::std::marker::PhantomData<T>);
impl<T> __BindgenUnionField<T> {
#[inline]
pub fn new() -> Self {
__BindgenUnionField(::std::marker::PhantomData)
}
#[inline]
pub unsafe fn as_ref(&self) -> &T {
::std::mem::transmute(self)
}
#[inline]
pub unsafe fn as_mut(&mut self) -> &mut T {
::std::mem::transmute(self)
}
}
impl<T> ::std::default::Default for __BindgenUnionField<T> {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<T> ::std::clone::Clone for __BindgenUnionField<T> {
#[inline]
fn clone(&self) -> Self {
Self::new()
}
}
impl<T> ::std::marker::Copy for __BindgenUnionField<T> {}
impl<T> ::std::fmt::Debug for __BindgenUnionField<T> {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_str("__BindgenUnionField")
}
}
impl<T> ::std::hash::Hash for __BindgenUnionField<T> {
fn hash<H: ::std::hash::Hasher>(&self, _state: &mut H) {}
}
impl<T> ::std::cmp::PartialEq for __BindgenUnionField<T> {
fn eq(&self, _other: &__BindgenUnionField<T>) -> bool {
true
}
}
impl<T> ::std::cmp::Eq for __BindgenUnionField<T> {}
#[repr(C)]
#[derive(Debug, Default)]
pub struct UnionWithDtor {
pub mFoo: __BindgenUnionField<::std::os::raw::c_int>,
pub mBar: __BindgenUnionField<*mut ::std::os::raw::c_void>,
pub bindgen_union_field: u64,
}
#[test]
fn bindgen_test_layout_UnionWithDtor() {
assert_eq!(
::std::mem::size_of::<UnionWithDtor>(),
8usize,
concat!("Size of: ", stringify!(UnionWithDtor))
);
assert_eq!(
::std::mem::align_of::<UnionWithDtor>(),
8usize,
concat!("Alignment of ", stringify!(UnionWithDtor))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<UnionWithDtor>())).mFoo as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(UnionWithDtor),
"::",
stringify!(mFoo)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<UnionWithDtor>())).mBar as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(UnionWithDtor),
"::",
stringify!(mBar)
|
pub fn UnionWithDtor_UnionWithDtor_destructor(this: *mut UnionWithDtor);
}
impl UnionWithDtor {
#[inline]
pub unsafe fn destruct(&mut self) {
UnionWithDtor_UnionWithDtor_destructor(self)
}
}
|
)
);
}
extern "C" {
#[link_name = "\u{1}_ZN13UnionWithDtorD1Ev"]
|
random_line_split
|
union_dtor_1_0.rs
|
/* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
pub struct __BindgenUnionField<T>(::std::marker::PhantomData<T>);
impl<T> __BindgenUnionField<T> {
#[inline]
pub fn new() -> Self {
__BindgenUnionField(::std::marker::PhantomData)
}
#[inline]
pub unsafe fn as_ref(&self) -> &T {
::std::mem::transmute(self)
}
#[inline]
pub unsafe fn as_mut(&mut self) -> &mut T {
::std::mem::transmute(self)
}
}
impl<T> ::std::default::Default for __BindgenUnionField<T> {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<T> ::std::clone::Clone for __BindgenUnionField<T> {
#[inline]
fn clone(&self) -> Self {
Self::new()
}
}
impl<T> ::std::marker::Copy for __BindgenUnionField<T> {}
impl<T> ::std::fmt::Debug for __BindgenUnionField<T> {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_str("__BindgenUnionField")
}
}
impl<T> ::std::hash::Hash for __BindgenUnionField<T> {
fn hash<H: ::std::hash::Hasher>(&self, _state: &mut H) {}
}
impl<T> ::std::cmp::PartialEq for __BindgenUnionField<T> {
fn eq(&self, _other: &__BindgenUnionField<T>) -> bool {
true
}
}
impl<T> ::std::cmp::Eq for __BindgenUnionField<T> {}
#[repr(C)]
#[derive(Debug, Default)]
pub struct UnionWithDtor {
pub mFoo: __BindgenUnionField<::std::os::raw::c_int>,
pub mBar: __BindgenUnionField<*mut ::std::os::raw::c_void>,
pub bindgen_union_field: u64,
}
#[test]
fn bindgen_test_layout_UnionWithDtor() {
assert_eq!(
::std::mem::size_of::<UnionWithDtor>(),
8usize,
concat!("Size of: ", stringify!(UnionWithDtor))
);
assert_eq!(
::std::mem::align_of::<UnionWithDtor>(),
8usize,
concat!("Alignment of ", stringify!(UnionWithDtor))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<UnionWithDtor>())).mFoo as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(UnionWithDtor),
"::",
stringify!(mFoo)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<UnionWithDtor>())).mBar as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(UnionWithDtor),
"::",
stringify!(mBar)
)
);
}
extern "C" {
#[link_name = "\u{1}_ZN13UnionWithDtorD1Ev"]
pub fn UnionWithDtor_UnionWithDtor_destructor(this: *mut UnionWithDtor);
}
impl UnionWithDtor {
#[inline]
pub unsafe fn
|
(&mut self) {
UnionWithDtor_UnionWithDtor_destructor(self)
}
}
|
destruct
|
identifier_name
|
barebone_blink.rs
|
//! Flash the BeagleBone USR1 LED 5 times at 2Hz.
//!
//! The PRU code notifies the host processor every time the LED is flashed by triggering Evtout0.
//! The 6-th event out is interpreted as a completion notification.
extern crate prusst;
use prusst::{Pruss, IntcConfig, Evtout, Sysevt};
use std::fs::File;
use std::io::Write;
static LED_TRIGGER_PATH: &'static str = "/sys/class/leds/beaglebone:green:usr1/trigger";
static LED_DEFAULT_TRIGGER: &'static str = "mmc0";
fn echo(value: &str, path: &str) {
let mut file = File::create(path).unwrap();
file.write_all(value.as_bytes()).unwrap();
}
fn main()
|
let irq = pruss.intc.register_irq(Evtout::E0);
// Open and load the PRU binary.
let mut pru_binary = File::open("examples/barebone_blink_pru0.bin").unwrap();
// Temporarily take control of the LED.
echo("none", LED_TRIGGER_PATH);
// Run the PRU binary.
unsafe { pruss.pru0.load_code(&mut pru_binary).unwrap().run(); }
// Let us know when the LED is turned on.
for i in 1..6 {
// Wait for the PRU to trigger the event out.
irq.wait();
println!("Blink {}", i);
// Clear the triggering interrupt and re-enable the host irq.
pruss.intc.clear_sysevt(Sysevt::S19);
pruss.intc.enable_host(Evtout::E0);
}
// Wait for completion of the PRU code.
irq.wait();
pruss.intc.clear_sysevt(Sysevt::S19);
println!("Goodbye!");
// Restore default LED status.
echo(LED_DEFAULT_TRIGGER, LED_TRIGGER_PATH);
}
|
{
// Get a view of the PRU subsystem.
let mut pruss = match Pruss::new(&IntcConfig::new_populated()) {
Ok(p) => p,
Err(e) => match e {
prusst::Error::AlreadyInstantiated
=> panic!("You can't instantiate more than one `Pruss` object at a time."),
prusst::Error::PermissionDenied
=> panic!("You do not have permission to access the PRU subsystem: \
maybe you should run this program as root?"),
prusst::Error::DeviceNotFound
=> panic!("The PRU subsystem could not be found: are you sure the `uio_pruss` \
module is loaded and supported by your kernel?"),
prusst::Error::OtherDeviceError
=> panic!("An unidentified problem occured with the PRU subsystem: \
do you have a valid overlay loaded?")
}
};
// Get a handle to an event out.
|
identifier_body
|
barebone_blink.rs
|
//! Flash the BeagleBone USR1 LED 5 times at 2Hz.
//!
//! The PRU code notifies the host processor every time the LED is flashed by triggering Evtout0.
//! The 6-th event out is interpreted as a completion notification.
extern crate prusst;
use prusst::{Pruss, IntcConfig, Evtout, Sysevt};
use std::fs::File;
use std::io::Write;
static LED_TRIGGER_PATH: &'static str = "/sys/class/leds/beaglebone:green:usr1/trigger";
static LED_DEFAULT_TRIGGER: &'static str = "mmc0";
fn echo(value: &str, path: &str) {
let mut file = File::create(path).unwrap();
file.write_all(value.as_bytes()).unwrap();
}
|
Ok(p) => p,
Err(e) => match e {
prusst::Error::AlreadyInstantiated
=> panic!("You can't instantiate more than one `Pruss` object at a time."),
prusst::Error::PermissionDenied
=> panic!("You do not have permission to access the PRU subsystem: \
maybe you should run this program as root?"),
prusst::Error::DeviceNotFound
=> panic!("The PRU subsystem could not be found: are you sure the `uio_pruss` \
module is loaded and supported by your kernel?"),
prusst::Error::OtherDeviceError
=> panic!("An unidentified problem occured with the PRU subsystem: \
do you have a valid overlay loaded?")
}
};
// Get a handle to an event out.
let irq = pruss.intc.register_irq(Evtout::E0);
// Open and load the PRU binary.
let mut pru_binary = File::open("examples/barebone_blink_pru0.bin").unwrap();
// Temporarily take control of the LED.
echo("none", LED_TRIGGER_PATH);
// Run the PRU binary.
unsafe { pruss.pru0.load_code(&mut pru_binary).unwrap().run(); }
// Let us know when the LED is turned on.
for i in 1..6 {
// Wait for the PRU to trigger the event out.
irq.wait();
println!("Blink {}", i);
// Clear the triggering interrupt and re-enable the host irq.
pruss.intc.clear_sysevt(Sysevt::S19);
pruss.intc.enable_host(Evtout::E0);
}
// Wait for completion of the PRU code.
irq.wait();
pruss.intc.clear_sysevt(Sysevt::S19);
println!("Goodbye!");
// Restore default LED status.
echo(LED_DEFAULT_TRIGGER, LED_TRIGGER_PATH);
}
|
fn main() {
// Get a view of the PRU subsystem.
let mut pruss = match Pruss::new(&IntcConfig::new_populated()) {
|
random_line_split
|
barebone_blink.rs
|
//! Flash the BeagleBone USR1 LED 5 times at 2Hz.
//!
//! The PRU code notifies the host processor every time the LED is flashed by triggering Evtout0.
//! The 6-th event out is interpreted as a completion notification.
extern crate prusst;
use prusst::{Pruss, IntcConfig, Evtout, Sysevt};
use std::fs::File;
use std::io::Write;
static LED_TRIGGER_PATH: &'static str = "/sys/class/leds/beaglebone:green:usr1/trigger";
static LED_DEFAULT_TRIGGER: &'static str = "mmc0";
fn echo(value: &str, path: &str) {
let mut file = File::create(path).unwrap();
file.write_all(value.as_bytes()).unwrap();
}
fn
|
() {
// Get a view of the PRU subsystem.
let mut pruss = match Pruss::new(&IntcConfig::new_populated()) {
Ok(p) => p,
Err(e) => match e {
prusst::Error::AlreadyInstantiated
=> panic!("You can't instantiate more than one `Pruss` object at a time."),
prusst::Error::PermissionDenied
=> panic!("You do not have permission to access the PRU subsystem: \
maybe you should run this program as root?"),
prusst::Error::DeviceNotFound
=> panic!("The PRU subsystem could not be found: are you sure the `uio_pruss` \
module is loaded and supported by your kernel?"),
prusst::Error::OtherDeviceError
=> panic!("An unidentified problem occured with the PRU subsystem: \
do you have a valid overlay loaded?")
}
};
// Get a handle to an event out.
let irq = pruss.intc.register_irq(Evtout::E0);
// Open and load the PRU binary.
let mut pru_binary = File::open("examples/barebone_blink_pru0.bin").unwrap();
// Temporarily take control of the LED.
echo("none", LED_TRIGGER_PATH);
// Run the PRU binary.
unsafe { pruss.pru0.load_code(&mut pru_binary).unwrap().run(); }
// Let us know when the LED is turned on.
for i in 1..6 {
// Wait for the PRU to trigger the event out.
irq.wait();
println!("Blink {}", i);
// Clear the triggering interrupt and re-enable the host irq.
pruss.intc.clear_sysevt(Sysevt::S19);
pruss.intc.enable_host(Evtout::E0);
}
// Wait for completion of the PRU code.
irq.wait();
pruss.intc.clear_sysevt(Sysevt::S19);
println!("Goodbye!");
// Restore default LED status.
echo(LED_DEFAULT_TRIGGER, LED_TRIGGER_PATH);
}
|
main
|
identifier_name
|
function_call.rs
|
use criterion::{black_box, criterion_group, criterion_main, Bencher, Criterion};
|
use gluon::{
new_vm,
vm::{
api::{primitive, FunctionRef, Primitive},
thread::{Status, Thread},
},
ThreadExt,
};
// Benchmarks function calls
fn identity(b: &mut Bencher) {
let vm = new_vm();
let text = r#"
let id x = x
id
"#;
vm.load_script("id", text).unwrap();
let mut id: FunctionRef<fn(i32) -> i32> = vm.get_global("id").unwrap();
b.iter(|| {
let result = id.call(20).unwrap();
black_box(result)
})
}
fn factorial(b: &mut Bencher) {
let vm = new_vm();
let text = r#"
let factorial n =
if n < 2
then 1
else n * factorial (n - 1)
factorial
"#;
vm.load_script("factorial", text).unwrap();
let mut factorial: FunctionRef<fn(i32) -> i32> = vm.get_global("factorial").unwrap();
b.iter(|| {
let result = factorial.call(20).unwrap();
black_box(result)
})
}
fn factorial_tail_call(b: &mut Bencher) {
let vm = new_vm();
let text = r#"
let factorial a n =
if n < 2
then a
else factorial (a * n) (n - 1)
factorial 1
"#;
vm.load_script("factorial", text).unwrap();
let mut factorial: FunctionRef<fn(i32) -> i32> = vm.get_global("factorial").unwrap();
b.iter(|| {
let result = factorial.call(20).unwrap();
black_box(result)
})
}
fn gluon_rust_boundary_overhead(b: &mut Bencher) {
let vm = new_vm();
extern "C" fn test_fn(_: &Thread) -> Status {
Status::Ok
}
let text = r#"
let for n f =
if n #Int== 0 then
()
else
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
for (n #Int- 10) f
for
"#;
vm.load_script("test", text).unwrap();
let mut test: FunctionRef<fn(i32, Primitive<fn(i32)>) -> ()> = vm.get_global("test").unwrap();
b.iter(|| {
let result = test
.call(1000, primitive::<fn(i32)>("test_fn", test_fn))
.unwrap();
black_box(result)
})
}
fn function_call_benchmark(c: &mut Criterion) {
c.bench_function("identity", identity);
c.bench_function("factorial", factorial);
c.bench_function("factorial tail call", factorial_tail_call);
c.bench_function("gluon rust boundary overhead", gluon_rust_boundary_overhead);
}
criterion_group!(function_call, function_call_benchmark);
criterion_main!(function_call);
|
random_line_split
|
|
function_call.rs
|
use criterion::{black_box, criterion_group, criterion_main, Bencher, Criterion};
use gluon::{
new_vm,
vm::{
api::{primitive, FunctionRef, Primitive},
thread::{Status, Thread},
},
ThreadExt,
};
// Benchmarks function calls
fn identity(b: &mut Bencher)
|
fn factorial(b: &mut Bencher) {
let vm = new_vm();
let text = r#"
let factorial n =
if n < 2
then 1
else n * factorial (n - 1)
factorial
"#;
vm.load_script("factorial", text).unwrap();
let mut factorial: FunctionRef<fn(i32) -> i32> = vm.get_global("factorial").unwrap();
b.iter(|| {
let result = factorial.call(20).unwrap();
black_box(result)
})
}
fn factorial_tail_call(b: &mut Bencher) {
let vm = new_vm();
let text = r#"
let factorial a n =
if n < 2
then a
else factorial (a * n) (n - 1)
factorial 1
"#;
vm.load_script("factorial", text).unwrap();
let mut factorial: FunctionRef<fn(i32) -> i32> = vm.get_global("factorial").unwrap();
b.iter(|| {
let result = factorial.call(20).unwrap();
black_box(result)
})
}
fn gluon_rust_boundary_overhead(b: &mut Bencher) {
let vm = new_vm();
extern "C" fn test_fn(_: &Thread) -> Status {
Status::Ok
}
let text = r#"
let for n f =
if n #Int== 0 then
()
else
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
for (n #Int- 10) f
for
"#;
vm.load_script("test", text).unwrap();
let mut test: FunctionRef<fn(i32, Primitive<fn(i32)>) -> ()> = vm.get_global("test").unwrap();
b.iter(|| {
let result = test
.call(1000, primitive::<fn(i32)>("test_fn", test_fn))
.unwrap();
black_box(result)
})
}
fn function_call_benchmark(c: &mut Criterion) {
c.bench_function("identity", identity);
c.bench_function("factorial", factorial);
c.bench_function("factorial tail call", factorial_tail_call);
c.bench_function("gluon rust boundary overhead", gluon_rust_boundary_overhead);
}
criterion_group!(function_call, function_call_benchmark);
criterion_main!(function_call);
|
{
let vm = new_vm();
let text = r#"
let id x = x
id
"#;
vm.load_script("id", text).unwrap();
let mut id: FunctionRef<fn(i32) -> i32> = vm.get_global("id").unwrap();
b.iter(|| {
let result = id.call(20).unwrap();
black_box(result)
})
}
|
identifier_body
|
function_call.rs
|
use criterion::{black_box, criterion_group, criterion_main, Bencher, Criterion};
use gluon::{
new_vm,
vm::{
api::{primitive, FunctionRef, Primitive},
thread::{Status, Thread},
},
ThreadExt,
};
// Benchmarks function calls
fn identity(b: &mut Bencher) {
let vm = new_vm();
let text = r#"
let id x = x
id
"#;
vm.load_script("id", text).unwrap();
let mut id: FunctionRef<fn(i32) -> i32> = vm.get_global("id").unwrap();
b.iter(|| {
let result = id.call(20).unwrap();
black_box(result)
})
}
fn factorial(b: &mut Bencher) {
let vm = new_vm();
let text = r#"
let factorial n =
if n < 2
then 1
else n * factorial (n - 1)
factorial
"#;
vm.load_script("factorial", text).unwrap();
let mut factorial: FunctionRef<fn(i32) -> i32> = vm.get_global("factorial").unwrap();
b.iter(|| {
let result = factorial.call(20).unwrap();
black_box(result)
})
}
fn
|
(b: &mut Bencher) {
let vm = new_vm();
let text = r#"
let factorial a n =
if n < 2
then a
else factorial (a * n) (n - 1)
factorial 1
"#;
vm.load_script("factorial", text).unwrap();
let mut factorial: FunctionRef<fn(i32) -> i32> = vm.get_global("factorial").unwrap();
b.iter(|| {
let result = factorial.call(20).unwrap();
black_box(result)
})
}
fn gluon_rust_boundary_overhead(b: &mut Bencher) {
let vm = new_vm();
extern "C" fn test_fn(_: &Thread) -> Status {
Status::Ok
}
let text = r#"
let for n f =
if n #Int== 0 then
()
else
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
let _ = f n
for (n #Int- 10) f
for
"#;
vm.load_script("test", text).unwrap();
let mut test: FunctionRef<fn(i32, Primitive<fn(i32)>) -> ()> = vm.get_global("test").unwrap();
b.iter(|| {
let result = test
.call(1000, primitive::<fn(i32)>("test_fn", test_fn))
.unwrap();
black_box(result)
})
}
fn function_call_benchmark(c: &mut Criterion) {
c.bench_function("identity", identity);
c.bench_function("factorial", factorial);
c.bench_function("factorial tail call", factorial_tail_call);
c.bench_function("gluon rust boundary overhead", gluon_rust_boundary_overhead);
}
criterion_group!(function_call, function_call_benchmark);
criterion_main!(function_call);
|
factorial_tail_call
|
identifier_name
|
mod.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/. */
//! The implementation of the DOM.
//!
//! The DOM is comprised of interfaces (defined by specifications using
//! [WebIDL](https://heycam.github.io/webidl/)) that are implemented as Rust
//! structs in submodules of this module. Its implementation is documented
//! below.
//!
//! A DOM object and its reflector
//! ==============================
//!
//! The implementation of an interface `Foo` in Servo's DOM involves two
//! related but distinct objects:
//!
//! * the **DOM object**: an instance of the Rust struct `dom::foo::Foo`
//! (marked with the `#[dom_struct]` attribute) on the Rust heap;
//! * the **reflector**: a `JSObject` allocated by SpiderMonkey, that owns the
//! DOM object.
//!
//! Memory management
//! =================
//!
//! Reflectors of DOM objects, and thus the DOM objects themselves, are managed
//! by the SpiderMonkey Garbage Collector. Thus, keeping alive a DOM object
//! is done through its reflector.
//!
//! For more information, see:
//!
//! * rooting pointers on the stack:
//! the [`Root`](bindings/root/struct.Root.html) smart pointer;
//! * tracing pointers in member fields: the [`Dom`](bindings/root/struct.Dom.html),
//! [`MutNullableDom`](bindings/root/struct.MutNullableDom.html) and
//! [`MutDom`](bindings/root/struct.MutDom.html) smart pointers and
//! [the tracing implementation](bindings/trace/index.html);
//! * rooting pointers from across thread boundaries or in channels: the
//! [`Trusted`](bindings/refcounted/struct.Trusted.html) smart pointer;
//!
//! Inheritance
//! ===========
//!
//! Rust does not support struct inheritance, as would be used for the
//! object-oriented DOM APIs. To work around this issue, Servo stores an
//! instance of the superclass in the first field of its subclasses. (Note that
//! it is stored by value, rather than in a smart pointer such as `Dom<T>`.)
//!
//! This implies that a pointer to an object can safely be cast to a pointer
//! to all its classes.
//!
//! This invariant is enforced by the lint in
//! `plugins::lints::inheritance_integrity`.
//!
//! Interfaces which either derive from or are derived by other interfaces
//! implement the `Castable` trait, which provides three methods `is::<T>()`,
//! `downcast::<T>()` and `upcast::<T>()` to cast across the type hierarchy
//! and check whether a given instance is of a given type.
//!
//! ```ignore
//! use dom::bindings::inheritance::Castable;
//! use dom::element::Element;
//! use dom::htmlelement::HTMLElement;
//! use dom::htmlinputelement::HTMLInputElement;
//!
//! if let Some(elem) = node.downcast::<Element> {
//! if elem.is::<HTMLInputElement>() {
//! return elem.upcast::<HTMLElement>();
//! }
//! }
//! ```
//!
//! Furthermore, when discriminating a given instance against multiple
//! interface types, code generation provides a convenient TypeId enum
//! which can be used to write `match` expressions instead of multiple
//! calls to `Castable::is::<T>`. The `type_id()` method of an instance is
//! provided by the farthest interface it derives from, e.g. `EventTarget`
//! for `HTMLMediaElement`. For convenience, that method is also provided
//! on the `Node` interface to avoid unnecessary upcasts to `EventTarget`.
//!
//! ```ignore
//! use dom::bindings::inheritance::{EventTargetTypeId, NodeTypeId};
//!
//! match *node.type_id() {
//! EventTargetTypeId::Node(NodeTypeId::CharacterData(_)) =>...,
//! EventTargetTypeId::Node(NodeTypeId::Element(_)) =>...,
//! ...,
//! }
//! ```
//!
//! Construction
//! ============
//!
//! DOM objects of type `T` in Servo have two constructors:
//!
//! * a `T::new_inherited` static method that returns a plain `T`, and
//! * a `T::new` static method that returns `DomRoot<T>`.
//!
//! (The result of either method can be wrapped in `Result`, if that is
//! appropriate for the type in question.)
//!
//! The latter calls the former, boxes the result, and creates a reflector
//! corresponding to it by calling `dom::bindings::utils::reflect_dom_object`
//! (which yields ownership of the object to the SpiderMonkey Garbage Collector).
//! This is the API to use when creating a DOM object.
//!
//! The former should only be called by the latter, and by subclasses'
//! `new_inherited` methods.
//!
//! DOM object constructors in JavaScript correspond to a `T::Constructor`
//! static method. This method is always fallible.
//!
//! Destruction
//! ===========
//!
//! When the SpiderMonkey Garbage Collector discovers that the reflector of a
//! DOM object is garbage, it calls the reflector's finalization hook. This
//! function deletes the reflector's DOM object, calling its destructor in the
//! process.
//!
//! Mutability and aliasing
//! =======================
//!
//! Reflectors are JavaScript objects, and as such can be freely aliased. As
//! Rust does not allow mutable aliasing, mutable borrows of DOM objects are
//! not allowed. In particular, any mutable fields use `Cell` or `DomRefCell`
//! to manage their mutability.
//!
//! `Reflector` and `DomObject`
//! =============================
//!
//! Every DOM object has a `Reflector` as its first (transitive) member field.
//! This contains a `*mut JSObject` that points to its reflector.
//!
//! The `FooBinding::Wrap` function creates the reflector, stores a pointer to
//! the DOM object in the reflector, and initializes the pointer to the reflector
//! in the `Reflector` field.
//!
//! The `DomObject` trait provides a `reflector()` method that returns the
//! DOM object's `Reflector`. It is implemented automatically for DOM structs
//! through the `#[dom_struct]` attribute.
//!
//! Implementing methods for a DOM object
//! =====================================
//!
//! * `dom::bindings::codegen::Bindings::FooBindings::FooMethods` for methods
//! defined through IDL;
//! * `&self` public methods for public helpers;
//! * `&self` methods for private helpers.
//!
//! Accessing fields of a DOM object
//! ================================
//!
//! All fields of DOM objects are private; accessing them from outside their
//! module is done through explicit getter or setter methods.
//!
//! Inheritance and casting
//! =======================
//!
//! All DOM interfaces part of an inheritance chain (i.e. interfaces
//! that derive others or are derived from) implement the trait `Castable`
//! which provides both downcast and upcasts.
//!
//! ```ignore
//! # use script::dom::bindings::inheritance::Castable;
//! # use script::dom::element::Element;
//! # use script::dom::node::Node;
//! # use script::dom::htmlelement::HTMLElement;
//! fn f(element: &Element) {
//! let base = element.upcast::<Node>();
//! let derived = element.downcast::<HTMLElement>().unwrap();
//! }
//! ```
//!
//! Adding a new DOM interface
//! ==========================
//!
//! Adding a new interface `Foo` requires at least the following:
//!
//! * adding the new IDL file at `components/script/dom/webidls/Foo.webidl`;
//! * creating `components/script/dom/foo.rs`;
//! * listing `foo.rs` in `components/script/dom/mod.rs`;
//! * defining the DOM struct `Foo` with a `#[dom_struct]` attribute, a
//! superclass or `Reflector` member, and other members as appropriate;
//! * implementing the
//! `dom::bindings::codegen::Bindings::FooBindings::FooMethods` trait for
//! `Foo`;
//! * adding/updating the match arm in create_element in
//! `components/script/dom/create.rs` (only applicable to new types inheriting
//! from `HTMLElement`)
//!
//! More information is available in the [bindings module](bindings/index.html).
//!
//! Accessing DOM objects from layout
//! =================================
//!
//! Layout code can access the DOM through the
//! [`LayoutDom`](bindings/root/struct.LayoutDom.html) smart pointer. This does not
//! keep the DOM object alive; we ensure that no DOM code (Garbage Collection
//! in particular) runs while the layout thread is accessing the DOM.
//!
//! Methods accessible to layout are implemented on `LayoutDom<Foo>` using
//! `LayoutFooHelpers` traits.
#[macro_use]
pub mod macros;
pub mod types {
include!(concat!(env!("OUT_DIR"), "/InterfaceTypes.rs"));
}
pub mod abstractworker;
pub mod abstractworkerglobalscope;
pub mod activation;
pub mod analysernode;
pub mod animationevent;
pub mod attr;
pub mod audiobuffer;
pub mod audiobuffersourcenode;
pub mod audiocontext;
pub mod audiodestinationnode;
pub mod audiolistener;
pub mod audionode;
pub mod audioparam;
pub mod audioscheduledsourcenode;
pub mod audiotrack;
pub mod audiotracklist;
pub mod baseaudiocontext;
pub mod beforeunloadevent;
pub mod bindings;
pub mod biquadfilternode;
pub mod blob;
pub mod bluetooth;
pub mod bluetoothadvertisingevent;
pub mod bluetoothcharacteristicproperties;
pub mod bluetoothdevice;
pub mod bluetoothpermissionresult;
pub mod bluetoothremotegattcharacteristic;
pub mod bluetoothremotegattdescriptor;
pub mod bluetoothremotegattserver;
pub mod bluetoothremotegattservice;
pub mod bluetoothuuid;
pub mod broadcastchannel;
pub mod canvasgradient;
pub mod canvaspattern;
pub mod canvasrenderingcontext2d;
pub mod cdatasection;
pub mod channelmergernode;
pub mod channelsplitternode;
pub mod characterdata;
pub mod client;
pub mod closeevent;
pub mod comment;
pub mod compositionevent;
pub mod console;
pub mod constantsourcenode;
mod create;
pub mod crypto;
pub mod css;
pub mod cssconditionrule;
pub mod cssfontfacerule;
pub mod cssgroupingrule;
pub mod cssimportrule;
pub mod csskeyframerule;
pub mod csskeyframesrule;
pub mod cssmediarule;
pub mod cssnamespacerule;
pub mod cssrule;
pub mod cssrulelist;
pub mod cssstyledeclaration;
pub mod cssstylerule;
pub mod cssstylesheet;
pub mod cssstylevalue;
pub mod csssupportsrule;
pub mod cssviewportrule;
pub mod customelementregistry;
pub mod customevent;
pub mod dedicatedworkerglobalscope;
pub mod dissimilaroriginlocation;
pub mod dissimilaroriginwindow;
pub mod document;
pub mod documentfragment;
pub mod documentorshadowroot;
pub mod documenttype;
pub mod domexception;
pub mod domimplementation;
pub mod dommatrix;
pub mod dommatrixreadonly;
pub mod domparser;
pub mod dompoint;
pub mod dompointreadonly;
pub mod domquad;
pub mod domrect;
pub mod domrectreadonly;
pub mod domstringlist;
pub mod domstringmap;
pub mod domtokenlist;
pub mod element;
pub mod errorevent;
pub mod event;
pub mod eventsource;
pub mod eventtarget;
pub mod extendableevent;
pub mod extendablemessageevent;
pub mod fakexrdevice;
pub mod fakexrinputcontroller;
pub mod file;
pub mod filelist;
pub mod filereader;
pub mod filereadersync;
pub mod focusevent;
pub mod formdata;
pub mod formdataevent;
pub mod gainnode;
pub mod gamepad;
pub mod gamepadbutton;
pub mod gamepadbuttonlist;
pub mod gamepadevent;
pub mod gamepadlist;
pub mod gamepadpose;
pub mod globalscope;
pub mod gpu;
pub mod gpuadapter;
pub mod gpubindgroup;
pub mod gpubindgrouplayout;
pub mod gpubuffer;
pub mod gpubufferusage;
pub mod gpucommandbuffer;
pub mod gpucommandencoder;
pub mod gpucomputepassencoder;
pub mod gpucomputepipeline;
pub mod gpudevice;
pub mod gpupipelinelayout;
pub mod gpuqueue;
pub mod gpushadermodule;
pub mod gpushaderstage;
pub mod hashchangeevent;
pub mod headers;
pub mod history;
pub mod htmlanchorelement;
pub mod htmlareaelement;
pub mod htmlaudioelement;
pub mod htmlbaseelement;
pub mod htmlbodyelement;
pub mod htmlbrelement;
pub mod htmlbuttonelement;
pub mod htmlcanvaselement;
pub mod htmlcollection;
pub mod htmldataelement;
pub mod htmldatalistelement;
pub mod htmldetailselement;
pub mod htmldialogelement;
pub mod htmldirectoryelement;
pub mod htmldivelement;
pub mod htmldlistelement;
pub mod htmlelement;
pub mod htmlembedelement;
pub mod htmlfieldsetelement;
pub mod htmlfontelement;
pub mod htmlformcontrolscollection;
pub mod htmlformelement;
pub mod htmlframeelement;
pub mod htmlframesetelement;
pub mod htmlheadelement;
pub mod htmlheadingelement;
pub mod htmlhrelement;
pub mod htmlhtmlelement;
pub mod htmliframeelement;
pub mod htmlimageelement;
pub mod htmlinputelement;
pub mod htmllabelelement;
pub mod htmllegendelement;
pub mod htmllielement;
pub mod htmllinkelement;
pub mod htmlmapelement;
pub mod htmlmediaelement;
pub mod htmlmenuelement;
pub mod htmlmetaelement;
pub mod htmlmeterelement;
pub mod htmlmodelement;
pub mod htmlobjectelement;
pub mod htmlolistelement;
pub mod htmloptgroupelement;
pub mod htmloptionelement;
pub mod htmloptionscollection;
pub mod htmloutputelement;
pub mod htmlparagraphelement;
pub mod htmlparamelement;
pub mod htmlpictureelement;
pub mod htmlpreelement;
pub mod htmlprogresselement;
pub mod htmlquoteelement;
pub mod htmlscriptelement;
pub mod htmlselectelement;
pub mod htmlsourceelement;
pub mod htmlspanelement;
pub mod htmlstyleelement;
pub mod htmltablecaptionelement;
pub mod htmltablecellelement;
pub mod htmltablecolelement;
pub mod htmltableelement;
pub mod htmltablerowelement;
pub mod htmltablesectionelement;
pub mod htmltemplateelement;
pub mod htmltextareaelement;
pub mod htmltimeelement;
pub mod htmltitleelement;
pub mod htmltrackelement;
pub mod htmlulistelement;
pub mod htmlunknownelement;
pub mod htmlvideoelement;
pub mod identityhub;
pub mod imagebitmap;
pub mod imagedata;
pub mod inputevent;
pub mod keyboardevent;
pub mod location;
pub mod mediadevices;
pub mod mediaelementaudiosourcenode;
pub mod mediaerror;
pub mod mediafragmentparser;
pub mod medialist;
pub mod mediametadata;
pub mod mediaquerylist;
pub mod mediaquerylistevent;
pub mod mediasession;
pub mod mediastream;
pub mod mediastreamtrack;
pub mod messagechannel;
pub mod messageevent;
pub mod messageport;
pub mod mimetype;
pub mod mimetypearray;
|
pub mod mutationobserver;
pub mod mutationrecord;
pub mod namednodemap;
pub mod navigationpreloadmanager;
pub mod navigator;
pub mod navigatorinfo;
pub mod node;
pub mod nodeiterator;
pub mod nodelist;
pub mod offlineaudiocompletionevent;
pub mod offlineaudiocontext;
pub mod offscreencanvas;
pub mod offscreencanvasrenderingcontext2d;
pub mod oscillatornode;
pub mod pagetransitionevent;
pub mod paintrenderingcontext2d;
pub mod paintsize;
pub mod paintworkletglobalscope;
pub mod pannernode;
pub mod performance;
pub mod performanceentry;
pub mod performancemark;
pub mod performancemeasure;
pub mod performancenavigation;
pub mod performancenavigationtiming;
pub mod performanceobserver;
pub mod performanceobserverentrylist;
pub mod performancepainttiming;
pub mod performanceresourcetiming;
pub mod permissions;
pub mod permissionstatus;
pub mod plugin;
pub mod pluginarray;
pub mod popstateevent;
pub mod processinginstruction;
pub mod progressevent;
pub mod promise;
pub mod promisenativehandler;
pub mod promiserejectionevent;
pub mod radionodelist;
pub mod range;
pub mod raredata;
pub mod request;
pub mod response;
pub mod rtcicecandidate;
pub mod rtcpeerconnection;
pub mod rtcpeerconnectioniceevent;
pub mod rtcsessiondescription;
pub mod rtctrackevent;
pub mod screen;
pub mod selection;
pub mod serviceworker;
pub mod serviceworkercontainer;
pub mod serviceworkerglobalscope;
pub mod serviceworkerregistration;
pub mod servoparser;
pub mod shadowroot;
pub mod stereopannernode;
pub mod storage;
pub mod storageevent;
pub mod stylepropertymapreadonly;
pub mod stylesheet;
pub mod stylesheetlist;
pub mod submitevent;
pub mod svgelement;
pub mod svggraphicselement;
pub mod svgsvgelement;
pub mod testbinding;
pub mod testbindingiterable;
pub mod testbindingpairiterable;
pub mod testbindingproxy;
pub mod testrunner;
pub mod testworklet;
pub mod testworkletglobalscope;
pub mod text;
pub mod textcontrol;
pub mod textdecoder;
pub mod textencoder;
pub mod textmetrics;
pub mod texttrack;
pub mod texttrackcue;
pub mod texttrackcuelist;
pub mod texttracklist;
pub mod timeranges;
pub mod touch;
pub mod touchevent;
pub mod touchlist;
pub mod trackevent;
pub mod transitionevent;
pub mod treewalker;
pub mod uievent;
pub mod url;
pub mod urlhelper;
pub mod urlsearchparams;
pub mod userscripts;
pub mod validation;
pub mod validitystate;
pub mod values;
pub mod vertexarrayobject;
pub mod videotrack;
pub mod videotracklist;
pub mod virtualmethods;
pub mod vttcue;
pub mod vttregion;
pub mod webgl2renderingcontext;
pub mod webgl_extensions;
pub mod webgl_validations;
pub mod webglactiveinfo;
pub mod webglbuffer;
pub mod webglcontextevent;
pub mod webglframebuffer;
pub mod webglobject;
pub mod webglprogram;
pub mod webglquery;
pub mod webglrenderbuffer;
pub mod webglrenderingcontext;
pub mod webglsampler;
pub mod webglshader;
pub mod webglshaderprecisionformat;
pub mod webglsync;
pub mod webgltexture;
pub mod webgltransformfeedback;
pub mod webgluniformlocation;
pub mod webglvertexarrayobject;
pub mod webglvertexarrayobjectoes;
pub mod websocket;
pub mod wheelevent;
pub mod window;
pub mod windowproxy;
pub mod worker;
pub mod workerglobalscope;
pub mod workerlocation;
pub mod workernavigator;
pub mod worklet;
pub mod workletglobalscope;
pub mod xmldocument;
pub mod xmlhttprequest;
pub mod xmlhttprequesteventtarget;
pub mod xmlhttprequestupload;
pub mod xmlserializer;
pub mod xrframe;
pub mod xrhand;
pub mod xrhittestresult;
pub mod xrhittestsource;
pub mod xrinputsource;
pub mod xrinputsourcearray;
pub mod xrinputsourceevent;
pub mod xrinputsourceschangeevent;
pub mod xrjointpose;
pub mod xrjointspace;
pub mod xrlayer;
pub mod xrmediabinding;
pub mod xrpose;
pub mod xrray;
pub mod xrreferencespace;
pub mod xrrenderstate;
pub mod xrrigidtransform;
pub mod xrsession;
pub mod xrsessionevent;
pub mod xrspace;
pub mod xrsubimage;
pub mod xrsystem;
pub mod xrtest;
pub mod xrview;
pub mod xrviewerpose;
pub mod xrviewport;
pub mod xrwebglbinding;
pub mod xrwebgllayer;
pub mod xrwebglsubimage;
pub use self::webgl_extensions::ext::*;
|
pub mod mouseevent;
|
random_line_split
|
clone.rs
|
//! The `Clone` trait for types that cannot be 'implicitly copied'.
//!
//! In Rust, some simple types are "implicitly copyable" and when you
//! assign them or pass them as arguments, the receiver will get a copy,
//! leaving the original value in place. These types do not require
//! allocation to copy and do not have finalizers (i.e., they do not
//! contain owned boxes or implement [`Drop`]), so the compiler considers
//! them cheap and safe to copy. For other types copies must be made
//! explicitly, by convention implementing the [`Clone`] trait and calling
//! the [`clone`] method.
//!
//! [`clone`]: Clone::clone
//!
//! Basic usage example:
//!
//! ```
//! let s = String::new(); // String type implements Clone
//! let copy = s.clone(); // so we can clone it
//! ```
//!
//! To easily implement the Clone trait, you can also use
//! `#[derive(Clone)]`. Example:
//!
//! ```
//! #[derive(Clone)] // we add the Clone trait to Morpheus struct
//! struct Morpheus {
//! blue_pill: f32,
//! red_pill: i64,
//! }
//!
//! fn main() {
//! let f = Morpheus { blue_pill: 0.0, red_pill: 0 };
//! let copy = f.clone(); // and now we can clone it!
//! }
//! ```
#![stable(feature = "rust1", since = "1.0.0")]
/// A common trait for the ability to explicitly duplicate an object.
///
/// Differs from [`Copy`] in that [`Copy`] is implicit and an inexpensive bit-wise copy, while
/// `Clone` is always explicit and may or may not be expensive. In order to enforce
/// these characteristics, Rust does not allow you to reimplement [`Copy`], but you
/// may reimplement `Clone` and run arbitrary code.
///
/// Since `Clone` is more general than [`Copy`], you can automatically make anything
/// [`Copy`] be `Clone` as well.
///
/// ## Derivable
///
/// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d
/// implementation of [`Clone`] calls [`clone`] on each field.
///
/// [`clone`]: Clone::clone
///
/// For a generic struct, `#[derive]` implements `Clone` conditionally by adding bound `Clone` on
/// generic parameters.
///
/// ```
/// // `derive` implements Clone for Reading<T> when T is Clone.
/// #[derive(Clone)]
/// struct Reading<T> {
/// frequency: T,
|
///
/// Types that are [`Copy`] should have a trivial implementation of `Clone`. More formally:
/// if `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`.
/// Manual implementations should be careful to uphold this invariant; however, unsafe code
/// must not rely on it to ensure memory safety.
///
/// An example is a generic struct holding a function pointer. In this case, the
/// implementation of `Clone` cannot be `derive`d, but can be implemented as:
///
/// ```
/// struct Generate<T>(fn() -> T);
///
/// impl<T> Copy for Generate<T> {}
///
/// impl<T> Clone for Generate<T> {
/// fn clone(&self) -> Self {
/// *self
/// }
/// }
/// ```
///
/// ## Additional implementors
///
/// In addition to the [implementors listed below][impls],
/// the following types also implement `Clone`:
///
/// * Function item types (i.e., the distinct types defined for each function)
/// * Function pointer types (e.g., `fn() -> i32`)
/// * Tuple types, if each component also implements `Clone` (e.g., `()`, `(i32, bool)`)
/// * Closure types, if they capture no value from the environment
/// or if all such captured values implement `Clone` themselves.
/// Note that variables captured by shared reference always implement `Clone`
/// (even if the referent doesn't),
/// while variables captured by mutable reference never implement `Clone`.
///
/// [impls]: #implementors
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "clone"]
#[rustc_diagnostic_item = "Clone"]
#[rustc_trivial_field_reads]
pub trait Clone: Sized {
/// Returns a copy of the value.
///
/// # Examples
///
/// ```
/// # #![allow(noop_method_call)]
/// let hello = "Hello"; // &str implements Clone
///
/// assert_eq!("Hello", hello.clone());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use = "cloning is often expensive and is not expected to have side effects"]
fn clone(&self) -> Self;
/// Performs copy-assignment from `source`.
///
/// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,
/// but can be overridden to reuse the resources of `a` to avoid unnecessary
/// allocations.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn clone_from(&mut self, source: &Self) {
*self = source.clone()
}
}
/// Derive macro generating an impl of the trait `Clone`.
#[rustc_builtin_macro]
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
pub macro Clone($item:item) {
/* compiler built-in */
}
// FIXME(aburka): these structs are used solely by #[derive] to
// assert that every component of a type implements Clone or Copy.
//
// These structs should never appear in user code.
#[doc(hidden)]
#[allow(missing_debug_implementations)]
#[unstable(
feature = "derive_clone_copy",
reason = "deriving hack, should not be public",
issue = "none"
)]
pub struct AssertParamIsClone<T: Clone +?Sized> {
_field: crate::marker::PhantomData<T>,
}
#[doc(hidden)]
#[allow(missing_debug_implementations)]
#[unstable(
feature = "derive_clone_copy",
reason = "deriving hack, should not be public",
issue = "none"
)]
pub struct AssertParamIsCopy<T: Copy +?Sized> {
_field: crate::marker::PhantomData<T>,
}
/// Implementations of `Clone` for primitive types.
///
/// Implementations that cannot be described in Rust
/// are implemented in `traits::SelectionContext::copy_clone_conditions()`
/// in `rustc_trait_selection`.
mod impls {
use super::Clone;
macro_rules! impl_clone {
($($t:ty)*) => {
$(
#[stable(feature = "rust1", since = "1.0.0")]
impl Clone for $t {
#[inline]
fn clone(&self) -> Self {
*self
}
}
)*
}
}
impl_clone! {
usize u8 u16 u32 u64 u128
isize i8 i16 i32 i64 i128
f32 f64
bool char
}
#[unstable(feature = "never_type", issue = "35121")]
impl Clone for! {
#[inline]
fn clone(&self) -> Self {
*self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Clone for *const T {
#[inline]
fn clone(&self) -> Self {
*self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Clone for *mut T {
#[inline]
fn clone(&self) -> Self {
*self
}
}
/// Shared references can be cloned, but mutable references *cannot*!
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Clone for &T {
#[inline]
#[rustc_diagnostic_item = "noop_method_clone"]
fn clone(&self) -> Self {
*self
}
}
/// Shared references can be cloned, but mutable references *cannot*!
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized>!Clone for &mut T {}
}
|
/// }
/// ```
///
/// ## How can I implement `Clone`?
|
random_line_split
|
clone.rs
|
//! The `Clone` trait for types that cannot be 'implicitly copied'.
//!
//! In Rust, some simple types are "implicitly copyable" and when you
//! assign them or pass them as arguments, the receiver will get a copy,
//! leaving the original value in place. These types do not require
//! allocation to copy and do not have finalizers (i.e., they do not
//! contain owned boxes or implement [`Drop`]), so the compiler considers
//! them cheap and safe to copy. For other types copies must be made
//! explicitly, by convention implementing the [`Clone`] trait and calling
//! the [`clone`] method.
//!
//! [`clone`]: Clone::clone
//!
//! Basic usage example:
//!
//! ```
//! let s = String::new(); // String type implements Clone
//! let copy = s.clone(); // so we can clone it
//! ```
//!
//! To easily implement the Clone trait, you can also use
//! `#[derive(Clone)]`. Example:
//!
//! ```
//! #[derive(Clone)] // we add the Clone trait to Morpheus struct
//! struct Morpheus {
//! blue_pill: f32,
//! red_pill: i64,
//! }
//!
//! fn main() {
//! let f = Morpheus { blue_pill: 0.0, red_pill: 0 };
//! let copy = f.clone(); // and now we can clone it!
//! }
//! ```
#![stable(feature = "rust1", since = "1.0.0")]
/// A common trait for the ability to explicitly duplicate an object.
///
/// Differs from [`Copy`] in that [`Copy`] is implicit and an inexpensive bit-wise copy, while
/// `Clone` is always explicit and may or may not be expensive. In order to enforce
/// these characteristics, Rust does not allow you to reimplement [`Copy`], but you
/// may reimplement `Clone` and run arbitrary code.
///
/// Since `Clone` is more general than [`Copy`], you can automatically make anything
/// [`Copy`] be `Clone` as well.
///
/// ## Derivable
///
/// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d
/// implementation of [`Clone`] calls [`clone`] on each field.
///
/// [`clone`]: Clone::clone
///
/// For a generic struct, `#[derive]` implements `Clone` conditionally by adding bound `Clone` on
/// generic parameters.
///
/// ```
/// // `derive` implements Clone for Reading<T> when T is Clone.
/// #[derive(Clone)]
/// struct Reading<T> {
/// frequency: T,
/// }
/// ```
///
/// ## How can I implement `Clone`?
///
/// Types that are [`Copy`] should have a trivial implementation of `Clone`. More formally:
/// if `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`.
/// Manual implementations should be careful to uphold this invariant; however, unsafe code
/// must not rely on it to ensure memory safety.
///
/// An example is a generic struct holding a function pointer. In this case, the
/// implementation of `Clone` cannot be `derive`d, but can be implemented as:
///
/// ```
/// struct Generate<T>(fn() -> T);
///
/// impl<T> Copy for Generate<T> {}
///
/// impl<T> Clone for Generate<T> {
/// fn clone(&self) -> Self {
/// *self
/// }
/// }
/// ```
///
/// ## Additional implementors
///
/// In addition to the [implementors listed below][impls],
/// the following types also implement `Clone`:
///
/// * Function item types (i.e., the distinct types defined for each function)
/// * Function pointer types (e.g., `fn() -> i32`)
/// * Tuple types, if each component also implements `Clone` (e.g., `()`, `(i32, bool)`)
/// * Closure types, if they capture no value from the environment
/// or if all such captured values implement `Clone` themselves.
/// Note that variables captured by shared reference always implement `Clone`
/// (even if the referent doesn't),
/// while variables captured by mutable reference never implement `Clone`.
///
/// [impls]: #implementors
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "clone"]
#[rustc_diagnostic_item = "Clone"]
#[rustc_trivial_field_reads]
pub trait Clone: Sized {
/// Returns a copy of the value.
///
/// # Examples
///
/// ```
/// # #![allow(noop_method_call)]
/// let hello = "Hello"; // &str implements Clone
///
/// assert_eq!("Hello", hello.clone());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use = "cloning is often expensive and is not expected to have side effects"]
fn clone(&self) -> Self;
/// Performs copy-assignment from `source`.
///
/// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,
/// but can be overridden to reuse the resources of `a` to avoid unnecessary
/// allocations.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn clone_from(&mut self, source: &Self) {
*self = source.clone()
}
}
/// Derive macro generating an impl of the trait `Clone`.
#[rustc_builtin_macro]
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
pub macro Clone($item:item) {
/* compiler built-in */
}
// FIXME(aburka): these structs are used solely by #[derive] to
// assert that every component of a type implements Clone or Copy.
//
// These structs should never appear in user code.
#[doc(hidden)]
#[allow(missing_debug_implementations)]
#[unstable(
feature = "derive_clone_copy",
reason = "deriving hack, should not be public",
issue = "none"
)]
pub struct AssertParamIsClone<T: Clone +?Sized> {
_field: crate::marker::PhantomData<T>,
}
#[doc(hidden)]
#[allow(missing_debug_implementations)]
#[unstable(
feature = "derive_clone_copy",
reason = "deriving hack, should not be public",
issue = "none"
)]
pub struct AssertParamIsCopy<T: Copy +?Sized> {
_field: crate::marker::PhantomData<T>,
}
/// Implementations of `Clone` for primitive types.
///
/// Implementations that cannot be described in Rust
/// are implemented in `traits::SelectionContext::copy_clone_conditions()`
/// in `rustc_trait_selection`.
mod impls {
use super::Clone;
macro_rules! impl_clone {
($($t:ty)*) => {
$(
#[stable(feature = "rust1", since = "1.0.0")]
impl Clone for $t {
#[inline]
fn clone(&self) -> Self {
*self
}
}
)*
}
}
impl_clone! {
usize u8 u16 u32 u64 u128
isize i8 i16 i32 i64 i128
f32 f64
bool char
}
#[unstable(feature = "never_type", issue = "35121")]
impl Clone for! {
#[inline]
fn clone(&self) -> Self
|
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Clone for *const T {
#[inline]
fn clone(&self) -> Self {
*self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Clone for *mut T {
#[inline]
fn clone(&self) -> Self {
*self
}
}
/// Shared references can be cloned, but mutable references *cannot*!
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Clone for &T {
#[inline]
#[rustc_diagnostic_item = "noop_method_clone"]
fn clone(&self) -> Self {
*self
}
}
/// Shared references can be cloned, but mutable references *cannot*!
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized>!Clone for &mut T {}
}
|
{
*self
}
|
identifier_body
|
clone.rs
|
//! The `Clone` trait for types that cannot be 'implicitly copied'.
//!
//! In Rust, some simple types are "implicitly copyable" and when you
//! assign them or pass them as arguments, the receiver will get a copy,
//! leaving the original value in place. These types do not require
//! allocation to copy and do not have finalizers (i.e., they do not
//! contain owned boxes or implement [`Drop`]), so the compiler considers
//! them cheap and safe to copy. For other types copies must be made
//! explicitly, by convention implementing the [`Clone`] trait and calling
//! the [`clone`] method.
//!
//! [`clone`]: Clone::clone
//!
//! Basic usage example:
//!
//! ```
//! let s = String::new(); // String type implements Clone
//! let copy = s.clone(); // so we can clone it
//! ```
//!
//! To easily implement the Clone trait, you can also use
//! `#[derive(Clone)]`. Example:
//!
//! ```
//! #[derive(Clone)] // we add the Clone trait to Morpheus struct
//! struct Morpheus {
//! blue_pill: f32,
//! red_pill: i64,
//! }
//!
//! fn main() {
//! let f = Morpheus { blue_pill: 0.0, red_pill: 0 };
//! let copy = f.clone(); // and now we can clone it!
//! }
//! ```
#![stable(feature = "rust1", since = "1.0.0")]
/// A common trait for the ability to explicitly duplicate an object.
///
/// Differs from [`Copy`] in that [`Copy`] is implicit and an inexpensive bit-wise copy, while
/// `Clone` is always explicit and may or may not be expensive. In order to enforce
/// these characteristics, Rust does not allow you to reimplement [`Copy`], but you
/// may reimplement `Clone` and run arbitrary code.
///
/// Since `Clone` is more general than [`Copy`], you can automatically make anything
/// [`Copy`] be `Clone` as well.
///
/// ## Derivable
///
/// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d
/// implementation of [`Clone`] calls [`clone`] on each field.
///
/// [`clone`]: Clone::clone
///
/// For a generic struct, `#[derive]` implements `Clone` conditionally by adding bound `Clone` on
/// generic parameters.
///
/// ```
/// // `derive` implements Clone for Reading<T> when T is Clone.
/// #[derive(Clone)]
/// struct Reading<T> {
/// frequency: T,
/// }
/// ```
///
/// ## How can I implement `Clone`?
///
/// Types that are [`Copy`] should have a trivial implementation of `Clone`. More formally:
/// if `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`.
/// Manual implementations should be careful to uphold this invariant; however, unsafe code
/// must not rely on it to ensure memory safety.
///
/// An example is a generic struct holding a function pointer. In this case, the
/// implementation of `Clone` cannot be `derive`d, but can be implemented as:
///
/// ```
/// struct Generate<T>(fn() -> T);
///
/// impl<T> Copy for Generate<T> {}
///
/// impl<T> Clone for Generate<T> {
/// fn clone(&self) -> Self {
/// *self
/// }
/// }
/// ```
///
/// ## Additional implementors
///
/// In addition to the [implementors listed below][impls],
/// the following types also implement `Clone`:
///
/// * Function item types (i.e., the distinct types defined for each function)
/// * Function pointer types (e.g., `fn() -> i32`)
/// * Tuple types, if each component also implements `Clone` (e.g., `()`, `(i32, bool)`)
/// * Closure types, if they capture no value from the environment
/// or if all such captured values implement `Clone` themselves.
/// Note that variables captured by shared reference always implement `Clone`
/// (even if the referent doesn't),
/// while variables captured by mutable reference never implement `Clone`.
///
/// [impls]: #implementors
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "clone"]
#[rustc_diagnostic_item = "Clone"]
#[rustc_trivial_field_reads]
pub trait Clone: Sized {
/// Returns a copy of the value.
///
/// # Examples
///
/// ```
/// # #![allow(noop_method_call)]
/// let hello = "Hello"; // &str implements Clone
///
/// assert_eq!("Hello", hello.clone());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use = "cloning is often expensive and is not expected to have side effects"]
fn clone(&self) -> Self;
/// Performs copy-assignment from `source`.
///
/// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,
/// but can be overridden to reuse the resources of `a` to avoid unnecessary
/// allocations.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn clone_from(&mut self, source: &Self) {
*self = source.clone()
}
}
/// Derive macro generating an impl of the trait `Clone`.
#[rustc_builtin_macro]
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
pub macro Clone($item:item) {
/* compiler built-in */
}
// FIXME(aburka): these structs are used solely by #[derive] to
// assert that every component of a type implements Clone or Copy.
//
// These structs should never appear in user code.
#[doc(hidden)]
#[allow(missing_debug_implementations)]
#[unstable(
feature = "derive_clone_copy",
reason = "deriving hack, should not be public",
issue = "none"
)]
pub struct
|
<T: Clone +?Sized> {
_field: crate::marker::PhantomData<T>,
}
#[doc(hidden)]
#[allow(missing_debug_implementations)]
#[unstable(
feature = "derive_clone_copy",
reason = "deriving hack, should not be public",
issue = "none"
)]
pub struct AssertParamIsCopy<T: Copy +?Sized> {
_field: crate::marker::PhantomData<T>,
}
/// Implementations of `Clone` for primitive types.
///
/// Implementations that cannot be described in Rust
/// are implemented in `traits::SelectionContext::copy_clone_conditions()`
/// in `rustc_trait_selection`.
mod impls {
use super::Clone;
macro_rules! impl_clone {
($($t:ty)*) => {
$(
#[stable(feature = "rust1", since = "1.0.0")]
impl Clone for $t {
#[inline]
fn clone(&self) -> Self {
*self
}
}
)*
}
}
impl_clone! {
usize u8 u16 u32 u64 u128
isize i8 i16 i32 i64 i128
f32 f64
bool char
}
#[unstable(feature = "never_type", issue = "35121")]
impl Clone for! {
#[inline]
fn clone(&self) -> Self {
*self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Clone for *const T {
#[inline]
fn clone(&self) -> Self {
*self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Clone for *mut T {
#[inline]
fn clone(&self) -> Self {
*self
}
}
/// Shared references can be cloned, but mutable references *cannot*!
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Clone for &T {
#[inline]
#[rustc_diagnostic_item = "noop_method_clone"]
fn clone(&self) -> Self {
*self
}
}
/// Shared references can be cloned, but mutable references *cannot*!
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized>!Clone for &mut T {}
}
|
AssertParamIsClone
|
identifier_name
|
issue-53548.rs
|
// Regression test for #53548. The `Box<dyn Trait>` type below is
// expanded to `Box<dyn Trait +'static>`, but the generator "witness"
// that results is `for<'r> { Box<dyn Trait + 'r> }`. The WF code was
// encountering an ICE (when debug-assertions were enabled) and an
// unexpected compilation error (without debug-asserions) when trying
// to process this `'r` region bound. In particular, to be WF, the
// region bound must meet the requirements of the trait, and hence we
// got `for<'r> { 'r:'static }`. This would ICE because the `Binder`
// constructor we were using was assering that no higher-ranked
// regions were involved (because the WF code is supposed to skip
// those). The error (if debug-asserions were disabled) came because
// we obviously cannot prove that `'r:'static` for any region `'r`.
// Pursuant with our "lazy WF" strategy for higher-ranked regions, the
// fix is not to require that `for<'r> { 'r:'static }` holds (this is
// also analogous to what we would do for higher-ranked regions
// appearing within the trait in other positions).
//
// check-pass
#![feature(generators)]
use std::cell::RefCell;
use std::rc::Rc;
trait Trait:'static {}
struct Store<C> {
inner: Rc<RefCell<Option<C>>>,
}
fn main() {
|
Box::new(static move || {
let store = Store::<Box<dyn Trait>> {
inner: Default::default(),
};
yield ();
});
}
|
random_line_split
|
|
issue-53548.rs
|
// Regression test for #53548. The `Box<dyn Trait>` type below is
// expanded to `Box<dyn Trait +'static>`, but the generator "witness"
// that results is `for<'r> { Box<dyn Trait + 'r> }`. The WF code was
// encountering an ICE (when debug-assertions were enabled) and an
// unexpected compilation error (without debug-asserions) when trying
// to process this `'r` region bound. In particular, to be WF, the
// region bound must meet the requirements of the trait, and hence we
// got `for<'r> { 'r:'static }`. This would ICE because the `Binder`
// constructor we were using was assering that no higher-ranked
// regions were involved (because the WF code is supposed to skip
// those). The error (if debug-asserions were disabled) came because
// we obviously cannot prove that `'r:'static` for any region `'r`.
// Pursuant with our "lazy WF" strategy for higher-ranked regions, the
// fix is not to require that `for<'r> { 'r:'static }` holds (this is
// also analogous to what we would do for higher-ranked regions
// appearing within the trait in other positions).
//
// check-pass
#![feature(generators)]
use std::cell::RefCell;
use std::rc::Rc;
trait Trait:'static {}
struct Store<C> {
inner: Rc<RefCell<Option<C>>>,
}
fn
|
() {
Box::new(static move || {
let store = Store::<Box<dyn Trait>> {
inner: Default::default(),
};
yield ();
});
}
|
main
|
identifier_name
|
issue-53548.rs
|
// Regression test for #53548. The `Box<dyn Trait>` type below is
// expanded to `Box<dyn Trait +'static>`, but the generator "witness"
// that results is `for<'r> { Box<dyn Trait + 'r> }`. The WF code was
// encountering an ICE (when debug-assertions were enabled) and an
// unexpected compilation error (without debug-asserions) when trying
// to process this `'r` region bound. In particular, to be WF, the
// region bound must meet the requirements of the trait, and hence we
// got `for<'r> { 'r:'static }`. This would ICE because the `Binder`
// constructor we were using was assering that no higher-ranked
// regions were involved (because the WF code is supposed to skip
// those). The error (if debug-asserions were disabled) came because
// we obviously cannot prove that `'r:'static` for any region `'r`.
// Pursuant with our "lazy WF" strategy for higher-ranked regions, the
// fix is not to require that `for<'r> { 'r:'static }` holds (this is
// also analogous to what we would do for higher-ranked regions
// appearing within the trait in other positions).
//
// check-pass
#![feature(generators)]
use std::cell::RefCell;
use std::rc::Rc;
trait Trait:'static {}
struct Store<C> {
inner: Rc<RefCell<Option<C>>>,
}
fn main()
|
{
Box::new(static move || {
let store = Store::<Box<dyn Trait>> {
inner: Default::default(),
};
yield ();
});
}
|
identifier_body
|
|
file.rs
|
use std::path::Path;
use std::fs::File;
use std::fs::OpenOptions;
use std::error::Error;
use std::io::prelude::*;
use std::io::BufReader;
use regex::Regex;
#[allow(unused_variables)]
pub fn write(pathstring: &str, content: &str) -> bool {
let path = Path::new(pathstring);
let mut file = match File::create(&path) {
Err(why) => {panic!("couldn't create File: {}, File: {:?}", Error::description(&why), &path)}
Ok(file) => file,
};
match file.write_all(content.as_bytes()) {
Err(_) => false,
Ok(_) => true,
}
}
#[allow(unused_must_use)]
pub fn read(path: &Path) -> String {
let mut content: String = String::new();
let mut file = match File::open(&path) {
Err(why) => {panic!("couldn't create File: {}, File: {:?}", Error::description(&why), &path)}
Ok(file) => file,
};
file.read_to_string(&mut content);
content
}
#[allow(unused_must_use)]
pub fn read_line_regex(path: &Path, regex: &str) -> Vec<String> {
let f = &File::open(path).unwrap();
let file = BufReader::new(f);
let mut matches: Vec<String> = vec![];
for line in file.lines() {
let l = line.unwrap();
let re = Regex::new(regex).unwrap();
if re.is_match(l.as_ref()) {
matches.push(l);
}
}
matches
}
#[allow(unused_must_use)]
pub fn append(pathstring: &str, content: &str) -> bool
|
{
let path = Path::new(pathstring);
let mut file;
if path.exists() {
file = match OpenOptions::new().write(true).append(true).open(&path) {
Err(why) => {panic!("couldn't create File: {}, File: {:?}", Error::description(&why), &path)}
Ok(file) => file,
};
} else {
file = match OpenOptions::new().create(true).write(true).append(true).open(&path) {
Err(why) => {panic!("couldn't create File: {}, File: {:?}", Error::description(&why), &path)}
Ok(file) => file,
};
}
match file.write_all(content.as_bytes()) {Err(_) => false,Ok(_) => true,}
}
|
identifier_body
|
|
file.rs
|
use std::path::Path;
use std::fs::File;
use std::fs::OpenOptions;
use std::error::Error;
use std::io::prelude::*;
use std::io::BufReader;
use regex::Regex;
#[allow(unused_variables)]
pub fn write(pathstring: &str, content: &str) -> bool {
let path = Path::new(pathstring);
let mut file = match File::create(&path) {
Err(why) => {panic!("couldn't create File: {}, File: {:?}", Error::description(&why), &path)}
Ok(file) => file,
};
match file.write_all(content.as_bytes()) {
Err(_) => false,
Ok(_) => true,
}
}
#[allow(unused_must_use)]
pub fn
|
(path: &Path) -> String {
let mut content: String = String::new();
let mut file = match File::open(&path) {
Err(why) => {panic!("couldn't create File: {}, File: {:?}", Error::description(&why), &path)}
Ok(file) => file,
};
file.read_to_string(&mut content);
content
}
#[allow(unused_must_use)]
pub fn read_line_regex(path: &Path, regex: &str) -> Vec<String> {
let f = &File::open(path).unwrap();
let file = BufReader::new(f);
let mut matches: Vec<String> = vec![];
for line in file.lines() {
let l = line.unwrap();
let re = Regex::new(regex).unwrap();
if re.is_match(l.as_ref()) {
matches.push(l);
}
}
matches
}
#[allow(unused_must_use)]
pub fn append(pathstring: &str, content: &str) -> bool {
let path = Path::new(pathstring);
let mut file;
if path.exists() {
file = match OpenOptions::new().write(true).append(true).open(&path) {
Err(why) => {panic!("couldn't create File: {}, File: {:?}", Error::description(&why), &path)}
Ok(file) => file,
};
} else {
file = match OpenOptions::new().create(true).write(true).append(true).open(&path) {
Err(why) => {panic!("couldn't create File: {}, File: {:?}", Error::description(&why), &path)}
Ok(file) => file,
};
}
match file.write_all(content.as_bytes()) {Err(_) => false,Ok(_) => true,}
}
|
read
|
identifier_name
|
file.rs
|
use std::path::Path;
use std::fs::File;
use std::fs::OpenOptions;
use std::error::Error;
use std::io::prelude::*;
use std::io::BufReader;
|
pub fn write(pathstring: &str, content: &str) -> bool {
let path = Path::new(pathstring);
let mut file = match File::create(&path) {
Err(why) => {panic!("couldn't create File: {}, File: {:?}", Error::description(&why), &path)}
Ok(file) => file,
};
match file.write_all(content.as_bytes()) {
Err(_) => false,
Ok(_) => true,
}
}
#[allow(unused_must_use)]
pub fn read(path: &Path) -> String {
let mut content: String = String::new();
let mut file = match File::open(&path) {
Err(why) => {panic!("couldn't create File: {}, File: {:?}", Error::description(&why), &path)}
Ok(file) => file,
};
file.read_to_string(&mut content);
content
}
#[allow(unused_must_use)]
pub fn read_line_regex(path: &Path, regex: &str) -> Vec<String> {
let f = &File::open(path).unwrap();
let file = BufReader::new(f);
let mut matches: Vec<String> = vec![];
for line in file.lines() {
let l = line.unwrap();
let re = Regex::new(regex).unwrap();
if re.is_match(l.as_ref()) {
matches.push(l);
}
}
matches
}
#[allow(unused_must_use)]
pub fn append(pathstring: &str, content: &str) -> bool {
let path = Path::new(pathstring);
let mut file;
if path.exists() {
file = match OpenOptions::new().write(true).append(true).open(&path) {
Err(why) => {panic!("couldn't create File: {}, File: {:?}", Error::description(&why), &path)}
Ok(file) => file,
};
} else {
file = match OpenOptions::new().create(true).write(true).append(true).open(&path) {
Err(why) => {panic!("couldn't create File: {}, File: {:?}", Error::description(&why), &path)}
Ok(file) => file,
};
}
match file.write_all(content.as_bytes()) {Err(_) => false,Ok(_) => true,}
}
|
use regex::Regex;
#[allow(unused_variables)]
|
random_line_split
|
cstore.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.
#![allow(non_camel_case_types)]
// The crate store - a central repo for information collected about external
// crates and libraries
use back::svh::Svh;
use metadata::decoder;
use metadata::loader;
use std::cell::RefCell;
use std::c_vec::CVec;
use std::rc::Rc;
use collections::HashMap;
use syntax::ast;
use syntax::crateid::CrateId;
use syntax::codemap::Span;
use syntax::parse::token::IdentInterner;
// A map from external crate numbers (as decoded from some crate file) to
// local crate numbers (as generated during this session). Each external
// crate may refer to types in other external crates, and each has their
// own crate numbers.
pub type cnum_map = HashMap<ast::CrateNum, ast::CrateNum>;
pub enum MetadataBlob {
MetadataVec(CVec<u8>),
MetadataArchive(loader::ArchiveMetadata),
}
pub struct crate_metadata {
pub name: ~str,
pub data: MetadataBlob,
pub cnum_map: cnum_map,
pub cnum: ast::CrateNum,
pub span: Span,
}
#[deriving(Eq)]
pub enum LinkagePreference {
RequireDynamic,
RequireStatic,
}
#[deriving(Eq, FromPrimitive)]
pub enum NativeLibaryKind {
NativeStatic, // native static library (.a archive)
NativeFramework, // OSX-specific
NativeUnknown, // default way to specify a dynamic library
}
// Where a crate came from on the local filesystem. One of these two options
// must be non-None.
#[deriving(Eq, Clone)]
pub struct CrateSource {
pub dylib: Option<Path>,
pub rlib: Option<Path>,
pub cnum: ast::CrateNum,
}
pub struct CStore {
metas: RefCell<HashMap<ast::CrateNum, Rc<crate_metadata>>>,
extern_mod_crate_map: RefCell<extern_mod_crate_map>,
used_crate_sources: RefCell<Vec<CrateSource>>,
used_libraries: RefCell<Vec<(~str, NativeLibaryKind)>>,
used_link_args: RefCell<Vec<~str>>,
pub intr: Rc<IdentInterner>,
}
// Map from NodeId's of local extern crate statements to crate numbers
type extern_mod_crate_map = HashMap<ast::NodeId, ast::CrateNum>;
impl CStore {
pub fn new(intr: Rc<IdentInterner>) -> CStore {
CStore {
metas: RefCell::new(HashMap::new()),
extern_mod_crate_map: RefCell::new(HashMap::new()),
used_crate_sources: RefCell::new(Vec::new()),
used_libraries: RefCell::new(Vec::new()),
used_link_args: RefCell::new(Vec::new()),
intr: intr
}
}
pub fn next_crate_num(&self) -> ast::CrateNum {
self.metas.borrow().len() as ast::CrateNum + 1
}
pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc<crate_metadata> {
self.metas.borrow().get(&cnum).clone()
}
pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh {
let cdata = self.get_crate_data(cnum);
decoder::get_crate_hash(cdata.data())
}
pub fn set_crate_data(&self, cnum: ast::CrateNum, data: Rc<crate_metadata>) {
self.metas.borrow_mut().insert(cnum, data);
}
pub fn iter_crate_data(&self, i: |ast::CrateNum, &crate_metadata|) {
for (&k, v) in self.metas.borrow().iter() {
i(k, &**v);
}
}
pub fn add_used_crate_source(&self, src: CrateSource) {
let mut used_crate_sources = self.used_crate_sources.borrow_mut();
if!used_crate_sources.contains(&src) {
used_crate_sources.push(src);
}
}
pub fn get_used_crate_source(&self, cnum: ast::CrateNum)
-> Option<CrateSource> {
self.used_crate_sources.borrow_mut()
.iter().find(|source| source.cnum == cnum)
.map(|source| source.clone())
}
pub fn dump_phase_syntax_crates(&self) {
}
pub fn reset(&self) {
self.metas.borrow_mut().clear();
self.extern_mod_crate_map.borrow_mut().clear();
self.used_crate_sources.borrow_mut().clear();
self.used_libraries.borrow_mut().clear();
self.used_link_args.borrow_mut().clear();
}
// This method is used when generating the command line to pass through to
// system linker. The linker expects undefined symbols on the left of the
// command line to be defined in libraries on the right, not the other way
// around. For more info, see some comments in the add_used_library function
// below.
//
// In order to get this left-to-right dependency ordering, we perform a
// topological sort of all crates putting the leaves at the right-most
// positions.
pub fn get_used_crates(&self, prefer: LinkagePreference)
-> Vec<(ast::CrateNum, Option<Path>)> {
let mut ordering = Vec::new();
fn visit(cstore: &CStore, cnum: ast::CrateNum,
ordering: &mut Vec<ast::CrateNum>) {
if ordering.as_slice().contains(&cnum) { return }
let meta = cstore.get_crate_data(cnum);
for (_, &dep) in meta.cnum_map.iter() {
visit(cstore, dep, ordering);
}
ordering.push(cnum);
};
for (&num, _) in self.metas.borrow().iter() {
visit(self, num, &mut ordering);
}
ordering.as_mut_slice().reverse();
let ordering = ordering.as_slice();
let mut libs = self.used_crate_sources.borrow()
.iter()
.map(|src| (src.cnum, match prefer {
RequireDynamic => src.dylib.clone(),
RequireStatic => src.rlib.clone(),
}))
.collect::<Vec<(ast::CrateNum, Option<Path>)>>();
libs.sort_by(|&(a, _), &(b, _)| {
ordering.position_elem(&a).cmp(&ordering.position_elem(&b))
});
libs
}
pub fn add_used_library(&self, lib: ~str, kind: NativeLibaryKind) {
assert!(!lib.is_empty());
self.used_libraries.borrow_mut().push((lib, kind));
}
pub fn get_used_libraries<'a>(&'a self)
-> &'a RefCell<Vec<(~str, NativeLibaryKind)> > {
&self.used_libraries
}
pub fn add_used_link_args(&self, args: &str)
|
pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<~str> > {
&self.used_link_args
}
pub fn add_extern_mod_stmt_cnum(&self,
emod_id: ast::NodeId,
cnum: ast::CrateNum) {
self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum);
}
pub fn find_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId)
-> Option<ast::CrateNum> {
self.extern_mod_crate_map.borrow().find(&emod_id).map(|x| *x)
}
}
impl crate_metadata {
pub fn data<'a>(&'a self) -> &'a [u8] { self.data.as_slice() }
pub fn crate_id(&self) -> CrateId { decoder::get_crate_id(self.data()) }
pub fn hash(&self) -> Svh { decoder::get_crate_hash(self.data()) }
}
impl MetadataBlob {
pub fn as_slice<'a>(&'a self) -> &'a [u8] {
match *self {
MetadataVec(ref vec) => vec.as_slice(),
MetadataArchive(ref ar) => ar.as_slice(),
}
}
}
|
{
for s in args.split(' ') {
self.used_link_args.borrow_mut().push(s.to_owned());
}
}
|
identifier_body
|
cstore.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.
#![allow(non_camel_case_types)]
// The crate store - a central repo for information collected about external
// crates and libraries
use back::svh::Svh;
use metadata::decoder;
use metadata::loader;
use std::cell::RefCell;
use std::c_vec::CVec;
use std::rc::Rc;
use collections::HashMap;
use syntax::ast;
use syntax::crateid::CrateId;
use syntax::codemap::Span;
use syntax::parse::token::IdentInterner;
// A map from external crate numbers (as decoded from some crate file) to
// local crate numbers (as generated during this session). Each external
// crate may refer to types in other external crates, and each has their
// own crate numbers.
pub type cnum_map = HashMap<ast::CrateNum, ast::CrateNum>;
pub enum MetadataBlob {
MetadataVec(CVec<u8>),
MetadataArchive(loader::ArchiveMetadata),
}
pub struct crate_metadata {
pub name: ~str,
pub data: MetadataBlob,
pub cnum_map: cnum_map,
pub cnum: ast::CrateNum,
pub span: Span,
}
#[deriving(Eq)]
pub enum LinkagePreference {
RequireDynamic,
RequireStatic,
}
#[deriving(Eq, FromPrimitive)]
pub enum NativeLibaryKind {
NativeStatic, // native static library (.a archive)
NativeFramework, // OSX-specific
NativeUnknown, // default way to specify a dynamic library
}
// Where a crate came from on the local filesystem. One of these two options
// must be non-None.
#[deriving(Eq, Clone)]
pub struct CrateSource {
pub dylib: Option<Path>,
pub rlib: Option<Path>,
pub cnum: ast::CrateNum,
}
pub struct CStore {
metas: RefCell<HashMap<ast::CrateNum, Rc<crate_metadata>>>,
extern_mod_crate_map: RefCell<extern_mod_crate_map>,
used_crate_sources: RefCell<Vec<CrateSource>>,
used_libraries: RefCell<Vec<(~str, NativeLibaryKind)>>,
used_link_args: RefCell<Vec<~str>>,
pub intr: Rc<IdentInterner>,
}
// Map from NodeId's of local extern crate statements to crate numbers
type extern_mod_crate_map = HashMap<ast::NodeId, ast::CrateNum>;
impl CStore {
pub fn new(intr: Rc<IdentInterner>) -> CStore {
CStore {
metas: RefCell::new(HashMap::new()),
extern_mod_crate_map: RefCell::new(HashMap::new()),
used_crate_sources: RefCell::new(Vec::new()),
used_libraries: RefCell::new(Vec::new()),
used_link_args: RefCell::new(Vec::new()),
intr: intr
}
}
pub fn
|
(&self) -> ast::CrateNum {
self.metas.borrow().len() as ast::CrateNum + 1
}
pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc<crate_metadata> {
self.metas.borrow().get(&cnum).clone()
}
pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh {
let cdata = self.get_crate_data(cnum);
decoder::get_crate_hash(cdata.data())
}
pub fn set_crate_data(&self, cnum: ast::CrateNum, data: Rc<crate_metadata>) {
self.metas.borrow_mut().insert(cnum, data);
}
pub fn iter_crate_data(&self, i: |ast::CrateNum, &crate_metadata|) {
for (&k, v) in self.metas.borrow().iter() {
i(k, &**v);
}
}
pub fn add_used_crate_source(&self, src: CrateSource) {
let mut used_crate_sources = self.used_crate_sources.borrow_mut();
if!used_crate_sources.contains(&src) {
used_crate_sources.push(src);
}
}
pub fn get_used_crate_source(&self, cnum: ast::CrateNum)
-> Option<CrateSource> {
self.used_crate_sources.borrow_mut()
.iter().find(|source| source.cnum == cnum)
.map(|source| source.clone())
}
pub fn dump_phase_syntax_crates(&self) {
}
pub fn reset(&self) {
self.metas.borrow_mut().clear();
self.extern_mod_crate_map.borrow_mut().clear();
self.used_crate_sources.borrow_mut().clear();
self.used_libraries.borrow_mut().clear();
self.used_link_args.borrow_mut().clear();
}
// This method is used when generating the command line to pass through to
// system linker. The linker expects undefined symbols on the left of the
// command line to be defined in libraries on the right, not the other way
// around. For more info, see some comments in the add_used_library function
// below.
//
// In order to get this left-to-right dependency ordering, we perform a
// topological sort of all crates putting the leaves at the right-most
// positions.
pub fn get_used_crates(&self, prefer: LinkagePreference)
-> Vec<(ast::CrateNum, Option<Path>)> {
let mut ordering = Vec::new();
fn visit(cstore: &CStore, cnum: ast::CrateNum,
ordering: &mut Vec<ast::CrateNum>) {
if ordering.as_slice().contains(&cnum) { return }
let meta = cstore.get_crate_data(cnum);
for (_, &dep) in meta.cnum_map.iter() {
visit(cstore, dep, ordering);
}
ordering.push(cnum);
};
for (&num, _) in self.metas.borrow().iter() {
visit(self, num, &mut ordering);
}
ordering.as_mut_slice().reverse();
let ordering = ordering.as_slice();
let mut libs = self.used_crate_sources.borrow()
.iter()
.map(|src| (src.cnum, match prefer {
RequireDynamic => src.dylib.clone(),
RequireStatic => src.rlib.clone(),
}))
.collect::<Vec<(ast::CrateNum, Option<Path>)>>();
libs.sort_by(|&(a, _), &(b, _)| {
ordering.position_elem(&a).cmp(&ordering.position_elem(&b))
});
libs
}
pub fn add_used_library(&self, lib: ~str, kind: NativeLibaryKind) {
assert!(!lib.is_empty());
self.used_libraries.borrow_mut().push((lib, kind));
}
pub fn get_used_libraries<'a>(&'a self)
-> &'a RefCell<Vec<(~str, NativeLibaryKind)> > {
&self.used_libraries
}
pub fn add_used_link_args(&self, args: &str) {
for s in args.split(' ') {
self.used_link_args.borrow_mut().push(s.to_owned());
}
}
pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<~str> > {
&self.used_link_args
}
pub fn add_extern_mod_stmt_cnum(&self,
emod_id: ast::NodeId,
cnum: ast::CrateNum) {
self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum);
}
pub fn find_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId)
-> Option<ast::CrateNum> {
self.extern_mod_crate_map.borrow().find(&emod_id).map(|x| *x)
}
}
impl crate_metadata {
pub fn data<'a>(&'a self) -> &'a [u8] { self.data.as_slice() }
pub fn crate_id(&self) -> CrateId { decoder::get_crate_id(self.data()) }
pub fn hash(&self) -> Svh { decoder::get_crate_hash(self.data()) }
}
impl MetadataBlob {
pub fn as_slice<'a>(&'a self) -> &'a [u8] {
match *self {
MetadataVec(ref vec) => vec.as_slice(),
MetadataArchive(ref ar) => ar.as_slice(),
}
}
}
|
next_crate_num
|
identifier_name
|
cstore.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.
#![allow(non_camel_case_types)]
// The crate store - a central repo for information collected about external
// crates and libraries
use back::svh::Svh;
use metadata::decoder;
use metadata::loader;
use std::cell::RefCell;
use std::c_vec::CVec;
use std::rc::Rc;
use collections::HashMap;
use syntax::ast;
use syntax::crateid::CrateId;
use syntax::codemap::Span;
use syntax::parse::token::IdentInterner;
// A map from external crate numbers (as decoded from some crate file) to
// local crate numbers (as generated during this session). Each external
// crate may refer to types in other external crates, and each has their
// own crate numbers.
pub type cnum_map = HashMap<ast::CrateNum, ast::CrateNum>;
pub enum MetadataBlob {
MetadataVec(CVec<u8>),
MetadataArchive(loader::ArchiveMetadata),
}
pub struct crate_metadata {
pub name: ~str,
pub data: MetadataBlob,
pub cnum_map: cnum_map,
pub cnum: ast::CrateNum,
pub span: Span,
}
#[deriving(Eq)]
pub enum LinkagePreference {
RequireDynamic,
RequireStatic,
}
#[deriving(Eq, FromPrimitive)]
pub enum NativeLibaryKind {
NativeStatic, // native static library (.a archive)
NativeFramework, // OSX-specific
NativeUnknown, // default way to specify a dynamic library
}
// Where a crate came from on the local filesystem. One of these two options
// must be non-None.
#[deriving(Eq, Clone)]
pub struct CrateSource {
pub dylib: Option<Path>,
pub rlib: Option<Path>,
pub cnum: ast::CrateNum,
}
pub struct CStore {
metas: RefCell<HashMap<ast::CrateNum, Rc<crate_metadata>>>,
extern_mod_crate_map: RefCell<extern_mod_crate_map>,
used_crate_sources: RefCell<Vec<CrateSource>>,
used_libraries: RefCell<Vec<(~str, NativeLibaryKind)>>,
used_link_args: RefCell<Vec<~str>>,
pub intr: Rc<IdentInterner>,
}
// Map from NodeId's of local extern crate statements to crate numbers
type extern_mod_crate_map = HashMap<ast::NodeId, ast::CrateNum>;
impl CStore {
pub fn new(intr: Rc<IdentInterner>) -> CStore {
CStore {
metas: RefCell::new(HashMap::new()),
extern_mod_crate_map: RefCell::new(HashMap::new()),
used_crate_sources: RefCell::new(Vec::new()),
used_libraries: RefCell::new(Vec::new()),
used_link_args: RefCell::new(Vec::new()),
intr: intr
}
}
pub fn next_crate_num(&self) -> ast::CrateNum {
self.metas.borrow().len() as ast::CrateNum + 1
}
pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc<crate_metadata> {
self.metas.borrow().get(&cnum).clone()
}
pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh {
let cdata = self.get_crate_data(cnum);
decoder::get_crate_hash(cdata.data())
}
pub fn set_crate_data(&self, cnum: ast::CrateNum, data: Rc<crate_metadata>) {
self.metas.borrow_mut().insert(cnum, data);
}
pub fn iter_crate_data(&self, i: |ast::CrateNum, &crate_metadata|) {
for (&k, v) in self.metas.borrow().iter() {
i(k, &**v);
}
}
pub fn add_used_crate_source(&self, src: CrateSource) {
let mut used_crate_sources = self.used_crate_sources.borrow_mut();
if!used_crate_sources.contains(&src) {
used_crate_sources.push(src);
}
}
pub fn get_used_crate_source(&self, cnum: ast::CrateNum)
-> Option<CrateSource> {
self.used_crate_sources.borrow_mut()
.iter().find(|source| source.cnum == cnum)
.map(|source| source.clone())
}
pub fn dump_phase_syntax_crates(&self) {
}
pub fn reset(&self) {
self.metas.borrow_mut().clear();
self.extern_mod_crate_map.borrow_mut().clear();
self.used_crate_sources.borrow_mut().clear();
self.used_libraries.borrow_mut().clear();
self.used_link_args.borrow_mut().clear();
}
// This method is used when generating the command line to pass through to
// system linker. The linker expects undefined symbols on the left of the
// command line to be defined in libraries on the right, not the other way
// around. For more info, see some comments in the add_used_library function
// below.
//
// In order to get this left-to-right dependency ordering, we perform a
// topological sort of all crates putting the leaves at the right-most
// positions.
pub fn get_used_crates(&self, prefer: LinkagePreference)
-> Vec<(ast::CrateNum, Option<Path>)> {
let mut ordering = Vec::new();
fn visit(cstore: &CStore, cnum: ast::CrateNum,
ordering: &mut Vec<ast::CrateNum>) {
if ordering.as_slice().contains(&cnum) { return }
let meta = cstore.get_crate_data(cnum);
for (_, &dep) in meta.cnum_map.iter() {
visit(cstore, dep, ordering);
}
ordering.push(cnum);
};
for (&num, _) in self.metas.borrow().iter() {
visit(self, num, &mut ordering);
}
ordering.as_mut_slice().reverse();
let ordering = ordering.as_slice();
let mut libs = self.used_crate_sources.borrow()
.iter()
.map(|src| (src.cnum, match prefer {
RequireDynamic => src.dylib.clone(),
RequireStatic => src.rlib.clone(),
}))
.collect::<Vec<(ast::CrateNum, Option<Path>)>>();
libs.sort_by(|&(a, _), &(b, _)| {
ordering.position_elem(&a).cmp(&ordering.position_elem(&b))
});
libs
}
pub fn add_used_library(&self, lib: ~str, kind: NativeLibaryKind) {
assert!(!lib.is_empty());
self.used_libraries.borrow_mut().push((lib, kind));
}
pub fn get_used_libraries<'a>(&'a self)
-> &'a RefCell<Vec<(~str, NativeLibaryKind)> > {
&self.used_libraries
}
pub fn add_used_link_args(&self, args: &str) {
for s in args.split(' ') {
self.used_link_args.borrow_mut().push(s.to_owned());
}
}
pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<~str> > {
&self.used_link_args
}
pub fn add_extern_mod_stmt_cnum(&self,
|
pub fn find_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId)
-> Option<ast::CrateNum> {
self.extern_mod_crate_map.borrow().find(&emod_id).map(|x| *x)
}
}
impl crate_metadata {
pub fn data<'a>(&'a self) -> &'a [u8] { self.data.as_slice() }
pub fn crate_id(&self) -> CrateId { decoder::get_crate_id(self.data()) }
pub fn hash(&self) -> Svh { decoder::get_crate_hash(self.data()) }
}
impl MetadataBlob {
pub fn as_slice<'a>(&'a self) -> &'a [u8] {
match *self {
MetadataVec(ref vec) => vec.as_slice(),
MetadataArchive(ref ar) => ar.as_slice(),
}
}
}
|
emod_id: ast::NodeId,
cnum: ast::CrateNum) {
self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum);
}
|
random_line_split
|
preserve.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ----------------------------------------------------------------------
// Preserve(Ex, S) holds if ToAddr(Ex) will remain valid for the entirety of
// the scope S.
//
use core::prelude::*;
use middle::borrowck::{RootInfo, bckerr, bckerr_code, bckres, BorrowckCtxt};
use middle::borrowck::{err_mut_uniq, err_mut_variant};
use middle::borrowck::{err_out_of_root_scope, err_out_of_scope};
use middle::borrowck::{err_root_not_permitted, root_map_key};
use middle::mem_categorization::{cat_arg, cat_binding, cat_comp, cat_deref};
use middle::mem_categorization::{cat_discr, cat_local, cat_self, cat_special};
use middle::mem_categorization::{cat_stack_upvar, cmt, comp_field};
use middle::mem_categorization::{comp_index, comp_variant, gc_ptr};
use middle::mem_categorization::{region_ptr};
use middle::ty;
use util::common::indenter;
use syntax::ast;
pub enum PreserveCondition {
PcOk,
PcIfPure(bckerr)
}
pub impl PreserveCondition {
// combines two preservation conditions such that if either of
// them requires purity, the result requires purity
fn combine(&self, pc: PreserveCondition) -> PreserveCondition {
match *self {
PcOk => {pc}
PcIfPure(_) => {*self}
}
}
}
pub impl BorrowckCtxt {
fn preserve(&self,
cmt: cmt,
scope_region: ty::Region,
item_ub: ast::node_id,
root_ub: ast::node_id) -> bckres<PreserveCondition>
{
let ctxt = PreserveCtxt {
bccx: self,
scope_region: scope_region,
item_ub: item_ub,
root_ub: root_ub,
root_managed_data: true
};
ctxt.preserve(cmt)
}
}
struct PreserveCtxt<'self> {
bccx: &'self BorrowckCtxt,
// the region scope for which we must preserve the memory
scope_region: ty::Region,
// the scope for the body of the enclosing fn/method item
item_ub: ast::node_id,
// the upper bound on how long we can root an @T pointer
root_ub: ast::node_id,
// if false, do not attempt to root managed data
root_managed_data: bool
}
pub impl<'self> PreserveCtxt<'self> {
fn tcx(&self) -> ty::ctxt { self.bccx.tcx }
fn preserve(&self, cmt: cmt) -> bckres<PreserveCondition> {
debug!("preserve(cmt=%s, root_ub=%?, root_managed_data=%b)",
self.bccx.cmt_to_repr(cmt), self.root_ub,
self.root_managed_data);
let _i = indenter();
match cmt.cat {
cat_special(sk_implicit_self) |
cat_special(sk_heap_upvar) => {
self.compare_scope(cmt, ty::re_scope(self.item_ub))
}
cat_special(sk_static_item) | cat_special(sk_method) => {
Ok(PcOk)
}
cat_rvalue => {
// when we borrow an rvalue, we can keep it rooted but only
// up to the root_ub point
// When we're in a 'const &x =...' context, self.root_ub is
// zero and the rvalue is static, not bound to a scope.
let scope_region = if self.root_ub == 0 {
ty::re_static
} else {
// Maybe if we pass in the parent instead here,
// we can prevent the "scope not found" error
debug!("scope_region thing: %? ", cmt.id);
ty::re_scope(*self.tcx().region_map.get(&cmt.id))
};
self.compare_scope(cmt, scope_region)
}
cat_stack_upvar(cmt) => {
self.preserve(cmt)
}
cat_local(local_id) => {
// Normally, local variables are lendable, and so this
// case should never trigger. However, if we are
// preserving an expression like a.b where the field `b`
// has @ type, then it will recurse to ensure that the `a`
// is stable to try and avoid rooting the value `a.b`. In
// this case, root_managed_data will be false.
if self.root_managed_data {
self.tcx().sess.span_bug(
cmt.span,
~"preserve() called with local and!root_managed_data");
}
let local_scope_id = *self.tcx().region_map.get(&local_id);
self.compare_scope(cmt, ty::re_scope(local_scope_id))
}
cat_binding(local_id) => {
// Bindings are these kind of weird implicit pointers (cc
// #2329). We require (in gather_loans) that they be
// rooted in an immutable location.
let local_scope_id = *self.tcx().region_map.get(&local_id);
self.compare_scope(cmt, ty::re_scope(local_scope_id))
}
cat_arg(local_id) => {
// This can happen as not all args are lendable (e.g., &&
// modes). In that case, the caller guarantees stability
// for at least the scope of the fn. This is basically a
// deref of a region ptr.
let local_scope_id = *self.tcx().region_map.get(&local_id);
self.compare_scope(cmt, ty::re_scope(local_scope_id))
}
cat_self(local_id) => {
let local_scope_id = *self.tcx().region_map.get(&local_id);
self.compare_scope(cmt, ty::re_scope(local_scope_id))
}
cat_comp(cmt_base, comp_field(*)) |
cat_comp(cmt_base, comp_index(*)) |
cat_comp(cmt_base, comp_tuple) |
cat_comp(cmt_base, comp_anon_field) => {
// Most embedded components: if the base is stable, the
// type never changes.
self.preserve(cmt_base)
}
cat_comp(cmt_base, comp_variant(enum_did)) => {
if ty::enum_is_univariant(self.tcx(), enum_did) {
self.preserve(cmt_base)
} else {
// If there are multiple variants: overwriting the
// base could cause the type of this memory to change,
// so require imm.
self.require_imm(cmt, cmt_base, err_mut_variant)
}
}
cat_deref(cmt_base, _, uniq_ptr) => {
// Overwriting the base could cause this memory to be
// freed, so require imm.
self.require_imm(cmt, cmt_base, err_mut_uniq)
}
cat_deref(_, _, region_ptr(_, region)) => {
// References are always "stable" for lifetime `region` by
// induction (when the reference of type &MT was created,
// the memory must have been stable).
self.compare_scope(cmt, region)
}
cat_deref(_, _, unsafe_ptr) => {
// Unsafe pointers are the user's problem
Ok(PcOk)
}
cat_deref(base, derefs, gc_ptr(*)) => {
// GC'd pointers of type @MT: if this pointer lives in
// immutable, stable memory, then everything is fine. But
// otherwise we have no guarantee the pointer will stay
// live, so we must root the pointer (i.e., inc the ref
// count) for the duration of the loan.
debug!("base.mutbl = %?", base.mutbl);
if cmt.cat.derefs_through_mutable_box() {
self.attempt_root(cmt, base, derefs)
} else if base.mutbl.is_immutable() {
let non_rooting_ctxt = PreserveCtxt {
root_managed_data: false,
..*self
};
match non_rooting_ctxt.preserve(base) {
Ok(PcOk) => {
Ok(PcOk)
}
Ok(PcIfPure(_)) => {
debug!("must root @T, otherwise purity req'd");
self.attempt_root(cmt, base, derefs)
}
Err(ref e) => {
debug!("must root @T, err: %s",
self.bccx.bckerr_to_str((*e)));
self.attempt_root(cmt, base, derefs)
}
}
} else {
self.attempt_root(cmt, base, derefs)
}
}
cat_discr(base, match_id) => {
// Subtle: in a match, we must ensure that each binding
// variable remains valid for the duration of the arm in
// which it appears, presuming that this arm is taken.
// But it is inconvenient in trans to root something just
// for one arm. Therefore, we insert a cat_discr(),
// basically a special kind of category that says "if this
// value must be dynamically rooted, root it for the scope
// `match_id`.
//
// As an example, consider this scenario:
//
// let mut x = @Some(3);
// match *x { Some(y) {...} None {...} }
//
// Technically, the value `x` need only be rooted
// in the `some` arm. However, we evaluate `x` in trans
// before we know what arm will be taken, so we just
// always root it for the duration of the match.
//
// As a second example, consider *this* scenario:
//
// let x = @mut @Some(3);
// match x { @@Some(y) {...} @@None {...} }
//
// Here again, `x` need only be rooted in the `some` arm.
// In this case, the value which needs to be rooted is
// found only when checking which pattern matches: but
// this check is done before entering the arm. Therefore,
// even in this case we just choose to keep the value
// rooted for the entire match. This means the value will be
// rooted even if the none arm is taken. Oh well.
//
// At first, I tried to optimize the second case to only
// root in one arm, but the result was suboptimal: first,
// it interfered with the construction of phi nodes in the
// arm, as we were adding code to root values before the
// phi nodes were added. This could have been addressed
// with a second basic block. However, the naive approach
// also yielded suboptimal results for patterns like:
//
// let x = @mut @...;
// match x { @@some_variant(y) | @@some_other_variant(y) =>
//
// The reason is that we would root the value once for
// each pattern and not once per arm. This is also easily
// fixed, but it's yet more code for what is really quite
// the corner case.
//
// Nonetheless, if you decide to optimize this case in the
// future, you need only adjust where the cat_discr()
// node appears to draw the line between what will be rooted
// in the *arm* vs the *match*.
let match_rooting_ctxt = PreserveCtxt {
scope_region: ty::re_scope(match_id),
..*self
};
match_rooting_ctxt.preserve(base)
}
}
}
/// Reqiures that `cmt` (which is a deref or subcomponent of
/// `base`) be found in an immutable location (that is, `base`
/// must be immutable). Also requires that `base` itself is
/// preserved.
fn require_imm(&self,
cmt: cmt,
cmt_base: cmt,
code: bckerr_code) -> bckres<PreserveCondition> {
// Variant contents and unique pointers: must be immutably
// rooted to a preserved address.
match self.preserve(cmt_base) {
// the base is preserved, but if we are not mutable then
// purity is required
Ok(PcOk) => {
if!cmt_base.mutbl.is_immutable() {
Ok(PcIfPure(bckerr {cmt:cmt, code:code}))
} else {
Ok(PcOk)
}
}
// the base requires purity too, that's fine
Ok(PcIfPure(ref e)) => {
Ok(PcIfPure((*e)))
}
// base is not stable, doesn't matter
Err(ref e) => {
Err((*e))
}
}
}
/// Checks that the scope for which the value must be preserved
/// is a subscope of `scope_ub`; if so, success.
fn compare_scope(&self,
cmt: cmt,
scope_ub: ty::Region) -> bckres<PreserveCondition> {
if self.bccx.is_subregion_of(self.scope_region, scope_ub) {
Ok(PcOk)
} else {
Err(bckerr {
cmt:cmt,
code:err_out_of_scope(scope_ub, self.scope_region)
})
}
}
/// Here, `cmt=*base` is always a deref of managed data (if
/// `derefs`!= 0, then an auto-deref). This routine determines
/// whether it is safe to MAKE cmt stable by rooting the pointer
/// `base`. We can only do the dynamic root if the desired
/// lifetime `self.scope_region` is a subset of `self.root_ub`
/// scope; otherwise, it would either require that we hold the
/// value live for longer than the current fn or else potentially
/// require that an statically unbounded number of values be
/// rooted (if a loop exists).
fn
|
(&self, cmt: cmt, base: cmt,
derefs: uint) -> bckres<PreserveCondition> {
if!self.root_managed_data {
// normally, there is a root_ub; the only time that this
// is none is when a boxed value is stored in an immutable
// location. In that case, we will test to see if that
// immutable location itself can be preserved long enough
// in which case no rooting is necessary. But there it
// would be sort of pointless to avoid rooting the inner
// box by rooting an outer box, as it would just keep more
// memory live than necessary, so we set root_ub to none.
return Err(bckerr { cmt: cmt, code: err_root_not_permitted });
}
let root_region = ty::re_scope(self.root_ub);
match self.scope_region {
// we can only root values if the desired region is some concrete
// scope within the fn body
ty::re_scope(scope_id) => {
debug!("Considering root map entry for %s: \
node %d:%u -> scope_id %?, root_ub %?",
self.bccx.cmt_to_repr(cmt), base.id,
derefs, scope_id, self.root_ub);
if self.bccx.is_subregion_of(self.scope_region, root_region) {
debug!("Elected to root");
let rk = root_map_key { id: base.id, derefs: derefs };
// This code could potentially lead cause boxes to be frozen
// for longer than necessarily at runtime. It prevents an
// ICE in trans; the fundamental problem is that it's hard
// to make sure trans and borrowck have the same notion of
// scope. The real fix is to clean up how trans handles
// cleanups, but that's hard. If this becomes an issue, it's
// an option to just change this to `let scope_to_use =
// scope_id;`. Though that would potentially re-introduce
// the ICE. See #3511 for more details.
let scope_to_use = if
self.bccx.stmt_map.contains(&scope_id) {
// Root it in its parent scope, b/c
// trans won't introduce a new scope for the
// stmt
self.root_ub
}
else {
// Use the more precise scope
scope_id
};
// We freeze if and only if this is a *mutable* @ box that
// we're borrowing into a pointer.
self.bccx.root_map.insert(rk, RootInfo {
scope: scope_to_use,
freezes: cmt.cat.derefs_through_mutable_box()
});
return Ok(PcOk);
} else {
debug!("Unable to root");
return Err(bckerr {
cmt: cmt,
code: err_out_of_root_scope(root_region,
self.scope_region)
});
}
}
// we won't be able to root long enough
_ => {
return Err(bckerr {
cmt:cmt,
code:err_out_of_root_scope(root_region, self.scope_region)
});
}
}
}
}
|
attempt_root
|
identifier_name
|
preserve.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ----------------------------------------------------------------------
// Preserve(Ex, S) holds if ToAddr(Ex) will remain valid for the entirety of
// the scope S.
//
use core::prelude::*;
use middle::borrowck::{RootInfo, bckerr, bckerr_code, bckres, BorrowckCtxt};
use middle::borrowck::{err_mut_uniq, err_mut_variant};
use middle::borrowck::{err_out_of_root_scope, err_out_of_scope};
use middle::borrowck::{err_root_not_permitted, root_map_key};
use middle::mem_categorization::{cat_arg, cat_binding, cat_comp, cat_deref};
use middle::mem_categorization::{cat_discr, cat_local, cat_self, cat_special};
use middle::mem_categorization::{cat_stack_upvar, cmt, comp_field};
use middle::mem_categorization::{comp_index, comp_variant, gc_ptr};
use middle::mem_categorization::{region_ptr};
use middle::ty;
use util::common::indenter;
use syntax::ast;
pub enum PreserveCondition {
PcOk,
PcIfPure(bckerr)
}
pub impl PreserveCondition {
// combines two preservation conditions such that if either of
// them requires purity, the result requires purity
fn combine(&self, pc: PreserveCondition) -> PreserveCondition {
match *self {
PcOk => {pc}
PcIfPure(_) => {*self}
}
}
}
pub impl BorrowckCtxt {
fn preserve(&self,
cmt: cmt,
scope_region: ty::Region,
item_ub: ast::node_id,
root_ub: ast::node_id) -> bckres<PreserveCondition>
{
let ctxt = PreserveCtxt {
bccx: self,
scope_region: scope_region,
item_ub: item_ub,
root_ub: root_ub,
root_managed_data: true
};
ctxt.preserve(cmt)
}
}
struct PreserveCtxt<'self> {
bccx: &'self BorrowckCtxt,
// the region scope for which we must preserve the memory
scope_region: ty::Region,
// the scope for the body of the enclosing fn/method item
item_ub: ast::node_id,
// the upper bound on how long we can root an @T pointer
root_ub: ast::node_id,
// if false, do not attempt to root managed data
root_managed_data: bool
}
pub impl<'self> PreserveCtxt<'self> {
fn tcx(&self) -> ty::ctxt { self.bccx.tcx }
fn preserve(&self, cmt: cmt) -> bckres<PreserveCondition> {
debug!("preserve(cmt=%s, root_ub=%?, root_managed_data=%b)",
self.bccx.cmt_to_repr(cmt), self.root_ub,
self.root_managed_data);
let _i = indenter();
match cmt.cat {
cat_special(sk_implicit_self) |
cat_special(sk_heap_upvar) => {
self.compare_scope(cmt, ty::re_scope(self.item_ub))
}
cat_special(sk_static_item) | cat_special(sk_method) => {
Ok(PcOk)
}
cat_rvalue => {
// when we borrow an rvalue, we can keep it rooted but only
// up to the root_ub point
// When we're in a 'const &x =...' context, self.root_ub is
// zero and the rvalue is static, not bound to a scope.
let scope_region = if self.root_ub == 0 {
ty::re_static
} else {
// Maybe if we pass in the parent instead here,
// we can prevent the "scope not found" error
debug!("scope_region thing: %? ", cmt.id);
ty::re_scope(*self.tcx().region_map.get(&cmt.id))
};
self.compare_scope(cmt, scope_region)
}
cat_stack_upvar(cmt) => {
self.preserve(cmt)
}
cat_local(local_id) => {
// Normally, local variables are lendable, and so this
// case should never trigger. However, if we are
// preserving an expression like a.b where the field `b`
// has @ type, then it will recurse to ensure that the `a`
// is stable to try and avoid rooting the value `a.b`. In
// this case, root_managed_data will be false.
if self.root_managed_data {
self.tcx().sess.span_bug(
cmt.span,
~"preserve() called with local and!root_managed_data");
}
let local_scope_id = *self.tcx().region_map.get(&local_id);
self.compare_scope(cmt, ty::re_scope(local_scope_id))
}
cat_binding(local_id) => {
// Bindings are these kind of weird implicit pointers (cc
// #2329). We require (in gather_loans) that they be
// rooted in an immutable location.
let local_scope_id = *self.tcx().region_map.get(&local_id);
self.compare_scope(cmt, ty::re_scope(local_scope_id))
}
cat_arg(local_id) => {
// This can happen as not all args are lendable (e.g., &&
// modes). In that case, the caller guarantees stability
// for at least the scope of the fn. This is basically a
// deref of a region ptr.
let local_scope_id = *self.tcx().region_map.get(&local_id);
self.compare_scope(cmt, ty::re_scope(local_scope_id))
}
cat_self(local_id) => {
let local_scope_id = *self.tcx().region_map.get(&local_id);
self.compare_scope(cmt, ty::re_scope(local_scope_id))
}
cat_comp(cmt_base, comp_field(*)) |
cat_comp(cmt_base, comp_index(*)) |
cat_comp(cmt_base, comp_tuple) |
cat_comp(cmt_base, comp_anon_field) => {
// Most embedded components: if the base is stable, the
// type never changes.
self.preserve(cmt_base)
}
cat_comp(cmt_base, comp_variant(enum_did)) => {
if ty::enum_is_univariant(self.tcx(), enum_did) {
self.preserve(cmt_base)
} else {
// If there are multiple variants: overwriting the
// base could cause the type of this memory to change,
// so require imm.
self.require_imm(cmt, cmt_base, err_mut_variant)
}
}
cat_deref(cmt_base, _, uniq_ptr) => {
// Overwriting the base could cause this memory to be
// freed, so require imm.
self.require_imm(cmt, cmt_base, err_mut_uniq)
}
cat_deref(_, _, region_ptr(_, region)) => {
// References are always "stable" for lifetime `region` by
// induction (when the reference of type &MT was created,
// the memory must have been stable).
self.compare_scope(cmt, region)
}
cat_deref(_, _, unsafe_ptr) => {
// Unsafe pointers are the user's problem
Ok(PcOk)
}
cat_deref(base, derefs, gc_ptr(*)) => {
// GC'd pointers of type @MT: if this pointer lives in
// immutable, stable memory, then everything is fine. But
// otherwise we have no guarantee the pointer will stay
// live, so we must root the pointer (i.e., inc the ref
// count) for the duration of the loan.
debug!("base.mutbl = %?", base.mutbl);
if cmt.cat.derefs_through_mutable_box() {
self.attempt_root(cmt, base, derefs)
} else if base.mutbl.is_immutable() {
let non_rooting_ctxt = PreserveCtxt {
root_managed_data: false,
..*self
};
match non_rooting_ctxt.preserve(base) {
Ok(PcOk) => {
Ok(PcOk)
}
Ok(PcIfPure(_)) => {
debug!("must root @T, otherwise purity req'd");
self.attempt_root(cmt, base, derefs)
}
Err(ref e) => {
debug!("must root @T, err: %s",
self.bccx.bckerr_to_str((*e)));
self.attempt_root(cmt, base, derefs)
}
}
} else {
self.attempt_root(cmt, base, derefs)
}
}
cat_discr(base, match_id) => {
// Subtle: in a match, we must ensure that each binding
// variable remains valid for the duration of the arm in
// which it appears, presuming that this arm is taken.
// But it is inconvenient in trans to root something just
// for one arm. Therefore, we insert a cat_discr(),
// basically a special kind of category that says "if this
// value must be dynamically rooted, root it for the scope
// `match_id`.
//
// As an example, consider this scenario:
//
// let mut x = @Some(3);
// match *x { Some(y) {...} None {...} }
//
// Technically, the value `x` need only be rooted
// in the `some` arm. However, we evaluate `x` in trans
// before we know what arm will be taken, so we just
// always root it for the duration of the match.
//
// As a second example, consider *this* scenario:
//
// let x = @mut @Some(3);
// match x { @@Some(y) {...} @@None {...} }
//
// Here again, `x` need only be rooted in the `some` arm.
// In this case, the value which needs to be rooted is
// found only when checking which pattern matches: but
// this check is done before entering the arm. Therefore,
// even in this case we just choose to keep the value
// rooted for the entire match. This means the value will be
// rooted even if the none arm is taken. Oh well.
//
// At first, I tried to optimize the second case to only
// root in one arm, but the result was suboptimal: first,
// it interfered with the construction of phi nodes in the
// arm, as we were adding code to root values before the
// phi nodes were added. This could have been addressed
// with a second basic block. However, the naive approach
// also yielded suboptimal results for patterns like:
//
// let x = @mut @...;
// match x { @@some_variant(y) | @@some_other_variant(y) =>
//
// The reason is that we would root the value once for
// each pattern and not once per arm. This is also easily
// fixed, but it's yet more code for what is really quite
// the corner case.
//
// Nonetheless, if you decide to optimize this case in the
// future, you need only adjust where the cat_discr()
// node appears to draw the line between what will be rooted
// in the *arm* vs the *match*.
let match_rooting_ctxt = PreserveCtxt {
scope_region: ty::re_scope(match_id),
..*self
};
match_rooting_ctxt.preserve(base)
}
}
}
/// Reqiures that `cmt` (which is a deref or subcomponent of
/// `base`) be found in an immutable location (that is, `base`
/// must be immutable). Also requires that `base` itself is
/// preserved.
fn require_imm(&self,
cmt: cmt,
cmt_base: cmt,
code: bckerr_code) -> bckres<PreserveCondition> {
// Variant contents and unique pointers: must be immutably
// rooted to a preserved address.
match self.preserve(cmt_base) {
// the base is preserved, but if we are not mutable then
// purity is required
Ok(PcOk) => {
if!cmt_base.mutbl.is_immutable() {
Ok(PcIfPure(bckerr {cmt:cmt, code:code}))
} else {
Ok(PcOk)
}
}
// the base requires purity too, that's fine
Ok(PcIfPure(ref e)) => {
Ok(PcIfPure((*e)))
}
// base is not stable, doesn't matter
Err(ref e) => {
Err((*e))
}
}
}
/// Checks that the scope for which the value must be preserved
/// is a subscope of `scope_ub`; if so, success.
fn compare_scope(&self,
cmt: cmt,
scope_ub: ty::Region) -> bckres<PreserveCondition>
|
/// Here, `cmt=*base` is always a deref of managed data (if
/// `derefs`!= 0, then an auto-deref). This routine determines
/// whether it is safe to MAKE cmt stable by rooting the pointer
/// `base`. We can only do the dynamic root if the desired
/// lifetime `self.scope_region` is a subset of `self.root_ub`
/// scope; otherwise, it would either require that we hold the
/// value live for longer than the current fn or else potentially
/// require that an statically unbounded number of values be
/// rooted (if a loop exists).
fn attempt_root(&self, cmt: cmt, base: cmt,
derefs: uint) -> bckres<PreserveCondition> {
if!self.root_managed_data {
// normally, there is a root_ub; the only time that this
// is none is when a boxed value is stored in an immutable
// location. In that case, we will test to see if that
// immutable location itself can be preserved long enough
// in which case no rooting is necessary. But there it
// would be sort of pointless to avoid rooting the inner
// box by rooting an outer box, as it would just keep more
// memory live than necessary, so we set root_ub to none.
return Err(bckerr { cmt: cmt, code: err_root_not_permitted });
}
let root_region = ty::re_scope(self.root_ub);
match self.scope_region {
// we can only root values if the desired region is some concrete
// scope within the fn body
ty::re_scope(scope_id) => {
debug!("Considering root map entry for %s: \
node %d:%u -> scope_id %?, root_ub %?",
self.bccx.cmt_to_repr(cmt), base.id,
derefs, scope_id, self.root_ub);
if self.bccx.is_subregion_of(self.scope_region, root_region) {
debug!("Elected to root");
let rk = root_map_key { id: base.id, derefs: derefs };
// This code could potentially lead cause boxes to be frozen
// for longer than necessarily at runtime. It prevents an
// ICE in trans; the fundamental problem is that it's hard
// to make sure trans and borrowck have the same notion of
// scope. The real fix is to clean up how trans handles
// cleanups, but that's hard. If this becomes an issue, it's
// an option to just change this to `let scope_to_use =
// scope_id;`. Though that would potentially re-introduce
// the ICE. See #3511 for more details.
let scope_to_use = if
self.bccx.stmt_map.contains(&scope_id) {
// Root it in its parent scope, b/c
// trans won't introduce a new scope for the
// stmt
self.root_ub
}
else {
// Use the more precise scope
scope_id
};
// We freeze if and only if this is a *mutable* @ box that
// we're borrowing into a pointer.
self.bccx.root_map.insert(rk, RootInfo {
scope: scope_to_use,
freezes: cmt.cat.derefs_through_mutable_box()
});
return Ok(PcOk);
} else {
debug!("Unable to root");
return Err(bckerr {
cmt: cmt,
code: err_out_of_root_scope(root_region,
self.scope_region)
});
}
}
// we won't be able to root long enough
_ => {
return Err(bckerr {
cmt:cmt,
code:err_out_of_root_scope(root_region, self.scope_region)
});
}
}
}
}
|
{
if self.bccx.is_subregion_of(self.scope_region, scope_ub) {
Ok(PcOk)
} else {
Err(bckerr {
cmt:cmt,
code:err_out_of_scope(scope_ub, self.scope_region)
})
}
}
|
identifier_body
|
preserve.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ----------------------------------------------------------------------
// Preserve(Ex, S) holds if ToAddr(Ex) will remain valid for the entirety of
// the scope S.
//
use core::prelude::*;
use middle::borrowck::{RootInfo, bckerr, bckerr_code, bckres, BorrowckCtxt};
use middle::borrowck::{err_mut_uniq, err_mut_variant};
use middle::borrowck::{err_out_of_root_scope, err_out_of_scope};
use middle::borrowck::{err_root_not_permitted, root_map_key};
use middle::mem_categorization::{cat_arg, cat_binding, cat_comp, cat_deref};
use middle::mem_categorization::{cat_discr, cat_local, cat_self, cat_special};
use middle::mem_categorization::{cat_stack_upvar, cmt, comp_field};
use middle::mem_categorization::{comp_index, comp_variant, gc_ptr};
use middle::mem_categorization::{region_ptr};
use middle::ty;
use util::common::indenter;
use syntax::ast;
pub enum PreserveCondition {
PcOk,
PcIfPure(bckerr)
}
pub impl PreserveCondition {
// combines two preservation conditions such that if either of
// them requires purity, the result requires purity
fn combine(&self, pc: PreserveCondition) -> PreserveCondition {
match *self {
PcOk => {pc}
PcIfPure(_) => {*self}
}
}
}
pub impl BorrowckCtxt {
fn preserve(&self,
cmt: cmt,
scope_region: ty::Region,
item_ub: ast::node_id,
root_ub: ast::node_id) -> bckres<PreserveCondition>
{
let ctxt = PreserveCtxt {
bccx: self,
scope_region: scope_region,
item_ub: item_ub,
root_ub: root_ub,
root_managed_data: true
};
ctxt.preserve(cmt)
}
}
struct PreserveCtxt<'self> {
bccx: &'self BorrowckCtxt,
// the region scope for which we must preserve the memory
scope_region: ty::Region,
// the scope for the body of the enclosing fn/method item
item_ub: ast::node_id,
// the upper bound on how long we can root an @T pointer
root_ub: ast::node_id,
// if false, do not attempt to root managed data
root_managed_data: bool
}
pub impl<'self> PreserveCtxt<'self> {
fn tcx(&self) -> ty::ctxt { self.bccx.tcx }
fn preserve(&self, cmt: cmt) -> bckres<PreserveCondition> {
debug!("preserve(cmt=%s, root_ub=%?, root_managed_data=%b)",
self.bccx.cmt_to_repr(cmt), self.root_ub,
self.root_managed_data);
let _i = indenter();
match cmt.cat {
cat_special(sk_implicit_self) |
cat_special(sk_heap_upvar) => {
self.compare_scope(cmt, ty::re_scope(self.item_ub))
}
cat_special(sk_static_item) | cat_special(sk_method) => {
Ok(PcOk)
}
cat_rvalue => {
// when we borrow an rvalue, we can keep it rooted but only
// up to the root_ub point
// When we're in a 'const &x =...' context, self.root_ub is
// zero and the rvalue is static, not bound to a scope.
let scope_region = if self.root_ub == 0 {
ty::re_static
} else {
// Maybe if we pass in the parent instead here,
// we can prevent the "scope not found" error
debug!("scope_region thing: %? ", cmt.id);
ty::re_scope(*self.tcx().region_map.get(&cmt.id))
};
self.compare_scope(cmt, scope_region)
}
cat_stack_upvar(cmt) => {
self.preserve(cmt)
}
cat_local(local_id) => {
// Normally, local variables are lendable, and so this
// case should never trigger. However, if we are
// preserving an expression like a.b where the field `b`
// has @ type, then it will recurse to ensure that the `a`
// is stable to try and avoid rooting the value `a.b`. In
// this case, root_managed_data will be false.
if self.root_managed_data {
self.tcx().sess.span_bug(
cmt.span,
~"preserve() called with local and!root_managed_data");
}
let local_scope_id = *self.tcx().region_map.get(&local_id);
self.compare_scope(cmt, ty::re_scope(local_scope_id))
}
cat_binding(local_id) => {
// Bindings are these kind of weird implicit pointers (cc
// #2329). We require (in gather_loans) that they be
// rooted in an immutable location.
let local_scope_id = *self.tcx().region_map.get(&local_id);
self.compare_scope(cmt, ty::re_scope(local_scope_id))
}
cat_arg(local_id) => {
// This can happen as not all args are lendable (e.g., &&
// modes). In that case, the caller guarantees stability
// for at least the scope of the fn. This is basically a
// deref of a region ptr.
let local_scope_id = *self.tcx().region_map.get(&local_id);
self.compare_scope(cmt, ty::re_scope(local_scope_id))
}
cat_self(local_id) => {
let local_scope_id = *self.tcx().region_map.get(&local_id);
self.compare_scope(cmt, ty::re_scope(local_scope_id))
}
cat_comp(cmt_base, comp_field(*)) |
cat_comp(cmt_base, comp_index(*)) |
cat_comp(cmt_base, comp_tuple) |
cat_comp(cmt_base, comp_anon_field) => {
// Most embedded components: if the base is stable, the
// type never changes.
self.preserve(cmt_base)
}
cat_comp(cmt_base, comp_variant(enum_did)) => {
if ty::enum_is_univariant(self.tcx(), enum_did) {
self.preserve(cmt_base)
} else {
// If there are multiple variants: overwriting the
// base could cause the type of this memory to change,
// so require imm.
self.require_imm(cmt, cmt_base, err_mut_variant)
}
}
cat_deref(cmt_base, _, uniq_ptr) => {
// Overwriting the base could cause this memory to be
// freed, so require imm.
self.require_imm(cmt, cmt_base, err_mut_uniq)
}
cat_deref(_, _, region_ptr(_, region)) => {
// References are always "stable" for lifetime `region` by
// induction (when the reference of type &MT was created,
// the memory must have been stable).
self.compare_scope(cmt, region)
}
cat_deref(_, _, unsafe_ptr) => {
// Unsafe pointers are the user's problem
Ok(PcOk)
}
cat_deref(base, derefs, gc_ptr(*)) => {
// GC'd pointers of type @MT: if this pointer lives in
// immutable, stable memory, then everything is fine. But
// otherwise we have no guarantee the pointer will stay
// live, so we must root the pointer (i.e., inc the ref
// count) for the duration of the loan.
debug!("base.mutbl = %?", base.mutbl);
if cmt.cat.derefs_through_mutable_box() {
self.attempt_root(cmt, base, derefs)
} else if base.mutbl.is_immutable() {
let non_rooting_ctxt = PreserveCtxt {
root_managed_data: false,
..*self
};
match non_rooting_ctxt.preserve(base) {
Ok(PcOk) => {
Ok(PcOk)
}
Ok(PcIfPure(_)) => {
debug!("must root @T, otherwise purity req'd");
self.attempt_root(cmt, base, derefs)
}
Err(ref e) => {
debug!("must root @T, err: %s",
self.bccx.bckerr_to_str((*e)));
self.attempt_root(cmt, base, derefs)
}
}
} else {
self.attempt_root(cmt, base, derefs)
}
}
cat_discr(base, match_id) => {
// Subtle: in a match, we must ensure that each binding
// variable remains valid for the duration of the arm in
// which it appears, presuming that this arm is taken.
// But it is inconvenient in trans to root something just
// for one arm. Therefore, we insert a cat_discr(),
// basically a special kind of category that says "if this
// value must be dynamically rooted, root it for the scope
// `match_id`.
//
// As an example, consider this scenario:
//
// let mut x = @Some(3);
// match *x { Some(y) {...} None {...} }
//
// Technically, the value `x` need only be rooted
// in the `some` arm. However, we evaluate `x` in trans
// before we know what arm will be taken, so we just
// always root it for the duration of the match.
//
// As a second example, consider *this* scenario:
//
// let x = @mut @Some(3);
// match x { @@Some(y) {...} @@None {...} }
//
// Here again, `x` need only be rooted in the `some` arm.
// In this case, the value which needs to be rooted is
// found only when checking which pattern matches: but
// this check is done before entering the arm. Therefore,
// even in this case we just choose to keep the value
// rooted for the entire match. This means the value will be
// rooted even if the none arm is taken. Oh well.
//
// At first, I tried to optimize the second case to only
// root in one arm, but the result was suboptimal: first,
// it interfered with the construction of phi nodes in the
// arm, as we were adding code to root values before the
// phi nodes were added. This could have been addressed
// with a second basic block. However, the naive approach
// also yielded suboptimal results for patterns like:
//
// let x = @mut @...;
// match x { @@some_variant(y) | @@some_other_variant(y) =>
//
// The reason is that we would root the value once for
// each pattern and not once per arm. This is also easily
// fixed, but it's yet more code for what is really quite
|
// the corner case.
//
// Nonetheless, if you decide to optimize this case in the
// future, you need only adjust where the cat_discr()
// node appears to draw the line between what will be rooted
// in the *arm* vs the *match*.
let match_rooting_ctxt = PreserveCtxt {
scope_region: ty::re_scope(match_id),
..*self
};
match_rooting_ctxt.preserve(base)
}
}
}
/// Reqiures that `cmt` (which is a deref or subcomponent of
/// `base`) be found in an immutable location (that is, `base`
/// must be immutable). Also requires that `base` itself is
/// preserved.
fn require_imm(&self,
cmt: cmt,
cmt_base: cmt,
code: bckerr_code) -> bckres<PreserveCondition> {
// Variant contents and unique pointers: must be immutably
// rooted to a preserved address.
match self.preserve(cmt_base) {
// the base is preserved, but if we are not mutable then
// purity is required
Ok(PcOk) => {
if!cmt_base.mutbl.is_immutable() {
Ok(PcIfPure(bckerr {cmt:cmt, code:code}))
} else {
Ok(PcOk)
}
}
// the base requires purity too, that's fine
Ok(PcIfPure(ref e)) => {
Ok(PcIfPure((*e)))
}
// base is not stable, doesn't matter
Err(ref e) => {
Err((*e))
}
}
}
/// Checks that the scope for which the value must be preserved
/// is a subscope of `scope_ub`; if so, success.
fn compare_scope(&self,
cmt: cmt,
scope_ub: ty::Region) -> bckres<PreserveCondition> {
if self.bccx.is_subregion_of(self.scope_region, scope_ub) {
Ok(PcOk)
} else {
Err(bckerr {
cmt:cmt,
code:err_out_of_scope(scope_ub, self.scope_region)
})
}
}
/// Here, `cmt=*base` is always a deref of managed data (if
/// `derefs`!= 0, then an auto-deref). This routine determines
/// whether it is safe to MAKE cmt stable by rooting the pointer
/// `base`. We can only do the dynamic root if the desired
/// lifetime `self.scope_region` is a subset of `self.root_ub`
/// scope; otherwise, it would either require that we hold the
/// value live for longer than the current fn or else potentially
/// require that an statically unbounded number of values be
/// rooted (if a loop exists).
fn attempt_root(&self, cmt: cmt, base: cmt,
derefs: uint) -> bckres<PreserveCondition> {
if!self.root_managed_data {
// normally, there is a root_ub; the only time that this
// is none is when a boxed value is stored in an immutable
// location. In that case, we will test to see if that
// immutable location itself can be preserved long enough
// in which case no rooting is necessary. But there it
// would be sort of pointless to avoid rooting the inner
// box by rooting an outer box, as it would just keep more
// memory live than necessary, so we set root_ub to none.
return Err(bckerr { cmt: cmt, code: err_root_not_permitted });
}
let root_region = ty::re_scope(self.root_ub);
match self.scope_region {
// we can only root values if the desired region is some concrete
// scope within the fn body
ty::re_scope(scope_id) => {
debug!("Considering root map entry for %s: \
node %d:%u -> scope_id %?, root_ub %?",
self.bccx.cmt_to_repr(cmt), base.id,
derefs, scope_id, self.root_ub);
if self.bccx.is_subregion_of(self.scope_region, root_region) {
debug!("Elected to root");
let rk = root_map_key { id: base.id, derefs: derefs };
// This code could potentially lead cause boxes to be frozen
// for longer than necessarily at runtime. It prevents an
// ICE in trans; the fundamental problem is that it's hard
// to make sure trans and borrowck have the same notion of
// scope. The real fix is to clean up how trans handles
// cleanups, but that's hard. If this becomes an issue, it's
// an option to just change this to `let scope_to_use =
// scope_id;`. Though that would potentially re-introduce
// the ICE. See #3511 for more details.
let scope_to_use = if
self.bccx.stmt_map.contains(&scope_id) {
// Root it in its parent scope, b/c
// trans won't introduce a new scope for the
// stmt
self.root_ub
}
else {
// Use the more precise scope
scope_id
};
// We freeze if and only if this is a *mutable* @ box that
// we're borrowing into a pointer.
self.bccx.root_map.insert(rk, RootInfo {
scope: scope_to_use,
freezes: cmt.cat.derefs_through_mutable_box()
});
return Ok(PcOk);
} else {
debug!("Unable to root");
return Err(bckerr {
cmt: cmt,
code: err_out_of_root_scope(root_region,
self.scope_region)
});
}
}
// we won't be able to root long enough
_ => {
return Err(bckerr {
cmt:cmt,
code:err_out_of_root_scope(root_region, self.scope_region)
});
}
}
}
}
|
random_line_split
|
|
preserve.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ----------------------------------------------------------------------
// Preserve(Ex, S) holds if ToAddr(Ex) will remain valid for the entirety of
// the scope S.
//
use core::prelude::*;
use middle::borrowck::{RootInfo, bckerr, bckerr_code, bckres, BorrowckCtxt};
use middle::borrowck::{err_mut_uniq, err_mut_variant};
use middle::borrowck::{err_out_of_root_scope, err_out_of_scope};
use middle::borrowck::{err_root_not_permitted, root_map_key};
use middle::mem_categorization::{cat_arg, cat_binding, cat_comp, cat_deref};
use middle::mem_categorization::{cat_discr, cat_local, cat_self, cat_special};
use middle::mem_categorization::{cat_stack_upvar, cmt, comp_field};
use middle::mem_categorization::{comp_index, comp_variant, gc_ptr};
use middle::mem_categorization::{region_ptr};
use middle::ty;
use util::common::indenter;
use syntax::ast;
pub enum PreserveCondition {
PcOk,
PcIfPure(bckerr)
}
pub impl PreserveCondition {
// combines two preservation conditions such that if either of
// them requires purity, the result requires purity
fn combine(&self, pc: PreserveCondition) -> PreserveCondition {
match *self {
PcOk => {pc}
PcIfPure(_) => {*self}
}
}
}
pub impl BorrowckCtxt {
fn preserve(&self,
cmt: cmt,
scope_region: ty::Region,
item_ub: ast::node_id,
root_ub: ast::node_id) -> bckres<PreserveCondition>
{
let ctxt = PreserveCtxt {
bccx: self,
scope_region: scope_region,
item_ub: item_ub,
root_ub: root_ub,
root_managed_data: true
};
ctxt.preserve(cmt)
}
}
struct PreserveCtxt<'self> {
bccx: &'self BorrowckCtxt,
// the region scope for which we must preserve the memory
scope_region: ty::Region,
// the scope for the body of the enclosing fn/method item
item_ub: ast::node_id,
// the upper bound on how long we can root an @T pointer
root_ub: ast::node_id,
// if false, do not attempt to root managed data
root_managed_data: bool
}
pub impl<'self> PreserveCtxt<'self> {
fn tcx(&self) -> ty::ctxt { self.bccx.tcx }
fn preserve(&self, cmt: cmt) -> bckres<PreserveCondition> {
debug!("preserve(cmt=%s, root_ub=%?, root_managed_data=%b)",
self.bccx.cmt_to_repr(cmt), self.root_ub,
self.root_managed_data);
let _i = indenter();
match cmt.cat {
cat_special(sk_implicit_self) |
cat_special(sk_heap_upvar) => {
self.compare_scope(cmt, ty::re_scope(self.item_ub))
}
cat_special(sk_static_item) | cat_special(sk_method) => {
Ok(PcOk)
}
cat_rvalue => {
// when we borrow an rvalue, we can keep it rooted but only
// up to the root_ub point
// When we're in a 'const &x =...' context, self.root_ub is
// zero and the rvalue is static, not bound to a scope.
let scope_region = if self.root_ub == 0 {
ty::re_static
} else {
// Maybe if we pass in the parent instead here,
// we can prevent the "scope not found" error
debug!("scope_region thing: %? ", cmt.id);
ty::re_scope(*self.tcx().region_map.get(&cmt.id))
};
self.compare_scope(cmt, scope_region)
}
cat_stack_upvar(cmt) => {
self.preserve(cmt)
}
cat_local(local_id) => {
// Normally, local variables are lendable, and so this
// case should never trigger. However, if we are
// preserving an expression like a.b where the field `b`
// has @ type, then it will recurse to ensure that the `a`
// is stable to try and avoid rooting the value `a.b`. In
// this case, root_managed_data will be false.
if self.root_managed_data {
self.tcx().sess.span_bug(
cmt.span,
~"preserve() called with local and!root_managed_data");
}
let local_scope_id = *self.tcx().region_map.get(&local_id);
self.compare_scope(cmt, ty::re_scope(local_scope_id))
}
cat_binding(local_id) => {
// Bindings are these kind of weird implicit pointers (cc
// #2329). We require (in gather_loans) that they be
// rooted in an immutable location.
let local_scope_id = *self.tcx().region_map.get(&local_id);
self.compare_scope(cmt, ty::re_scope(local_scope_id))
}
cat_arg(local_id) => {
// This can happen as not all args are lendable (e.g., &&
// modes). In that case, the caller guarantees stability
// for at least the scope of the fn. This is basically a
// deref of a region ptr.
let local_scope_id = *self.tcx().region_map.get(&local_id);
self.compare_scope(cmt, ty::re_scope(local_scope_id))
}
cat_self(local_id) => {
let local_scope_id = *self.tcx().region_map.get(&local_id);
self.compare_scope(cmt, ty::re_scope(local_scope_id))
}
cat_comp(cmt_base, comp_field(*)) |
cat_comp(cmt_base, comp_index(*)) |
cat_comp(cmt_base, comp_tuple) |
cat_comp(cmt_base, comp_anon_field) => {
// Most embedded components: if the base is stable, the
// type never changes.
self.preserve(cmt_base)
}
cat_comp(cmt_base, comp_variant(enum_did)) => {
if ty::enum_is_univariant(self.tcx(), enum_did) {
self.preserve(cmt_base)
} else {
// If there are multiple variants: overwriting the
// base could cause the type of this memory to change,
// so require imm.
self.require_imm(cmt, cmt_base, err_mut_variant)
}
}
cat_deref(cmt_base, _, uniq_ptr) => {
// Overwriting the base could cause this memory to be
// freed, so require imm.
self.require_imm(cmt, cmt_base, err_mut_uniq)
}
cat_deref(_, _, region_ptr(_, region)) => {
// References are always "stable" for lifetime `region` by
// induction (when the reference of type &MT was created,
// the memory must have been stable).
self.compare_scope(cmt, region)
}
cat_deref(_, _, unsafe_ptr) => {
// Unsafe pointers are the user's problem
Ok(PcOk)
}
cat_deref(base, derefs, gc_ptr(*)) => {
// GC'd pointers of type @MT: if this pointer lives in
// immutable, stable memory, then everything is fine. But
// otherwise we have no guarantee the pointer will stay
// live, so we must root the pointer (i.e., inc the ref
// count) for the duration of the loan.
debug!("base.mutbl = %?", base.mutbl);
if cmt.cat.derefs_through_mutable_box() {
self.attempt_root(cmt, base, derefs)
} else if base.mutbl.is_immutable()
|
else {
self.attempt_root(cmt, base, derefs)
}
}
cat_discr(base, match_id) => {
// Subtle: in a match, we must ensure that each binding
// variable remains valid for the duration of the arm in
// which it appears, presuming that this arm is taken.
// But it is inconvenient in trans to root something just
// for one arm. Therefore, we insert a cat_discr(),
// basically a special kind of category that says "if this
// value must be dynamically rooted, root it for the scope
// `match_id`.
//
// As an example, consider this scenario:
//
// let mut x = @Some(3);
// match *x { Some(y) {...} None {...} }
//
// Technically, the value `x` need only be rooted
// in the `some` arm. However, we evaluate `x` in trans
// before we know what arm will be taken, so we just
// always root it for the duration of the match.
//
// As a second example, consider *this* scenario:
//
// let x = @mut @Some(3);
// match x { @@Some(y) {...} @@None {...} }
//
// Here again, `x` need only be rooted in the `some` arm.
// In this case, the value which needs to be rooted is
// found only when checking which pattern matches: but
// this check is done before entering the arm. Therefore,
// even in this case we just choose to keep the value
// rooted for the entire match. This means the value will be
// rooted even if the none arm is taken. Oh well.
//
// At first, I tried to optimize the second case to only
// root in one arm, but the result was suboptimal: first,
// it interfered with the construction of phi nodes in the
// arm, as we were adding code to root values before the
// phi nodes were added. This could have been addressed
// with a second basic block. However, the naive approach
// also yielded suboptimal results for patterns like:
//
// let x = @mut @...;
// match x { @@some_variant(y) | @@some_other_variant(y) =>
//
// The reason is that we would root the value once for
// each pattern and not once per arm. This is also easily
// fixed, but it's yet more code for what is really quite
// the corner case.
//
// Nonetheless, if you decide to optimize this case in the
// future, you need only adjust where the cat_discr()
// node appears to draw the line between what will be rooted
// in the *arm* vs the *match*.
let match_rooting_ctxt = PreserveCtxt {
scope_region: ty::re_scope(match_id),
..*self
};
match_rooting_ctxt.preserve(base)
}
}
}
/// Reqiures that `cmt` (which is a deref or subcomponent of
/// `base`) be found in an immutable location (that is, `base`
/// must be immutable). Also requires that `base` itself is
/// preserved.
fn require_imm(&self,
cmt: cmt,
cmt_base: cmt,
code: bckerr_code) -> bckres<PreserveCondition> {
// Variant contents and unique pointers: must be immutably
// rooted to a preserved address.
match self.preserve(cmt_base) {
// the base is preserved, but if we are not mutable then
// purity is required
Ok(PcOk) => {
if!cmt_base.mutbl.is_immutable() {
Ok(PcIfPure(bckerr {cmt:cmt, code:code}))
} else {
Ok(PcOk)
}
}
// the base requires purity too, that's fine
Ok(PcIfPure(ref e)) => {
Ok(PcIfPure((*e)))
}
// base is not stable, doesn't matter
Err(ref e) => {
Err((*e))
}
}
}
/// Checks that the scope for which the value must be preserved
/// is a subscope of `scope_ub`; if so, success.
fn compare_scope(&self,
cmt: cmt,
scope_ub: ty::Region) -> bckres<PreserveCondition> {
if self.bccx.is_subregion_of(self.scope_region, scope_ub) {
Ok(PcOk)
} else {
Err(bckerr {
cmt:cmt,
code:err_out_of_scope(scope_ub, self.scope_region)
})
}
}
/// Here, `cmt=*base` is always a deref of managed data (if
/// `derefs`!= 0, then an auto-deref). This routine determines
/// whether it is safe to MAKE cmt stable by rooting the pointer
/// `base`. We can only do the dynamic root if the desired
/// lifetime `self.scope_region` is a subset of `self.root_ub`
/// scope; otherwise, it would either require that we hold the
/// value live for longer than the current fn or else potentially
/// require that an statically unbounded number of values be
/// rooted (if a loop exists).
fn attempt_root(&self, cmt: cmt, base: cmt,
derefs: uint) -> bckres<PreserveCondition> {
if!self.root_managed_data {
// normally, there is a root_ub; the only time that this
// is none is when a boxed value is stored in an immutable
// location. In that case, we will test to see if that
// immutable location itself can be preserved long enough
// in which case no rooting is necessary. But there it
// would be sort of pointless to avoid rooting the inner
// box by rooting an outer box, as it would just keep more
// memory live than necessary, so we set root_ub to none.
return Err(bckerr { cmt: cmt, code: err_root_not_permitted });
}
let root_region = ty::re_scope(self.root_ub);
match self.scope_region {
// we can only root values if the desired region is some concrete
// scope within the fn body
ty::re_scope(scope_id) => {
debug!("Considering root map entry for %s: \
node %d:%u -> scope_id %?, root_ub %?",
self.bccx.cmt_to_repr(cmt), base.id,
derefs, scope_id, self.root_ub);
if self.bccx.is_subregion_of(self.scope_region, root_region) {
debug!("Elected to root");
let rk = root_map_key { id: base.id, derefs: derefs };
// This code could potentially lead cause boxes to be frozen
// for longer than necessarily at runtime. It prevents an
// ICE in trans; the fundamental problem is that it's hard
// to make sure trans and borrowck have the same notion of
// scope. The real fix is to clean up how trans handles
// cleanups, but that's hard. If this becomes an issue, it's
// an option to just change this to `let scope_to_use =
// scope_id;`. Though that would potentially re-introduce
// the ICE. See #3511 for more details.
let scope_to_use = if
self.bccx.stmt_map.contains(&scope_id) {
// Root it in its parent scope, b/c
// trans won't introduce a new scope for the
// stmt
self.root_ub
}
else {
// Use the more precise scope
scope_id
};
// We freeze if and only if this is a *mutable* @ box that
// we're borrowing into a pointer.
self.bccx.root_map.insert(rk, RootInfo {
scope: scope_to_use,
freezes: cmt.cat.derefs_through_mutable_box()
});
return Ok(PcOk);
} else {
debug!("Unable to root");
return Err(bckerr {
cmt: cmt,
code: err_out_of_root_scope(root_region,
self.scope_region)
});
}
}
// we won't be able to root long enough
_ => {
return Err(bckerr {
cmt:cmt,
code:err_out_of_root_scope(root_region, self.scope_region)
});
}
}
}
}
|
{
let non_rooting_ctxt = PreserveCtxt {
root_managed_data: false,
..*self
};
match non_rooting_ctxt.preserve(base) {
Ok(PcOk) => {
Ok(PcOk)
}
Ok(PcIfPure(_)) => {
debug!("must root @T, otherwise purity req'd");
self.attempt_root(cmt, base, derefs)
}
Err(ref e) => {
debug!("must root @T, err: %s",
self.bccx.bckerr_to_str((*e)));
self.attempt_root(cmt, base, derefs)
}
}
}
|
conditional_block
|
sparkline.rs
|
use std::fmt;
pub struct Ascii {
min: f64,
max: f64,
data: Vec<f64>,
step: usize,
}
|
Self {
min,
max,
data,
step,
}
}
}
impl fmt::Display for Ascii {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let ticks = vec!['▁', '▂', '▃', '▄', '▅', '▆', '▇'];
let ticks_len = (ticks.len() - 1) as f64;
let sparkline: String = self
.data
.iter()
.step_by(self.step)
.map(|x| {
let mut i = ticks_len * (x - self.min);
if i > 0. {
i = (i / self.max).round();
}
ticks[i as usize]
})
.collect();
write!(f, "{}", sparkline)
}
}
#[test]
fn test_display() {
let s = Ascii {
min: 0.,
max: 1.,
data: vec![0.],
step: 2,
};
assert_eq!(format!("{}", s), "▁");
let s = Ascii {
min: 0.,
max: 1.,
data: vec![0., 10.],
step: 2,
};
assert_eq!(format!("{}", s), "▁");
let s = Ascii {
min: 0.,
max: 1.,
data: vec![0., 0., 1.],
step: 2,
};
assert_eq!(format!("{}", s), "▁▇");
}
|
impl Ascii {
pub fn new(min: f64, max: f64, data: Vec<f64>, step: usize) -> Self {
|
random_line_split
|
sparkline.rs
|
use std::fmt;
pub struct Ascii {
min: f64,
max: f64,
data: Vec<f64>,
step: usize,
}
impl Ascii {
pub fn new(min: f64, max: f64, data: Vec<f64>, step: usize) -> Self {
Self {
min,
max,
data,
step,
}
}
}
impl fmt::Display for Ascii {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let ticks = vec!['▁', '▂', '▃', '▄', '▅', '▆', '▇'];
let ticks_len = (ticks.len() - 1) as f64;
let sparkline: String = self
.data
.iter()
.step_by(self.step)
.map(|x| {
let mut i = ticks_len * (x - self.min);
if i > 0. {
|
ticks[i as usize]
})
.collect();
write!(f, "{}", sparkline)
}
}
#[test]
fn test_display() {
let s = Ascii {
min: 0.,
max: 1.,
data: vec![0.],
step: 2,
};
assert_eq!(format!("{}", s), "▁");
let s = Ascii {
min: 0.,
max: 1.,
data: vec![0., 10.],
step: 2,
};
assert_eq!(format!("{}", s), "▁");
let s = Ascii {
min: 0.,
max: 1.,
data: vec![0., 0., 1.],
step: 2,
};
assert_eq!(format!("{}", s), "▁▇");
}
|
i = (i / self.max).round();
}
|
conditional_block
|
sparkline.rs
|
use std::fmt;
pub struct Ascii {
min: f64,
max: f64,
data: Vec<f64>,
step: usize,
}
impl Ascii {
pub fn new(min: f64, max: f64, data: Vec<f64>, step: usize) -> Self {
Self {
min,
max,
data,
step,
}
}
}
impl fmt::Display for Ascii {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
|
fn
test_display() {
let s = Ascii {
min: 0.,
max: 1.,
data: vec![0.],
step: 2,
};
assert_eq!(format!("{}", s), "▁");
let s = Ascii {
min: 0.,
max: 1.,
data: vec![0., 10.],
step: 2,
};
assert_eq!(format!("{}", s), "▁");
let s = Ascii {
min: 0.,
max: 1.,
data: vec![0., 0., 1.],
step: 2,
};
assert_eq!(format!("{}", s), "▁▇");
}
|
{
let ticks = vec!['▁', '▂', '▃', '▄', '▅', '▆', '▇'];
let ticks_len = (ticks.len() - 1) as f64;
let sparkline: String = self
.data
.iter()
.step_by(self.step)
.map(|x| {
let mut i = ticks_len * (x - self.min);
if i > 0. {
i = (i / self.max).round();
}
ticks[i as usize]
})
.collect();
write!(f, "{}", sparkline)
}
}
#[test]
|
identifier_body
|
sparkline.rs
|
use std::fmt;
pub struct Ascii {
min: f64,
max: f64,
data: Vec<f64>,
step: usize,
}
impl Ascii {
pub fn
|
(min: f64, max: f64, data: Vec<f64>, step: usize) -> Self {
Self {
min,
max,
data,
step,
}
}
}
impl fmt::Display for Ascii {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let ticks = vec!['▁', '▂', '▃', '▄', '▅', '▆', '▇'];
let ticks_len = (ticks.len() - 1) as f64;
let sparkline: String = self
.data
.iter()
.step_by(self.step)
.map(|x| {
let mut i = ticks_len * (x - self.min);
if i > 0. {
i = (i / self.max).round();
}
ticks[i as usize]
})
.collect();
write!(f, "{}", sparkline)
}
}
#[test]
fn test_display() {
let s = Ascii {
min: 0.,
max: 1.,
data: vec![0.],
step: 2,
};
assert_eq!(format!("{}", s), "▁");
let s = Ascii {
min: 0.,
max: 1.,
data: vec![0., 10.],
step: 2,
};
assert_eq!(format!("{}", s), "▁");
let s = Ascii {
min: 0.,
max: 1.,
data: vec![0., 0., 1.],
step: 2,
};
assert_eq!(format!("{}", s), "▁▇");
}
|
new
|
identifier_name
|
main.rs
|
// Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
mod action;
mod command;
mod error;
mod graphql;
mod task;
mod timer;
use iml_manager_env::get_pool_limit;
use iml_postgres::get_db_pool;
use iml_rabbit::{self, create_connection_filter};
use iml_wire_types::Conf;
use std::sync::Arc;
use warp::Filter;
// Default pool limit if not overridden by POOL_LIMIT
const DEFAULT_POOL_LIMIT: u32 = 5;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
let addr = iml_manager_env::get_iml_api_addr();
let conf = Conf {
allow_anonymous_read: iml_manager_env::get_allow_anonymous_read(),
build: iml_manager_env::get_build(),
version: iml_manager_env::get_version(),
exa_version: iml_manager_env::get_exa_version(),
is_release: iml_manager_env::get_is_release(),
branding: iml_manager_env::get_branding().into(),
use_stratagem: iml_manager_env::get_use_stratagem(),
use_snapshots: iml_manager_env::get_use_snapshots(),
monitor_sfa: iml_manager_env::get_sfa_endpoints().is_some(),
};
let rabbit_pool = iml_rabbit::connect_to_rabbit(2);
let rabbit_pool_2 = rabbit_pool.clone();
let conn_filter = create_connection_filter(rabbit_pool);
let pg_pool = get_db_pool(get_pool_limit().unwrap_or(DEFAULT_POOL_LIMIT)).await?;
let pg_pool_2 = pg_pool.clone();
let db_pool_filter = warp::any().map(move || pg_pool.clone());
let schema = Arc::new(graphql::Schema::new(
graphql::QueryRoot,
graphql::MutationRoot,
juniper::EmptySubscription::new(),
));
let schema_filter = warp::any().map(move || Arc::clone(&schema));
let ctx = Arc::new(graphql::Context {
pg_pool: pg_pool_2,
rabbit_pool: rabbit_pool_2,
});
let ctx_filter = warp::any().map(move || Arc::clone(&ctx));
let routes = warp::path("conf")
.map(move || warp::reply::json(&conf))
.or(action::endpoint(conn_filter.clone()))
.or(task::endpoint(conn_filter, db_pool_filter))
.or(graphql::endpoint(schema_filter, ctx_filter));
tracing::info!("Starting on {:?}", addr);
let log = warp::log::custom(|info| {
tracing::debug!(
"{:?} \"{} {} {:?}\" {} \"{:?}\" \"{:?}\" {:?}",
info.remote_addr(),
info.method(),
info.path(),
info.version(),
info.status().as_u16(),
info.referer(),
info.user_agent(),
info.elapsed(),
);
});
warp::serve(
routes
.or_else(|e| async {
tracing::error!("{:?}", e);
Err(e)
})
.with(log),
)
.run(addr)
.await;
Ok(())
}
|
iml_tracing::init();
|
random_line_split
|
main.rs
|
// Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
mod action;
mod command;
mod error;
mod graphql;
mod task;
mod timer;
use iml_manager_env::get_pool_limit;
use iml_postgres::get_db_pool;
use iml_rabbit::{self, create_connection_filter};
use iml_wire_types::Conf;
use std::sync::Arc;
use warp::Filter;
// Default pool limit if not overridden by POOL_LIMIT
const DEFAULT_POOL_LIMIT: u32 = 5;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>>
|
let conn_filter = create_connection_filter(rabbit_pool);
let pg_pool = get_db_pool(get_pool_limit().unwrap_or(DEFAULT_POOL_LIMIT)).await?;
let pg_pool_2 = pg_pool.clone();
let db_pool_filter = warp::any().map(move || pg_pool.clone());
let schema = Arc::new(graphql::Schema::new(
graphql::QueryRoot,
graphql::MutationRoot,
juniper::EmptySubscription::new(),
));
let schema_filter = warp::any().map(move || Arc::clone(&schema));
let ctx = Arc::new(graphql::Context {
pg_pool: pg_pool_2,
rabbit_pool: rabbit_pool_2,
});
let ctx_filter = warp::any().map(move || Arc::clone(&ctx));
let routes = warp::path("conf")
.map(move || warp::reply::json(&conf))
.or(action::endpoint(conn_filter.clone()))
.or(task::endpoint(conn_filter, db_pool_filter))
.or(graphql::endpoint(schema_filter, ctx_filter));
tracing::info!("Starting on {:?}", addr);
let log = warp::log::custom(|info| {
tracing::debug!(
"{:?} \"{} {} {:?}\" {} \"{:?}\" \"{:?}\" {:?}",
info.remote_addr(),
info.method(),
info.path(),
info.version(),
info.status().as_u16(),
info.referer(),
info.user_agent(),
info.elapsed(),
);
});
warp::serve(
routes
.or_else(|e| async {
tracing::error!("{:?}", e);
Err(e)
})
.with(log),
)
.run(addr)
.await;
Ok(())
}
|
{
iml_tracing::init();
let addr = iml_manager_env::get_iml_api_addr();
let conf = Conf {
allow_anonymous_read: iml_manager_env::get_allow_anonymous_read(),
build: iml_manager_env::get_build(),
version: iml_manager_env::get_version(),
exa_version: iml_manager_env::get_exa_version(),
is_release: iml_manager_env::get_is_release(),
branding: iml_manager_env::get_branding().into(),
use_stratagem: iml_manager_env::get_use_stratagem(),
use_snapshots: iml_manager_env::get_use_snapshots(),
monitor_sfa: iml_manager_env::get_sfa_endpoints().is_some(),
};
let rabbit_pool = iml_rabbit::connect_to_rabbit(2);
let rabbit_pool_2 = rabbit_pool.clone();
|
identifier_body
|
main.rs
|
// Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
mod action;
mod command;
mod error;
mod graphql;
mod task;
mod timer;
use iml_manager_env::get_pool_limit;
use iml_postgres::get_db_pool;
use iml_rabbit::{self, create_connection_filter};
use iml_wire_types::Conf;
use std::sync::Arc;
use warp::Filter;
// Default pool limit if not overridden by POOL_LIMIT
const DEFAULT_POOL_LIMIT: u32 = 5;
#[tokio::main]
async fn
|
() -> Result<(), Box<dyn std::error::Error>> {
iml_tracing::init();
let addr = iml_manager_env::get_iml_api_addr();
let conf = Conf {
allow_anonymous_read: iml_manager_env::get_allow_anonymous_read(),
build: iml_manager_env::get_build(),
version: iml_manager_env::get_version(),
exa_version: iml_manager_env::get_exa_version(),
is_release: iml_manager_env::get_is_release(),
branding: iml_manager_env::get_branding().into(),
use_stratagem: iml_manager_env::get_use_stratagem(),
use_snapshots: iml_manager_env::get_use_snapshots(),
monitor_sfa: iml_manager_env::get_sfa_endpoints().is_some(),
};
let rabbit_pool = iml_rabbit::connect_to_rabbit(2);
let rabbit_pool_2 = rabbit_pool.clone();
let conn_filter = create_connection_filter(rabbit_pool);
let pg_pool = get_db_pool(get_pool_limit().unwrap_or(DEFAULT_POOL_LIMIT)).await?;
let pg_pool_2 = pg_pool.clone();
let db_pool_filter = warp::any().map(move || pg_pool.clone());
let schema = Arc::new(graphql::Schema::new(
graphql::QueryRoot,
graphql::MutationRoot,
juniper::EmptySubscription::new(),
));
let schema_filter = warp::any().map(move || Arc::clone(&schema));
let ctx = Arc::new(graphql::Context {
pg_pool: pg_pool_2,
rabbit_pool: rabbit_pool_2,
});
let ctx_filter = warp::any().map(move || Arc::clone(&ctx));
let routes = warp::path("conf")
.map(move || warp::reply::json(&conf))
.or(action::endpoint(conn_filter.clone()))
.or(task::endpoint(conn_filter, db_pool_filter))
.or(graphql::endpoint(schema_filter, ctx_filter));
tracing::info!("Starting on {:?}", addr);
let log = warp::log::custom(|info| {
tracing::debug!(
"{:?} \"{} {} {:?}\" {} \"{:?}\" \"{:?}\" {:?}",
info.remote_addr(),
info.method(),
info.path(),
info.version(),
info.status().as_u16(),
info.referer(),
info.user_agent(),
info.elapsed(),
);
});
warp::serve(
routes
.or_else(|e| async {
tracing::error!("{:?}", e);
Err(e)
})
.with(log),
)
.run(addr)
.await;
Ok(())
}
|
main
|
identifier_name
|
relocation.rs
|
use crate::error;
use scroll::{IOread, IOwrite, Pread, Pwrite, SizeWith};
/// Size of a single COFF relocation.
pub const COFF_RELOCATION_SIZE: usize = 10;
// x86 relocations.
/// The relocation is ignored.
pub const IMAGE_REL_I386_ABSOLUTE: u16 = 0x0000;
|
/// Not supported.
pub const IMAGE_REL_I386_REL16: u16 = 0x0002;
/// The target's 32-bit VA.
pub const IMAGE_REL_I386_DIR32: u16 = 0x0006;
/// The target's 32-bit RVA.
pub const IMAGE_REL_I386_DIR32NB: u16 = 0x0007;
/// Not supported.
pub const IMAGE_REL_I386_SEG12: u16 = 0x0009;
/// The 16-bit section index of the section that contains the target.
///
/// This is used to support debugging information.
pub const IMAGE_REL_I386_SECTION: u16 = 0x000A;
/// The 32-bit offset of the target from the beginning of its section.
///
/// This is used to support debugging information and static thread local storage.
pub const IMAGE_REL_I386_SECREL: u16 = 0x000B;
/// The CLR token.
pub const IMAGE_REL_I386_TOKEN: u16 = 0x000C;
/// A 7-bit offset from the base of the section that contains the target.
pub const IMAGE_REL_I386_SECREL7: u16 = 0x000D;
/// The 32-bit relative displacement to the target.
///
/// This supports the x86 relative branch and call instructions.
pub const IMAGE_REL_I386_REL32: u16 = 0x0014;
// x86-64 relocations.
/// The relocation is ignored.
pub const IMAGE_REL_AMD64_ABSOLUTE: u16 = 0x0000;
/// The 64-bit VA of the relocation target.
pub const IMAGE_REL_AMD64_ADDR64: u16 = 0x0001;
/// The 32-bit VA of the relocation target.
pub const IMAGE_REL_AMD64_ADDR32: u16 = 0x0002;
/// The 32-bit address without an image base (RVA).
pub const IMAGE_REL_AMD64_ADDR32NB: u16 = 0x0003;
/// The 32-bit relative address from the byte following the relocation.
pub const IMAGE_REL_AMD64_REL32: u16 = 0x0004;
/// The 32-bit address relative to byte distance 1 from the relocation.
pub const IMAGE_REL_AMD64_REL32_1: u16 = 0x0005;
/// The 32-bit address relative to byte distance 2 from the relocation.
pub const IMAGE_REL_AMD64_REL32_2: u16 = 0x0006;
/// The 32-bit address relative to byte distance 3 from the relocation.
pub const IMAGE_REL_AMD64_REL32_3: u16 = 0x0007;
/// The 32-bit address relative to byte distance 4 from the relocation.
pub const IMAGE_REL_AMD64_REL32_4: u16 = 0x0008;
/// The 32-bit address relative to byte distance 5 from the relocation.
pub const IMAGE_REL_AMD64_REL32_5: u16 = 0x0009;
/// The 16-bit section index of the section that contains the target.
///
/// This is used to support debugging information.
pub const IMAGE_REL_AMD64_SECTION: u16 = 0x000A;
/// The 32-bit offset of the target from the beginning of its section.
///
/// This is used to support debugging information and static thread local storage.
pub const IMAGE_REL_AMD64_SECREL: u16 = 0x000B;
/// A 7-bit unsigned offset from the base of the section that contains the target.
pub const IMAGE_REL_AMD64_SECREL7: u16 = 0x000C;
/// CLR tokens.
pub const IMAGE_REL_AMD64_TOKEN: u16 = 0x000D;
/// A 32-bit signed span-dependent value emitted into the object.
pub const IMAGE_REL_AMD64_SREL32: u16 = 0x000E;
/// A pair that must immediately follow every span-dependent value.
pub const IMAGE_REL_AMD64_PAIR: u16 = 0x000F;
/// A 32-bit signed span-dependent value that is applied at link time.
pub const IMAGE_REL_AMD64_SSPAN32: u16 = 0x0010;
/// A COFF relocation.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Default, Pread, Pwrite, IOread, IOwrite, SizeWith)]
pub struct Relocation {
/// The address of the item to which relocation is applied.
///
/// This is the offset from the beginning of the section, plus the
/// value of the section's `virtual_address` field.
pub virtual_address: u32,
/// A zero-based index into the symbol table.
///
/// This symbol gives the address that is to be used for the relocation. If the specified
/// symbol has section storage class, then the symbol's address is the address with the
/// first section of the same name.
pub symbol_table_index: u32,
/// A value that indicates the kind of relocation that should be performed.
///
/// Valid relocation types depend on machine type.
pub typ: u16,
}
/// An iterator for COFF relocations.
#[derive(Default)]
pub struct Relocations<'a> {
offset: usize,
relocations: &'a [u8],
}
impl<'a> Relocations<'a> {
/// Parse a COFF relocation table at the given offset.
///
/// The offset and number of relocations should be from the COFF section header.
pub fn parse(bytes: &'a [u8], offset: usize, number: usize) -> error::Result<Relocations<'a>> {
let relocations = bytes.pread_with(offset, number * COFF_RELOCATION_SIZE)?;
Ok(Relocations {
offset: 0,
relocations,
})
}
}
impl<'a> Iterator for Relocations<'a> {
type Item = Relocation;
fn next(&mut self) -> Option<Self::Item> {
if self.offset >= self.relocations.len() {
None
} else {
Some(
self.relocations
.gread_with(&mut self.offset, scroll::LE)
.unwrap(),
)
}
}
}
|
/// Not supported.
pub const IMAGE_REL_I386_DIR16: u16 = 0x0001;
|
random_line_split
|
relocation.rs
|
use crate::error;
use scroll::{IOread, IOwrite, Pread, Pwrite, SizeWith};
/// Size of a single COFF relocation.
pub const COFF_RELOCATION_SIZE: usize = 10;
// x86 relocations.
/// The relocation is ignored.
pub const IMAGE_REL_I386_ABSOLUTE: u16 = 0x0000;
/// Not supported.
pub const IMAGE_REL_I386_DIR16: u16 = 0x0001;
/// Not supported.
pub const IMAGE_REL_I386_REL16: u16 = 0x0002;
/// The target's 32-bit VA.
pub const IMAGE_REL_I386_DIR32: u16 = 0x0006;
/// The target's 32-bit RVA.
pub const IMAGE_REL_I386_DIR32NB: u16 = 0x0007;
/// Not supported.
pub const IMAGE_REL_I386_SEG12: u16 = 0x0009;
/// The 16-bit section index of the section that contains the target.
///
/// This is used to support debugging information.
pub const IMAGE_REL_I386_SECTION: u16 = 0x000A;
/// The 32-bit offset of the target from the beginning of its section.
///
/// This is used to support debugging information and static thread local storage.
pub const IMAGE_REL_I386_SECREL: u16 = 0x000B;
/// The CLR token.
pub const IMAGE_REL_I386_TOKEN: u16 = 0x000C;
/// A 7-bit offset from the base of the section that contains the target.
pub const IMAGE_REL_I386_SECREL7: u16 = 0x000D;
/// The 32-bit relative displacement to the target.
///
/// This supports the x86 relative branch and call instructions.
pub const IMAGE_REL_I386_REL32: u16 = 0x0014;
// x86-64 relocations.
/// The relocation is ignored.
pub const IMAGE_REL_AMD64_ABSOLUTE: u16 = 0x0000;
/// The 64-bit VA of the relocation target.
pub const IMAGE_REL_AMD64_ADDR64: u16 = 0x0001;
/// The 32-bit VA of the relocation target.
pub const IMAGE_REL_AMD64_ADDR32: u16 = 0x0002;
/// The 32-bit address without an image base (RVA).
pub const IMAGE_REL_AMD64_ADDR32NB: u16 = 0x0003;
/// The 32-bit relative address from the byte following the relocation.
pub const IMAGE_REL_AMD64_REL32: u16 = 0x0004;
/// The 32-bit address relative to byte distance 1 from the relocation.
pub const IMAGE_REL_AMD64_REL32_1: u16 = 0x0005;
/// The 32-bit address relative to byte distance 2 from the relocation.
pub const IMAGE_REL_AMD64_REL32_2: u16 = 0x0006;
/// The 32-bit address relative to byte distance 3 from the relocation.
pub const IMAGE_REL_AMD64_REL32_3: u16 = 0x0007;
/// The 32-bit address relative to byte distance 4 from the relocation.
pub const IMAGE_REL_AMD64_REL32_4: u16 = 0x0008;
/// The 32-bit address relative to byte distance 5 from the relocation.
pub const IMAGE_REL_AMD64_REL32_5: u16 = 0x0009;
/// The 16-bit section index of the section that contains the target.
///
/// This is used to support debugging information.
pub const IMAGE_REL_AMD64_SECTION: u16 = 0x000A;
/// The 32-bit offset of the target from the beginning of its section.
///
/// This is used to support debugging information and static thread local storage.
pub const IMAGE_REL_AMD64_SECREL: u16 = 0x000B;
/// A 7-bit unsigned offset from the base of the section that contains the target.
pub const IMAGE_REL_AMD64_SECREL7: u16 = 0x000C;
/// CLR tokens.
pub const IMAGE_REL_AMD64_TOKEN: u16 = 0x000D;
/// A 32-bit signed span-dependent value emitted into the object.
pub const IMAGE_REL_AMD64_SREL32: u16 = 0x000E;
/// A pair that must immediately follow every span-dependent value.
pub const IMAGE_REL_AMD64_PAIR: u16 = 0x000F;
/// A 32-bit signed span-dependent value that is applied at link time.
pub const IMAGE_REL_AMD64_SSPAN32: u16 = 0x0010;
/// A COFF relocation.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Default, Pread, Pwrite, IOread, IOwrite, SizeWith)]
pub struct Relocation {
/// The address of the item to which relocation is applied.
///
/// This is the offset from the beginning of the section, plus the
/// value of the section's `virtual_address` field.
pub virtual_address: u32,
/// A zero-based index into the symbol table.
///
/// This symbol gives the address that is to be used for the relocation. If the specified
/// symbol has section storage class, then the symbol's address is the address with the
/// first section of the same name.
pub symbol_table_index: u32,
/// A value that indicates the kind of relocation that should be performed.
///
/// Valid relocation types depend on machine type.
pub typ: u16,
}
/// An iterator for COFF relocations.
#[derive(Default)]
pub struct Relocations<'a> {
offset: usize,
relocations: &'a [u8],
}
impl<'a> Relocations<'a> {
/// Parse a COFF relocation table at the given offset.
///
/// The offset and number of relocations should be from the COFF section header.
pub fn parse(bytes: &'a [u8], offset: usize, number: usize) -> error::Result<Relocations<'a>> {
let relocations = bytes.pread_with(offset, number * COFF_RELOCATION_SIZE)?;
Ok(Relocations {
offset: 0,
relocations,
})
}
}
impl<'a> Iterator for Relocations<'a> {
type Item = Relocation;
fn next(&mut self) -> Option<Self::Item>
|
}
|
{
if self.offset >= self.relocations.len() {
None
} else {
Some(
self.relocations
.gread_with(&mut self.offset, scroll::LE)
.unwrap(),
)
}
}
|
identifier_body
|
relocation.rs
|
use crate::error;
use scroll::{IOread, IOwrite, Pread, Pwrite, SizeWith};
/// Size of a single COFF relocation.
pub const COFF_RELOCATION_SIZE: usize = 10;
// x86 relocations.
/// The relocation is ignored.
pub const IMAGE_REL_I386_ABSOLUTE: u16 = 0x0000;
/// Not supported.
pub const IMAGE_REL_I386_DIR16: u16 = 0x0001;
/// Not supported.
pub const IMAGE_REL_I386_REL16: u16 = 0x0002;
/// The target's 32-bit VA.
pub const IMAGE_REL_I386_DIR32: u16 = 0x0006;
/// The target's 32-bit RVA.
pub const IMAGE_REL_I386_DIR32NB: u16 = 0x0007;
/// Not supported.
pub const IMAGE_REL_I386_SEG12: u16 = 0x0009;
/// The 16-bit section index of the section that contains the target.
///
/// This is used to support debugging information.
pub const IMAGE_REL_I386_SECTION: u16 = 0x000A;
/// The 32-bit offset of the target from the beginning of its section.
///
/// This is used to support debugging information and static thread local storage.
pub const IMAGE_REL_I386_SECREL: u16 = 0x000B;
/// The CLR token.
pub const IMAGE_REL_I386_TOKEN: u16 = 0x000C;
/// A 7-bit offset from the base of the section that contains the target.
pub const IMAGE_REL_I386_SECREL7: u16 = 0x000D;
/// The 32-bit relative displacement to the target.
///
/// This supports the x86 relative branch and call instructions.
pub const IMAGE_REL_I386_REL32: u16 = 0x0014;
// x86-64 relocations.
/// The relocation is ignored.
pub const IMAGE_REL_AMD64_ABSOLUTE: u16 = 0x0000;
/// The 64-bit VA of the relocation target.
pub const IMAGE_REL_AMD64_ADDR64: u16 = 0x0001;
/// The 32-bit VA of the relocation target.
pub const IMAGE_REL_AMD64_ADDR32: u16 = 0x0002;
/// The 32-bit address without an image base (RVA).
pub const IMAGE_REL_AMD64_ADDR32NB: u16 = 0x0003;
/// The 32-bit relative address from the byte following the relocation.
pub const IMAGE_REL_AMD64_REL32: u16 = 0x0004;
/// The 32-bit address relative to byte distance 1 from the relocation.
pub const IMAGE_REL_AMD64_REL32_1: u16 = 0x0005;
/// The 32-bit address relative to byte distance 2 from the relocation.
pub const IMAGE_REL_AMD64_REL32_2: u16 = 0x0006;
/// The 32-bit address relative to byte distance 3 from the relocation.
pub const IMAGE_REL_AMD64_REL32_3: u16 = 0x0007;
/// The 32-bit address relative to byte distance 4 from the relocation.
pub const IMAGE_REL_AMD64_REL32_4: u16 = 0x0008;
/// The 32-bit address relative to byte distance 5 from the relocation.
pub const IMAGE_REL_AMD64_REL32_5: u16 = 0x0009;
/// The 16-bit section index of the section that contains the target.
///
/// This is used to support debugging information.
pub const IMAGE_REL_AMD64_SECTION: u16 = 0x000A;
/// The 32-bit offset of the target from the beginning of its section.
///
/// This is used to support debugging information and static thread local storage.
pub const IMAGE_REL_AMD64_SECREL: u16 = 0x000B;
/// A 7-bit unsigned offset from the base of the section that contains the target.
pub const IMAGE_REL_AMD64_SECREL7: u16 = 0x000C;
/// CLR tokens.
pub const IMAGE_REL_AMD64_TOKEN: u16 = 0x000D;
/// A 32-bit signed span-dependent value emitted into the object.
pub const IMAGE_REL_AMD64_SREL32: u16 = 0x000E;
/// A pair that must immediately follow every span-dependent value.
pub const IMAGE_REL_AMD64_PAIR: u16 = 0x000F;
/// A 32-bit signed span-dependent value that is applied at link time.
pub const IMAGE_REL_AMD64_SSPAN32: u16 = 0x0010;
/// A COFF relocation.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Default, Pread, Pwrite, IOread, IOwrite, SizeWith)]
pub struct Relocation {
/// The address of the item to which relocation is applied.
///
/// This is the offset from the beginning of the section, plus the
/// value of the section's `virtual_address` field.
pub virtual_address: u32,
/// A zero-based index into the symbol table.
///
/// This symbol gives the address that is to be used for the relocation. If the specified
/// symbol has section storage class, then the symbol's address is the address with the
/// first section of the same name.
pub symbol_table_index: u32,
/// A value that indicates the kind of relocation that should be performed.
///
/// Valid relocation types depend on machine type.
pub typ: u16,
}
/// An iterator for COFF relocations.
#[derive(Default)]
pub struct Relocations<'a> {
offset: usize,
relocations: &'a [u8],
}
impl<'a> Relocations<'a> {
/// Parse a COFF relocation table at the given offset.
///
/// The offset and number of relocations should be from the COFF section header.
pub fn parse(bytes: &'a [u8], offset: usize, number: usize) -> error::Result<Relocations<'a>> {
let relocations = bytes.pread_with(offset, number * COFF_RELOCATION_SIZE)?;
Ok(Relocations {
offset: 0,
relocations,
})
}
}
impl<'a> Iterator for Relocations<'a> {
type Item = Relocation;
fn
|
(&mut self) -> Option<Self::Item> {
if self.offset >= self.relocations.len() {
None
} else {
Some(
self.relocations
.gread_with(&mut self.offset, scroll::LE)
.unwrap(),
)
}
}
}
|
next
|
identifier_name
|
relocation.rs
|
use crate::error;
use scroll::{IOread, IOwrite, Pread, Pwrite, SizeWith};
/// Size of a single COFF relocation.
pub const COFF_RELOCATION_SIZE: usize = 10;
// x86 relocations.
/// The relocation is ignored.
pub const IMAGE_REL_I386_ABSOLUTE: u16 = 0x0000;
/// Not supported.
pub const IMAGE_REL_I386_DIR16: u16 = 0x0001;
/// Not supported.
pub const IMAGE_REL_I386_REL16: u16 = 0x0002;
/// The target's 32-bit VA.
pub const IMAGE_REL_I386_DIR32: u16 = 0x0006;
/// The target's 32-bit RVA.
pub const IMAGE_REL_I386_DIR32NB: u16 = 0x0007;
/// Not supported.
pub const IMAGE_REL_I386_SEG12: u16 = 0x0009;
/// The 16-bit section index of the section that contains the target.
///
/// This is used to support debugging information.
pub const IMAGE_REL_I386_SECTION: u16 = 0x000A;
/// The 32-bit offset of the target from the beginning of its section.
///
/// This is used to support debugging information and static thread local storage.
pub const IMAGE_REL_I386_SECREL: u16 = 0x000B;
/// The CLR token.
pub const IMAGE_REL_I386_TOKEN: u16 = 0x000C;
/// A 7-bit offset from the base of the section that contains the target.
pub const IMAGE_REL_I386_SECREL7: u16 = 0x000D;
/// The 32-bit relative displacement to the target.
///
/// This supports the x86 relative branch and call instructions.
pub const IMAGE_REL_I386_REL32: u16 = 0x0014;
// x86-64 relocations.
/// The relocation is ignored.
pub const IMAGE_REL_AMD64_ABSOLUTE: u16 = 0x0000;
/// The 64-bit VA of the relocation target.
pub const IMAGE_REL_AMD64_ADDR64: u16 = 0x0001;
/// The 32-bit VA of the relocation target.
pub const IMAGE_REL_AMD64_ADDR32: u16 = 0x0002;
/// The 32-bit address without an image base (RVA).
pub const IMAGE_REL_AMD64_ADDR32NB: u16 = 0x0003;
/// The 32-bit relative address from the byte following the relocation.
pub const IMAGE_REL_AMD64_REL32: u16 = 0x0004;
/// The 32-bit address relative to byte distance 1 from the relocation.
pub const IMAGE_REL_AMD64_REL32_1: u16 = 0x0005;
/// The 32-bit address relative to byte distance 2 from the relocation.
pub const IMAGE_REL_AMD64_REL32_2: u16 = 0x0006;
/// The 32-bit address relative to byte distance 3 from the relocation.
pub const IMAGE_REL_AMD64_REL32_3: u16 = 0x0007;
/// The 32-bit address relative to byte distance 4 from the relocation.
pub const IMAGE_REL_AMD64_REL32_4: u16 = 0x0008;
/// The 32-bit address relative to byte distance 5 from the relocation.
pub const IMAGE_REL_AMD64_REL32_5: u16 = 0x0009;
/// The 16-bit section index of the section that contains the target.
///
/// This is used to support debugging information.
pub const IMAGE_REL_AMD64_SECTION: u16 = 0x000A;
/// The 32-bit offset of the target from the beginning of its section.
///
/// This is used to support debugging information and static thread local storage.
pub const IMAGE_REL_AMD64_SECREL: u16 = 0x000B;
/// A 7-bit unsigned offset from the base of the section that contains the target.
pub const IMAGE_REL_AMD64_SECREL7: u16 = 0x000C;
/// CLR tokens.
pub const IMAGE_REL_AMD64_TOKEN: u16 = 0x000D;
/// A 32-bit signed span-dependent value emitted into the object.
pub const IMAGE_REL_AMD64_SREL32: u16 = 0x000E;
/// A pair that must immediately follow every span-dependent value.
pub const IMAGE_REL_AMD64_PAIR: u16 = 0x000F;
/// A 32-bit signed span-dependent value that is applied at link time.
pub const IMAGE_REL_AMD64_SSPAN32: u16 = 0x0010;
/// A COFF relocation.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Default, Pread, Pwrite, IOread, IOwrite, SizeWith)]
pub struct Relocation {
/// The address of the item to which relocation is applied.
///
/// This is the offset from the beginning of the section, plus the
/// value of the section's `virtual_address` field.
pub virtual_address: u32,
/// A zero-based index into the symbol table.
///
/// This symbol gives the address that is to be used for the relocation. If the specified
/// symbol has section storage class, then the symbol's address is the address with the
/// first section of the same name.
pub symbol_table_index: u32,
/// A value that indicates the kind of relocation that should be performed.
///
/// Valid relocation types depend on machine type.
pub typ: u16,
}
/// An iterator for COFF relocations.
#[derive(Default)]
pub struct Relocations<'a> {
offset: usize,
relocations: &'a [u8],
}
impl<'a> Relocations<'a> {
/// Parse a COFF relocation table at the given offset.
///
/// The offset and number of relocations should be from the COFF section header.
pub fn parse(bytes: &'a [u8], offset: usize, number: usize) -> error::Result<Relocations<'a>> {
let relocations = bytes.pread_with(offset, number * COFF_RELOCATION_SIZE)?;
Ok(Relocations {
offset: 0,
relocations,
})
}
}
impl<'a> Iterator for Relocations<'a> {
type Item = Relocation;
fn next(&mut self) -> Option<Self::Item> {
if self.offset >= self.relocations.len()
|
else {
Some(
self.relocations
.gread_with(&mut self.offset, scroll::LE)
.unwrap(),
)
}
}
}
|
{
None
}
|
conditional_block
|
main.rs
|
extern crate rand;
use std::io;
use std::io::Write;
use std::cmp::Ordering;
use rand::Rng;
fn main()
|
Ordering::Less => {
println!("{} ist zu klein, versuch's nochmal!\n", guess);
},
Ordering::Greater => {
println!("{} ist zu gross, versuch's nochmal!\n", guess);
},
Ordering::Equal => {
println!("-------------------");
println!("\\o/ Gewonnen! \\o/");
println!("-------------------");
break;
},
}
}
}
|
{
println!("Zahlenraten!");
println!("============");
let secret = rand::thread_rng().gen_range(1, 101);
//println!("Die Geheimzahl lautet: {}", secret);
loop {
print!("Geheimzahl eingeben (< 100): ");
io::stdout().flush().ok().expect("Konnte stdout nicht flushen.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.ok()
.expect("Konnte die Zeile nicht einlesen.");
let guess: u8 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
match guess.cmp(&secret) {
|
identifier_body
|
main.rs
|
extern crate rand;
use std::io;
use std::io::Write;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("Zahlenraten!");
println!("============");
let secret = rand::thread_rng().gen_range(1, 101);
//println!("Die Geheimzahl lautet: {}", secret);
loop {
print!("Geheimzahl eingeben (< 100): ");
io::stdout().flush().ok().expect("Konnte stdout nicht flushen.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.ok()
.expect("Konnte die Zeile nicht einlesen.");
let guess: u8 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
match guess.cmp(&secret) {
Ordering::Less =>
|
,
Ordering::Greater => {
println!("{} ist zu gross, versuch's nochmal!\n", guess);
},
Ordering::Equal => {
println!("-------------------");
println!("\\o/ Gewonnen! \\o/");
println!("-------------------");
break;
},
}
}
}
|
{
println!("{} ist zu klein, versuch's nochmal!\n", guess);
}
|
conditional_block
|
main.rs
|
extern crate rand;
use std::io;
use std::io::Write;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("Zahlenraten!");
println!("============");
let secret = rand::thread_rng().gen_range(1, 101);
//println!("Die Geheimzahl lautet: {}", secret);
loop {
print!("Geheimzahl eingeben (< 100): ");
io::stdout().flush().ok().expect("Konnte stdout nicht flushen.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.ok()
.expect("Konnte die Zeile nicht einlesen.");
let guess: u8 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
match guess.cmp(&secret) {
Ordering::Less => {
println!("{} ist zu klein, versuch's nochmal!\n", guess);
},
Ordering::Greater => {
println!("{} ist zu gross, versuch's nochmal!\n", guess);
},
Ordering::Equal => {
|
println!("-------------------");
break;
},
}
}
}
|
println!("-------------------");
println!("\\o/ Gewonnen! \\o/");
|
random_line_split
|
main.rs
|
extern crate rand;
use std::io;
use std::io::Write;
use std::cmp::Ordering;
use rand::Rng;
fn
|
() {
println!("Zahlenraten!");
println!("============");
let secret = rand::thread_rng().gen_range(1, 101);
//println!("Die Geheimzahl lautet: {}", secret);
loop {
print!("Geheimzahl eingeben (< 100): ");
io::stdout().flush().ok().expect("Konnte stdout nicht flushen.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.ok()
.expect("Konnte die Zeile nicht einlesen.");
let guess: u8 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
match guess.cmp(&secret) {
Ordering::Less => {
println!("{} ist zu klein, versuch's nochmal!\n", guess);
},
Ordering::Greater => {
println!("{} ist zu gross, versuch's nochmal!\n", guess);
},
Ordering::Equal => {
println!("-------------------");
println!("\\o/ Gewonnen! \\o/");
println!("-------------------");
break;
},
}
}
}
|
main
|
identifier_name
|
autoderef-method-twice.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(non_camel_case_types)]
#![feature(box_syntax)]
trait double {
fn double(self: Box<Self>) -> usize;
}
impl double for usize {
fn
|
(self: Box<usize>) -> usize { *self * 2 }
}
pub fn main() {
let x: Box<Box<_>> = box box 3;
assert_eq!(x.double(), 6);
}
|
double
|
identifier_name
|
autoderef-method-twice.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(non_camel_case_types)]
#![feature(box_syntax)]
trait double {
fn double(self: Box<Self>) -> usize;
}
impl double for usize {
fn double(self: Box<usize>) -> usize { *self * 2 }
}
pub fn main()
|
{
let x: Box<Box<_>> = box box 3;
assert_eq!(x.double(), 6);
}
|
identifier_body
|
|
aarch64_unknown_netbsd.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn
|
() -> TargetResult {
let mut base = super::netbsd_base::opts();
base.max_atomic_width = Some(128);
base.abi_blacklist = super::arm_base::abi_blacklist();
Ok(Target {
llvm_target: "aarch64-unknown-netbsd".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
target_os: "netbsd".to_string(),
target_env: String::new(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
|
target
|
identifier_name
|
aarch64_unknown_netbsd.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult
|
{
let mut base = super::netbsd_base::opts();
base.max_atomic_width = Some(128);
base.abi_blacklist = super::arm_base::abi_blacklist();
Ok(Target {
llvm_target: "aarch64-unknown-netbsd".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
target_os: "netbsd".to_string(),
target_env: String::new(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
|
identifier_body
|
|
aarch64_unknown_netbsd.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
|
pub fn target() -> TargetResult {
let mut base = super::netbsd_base::opts();
base.max_atomic_width = Some(128);
base.abi_blacklist = super::arm_base::abi_blacklist();
Ok(Target {
llvm_target: "aarch64-unknown-netbsd".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
target_os: "netbsd".to_string(),
target_env: String::new(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
|
use spec::{LinkerFlavor, Target, TargetResult};
|
random_line_split
|
running-with-no-runtime.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(catch_panic, start)]
use std::ffi::CStr;
use std::process::{Command, Output};
|
#[start]
fn start(argc: isize, argv: *const *const u8) -> isize {
if argc > 1 {
unsafe {
match **argv.offset(1) as char {
'1' => {}
'2' => println!("foo"),
'3' => assert!(thread::catch_panic(|| {}).is_ok()),
'4' => assert!(thread::catch_panic(|| panic!()).is_err()),
'5' => assert!(Command::new("test").spawn().is_err()),
_ => panic!()
}
}
return 0
}
let args = unsafe {
(0..argc as usize).map(|i| {
let ptr = *argv.offset(i as isize) as *const _;
CStr::from_ptr(ptr).to_bytes().to_vec()
}).collect::<Vec<_>>()
};
let me = String::from_utf8(args[0].to_vec()).unwrap();
pass(Command::new(&me).arg("1").output().unwrap());
pass(Command::new(&me).arg("2").output().unwrap());
pass(Command::new(&me).arg("3").output().unwrap());
pass(Command::new(&me).arg("4").output().unwrap());
pass(Command::new(&me).arg("5").output().unwrap());
0
}
fn pass(output: Output) {
if!output.status.success() {
println!("{:?}", str::from_utf8(&output.stdout));
println!("{:?}", str::from_utf8(&output.stderr));
}
}
|
use std::thread;
use std::str;
|
random_line_split
|
running-with-no-runtime.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(catch_panic, start)]
use std::ffi::CStr;
use std::process::{Command, Output};
use std::thread;
use std::str;
#[start]
fn start(argc: isize, argv: *const *const u8) -> isize
|
};
let me = String::from_utf8(args[0].to_vec()).unwrap();
pass(Command::new(&me).arg("1").output().unwrap());
pass(Command::new(&me).arg("2").output().unwrap());
pass(Command::new(&me).arg("3").output().unwrap());
pass(Command::new(&me).arg("4").output().unwrap());
pass(Command::new(&me).arg("5").output().unwrap());
0
}
fn pass(output: Output) {
if!output.status.success() {
println!("{:?}", str::from_utf8(&output.stdout));
println!("{:?}", str::from_utf8(&output.stderr));
}
}
|
{
if argc > 1 {
unsafe {
match **argv.offset(1) as char {
'1' => {}
'2' => println!("foo"),
'3' => assert!(thread::catch_panic(|| {}).is_ok()),
'4' => assert!(thread::catch_panic(|| panic!()).is_err()),
'5' => assert!(Command::new("test").spawn().is_err()),
_ => panic!()
}
}
return 0
}
let args = unsafe {
(0..argc as usize).map(|i| {
let ptr = *argv.offset(i as isize) as *const _;
CStr::from_ptr(ptr).to_bytes().to_vec()
}).collect::<Vec<_>>()
|
identifier_body
|
running-with-no-runtime.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(catch_panic, start)]
use std::ffi::CStr;
use std::process::{Command, Output};
use std::thread;
use std::str;
#[start]
fn start(argc: isize, argv: *const *const u8) -> isize {
if argc > 1 {
unsafe {
match **argv.offset(1) as char {
'1' => {}
'2' => println!("foo"),
'3' => assert!(thread::catch_panic(|| {}).is_ok()),
'4' => assert!(thread::catch_panic(|| panic!()).is_err()),
'5' => assert!(Command::new("test").spawn().is_err()),
_ => panic!()
}
}
return 0
}
let args = unsafe {
(0..argc as usize).map(|i| {
let ptr = *argv.offset(i as isize) as *const _;
CStr::from_ptr(ptr).to_bytes().to_vec()
}).collect::<Vec<_>>()
};
let me = String::from_utf8(args[0].to_vec()).unwrap();
pass(Command::new(&me).arg("1").output().unwrap());
pass(Command::new(&me).arg("2").output().unwrap());
pass(Command::new(&me).arg("3").output().unwrap());
pass(Command::new(&me).arg("4").output().unwrap());
pass(Command::new(&me).arg("5").output().unwrap());
0
}
fn
|
(output: Output) {
if!output.status.success() {
println!("{:?}", str::from_utf8(&output.stdout));
println!("{:?}", str::from_utf8(&output.stderr));
}
}
|
pass
|
identifier_name
|
mod.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::io;
use std::mem;
use std::net::{TcpListener, TcpStream, UdpSocket};
use std::os::unix::io::FromRawFd;
use libc::{self, c_int};
cfg_if! {
if #[cfg(any(target_os = "linux", target_os = "android"))] {
const FIOCLEX: libc::c_ulong = 0x5451;
} else {
const FIOCLEX: libc::c_ulong = 0x20006601;
}
}
extern {
fn ioctl(fd: libc::c_int, req: libc::c_ulong,...) -> libc::c_int;
}
mod impls;
pub struct Socket {
fd: c_int,
}
impl Socket {
pub fn new(family: c_int, ty: c_int) -> io::Result<Socket> {
unsafe {
let fd = try!(::cvt(libc::socket(family, ty, 0)));
ioctl(fd, FIOCLEX);
Ok(Socket { fd: fd })
}
}
pub fn raw(&self) -> c_int { self.fd }
fn into_fd(self) -> c_int {
let fd = self.fd;
mem::forget(self);
fd
}
pub fn into_tcp_listener(self) -> TcpListener {
unsafe { TcpListener::from_raw_fd(self.into_fd()) }
}
pub fn into_tcp_stream(self) -> TcpStream {
unsafe { TcpStream::from_raw_fd(self.into_fd()) }
}
pub fn into_udp_socket(self) -> UdpSocket {
unsafe { UdpSocket::from_raw_fd(self.into_fd()) }
}
}
impl ::FromInner for Socket {
type Inner = c_int;
fn from_inner(fd: c_int) -> Socket {
Socket { fd: fd }
}
}
impl Drop for Socket {
fn drop(&mut self) {
unsafe {
let _ = libc::close(self.fd);
}
}
|
}
|
random_line_split
|
|
mod.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::io;
use std::mem;
use std::net::{TcpListener, TcpStream, UdpSocket};
use std::os::unix::io::FromRawFd;
use libc::{self, c_int};
cfg_if! {
if #[cfg(any(target_os = "linux", target_os = "android"))] {
const FIOCLEX: libc::c_ulong = 0x5451;
} else {
const FIOCLEX: libc::c_ulong = 0x20006601;
}
}
extern {
fn ioctl(fd: libc::c_int, req: libc::c_ulong,...) -> libc::c_int;
}
mod impls;
pub struct Socket {
fd: c_int,
}
impl Socket {
pub fn new(family: c_int, ty: c_int) -> io::Result<Socket> {
unsafe {
let fd = try!(::cvt(libc::socket(family, ty, 0)));
ioctl(fd, FIOCLEX);
Ok(Socket { fd: fd })
}
}
pub fn raw(&self) -> c_int { self.fd }
fn into_fd(self) -> c_int {
let fd = self.fd;
mem::forget(self);
fd
}
pub fn into_tcp_listener(self) -> TcpListener {
unsafe { TcpListener::from_raw_fd(self.into_fd()) }
}
pub fn into_tcp_stream(self) -> TcpStream {
unsafe { TcpStream::from_raw_fd(self.into_fd()) }
}
pub fn into_udp_socket(self) -> UdpSocket {
unsafe { UdpSocket::from_raw_fd(self.into_fd()) }
}
}
impl ::FromInner for Socket {
type Inner = c_int;
fn from_inner(fd: c_int) -> Socket
|
}
impl Drop for Socket {
fn drop(&mut self) {
unsafe {
let _ = libc::close(self.fd);
}
}
}
|
{
Socket { fd: fd }
}
|
identifier_body
|
mod.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::io;
use std::mem;
use std::net::{TcpListener, TcpStream, UdpSocket};
use std::os::unix::io::FromRawFd;
use libc::{self, c_int};
cfg_if! {
if #[cfg(any(target_os = "linux", target_os = "android"))] {
const FIOCLEX: libc::c_ulong = 0x5451;
} else {
const FIOCLEX: libc::c_ulong = 0x20006601;
}
}
extern {
fn ioctl(fd: libc::c_int, req: libc::c_ulong,...) -> libc::c_int;
}
mod impls;
pub struct Socket {
fd: c_int,
}
impl Socket {
pub fn new(family: c_int, ty: c_int) -> io::Result<Socket> {
unsafe {
let fd = try!(::cvt(libc::socket(family, ty, 0)));
ioctl(fd, FIOCLEX);
Ok(Socket { fd: fd })
}
}
pub fn raw(&self) -> c_int { self.fd }
fn into_fd(self) -> c_int {
let fd = self.fd;
mem::forget(self);
fd
}
pub fn into_tcp_listener(self) -> TcpListener {
unsafe { TcpListener::from_raw_fd(self.into_fd()) }
}
pub fn
|
(self) -> TcpStream {
unsafe { TcpStream::from_raw_fd(self.into_fd()) }
}
pub fn into_udp_socket(self) -> UdpSocket {
unsafe { UdpSocket::from_raw_fd(self.into_fd()) }
}
}
impl ::FromInner for Socket {
type Inner = c_int;
fn from_inner(fd: c_int) -> Socket {
Socket { fd: fd }
}
}
impl Drop for Socket {
fn drop(&mut self) {
unsafe {
let _ = libc::close(self.fd);
}
}
}
|
into_tcp_stream
|
identifier_name
|
mode.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Mode type
pub use std::time::Duration;
use client::Mode as ClientMode;
/// IPC-capable shadow-type for `client::config::Mode`
#[derive(Clone, Debug)]
#[cfg_attr(feature = "ipc", binary)]
pub enum Mode {
/// Same as `ClientMode::Off`.
Off,
/// Same as `ClientMode::Dark`; values in seconds.
Dark(u64),
/// Same as `ClientMode::Passive`; values in seconds.
Passive(u64, u64),
/// Same as `ClientMode::Active`.
Active,
}
impl From<ClientMode> for Mode {
fn from(mode: ClientMode) -> Self {
match mode {
ClientMode::Off => Mode::Off,
ClientMode::Dark(timeout) => Mode::Dark(timeout.as_secs()),
ClientMode::Passive(timeout, alarm) => Mode::Passive(timeout.as_secs(), alarm.as_secs()),
ClientMode::Active => Mode::Active,
}
}
}
impl From<Mode> for ClientMode {
fn
|
(mode: Mode) -> Self {
match mode {
Mode::Off => ClientMode::Off,
Mode::Dark(timeout) => ClientMode::Dark(Duration::from_secs(timeout)),
Mode::Passive(timeout, alarm) => ClientMode::Passive(Duration::from_secs(timeout), Duration::from_secs(alarm)),
Mode::Active => ClientMode::Active,
}
}
}
|
from
|
identifier_name
|
mode.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Mode type
pub use std::time::Duration;
use client::Mode as ClientMode;
/// IPC-capable shadow-type for `client::config::Mode`
#[derive(Clone, Debug)]
#[cfg_attr(feature = "ipc", binary)]
pub enum Mode {
/// Same as `ClientMode::Off`.
Off,
/// Same as `ClientMode::Dark`; values in seconds.
Dark(u64),
/// Same as `ClientMode::Passive`; values in seconds.
Passive(u64, u64),
/// Same as `ClientMode::Active`.
Active,
}
impl From<ClientMode> for Mode {
fn from(mode: ClientMode) -> Self {
match mode {
ClientMode::Off => Mode::Off,
ClientMode::Dark(timeout) => Mode::Dark(timeout.as_secs()),
ClientMode::Passive(timeout, alarm) => Mode::Passive(timeout.as_secs(), alarm.as_secs()),
ClientMode::Active => Mode::Active,
}
}
}
impl From<Mode> for ClientMode {
fn from(mode: Mode) -> Self {
match mode {
|
Mode::Passive(timeout, alarm) => ClientMode::Passive(Duration::from_secs(timeout), Duration::from_secs(alarm)),
Mode::Active => ClientMode::Active,
}
}
}
|
Mode::Off => ClientMode::Off,
Mode::Dark(timeout) => ClientMode::Dark(Duration::from_secs(timeout)),
|
random_line_split
|
mode.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Mode type
pub use std::time::Duration;
use client::Mode as ClientMode;
/// IPC-capable shadow-type for `client::config::Mode`
#[derive(Clone, Debug)]
#[cfg_attr(feature = "ipc", binary)]
pub enum Mode {
/// Same as `ClientMode::Off`.
Off,
/// Same as `ClientMode::Dark`; values in seconds.
Dark(u64),
/// Same as `ClientMode::Passive`; values in seconds.
Passive(u64, u64),
/// Same as `ClientMode::Active`.
Active,
}
impl From<ClientMode> for Mode {
fn from(mode: ClientMode) -> Self {
match mode {
ClientMode::Off => Mode::Off,
ClientMode::Dark(timeout) => Mode::Dark(timeout.as_secs()),
ClientMode::Passive(timeout, alarm) => Mode::Passive(timeout.as_secs(), alarm.as_secs()),
ClientMode::Active => Mode::Active,
}
}
}
impl From<Mode> for ClientMode {
fn from(mode: Mode) -> Self
|
}
|
{
match mode {
Mode::Off => ClientMode::Off,
Mode::Dark(timeout) => ClientMode::Dark(Duration::from_secs(timeout)),
Mode::Passive(timeout, alarm) => ClientMode::Passive(Duration::from_secs(timeout), Duration::from_secs(alarm)),
Mode::Active => ClientMode::Active,
}
}
|
identifier_body
|
fixed_bug_11.rs
|
/*!
* # Expected behaviour:
* The top cube will fall asleep while the bottom cube goes right at constant speed.
*
* # Symptoms:
* Bothe cube fall asleep at some point.
*
* # Cause:
* There was no way of customizing the deactivation threshold.
*
* # Solution:
* Rigid bodies now have a `set_deactivation_threshold` method to set the threshold to a
* user-defined value, or to prevent completely any deactivation (by setting None as the
* threshold).
*
* # Limitations of the solution:
*/
extern crate nalgebra as na;
extern crate ncollide;
extern crate nphysics;
extern crate nphysics_testbed2d;
use na::{Vec2, Translation};
use ncollide::shape::Cuboid;
use nphysics::world::World;
use nphysics::object::RigidBody;
use nphysics_testbed2d::Testbed;
fn main()
|
*/
rb.set_deactivation_threshold(Some(0.5));
rb.append_translation(&Vec2::new(0.0, 3.0));
world.add_body(rb);
/*
* Set up the testbed.
*/
let mut testbed = Testbed::new(world);
testbed.run();
}
|
{
/*
* World
*/
let mut world = World::new();
world.set_gravity(Vec2::new(0.0, 0.0));
/*
* Create the box that will be deactivated.
*/
let rad = 1.0;
let geom = Cuboid::new(Vec2::new(rad, rad));
let mut rb = RigidBody::new_dynamic(geom, 1.0, 0.3, 0.5);
rb.set_lin_vel(Vec2::new(0.99, 0.0));
world.add_body(rb.clone());
/*
* Create the box that will not be deactivated.
|
identifier_body
|
fixed_bug_11.rs
|
/*!
* # Expected behaviour:
* The top cube will fall asleep while the bottom cube goes right at constant speed.
*
* # Symptoms:
* Bothe cube fall asleep at some point.
*
* # Cause:
* There was no way of customizing the deactivation threshold.
*
* # Solution:
* Rigid bodies now have a `set_deactivation_threshold` method to set the threshold to a
* user-defined value, or to prevent completely any deactivation (by setting None as the
* threshold).
*
* # Limitations of the solution:
*/
extern crate nalgebra as na;
extern crate ncollide;
extern crate nphysics;
extern crate nphysics_testbed2d;
use na::{Vec2, Translation};
use ncollide::shape::Cuboid;
use nphysics::world::World;
use nphysics::object::RigidBody;
use nphysics_testbed2d::Testbed;
fn main() {
/*
* World
*/
let mut world = World::new();
world.set_gravity(Vec2::new(0.0, 0.0));
/*
* Create the box that will be deactivated.
*/
let rad = 1.0;
let geom = Cuboid::new(Vec2::new(rad, rad));
let mut rb = RigidBody::new_dynamic(geom, 1.0, 0.3, 0.5);
rb.set_lin_vel(Vec2::new(0.99, 0.0));
world.add_body(rb.clone());
|
/*
* Create the box that will not be deactivated.
*/
rb.set_deactivation_threshold(Some(0.5));
rb.append_translation(&Vec2::new(0.0, 3.0));
world.add_body(rb);
/*
* Set up the testbed.
*/
let mut testbed = Testbed::new(world);
testbed.run();
}
|
random_line_split
|
|
fixed_bug_11.rs
|
/*!
* # Expected behaviour:
* The top cube will fall asleep while the bottom cube goes right at constant speed.
*
* # Symptoms:
* Bothe cube fall asleep at some point.
*
* # Cause:
* There was no way of customizing the deactivation threshold.
*
* # Solution:
* Rigid bodies now have a `set_deactivation_threshold` method to set the threshold to a
* user-defined value, or to prevent completely any deactivation (by setting None as the
* threshold).
*
* # Limitations of the solution:
*/
extern crate nalgebra as na;
extern crate ncollide;
extern crate nphysics;
extern crate nphysics_testbed2d;
use na::{Vec2, Translation};
use ncollide::shape::Cuboid;
use nphysics::world::World;
use nphysics::object::RigidBody;
use nphysics_testbed2d::Testbed;
fn
|
() {
/*
* World
*/
let mut world = World::new();
world.set_gravity(Vec2::new(0.0, 0.0));
/*
* Create the box that will be deactivated.
*/
let rad = 1.0;
let geom = Cuboid::new(Vec2::new(rad, rad));
let mut rb = RigidBody::new_dynamic(geom, 1.0, 0.3, 0.5);
rb.set_lin_vel(Vec2::new(0.99, 0.0));
world.add_body(rb.clone());
/*
* Create the box that will not be deactivated.
*/
rb.set_deactivation_threshold(Some(0.5));
rb.append_translation(&Vec2::new(0.0, 3.0));
world.add_body(rb);
/*
* Set up the testbed.
*/
let mut testbed = Testbed::new(world);
testbed.run();
}
|
main
|
identifier_name
|
pipe.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use prelude::v1::*;
use sys::fd::FileDesc;
use io;
use libc;
////////////////////////////////////////////////////////////////////////////////
// Anonymous pipes
////////////////////////////////////////////////////////////////////////////////
pub struct AnonPipe(FileDesc);
pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> {
let mut fds = [0; 2];
if unsafe { libc::pipe(fds.as_mut_ptr()) == 0 } {
Ok((AnonPipe::from_fd(fds[0]), AnonPipe::from_fd(fds[1])))
} else {
Err(io::Error::last_os_error())
}
}
impl AnonPipe {
pub fn from_fd(fd: libc::c_int) -> AnonPipe {
let fd = FileDesc::new(fd);
fd.set_cloexec();
AnonPipe(fd)
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
pub fn write(&self, buf: &[u8]) -> io::Result<usize>
|
pub fn raw(&self) -> libc::c_int { self.0.raw() }
pub fn fd(&self) -> &FileDesc { &self.0 }
}
|
{
self.0.write(buf)
}
|
identifier_body
|
pipe.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use prelude::v1::*;
use sys::fd::FileDesc;
use io;
use libc;
////////////////////////////////////////////////////////////////////////////////
// Anonymous pipes
////////////////////////////////////////////////////////////////////////////////
pub struct AnonPipe(FileDesc);
pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> {
let mut fds = [0; 2];
if unsafe { libc::pipe(fds.as_mut_ptr()) == 0 }
|
else {
Err(io::Error::last_os_error())
}
}
impl AnonPipe {
pub fn from_fd(fd: libc::c_int) -> AnonPipe {
let fd = FileDesc::new(fd);
fd.set_cloexec();
AnonPipe(fd)
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
pub fn raw(&self) -> libc::c_int { self.0.raw() }
pub fn fd(&self) -> &FileDesc { &self.0 }
}
|
{
Ok((AnonPipe::from_fd(fds[0]), AnonPipe::from_fd(fds[1])))
}
|
conditional_block
|
pipe.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use prelude::v1::*;
use sys::fd::FileDesc;
use io;
use libc;
////////////////////////////////////////////////////////////////////////////////
// Anonymous pipes
////////////////////////////////////////////////////////////////////////////////
pub struct AnonPipe(FileDesc);
pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> {
let mut fds = [0; 2];
if unsafe { libc::pipe(fds.as_mut_ptr()) == 0 } {
Ok((AnonPipe::from_fd(fds[0]), AnonPipe::from_fd(fds[1])))
} else {
Err(io::Error::last_os_error())
}
}
impl AnonPipe {
pub fn
|
(fd: libc::c_int) -> AnonPipe {
let fd = FileDesc::new(fd);
fd.set_cloexec();
AnonPipe(fd)
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
pub fn raw(&self) -> libc::c_int { self.0.raw() }
pub fn fd(&self) -> &FileDesc { &self.0 }
}
|
from_fd
|
identifier_name
|
pipe.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use prelude::v1::*;
use sys::fd::FileDesc;
use io;
use libc;
////////////////////////////////////////////////////////////////////////////////
// Anonymous pipes
////////////////////////////////////////////////////////////////////////////////
pub struct AnonPipe(FileDesc);
pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> {
let mut fds = [0; 2];
if unsafe { libc::pipe(fds.as_mut_ptr()) == 0 } {
Ok((AnonPipe::from_fd(fds[0]), AnonPipe::from_fd(fds[1])))
} else {
Err(io::Error::last_os_error())
}
}
impl AnonPipe {
pub fn from_fd(fd: libc::c_int) -> AnonPipe {
let fd = FileDesc::new(fd);
fd.set_cloexec();
AnonPipe(fd)
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
|
pub fn raw(&self) -> libc::c_int { self.0.raw() }
pub fn fd(&self) -> &FileDesc { &self.0 }
}
|
random_line_split
|
|
ignore-all-the-things.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct Foo(int, int, int, int);
struct
|
{a: int, b: int, c: int, d: int}
pub fn main() {
let Foo(..) = Foo(5, 5, 5, 5);
let Foo(..) = Foo(5, 5, 5, 5);
let Bar{..} = Bar{a: 5, b: 5, c: 5, d: 5};
//let (..) = (5, 5, 5, 5);
//let Foo(a, b,..) = Foo(5, 5, 5, 5);
//let Foo(.., d) = Foo(5, 5, 5, 5);
//let (a, b,..) = (5, 5, 5, 5);
//let (.., c, d) = (5, 5, 5, 5);
let Bar{b: b,..} = Bar{a: 5, b: 5, c: 5, d: 5};
match [5, 5, 5, 5] {
[..] => { }
}
match [5, 5, 5, 5] {
[a,..] => { }
}
match [5, 5, 5, 5] {
[.., b] => { }
}
match [5, 5, 5, 5] {
[a,.., b] => { }
}
match [5, 5, 5] {
[..] => { }
}
match [5, 5, 5] {
[a,..] => { }
}
match [5, 5, 5] {
[.., a] => { }
}
match [5, 5, 5] {
[a,.., b] => { }
}
}
|
Bar
|
identifier_name
|
ignore-all-the-things.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct Foo(int, int, int, int);
struct Bar{a: int, b: int, c: int, d: int}
pub fn main() {
let Foo(..) = Foo(5, 5, 5, 5);
let Foo(..) = Foo(5, 5, 5, 5);
let Bar{..} = Bar{a: 5, b: 5, c: 5, d: 5};
//let (..) = (5, 5, 5, 5);
//let Foo(a, b,..) = Foo(5, 5, 5, 5);
//let Foo(.., d) = Foo(5, 5, 5, 5);
//let (a, b,..) = (5, 5, 5, 5);
//let (.., c, d) = (5, 5, 5, 5);
let Bar{b: b,..} = Bar{a: 5, b: 5, c: 5, d: 5};
match [5, 5, 5, 5] {
[..] => { }
}
match [5, 5, 5, 5] {
[a,..] => { }
}
match [5, 5, 5, 5] {
[.., b] =>
|
}
match [5, 5, 5, 5] {
[a,.., b] => { }
}
match [5, 5, 5] {
[..] => { }
}
match [5, 5, 5] {
[a,..] => { }
}
match [5, 5, 5] {
[.., a] => { }
}
match [5, 5, 5] {
[a,.., b] => { }
}
}
|
{ }
|
conditional_block
|
ignore-all-the-things.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct Foo(int, int, int, int);
struct Bar{a: int, b: int, c: int, d: int}
pub fn main() {
let Foo(..) = Foo(5, 5, 5, 5);
let Foo(..) = Foo(5, 5, 5, 5);
let Bar{..} = Bar{a: 5, b: 5, c: 5, d: 5};
//let (..) = (5, 5, 5, 5);
//let Foo(a, b,..) = Foo(5, 5, 5, 5);
//let Foo(.., d) = Foo(5, 5, 5, 5);
//let (a, b,..) = (5, 5, 5, 5);
//let (.., c, d) = (5, 5, 5, 5);
let Bar{b: b,..} = Bar{a: 5, b: 5, c: 5, d: 5};
match [5, 5, 5, 5] {
[..] => { }
}
match [5, 5, 5, 5] {
[a,..] => { }
}
match [5, 5, 5, 5] {
[.., b] => { }
}
match [5, 5, 5, 5] {
[a,.., b] => { }
}
match [5, 5, 5] {
[..] => { }
}
match [5, 5, 5] {
[a,..] => { }
}
match [5, 5, 5] {
[.., a] => { }
}
match [5, 5, 5] {
[a,.., b] => { }
|
}
}
|
random_line_split
|
|
scribe.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::num::NonZeroU64;
use anyhow::anyhow;
use bookmarks_types::BookmarkName;
use changesets::ChangesetsRef;
use chrono::Utc;
use context::CoreContext;
use ephemeral_blobstore::BubbleId;
use futures::{stream, StreamExt, TryStreamExt};
use mononoke_types::{BonsaiChangeset, ChangesetId, Generation};
use repo_identity::RepoIdentityRef;
use scribe_commit_queue::{ChangedFilesInfo, CommitInfo, LogToScribe};
pub struct ScribeCommitInfo {
pub changeset_id: ChangesetId,
pub bubble_id: Option<NonZeroU64>,
pub changed_files: ChangedFilesInfo,
}
pub async fn log_commits_to_scribe_raw(
ctx: &CoreContext,
|
repo: &(impl RepoIdentityRef + ChangesetsRef),
bookmark: Option<&BookmarkName>,
changesets_and_changed_files_count: Vec<ScribeCommitInfo>,
commit_scribe_category: Option<&str>,
) {
let queue = match commit_scribe_category {
Some(category) if!category.is_empty() => {
LogToScribe::new(ctx.scribe().clone(), category.to_string())
}
_ => LogToScribe::new_with_discard(),
};
let repo_id = repo.repo_identity().id();
let repo_name = repo.repo_identity().name();
let bookmark = bookmark.map(|bm| bm.as_str());
let received_timestamp = Utc::now();
let res = stream::iter(changesets_and_changed_files_count)
.map(Ok)
.map_ok(
|
ScribeCommitInfo {
changeset_id,
bubble_id,
changed_files,
},
| {
let queue = &queue;
async move {
let cs = repo
.changesets()
.get(ctx.clone(), changeset_id)
.await?
.ok_or_else(|| anyhow!("Changeset not found: {}", changeset_id))?;
let generation = Generation::new(cs.gen);
let parents = cs.parents;
let username = ctx.metadata().unix_name();
let hostname = ctx.metadata().client_hostname();
let identities = ctx.metadata().identities();
let ci = CommitInfo::new(
repo_id,
repo_name,
bookmark,
generation,
changeset_id,
bubble_id,
parents,
username,
identities,
hostname,
received_timestamp,
changed_files,
);
queue.queue_commit(&ci)
}
},
)
.try_for_each_concurrent(100, |f| f)
.await;
if let Err(err) = res {
ctx.scuba()
.clone()
.log_with_msg("Failed to log pushed commits", Some(format!("{}", err)));
}
}
pub async fn log_commit_to_scribe(
ctx: &CoreContext,
category: &str,
container: &(impl RepoIdentityRef + ChangesetsRef),
changeset: &BonsaiChangeset,
bubble: Option<BubbleId>,
) {
let changeset_id = changeset.get_changeset_id();
let changed_files = ChangedFilesInfo::new(changeset);
log_commits_to_scribe_raw(
ctx,
container,
None,
vec![ScribeCommitInfo {
changeset_id,
bubble_id: bubble.map(Into::into),
changed_files,
}],
Some(category),
)
.await;
}
|
random_line_split
|
|
scribe.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::num::NonZeroU64;
use anyhow::anyhow;
use bookmarks_types::BookmarkName;
use changesets::ChangesetsRef;
use chrono::Utc;
use context::CoreContext;
use ephemeral_blobstore::BubbleId;
use futures::{stream, StreamExt, TryStreamExt};
use mononoke_types::{BonsaiChangeset, ChangesetId, Generation};
use repo_identity::RepoIdentityRef;
use scribe_commit_queue::{ChangedFilesInfo, CommitInfo, LogToScribe};
pub struct ScribeCommitInfo {
pub changeset_id: ChangesetId,
pub bubble_id: Option<NonZeroU64>,
pub changed_files: ChangedFilesInfo,
}
pub async fn log_commits_to_scribe_raw(
ctx: &CoreContext,
repo: &(impl RepoIdentityRef + ChangesetsRef),
bookmark: Option<&BookmarkName>,
changesets_and_changed_files_count: Vec<ScribeCommitInfo>,
commit_scribe_category: Option<&str>,
) {
let queue = match commit_scribe_category {
Some(category) if!category.is_empty() => {
LogToScribe::new(ctx.scribe().clone(), category.to_string())
}
_ => LogToScribe::new_with_discard(),
};
let repo_id = repo.repo_identity().id();
let repo_name = repo.repo_identity().name();
let bookmark = bookmark.map(|bm| bm.as_str());
let received_timestamp = Utc::now();
let res = stream::iter(changesets_and_changed_files_count)
.map(Ok)
.map_ok(
|
ScribeCommitInfo {
changeset_id,
bubble_id,
changed_files,
},
| {
let queue = &queue;
async move {
let cs = repo
.changesets()
.get(ctx.clone(), changeset_id)
.await?
.ok_or_else(|| anyhow!("Changeset not found: {}", changeset_id))?;
let generation = Generation::new(cs.gen);
let parents = cs.parents;
let username = ctx.metadata().unix_name();
let hostname = ctx.metadata().client_hostname();
let identities = ctx.metadata().identities();
let ci = CommitInfo::new(
repo_id,
repo_name,
bookmark,
generation,
changeset_id,
bubble_id,
parents,
username,
identities,
hostname,
received_timestamp,
changed_files,
);
queue.queue_commit(&ci)
}
},
)
.try_for_each_concurrent(100, |f| f)
.await;
if let Err(err) = res
|
}
pub async fn log_commit_to_scribe(
ctx: &CoreContext,
category: &str,
container: &(impl RepoIdentityRef + ChangesetsRef),
changeset: &BonsaiChangeset,
bubble: Option<BubbleId>,
) {
let changeset_id = changeset.get_changeset_id();
let changed_files = ChangedFilesInfo::new(changeset);
log_commits_to_scribe_raw(
ctx,
container,
None,
vec![ScribeCommitInfo {
changeset_id,
bubble_id: bubble.map(Into::into),
changed_files,
}],
Some(category),
)
.await;
}
|
{
ctx.scuba()
.clone()
.log_with_msg("Failed to log pushed commits", Some(format!("{}", err)));
}
|
conditional_block
|
scribe.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::num::NonZeroU64;
use anyhow::anyhow;
use bookmarks_types::BookmarkName;
use changesets::ChangesetsRef;
use chrono::Utc;
use context::CoreContext;
use ephemeral_blobstore::BubbleId;
use futures::{stream, StreamExt, TryStreamExt};
use mononoke_types::{BonsaiChangeset, ChangesetId, Generation};
use repo_identity::RepoIdentityRef;
use scribe_commit_queue::{ChangedFilesInfo, CommitInfo, LogToScribe};
pub struct ScribeCommitInfo {
pub changeset_id: ChangesetId,
pub bubble_id: Option<NonZeroU64>,
pub changed_files: ChangedFilesInfo,
}
pub async fn log_commits_to_scribe_raw(
ctx: &CoreContext,
repo: &(impl RepoIdentityRef + ChangesetsRef),
bookmark: Option<&BookmarkName>,
changesets_and_changed_files_count: Vec<ScribeCommitInfo>,
commit_scribe_category: Option<&str>,
) {
let queue = match commit_scribe_category {
Some(category) if!category.is_empty() => {
LogToScribe::new(ctx.scribe().clone(), category.to_string())
}
_ => LogToScribe::new_with_discard(),
};
let repo_id = repo.repo_identity().id();
let repo_name = repo.repo_identity().name();
let bookmark = bookmark.map(|bm| bm.as_str());
let received_timestamp = Utc::now();
let res = stream::iter(changesets_and_changed_files_count)
.map(Ok)
.map_ok(
|
ScribeCommitInfo {
changeset_id,
bubble_id,
changed_files,
},
| {
let queue = &queue;
async move {
let cs = repo
.changesets()
.get(ctx.clone(), changeset_id)
.await?
.ok_or_else(|| anyhow!("Changeset not found: {}", changeset_id))?;
let generation = Generation::new(cs.gen);
let parents = cs.parents;
let username = ctx.metadata().unix_name();
let hostname = ctx.metadata().client_hostname();
let identities = ctx.metadata().identities();
let ci = CommitInfo::new(
repo_id,
repo_name,
bookmark,
generation,
changeset_id,
bubble_id,
parents,
username,
identities,
hostname,
received_timestamp,
changed_files,
);
queue.queue_commit(&ci)
}
},
)
.try_for_each_concurrent(100, |f| f)
.await;
if let Err(err) = res {
ctx.scuba()
.clone()
.log_with_msg("Failed to log pushed commits", Some(format!("{}", err)));
}
}
pub async fn
|
(
ctx: &CoreContext,
category: &str,
container: &(impl RepoIdentityRef + ChangesetsRef),
changeset: &BonsaiChangeset,
bubble: Option<BubbleId>,
) {
let changeset_id = changeset.get_changeset_id();
let changed_files = ChangedFilesInfo::new(changeset);
log_commits_to_scribe_raw(
ctx,
container,
None,
vec![ScribeCommitInfo {
changeset_id,
bubble_id: bubble.map(Into::into),
changed_files,
}],
Some(category),
)
.await;
}
|
log_commit_to_scribe
|
identifier_name
|
lib.rs
|
fn compute_kmp_table(word: &String) -> Vec<i32> {
let mut table : Vec<i32> = vec![0; word.len()];
let mut pos = 2;
let mut cnd = 0;
let word_chars : Vec<char> = word.chars().collect::<Vec<char>>();
table[0] = -1;
table[1] = 0;
while pos < word.len() {
if word_chars[pos - 1] == word_chars[cnd] {
table[pos] = (cnd + 1) as i32;
cnd += 1;
pos += 1;
} else if cnd > 0 {
cnd = (table[cnd]) as usize;
} else {
table[pos] = 0;
pos += 1;
}
}
table
}
fn kmp_serch(word: & String, text: & String) -> usize {
let mut m : usize = 0;
let mut i : usize = 0;
let table : Vec<i32> = compute_kmp_table(&word);
let text_len : usize = text.len();
let word_len : usize = word.len();
let word_chars : Vec<char> = word.chars().collect::<Vec<char>>();
let text_chars : Vec<char> = text.chars().collect::<Vec<char>>();
while m + i < text_len {
if word_chars[i] == text_chars[m + i] {
if i == word_len - 1 {
return m;
}
i += 1;
} else {
if table[i] > -1 {
m += i - (table[i] as usize);
i = table[i] as usize;
} else {
i = 0;
m += 1;
}
}
}
text_len // no match found
}
#[test]
fn compute_kmp_table_test_1() {
let word : String = "ABCDABD".to_string();
let expected_res : Vec<i32> = vec![-1, 0, 0, 0, 0, 1, 2];
let res : Vec<i32> = compute_kmp_table(&word);
assert_eq!(res.len(), expected_res.len());
for i in 0..res.len() {
assert_eq!(res[i], expected_res[i]);
}
}
#[test]
fn
|
() {
let word : String = "ABCDABD".to_string();
let text : String = "ABC ABCDAB ABCDABCDABDE".to_string();
let expected_res : usize = 15;
let res : usize = kmp_serch(&word, &text);
assert_eq!(res, expected_res);
}
|
kmp_serch_1
|
identifier_name
|
lib.rs
|
fn compute_kmp_table(word: &String) -> Vec<i32> {
let mut table : Vec<i32> = vec![0; word.len()];
let mut pos = 2;
let mut cnd = 0;
let word_chars : Vec<char> = word.chars().collect::<Vec<char>>();
table[0] = -1;
table[1] = 0;
while pos < word.len() {
if word_chars[pos - 1] == word_chars[cnd] {
table[pos] = (cnd + 1) as i32;
cnd += 1;
pos += 1;
} else if cnd > 0 {
|
}
table
}
fn kmp_serch(word: & String, text: & String) -> usize {
let mut m : usize = 0;
let mut i : usize = 0;
let table : Vec<i32> = compute_kmp_table(&word);
let text_len : usize = text.len();
let word_len : usize = word.len();
let word_chars : Vec<char> = word.chars().collect::<Vec<char>>();
let text_chars : Vec<char> = text.chars().collect::<Vec<char>>();
while m + i < text_len {
if word_chars[i] == text_chars[m + i] {
if i == word_len - 1 {
return m;
}
i += 1;
} else {
if table[i] > -1 {
m += i - (table[i] as usize);
i = table[i] as usize;
} else {
i = 0;
m += 1;
}
}
}
text_len // no match found
}
#[test]
fn compute_kmp_table_test_1() {
let word : String = "ABCDABD".to_string();
let expected_res : Vec<i32> = vec![-1, 0, 0, 0, 0, 1, 2];
let res : Vec<i32> = compute_kmp_table(&word);
assert_eq!(res.len(), expected_res.len());
for i in 0..res.len() {
assert_eq!(res[i], expected_res[i]);
}
}
#[test]
fn kmp_serch_1() {
let word : String = "ABCDABD".to_string();
let text : String = "ABC ABCDAB ABCDABCDABDE".to_string();
let expected_res : usize = 15;
let res : usize = kmp_serch(&word, &text);
assert_eq!(res, expected_res);
}
|
cnd = (table[cnd]) as usize;
} else {
table[pos] = 0;
pos += 1;
}
|
random_line_split
|
lib.rs
|
fn compute_kmp_table(word: &String) -> Vec<i32> {
let mut table : Vec<i32> = vec![0; word.len()];
let mut pos = 2;
let mut cnd = 0;
let word_chars : Vec<char> = word.chars().collect::<Vec<char>>();
table[0] = -1;
table[1] = 0;
while pos < word.len() {
if word_chars[pos - 1] == word_chars[cnd] {
table[pos] = (cnd + 1) as i32;
cnd += 1;
pos += 1;
} else if cnd > 0 {
cnd = (table[cnd]) as usize;
} else {
table[pos] = 0;
pos += 1;
}
}
table
}
fn kmp_serch(word: & String, text: & String) -> usize
|
} else {
i = 0;
m += 1;
}
}
}
text_len // no match found
}
#[test]
fn compute_kmp_table_test_1() {
let word : String = "ABCDABD".to_string();
let expected_res : Vec<i32> = vec![-1, 0, 0, 0, 0, 1, 2];
let res : Vec<i32> = compute_kmp_table(&word);
assert_eq!(res.len(), expected_res.len());
for i in 0..res.len() {
assert_eq!(res[i], expected_res[i]);
}
}
#[test]
fn kmp_serch_1() {
let word : String = "ABCDABD".to_string();
let text : String = "ABC ABCDAB ABCDABCDABDE".to_string();
let expected_res : usize = 15;
let res : usize = kmp_serch(&word, &text);
assert_eq!(res, expected_res);
}
|
{
let mut m : usize = 0;
let mut i : usize = 0;
let table : Vec<i32> = compute_kmp_table(&word);
let text_len : usize = text.len();
let word_len : usize = word.len();
let word_chars : Vec<char> = word.chars().collect::<Vec<char>>();
let text_chars : Vec<char> = text.chars().collect::<Vec<char>>();
while m + i < text_len {
if word_chars[i] == text_chars[m + i] {
if i == word_len - 1 {
return m;
}
i += 1;
} else {
if table[i] > -1 {
m += i - (table[i] as usize);
i = table[i] as usize;
|
identifier_body
|
where_clauses_in_functions.rs
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags: -Zborrowck=mir
#![allow(dead_code)]
fn foo<'a, 'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32)
where
'a: 'b,
{
(x, y)
}
fn bar<'a, 'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) {
foo(x, y)
//~^ ERROR unsatisfied lifetime constraints
}
fn main()
|
{}
|
identifier_body
|
|
where_clauses_in_functions.rs
|
// Copyright 2017 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
|
// compile-flags: -Zborrowck=mir
#![allow(dead_code)]
fn foo<'a, 'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32)
where
'a: 'b,
{
(x, y)
}
fn bar<'a, 'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) {
foo(x, y)
//~^ ERROR unsatisfied lifetime constraints
}
fn main() {}
|
// option. This file may not be copied, modified, or distributed
// except according to those terms.
|
random_line_split
|
where_clauses_in_functions.rs
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags: -Zborrowck=mir
#![allow(dead_code)]
fn
|
<'a, 'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32)
where
'a: 'b,
{
(x, y)
}
fn bar<'a, 'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) {
foo(x, y)
//~^ ERROR unsatisfied lifetime constraints
}
fn main() {}
|
foo
|
identifier_name
|
lib.rs
|
//! Asynchronous sinks
//!
//! This crate contains the `Sink` trait which allows values to be sent
//! asynchronously.
#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_debug_implementations, missing_docs, rust_2018_idioms, unreachable_pub)]
// It cannot be included in the published code because this lints have false positives in the minimum required version.
#![cfg_attr(test, warn(single_use_lifetimes))]
#![doc(test(
no_crate_inject,
attr(
deny(warnings, rust_2018_idioms, single_use_lifetimes),
allow(dead_code, unused_assignments, unused_variables)
)
))]
#[cfg(feature = "alloc")]
extern crate alloc;
use core::ops::DerefMut;
use core::pin::Pin;
use core::task::{Context, Poll};
/// A `Sink` is a value into which other values can be sent, asynchronously.
///
/// Basic examples of sinks include the sending side of:
///
/// - Channels
/// - Sockets
/// - Pipes
///
/// In addition to such "primitive" sinks, it's typical to layer additional
/// functionality, such as buffering, on top of an existing sink.
///
/// Sending to a sink is "asynchronous" in the sense that the value may not be
/// sent in its entirety immediately. Instead, values are sent in a two-phase
/// way: first by initiating a send, and then by polling for completion. This
/// two-phase setup is analogous to buffered writing in synchronous code, where
/// writes often succeed immediately, but internally are buffered and are
/// *actually* written only upon flushing.
///
/// In addition, the `Sink` may be *full*, in which case it is not even possible
/// to start the sending process.
///
/// As with `Future` and `Stream`, the `Sink` trait is built from a few core
/// required methods, and a host of default methods for working in a
/// higher-level way. The `Sink::send_all` combinator is of particular
/// importance: you can use it to send an entire stream to a sink, which is
/// the simplest way to ultimately consume a stream.
#[must_use = "sinks do nothing unless polled"]
pub trait Sink<Item> {
/// The type of value produced by the sink when an error occurs.
type Error;
/// Attempts to prepare the `Sink` to receive a value.
///
/// This method must be called and return `Poll::Ready(Ok(()))` prior to
/// each call to `start_send`.
///
/// This method returns `Poll::Ready` once the underlying sink is ready to
/// receive data. If this method returns `Poll::Pending`, the current task
/// is registered to be notified (via `cx.waker().wake_by_ref()`) when `poll_ready`
/// should be called again.
///
/// In most cases, if the sink encounters an error, the sink will
/// permanently be unable to receive items.
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
/// Begin the process of sending a value to the sink.
/// Each call to this function must be preceded by a successful call to
/// `poll_ready` which returned `Poll::Ready(Ok(()))`.
///
/// As the name suggests, this method only *begins* the process of sending
/// the item. If the sink employs buffering, the item isn't fully processed
/// until the buffer is fully flushed. Since sinks are designed to work with
/// asynchronous I/O, the process of actually writing out the data to an
/// underlying object takes place asynchronously. **You *must* use
/// `poll_flush` or `poll_close` in order to guarantee completion of a
/// send**.
///
/// Implementations of `poll_ready` and `start_send` will usually involve
/// flushing behind the scenes in order to make room for new messages.
/// It is only necessary to call `poll_flush` if you need to guarantee that
/// *all* of the items placed into the `Sink` have been sent.
///
/// In most cases, if the sink encounters an error, the sink will
/// permanently be unable to receive items.
fn start_send(self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error>;
/// Flush any remaining output from this sink.
///
/// Returns `Poll::Ready(Ok(()))` when no buffered items remain. If this
/// value is returned then it is guaranteed that all previous values sent
/// via `start_send` have been flushed.
///
/// Returns `Poll::Pending` if there is more work left to do, in which
/// case the current task is scheduled (via `cx.waker().wake_by_ref()`) to wake up when
/// `poll_flush` should be called again.
///
/// In most cases, if the sink encounters an error, the sink will
/// permanently be unable to receive items.
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
/// Flush any remaining output and close this sink, if necessary.
///
/// Returns `Poll::Ready(Ok(()))` when no buffered items remain and the sink
/// has been successfully closed.
///
/// Returns `Poll::Pending` if there is more work left to do, in which
/// case the current task is scheduled (via `cx.waker().wake_by_ref()`) to wake up when
/// `poll_close` should be called again.
///
/// If this function encounters an error, the sink should be considered to
/// have failed permanently, and no more `Sink` methods should be called.
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
}
impl<S:?Sized + Sink<Item> + Unpin, Item> Sink<Item> for &mut S {
type Error = S::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_ready(cx)
}
fn start_send(mut self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> {
Pin::new(&mut **self).start_send(item)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_flush(cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_close(cx)
}
}
impl<P, Item> Sink<Item> for Pin<P>
where
P: DerefMut + Unpin,
P::Target: Sink<Item>,
{
type Error = <P::Target as Sink<Item>>::Error;
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.get_mut().as_mut().poll_ready(cx)
}
fn start_send(self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> {
self.get_mut().as_mut().start_send(item)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.get_mut().as_mut().poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.get_mut().as_mut().poll_close(cx)
}
}
#[cfg(feature = "alloc")]
mod if_alloc {
use super::*;
use core::convert::Infallible;
impl<T> Sink<T> for alloc::vec::Vec<T> {
type Error = Infallible;
fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
// TODO: impl<T> Unpin for Vec<T> {}
unsafe { self.get_unchecked_mut() }.push(item);
Ok(())
}
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn
|
(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
}
impl<T> Sink<T> for alloc::collections::VecDeque<T> {
type Error = Infallible;
fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
// TODO: impl<T> Unpin for Vec<T> {}
unsafe { self.get_unchecked_mut() }.push_back(item);
Ok(())
}
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
}
impl<S:?Sized + Sink<Item> + Unpin, Item> Sink<Item> for alloc::boxed::Box<S> {
type Error = S::Error;
fn poll_ready(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_ready(cx)
}
fn start_send(mut self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> {
Pin::new(&mut **self).start_send(item)
}
fn poll_flush(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_flush(cx)
}
fn poll_close(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_close(cx)
}
}
}
|
poll_close
|
identifier_name
|
lib.rs
|
//! Asynchronous sinks
//!
//! This crate contains the `Sink` trait which allows values to be sent
//! asynchronously.
#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_debug_implementations, missing_docs, rust_2018_idioms, unreachable_pub)]
// It cannot be included in the published code because this lints have false positives in the minimum required version.
#![cfg_attr(test, warn(single_use_lifetimes))]
#![doc(test(
no_crate_inject,
attr(
deny(warnings, rust_2018_idioms, single_use_lifetimes),
allow(dead_code, unused_assignments, unused_variables)
)
))]
#[cfg(feature = "alloc")]
extern crate alloc;
use core::ops::DerefMut;
use core::pin::Pin;
use core::task::{Context, Poll};
/// A `Sink` is a value into which other values can be sent, asynchronously.
///
/// Basic examples of sinks include the sending side of:
///
/// - Channels
/// - Sockets
/// - Pipes
///
/// In addition to such "primitive" sinks, it's typical to layer additional
/// functionality, such as buffering, on top of an existing sink.
///
/// Sending to a sink is "asynchronous" in the sense that the value may not be
/// sent in its entirety immediately. Instead, values are sent in a two-phase
/// way: first by initiating a send, and then by polling for completion. This
/// two-phase setup is analogous to buffered writing in synchronous code, where
/// writes often succeed immediately, but internally are buffered and are
/// *actually* written only upon flushing.
///
/// In addition, the `Sink` may be *full*, in which case it is not even possible
/// to start the sending process.
///
/// As with `Future` and `Stream`, the `Sink` trait is built from a few core
/// required methods, and a host of default methods for working in a
/// higher-level way. The `Sink::send_all` combinator is of particular
/// importance: you can use it to send an entire stream to a sink, which is
/// the simplest way to ultimately consume a stream.
#[must_use = "sinks do nothing unless polled"]
pub trait Sink<Item> {
/// The type of value produced by the sink when an error occurs.
type Error;
/// Attempts to prepare the `Sink` to receive a value.
///
/// This method must be called and return `Poll::Ready(Ok(()))` prior to
/// each call to `start_send`.
///
/// This method returns `Poll::Ready` once the underlying sink is ready to
/// receive data. If this method returns `Poll::Pending`, the current task
/// is registered to be notified (via `cx.waker().wake_by_ref()`) when `poll_ready`
/// should be called again.
///
/// In most cases, if the sink encounters an error, the sink will
/// permanently be unable to receive items.
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
/// Begin the process of sending a value to the sink.
/// Each call to this function must be preceded by a successful call to
/// `poll_ready` which returned `Poll::Ready(Ok(()))`.
///
/// As the name suggests, this method only *begins* the process of sending
/// the item. If the sink employs buffering, the item isn't fully processed
/// until the buffer is fully flushed. Since sinks are designed to work with
/// asynchronous I/O, the process of actually writing out the data to an
|
///
/// Implementations of `poll_ready` and `start_send` will usually involve
/// flushing behind the scenes in order to make room for new messages.
/// It is only necessary to call `poll_flush` if you need to guarantee that
/// *all* of the items placed into the `Sink` have been sent.
///
/// In most cases, if the sink encounters an error, the sink will
/// permanently be unable to receive items.
fn start_send(self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error>;
/// Flush any remaining output from this sink.
///
/// Returns `Poll::Ready(Ok(()))` when no buffered items remain. If this
/// value is returned then it is guaranteed that all previous values sent
/// via `start_send` have been flushed.
///
/// Returns `Poll::Pending` if there is more work left to do, in which
/// case the current task is scheduled (via `cx.waker().wake_by_ref()`) to wake up when
/// `poll_flush` should be called again.
///
/// In most cases, if the sink encounters an error, the sink will
/// permanently be unable to receive items.
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
/// Flush any remaining output and close this sink, if necessary.
///
/// Returns `Poll::Ready(Ok(()))` when no buffered items remain and the sink
/// has been successfully closed.
///
/// Returns `Poll::Pending` if there is more work left to do, in which
/// case the current task is scheduled (via `cx.waker().wake_by_ref()`) to wake up when
/// `poll_close` should be called again.
///
/// If this function encounters an error, the sink should be considered to
/// have failed permanently, and no more `Sink` methods should be called.
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
}
impl<S:?Sized + Sink<Item> + Unpin, Item> Sink<Item> for &mut S {
type Error = S::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_ready(cx)
}
fn start_send(mut self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> {
Pin::new(&mut **self).start_send(item)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_flush(cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_close(cx)
}
}
impl<P, Item> Sink<Item> for Pin<P>
where
P: DerefMut + Unpin,
P::Target: Sink<Item>,
{
type Error = <P::Target as Sink<Item>>::Error;
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.get_mut().as_mut().poll_ready(cx)
}
fn start_send(self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> {
self.get_mut().as_mut().start_send(item)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.get_mut().as_mut().poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.get_mut().as_mut().poll_close(cx)
}
}
#[cfg(feature = "alloc")]
mod if_alloc {
use super::*;
use core::convert::Infallible;
impl<T> Sink<T> for alloc::vec::Vec<T> {
type Error = Infallible;
fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
// TODO: impl<T> Unpin for Vec<T> {}
unsafe { self.get_unchecked_mut() }.push(item);
Ok(())
}
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
}
impl<T> Sink<T> for alloc::collections::VecDeque<T> {
type Error = Infallible;
fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
// TODO: impl<T> Unpin for Vec<T> {}
unsafe { self.get_unchecked_mut() }.push_back(item);
Ok(())
}
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
}
impl<S:?Sized + Sink<Item> + Unpin, Item> Sink<Item> for alloc::boxed::Box<S> {
type Error = S::Error;
fn poll_ready(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_ready(cx)
}
fn start_send(mut self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> {
Pin::new(&mut **self).start_send(item)
}
fn poll_flush(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_flush(cx)
}
fn poll_close(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_close(cx)
}
}
}
|
/// underlying object takes place asynchronously. **You *must* use
/// `poll_flush` or `poll_close` in order to guarantee completion of a
/// send**.
|
random_line_split
|
lib.rs
|
//! Asynchronous sinks
//!
//! This crate contains the `Sink` trait which allows values to be sent
//! asynchronously.
#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_debug_implementations, missing_docs, rust_2018_idioms, unreachable_pub)]
// It cannot be included in the published code because this lints have false positives in the minimum required version.
#![cfg_attr(test, warn(single_use_lifetimes))]
#![doc(test(
no_crate_inject,
attr(
deny(warnings, rust_2018_idioms, single_use_lifetimes),
allow(dead_code, unused_assignments, unused_variables)
)
))]
#[cfg(feature = "alloc")]
extern crate alloc;
use core::ops::DerefMut;
use core::pin::Pin;
use core::task::{Context, Poll};
/// A `Sink` is a value into which other values can be sent, asynchronously.
///
/// Basic examples of sinks include the sending side of:
///
/// - Channels
/// - Sockets
/// - Pipes
///
/// In addition to such "primitive" sinks, it's typical to layer additional
/// functionality, such as buffering, on top of an existing sink.
///
/// Sending to a sink is "asynchronous" in the sense that the value may not be
/// sent in its entirety immediately. Instead, values are sent in a two-phase
/// way: first by initiating a send, and then by polling for completion. This
/// two-phase setup is analogous to buffered writing in synchronous code, where
/// writes often succeed immediately, but internally are buffered and are
/// *actually* written only upon flushing.
///
/// In addition, the `Sink` may be *full*, in which case it is not even possible
/// to start the sending process.
///
/// As with `Future` and `Stream`, the `Sink` trait is built from a few core
/// required methods, and a host of default methods for working in a
/// higher-level way. The `Sink::send_all` combinator is of particular
/// importance: you can use it to send an entire stream to a sink, which is
/// the simplest way to ultimately consume a stream.
#[must_use = "sinks do nothing unless polled"]
pub trait Sink<Item> {
/// The type of value produced by the sink when an error occurs.
type Error;
/// Attempts to prepare the `Sink` to receive a value.
///
/// This method must be called and return `Poll::Ready(Ok(()))` prior to
/// each call to `start_send`.
///
/// This method returns `Poll::Ready` once the underlying sink is ready to
/// receive data. If this method returns `Poll::Pending`, the current task
/// is registered to be notified (via `cx.waker().wake_by_ref()`) when `poll_ready`
/// should be called again.
///
/// In most cases, if the sink encounters an error, the sink will
/// permanently be unable to receive items.
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
/// Begin the process of sending a value to the sink.
/// Each call to this function must be preceded by a successful call to
/// `poll_ready` which returned `Poll::Ready(Ok(()))`.
///
/// As the name suggests, this method only *begins* the process of sending
/// the item. If the sink employs buffering, the item isn't fully processed
/// until the buffer is fully flushed. Since sinks are designed to work with
/// asynchronous I/O, the process of actually writing out the data to an
/// underlying object takes place asynchronously. **You *must* use
/// `poll_flush` or `poll_close` in order to guarantee completion of a
/// send**.
///
/// Implementations of `poll_ready` and `start_send` will usually involve
/// flushing behind the scenes in order to make room for new messages.
/// It is only necessary to call `poll_flush` if you need to guarantee that
/// *all* of the items placed into the `Sink` have been sent.
///
/// In most cases, if the sink encounters an error, the sink will
/// permanently be unable to receive items.
fn start_send(self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error>;
/// Flush any remaining output from this sink.
///
/// Returns `Poll::Ready(Ok(()))` when no buffered items remain. If this
/// value is returned then it is guaranteed that all previous values sent
/// via `start_send` have been flushed.
///
/// Returns `Poll::Pending` if there is more work left to do, in which
/// case the current task is scheduled (via `cx.waker().wake_by_ref()`) to wake up when
/// `poll_flush` should be called again.
///
/// In most cases, if the sink encounters an error, the sink will
/// permanently be unable to receive items.
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
/// Flush any remaining output and close this sink, if necessary.
///
/// Returns `Poll::Ready(Ok(()))` when no buffered items remain and the sink
/// has been successfully closed.
///
/// Returns `Poll::Pending` if there is more work left to do, in which
/// case the current task is scheduled (via `cx.waker().wake_by_ref()`) to wake up when
/// `poll_close` should be called again.
///
/// If this function encounters an error, the sink should be considered to
/// have failed permanently, and no more `Sink` methods should be called.
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
}
impl<S:?Sized + Sink<Item> + Unpin, Item> Sink<Item> for &mut S {
type Error = S::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_ready(cx)
}
fn start_send(mut self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> {
Pin::new(&mut **self).start_send(item)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_flush(cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_close(cx)
}
}
impl<P, Item> Sink<Item> for Pin<P>
where
P: DerefMut + Unpin,
P::Target: Sink<Item>,
{
type Error = <P::Target as Sink<Item>>::Error;
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.get_mut().as_mut().poll_ready(cx)
}
fn start_send(self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> {
self.get_mut().as_mut().start_send(item)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.get_mut().as_mut().poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.get_mut().as_mut().poll_close(cx)
}
}
#[cfg(feature = "alloc")]
mod if_alloc {
use super::*;
use core::convert::Infallible;
impl<T> Sink<T> for alloc::vec::Vec<T> {
type Error = Infallible;
fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>
|
fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
// TODO: impl<T> Unpin for Vec<T> {}
unsafe { self.get_unchecked_mut() }.push(item);
Ok(())
}
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
}
impl<T> Sink<T> for alloc::collections::VecDeque<T> {
type Error = Infallible;
fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
// TODO: impl<T> Unpin for Vec<T> {}
unsafe { self.get_unchecked_mut() }.push_back(item);
Ok(())
}
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
}
impl<S:?Sized + Sink<Item> + Unpin, Item> Sink<Item> for alloc::boxed::Box<S> {
type Error = S::Error;
fn poll_ready(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_ready(cx)
}
fn start_send(mut self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> {
Pin::new(&mut **self).start_send(item)
}
fn poll_flush(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_flush(cx)
}
fn poll_close(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut **self).poll_close(cx)
}
}
}
|
{
Poll::Ready(Ok(()))
}
|
identifier_body
|
small_vector.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.
use self::SmallVectorRepr::*;
use self::IntoIterRepr::*;
use std::iter::{IntoIterator, FromIterator};
use std::mem;
use std::slice;
use std::vec;
use fold::MoveMap;
/// A vector type optimized for cases where the size is almost always 0 or 1
pub struct SmallVector<T> {
repr: SmallVectorRepr<T>,
}
enum SmallVectorRepr<T> {
Zero,
One(T),
Many(Vec<T>),
}
impl<T> FromIterator<T> for SmallVector<T> {
fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> SmallVector<T> {
let mut v = SmallVector::zero();
v.extend(iter);
v
}
}
impl<T> Extend<T> for SmallVector<T> {
fn extend<I: IntoIterator<Item=T>>(&mut self, iter: I) {
for val in iter {
self.push(val);
}
}
}
impl<T> SmallVector<T> {
pub fn zero() -> SmallVector<T> {
SmallVector { repr: Zero }
}
pub fn one(v: T) -> SmallVector<T> {
SmallVector { repr: One(v) }
}
pub fn many(vs: Vec<T>) -> SmallVector<T> {
SmallVector { repr: Many(vs) }
}
pub fn as_slice<'a>(&'a self) -> &'a [T] {
match self.repr {
Zero => {
let result: &[T] = &[];
result
}
One(ref v) => slice::ref_slice(v),
Many(ref vs) => vs
}
}
pub fn push(&mut self, v: T) {
match self.repr {
Zero => self.repr = One(v),
One(..) => {
let one = mem::replace(&mut self.repr, Zero);
match one {
One(v1) => mem::replace(&mut self.repr, Many(vec!(v1, v))),
_ => unreachable!()
};
}
Many(ref mut vs) => vs.push(v)
}
}
pub fn push_all(&mut self, other: SmallVector<T>) {
for v in other.into_iter() {
self.push(v);
}
}
pub fn get<'a>(&'a self, idx: usize) -> &'a T {
match self.repr {
One(ref v) if idx == 0 => v,
Many(ref vs) => &vs[idx],
_ => panic!("out of bounds access")
}
}
pub fn expect_one(self, err: &'static str) -> T {
match self.repr {
One(v) => v,
Many(v) => {
if v.len() == 1 {
v.into_iter().next().unwrap()
} else {
panic!(err)
}
}
_ => panic!(err)
}
}
/// Deprecated: use `into_iter`.
#[unstable(feature = "rustc_private")]
#[deprecated(since = "1.0.0", reason = "use into_iter")]
pub fn move_iter(self) -> IntoIter<T> {
self.into_iter()
}
pub fn into_iter(self) -> IntoIter<T> {
let repr = match self.repr {
Zero => ZeroIterator,
One(v) => OneIterator(v),
Many(vs) => ManyIterator(vs.into_iter())
};
IntoIter { repr: repr }
}
pub fn len(&self) -> usize {
match self.repr {
Zero => 0,
One(..) => 1,
Many(ref vals) => vals.len()
}
}
pub fn is_empty(&self) -> bool { self.len() == 0 }
}
pub struct IntoIter<T> {
repr: IntoIterRepr<T>,
}
enum IntoIterRepr<T> {
ZeroIterator,
OneIterator(T),
ManyIterator(vec::IntoIter<T>),
}
impl<T> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
match self.repr {
|
OneIterator(..) => {
let mut replacement = ZeroIterator;
mem::swap(&mut self.repr, &mut replacement);
match replacement {
OneIterator(v) => Some(v),
_ => unreachable!()
}
}
ManyIterator(ref mut inner) => inner.next()
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self.repr {
ZeroIterator => (0, Some(0)),
OneIterator(..) => (1, Some(1)),
ManyIterator(ref inner) => inner.size_hint()
}
}
}
impl<T> MoveMap<T> for SmallVector<T> {
fn move_map<F>(self, mut f: F) -> SmallVector<T> where F: FnMut(T) -> T {
let repr = match self.repr {
Zero => Zero,
One(v) => One(f(v)),
Many(vs) => Many(vs.move_map(f))
};
SmallVector { repr: repr }
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_len() {
let v: SmallVector<isize> = SmallVector::zero();
assert_eq!(0, v.len());
assert_eq!(1, SmallVector::one(1).len());
assert_eq!(5, SmallVector::many(vec![1, 2, 3, 4, 5]).len());
}
#[test]
fn test_push_get() {
let mut v = SmallVector::zero();
v.push(1);
assert_eq!(1, v.len());
assert_eq!(&1, v.get(0));
v.push(2);
assert_eq!(2, v.len());
assert_eq!(&2, v.get(1));
v.push(3);
assert_eq!(3, v.len());
assert_eq!(&3, v.get(2));
}
#[test]
fn test_from_iter() {
let v: SmallVector<isize> = (vec![1, 2, 3]).into_iter().collect();
assert_eq!(3, v.len());
assert_eq!(&1, v.get(0));
assert_eq!(&2, v.get(1));
assert_eq!(&3, v.get(2));
}
#[test]
fn test_move_iter() {
let v = SmallVector::zero();
let v: Vec<isize> = v.into_iter().collect();
assert_eq!(Vec::new(), v);
let v = SmallVector::one(1);
assert_eq!(vec![1], v.into_iter().collect::<Vec<_>>());
let v = SmallVector::many(vec![1, 2, 3]);
assert_eq!(vec!(1, 2, 3), v.into_iter().collect::<Vec<_>>());
}
#[test]
#[should_fail]
fn test_expect_one_zero() {
let _: isize = SmallVector::zero().expect_one("");
}
#[test]
#[should_fail]
fn test_expect_one_many() {
SmallVector::many(vec!(1, 2)).expect_one("");
}
#[test]
fn test_expect_one_one() {
assert_eq!(1, SmallVector::one(1).expect_one(""));
assert_eq!(1, SmallVector::many(vec!(1)).expect_one(""));
}
}
|
ZeroIterator => None,
|
random_line_split
|
small_vector.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.
use self::SmallVectorRepr::*;
use self::IntoIterRepr::*;
use std::iter::{IntoIterator, FromIterator};
use std::mem;
use std::slice;
use std::vec;
use fold::MoveMap;
/// A vector type optimized for cases where the size is almost always 0 or 1
pub struct SmallVector<T> {
repr: SmallVectorRepr<T>,
}
enum SmallVectorRepr<T> {
Zero,
One(T),
Many(Vec<T>),
}
impl<T> FromIterator<T> for SmallVector<T> {
fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> SmallVector<T> {
let mut v = SmallVector::zero();
v.extend(iter);
v
}
}
impl<T> Extend<T> for SmallVector<T> {
fn extend<I: IntoIterator<Item=T>>(&mut self, iter: I) {
for val in iter {
self.push(val);
}
}
}
impl<T> SmallVector<T> {
pub fn zero() -> SmallVector<T> {
SmallVector { repr: Zero }
}
pub fn one(v: T) -> SmallVector<T> {
SmallVector { repr: One(v) }
}
pub fn many(vs: Vec<T>) -> SmallVector<T> {
SmallVector { repr: Many(vs) }
}
pub fn as_slice<'a>(&'a self) -> &'a [T] {
match self.repr {
Zero => {
let result: &[T] = &[];
result
}
One(ref v) => slice::ref_slice(v),
Many(ref vs) => vs
}
}
pub fn push(&mut self, v: T) {
match self.repr {
Zero => self.repr = One(v),
One(..) => {
let one = mem::replace(&mut self.repr, Zero);
match one {
One(v1) => mem::replace(&mut self.repr, Many(vec!(v1, v))),
_ => unreachable!()
};
}
Many(ref mut vs) => vs.push(v)
}
}
pub fn push_all(&mut self, other: SmallVector<T>) {
for v in other.into_iter() {
self.push(v);
}
}
pub fn get<'a>(&'a self, idx: usize) -> &'a T {
match self.repr {
One(ref v) if idx == 0 => v,
Many(ref vs) => &vs[idx],
_ => panic!("out of bounds access")
}
}
pub fn expect_one(self, err: &'static str) -> T {
match self.repr {
One(v) => v,
Many(v) => {
if v.len() == 1 {
v.into_iter().next().unwrap()
} else {
panic!(err)
}
}
_ => panic!(err)
}
}
/// Deprecated: use `into_iter`.
#[unstable(feature = "rustc_private")]
#[deprecated(since = "1.0.0", reason = "use into_iter")]
pub fn move_iter(self) -> IntoIter<T> {
self.into_iter()
}
pub fn into_iter(self) -> IntoIter<T> {
let repr = match self.repr {
Zero => ZeroIterator,
One(v) => OneIterator(v),
Many(vs) => ManyIterator(vs.into_iter())
};
IntoIter { repr: repr }
}
pub fn len(&self) -> usize {
match self.repr {
Zero => 0,
One(..) => 1,
Many(ref vals) => vals.len()
}
}
pub fn is_empty(&self) -> bool { self.len() == 0 }
}
pub struct IntoIter<T> {
repr: IntoIterRepr<T>,
}
enum IntoIterRepr<T> {
ZeroIterator,
OneIterator(T),
ManyIterator(vec::IntoIter<T>),
}
impl<T> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
match self.repr {
ZeroIterator => None,
OneIterator(..) => {
let mut replacement = ZeroIterator;
mem::swap(&mut self.repr, &mut replacement);
match replacement {
OneIterator(v) => Some(v),
_ => unreachable!()
}
}
ManyIterator(ref mut inner) => inner.next()
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self.repr {
ZeroIterator => (0, Some(0)),
OneIterator(..) => (1, Some(1)),
ManyIterator(ref inner) => inner.size_hint()
}
}
}
impl<T> MoveMap<T> for SmallVector<T> {
fn move_map<F>(self, mut f: F) -> SmallVector<T> where F: FnMut(T) -> T {
let repr = match self.repr {
Zero => Zero,
One(v) => One(f(v)),
Many(vs) => Many(vs.move_map(f))
};
SmallVector { repr: repr }
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_len() {
let v: SmallVector<isize> = SmallVector::zero();
assert_eq!(0, v.len());
assert_eq!(1, SmallVector::one(1).len());
assert_eq!(5, SmallVector::many(vec![1, 2, 3, 4, 5]).len());
}
#[test]
fn test_push_get() {
let mut v = SmallVector::zero();
v.push(1);
assert_eq!(1, v.len());
assert_eq!(&1, v.get(0));
v.push(2);
assert_eq!(2, v.len());
assert_eq!(&2, v.get(1));
v.push(3);
assert_eq!(3, v.len());
assert_eq!(&3, v.get(2));
}
#[test]
fn test_from_iter() {
let v: SmallVector<isize> = (vec![1, 2, 3]).into_iter().collect();
assert_eq!(3, v.len());
assert_eq!(&1, v.get(0));
assert_eq!(&2, v.get(1));
assert_eq!(&3, v.get(2));
}
#[test]
fn test_move_iter() {
let v = SmallVector::zero();
let v: Vec<isize> = v.into_iter().collect();
assert_eq!(Vec::new(), v);
let v = SmallVector::one(1);
assert_eq!(vec![1], v.into_iter().collect::<Vec<_>>());
let v = SmallVector::many(vec![1, 2, 3]);
assert_eq!(vec!(1, 2, 3), v.into_iter().collect::<Vec<_>>());
}
#[test]
#[should_fail]
fn test_expect_one_zero() {
let _: isize = SmallVector::zero().expect_one("");
}
#[test]
#[should_fail]
fn test_expect_one_many()
|
#[test]
fn test_expect_one_one() {
assert_eq!(1, SmallVector::one(1).expect_one(""));
assert_eq!(1, SmallVector::many(vec!(1)).expect_one(""));
}
}
|
{
SmallVector::many(vec!(1, 2)).expect_one("");
}
|
identifier_body
|
small_vector.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.
use self::SmallVectorRepr::*;
use self::IntoIterRepr::*;
use std::iter::{IntoIterator, FromIterator};
use std::mem;
use std::slice;
use std::vec;
use fold::MoveMap;
/// A vector type optimized for cases where the size is almost always 0 or 1
pub struct SmallVector<T> {
repr: SmallVectorRepr<T>,
}
enum SmallVectorRepr<T> {
Zero,
One(T),
Many(Vec<T>),
}
impl<T> FromIterator<T> for SmallVector<T> {
fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> SmallVector<T> {
let mut v = SmallVector::zero();
v.extend(iter);
v
}
}
impl<T> Extend<T> for SmallVector<T> {
fn extend<I: IntoIterator<Item=T>>(&mut self, iter: I) {
for val in iter {
self.push(val);
}
}
}
impl<T> SmallVector<T> {
pub fn zero() -> SmallVector<T> {
SmallVector { repr: Zero }
}
pub fn one(v: T) -> SmallVector<T> {
SmallVector { repr: One(v) }
}
pub fn many(vs: Vec<T>) -> SmallVector<T> {
SmallVector { repr: Many(vs) }
}
pub fn as_slice<'a>(&'a self) -> &'a [T] {
match self.repr {
Zero => {
let result: &[T] = &[];
result
}
One(ref v) => slice::ref_slice(v),
Many(ref vs) => vs
}
}
pub fn push(&mut self, v: T) {
match self.repr {
Zero => self.repr = One(v),
One(..) => {
let one = mem::replace(&mut self.repr, Zero);
match one {
One(v1) => mem::replace(&mut self.repr, Many(vec!(v1, v))),
_ => unreachable!()
};
}
Many(ref mut vs) => vs.push(v)
}
}
pub fn push_all(&mut self, other: SmallVector<T>) {
for v in other.into_iter() {
self.push(v);
}
}
pub fn get<'a>(&'a self, idx: usize) -> &'a T {
match self.repr {
One(ref v) if idx == 0 => v,
Many(ref vs) => &vs[idx],
_ => panic!("out of bounds access")
}
}
pub fn expect_one(self, err: &'static str) -> T {
match self.repr {
One(v) => v,
Many(v) => {
if v.len() == 1 {
v.into_iter().next().unwrap()
} else {
panic!(err)
}
}
_ => panic!(err)
}
}
/// Deprecated: use `into_iter`.
#[unstable(feature = "rustc_private")]
#[deprecated(since = "1.0.0", reason = "use into_iter")]
pub fn move_iter(self) -> IntoIter<T> {
self.into_iter()
}
pub fn into_iter(self) -> IntoIter<T> {
let repr = match self.repr {
Zero => ZeroIterator,
One(v) => OneIterator(v),
Many(vs) => ManyIterator(vs.into_iter())
};
IntoIter { repr: repr }
}
pub fn len(&self) -> usize {
match self.repr {
Zero => 0,
One(..) => 1,
Many(ref vals) => vals.len()
}
}
pub fn is_empty(&self) -> bool { self.len() == 0 }
}
pub struct IntoIter<T> {
repr: IntoIterRepr<T>,
}
enum IntoIterRepr<T> {
ZeroIterator,
OneIterator(T),
ManyIterator(vec::IntoIter<T>),
}
impl<T> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
match self.repr {
ZeroIterator => None,
OneIterator(..) => {
let mut replacement = ZeroIterator;
mem::swap(&mut self.repr, &mut replacement);
match replacement {
OneIterator(v) => Some(v),
_ => unreachable!()
}
}
ManyIterator(ref mut inner) => inner.next()
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self.repr {
ZeroIterator => (0, Some(0)),
OneIterator(..) => (1, Some(1)),
ManyIterator(ref inner) => inner.size_hint()
}
}
}
impl<T> MoveMap<T> for SmallVector<T> {
fn move_map<F>(self, mut f: F) -> SmallVector<T> where F: FnMut(T) -> T {
let repr = match self.repr {
Zero => Zero,
One(v) => One(f(v)),
Many(vs) => Many(vs.move_map(f))
};
SmallVector { repr: repr }
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_len() {
let v: SmallVector<isize> = SmallVector::zero();
assert_eq!(0, v.len());
assert_eq!(1, SmallVector::one(1).len());
assert_eq!(5, SmallVector::many(vec![1, 2, 3, 4, 5]).len());
}
#[test]
fn test_push_get() {
let mut v = SmallVector::zero();
v.push(1);
assert_eq!(1, v.len());
assert_eq!(&1, v.get(0));
v.push(2);
assert_eq!(2, v.len());
assert_eq!(&2, v.get(1));
v.push(3);
assert_eq!(3, v.len());
assert_eq!(&3, v.get(2));
}
#[test]
fn test_from_iter() {
let v: SmallVector<isize> = (vec![1, 2, 3]).into_iter().collect();
assert_eq!(3, v.len());
assert_eq!(&1, v.get(0));
assert_eq!(&2, v.get(1));
assert_eq!(&3, v.get(2));
}
#[test]
fn test_move_iter() {
let v = SmallVector::zero();
let v: Vec<isize> = v.into_iter().collect();
assert_eq!(Vec::new(), v);
let v = SmallVector::one(1);
assert_eq!(vec![1], v.into_iter().collect::<Vec<_>>());
let v = SmallVector::many(vec![1, 2, 3]);
assert_eq!(vec!(1, 2, 3), v.into_iter().collect::<Vec<_>>());
}
#[test]
#[should_fail]
fn test_expect_one_zero() {
let _: isize = SmallVector::zero().expect_one("");
}
#[test]
#[should_fail]
fn test_expect_one_many() {
SmallVector::many(vec!(1, 2)).expect_one("");
}
#[test]
fn
|
() {
assert_eq!(1, SmallVector::one(1).expect_one(""));
assert_eq!(1, SmallVector::many(vec!(1)).expect_one(""));
}
}
|
test_expect_one_one
|
identifier_name
|
taskstore.rs
|
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use std::collections::BTreeMap;
use std::io::BufRead;
use std::result::Result as RResult;
use toml::Value;
use uuid::Uuid;
use task_hookrs::task::Task as TTask;
use task_hookrs::import::{import_task, import_tasks};
use libimagstore::store::{FileLockEntry, Store};
use libimagstore::storeid::{IntoStoreId, StoreIdIterator};
use module_path::ModuleEntryPath;
use error::TodoErrorKind as TEK;
use error::TodoError as TE;
use error::Result;
use error::ResultExt;
/// Task struct containing a `FileLockEntry`
pub trait TaskStore<'a> {
fn import_task_from_reader<R: BufRead>(&'a self, r: R) -> Result<(FileLockEntry<'a>, String, Uuid)>;
fn get_task_from_import<R: BufRead>(&'a self, r: R) -> Result<RResult<FileLockEntry<'a>, String>>;
fn get_task_from_string(&'a self, s: String) -> Result<RResult<FileLockEntry<'a>, String>>;
fn get_task_from_uuid(&'a self, uuid: Uuid) -> Result<Option<FileLockEntry<'a>>>;
fn retrieve_task_from_import<R: BufRead>(&'a self, r: R) -> Result<FileLockEntry<'a>>;
fn retrieve_task_from_string(&'a self, s: String) -> Result<FileLockEntry<'a>>;
fn delete_tasks_by_imports<R: BufRead>(&self, r: R) -> Result<()>;
fn delete_task_by_uuid(&self, uuid: Uuid) -> Result<()>;
fn all_tasks(&self) -> Result<StoreIdIterator>;
fn new_from_twtask(&'a self, task: TTask) -> Result<FileLockEntry<'a>>;
}
impl<'a> TaskStore<'a> for Store {
fn import_task_from_reader<R: BufRead>(&'a self, mut r: R) -> Result<(FileLockEntry<'a>, String, Uuid)> {
let mut line = String::new();
r.read_line(&mut line).map_err(|_| TE::from_kind(TEK::UTF8Error))?;
import_task(&line.as_str())
.map_err(|_| TE::from_kind(TEK::ImportError))
.and_then(|t| {
let uuid = t.uuid().clone();
self.new_from_twtask(t).map(|t| (t, line, uuid))
})
}
/// Get a task from an import string. That is: read the imported string, get the UUID from it
/// and try to load this UUID from store.
///
/// Possible return values are:
///
/// * Ok(Ok(Task))
/// * Ok(Err(String)) - where the String is the String read from the `r` parameter
/// * Err(_) - where the error is an error that happened during evaluation
///
fn get_task_from_import<R: BufRead>(&'a self, mut r: R) -> Result<RResult<FileLockEntry<'a>, String>> {
let mut line = String::new();
r.read_line(&mut line).chain_err(|| TEK::UTF8Error)?;
self.get_task_from_string(line)
}
/// Get a task from a String. The String is expected to contain the JSON-representation of the
/// Task to get from the store (only the UUID really matters in this case)
///
/// For an explanation on the return values see `Task::get_from_import()`.
fn get_task_from_string(&'a self, s: String) -> Result<RResult<FileLockEntry<'a>, String>> {
import_task(s.as_str())
.map_err(|_| TE::from_kind(TEK::ImportError))
.map(|t| t.uuid().clone())
.and_then(|uuid| self.get_task_from_uuid(uuid))
.and_then(|o| match o {
None => Ok(Err(s)),
Some(t) => Ok(Ok(t)),
})
}
/// Get a task from an UUID.
///
/// If there is no task with this UUID, this returns `Ok(None)`.
fn get_task_from_uuid(&'a self, uuid: Uuid) -> Result<Option<FileLockEntry<'a>>> {
ModuleEntryPath::new(format!("taskwarrior/{}", uuid))
.into_storeid()
.and_then(|store_id| self.get(store_id))
.chain_err(|| TEK::StoreError)
}
/// Same as Task::get_from_import() but uses Store::retrieve() rather than Store::get(), to
/// implicitely create the task if it does not exist.
fn
|
<R: BufRead>(&'a self, mut r: R) -> Result<FileLockEntry<'a>> {
let mut line = String::new();
r.read_line(&mut line).chain_err(|| TEK::UTF8Error)?;
self.retrieve_task_from_string(line)
}
/// Retrieve a task from a String. The String is expected to contain the JSON-representation of
/// the Task to retrieve from the store (only the UUID really matters in this case)
fn retrieve_task_from_string(&'a self, s: String) -> Result<FileLockEntry<'a>> {
self.get_task_from_string(s)
.and_then(|opt| match opt {
Ok(task) => Ok(task),
Err(string) => import_task(string.as_str())
.map_err(|_| TE::from_kind(TEK::ImportError))
.and_then(|t| self.new_from_twtask(t)),
})
}
fn delete_tasks_by_imports<R: BufRead>(&self, r: R) -> Result<()> {
use serde_json::ser::to_string as serde_to_string;
use task_hookrs::status::TaskStatus;
for (counter, res_ttask) in import_tasks(r).into_iter().enumerate() {
match res_ttask {
Ok(ttask) => {
if counter % 2 == 1 {
// Only every second task is needed, the first one is the
// task before the change, and the second one after
// the change. The (maybe modified) second one is
// expected by taskwarrior.
match serde_to_string(&ttask).chain_err(|| TEK::ImportError) {
// use println!() here, as we talk with TW
Ok(val) => println!("{}", val),
Err(e) => return Err(e),
}
// Taskwarrior does not have the concept of deleted tasks, but only modified
// ones.
//
// Here we check if the status of a task is deleted and if yes, we delete it
// from the store.
if *ttask.status() == TaskStatus::Deleted {
match self.delete_task_by_uuid(*ttask.uuid()) {
Ok(_) => info!("Deleted task {}", *ttask.uuid()),
Err(e) => return Err(e),
}
}
} // end if c % 2
},
Err(_) => return Err(TE::from_kind(TEK::ImportError)),
}
}
Ok(())
}
fn delete_task_by_uuid(&self, uuid: Uuid) -> Result<()> {
ModuleEntryPath::new(format!("taskwarrior/{}", uuid))
.into_storeid()
.and_then(|id| self.delete(id))
.chain_err(|| TEK::StoreError)
}
fn all_tasks(&self) -> Result<StoreIdIterator> {
self.retrieve_for_module("todo/taskwarrior")
.chain_err(|| TEK::StoreError)
}
fn new_from_twtask(&'a self, task: TTask) -> Result<FileLockEntry<'a>> {
use toml_query::read::TomlValueReadExt;
use toml_query::set::TomlValueSetExt;
let uuid = task.uuid();
ModuleEntryPath::new(format!("taskwarrior/{}", uuid))
.into_storeid()
.chain_err(|| TEK::StoreIdError)
.and_then(|id| {
self.retrieve(id)
.chain_err(|| TEK::StoreError)
.and_then(|mut fle| {
{
let hdr = fle.get_header_mut();
if hdr.read("todo").chain_err(|| TEK::StoreError)?.is_none() {
hdr
.set("todo", Value::Table(BTreeMap::new()))
.chain_err(|| TEK::StoreError)?;
}
hdr.set("todo.uuid", Value::String(format!("{}",uuid)))
.chain_err(|| TEK::StoreError)?;
}
// If none of the errors above have returned the function, everything is fine
Ok(fle)
})
})
}
}
|
retrieve_task_from_import
|
identifier_name
|
taskstore.rs
|
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use std::collections::BTreeMap;
use std::io::BufRead;
use std::result::Result as RResult;
use toml::Value;
use uuid::Uuid;
use task_hookrs::task::Task as TTask;
use task_hookrs::import::{import_task, import_tasks};
use libimagstore::store::{FileLockEntry, Store};
use libimagstore::storeid::{IntoStoreId, StoreIdIterator};
use module_path::ModuleEntryPath;
use error::TodoErrorKind as TEK;
use error::TodoError as TE;
use error::Result;
use error::ResultExt;
/// Task struct containing a `FileLockEntry`
pub trait TaskStore<'a> {
fn import_task_from_reader<R: BufRead>(&'a self, r: R) -> Result<(FileLockEntry<'a>, String, Uuid)>;
fn get_task_from_import<R: BufRead>(&'a self, r: R) -> Result<RResult<FileLockEntry<'a>, String>>;
fn get_task_from_string(&'a self, s: String) -> Result<RResult<FileLockEntry<'a>, String>>;
fn get_task_from_uuid(&'a self, uuid: Uuid) -> Result<Option<FileLockEntry<'a>>>;
fn retrieve_task_from_import<R: BufRead>(&'a self, r: R) -> Result<FileLockEntry<'a>>;
fn retrieve_task_from_string(&'a self, s: String) -> Result<FileLockEntry<'a>>;
fn delete_tasks_by_imports<R: BufRead>(&self, r: R) -> Result<()>;
fn delete_task_by_uuid(&self, uuid: Uuid) -> Result<()>;
fn all_tasks(&self) -> Result<StoreIdIterator>;
fn new_from_twtask(&'a self, task: TTask) -> Result<FileLockEntry<'a>>;
}
impl<'a> TaskStore<'a> for Store {
fn import_task_from_reader<R: BufRead>(&'a self, mut r: R) -> Result<(FileLockEntry<'a>, String, Uuid)> {
let mut line = String::new();
r.read_line(&mut line).map_err(|_| TE::from_kind(TEK::UTF8Error))?;
import_task(&line.as_str())
.map_err(|_| TE::from_kind(TEK::ImportError))
.and_then(|t| {
let uuid = t.uuid().clone();
self.new_from_twtask(t).map(|t| (t, line, uuid))
})
}
/// Get a task from an import string. That is: read the imported string, get the UUID from it
/// and try to load this UUID from store.
///
/// Possible return values are:
///
/// * Ok(Ok(Task))
/// * Ok(Err(String)) - where the String is the String read from the `r` parameter
/// * Err(_) - where the error is an error that happened during evaluation
///
fn get_task_from_import<R: BufRead>(&'a self, mut r: R) -> Result<RResult<FileLockEntry<'a>, String>> {
let mut line = String::new();
r.read_line(&mut line).chain_err(|| TEK::UTF8Error)?;
self.get_task_from_string(line)
}
/// Get a task from a String. The String is expected to contain the JSON-representation of the
/// Task to get from the store (only the UUID really matters in this case)
///
/// For an explanation on the return values see `Task::get_from_import()`.
fn get_task_from_string(&'a self, s: String) -> Result<RResult<FileLockEntry<'a>, String>>
|
/// Get a task from an UUID.
///
/// If there is no task with this UUID, this returns `Ok(None)`.
fn get_task_from_uuid(&'a self, uuid: Uuid) -> Result<Option<FileLockEntry<'a>>> {
ModuleEntryPath::new(format!("taskwarrior/{}", uuid))
.into_storeid()
.and_then(|store_id| self.get(store_id))
.chain_err(|| TEK::StoreError)
}
/// Same as Task::get_from_import() but uses Store::retrieve() rather than Store::get(), to
/// implicitely create the task if it does not exist.
fn retrieve_task_from_import<R: BufRead>(&'a self, mut r: R) -> Result<FileLockEntry<'a>> {
let mut line = String::new();
r.read_line(&mut line).chain_err(|| TEK::UTF8Error)?;
self.retrieve_task_from_string(line)
}
/// Retrieve a task from a String. The String is expected to contain the JSON-representation of
/// the Task to retrieve from the store (only the UUID really matters in this case)
fn retrieve_task_from_string(&'a self, s: String) -> Result<FileLockEntry<'a>> {
self.get_task_from_string(s)
.and_then(|opt| match opt {
Ok(task) => Ok(task),
Err(string) => import_task(string.as_str())
.map_err(|_| TE::from_kind(TEK::ImportError))
.and_then(|t| self.new_from_twtask(t)),
})
}
fn delete_tasks_by_imports<R: BufRead>(&self, r: R) -> Result<()> {
use serde_json::ser::to_string as serde_to_string;
use task_hookrs::status::TaskStatus;
for (counter, res_ttask) in import_tasks(r).into_iter().enumerate() {
match res_ttask {
Ok(ttask) => {
if counter % 2 == 1 {
// Only every second task is needed, the first one is the
// task before the change, and the second one after
// the change. The (maybe modified) second one is
// expected by taskwarrior.
match serde_to_string(&ttask).chain_err(|| TEK::ImportError) {
// use println!() here, as we talk with TW
Ok(val) => println!("{}", val),
Err(e) => return Err(e),
}
// Taskwarrior does not have the concept of deleted tasks, but only modified
// ones.
//
// Here we check if the status of a task is deleted and if yes, we delete it
// from the store.
if *ttask.status() == TaskStatus::Deleted {
match self.delete_task_by_uuid(*ttask.uuid()) {
Ok(_) => info!("Deleted task {}", *ttask.uuid()),
Err(e) => return Err(e),
}
}
} // end if c % 2
},
Err(_) => return Err(TE::from_kind(TEK::ImportError)),
}
}
Ok(())
}
fn delete_task_by_uuid(&self, uuid: Uuid) -> Result<()> {
ModuleEntryPath::new(format!("taskwarrior/{}", uuid))
.into_storeid()
.and_then(|id| self.delete(id))
.chain_err(|| TEK::StoreError)
}
fn all_tasks(&self) -> Result<StoreIdIterator> {
self.retrieve_for_module("todo/taskwarrior")
.chain_err(|| TEK::StoreError)
}
fn new_from_twtask(&'a self, task: TTask) -> Result<FileLockEntry<'a>> {
use toml_query::read::TomlValueReadExt;
use toml_query::set::TomlValueSetExt;
let uuid = task.uuid();
ModuleEntryPath::new(format!("taskwarrior/{}", uuid))
.into_storeid()
.chain_err(|| TEK::StoreIdError)
.and_then(|id| {
self.retrieve(id)
.chain_err(|| TEK::StoreError)
.and_then(|mut fle| {
{
let hdr = fle.get_header_mut();
if hdr.read("todo").chain_err(|| TEK::StoreError)?.is_none() {
hdr
.set("todo", Value::Table(BTreeMap::new()))
.chain_err(|| TEK::StoreError)?;
}
hdr.set("todo.uuid", Value::String(format!("{}",uuid)))
.chain_err(|| TEK::StoreError)?;
}
// If none of the errors above have returned the function, everything is fine
Ok(fle)
})
})
}
}
|
{
import_task(s.as_str())
.map_err(|_| TE::from_kind(TEK::ImportError))
.map(|t| t.uuid().clone())
.and_then(|uuid| self.get_task_from_uuid(uuid))
.and_then(|o| match o {
None => Ok(Err(s)),
Some(t) => Ok(Ok(t)),
})
}
|
identifier_body
|
taskstore.rs
|
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use std::collections::BTreeMap;
use std::io::BufRead;
use std::result::Result as RResult;
use toml::Value;
use uuid::Uuid;
|
use libimagstore::storeid::{IntoStoreId, StoreIdIterator};
use module_path::ModuleEntryPath;
use error::TodoErrorKind as TEK;
use error::TodoError as TE;
use error::Result;
use error::ResultExt;
/// Task struct containing a `FileLockEntry`
pub trait TaskStore<'a> {
fn import_task_from_reader<R: BufRead>(&'a self, r: R) -> Result<(FileLockEntry<'a>, String, Uuid)>;
fn get_task_from_import<R: BufRead>(&'a self, r: R) -> Result<RResult<FileLockEntry<'a>, String>>;
fn get_task_from_string(&'a self, s: String) -> Result<RResult<FileLockEntry<'a>, String>>;
fn get_task_from_uuid(&'a self, uuid: Uuid) -> Result<Option<FileLockEntry<'a>>>;
fn retrieve_task_from_import<R: BufRead>(&'a self, r: R) -> Result<FileLockEntry<'a>>;
fn retrieve_task_from_string(&'a self, s: String) -> Result<FileLockEntry<'a>>;
fn delete_tasks_by_imports<R: BufRead>(&self, r: R) -> Result<()>;
fn delete_task_by_uuid(&self, uuid: Uuid) -> Result<()>;
fn all_tasks(&self) -> Result<StoreIdIterator>;
fn new_from_twtask(&'a self, task: TTask) -> Result<FileLockEntry<'a>>;
}
impl<'a> TaskStore<'a> for Store {
fn import_task_from_reader<R: BufRead>(&'a self, mut r: R) -> Result<(FileLockEntry<'a>, String, Uuid)> {
let mut line = String::new();
r.read_line(&mut line).map_err(|_| TE::from_kind(TEK::UTF8Error))?;
import_task(&line.as_str())
.map_err(|_| TE::from_kind(TEK::ImportError))
.and_then(|t| {
let uuid = t.uuid().clone();
self.new_from_twtask(t).map(|t| (t, line, uuid))
})
}
/// Get a task from an import string. That is: read the imported string, get the UUID from it
/// and try to load this UUID from store.
///
/// Possible return values are:
///
/// * Ok(Ok(Task))
/// * Ok(Err(String)) - where the String is the String read from the `r` parameter
/// * Err(_) - where the error is an error that happened during evaluation
///
fn get_task_from_import<R: BufRead>(&'a self, mut r: R) -> Result<RResult<FileLockEntry<'a>, String>> {
let mut line = String::new();
r.read_line(&mut line).chain_err(|| TEK::UTF8Error)?;
self.get_task_from_string(line)
}
/// Get a task from a String. The String is expected to contain the JSON-representation of the
/// Task to get from the store (only the UUID really matters in this case)
///
/// For an explanation on the return values see `Task::get_from_import()`.
fn get_task_from_string(&'a self, s: String) -> Result<RResult<FileLockEntry<'a>, String>> {
import_task(s.as_str())
.map_err(|_| TE::from_kind(TEK::ImportError))
.map(|t| t.uuid().clone())
.and_then(|uuid| self.get_task_from_uuid(uuid))
.and_then(|o| match o {
None => Ok(Err(s)),
Some(t) => Ok(Ok(t)),
})
}
/// Get a task from an UUID.
///
/// If there is no task with this UUID, this returns `Ok(None)`.
fn get_task_from_uuid(&'a self, uuid: Uuid) -> Result<Option<FileLockEntry<'a>>> {
ModuleEntryPath::new(format!("taskwarrior/{}", uuid))
.into_storeid()
.and_then(|store_id| self.get(store_id))
.chain_err(|| TEK::StoreError)
}
/// Same as Task::get_from_import() but uses Store::retrieve() rather than Store::get(), to
/// implicitely create the task if it does not exist.
fn retrieve_task_from_import<R: BufRead>(&'a self, mut r: R) -> Result<FileLockEntry<'a>> {
let mut line = String::new();
r.read_line(&mut line).chain_err(|| TEK::UTF8Error)?;
self.retrieve_task_from_string(line)
}
/// Retrieve a task from a String. The String is expected to contain the JSON-representation of
/// the Task to retrieve from the store (only the UUID really matters in this case)
fn retrieve_task_from_string(&'a self, s: String) -> Result<FileLockEntry<'a>> {
self.get_task_from_string(s)
.and_then(|opt| match opt {
Ok(task) => Ok(task),
Err(string) => import_task(string.as_str())
.map_err(|_| TE::from_kind(TEK::ImportError))
.and_then(|t| self.new_from_twtask(t)),
})
}
fn delete_tasks_by_imports<R: BufRead>(&self, r: R) -> Result<()> {
use serde_json::ser::to_string as serde_to_string;
use task_hookrs::status::TaskStatus;
for (counter, res_ttask) in import_tasks(r).into_iter().enumerate() {
match res_ttask {
Ok(ttask) => {
if counter % 2 == 1 {
// Only every second task is needed, the first one is the
// task before the change, and the second one after
// the change. The (maybe modified) second one is
// expected by taskwarrior.
match serde_to_string(&ttask).chain_err(|| TEK::ImportError) {
// use println!() here, as we talk with TW
Ok(val) => println!("{}", val),
Err(e) => return Err(e),
}
// Taskwarrior does not have the concept of deleted tasks, but only modified
// ones.
//
// Here we check if the status of a task is deleted and if yes, we delete it
// from the store.
if *ttask.status() == TaskStatus::Deleted {
match self.delete_task_by_uuid(*ttask.uuid()) {
Ok(_) => info!("Deleted task {}", *ttask.uuid()),
Err(e) => return Err(e),
}
}
} // end if c % 2
},
Err(_) => return Err(TE::from_kind(TEK::ImportError)),
}
}
Ok(())
}
fn delete_task_by_uuid(&self, uuid: Uuid) -> Result<()> {
ModuleEntryPath::new(format!("taskwarrior/{}", uuid))
.into_storeid()
.and_then(|id| self.delete(id))
.chain_err(|| TEK::StoreError)
}
fn all_tasks(&self) -> Result<StoreIdIterator> {
self.retrieve_for_module("todo/taskwarrior")
.chain_err(|| TEK::StoreError)
}
fn new_from_twtask(&'a self, task: TTask) -> Result<FileLockEntry<'a>> {
use toml_query::read::TomlValueReadExt;
use toml_query::set::TomlValueSetExt;
let uuid = task.uuid();
ModuleEntryPath::new(format!("taskwarrior/{}", uuid))
.into_storeid()
.chain_err(|| TEK::StoreIdError)
.and_then(|id| {
self.retrieve(id)
.chain_err(|| TEK::StoreError)
.and_then(|mut fle| {
{
let hdr = fle.get_header_mut();
if hdr.read("todo").chain_err(|| TEK::StoreError)?.is_none() {
hdr
.set("todo", Value::Table(BTreeMap::new()))
.chain_err(|| TEK::StoreError)?;
}
hdr.set("todo.uuid", Value::String(format!("{}",uuid)))
.chain_err(|| TEK::StoreError)?;
}
// If none of the errors above have returned the function, everything is fine
Ok(fle)
})
})
}
}
|
use task_hookrs::task::Task as TTask;
use task_hookrs::import::{import_task, import_tasks};
use libimagstore::store::{FileLockEntry, Store};
|
random_line_split
|
simple.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A small module implementing a simple "runtime" used for bootstrapping a rust
//! scheduler pool and then interacting with it.
use std::cast;
use std::rt::Runtime;
use std::rt::local::Local;
use std::rt::rtio;
use std::rt::task::{Task, BlockedTask};
use std::task::TaskOpts;
use std::unstable::sync::LittleLock;
struct SimpleTask {
lock: LittleLock,
awoken: bool,
}
impl Runtime for SimpleTask {
// Implement the simple tasks of descheduling and rescheduling, but only in
// a simple number of cases.
fn deschedule(mut ~self, times: uint, mut cur_task: ~Task,
f: |BlockedTask| -> Result<(), BlockedTask>) {
assert!(times == 1);
let me = &mut *self as *mut SimpleTask;
let cur_dupe = &*cur_task as *Task;
cur_task.put_runtime(self as ~Runtime);
let task = BlockedTask::block(cur_task);
// See libnative/task.rs for what's going on here with the `awoken`
// field and the while loop around wait()
unsafe {
let mut guard = (*me).lock.lock();
(*me).awoken = false;
match f(task) {
Ok(()) => {
while!(*me).awoken {
guard.wait();
}
}
Err(task) => { cast::forget(task.wake()); }
}
drop(guard);
cur_task = cast::transmute(cur_dupe);
}
Local::put(cur_task);
}
fn reawaken(mut ~self, mut to_wake: ~Task, _can_resched: bool) {
let me = &mut *self as *mut SimpleTask;
to_wake.put_runtime(self as ~Runtime);
unsafe {
cast::forget(to_wake);
let _l = (*me).lock.lock();
(*me).awoken = true;
(*me).lock.signal();
}
}
// These functions are all unimplemented and fail as a result. This is on
// purpose. A "simple task" is just that, a very simple task that can't
// really do a whole lot. The only purpose of the task is to get us off our
// feet and running.
fn yield_now(~self, _cur_task: ~Task)
|
fn maybe_yield(~self, _cur_task: ~Task) { fail!() }
fn spawn_sibling(~self, _cur_task: ~Task, _opts: TaskOpts, _f: proc()) {
fail!()
}
fn local_io<'a>(&'a mut self) -> Option<rtio::LocalIo<'a>> { None }
fn stack_bounds(&self) -> (uint, uint) { fail!() }
fn wrap(~self) -> ~Any { fail!() }
}
pub fn task() -> ~Task {
let mut task = ~Task::new();
task.put_runtime(~SimpleTask {
lock: LittleLock::new(),
awoken: false,
} as ~Runtime);
return task;
}
|
{ fail!() }
|
identifier_body
|
simple.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A small module implementing a simple "runtime" used for bootstrapping a rust
//! scheduler pool and then interacting with it.
use std::cast;
use std::rt::Runtime;
use std::rt::local::Local;
use std::rt::rtio;
use std::rt::task::{Task, BlockedTask};
use std::task::TaskOpts;
use std::unstable::sync::LittleLock;
struct SimpleTask {
lock: LittleLock,
awoken: bool,
}
impl Runtime for SimpleTask {
// Implement the simple tasks of descheduling and rescheduling, but only in
// a simple number of cases.
fn deschedule(mut ~self, times: uint, mut cur_task: ~Task,
f: |BlockedTask| -> Result<(), BlockedTask>) {
assert!(times == 1);
let me = &mut *self as *mut SimpleTask;
let cur_dupe = &*cur_task as *Task;
cur_task.put_runtime(self as ~Runtime);
let task = BlockedTask::block(cur_task);
// See libnative/task.rs for what's going on here with the `awoken`
// field and the while loop around wait()
unsafe {
let mut guard = (*me).lock.lock();
(*me).awoken = false;
match f(task) {
Ok(()) => {
while!(*me).awoken {
guard.wait();
}
}
Err(task) => { cast::forget(task.wake()); }
}
drop(guard);
cur_task = cast::transmute(cur_dupe);
}
Local::put(cur_task);
}
fn reawaken(mut ~self, mut to_wake: ~Task, _can_resched: bool) {
let me = &mut *self as *mut SimpleTask;
to_wake.put_runtime(self as ~Runtime);
unsafe {
cast::forget(to_wake);
let _l = (*me).lock.lock();
(*me).awoken = true;
(*me).lock.signal();
}
}
// These functions are all unimplemented and fail as a result. This is on
// purpose. A "simple task" is just that, a very simple task that can't
// really do a whole lot. The only purpose of the task is to get us off our
// feet and running.
fn yield_now(~self, _cur_task: ~Task) { fail!() }
fn maybe_yield(~self, _cur_task: ~Task) { fail!() }
fn spawn_sibling(~self, _cur_task: ~Task, _opts: TaskOpts, _f: proc()) {
fail!()
}
fn local_io<'a>(&'a mut self) -> Option<rtio::LocalIo<'a>> { None }
fn stack_bounds(&self) -> (uint, uint) { fail!() }
fn
|
(~self) -> ~Any { fail!() }
}
pub fn task() -> ~Task {
let mut task = ~Task::new();
task.put_runtime(~SimpleTask {
lock: LittleLock::new(),
awoken: false,
} as ~Runtime);
return task;
}
|
wrap
|
identifier_name
|
simple.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A small module implementing a simple "runtime" used for bootstrapping a rust
//! scheduler pool and then interacting with it.
use std::cast;
use std::rt::Runtime;
use std::rt::local::Local;
use std::rt::rtio;
use std::rt::task::{Task, BlockedTask};
use std::task::TaskOpts;
use std::unstable::sync::LittleLock;
struct SimpleTask {
lock: LittleLock,
awoken: bool,
}
|
impl Runtime for SimpleTask {
// Implement the simple tasks of descheduling and rescheduling, but only in
// a simple number of cases.
fn deschedule(mut ~self, times: uint, mut cur_task: ~Task,
f: |BlockedTask| -> Result<(), BlockedTask>) {
assert!(times == 1);
let me = &mut *self as *mut SimpleTask;
let cur_dupe = &*cur_task as *Task;
cur_task.put_runtime(self as ~Runtime);
let task = BlockedTask::block(cur_task);
// See libnative/task.rs for what's going on here with the `awoken`
// field and the while loop around wait()
unsafe {
let mut guard = (*me).lock.lock();
(*me).awoken = false;
match f(task) {
Ok(()) => {
while!(*me).awoken {
guard.wait();
}
}
Err(task) => { cast::forget(task.wake()); }
}
drop(guard);
cur_task = cast::transmute(cur_dupe);
}
Local::put(cur_task);
}
fn reawaken(mut ~self, mut to_wake: ~Task, _can_resched: bool) {
let me = &mut *self as *mut SimpleTask;
to_wake.put_runtime(self as ~Runtime);
unsafe {
cast::forget(to_wake);
let _l = (*me).lock.lock();
(*me).awoken = true;
(*me).lock.signal();
}
}
// These functions are all unimplemented and fail as a result. This is on
// purpose. A "simple task" is just that, a very simple task that can't
// really do a whole lot. The only purpose of the task is to get us off our
// feet and running.
fn yield_now(~self, _cur_task: ~Task) { fail!() }
fn maybe_yield(~self, _cur_task: ~Task) { fail!() }
fn spawn_sibling(~self, _cur_task: ~Task, _opts: TaskOpts, _f: proc()) {
fail!()
}
fn local_io<'a>(&'a mut self) -> Option<rtio::LocalIo<'a>> { None }
fn stack_bounds(&self) -> (uint, uint) { fail!() }
fn wrap(~self) -> ~Any { fail!() }
}
pub fn task() -> ~Task {
let mut task = ~Task::new();
task.put_runtime(~SimpleTask {
lock: LittleLock::new(),
awoken: false,
} as ~Runtime);
return task;
}
|
random_line_split
|
|
main.rs
|
use std::rc::Rc;
fn main() {
println!("Rust ownership system achieves memory safety");
println!("ownership, borrowing and lifetimes");
// META
// Rust focus: speed & safety
// through zero-cost abstractions
// ownership system at compile time
|
// {
// int *x = malloc(sizeof(int));
// *x = 5;
// free(x);
// }
// malloc allocates some memory, free deallocates the memory.
// thus bookkeeping about allocating the right amount of memory.
// Rust combines these 2 aspects of memory allocation into concept
// called ownership.
//
// Whenever memory request comes in it is called: owning handle.
// After handle goes out of scope it is automatically deallocated.
//
// Allocating i32 pointer to HEAP
{
let x = Box::new(5);
}
// at block end memory is automatically deallocated
// each allocation is paired with deallocation
{
let z = Box::new(5);
let y = add_one(z);
println!("{}", y);
}
fn add_one(mut num: Box<i32>) -> Box<i32> {
*num += 1;
num // ownership is transferred back
}
// Borrowing
//
// version of borrowing rather than taking ownership
{
let mut x = 7;
add_one2(&mut x);
println!("{}", x);
}
fn add_one2(num: &mut i32) {
*num += 1 // ownership borrowing
}
// Lifetimes
// Linking out a reference to a resource that someone else owns, can
// be complicated, however:
//
// 1. I acquire a handle to some kind of resource
// 2. I lend you a reference to the resource
// 3. I decide I'm done with the resource, and deallocate it,
// while still having reference
// 4. You decided to use the resource
//
// Whne reference is pointing to invalid resource - dangling pointer or
// 'use after free', when the resource is memory
//
// To fix this, we have to make sure that step four never happens after
// step three. The ownership system in Rust does this through a concept
// called lifetimes, which describe the scope that a reference is valid
// for.
//
fn lifetime1(num: &mut i32) {
*num += 1
}
// Rust: 'lifetime elision' which allows not to write
// lifetimes in certain circumstances.
//
// lifetime1 - without eliding lifetimes
fn lifetime2<'a>(num: &'a mut i32) {
*num += 1
}
// 'a is called a lifetime
// lifetime2<'a> - declares one lifetime, it is possible to specify more
// lifetime2<'a, 'b>.
// In parameter list - we use declared lifetimes
//
// &mut i32 - mutable reference to an i32
// &'a mut i32 - mutable reference to an i32 with lifetime 'a
//
// Why do lifetimes matter?
struct Foo<'a> {
x: &'a i32,
}
// we need to ensure that any reference to a Foo cannot outlive the
// reference to an i32 it contains
let y = &5; // same as let _y = 5; let y = &_y;
let f = Foo { x: y };
println!("{}", f.x);
// Static lifetime
// it signals that something has lifetime of entire program.
let x: &'static str = "Yet another hello";
// String literals have the type &'static str becuase the reference
// is always alive: they are baked into the data segment of the final
// binary.
// Globals:
static FOO: i32 = 5;
let x: &'static i32 = &FOO;
// adds an i32 to the data segment of the binary, and x is a reference
// to it.
// Shared ownership
// in all considered exampels we've assumed that each handle has a singular
// owner. But sometimes this doesn't work.
//
// E.g.: Car with four wheels, we want to know which wheel it was attached
// to.
// use std::rc::Rc;
struct Car {
name: String,
}
struct Wheel {
size: i32,
owner: Rc<Car>,
}
{
let car = Car { name: "MB".to_string() };
let car_owner = Rc::new(car);
for _ in 0..4 {
Wheel { size: 360, owner: car_owner.clone() };
}
}
// We can't do this with Box<T> pointer since it has single owner
// We need to use Rc<T> getting Rc<Car> we can use clone() to make new
// references.
// Arc<T> could be used to make atomic instructions and be thread-safe
// counterpar of Rc<T>.
// Lifetime elision
// Rust supports powerful local type inference in function bodies, but it's
// forbidden in item signatures to allow reasoning about the types just based
// in the item signature alone. However for ergonomic reasons a very
// restricted secondary inference algorithm called 'lifetime elision'
// applies in function signatures. It infers only based on the signature
// components themselves and not based on the body of the function, only
// infers lifetime parameters, and does this with three easily memorizable
// and unambigous rules. This makes lifetime elision a shorthand for writing
// an item signature, while not hiding away the actual types involved
// as full local inference would if applied to it.
//
// When talking about lifetime elision, we use the term 'input lifetime'
// and 'output lifetime'.
//
// 'input lifetime' - lifetime associated with a parameter of a function
// 'output lifetime' - lifetime associated with the return value of a
// function
// input lifetime, e.g.:
// fn foo<'a>(bar: &'a str)
// output lifetime
// fn foo<'a>() -> &'a str
// input && output lifetime
// fn foo<'a>(bar: &'a str) -> &'a str
// 3 rules
// - Each elided lifetime in a function's arguments becomes distinct
// lifetime parameter
// - If there is exactly 1 input lifetime, elided or not, that lifetime
// is assigned to all elided lifetimes in the return values of that function.
// - If there are multiple input lifetimes, but one of them &self or
// &mut self, the lifetime of self is assigned to all elided output
// lifetimes.
//
// Otherwise, it is an error to elide an output lifetime.
// fn print(s: &str); // elided
// fn print<'a>(s: &'a str); // expanded
//
// fn debug(lvl: u32, s: &str); // elided
// fn debug<'a>(lvl: u32, s: &'a str); // expanded
//
// // In the preceding example, `lvl` doesn't need a lifetime because it's not a
// // reference (`&`). Only things relating to references (such as a `struct`
// // which contains a reference) need lifetimes.
//
// fn substr(s: &str, until: u32) -> &str; // elided
// fn substr<'a>(s: &'a str, until: u32) -> &'a str; // expanded
//
// fn get_str() -> &str; // ILLEGAL, no inputs
//
// fn frob(s: &str, t: &str) -> &str; // ILLEGAL, two inputs
// fn frob<'a, 'b>(s: &'a str, t: &'b str) -> &str; // Expanded: Output lifetime is unclear
//
// fn get_mut(&mut self) -> &mut T; // elided
// fn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded
//
// fn args<T:ToCStr>(&mut self, args: &[T]) -> &mut Command // elided
// fn args<'a, 'b, T:ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command // expanded
//
// fn new(buf: &mut [u8]) -> BufWriter; // elided
// fn new<'a>(buf: &'a mut [u8]) -> BufWriter<'a> // expanded'>
}
|
// Fighting with the borrow checker
// programmer mental model mismatch with actual Rust rules
// Tracking memory allocations & deallocations
|
random_line_split
|
main.rs
|
use std::rc::Rc;
fn main() {
println!("Rust ownership system achieves memory safety");
println!("ownership, borrowing and lifetimes");
// META
// Rust focus: speed & safety
// through zero-cost abstractions
// ownership system at compile time
// Fighting with the borrow checker
// programmer mental model mismatch with actual Rust rules
// Tracking memory allocations & deallocations
// {
// int *x = malloc(sizeof(int));
// *x = 5;
// free(x);
// }
// malloc allocates some memory, free deallocates the memory.
// thus bookkeeping about allocating the right amount of memory.
// Rust combines these 2 aspects of memory allocation into concept
// called ownership.
//
// Whenever memory request comes in it is called: owning handle.
// After handle goes out of scope it is automatically deallocated.
//
// Allocating i32 pointer to HEAP
{
let x = Box::new(5);
}
// at block end memory is automatically deallocated
// each allocation is paired with deallocation
{
let z = Box::new(5);
let y = add_one(z);
println!("{}", y);
}
fn add_one(mut num: Box<i32>) -> Box<i32> {
*num += 1;
num // ownership is transferred back
}
// Borrowing
//
// version of borrowing rather than taking ownership
{
let mut x = 7;
add_one2(&mut x);
println!("{}", x);
}
fn add_one2(num: &mut i32) {
*num += 1 // ownership borrowing
}
// Lifetimes
// Linking out a reference to a resource that someone else owns, can
// be complicated, however:
//
// 1. I acquire a handle to some kind of resource
// 2. I lend you a reference to the resource
// 3. I decide I'm done with the resource, and deallocate it,
// while still having reference
// 4. You decided to use the resource
//
// Whne reference is pointing to invalid resource - dangling pointer or
// 'use after free', when the resource is memory
//
// To fix this, we have to make sure that step four never happens after
// step three. The ownership system in Rust does this through a concept
// called lifetimes, which describe the scope that a reference is valid
// for.
//
fn lifetime1(num: &mut i32) {
*num += 1
}
// Rust: 'lifetime elision' which allows not to write
// lifetimes in certain circumstances.
//
// lifetime1 - without eliding lifetimes
fn lifetime2<'a>(num: &'a mut i32) {
*num += 1
}
// 'a is called a lifetime
// lifetime2<'a> - declares one lifetime, it is possible to specify more
// lifetime2<'a, 'b>.
// In parameter list - we use declared lifetimes
//
// &mut i32 - mutable reference to an i32
// &'a mut i32 - mutable reference to an i32 with lifetime 'a
//
// Why do lifetimes matter?
struct Foo<'a> {
x: &'a i32,
}
// we need to ensure that any reference to a Foo cannot outlive the
// reference to an i32 it contains
let y = &5; // same as let _y = 5; let y = &_y;
let f = Foo { x: y };
println!("{}", f.x);
// Static lifetime
// it signals that something has lifetime of entire program.
let x: &'static str = "Yet another hello";
// String literals have the type &'static str becuase the reference
// is always alive: they are baked into the data segment of the final
// binary.
// Globals:
static FOO: i32 = 5;
let x: &'static i32 = &FOO;
// adds an i32 to the data segment of the binary, and x is a reference
// to it.
// Shared ownership
// in all considered exampels we've assumed that each handle has a singular
// owner. But sometimes this doesn't work.
//
// E.g.: Car with four wheels, we want to know which wheel it was attached
// to.
// use std::rc::Rc;
struct
|
{
name: String,
}
struct Wheel {
size: i32,
owner: Rc<Car>,
}
{
let car = Car { name: "MB".to_string() };
let car_owner = Rc::new(car);
for _ in 0..4 {
Wheel { size: 360, owner: car_owner.clone() };
}
}
// We can't do this with Box<T> pointer since it has single owner
// We need to use Rc<T> getting Rc<Car> we can use clone() to make new
// references.
// Arc<T> could be used to make atomic instructions and be thread-safe
// counterpar of Rc<T>.
// Lifetime elision
// Rust supports powerful local type inference in function bodies, but it's
// forbidden in item signatures to allow reasoning about the types just based
// in the item signature alone. However for ergonomic reasons a very
// restricted secondary inference algorithm called 'lifetime elision'
// applies in function signatures. It infers only based on the signature
// components themselves and not based on the body of the function, only
// infers lifetime parameters, and does this with three easily memorizable
// and unambigous rules. This makes lifetime elision a shorthand for writing
// an item signature, while not hiding away the actual types involved
// as full local inference would if applied to it.
//
// When talking about lifetime elision, we use the term 'input lifetime'
// and 'output lifetime'.
//
// 'input lifetime' - lifetime associated with a parameter of a function
// 'output lifetime' - lifetime associated with the return value of a
// function
// input lifetime, e.g.:
// fn foo<'a>(bar: &'a str)
// output lifetime
// fn foo<'a>() -> &'a str
// input && output lifetime
// fn foo<'a>(bar: &'a str) -> &'a str
// 3 rules
// - Each elided lifetime in a function's arguments becomes distinct
// lifetime parameter
// - If there is exactly 1 input lifetime, elided or not, that lifetime
// is assigned to all elided lifetimes in the return values of that function.
// - If there are multiple input lifetimes, but one of them &self or
// &mut self, the lifetime of self is assigned to all elided output
// lifetimes.
//
// Otherwise, it is an error to elide an output lifetime.
// fn print(s: &str); // elided
// fn print<'a>(s: &'a str); // expanded
//
// fn debug(lvl: u32, s: &str); // elided
// fn debug<'a>(lvl: u32, s: &'a str); // expanded
//
// // In the preceding example, `lvl` doesn't need a lifetime because it's not a
// // reference (`&`). Only things relating to references (such as a `struct`
// // which contains a reference) need lifetimes.
//
// fn substr(s: &str, until: u32) -> &str; // elided
// fn substr<'a>(s: &'a str, until: u32) -> &'a str; // expanded
//
// fn get_str() -> &str; // ILLEGAL, no inputs
//
// fn frob(s: &str, t: &str) -> &str; // ILLEGAL, two inputs
// fn frob<'a, 'b>(s: &'a str, t: &'b str) -> &str; // Expanded: Output lifetime is unclear
//
// fn get_mut(&mut self) -> &mut T; // elided
// fn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded
//
// fn args<T:ToCStr>(&mut self, args: &[T]) -> &mut Command // elided
// fn args<'a, 'b, T:ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command // expanded
//
// fn new(buf: &mut [u8]) -> BufWriter; // elided
// fn new<'a>(buf: &'a mut [u8]) -> BufWriter<'a> // expanded'>
}
|
Car
|
identifier_name
|
main.rs
|
use std::rc::Rc;
fn main() {
println!("Rust ownership system achieves memory safety");
println!("ownership, borrowing and lifetimes");
// META
// Rust focus: speed & safety
// through zero-cost abstractions
// ownership system at compile time
// Fighting with the borrow checker
// programmer mental model mismatch with actual Rust rules
// Tracking memory allocations & deallocations
// {
// int *x = malloc(sizeof(int));
// *x = 5;
// free(x);
// }
// malloc allocates some memory, free deallocates the memory.
// thus bookkeeping about allocating the right amount of memory.
// Rust combines these 2 aspects of memory allocation into concept
// called ownership.
//
// Whenever memory request comes in it is called: owning handle.
// After handle goes out of scope it is automatically deallocated.
//
// Allocating i32 pointer to HEAP
{
let x = Box::new(5);
}
// at block end memory is automatically deallocated
// each allocation is paired with deallocation
{
let z = Box::new(5);
let y = add_one(z);
println!("{}", y);
}
fn add_one(mut num: Box<i32>) -> Box<i32> {
*num += 1;
num // ownership is transferred back
}
// Borrowing
//
// version of borrowing rather than taking ownership
{
let mut x = 7;
add_one2(&mut x);
println!("{}", x);
}
fn add_one2(num: &mut i32) {
*num += 1 // ownership borrowing
}
// Lifetimes
// Linking out a reference to a resource that someone else owns, can
// be complicated, however:
//
// 1. I acquire a handle to some kind of resource
// 2. I lend you a reference to the resource
// 3. I decide I'm done with the resource, and deallocate it,
// while still having reference
// 4. You decided to use the resource
//
// Whne reference is pointing to invalid resource - dangling pointer or
// 'use after free', when the resource is memory
//
// To fix this, we have to make sure that step four never happens after
// step three. The ownership system in Rust does this through a concept
// called lifetimes, which describe the scope that a reference is valid
// for.
//
fn lifetime1(num: &mut i32)
|
// Rust: 'lifetime elision' which allows not to write
// lifetimes in certain circumstances.
//
// lifetime1 - without eliding lifetimes
fn lifetime2<'a>(num: &'a mut i32) {
*num += 1
}
// 'a is called a lifetime
// lifetime2<'a> - declares one lifetime, it is possible to specify more
// lifetime2<'a, 'b>.
// In parameter list - we use declared lifetimes
//
// &mut i32 - mutable reference to an i32
// &'a mut i32 - mutable reference to an i32 with lifetime 'a
//
// Why do lifetimes matter?
struct Foo<'a> {
x: &'a i32,
}
// we need to ensure that any reference to a Foo cannot outlive the
// reference to an i32 it contains
let y = &5; // same as let _y = 5; let y = &_y;
let f = Foo { x: y };
println!("{}", f.x);
// Static lifetime
// it signals that something has lifetime of entire program.
let x: &'static str = "Yet another hello";
// String literals have the type &'static str becuase the reference
// is always alive: they are baked into the data segment of the final
// binary.
// Globals:
static FOO: i32 = 5;
let x: &'static i32 = &FOO;
// adds an i32 to the data segment of the binary, and x is a reference
// to it.
// Shared ownership
// in all considered exampels we've assumed that each handle has a singular
// owner. But sometimes this doesn't work.
//
// E.g.: Car with four wheels, we want to know which wheel it was attached
// to.
// use std::rc::Rc;
struct Car {
name: String,
}
struct Wheel {
size: i32,
owner: Rc<Car>,
}
{
let car = Car { name: "MB".to_string() };
let car_owner = Rc::new(car);
for _ in 0..4 {
Wheel { size: 360, owner: car_owner.clone() };
}
}
// We can't do this with Box<T> pointer since it has single owner
// We need to use Rc<T> getting Rc<Car> we can use clone() to make new
// references.
// Arc<T> could be used to make atomic instructions and be thread-safe
// counterpar of Rc<T>.
// Lifetime elision
// Rust supports powerful local type inference in function bodies, but it's
// forbidden in item signatures to allow reasoning about the types just based
// in the item signature alone. However for ergonomic reasons a very
// restricted secondary inference algorithm called 'lifetime elision'
// applies in function signatures. It infers only based on the signature
// components themselves and not based on the body of the function, only
// infers lifetime parameters, and does this with three easily memorizable
// and unambigous rules. This makes lifetime elision a shorthand for writing
// an item signature, while not hiding away the actual types involved
// as full local inference would if applied to it.
//
// When talking about lifetime elision, we use the term 'input lifetime'
// and 'output lifetime'.
//
// 'input lifetime' - lifetime associated with a parameter of a function
// 'output lifetime' - lifetime associated with the return value of a
// function
// input lifetime, e.g.:
// fn foo<'a>(bar: &'a str)
// output lifetime
// fn foo<'a>() -> &'a str
// input && output lifetime
// fn foo<'a>(bar: &'a str) -> &'a str
// 3 rules
// - Each elided lifetime in a function's arguments becomes distinct
// lifetime parameter
// - If there is exactly 1 input lifetime, elided or not, that lifetime
// is assigned to all elided lifetimes in the return values of that function.
// - If there are multiple input lifetimes, but one of them &self or
// &mut self, the lifetime of self is assigned to all elided output
// lifetimes.
//
// Otherwise, it is an error to elide an output lifetime.
// fn print(s: &str); // elided
// fn print<'a>(s: &'a str); // expanded
//
// fn debug(lvl: u32, s: &str); // elided
// fn debug<'a>(lvl: u32, s: &'a str); // expanded
//
// // In the preceding example, `lvl` doesn't need a lifetime because it's not a
// // reference (`&`). Only things relating to references (such as a `struct`
// // which contains a reference) need lifetimes.
//
// fn substr(s: &str, until: u32) -> &str; // elided
// fn substr<'a>(s: &'a str, until: u32) -> &'a str; // expanded
//
// fn get_str() -> &str; // ILLEGAL, no inputs
//
// fn frob(s: &str, t: &str) -> &str; // ILLEGAL, two inputs
// fn frob<'a, 'b>(s: &'a str, t: &'b str) -> &str; // Expanded: Output lifetime is unclear
//
// fn get_mut(&mut self) -> &mut T; // elided
// fn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded
//
// fn args<T:ToCStr>(&mut self, args: &[T]) -> &mut Command // elided
// fn args<'a, 'b, T:ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command // expanded
//
// fn new(buf: &mut [u8]) -> BufWriter; // elided
// fn new<'a>(buf: &'a mut [u8]) -> BufWriter<'a> // expanded'>
}
|
{
*num += 1
}
|
identifier_body
|
day1.rs
|
const DIRECTIONS: &'static str =
"R4, R5, L5, L5, L3, R2, R1, R1, L5, R5, R2, L1, L3, L4, R3, L1, L1, R2, R3, R3, R1, L3, L5, \
R3, R1, L1, R1, R2, L1, L4, L5, R4, R2, L192, R5, L2, R53, R1, L5, R73, R5, L5, R186, L3, \
L2, R1, R3, L3, L3, R1, L4, L2, R3, L5, R4, R3, R1, L1, R5, R2, R1, R1, R1, R3, R2, L1, R5, \
R1, L5, R2, L2, L4, R3, L1, R4, L5, R4, R3, L5, L3, R4, R2, L5, L5, R2, R3, R5, R4, R2, R1, \
L1, L5, L2, L3, L4, L5, L4, L5, L1, R3, R4, R5, R3, L5, L4, L3, L1, L4, R2, R5, R5, R4, L2, \
L4, R3, R1, L2, R5, L5, R1, R1, L1, L5, L5, L2, L1, R5, R2, L4, L1, R4, R3, L3, R1, R5, L1, \
L4, R2, L3, R5, R3, R1, L3";
// const DIRECTIONS: &'static str = "R8, R4, R4, R8";
#[derive(Debug)]
enum Direction {
N,
E,
S,
W,
}
use self::Direction::*;
impl Direction {
fn turn(&mut self, rl: &char) {
*self = match *rl {
'R' => {
match *self {
N => E,
E => S,
S => W,
W => N,
}
}
'L' => {
match *self {
N => W,
E => N,
S => E,
W => S,
}
}
_ => panic!("can't turn {}", rl),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
#[derive(Debug)]
struct Line {
start: Point,
end: Point,
}
impl Line {
fn intersect(&self, other: &Line) -> Option<Point> {
if self.is_parallel(other) {
return None;
}
let horz = if self.is_horizontal() { self } else { other };
let vert = if self.is_vertical() { self } else { other };
let &Line { start: Point { x: hx1, y: hy }, end: Point { x: hx2, y: _ } } = horz;
let &Line { start: Point { x: vx, y: vy1 }, end: Point { x: _, y: vy2 } } = vert;
// order coords so that 1 < 2
let (hx1, hx2) = if hx1 < hx2 { (hx1, hx2) } else { (hx2, hx1) };
let (vy1, vy2) = if vy1 < vy2
|
else { (vy2, vy1) };
if (vx > hx1 && vx < hx2) && (hy > vy1 && hy < vy2) {
println!("({},{})", vx, hy);
Some(Point { x: vx, y: hy })
} else {
None
}
}
fn is_parallel(&self, other: &Line) -> bool {
(self.is_horizontal() && other.is_horizontal()) ||
(self.is_vertical() && other.is_vertical())
}
fn is_horizontal(&self) -> bool {
self.start.y == self.end.y
}
fn is_vertical(&self) -> bool {
self.start.x == self.end.x
}
}
pub fn main() {
let mut path = Vec::new();
let mut pos = Point { x: 0, y: 0 };
let mut prev_pos;
let mut intersect = None;
let mut facing = N;
let dirs = DIRECTIONS.split(", ");
for d in dirs {
prev_pos = pos;
let mut x = d.chars();
let turn = x.next().unwrap();
let steps = x.collect::<String>().parse::<i32>().unwrap();
facing.turn(&turn);
match facing {
N => pos.y += steps,
S => pos.y -= steps,
E => pos.x += steps,
W => pos.x -= steps,
}
println!("{}, {} => {:?} {:?}", turn, steps, facing, pos);
let line = Line {
start: prev_pos,
end: pos,
};
if let None = intersect {
intersect = path.iter()
.map(|l: &Line| l.intersect(&line))
.fold(None, |acc, p| {
match acc {
None => p,
Some(_) => acc,
}
});
}
path.push(line);
}
let dist = pos.x.abs() + pos.y.abs();
let intersect_dist = match intersect {
Some(p) => p.x.abs() + p.y.abs(),
None => 0,
};
println!("part1 distance: {}", dist);
println!("part2 distance: {}", intersect_dist);
}
|
{ (vy1, vy2) }
|
conditional_block
|
day1.rs
|
const DIRECTIONS: &'static str =
"R4, R5, L5, L5, L3, R2, R1, R1, L5, R5, R2, L1, L3, L4, R3, L1, L1, R2, R3, R3, R1, L3, L5, \
R3, R1, L1, R1, R2, L1, L4, L5, R4, R2, L192, R5, L2, R53, R1, L5, R73, R5, L5, R186, L3, \
L2, R1, R3, L3, L3, R1, L4, L2, R3, L5, R4, R3, R1, L1, R5, R2, R1, R1, R1, R3, R2, L1, R5, \
R1, L5, R2, L2, L4, R3, L1, R4, L5, R4, R3, L5, L3, R4, R2, L5, L5, R2, R3, R5, R4, R2, R1, \
L1, L5, L2, L3, L4, L5, L4, L5, L1, R3, R4, R5, R3, L5, L4, L3, L1, L4, R2, R5, R5, R4, L2, \
L4, R3, R1, L2, R5, L5, R1, R1, L1, L5, L5, L2, L1, R5, R2, L4, L1, R4, R3, L3, R1, R5, L1, \
L4, R2, L3, R5, R3, R1, L3";
// const DIRECTIONS: &'static str = "R8, R4, R4, R8";
#[derive(Debug)]
enum Direction {
N,
E,
S,
W,
}
use self::Direction::*;
impl Direction {
fn turn(&mut self, rl: &char) {
*self = match *rl {
'R' => {
match *self {
N => E,
E => S,
S => W,
W => N,
}
}
'L' => {
match *self {
N => W,
E => N,
S => E,
W => S,
}
}
_ => panic!("can't turn {}", rl),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
#[derive(Debug)]
struct Line {
start: Point,
end: Point,
}
impl Line {
fn intersect(&self, other: &Line) -> Option<Point> {
if self.is_parallel(other) {
return None;
}
let horz = if self.is_horizontal() { self } else { other };
let vert = if self.is_vertical() { self } else { other };
let &Line { start: Point { x: hx1, y: hy }, end: Point { x: hx2, y: _ } } = horz;
let &Line { start: Point { x: vx, y: vy1 }, end: Point { x: _, y: vy2 } } = vert;
// order coords so that 1 < 2
let (hx1, hx2) = if hx1 < hx2 { (hx1, hx2) } else { (hx2, hx1) };
let (vy1, vy2) = if vy1 < vy2 { (vy1, vy2) } else { (vy2, vy1) };
if (vx > hx1 && vx < hx2) && (hy > vy1 && hy < vy2) {
println!("({},{})", vx, hy);
Some(Point { x: vx, y: hy })
} else {
None
}
}
|
(self.is_horizontal() && other.is_horizontal()) ||
(self.is_vertical() && other.is_vertical())
}
fn is_horizontal(&self) -> bool {
self.start.y == self.end.y
}
fn is_vertical(&self) -> bool {
self.start.x == self.end.x
}
}
pub fn main() {
let mut path = Vec::new();
let mut pos = Point { x: 0, y: 0 };
let mut prev_pos;
let mut intersect = None;
let mut facing = N;
let dirs = DIRECTIONS.split(", ");
for d in dirs {
prev_pos = pos;
let mut x = d.chars();
let turn = x.next().unwrap();
let steps = x.collect::<String>().parse::<i32>().unwrap();
facing.turn(&turn);
match facing {
N => pos.y += steps,
S => pos.y -= steps,
E => pos.x += steps,
W => pos.x -= steps,
}
println!("{}, {} => {:?} {:?}", turn, steps, facing, pos);
let line = Line {
start: prev_pos,
end: pos,
};
if let None = intersect {
intersect = path.iter()
.map(|l: &Line| l.intersect(&line))
.fold(None, |acc, p| {
match acc {
None => p,
Some(_) => acc,
}
});
}
path.push(line);
}
let dist = pos.x.abs() + pos.y.abs();
let intersect_dist = match intersect {
Some(p) => p.x.abs() + p.y.abs(),
None => 0,
};
println!("part1 distance: {}", dist);
println!("part2 distance: {}", intersect_dist);
}
|
fn is_parallel(&self, other: &Line) -> bool {
|
random_line_split
|
day1.rs
|
const DIRECTIONS: &'static str =
"R4, R5, L5, L5, L3, R2, R1, R1, L5, R5, R2, L1, L3, L4, R3, L1, L1, R2, R3, R3, R1, L3, L5, \
R3, R1, L1, R1, R2, L1, L4, L5, R4, R2, L192, R5, L2, R53, R1, L5, R73, R5, L5, R186, L3, \
L2, R1, R3, L3, L3, R1, L4, L2, R3, L5, R4, R3, R1, L1, R5, R2, R1, R1, R1, R3, R2, L1, R5, \
R1, L5, R2, L2, L4, R3, L1, R4, L5, R4, R3, L5, L3, R4, R2, L5, L5, R2, R3, R5, R4, R2, R1, \
L1, L5, L2, L3, L4, L5, L4, L5, L1, R3, R4, R5, R3, L5, L4, L3, L1, L4, R2, R5, R5, R4, L2, \
L4, R3, R1, L2, R5, L5, R1, R1, L1, L5, L5, L2, L1, R5, R2, L4, L1, R4, R3, L3, R1, R5, L1, \
L4, R2, L3, R5, R3, R1, L3";
// const DIRECTIONS: &'static str = "R8, R4, R4, R8";
#[derive(Debug)]
enum Direction {
N,
E,
S,
W,
}
use self::Direction::*;
impl Direction {
fn turn(&mut self, rl: &char) {
*self = match *rl {
'R' => {
match *self {
N => E,
E => S,
S => W,
W => N,
}
}
'L' => {
match *self {
N => W,
E => N,
S => E,
W => S,
}
}
_ => panic!("can't turn {}", rl),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
#[derive(Debug)]
struct Line {
start: Point,
end: Point,
}
impl Line {
fn intersect(&self, other: &Line) -> Option<Point> {
if self.is_parallel(other) {
return None;
}
let horz = if self.is_horizontal() { self } else { other };
let vert = if self.is_vertical() { self } else { other };
let &Line { start: Point { x: hx1, y: hy }, end: Point { x: hx2, y: _ } } = horz;
let &Line { start: Point { x: vx, y: vy1 }, end: Point { x: _, y: vy2 } } = vert;
// order coords so that 1 < 2
let (hx1, hx2) = if hx1 < hx2 { (hx1, hx2) } else { (hx2, hx1) };
let (vy1, vy2) = if vy1 < vy2 { (vy1, vy2) } else { (vy2, vy1) };
if (vx > hx1 && vx < hx2) && (hy > vy1 && hy < vy2) {
println!("({},{})", vx, hy);
Some(Point { x: vx, y: hy })
} else {
None
}
}
fn is_parallel(&self, other: &Line) -> bool {
(self.is_horizontal() && other.is_horizontal()) ||
(self.is_vertical() && other.is_vertical())
}
fn is_horizontal(&self) -> bool {
self.start.y == self.end.y
}
fn is_vertical(&self) -> bool
|
}
pub fn main() {
let mut path = Vec::new();
let mut pos = Point { x: 0, y: 0 };
let mut prev_pos;
let mut intersect = None;
let mut facing = N;
let dirs = DIRECTIONS.split(", ");
for d in dirs {
prev_pos = pos;
let mut x = d.chars();
let turn = x.next().unwrap();
let steps = x.collect::<String>().parse::<i32>().unwrap();
facing.turn(&turn);
match facing {
N => pos.y += steps,
S => pos.y -= steps,
E => pos.x += steps,
W => pos.x -= steps,
}
println!("{}, {} => {:?} {:?}", turn, steps, facing, pos);
let line = Line {
start: prev_pos,
end: pos,
};
if let None = intersect {
intersect = path.iter()
.map(|l: &Line| l.intersect(&line))
.fold(None, |acc, p| {
match acc {
None => p,
Some(_) => acc,
}
});
}
path.push(line);
}
let dist = pos.x.abs() + pos.y.abs();
let intersect_dist = match intersect {
Some(p) => p.x.abs() + p.y.abs(),
None => 0,
};
println!("part1 distance: {}", dist);
println!("part2 distance: {}", intersect_dist);
}
|
{
self.start.x == self.end.x
}
|
identifier_body
|
day1.rs
|
const DIRECTIONS: &'static str =
"R4, R5, L5, L5, L3, R2, R1, R1, L5, R5, R2, L1, L3, L4, R3, L1, L1, R2, R3, R3, R1, L3, L5, \
R3, R1, L1, R1, R2, L1, L4, L5, R4, R2, L192, R5, L2, R53, R1, L5, R73, R5, L5, R186, L3, \
L2, R1, R3, L3, L3, R1, L4, L2, R3, L5, R4, R3, R1, L1, R5, R2, R1, R1, R1, R3, R2, L1, R5, \
R1, L5, R2, L2, L4, R3, L1, R4, L5, R4, R3, L5, L3, R4, R2, L5, L5, R2, R3, R5, R4, R2, R1, \
L1, L5, L2, L3, L4, L5, L4, L5, L1, R3, R4, R5, R3, L5, L4, L3, L1, L4, R2, R5, R5, R4, L2, \
L4, R3, R1, L2, R5, L5, R1, R1, L1, L5, L5, L2, L1, R5, R2, L4, L1, R4, R3, L3, R1, R5, L1, \
L4, R2, L3, R5, R3, R1, L3";
// const DIRECTIONS: &'static str = "R8, R4, R4, R8";
#[derive(Debug)]
enum Direction {
N,
E,
S,
W,
}
use self::Direction::*;
impl Direction {
fn turn(&mut self, rl: &char) {
*self = match *rl {
'R' => {
match *self {
N => E,
E => S,
S => W,
W => N,
}
}
'L' => {
match *self {
N => W,
E => N,
S => E,
W => S,
}
}
_ => panic!("can't turn {}", rl),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
#[derive(Debug)]
struct Line {
start: Point,
end: Point,
}
impl Line {
fn intersect(&self, other: &Line) -> Option<Point> {
if self.is_parallel(other) {
return None;
}
let horz = if self.is_horizontal() { self } else { other };
let vert = if self.is_vertical() { self } else { other };
let &Line { start: Point { x: hx1, y: hy }, end: Point { x: hx2, y: _ } } = horz;
let &Line { start: Point { x: vx, y: vy1 }, end: Point { x: _, y: vy2 } } = vert;
// order coords so that 1 < 2
let (hx1, hx2) = if hx1 < hx2 { (hx1, hx2) } else { (hx2, hx1) };
let (vy1, vy2) = if vy1 < vy2 { (vy1, vy2) } else { (vy2, vy1) };
if (vx > hx1 && vx < hx2) && (hy > vy1 && hy < vy2) {
println!("({},{})", vx, hy);
Some(Point { x: vx, y: hy })
} else {
None
}
}
fn is_parallel(&self, other: &Line) -> bool {
(self.is_horizontal() && other.is_horizontal()) ||
(self.is_vertical() && other.is_vertical())
}
fn
|
(&self) -> bool {
self.start.y == self.end.y
}
fn is_vertical(&self) -> bool {
self.start.x == self.end.x
}
}
pub fn main() {
let mut path = Vec::new();
let mut pos = Point { x: 0, y: 0 };
let mut prev_pos;
let mut intersect = None;
let mut facing = N;
let dirs = DIRECTIONS.split(", ");
for d in dirs {
prev_pos = pos;
let mut x = d.chars();
let turn = x.next().unwrap();
let steps = x.collect::<String>().parse::<i32>().unwrap();
facing.turn(&turn);
match facing {
N => pos.y += steps,
S => pos.y -= steps,
E => pos.x += steps,
W => pos.x -= steps,
}
println!("{}, {} => {:?} {:?}", turn, steps, facing, pos);
let line = Line {
start: prev_pos,
end: pos,
};
if let None = intersect {
intersect = path.iter()
.map(|l: &Line| l.intersect(&line))
.fold(None, |acc, p| {
match acc {
None => p,
Some(_) => acc,
}
});
}
path.push(line);
}
let dist = pos.x.abs() + pos.y.abs();
let intersect_dist = match intersect {
Some(p) => p.x.abs() + p.y.abs(),
None => 0,
};
println!("part1 distance: {}", dist);
println!("part2 distance: {}", intersect_dist);
}
|
is_horizontal
|
identifier_name
|
raw.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! MacOS-specific raw type definitions
use os::raw::c_long;
use os::unix::raw::{uid_t, gid_t};
pub type blkcnt_t = i64;
pub type blksize_t = i32;
pub type dev_t = i32;
pub type ino_t = u64;
pub type mode_t = u16;
pub type nlink_t = u16;
pub type off_t = i64;
pub type time_t = c_long;
#[repr(C)]
pub struct
|
{
pub st_dev: dev_t,
pub st_mode: mode_t,
pub st_nlink: nlink_t,
pub st_ino: ino_t,
pub st_uid: uid_t,
pub st_gid: gid_t,
pub st_rdev: dev_t,
pub st_atime: time_t,
pub st_atime_nsec: c_long,
pub st_mtime: time_t,
pub st_mtime_nsec: c_long,
pub st_ctime: time_t,
pub st_ctime_nsec: c_long,
pub st_birthtime: time_t,
pub st_birthtime_nsec: c_long,
pub st_size: off_t,
pub st_blocks: blkcnt_t,
pub st_blksize: blksize_t,
pub st_flags: u32,
pub st_gen: u32,
pub st_lspare: i32,
pub st_qspare: [i64; 2],
}
|
stat
|
identifier_name
|
raw.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! MacOS-specific raw type definitions
use os::raw::c_long;
use os::unix::raw::{uid_t, gid_t};
pub type blkcnt_t = i64;
pub type blksize_t = i32;
pub type dev_t = i32;
pub type ino_t = u64;
pub type mode_t = u16;
pub type nlink_t = u16;
pub type off_t = i64;
pub type time_t = c_long;
|
#[repr(C)]
pub struct stat {
pub st_dev: dev_t,
pub st_mode: mode_t,
pub st_nlink: nlink_t,
pub st_ino: ino_t,
pub st_uid: uid_t,
pub st_gid: gid_t,
pub st_rdev: dev_t,
pub st_atime: time_t,
pub st_atime_nsec: c_long,
pub st_mtime: time_t,
pub st_mtime_nsec: c_long,
pub st_ctime: time_t,
pub st_ctime_nsec: c_long,
pub st_birthtime: time_t,
pub st_birthtime_nsec: c_long,
pub st_size: off_t,
pub st_blocks: blkcnt_t,
pub st_blksize: blksize_t,
pub st_flags: u32,
pub st_gen: u32,
pub st_lspare: i32,
pub st_qspare: [i64; 2],
}
|
random_line_split
|
|
rdynload.rs
|
// automatically generated by rust-bindgen
use super::boolean::*;
#[allow(dead_code)]
const SINGLESXP: u32 = 302;
#[allow(non_camel_case_types)]
pub type DL_FUNC = ::std::option::Option<extern "C" fn() -> *mut ::libc::c_void>;
#[allow(non_camel_case_types)]
pub type R_NativePrimitiveArgType = ::libc::c_uint;
#[allow(non_camel_case_types)]
pub type R_NativeObjectArgType = ::libc::c_uint;
#[repr(C)]
#[derive(Copy, Clone, Debug)]
#[allow(non_camel_case_types)]
pub enum R_NativeArgStyle {
R_ARG_IN = 0,
R_ARG_OUT,
R_ARG_IN_OUT,
R_IRRELEVANT,
}
#[repr(C)]
#[derive(Copy)]
#[allow(non_snake_case)]
pub struct R_CMethodDef {
pub name: *const ::libc::c_char,
pub fun: DL_FUNC,
pub numArgs: ::libc::c_int,
pub types: *mut R_NativePrimitiveArgType,
pub styles: *mut R_NativeArgStyle,
}
impl ::std::clone::Clone for R_CMethodDef {
fn clone(&self) -> Self
|
}
impl ::std::default::Default for R_CMethodDef {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
#[allow(non_camel_case_types)]
pub type R_FortranMethodDef = R_CMethodDef;
#[repr(C)]
#[derive(Copy)]
#[allow(non_snake_case)]
pub struct R_CallMethodDef {
pub name: *const ::libc::c_char,
pub fun: DL_FUNC,
pub numArgs: ::libc::c_int,
}
impl ::std::clone::Clone for R_CallMethodDef {
fn clone(&self) -> Self {
*self
}
}
impl ::std::default::Default for R_CallMethodDef {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
#[allow(non_camel_case_types)]
pub type R_ExternalMethodDef = R_CallMethodDef;
#[allow(non_camel_case_types)]
pub enum Struct__DllInfo {
}
pub type DllInfo = Struct__DllInfo;
#[allow(non_camel_case_types)]
pub enum Struct_Rf_RegisteredNativeSymbol {
}
#[allow(non_camel_case_types)]
pub type R_RegisteredNativeSymbol = Struct_Rf_RegisteredNativeSymbol;
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub enum NativeSymbolType {
R_ANY_SYM = 0,
R_C_SYM,
R_CALL_SYM,
R_FORTRAN_SYM,
R_EXTERNAL_SYM,
}
extern "C" {
pub fn R_registerRoutines(
info: *mut DllInfo,
croutines: *const R_CMethodDef,
callRoutines: *const R_CallMethodDef,
fortranRoutines: *const R_FortranMethodDef,
externalRoutines: *const R_ExternalMethodDef,
) -> ::libc::c_int;
pub fn R_useDynamicSymbols(info: *mut DllInfo, value: Rboolean) -> Rboolean;
pub fn R_forceSymbols(info: *mut DllInfo, value: Rboolean) -> Rboolean;
pub fn R_getDllInfo(name: *const ::libc::c_char) -> *mut DllInfo;
pub fn R_getEmbeddingDllInfo() -> *mut DllInfo;
pub fn R_FindSymbol(
arg1: *const ::libc::c_char,
arg2: *const ::libc::c_char,
symbol: *mut R_RegisteredNativeSymbol,
) -> DL_FUNC;
pub fn R_RegisterCCallable(
package: *const ::libc::c_char,
name: *const ::libc::c_char,
fptr: DL_FUNC,
) -> ();
pub fn R_GetCCallable(package: *const ::libc::c_char, name: *const ::libc::c_char) -> DL_FUNC;
}
|
{
*self
}
|
identifier_body
|
rdynload.rs
|
// automatically generated by rust-bindgen
use super::boolean::*;
#[allow(dead_code)]
const SINGLESXP: u32 = 302;
#[allow(non_camel_case_types)]
pub type DL_FUNC = ::std::option::Option<extern "C" fn() -> *mut ::libc::c_void>;
#[allow(non_camel_case_types)]
pub type R_NativePrimitiveArgType = ::libc::c_uint;
#[allow(non_camel_case_types)]
pub type R_NativeObjectArgType = ::libc::c_uint;
#[repr(C)]
#[derive(Copy, Clone, Debug)]
#[allow(non_camel_case_types)]
pub enum R_NativeArgStyle {
R_ARG_IN = 0,
R_ARG_OUT,
R_ARG_IN_OUT,
R_IRRELEVANT,
}
#[repr(C)]
#[derive(Copy)]
#[allow(non_snake_case)]
pub struct R_CMethodDef {
pub name: *const ::libc::c_char,
pub fun: DL_FUNC,
pub numArgs: ::libc::c_int,
pub types: *mut R_NativePrimitiveArgType,
pub styles: *mut R_NativeArgStyle,
}
impl ::std::clone::Clone for R_CMethodDef {
fn clone(&self) -> Self {
*self
}
}
impl ::std::default::Default for R_CMethodDef {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
|
}
}
#[allow(non_camel_case_types)]
pub type R_FortranMethodDef = R_CMethodDef;
#[repr(C)]
#[derive(Copy)]
#[allow(non_snake_case)]
pub struct R_CallMethodDef {
pub name: *const ::libc::c_char,
pub fun: DL_FUNC,
pub numArgs: ::libc::c_int,
}
impl ::std::clone::Clone for R_CallMethodDef {
fn clone(&self) -> Self {
*self
}
}
impl ::std::default::Default for R_CallMethodDef {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
#[allow(non_camel_case_types)]
pub type R_ExternalMethodDef = R_CallMethodDef;
#[allow(non_camel_case_types)]
pub enum Struct__DllInfo {
}
pub type DllInfo = Struct__DllInfo;
#[allow(non_camel_case_types)]
pub enum Struct_Rf_RegisteredNativeSymbol {
}
#[allow(non_camel_case_types)]
pub type R_RegisteredNativeSymbol = Struct_Rf_RegisteredNativeSymbol;
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub enum NativeSymbolType {
R_ANY_SYM = 0,
R_C_SYM,
R_CALL_SYM,
R_FORTRAN_SYM,
R_EXTERNAL_SYM,
}
extern "C" {
pub fn R_registerRoutines(
info: *mut DllInfo,
croutines: *const R_CMethodDef,
callRoutines: *const R_CallMethodDef,
fortranRoutines: *const R_FortranMethodDef,
externalRoutines: *const R_ExternalMethodDef,
) -> ::libc::c_int;
pub fn R_useDynamicSymbols(info: *mut DllInfo, value: Rboolean) -> Rboolean;
pub fn R_forceSymbols(info: *mut DllInfo, value: Rboolean) -> Rboolean;
pub fn R_getDllInfo(name: *const ::libc::c_char) -> *mut DllInfo;
pub fn R_getEmbeddingDllInfo() -> *mut DllInfo;
pub fn R_FindSymbol(
arg1: *const ::libc::c_char,
arg2: *const ::libc::c_char,
symbol: *mut R_RegisteredNativeSymbol,
) -> DL_FUNC;
pub fn R_RegisterCCallable(
package: *const ::libc::c_char,
name: *const ::libc::c_char,
fptr: DL_FUNC,
) -> ();
pub fn R_GetCCallable(package: *const ::libc::c_char, name: *const ::libc::c_char) -> DL_FUNC;
}
|
random_line_split
|
|
rdynload.rs
|
// automatically generated by rust-bindgen
use super::boolean::*;
#[allow(dead_code)]
const SINGLESXP: u32 = 302;
#[allow(non_camel_case_types)]
pub type DL_FUNC = ::std::option::Option<extern "C" fn() -> *mut ::libc::c_void>;
#[allow(non_camel_case_types)]
pub type R_NativePrimitiveArgType = ::libc::c_uint;
#[allow(non_camel_case_types)]
pub type R_NativeObjectArgType = ::libc::c_uint;
#[repr(C)]
#[derive(Copy, Clone, Debug)]
#[allow(non_camel_case_types)]
pub enum R_NativeArgStyle {
R_ARG_IN = 0,
R_ARG_OUT,
R_ARG_IN_OUT,
R_IRRELEVANT,
}
#[repr(C)]
#[derive(Copy)]
#[allow(non_snake_case)]
pub struct
|
{
pub name: *const ::libc::c_char,
pub fun: DL_FUNC,
pub numArgs: ::libc::c_int,
pub types: *mut R_NativePrimitiveArgType,
pub styles: *mut R_NativeArgStyle,
}
impl ::std::clone::Clone for R_CMethodDef {
fn clone(&self) -> Self {
*self
}
}
impl ::std::default::Default for R_CMethodDef {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
#[allow(non_camel_case_types)]
pub type R_FortranMethodDef = R_CMethodDef;
#[repr(C)]
#[derive(Copy)]
#[allow(non_snake_case)]
pub struct R_CallMethodDef {
pub name: *const ::libc::c_char,
pub fun: DL_FUNC,
pub numArgs: ::libc::c_int,
}
impl ::std::clone::Clone for R_CallMethodDef {
fn clone(&self) -> Self {
*self
}
}
impl ::std::default::Default for R_CallMethodDef {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
#[allow(non_camel_case_types)]
pub type R_ExternalMethodDef = R_CallMethodDef;
#[allow(non_camel_case_types)]
pub enum Struct__DllInfo {
}
pub type DllInfo = Struct__DllInfo;
#[allow(non_camel_case_types)]
pub enum Struct_Rf_RegisteredNativeSymbol {
}
#[allow(non_camel_case_types)]
pub type R_RegisteredNativeSymbol = Struct_Rf_RegisteredNativeSymbol;
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub enum NativeSymbolType {
R_ANY_SYM = 0,
R_C_SYM,
R_CALL_SYM,
R_FORTRAN_SYM,
R_EXTERNAL_SYM,
}
extern "C" {
pub fn R_registerRoutines(
info: *mut DllInfo,
croutines: *const R_CMethodDef,
callRoutines: *const R_CallMethodDef,
fortranRoutines: *const R_FortranMethodDef,
externalRoutines: *const R_ExternalMethodDef,
) -> ::libc::c_int;
pub fn R_useDynamicSymbols(info: *mut DllInfo, value: Rboolean) -> Rboolean;
pub fn R_forceSymbols(info: *mut DllInfo, value: Rboolean) -> Rboolean;
pub fn R_getDllInfo(name: *const ::libc::c_char) -> *mut DllInfo;
pub fn R_getEmbeddingDllInfo() -> *mut DllInfo;
pub fn R_FindSymbol(
arg1: *const ::libc::c_char,
arg2: *const ::libc::c_char,
symbol: *mut R_RegisteredNativeSymbol,
) -> DL_FUNC;
pub fn R_RegisterCCallable(
package: *const ::libc::c_char,
name: *const ::libc::c_char,
fptr: DL_FUNC,
) -> ();
pub fn R_GetCCallable(package: *const ::libc::c_char, name: *const ::libc::c_char) -> DL_FUNC;
}
|
R_CMethodDef
|
identifier_name
|
component.rs
|
use std::comm::{TryRecvError,Empty,Disconnected};
use std::fmt;
use message::{Message,MessageData};
use message::MessageData::{MsgStart};
#[deriving(PartialEq,Clone)]
pub enum ComponentType {
ManagerComponent,
ExtractorComponent,
AudioDecoderComponent,
VideoDecoderComponent,
ClockComponent,
AudioRendererComponent,
VideoRendererComponent,
UiComponent,
}
impl fmt::Show for ComponentType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ComponentType::ManagerComponent => write!(f, "ComponentManager"),
ComponentType::ExtractorComponent => write!(f, "Extractor"),
ComponentType::AudioDecoderComponent => write!(f, "AudioDecoder"),
ComponentType::VideoDecoderComponent => write!(f, "VideoDecoder"),
ComponentType::ClockComponent => write!(f, "Clock"),
ComponentType::AudioRendererComponent => write!(f, "AudioRenderer"),
ComponentType::VideoRendererComponent => write!(f, "VideoRenderer"),
ComponentType::UiComponent => write!(f, "UI"),
}
}
}
pub struct
|
{
pub component_type: ComponentType,
pub mgr_sender: Option<Sender<Message>>,
pub receiver: Receiver<Message>,
pub sender: Option<Sender<Message>>,
}
impl ComponentStruct {
pub fn new(component_type: ComponentType) -> ComponentStruct {
let (sender, receiver) = channel::<Message>();
ComponentStruct {
component_type: component_type,
mgr_sender: None,
receiver: receiver,
sender: Some(sender),
}
}
pub fn set_mgr_sender(&mut self, sender: Sender<Message>) {
self.mgr_sender= Some(sender);
}
pub fn take_sender(&mut self) -> Sender<Message> {
self.sender.take().unwrap()
}
pub fn send(&self, to: ComponentType, msg:MessageData) -> bool {
match self.mgr_sender.as_ref().unwrap().send_opt(Message {
from: self.component_type.clone(),
to: to,
msg: msg
}) {
Ok(_) => true,
Err(_) => false
}
}
pub fn recv(&self) -> Message {
self.receiver.recv()
}
pub fn try_recv(&self) -> Result<Message, TryRecvError> {
self.receiver.try_recv()
}
pub fn flush(&self) {
loop {
match self.receiver.try_recv() {
Ok(_msg) => {
debug!("{} flush", self.component_type);
}
Err(Empty) => {
break
}
Err(Disconnected) => {
break;
}
}
}
}
pub fn wait_for_start(&self) {
match self.recv() {
Message { from: ComponentType::ManagerComponent, msg: MsgStart,.. } => {
info!("start {}", self.component_type);
}
_ => {
panic!("unexpected message received");
}
}
}
}
pub trait Component {
fn get<'a>(&'a mut self) -> &'a mut ComponentStruct;
}
|
ComponentStruct
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.