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
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains traits in script used generically in the rest of Servo. //! The traits are here instead of in script so that these modules won't have //! to depend on script. #![deny(unsafe_code)] #![feature(box_syntax)] #![feature(custom_attribute)] #![feature(custom_derive)] #![feature(nonzero)] #![feature(plugin)] #![plugin(heapsize_plugin)] #![plugin(plugins)] extern crate app_units; #[allow(unused_extern_crates)] #[macro_use] extern crate bitflags; extern crate canvas_traits; extern crate core; extern crate cssparser; extern crate euclid; extern crate gfx_traits; extern crate heapsize; extern crate ipc_channel; extern crate libc; #[macro_use] extern crate log; extern crate msg; extern crate net_traits; extern crate profile_traits; extern crate range; extern crate script_traits; extern crate selectors; #[macro_use(atom, ns)] extern crate string_cache; extern crate style; extern crate url; extern crate util; pub mod message; pub mod reporter; pub mod restyle_damage; pub mod rpc; pub mod wrapper_traits; use canvas_traits::CanvasMsg; use core::nonzero::NonZero; use ipc_channel::ipc::IpcSender; use libc::c_void; use restyle_damage::RestyleDamage; use style::refcell::RefCell; use style::servo::PrivateStyleData; pub struct PartialStyleAndLayoutData { pub style_data: PrivateStyleData, pub restyle_damage: RestyleDamage, } #[derive(Copy, Clone, HeapSizeOf)] pub struct OpaqueStyleAndLayoutData { #[ignore_heap_size_of = "TODO(#6910) Box value that should be counted but \ the type lives in layout"] pub ptr: NonZero<*mut RefCell<PartialStyleAndLayoutData>> } #[allow(unsafe_code)] unsafe impl Send for OpaqueStyleAndLayoutData {} #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum LayoutNodeType { Comment, Document, DocumentFragment, DocumentType, Element(LayoutElementType), ProcessingInstruction, Text, } #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum LayoutElementType { Element, HTMLCanvasElement, HTMLIFrameElement, HTMLImageElement, HTMLInputElement, HTMLObjectElement, HTMLTableCellElement, HTMLTableColElement, HTMLTableElement, HTMLTableRowElement, HTMLTableSectionElement, HTMLTextAreaElement, } pub struct HTMLCanvasData { pub ipc_renderer: Option<IpcSender<CanvasMsg>>, pub width: u32, pub height: u32, } /// The address of a node known to be valid. These are sent from script to layout. #[derive(Clone, PartialEq, Eq, Copy)] pub struct TrustedNodeAddress(pub *const c_void); #[allow(unsafe_code)] unsafe impl Send for TrustedNodeAddress {} pub fn is_image_data(uri: &str) -> bool
{ static TYPES: &'static [&'static str] = &["data:image/png", "data:image/gif", "data:image/jpeg"]; TYPES.iter().any(|&type_| uri.starts_with(type_)) }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains traits in script used generically in the rest of Servo. //! The traits are here instead of in script so that these modules won't have //! to depend on script. #![deny(unsafe_code)] #![feature(box_syntax)] #![feature(custom_attribute)] #![feature(custom_derive)] #![feature(nonzero)] #![feature(plugin)] #![plugin(heapsize_plugin)] #![plugin(plugins)] extern crate app_units; #[allow(unused_extern_crates)] #[macro_use] extern crate bitflags; extern crate canvas_traits; extern crate core; extern crate cssparser; extern crate euclid; extern crate gfx_traits; extern crate heapsize; extern crate ipc_channel; extern crate libc; #[macro_use] extern crate log; extern crate msg; extern crate net_traits; extern crate profile_traits; extern crate range; extern crate script_traits; extern crate selectors; #[macro_use(atom, ns)] extern crate string_cache; extern crate style; extern crate url; extern crate util; pub mod message; pub mod reporter; pub mod restyle_damage; pub mod rpc; pub mod wrapper_traits; use canvas_traits::CanvasMsg; use core::nonzero::NonZero; use ipc_channel::ipc::IpcSender; use libc::c_void; use restyle_damage::RestyleDamage; use style::refcell::RefCell; use style::servo::PrivateStyleData; pub struct PartialStyleAndLayoutData { pub style_data: PrivateStyleData, pub restyle_damage: RestyleDamage, } #[derive(Copy, Clone, HeapSizeOf)] pub struct
{ #[ignore_heap_size_of = "TODO(#6910) Box value that should be counted but \ the type lives in layout"] pub ptr: NonZero<*mut RefCell<PartialStyleAndLayoutData>> } #[allow(unsafe_code)] unsafe impl Send for OpaqueStyleAndLayoutData {} #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum LayoutNodeType { Comment, Document, DocumentFragment, DocumentType, Element(LayoutElementType), ProcessingInstruction, Text, } #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum LayoutElementType { Element, HTMLCanvasElement, HTMLIFrameElement, HTMLImageElement, HTMLInputElement, HTMLObjectElement, HTMLTableCellElement, HTMLTableColElement, HTMLTableElement, HTMLTableRowElement, HTMLTableSectionElement, HTMLTextAreaElement, } pub struct HTMLCanvasData { pub ipc_renderer: Option<IpcSender<CanvasMsg>>, pub width: u32, pub height: u32, } /// The address of a node known to be valid. These are sent from script to layout. #[derive(Clone, PartialEq, Eq, Copy)] pub struct TrustedNodeAddress(pub *const c_void); #[allow(unsafe_code)] unsafe impl Send for TrustedNodeAddress {} pub fn is_image_data(uri: &str) -> bool { static TYPES: &'static [&'static str] = &["data:image/png", "data:image/gif", "data:image/jpeg"]; TYPES.iter().any(|&type_| uri.starts_with(type_)) }
OpaqueStyleAndLayoutData
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains traits in script used generically in the rest of Servo. //! The traits are here instead of in script so that these modules won't have //! to depend on script. #![deny(unsafe_code)] #![feature(box_syntax)] #![feature(custom_attribute)] #![feature(custom_derive)] #![feature(nonzero)] #![feature(plugin)] #![plugin(heapsize_plugin)] #![plugin(plugins)] extern crate app_units; #[allow(unused_extern_crates)] #[macro_use] extern crate bitflags; extern crate canvas_traits; extern crate core; extern crate cssparser; extern crate euclid; extern crate gfx_traits; extern crate heapsize; extern crate ipc_channel; extern crate libc; #[macro_use] extern crate log; extern crate msg; extern crate net_traits; extern crate profile_traits; extern crate range; extern crate script_traits; extern crate selectors; #[macro_use(atom, ns)] extern crate string_cache; extern crate style; extern crate url; extern crate util; pub mod message; pub mod reporter; pub mod restyle_damage; pub mod rpc; pub mod wrapper_traits; use canvas_traits::CanvasMsg; use core::nonzero::NonZero;
use style::servo::PrivateStyleData; pub struct PartialStyleAndLayoutData { pub style_data: PrivateStyleData, pub restyle_damage: RestyleDamage, } #[derive(Copy, Clone, HeapSizeOf)] pub struct OpaqueStyleAndLayoutData { #[ignore_heap_size_of = "TODO(#6910) Box value that should be counted but \ the type lives in layout"] pub ptr: NonZero<*mut RefCell<PartialStyleAndLayoutData>> } #[allow(unsafe_code)] unsafe impl Send for OpaqueStyleAndLayoutData {} #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum LayoutNodeType { Comment, Document, DocumentFragment, DocumentType, Element(LayoutElementType), ProcessingInstruction, Text, } #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum LayoutElementType { Element, HTMLCanvasElement, HTMLIFrameElement, HTMLImageElement, HTMLInputElement, HTMLObjectElement, HTMLTableCellElement, HTMLTableColElement, HTMLTableElement, HTMLTableRowElement, HTMLTableSectionElement, HTMLTextAreaElement, } pub struct HTMLCanvasData { pub ipc_renderer: Option<IpcSender<CanvasMsg>>, pub width: u32, pub height: u32, } /// The address of a node known to be valid. These are sent from script to layout. #[derive(Clone, PartialEq, Eq, Copy)] pub struct TrustedNodeAddress(pub *const c_void); #[allow(unsafe_code)] unsafe impl Send for TrustedNodeAddress {} pub fn is_image_data(uri: &str) -> bool { static TYPES: &'static [&'static str] = &["data:image/png", "data:image/gif", "data:image/jpeg"]; TYPES.iter().any(|&type_| uri.starts_with(type_)) }
use ipc_channel::ipc::IpcSender; use libc::c_void; use restyle_damage::RestyleDamage; use style::refcell::RefCell;
random_line_split
borrowck-pat-enum.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. fn match_ref(v: Option<int>) -> int { match v { Some(ref i) => { *i } None => {0} } } fn match_ref_unused(v: Option<int>) { match v { Some(_) => {} None => {} } } fn match_const_reg(v: &const Option<int>) -> int { match *v { Some(ref i) => {*i} //~ ERROR cannot borrow //~^ ERROR unsafe borrow None => {0} } } fn
(_i: int) { } fn match_const_reg_unused(v: &const Option<int>) { match *v { Some(_) => {impure(0)} // OK because nothing is captured None => {} } } fn match_const_reg_impure(v: &const Option<int>) { match *v { Some(ref i) => {impure(*i)} //~ ERROR cannot borrow //~^ ERROR unsafe borrow None => {} } } fn match_imm_reg(v: &Option<int>) { match *v { Some(ref i) => {impure(*i)} // OK because immutable None => {} } } fn match_mut_reg(v: &mut Option<int>) { match *v { Some(ref i) => {impure(*i)} // OK, frozen None => {} } } fn main() { }
impure
identifier_name
borrowck-pat-enum.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. fn match_ref(v: Option<int>) -> int { match v { Some(ref i) => { *i } None => {0} } } fn match_ref_unused(v: Option<int>) { match v { Some(_) => {} None => {} } } fn match_const_reg(v: &const Option<int>) -> int { match *v { Some(ref i) => {*i} //~ ERROR cannot borrow //~^ ERROR unsafe borrow None => {0} } } fn impure(_i: int) { } fn match_const_reg_unused(v: &const Option<int>) { match *v { Some(_) => {impure(0)} // OK because nothing is captured None => {} } } fn match_const_reg_impure(v: &const Option<int>) { match *v { Some(ref i) => {impure(*i)} //~ ERROR cannot borrow //~^ ERROR unsafe borrow None => {} } } fn match_imm_reg(v: &Option<int>) { match *v { Some(ref i) => {impure(*i)} // OK because immutable None => {} } } fn match_mut_reg(v: &mut Option<int>) { match *v { Some(ref i) => {impure(*i)} // OK, frozen None => {} } } fn main()
{ }
identifier_body
borrowck-pat-enum.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. fn match_ref(v: Option<int>) -> int { match v { Some(ref i) => { *i } None => {0} } } fn match_ref_unused(v: Option<int>) { match v { Some(_) => {} None =>
} } fn match_const_reg(v: &const Option<int>) -> int { match *v { Some(ref i) => {*i} //~ ERROR cannot borrow //~^ ERROR unsafe borrow None => {0} } } fn impure(_i: int) { } fn match_const_reg_unused(v: &const Option<int>) { match *v { Some(_) => {impure(0)} // OK because nothing is captured None => {} } } fn match_const_reg_impure(v: &const Option<int>) { match *v { Some(ref i) => {impure(*i)} //~ ERROR cannot borrow //~^ ERROR unsafe borrow None => {} } } fn match_imm_reg(v: &Option<int>) { match *v { Some(ref i) => {impure(*i)} // OK because immutable None => {} } } fn match_mut_reg(v: &mut Option<int>) { match *v { Some(ref i) => {impure(*i)} // OK, frozen None => {} } } fn main() { }
{}
conditional_block
borrowck-pat-enum.rs
// Copyright 2012 The Rust Project Developers. See the 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. fn match_ref(v: Option<int>) -> int { match v { Some(ref i) => { *i } None => {0} } } fn match_ref_unused(v: Option<int>) { match v { Some(_) => {} None => {} } } fn match_const_reg(v: &const Option<int>) -> int { match *v { Some(ref i) => {*i} //~ ERROR cannot borrow //~^ ERROR unsafe borrow None => {0} } } fn impure(_i: int) { } fn match_const_reg_unused(v: &const Option<int>) { match *v { Some(_) => {impure(0)} // OK because nothing is captured None => {} } } fn match_const_reg_impure(v: &const Option<int>) { match *v { Some(ref i) => {impure(*i)} //~ ERROR cannot borrow //~^ ERROR unsafe borrow None => {} } } fn match_imm_reg(v: &Option<int>) { match *v { Some(ref i) => {impure(*i)} // OK because immutable None => {} } } fn match_mut_reg(v: &mut Option<int>) { match *v { Some(ref i) => {impure(*i)} // OK, frozen None => {} } } fn main() { }
// file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
random_line_split
simple.rs
extern crate klee; #[test] fn basic_test() { let mut a : i32 = 0; klee::symbol(&mut a, "a"); assert_eq!(a, 56); } #[test] fn other_test() { let mut a : i32 = 0; let mut b : i32 = 0; klee::symbol(&mut a, "a"); klee::symbol(&mut b, "b"); if a == 50 && b == 50 { panic!("I should happen!"); } } #[test] fn yant() { let a = klee::some::<bool>("a"); let b = klee::some::<i32>("b"); let c = if a { if b > 50 && b < 100 { true } else { false } } else { true }; assert_eq!(c, false); } #[test] fn another_test() { let a = klee::some::<i32>("a"); if a > 60 && a < 90 { let b = a + 40; assert_eq!(b, 0); if b == 12 { panic!("This path should be unreachable"); } assert_eq!(b, 101);
} }
assert_eq!(b, 150000);
random_line_split
simple.rs
extern crate klee; #[test] fn
() { let mut a : i32 = 0; klee::symbol(&mut a, "a"); assert_eq!(a, 56); } #[test] fn other_test() { let mut a : i32 = 0; let mut b : i32 = 0; klee::symbol(&mut a, "a"); klee::symbol(&mut b, "b"); if a == 50 && b == 50 { panic!("I should happen!"); } } #[test] fn yant() { let a = klee::some::<bool>("a"); let b = klee::some::<i32>("b"); let c = if a { if b > 50 && b < 100 { true } else { false } } else { true }; assert_eq!(c, false); } #[test] fn another_test() { let a = klee::some::<i32>("a"); if a > 60 && a < 90 { let b = a + 40; assert_eq!(b, 0); if b == 12 { panic!("This path should be unreachable"); } assert_eq!(b, 101); assert_eq!(b, 150000); } }
basic_test
identifier_name
simple.rs
extern crate klee; #[test] fn basic_test()
#[test] fn other_test() { let mut a : i32 = 0; let mut b : i32 = 0; klee::symbol(&mut a, "a"); klee::symbol(&mut b, "b"); if a == 50 && b == 50 { panic!("I should happen!"); } } #[test] fn yant() { let a = klee::some::<bool>("a"); let b = klee::some::<i32>("b"); let c = if a { if b > 50 && b < 100 { true } else { false } } else { true }; assert_eq!(c, false); } #[test] fn another_test() { let a = klee::some::<i32>("a"); if a > 60 && a < 90 { let b = a + 40; assert_eq!(b, 0); if b == 12 { panic!("This path should be unreachable"); } assert_eq!(b, 101); assert_eq!(b, 150000); } }
{ let mut a : i32 = 0; klee::symbol(&mut a, "a"); assert_eq!(a, 56); }
identifier_body
simple.rs
extern crate klee; #[test] fn basic_test() { let mut a : i32 = 0; klee::symbol(&mut a, "a"); assert_eq!(a, 56); } #[test] fn other_test() { let mut a : i32 = 0; let mut b : i32 = 0; klee::symbol(&mut a, "a"); klee::symbol(&mut b, "b"); if a == 50 && b == 50
} #[test] fn yant() { let a = klee::some::<bool>("a"); let b = klee::some::<i32>("b"); let c = if a { if b > 50 && b < 100 { true } else { false } } else { true }; assert_eq!(c, false); } #[test] fn another_test() { let a = klee::some::<i32>("a"); if a > 60 && a < 90 { let b = a + 40; assert_eq!(b, 0); if b == 12 { panic!("This path should be unreachable"); } assert_eq!(b, 101); assert_eq!(b, 150000); } }
{ panic!("I should happen!"); }
conditional_block
mod.rs
use std::ops::BitXor; use error::{LengthError, LengthResult, LengthErrorKind}; mod builder; pub use sha::builder::ShaHashBuilder; /// Length of a SHA-1 hash. pub const SHA_HASH_LEN: usize = 20; /// SHA-1 hash wrapper type for performing operations on the hash. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)] pub struct ShaHash { hash: [u8; SHA_HASH_LEN], } impl ShaHash { /// Create a ShaHash by hashing the given bytes. pub fn from_bytes(bytes: &[u8]) -> ShaHash { ShaHashBuilder::new().add_bytes(bytes).build() } /// Create a ShaHash directly from the given hash. pub fn from_hash(hash: &[u8]) -> LengthResult<ShaHash> { if hash.len()!= SHA_HASH_LEN { Err(LengthError::new(LengthErrorKind::LengthExpected, SHA_HASH_LEN)) } else { let mut my_hash = [0u8; SHA_HASH_LEN]; my_hash.iter_mut().zip(hash.iter()).map(|(dst, src)| *dst = *src).count(); Ok(ShaHash { hash: my_hash }) } } pub fn bits<'a>(&'a self) -> Bits<'a> { Bits::new(&self.hash) } pub fn len() -> usize { SHA_HASH_LEN } } impl AsRef<[u8]> for ShaHash { fn as_ref(&self) -> &[u8] { &self.hash } } impl Into<[u8; SHA_HASH_LEN]> for ShaHash { fn into(self) -> [u8; SHA_HASH_LEN] { self.hash } } impl From<[u8; SHA_HASH_LEN]> for ShaHash { fn from(sha_hash: [u8; SHA_HASH_LEN]) -> ShaHash { ShaHash { hash: sha_hash } } } impl PartialEq<[u8]> for ShaHash { fn eq(&self, other: &[u8]) -> bool { let is_equal = other.len() == self.hash.len(); self.hash.iter().zip(other.iter()).fold(is_equal, |prev, (h, o)| prev && h == o) } } impl BitXor<ShaHash> for ShaHash { type Output = ShaHash; fn bitxor(mut self, rhs: ShaHash) -> ShaHash { for (src, dst) in rhs.hash.iter().zip(self.hash.iter_mut()) { *dst = *src ^ *dst; } self } } // ----------------------------------------------------------------------------// /// Representation of a bit after a xor operation. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub enum XorRep { /// Bits were equal (1). Diff, /// Bits were not equal (0). Same, } /// Iterator over the bits of a xor operation. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub struct XorBits<'a> { bits: Bits<'a>, } impl<'a> Iterator for XorBits<'a> { type Item = XorRep; fn next(&mut self) -> Option<XorRep> { self.bits.next().map(|n| { match n { BitRep::Set => XorRep::Diff, BitRep::Unset => XorRep::Same, } }) } } // ----------------------------------------------------------------------------// /// Representation of a bit. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub enum BitRep { /// Bit is set (1). Set, /// Bit is not set (0). Unset, } impl PartialEq<XorRep> for BitRep { fn eq(&self, other: &XorRep) -> bool { match (self, other) { (&BitRep::Set, &XorRep::Diff) => true, (&BitRep::Unset, &XorRep::Same) => true, _ => false, } } } /// Iterator over some bits. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub struct Bits<'a> { bytes: &'a [u8], bit_pos: usize, } impl<'a> Bits<'a> { fn new(bytes: &'a [u8]) -> Bits<'a> { Bits { bytes: bytes, bit_pos: 0, } } } impl<'a> Iterator for Bits<'a> { type Item = BitRep; fn next(&mut self) -> Option<BitRep> { if self.bit_pos < self.bytes.len() * 8 { let byte_index = self.bit_pos / 8; let bit_offset = 7 - (self.bit_pos % 8); let bit_value = self.bytes[byte_index] >> bit_offset; self.bit_pos += 1; Some(bit_value).map(|x| if x == 1 { BitRep::Set } else { BitRep::Unset }) } else { None } } } // ----------------------------------------------------------------------------// #[cfg(test)] mod tests { use super::{ShaHash, XorRep}; #[test] fn positive_no_leading_zeroes() { let zero_bits = ShaHash::from([0u8; super::SHA_HASH_LEN]); let one_bits = ShaHash::from([255u8; super::SHA_HASH_LEN]); let xor_hash = zero_bits ^ one_bits; let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count(); assert!(leading_zeroes == 0); } #[test] fn
() { let first_one_bits = ShaHash::from([255u8; super::SHA_HASH_LEN]); let second_one_bits = ShaHash::from([255u8; super::SHA_HASH_LEN]); let xor_hash = first_one_bits ^ second_one_bits; let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count(); assert!(leading_zeroes == (super::SHA_HASH_LEN * 8)); } #[test] fn positive_one_leading_zero() { let zero_bits = ShaHash::from([0u8; super::SHA_HASH_LEN]); let mut bytes = [255u8; super::SHA_HASH_LEN]; bytes[0] = 127; let mostly_one_bits = ShaHash::from(bytes); let xor_hash = zero_bits ^ mostly_one_bits; let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count(); assert!(leading_zeroes == 1); } #[test] fn positive_one_trailing_zero() { let zero_bits = ShaHash::from([0u8; super::SHA_HASH_LEN]); let mut bytes = [255u8; super::SHA_HASH_LEN]; bytes[super::SHA_HASH_LEN - 1] = 254; let mostly_zero_bits = ShaHash::from(bytes); let xor_hash = zero_bits ^ mostly_zero_bits; let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count(); assert!(leading_zeroes == 0); } #[test] #[should_panic] fn negative_from_hash_too_long() { let bits = [0u8; super::SHA_HASH_LEN + 1]; ShaHash::from_hash(&bits).unwrap(); } #[test] #[should_panic] fn negative_from_hash_too_short() { let bits = [0u8; super::SHA_HASH_LEN - 1]; ShaHash::from_hash(&bits).unwrap(); } }
positive_all_leading_zeroes
identifier_name
mod.rs
use std::ops::BitXor; use error::{LengthError, LengthResult, LengthErrorKind}; mod builder; pub use sha::builder::ShaHashBuilder; /// Length of a SHA-1 hash. pub const SHA_HASH_LEN: usize = 20; /// SHA-1 hash wrapper type for performing operations on the hash. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)] pub struct ShaHash { hash: [u8; SHA_HASH_LEN], } impl ShaHash { /// Create a ShaHash by hashing the given bytes. pub fn from_bytes(bytes: &[u8]) -> ShaHash { ShaHashBuilder::new().add_bytes(bytes).build() } /// Create a ShaHash directly from the given hash. pub fn from_hash(hash: &[u8]) -> LengthResult<ShaHash> { if hash.len()!= SHA_HASH_LEN { Err(LengthError::new(LengthErrorKind::LengthExpected, SHA_HASH_LEN)) } else { let mut my_hash = [0u8; SHA_HASH_LEN]; my_hash.iter_mut().zip(hash.iter()).map(|(dst, src)| *dst = *src).count(); Ok(ShaHash { hash: my_hash }) } } pub fn bits<'a>(&'a self) -> Bits<'a> { Bits::new(&self.hash) } pub fn len() -> usize { SHA_HASH_LEN } } impl AsRef<[u8]> for ShaHash { fn as_ref(&self) -> &[u8] { &self.hash } } impl Into<[u8; SHA_HASH_LEN]> for ShaHash { fn into(self) -> [u8; SHA_HASH_LEN] { self.hash } } impl From<[u8; SHA_HASH_LEN]> for ShaHash { fn from(sha_hash: [u8; SHA_HASH_LEN]) -> ShaHash { ShaHash { hash: sha_hash } } } impl PartialEq<[u8]> for ShaHash { fn eq(&self, other: &[u8]) -> bool { let is_equal = other.len() == self.hash.len(); self.hash.iter().zip(other.iter()).fold(is_equal, |prev, (h, o)| prev && h == o) } } impl BitXor<ShaHash> for ShaHash { type Output = ShaHash; fn bitxor(mut self, rhs: ShaHash) -> ShaHash
} // ----------------------------------------------------------------------------// /// Representation of a bit after a xor operation. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub enum XorRep { /// Bits were equal (1). Diff, /// Bits were not equal (0). Same, } /// Iterator over the bits of a xor operation. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub struct XorBits<'a> { bits: Bits<'a>, } impl<'a> Iterator for XorBits<'a> { type Item = XorRep; fn next(&mut self) -> Option<XorRep> { self.bits.next().map(|n| { match n { BitRep::Set => XorRep::Diff, BitRep::Unset => XorRep::Same, } }) } } // ----------------------------------------------------------------------------// /// Representation of a bit. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub enum BitRep { /// Bit is set (1). Set, /// Bit is not set (0). Unset, } impl PartialEq<XorRep> for BitRep { fn eq(&self, other: &XorRep) -> bool { match (self, other) { (&BitRep::Set, &XorRep::Diff) => true, (&BitRep::Unset, &XorRep::Same) => true, _ => false, } } } /// Iterator over some bits. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub struct Bits<'a> { bytes: &'a [u8], bit_pos: usize, } impl<'a> Bits<'a> { fn new(bytes: &'a [u8]) -> Bits<'a> { Bits { bytes: bytes, bit_pos: 0, } } } impl<'a> Iterator for Bits<'a> { type Item = BitRep; fn next(&mut self) -> Option<BitRep> { if self.bit_pos < self.bytes.len() * 8 { let byte_index = self.bit_pos / 8; let bit_offset = 7 - (self.bit_pos % 8); let bit_value = self.bytes[byte_index] >> bit_offset; self.bit_pos += 1; Some(bit_value).map(|x| if x == 1 { BitRep::Set } else { BitRep::Unset }) } else { None } } } // ----------------------------------------------------------------------------// #[cfg(test)] mod tests { use super::{ShaHash, XorRep}; #[test] fn positive_no_leading_zeroes() { let zero_bits = ShaHash::from([0u8; super::SHA_HASH_LEN]); let one_bits = ShaHash::from([255u8; super::SHA_HASH_LEN]); let xor_hash = zero_bits ^ one_bits; let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count(); assert!(leading_zeroes == 0); } #[test] fn positive_all_leading_zeroes() { let first_one_bits = ShaHash::from([255u8; super::SHA_HASH_LEN]); let second_one_bits = ShaHash::from([255u8; super::SHA_HASH_LEN]); let xor_hash = first_one_bits ^ second_one_bits; let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count(); assert!(leading_zeroes == (super::SHA_HASH_LEN * 8)); } #[test] fn positive_one_leading_zero() { let zero_bits = ShaHash::from([0u8; super::SHA_HASH_LEN]); let mut bytes = [255u8; super::SHA_HASH_LEN]; bytes[0] = 127; let mostly_one_bits = ShaHash::from(bytes); let xor_hash = zero_bits ^ mostly_one_bits; let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count(); assert!(leading_zeroes == 1); } #[test] fn positive_one_trailing_zero() { let zero_bits = ShaHash::from([0u8; super::SHA_HASH_LEN]); let mut bytes = [255u8; super::SHA_HASH_LEN]; bytes[super::SHA_HASH_LEN - 1] = 254; let mostly_zero_bits = ShaHash::from(bytes); let xor_hash = zero_bits ^ mostly_zero_bits; let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count(); assert!(leading_zeroes == 0); } #[test] #[should_panic] fn negative_from_hash_too_long() { let bits = [0u8; super::SHA_HASH_LEN + 1]; ShaHash::from_hash(&bits).unwrap(); } #[test] #[should_panic] fn negative_from_hash_too_short() { let bits = [0u8; super::SHA_HASH_LEN - 1]; ShaHash::from_hash(&bits).unwrap(); } }
{ for (src, dst) in rhs.hash.iter().zip(self.hash.iter_mut()) { *dst = *src ^ *dst; } self }
identifier_body
mod.rs
use std::ops::BitXor; use error::{LengthError, LengthResult, LengthErrorKind}; mod builder; pub use sha::builder::ShaHashBuilder; /// Length of a SHA-1 hash. pub const SHA_HASH_LEN: usize = 20; /// SHA-1 hash wrapper type for performing operations on the hash. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)] pub struct ShaHash { hash: [u8; SHA_HASH_LEN], } impl ShaHash { /// Create a ShaHash by hashing the given bytes. pub fn from_bytes(bytes: &[u8]) -> ShaHash { ShaHashBuilder::new().add_bytes(bytes).build() } /// Create a ShaHash directly from the given hash. pub fn from_hash(hash: &[u8]) -> LengthResult<ShaHash> { if hash.len()!= SHA_HASH_LEN { Err(LengthError::new(LengthErrorKind::LengthExpected, SHA_HASH_LEN)) } else { let mut my_hash = [0u8; SHA_HASH_LEN]; my_hash.iter_mut().zip(hash.iter()).map(|(dst, src)| *dst = *src).count(); Ok(ShaHash { hash: my_hash }) } } pub fn bits<'a>(&'a self) -> Bits<'a> { Bits::new(&self.hash) } pub fn len() -> usize { SHA_HASH_LEN } } impl AsRef<[u8]> for ShaHash { fn as_ref(&self) -> &[u8] { &self.hash } } impl Into<[u8; SHA_HASH_LEN]> for ShaHash { fn into(self) -> [u8; SHA_HASH_LEN] { self.hash } } impl From<[u8; SHA_HASH_LEN]> for ShaHash { fn from(sha_hash: [u8; SHA_HASH_LEN]) -> ShaHash { ShaHash { hash: sha_hash } } } impl PartialEq<[u8]> for ShaHash { fn eq(&self, other: &[u8]) -> bool { let is_equal = other.len() == self.hash.len(); self.hash.iter().zip(other.iter()).fold(is_equal, |prev, (h, o)| prev && h == o) } } impl BitXor<ShaHash> for ShaHash { type Output = ShaHash; fn bitxor(mut self, rhs: ShaHash) -> ShaHash { for (src, dst) in rhs.hash.iter().zip(self.hash.iter_mut()) { *dst = *src ^ *dst; } self } } // ----------------------------------------------------------------------------// /// Representation of a bit after a xor operation. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub enum XorRep { /// Bits were equal (1). Diff, /// Bits were not equal (0). Same, } /// Iterator over the bits of a xor operation. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub struct XorBits<'a> { bits: Bits<'a>, } impl<'a> Iterator for XorBits<'a> { type Item = XorRep; fn next(&mut self) -> Option<XorRep> {
}) } } // ----------------------------------------------------------------------------// /// Representation of a bit. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub enum BitRep { /// Bit is set (1). Set, /// Bit is not set (0). Unset, } impl PartialEq<XorRep> for BitRep { fn eq(&self, other: &XorRep) -> bool { match (self, other) { (&BitRep::Set, &XorRep::Diff) => true, (&BitRep::Unset, &XorRep::Same) => true, _ => false, } } } /// Iterator over some bits. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub struct Bits<'a> { bytes: &'a [u8], bit_pos: usize, } impl<'a> Bits<'a> { fn new(bytes: &'a [u8]) -> Bits<'a> { Bits { bytes: bytes, bit_pos: 0, } } } impl<'a> Iterator for Bits<'a> { type Item = BitRep; fn next(&mut self) -> Option<BitRep> { if self.bit_pos < self.bytes.len() * 8 { let byte_index = self.bit_pos / 8; let bit_offset = 7 - (self.bit_pos % 8); let bit_value = self.bytes[byte_index] >> bit_offset; self.bit_pos += 1; Some(bit_value).map(|x| if x == 1 { BitRep::Set } else { BitRep::Unset }) } else { None } } } // ----------------------------------------------------------------------------// #[cfg(test)] mod tests { use super::{ShaHash, XorRep}; #[test] fn positive_no_leading_zeroes() { let zero_bits = ShaHash::from([0u8; super::SHA_HASH_LEN]); let one_bits = ShaHash::from([255u8; super::SHA_HASH_LEN]); let xor_hash = zero_bits ^ one_bits; let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count(); assert!(leading_zeroes == 0); } #[test] fn positive_all_leading_zeroes() { let first_one_bits = ShaHash::from([255u8; super::SHA_HASH_LEN]); let second_one_bits = ShaHash::from([255u8; super::SHA_HASH_LEN]); let xor_hash = first_one_bits ^ second_one_bits; let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count(); assert!(leading_zeroes == (super::SHA_HASH_LEN * 8)); } #[test] fn positive_one_leading_zero() { let zero_bits = ShaHash::from([0u8; super::SHA_HASH_LEN]); let mut bytes = [255u8; super::SHA_HASH_LEN]; bytes[0] = 127; let mostly_one_bits = ShaHash::from(bytes); let xor_hash = zero_bits ^ mostly_one_bits; let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count(); assert!(leading_zeroes == 1); } #[test] fn positive_one_trailing_zero() { let zero_bits = ShaHash::from([0u8; super::SHA_HASH_LEN]); let mut bytes = [255u8; super::SHA_HASH_LEN]; bytes[super::SHA_HASH_LEN - 1] = 254; let mostly_zero_bits = ShaHash::from(bytes); let xor_hash = zero_bits ^ mostly_zero_bits; let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count(); assert!(leading_zeroes == 0); } #[test] #[should_panic] fn negative_from_hash_too_long() { let bits = [0u8; super::SHA_HASH_LEN + 1]; ShaHash::from_hash(&bits).unwrap(); } #[test] #[should_panic] fn negative_from_hash_too_short() { let bits = [0u8; super::SHA_HASH_LEN - 1]; ShaHash::from_hash(&bits).unwrap(); } }
self.bits.next().map(|n| { match n { BitRep::Set => XorRep::Diff, BitRep::Unset => XorRep::Same, }
random_line_split
mod.rs
use std::ops::BitXor; use error::{LengthError, LengthResult, LengthErrorKind}; mod builder; pub use sha::builder::ShaHashBuilder; /// Length of a SHA-1 hash. pub const SHA_HASH_LEN: usize = 20; /// SHA-1 hash wrapper type for performing operations on the hash. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)] pub struct ShaHash { hash: [u8; SHA_HASH_LEN], } impl ShaHash { /// Create a ShaHash by hashing the given bytes. pub fn from_bytes(bytes: &[u8]) -> ShaHash { ShaHashBuilder::new().add_bytes(bytes).build() } /// Create a ShaHash directly from the given hash. pub fn from_hash(hash: &[u8]) -> LengthResult<ShaHash> { if hash.len()!= SHA_HASH_LEN { Err(LengthError::new(LengthErrorKind::LengthExpected, SHA_HASH_LEN)) } else { let mut my_hash = [0u8; SHA_HASH_LEN]; my_hash.iter_mut().zip(hash.iter()).map(|(dst, src)| *dst = *src).count(); Ok(ShaHash { hash: my_hash }) } } pub fn bits<'a>(&'a self) -> Bits<'a> { Bits::new(&self.hash) } pub fn len() -> usize { SHA_HASH_LEN } } impl AsRef<[u8]> for ShaHash { fn as_ref(&self) -> &[u8] { &self.hash } } impl Into<[u8; SHA_HASH_LEN]> for ShaHash { fn into(self) -> [u8; SHA_HASH_LEN] { self.hash } } impl From<[u8; SHA_HASH_LEN]> for ShaHash { fn from(sha_hash: [u8; SHA_HASH_LEN]) -> ShaHash { ShaHash { hash: sha_hash } } } impl PartialEq<[u8]> for ShaHash { fn eq(&self, other: &[u8]) -> bool { let is_equal = other.len() == self.hash.len(); self.hash.iter().zip(other.iter()).fold(is_equal, |prev, (h, o)| prev && h == o) } } impl BitXor<ShaHash> for ShaHash { type Output = ShaHash; fn bitxor(mut self, rhs: ShaHash) -> ShaHash { for (src, dst) in rhs.hash.iter().zip(self.hash.iter_mut()) { *dst = *src ^ *dst; } self } } // ----------------------------------------------------------------------------// /// Representation of a bit after a xor operation. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub enum XorRep { /// Bits were equal (1). Diff, /// Bits were not equal (0). Same, } /// Iterator over the bits of a xor operation. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub struct XorBits<'a> { bits: Bits<'a>, } impl<'a> Iterator for XorBits<'a> { type Item = XorRep; fn next(&mut self) -> Option<XorRep> { self.bits.next().map(|n| { match n { BitRep::Set => XorRep::Diff, BitRep::Unset => XorRep::Same, } }) } } // ----------------------------------------------------------------------------// /// Representation of a bit. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub enum BitRep { /// Bit is set (1). Set, /// Bit is not set (0). Unset, } impl PartialEq<XorRep> for BitRep { fn eq(&self, other: &XorRep) -> bool { match (self, other) { (&BitRep::Set, &XorRep::Diff) => true, (&BitRep::Unset, &XorRep::Same) => true, _ => false, } } } /// Iterator over some bits. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub struct Bits<'a> { bytes: &'a [u8], bit_pos: usize, } impl<'a> Bits<'a> { fn new(bytes: &'a [u8]) -> Bits<'a> { Bits { bytes: bytes, bit_pos: 0, } } } impl<'a> Iterator for Bits<'a> { type Item = BitRep; fn next(&mut self) -> Option<BitRep> { if self.bit_pos < self.bytes.len() * 8 { let byte_index = self.bit_pos / 8; let bit_offset = 7 - (self.bit_pos % 8); let bit_value = self.bytes[byte_index] >> bit_offset; self.bit_pos += 1; Some(bit_value).map(|x| if x == 1 { BitRep::Set } else { BitRep::Unset }) } else
} } // ----------------------------------------------------------------------------// #[cfg(test)] mod tests { use super::{ShaHash, XorRep}; #[test] fn positive_no_leading_zeroes() { let zero_bits = ShaHash::from([0u8; super::SHA_HASH_LEN]); let one_bits = ShaHash::from([255u8; super::SHA_HASH_LEN]); let xor_hash = zero_bits ^ one_bits; let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count(); assert!(leading_zeroes == 0); } #[test] fn positive_all_leading_zeroes() { let first_one_bits = ShaHash::from([255u8; super::SHA_HASH_LEN]); let second_one_bits = ShaHash::from([255u8; super::SHA_HASH_LEN]); let xor_hash = first_one_bits ^ second_one_bits; let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count(); assert!(leading_zeroes == (super::SHA_HASH_LEN * 8)); } #[test] fn positive_one_leading_zero() { let zero_bits = ShaHash::from([0u8; super::SHA_HASH_LEN]); let mut bytes = [255u8; super::SHA_HASH_LEN]; bytes[0] = 127; let mostly_one_bits = ShaHash::from(bytes); let xor_hash = zero_bits ^ mostly_one_bits; let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count(); assert!(leading_zeroes == 1); } #[test] fn positive_one_trailing_zero() { let zero_bits = ShaHash::from([0u8; super::SHA_HASH_LEN]); let mut bytes = [255u8; super::SHA_HASH_LEN]; bytes[super::SHA_HASH_LEN - 1] = 254; let mostly_zero_bits = ShaHash::from(bytes); let xor_hash = zero_bits ^ mostly_zero_bits; let leading_zeroes = xor_hash.bits().take_while(|&n| n == XorRep::Same).count(); assert!(leading_zeroes == 0); } #[test] #[should_panic] fn negative_from_hash_too_long() { let bits = [0u8; super::SHA_HASH_LEN + 1]; ShaHash::from_hash(&bits).unwrap(); } #[test] #[should_panic] fn negative_from_hash_too_short() { let bits = [0u8; super::SHA_HASH_LEN - 1]; ShaHash::from_hash(&bits).unwrap(); } }
{ None }
conditional_block
post_drop_elaboration.rs
use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::{self, BasicBlock, Location}; use rustc_middle::ty::TyCtxt; use rustc_span::{symbol::sym, Span}; use super::check::Qualifs; use super::ops::{self, NonConstOp}; use super::qualifs::{NeedsNonConstDrop, Qualif}; use super::ConstCx; /// Returns `true` if we should use the more precise live drop checker that runs after drop /// elaboration. pub fn checking_enabled(ccx: &ConstCx<'_, '_>) -> bool { // Const-stable functions must always use the stable live drop checker. if ccx.is_const_stable_const_fn() { return false; } ccx.tcx.features().const_precise_live_drops } /// Look for live drops in a const context. /// /// This is separate from the rest of the const checking logic because it must run after drop /// elaboration. pub fn
(tcx: TyCtxt<'tcx>, body: &mir::Body<'tcx>) { let def_id = body.source.def_id().expect_local(); let const_kind = tcx.hir().body_const_context(def_id); if const_kind.is_none() { return; } if tcx.has_attr(def_id.to_def_id(), sym::rustc_do_not_const_check) { return; } let ccx = ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def_id) }; if!checking_enabled(&ccx) { return; } let mut visitor = CheckLiveDrops { ccx: &ccx, qualifs: Qualifs::default() }; visitor.visit_body(body); } struct CheckLiveDrops<'mir, 'tcx> { ccx: &'mir ConstCx<'mir, 'tcx>, qualifs: Qualifs<'mir, 'tcx>, } // So we can access `body` and `tcx`. impl std::ops::Deref for CheckLiveDrops<'mir, 'tcx> { type Target = ConstCx<'mir, 'tcx>; fn deref(&self) -> &Self::Target { &self.ccx } } impl CheckLiveDrops<'mir, 'tcx> { fn check_live_drop(&self, span: Span) { ops::LiveDrop { dropped_at: None }.build_error(self.ccx, span).emit(); } } impl Visitor<'tcx> for CheckLiveDrops<'mir, 'tcx> { fn visit_basic_block_data(&mut self, bb: BasicBlock, block: &mir::BasicBlockData<'tcx>) { trace!("visit_basic_block_data: bb={:?} is_cleanup={:?}", bb, block.is_cleanup); // Ignore drop terminators in cleanup blocks. if block.is_cleanup { return; } self.super_basic_block_data(bb, block); } fn visit_terminator(&mut self, terminator: &mir::Terminator<'tcx>, location: Location) { trace!("visit_terminator: terminator={:?} location={:?}", terminator, location); match &terminator.kind { mir::TerminatorKind::Drop { place: dropped_place,.. } => { let dropped_ty = dropped_place.ty(self.body, self.tcx).ty; if!NeedsNonConstDrop::in_any_value_of_ty(self.ccx, dropped_ty) { // Instead of throwing a bug, we just return here. This is because we have to // run custom `const Drop` impls. return; } if dropped_place.is_indirect() { self.check_live_drop(terminator.source_info.span); return; } // Drop elaboration is not precise enough to accept code like // `src/test/ui/consts/control-flow/drop-pass.rs`; e.g., when an `Option<Vec<T>>` is // initialized with `None` and never changed, it still emits drop glue. // Hence we additionally check the qualifs here to allow more code to pass. if self.qualifs.needs_non_const_drop(self.ccx, dropped_place.local, location) { // Use the span where the dropped local was declared for the error. let span = self.body.local_decls[dropped_place.local].source_info.span; self.check_live_drop(span); } } mir::TerminatorKind::DropAndReplace {.. } => span_bug!( terminator.source_info.span, "`DropAndReplace` should be removed by drop elaboration", ), mir::TerminatorKind::Abort | mir::TerminatorKind::Call {.. } | mir::TerminatorKind::Assert {.. } | mir::TerminatorKind::FalseEdge {.. } | mir::TerminatorKind::FalseUnwind {.. } | mir::TerminatorKind::GeneratorDrop | mir::TerminatorKind::Goto {.. } | mir::TerminatorKind::InlineAsm {.. } | mir::TerminatorKind::Resume | mir::TerminatorKind::Return | mir::TerminatorKind::SwitchInt {.. } | mir::TerminatorKind::Unreachable | mir::TerminatorKind::Yield {.. } => {} } } }
check_live_drops
identifier_name
post_drop_elaboration.rs
use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::{self, BasicBlock, Location}; use rustc_middle::ty::TyCtxt; use rustc_span::{symbol::sym, Span}; use super::check::Qualifs; use super::ops::{self, NonConstOp}; use super::qualifs::{NeedsNonConstDrop, Qualif}; use super::ConstCx; /// Returns `true` if we should use the more precise live drop checker that runs after drop /// elaboration. pub fn checking_enabled(ccx: &ConstCx<'_, '_>) -> bool { // Const-stable functions must always use the stable live drop checker. if ccx.is_const_stable_const_fn() { return false; } ccx.tcx.features().const_precise_live_drops } /// Look for live drops in a const context. /// /// This is separate from the rest of the const checking logic because it must run after drop /// elaboration. pub fn check_live_drops(tcx: TyCtxt<'tcx>, body: &mir::Body<'tcx>)
struct CheckLiveDrops<'mir, 'tcx> { ccx: &'mir ConstCx<'mir, 'tcx>, qualifs: Qualifs<'mir, 'tcx>, } // So we can access `body` and `tcx`. impl std::ops::Deref for CheckLiveDrops<'mir, 'tcx> { type Target = ConstCx<'mir, 'tcx>; fn deref(&self) -> &Self::Target { &self.ccx } } impl CheckLiveDrops<'mir, 'tcx> { fn check_live_drop(&self, span: Span) { ops::LiveDrop { dropped_at: None }.build_error(self.ccx, span).emit(); } } impl Visitor<'tcx> for CheckLiveDrops<'mir, 'tcx> { fn visit_basic_block_data(&mut self, bb: BasicBlock, block: &mir::BasicBlockData<'tcx>) { trace!("visit_basic_block_data: bb={:?} is_cleanup={:?}", bb, block.is_cleanup); // Ignore drop terminators in cleanup blocks. if block.is_cleanup { return; } self.super_basic_block_data(bb, block); } fn visit_terminator(&mut self, terminator: &mir::Terminator<'tcx>, location: Location) { trace!("visit_terminator: terminator={:?} location={:?}", terminator, location); match &terminator.kind { mir::TerminatorKind::Drop { place: dropped_place,.. } => { let dropped_ty = dropped_place.ty(self.body, self.tcx).ty; if!NeedsNonConstDrop::in_any_value_of_ty(self.ccx, dropped_ty) { // Instead of throwing a bug, we just return here. This is because we have to // run custom `const Drop` impls. return; } if dropped_place.is_indirect() { self.check_live_drop(terminator.source_info.span); return; } // Drop elaboration is not precise enough to accept code like // `src/test/ui/consts/control-flow/drop-pass.rs`; e.g., when an `Option<Vec<T>>` is // initialized with `None` and never changed, it still emits drop glue. // Hence we additionally check the qualifs here to allow more code to pass. if self.qualifs.needs_non_const_drop(self.ccx, dropped_place.local, location) { // Use the span where the dropped local was declared for the error. let span = self.body.local_decls[dropped_place.local].source_info.span; self.check_live_drop(span); } } mir::TerminatorKind::DropAndReplace {.. } => span_bug!( terminator.source_info.span, "`DropAndReplace` should be removed by drop elaboration", ), mir::TerminatorKind::Abort | mir::TerminatorKind::Call {.. } | mir::TerminatorKind::Assert {.. } | mir::TerminatorKind::FalseEdge {.. } | mir::TerminatorKind::FalseUnwind {.. } | mir::TerminatorKind::GeneratorDrop | mir::TerminatorKind::Goto {.. } | mir::TerminatorKind::InlineAsm {.. } | mir::TerminatorKind::Resume | mir::TerminatorKind::Return | mir::TerminatorKind::SwitchInt {.. } | mir::TerminatorKind::Unreachable | mir::TerminatorKind::Yield {.. } => {} } } }
{ let def_id = body.source.def_id().expect_local(); let const_kind = tcx.hir().body_const_context(def_id); if const_kind.is_none() { return; } if tcx.has_attr(def_id.to_def_id(), sym::rustc_do_not_const_check) { return; } let ccx = ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def_id) }; if !checking_enabled(&ccx) { return; } let mut visitor = CheckLiveDrops { ccx: &ccx, qualifs: Qualifs::default() }; visitor.visit_body(body); }
identifier_body
post_drop_elaboration.rs
use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::{self, BasicBlock, Location}; use rustc_middle::ty::TyCtxt; use rustc_span::{symbol::sym, Span}; use super::check::Qualifs; use super::ops::{self, NonConstOp}; use super::qualifs::{NeedsNonConstDrop, Qualif}; use super::ConstCx; /// Returns `true` if we should use the more precise live drop checker that runs after drop /// elaboration. pub fn checking_enabled(ccx: &ConstCx<'_, '_>) -> bool { // Const-stable functions must always use the stable live drop checker. if ccx.is_const_stable_const_fn() { return false; } ccx.tcx.features().const_precise_live_drops }
/// /// This is separate from the rest of the const checking logic because it must run after drop /// elaboration. pub fn check_live_drops(tcx: TyCtxt<'tcx>, body: &mir::Body<'tcx>) { let def_id = body.source.def_id().expect_local(); let const_kind = tcx.hir().body_const_context(def_id); if const_kind.is_none() { return; } if tcx.has_attr(def_id.to_def_id(), sym::rustc_do_not_const_check) { return; } let ccx = ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def_id) }; if!checking_enabled(&ccx) { return; } let mut visitor = CheckLiveDrops { ccx: &ccx, qualifs: Qualifs::default() }; visitor.visit_body(body); } struct CheckLiveDrops<'mir, 'tcx> { ccx: &'mir ConstCx<'mir, 'tcx>, qualifs: Qualifs<'mir, 'tcx>, } // So we can access `body` and `tcx`. impl std::ops::Deref for CheckLiveDrops<'mir, 'tcx> { type Target = ConstCx<'mir, 'tcx>; fn deref(&self) -> &Self::Target { &self.ccx } } impl CheckLiveDrops<'mir, 'tcx> { fn check_live_drop(&self, span: Span) { ops::LiveDrop { dropped_at: None }.build_error(self.ccx, span).emit(); } } impl Visitor<'tcx> for CheckLiveDrops<'mir, 'tcx> { fn visit_basic_block_data(&mut self, bb: BasicBlock, block: &mir::BasicBlockData<'tcx>) { trace!("visit_basic_block_data: bb={:?} is_cleanup={:?}", bb, block.is_cleanup); // Ignore drop terminators in cleanup blocks. if block.is_cleanup { return; } self.super_basic_block_data(bb, block); } fn visit_terminator(&mut self, terminator: &mir::Terminator<'tcx>, location: Location) { trace!("visit_terminator: terminator={:?} location={:?}", terminator, location); match &terminator.kind { mir::TerminatorKind::Drop { place: dropped_place,.. } => { let dropped_ty = dropped_place.ty(self.body, self.tcx).ty; if!NeedsNonConstDrop::in_any_value_of_ty(self.ccx, dropped_ty) { // Instead of throwing a bug, we just return here. This is because we have to // run custom `const Drop` impls. return; } if dropped_place.is_indirect() { self.check_live_drop(terminator.source_info.span); return; } // Drop elaboration is not precise enough to accept code like // `src/test/ui/consts/control-flow/drop-pass.rs`; e.g., when an `Option<Vec<T>>` is // initialized with `None` and never changed, it still emits drop glue. // Hence we additionally check the qualifs here to allow more code to pass. if self.qualifs.needs_non_const_drop(self.ccx, dropped_place.local, location) { // Use the span where the dropped local was declared for the error. let span = self.body.local_decls[dropped_place.local].source_info.span; self.check_live_drop(span); } } mir::TerminatorKind::DropAndReplace {.. } => span_bug!( terminator.source_info.span, "`DropAndReplace` should be removed by drop elaboration", ), mir::TerminatorKind::Abort | mir::TerminatorKind::Call {.. } | mir::TerminatorKind::Assert {.. } | mir::TerminatorKind::FalseEdge {.. } | mir::TerminatorKind::FalseUnwind {.. } | mir::TerminatorKind::GeneratorDrop | mir::TerminatorKind::Goto {.. } | mir::TerminatorKind::InlineAsm {.. } | mir::TerminatorKind::Resume | mir::TerminatorKind::Return | mir::TerminatorKind::SwitchInt {.. } | mir::TerminatorKind::Unreachable | mir::TerminatorKind::Yield {.. } => {} } } }
/// Look for live drops in a const context.
random_line_split
post_drop_elaboration.rs
use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::{self, BasicBlock, Location}; use rustc_middle::ty::TyCtxt; use rustc_span::{symbol::sym, Span}; use super::check::Qualifs; use super::ops::{self, NonConstOp}; use super::qualifs::{NeedsNonConstDrop, Qualif}; use super::ConstCx; /// Returns `true` if we should use the more precise live drop checker that runs after drop /// elaboration. pub fn checking_enabled(ccx: &ConstCx<'_, '_>) -> bool { // Const-stable functions must always use the stable live drop checker. if ccx.is_const_stable_const_fn()
ccx.tcx.features().const_precise_live_drops } /// Look for live drops in a const context. /// /// This is separate from the rest of the const checking logic because it must run after drop /// elaboration. pub fn check_live_drops(tcx: TyCtxt<'tcx>, body: &mir::Body<'tcx>) { let def_id = body.source.def_id().expect_local(); let const_kind = tcx.hir().body_const_context(def_id); if const_kind.is_none() { return; } if tcx.has_attr(def_id.to_def_id(), sym::rustc_do_not_const_check) { return; } let ccx = ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def_id) }; if!checking_enabled(&ccx) { return; } let mut visitor = CheckLiveDrops { ccx: &ccx, qualifs: Qualifs::default() }; visitor.visit_body(body); } struct CheckLiveDrops<'mir, 'tcx> { ccx: &'mir ConstCx<'mir, 'tcx>, qualifs: Qualifs<'mir, 'tcx>, } // So we can access `body` and `tcx`. impl std::ops::Deref for CheckLiveDrops<'mir, 'tcx> { type Target = ConstCx<'mir, 'tcx>; fn deref(&self) -> &Self::Target { &self.ccx } } impl CheckLiveDrops<'mir, 'tcx> { fn check_live_drop(&self, span: Span) { ops::LiveDrop { dropped_at: None }.build_error(self.ccx, span).emit(); } } impl Visitor<'tcx> for CheckLiveDrops<'mir, 'tcx> { fn visit_basic_block_data(&mut self, bb: BasicBlock, block: &mir::BasicBlockData<'tcx>) { trace!("visit_basic_block_data: bb={:?} is_cleanup={:?}", bb, block.is_cleanup); // Ignore drop terminators in cleanup blocks. if block.is_cleanup { return; } self.super_basic_block_data(bb, block); } fn visit_terminator(&mut self, terminator: &mir::Terminator<'tcx>, location: Location) { trace!("visit_terminator: terminator={:?} location={:?}", terminator, location); match &terminator.kind { mir::TerminatorKind::Drop { place: dropped_place,.. } => { let dropped_ty = dropped_place.ty(self.body, self.tcx).ty; if!NeedsNonConstDrop::in_any_value_of_ty(self.ccx, dropped_ty) { // Instead of throwing a bug, we just return here. This is because we have to // run custom `const Drop` impls. return; } if dropped_place.is_indirect() { self.check_live_drop(terminator.source_info.span); return; } // Drop elaboration is not precise enough to accept code like // `src/test/ui/consts/control-flow/drop-pass.rs`; e.g., when an `Option<Vec<T>>` is // initialized with `None` and never changed, it still emits drop glue. // Hence we additionally check the qualifs here to allow more code to pass. if self.qualifs.needs_non_const_drop(self.ccx, dropped_place.local, location) { // Use the span where the dropped local was declared for the error. let span = self.body.local_decls[dropped_place.local].source_info.span; self.check_live_drop(span); } } mir::TerminatorKind::DropAndReplace {.. } => span_bug!( terminator.source_info.span, "`DropAndReplace` should be removed by drop elaboration", ), mir::TerminatorKind::Abort | mir::TerminatorKind::Call {.. } | mir::TerminatorKind::Assert {.. } | mir::TerminatorKind::FalseEdge {.. } | mir::TerminatorKind::FalseUnwind {.. } | mir::TerminatorKind::GeneratorDrop | mir::TerminatorKind::Goto {.. } | mir::TerminatorKind::InlineAsm {.. } | mir::TerminatorKind::Resume | mir::TerminatorKind::Return | mir::TerminatorKind::SwitchInt {.. } | mir::TerminatorKind::Unreachable | mir::TerminatorKind::Yield {.. } => {} } } }
{ return false; }
conditional_block
gp.rs
//! Gaussian Processes //! //! Provides implementation of gaussian process regression. //! //! # Usage //! //! ``` //! use rusty_machine::learning::gp; //! use rusty_machine::learning::SupModel; //! use rusty_machine::linalg::Matrix; //! use rusty_machine::linalg::Vector; //! //! let mut gaussp = gp::GaussianProcess::default(); //! gaussp.noise = 10f64; //! //! let train_data = Matrix::new(10,1,vec![0.,1.,2.,3.,4.,5.,6.,7.,8.,9.]); //! let target = Vector::new(vec![0.,1.,2.,3.,4.,4.,3.,2.,1.,0.]); //! //! gaussp.train(&train_data, &target); //! //! let test_data = Matrix::new(5,1,vec![2.3,4.4,5.1,6.2,7.1]); //! //! let outputs = gaussp.predict(&test_data); //! ``` //! Alternatively one could use `gaussp.get_posterior()` which would return both //! the predictive mean and covariance. However, this is likely to change in //! a future release. use learning::toolkit::kernel::{Kernel, SquaredExp}; use learning::SupModel; use linalg::Matrix; use linalg::Vector; /// Trait for GP mean functions. pub trait MeanFunc { /// Compute the mean function applied elementwise to a matrix. fn func(&self, x: Matrix<f64>) -> Vector<f64>; } /// Constant mean function #[derive(Clone, Copy, Debug)] pub struct ConstMean { a: f64, } /// Constructs the zero function. impl Default for ConstMean { fn default() -> ConstMean { ConstMean { a: 0f64 } } } impl MeanFunc for ConstMean { fn func(&self, x: Matrix<f64>) -> Vector<f64> { Vector::zeros(x.rows()) + self.a } } /// Gaussian Process struct /// /// Gaussian process with generic kernel and deterministic mean function. /// Can be used for gaussian process regression with noise. /// Currently does not support classification. #[derive(Debug)] pub struct GaussianProcess<T: Kernel, U: MeanFunc> { ker: T, mean: U, /// The observation noise of the GP. pub noise: f64, alpha: Option<Vector<f64>>, train_mat: Option<Matrix<f64>>, train_data: Option<Matrix<f64>>, } /// Construct a default Gaussian Process /// /// The defaults are: /// /// - Squared Exponential kernel. /// - Zero-mean function. /// - Zero noise. /// /// Note that zero noise can often lead to numerical instability. /// A small value for the noise may be a better alternative. impl Default for GaussianProcess<SquaredExp, ConstMean> { fn default() -> GaussianProcess<SquaredExp, ConstMean> { GaussianProcess { ker: SquaredExp::default(), mean: ConstMean::default(), noise: 0f64, train_mat: None, train_data: None, alpha: None, } } } impl<T: Kernel, U: MeanFunc> GaussianProcess<T, U> { /// Construct a new Gaussian Process. /// /// # Examples ///
/// let mean = gp::ConstMean::default(); /// let gaussp = gp::GaussianProcess::new(ker, mean, 1e-3f64); /// ``` pub fn new(ker: T, mean: U, noise: f64) -> GaussianProcess<T, U> { GaussianProcess { ker: ker, mean: mean, noise: noise, train_mat: None, train_data: None, alpha: None, } } /// Construct a kernel matrix fn ker_mat(&self, m1: &Matrix<f64>, m2: &Matrix<f64>) -> Matrix<f64> { assert_eq!(m1.cols(), m2.cols()); let dim1 = m1.rows(); let dim2 = m2.rows(); let mut ker_data = Vec::with_capacity(dim1 * dim2); ker_data.extend( m1.iter_rows().flat_map(|row1| m2.iter_rows() .map(move |row2| self.ker.kernel(row1, row2)))); Matrix::new(dim1, dim2, ker_data) } } impl<T: Kernel, U: MeanFunc> SupModel<Matrix<f64>, Vector<f64>> for GaussianProcess<T, U> { /// Predict output from inputs. fn predict(&self, inputs: &Matrix<f64>) -> Vector<f64> { // Messy referencing for succint syntax if let (&Some(ref alpha), &Some(ref t_data)) = (&self.alpha, &self.train_data) { let mean = self.mean.func(inputs.clone()); let post_mean = self.ker_mat(inputs, t_data) * alpha; return mean + post_mean; } panic!("The model has not been trained."); } /// Train the model using data and outputs. fn train(&mut self, inputs: &Matrix<f64>, targets: &Vector<f64>) { let noise_mat = Matrix::identity(inputs.rows()) * self.noise; let ker_mat = self.ker_mat(inputs, inputs); let train_mat = (ker_mat + noise_mat).cholesky().expect("Could not compute Cholesky decomposition."); let x = train_mat.solve_l_triangular(targets - self.mean.func(inputs.clone())).unwrap(); let alpha = train_mat.transpose().solve_u_triangular(x).unwrap(); self.train_mat = Some(train_mat); self.train_data = Some(inputs.clone()); self.alpha = Some(alpha); } } impl<T: Kernel, U: MeanFunc> GaussianProcess<T, U> { /// Compute the posterior distribution [UNSTABLE] /// /// Requires the model to be trained first. /// /// Outputs the posterior mean and covariance matrix. pub fn get_posterior(&self, inputs: &Matrix<f64>) -> (Vector<f64>, Matrix<f64>) { if let (&Some(ref t_mat), &Some(ref alpha), &Some(ref t_data)) = (&self.train_mat, &self.alpha, &self.train_data) { let mean = self.mean.func(inputs.clone()); let post_mean = mean + self.ker_mat(inputs, t_data) * alpha; let test_mat = self.ker_mat(inputs, t_data); let mut var_data = Vec::with_capacity(inputs.rows() * inputs.cols()); for row in test_mat.iter_rows() { let test_point = Vector::new(row.to_vec()); var_data.append(&mut t_mat.solve_l_triangular(test_point).unwrap().into_vec()); } let v_mat = Matrix::new(test_mat.rows(), test_mat.cols(), var_data); let post_var = self.ker_mat(inputs, inputs) - &v_mat * v_mat.transpose(); return (post_mean, post_var); } panic!("The model has not been trained."); } }
/// ``` /// use rusty_machine::learning::gp; /// use rusty_machine::learning::toolkit::kernel; /// /// let ker = kernel::SquaredExp::default();
random_line_split
gp.rs
//! Gaussian Processes //! //! Provides implementation of gaussian process regression. //! //! # Usage //! //! ``` //! use rusty_machine::learning::gp; //! use rusty_machine::learning::SupModel; //! use rusty_machine::linalg::Matrix; //! use rusty_machine::linalg::Vector; //! //! let mut gaussp = gp::GaussianProcess::default(); //! gaussp.noise = 10f64; //! //! let train_data = Matrix::new(10,1,vec![0.,1.,2.,3.,4.,5.,6.,7.,8.,9.]); //! let target = Vector::new(vec![0.,1.,2.,3.,4.,4.,3.,2.,1.,0.]); //! //! gaussp.train(&train_data, &target); //! //! let test_data = Matrix::new(5,1,vec![2.3,4.4,5.1,6.2,7.1]); //! //! let outputs = gaussp.predict(&test_data); //! ``` //! Alternatively one could use `gaussp.get_posterior()` which would return both //! the predictive mean and covariance. However, this is likely to change in //! a future release. use learning::toolkit::kernel::{Kernel, SquaredExp}; use learning::SupModel; use linalg::Matrix; use linalg::Vector; /// Trait for GP mean functions. pub trait MeanFunc { /// Compute the mean function applied elementwise to a matrix. fn func(&self, x: Matrix<f64>) -> Vector<f64>; } /// Constant mean function #[derive(Clone, Copy, Debug)] pub struct ConstMean { a: f64, } /// Constructs the zero function. impl Default for ConstMean { fn default() -> ConstMean { ConstMean { a: 0f64 } } } impl MeanFunc for ConstMean { fn func(&self, x: Matrix<f64>) -> Vector<f64>
} /// Gaussian Process struct /// /// Gaussian process with generic kernel and deterministic mean function. /// Can be used for gaussian process regression with noise. /// Currently does not support classification. #[derive(Debug)] pub struct GaussianProcess<T: Kernel, U: MeanFunc> { ker: T, mean: U, /// The observation noise of the GP. pub noise: f64, alpha: Option<Vector<f64>>, train_mat: Option<Matrix<f64>>, train_data: Option<Matrix<f64>>, } /// Construct a default Gaussian Process /// /// The defaults are: /// /// - Squared Exponential kernel. /// - Zero-mean function. /// - Zero noise. /// /// Note that zero noise can often lead to numerical instability. /// A small value for the noise may be a better alternative. impl Default for GaussianProcess<SquaredExp, ConstMean> { fn default() -> GaussianProcess<SquaredExp, ConstMean> { GaussianProcess { ker: SquaredExp::default(), mean: ConstMean::default(), noise: 0f64, train_mat: None, train_data: None, alpha: None, } } } impl<T: Kernel, U: MeanFunc> GaussianProcess<T, U> { /// Construct a new Gaussian Process. /// /// # Examples /// /// ``` /// use rusty_machine::learning::gp; /// use rusty_machine::learning::toolkit::kernel; /// /// let ker = kernel::SquaredExp::default(); /// let mean = gp::ConstMean::default(); /// let gaussp = gp::GaussianProcess::new(ker, mean, 1e-3f64); /// ``` pub fn new(ker: T, mean: U, noise: f64) -> GaussianProcess<T, U> { GaussianProcess { ker: ker, mean: mean, noise: noise, train_mat: None, train_data: None, alpha: None, } } /// Construct a kernel matrix fn ker_mat(&self, m1: &Matrix<f64>, m2: &Matrix<f64>) -> Matrix<f64> { assert_eq!(m1.cols(), m2.cols()); let dim1 = m1.rows(); let dim2 = m2.rows(); let mut ker_data = Vec::with_capacity(dim1 * dim2); ker_data.extend( m1.iter_rows().flat_map(|row1| m2.iter_rows() .map(move |row2| self.ker.kernel(row1, row2)))); Matrix::new(dim1, dim2, ker_data) } } impl<T: Kernel, U: MeanFunc> SupModel<Matrix<f64>, Vector<f64>> for GaussianProcess<T, U> { /// Predict output from inputs. fn predict(&self, inputs: &Matrix<f64>) -> Vector<f64> { // Messy referencing for succint syntax if let (&Some(ref alpha), &Some(ref t_data)) = (&self.alpha, &self.train_data) { let mean = self.mean.func(inputs.clone()); let post_mean = self.ker_mat(inputs, t_data) * alpha; return mean + post_mean; } panic!("The model has not been trained."); } /// Train the model using data and outputs. fn train(&mut self, inputs: &Matrix<f64>, targets: &Vector<f64>) { let noise_mat = Matrix::identity(inputs.rows()) * self.noise; let ker_mat = self.ker_mat(inputs, inputs); let train_mat = (ker_mat + noise_mat).cholesky().expect("Could not compute Cholesky decomposition."); let x = train_mat.solve_l_triangular(targets - self.mean.func(inputs.clone())).unwrap(); let alpha = train_mat.transpose().solve_u_triangular(x).unwrap(); self.train_mat = Some(train_mat); self.train_data = Some(inputs.clone()); self.alpha = Some(alpha); } } impl<T: Kernel, U: MeanFunc> GaussianProcess<T, U> { /// Compute the posterior distribution [UNSTABLE] /// /// Requires the model to be trained first. /// /// Outputs the posterior mean and covariance matrix. pub fn get_posterior(&self, inputs: &Matrix<f64>) -> (Vector<f64>, Matrix<f64>) { if let (&Some(ref t_mat), &Some(ref alpha), &Some(ref t_data)) = (&self.train_mat, &self.alpha, &self.train_data) { let mean = self.mean.func(inputs.clone()); let post_mean = mean + self.ker_mat(inputs, t_data) * alpha; let test_mat = self.ker_mat(inputs, t_data); let mut var_data = Vec::with_capacity(inputs.rows() * inputs.cols()); for row in test_mat.iter_rows() { let test_point = Vector::new(row.to_vec()); var_data.append(&mut t_mat.solve_l_triangular(test_point).unwrap().into_vec()); } let v_mat = Matrix::new(test_mat.rows(), test_mat.cols(), var_data); let post_var = self.ker_mat(inputs, inputs) - &v_mat * v_mat.transpose(); return (post_mean, post_var); } panic!("The model has not been trained."); } }
{ Vector::zeros(x.rows()) + self.a }
identifier_body
gp.rs
//! Gaussian Processes //! //! Provides implementation of gaussian process regression. //! //! # Usage //! //! ``` //! use rusty_machine::learning::gp; //! use rusty_machine::learning::SupModel; //! use rusty_machine::linalg::Matrix; //! use rusty_machine::linalg::Vector; //! //! let mut gaussp = gp::GaussianProcess::default(); //! gaussp.noise = 10f64; //! //! let train_data = Matrix::new(10,1,vec![0.,1.,2.,3.,4.,5.,6.,7.,8.,9.]); //! let target = Vector::new(vec![0.,1.,2.,3.,4.,4.,3.,2.,1.,0.]); //! //! gaussp.train(&train_data, &target); //! //! let test_data = Matrix::new(5,1,vec![2.3,4.4,5.1,6.2,7.1]); //! //! let outputs = gaussp.predict(&test_data); //! ``` //! Alternatively one could use `gaussp.get_posterior()` which would return both //! the predictive mean and covariance. However, this is likely to change in //! a future release. use learning::toolkit::kernel::{Kernel, SquaredExp}; use learning::SupModel; use linalg::Matrix; use linalg::Vector; /// Trait for GP mean functions. pub trait MeanFunc { /// Compute the mean function applied elementwise to a matrix. fn func(&self, x: Matrix<f64>) -> Vector<f64>; } /// Constant mean function #[derive(Clone, Copy, Debug)] pub struct ConstMean { a: f64, } /// Constructs the zero function. impl Default for ConstMean { fn default() -> ConstMean { ConstMean { a: 0f64 } } } impl MeanFunc for ConstMean { fn func(&self, x: Matrix<f64>) -> Vector<f64> { Vector::zeros(x.rows()) + self.a } } /// Gaussian Process struct /// /// Gaussian process with generic kernel and deterministic mean function. /// Can be used for gaussian process regression with noise. /// Currently does not support classification. #[derive(Debug)] pub struct GaussianProcess<T: Kernel, U: MeanFunc> { ker: T, mean: U, /// The observation noise of the GP. pub noise: f64, alpha: Option<Vector<f64>>, train_mat: Option<Matrix<f64>>, train_data: Option<Matrix<f64>>, } /// Construct a default Gaussian Process /// /// The defaults are: /// /// - Squared Exponential kernel. /// - Zero-mean function. /// - Zero noise. /// /// Note that zero noise can often lead to numerical instability. /// A small value for the noise may be a better alternative. impl Default for GaussianProcess<SquaredExp, ConstMean> { fn default() -> GaussianProcess<SquaredExp, ConstMean> { GaussianProcess { ker: SquaredExp::default(), mean: ConstMean::default(), noise: 0f64, train_mat: None, train_data: None, alpha: None, } } } impl<T: Kernel, U: MeanFunc> GaussianProcess<T, U> { /// Construct a new Gaussian Process. /// /// # Examples /// /// ``` /// use rusty_machine::learning::gp; /// use rusty_machine::learning::toolkit::kernel; /// /// let ker = kernel::SquaredExp::default(); /// let mean = gp::ConstMean::default(); /// let gaussp = gp::GaussianProcess::new(ker, mean, 1e-3f64); /// ``` pub fn new(ker: T, mean: U, noise: f64) -> GaussianProcess<T, U> { GaussianProcess { ker: ker, mean: mean, noise: noise, train_mat: None, train_data: None, alpha: None, } } /// Construct a kernel matrix fn ker_mat(&self, m1: &Matrix<f64>, m2: &Matrix<f64>) -> Matrix<f64> { assert_eq!(m1.cols(), m2.cols()); let dim1 = m1.rows(); let dim2 = m2.rows(); let mut ker_data = Vec::with_capacity(dim1 * dim2); ker_data.extend( m1.iter_rows().flat_map(|row1| m2.iter_rows() .map(move |row2| self.ker.kernel(row1, row2)))); Matrix::new(dim1, dim2, ker_data) } } impl<T: Kernel, U: MeanFunc> SupModel<Matrix<f64>, Vector<f64>> for GaussianProcess<T, U> { /// Predict output from inputs. fn predict(&self, inputs: &Matrix<f64>) -> Vector<f64> { // Messy referencing for succint syntax if let (&Some(ref alpha), &Some(ref t_data)) = (&self.alpha, &self.train_data)
panic!("The model has not been trained."); } /// Train the model using data and outputs. fn train(&mut self, inputs: &Matrix<f64>, targets: &Vector<f64>) { let noise_mat = Matrix::identity(inputs.rows()) * self.noise; let ker_mat = self.ker_mat(inputs, inputs); let train_mat = (ker_mat + noise_mat).cholesky().expect("Could not compute Cholesky decomposition."); let x = train_mat.solve_l_triangular(targets - self.mean.func(inputs.clone())).unwrap(); let alpha = train_mat.transpose().solve_u_triangular(x).unwrap(); self.train_mat = Some(train_mat); self.train_data = Some(inputs.clone()); self.alpha = Some(alpha); } } impl<T: Kernel, U: MeanFunc> GaussianProcess<T, U> { /// Compute the posterior distribution [UNSTABLE] /// /// Requires the model to be trained first. /// /// Outputs the posterior mean and covariance matrix. pub fn get_posterior(&self, inputs: &Matrix<f64>) -> (Vector<f64>, Matrix<f64>) { if let (&Some(ref t_mat), &Some(ref alpha), &Some(ref t_data)) = (&self.train_mat, &self.alpha, &self.train_data) { let mean = self.mean.func(inputs.clone()); let post_mean = mean + self.ker_mat(inputs, t_data) * alpha; let test_mat = self.ker_mat(inputs, t_data); let mut var_data = Vec::with_capacity(inputs.rows() * inputs.cols()); for row in test_mat.iter_rows() { let test_point = Vector::new(row.to_vec()); var_data.append(&mut t_mat.solve_l_triangular(test_point).unwrap().into_vec()); } let v_mat = Matrix::new(test_mat.rows(), test_mat.cols(), var_data); let post_var = self.ker_mat(inputs, inputs) - &v_mat * v_mat.transpose(); return (post_mean, post_var); } panic!("The model has not been trained."); } }
{ let mean = self.mean.func(inputs.clone()); let post_mean = self.ker_mat(inputs, t_data) * alpha; return mean + post_mean; }
conditional_block
gp.rs
//! Gaussian Processes //! //! Provides implementation of gaussian process regression. //! //! # Usage //! //! ``` //! use rusty_machine::learning::gp; //! use rusty_machine::learning::SupModel; //! use rusty_machine::linalg::Matrix; //! use rusty_machine::linalg::Vector; //! //! let mut gaussp = gp::GaussianProcess::default(); //! gaussp.noise = 10f64; //! //! let train_data = Matrix::new(10,1,vec![0.,1.,2.,3.,4.,5.,6.,7.,8.,9.]); //! let target = Vector::new(vec![0.,1.,2.,3.,4.,4.,3.,2.,1.,0.]); //! //! gaussp.train(&train_data, &target); //! //! let test_data = Matrix::new(5,1,vec![2.3,4.4,5.1,6.2,7.1]); //! //! let outputs = gaussp.predict(&test_data); //! ``` //! Alternatively one could use `gaussp.get_posterior()` which would return both //! the predictive mean and covariance. However, this is likely to change in //! a future release. use learning::toolkit::kernel::{Kernel, SquaredExp}; use learning::SupModel; use linalg::Matrix; use linalg::Vector; /// Trait for GP mean functions. pub trait MeanFunc { /// Compute the mean function applied elementwise to a matrix. fn func(&self, x: Matrix<f64>) -> Vector<f64>; } /// Constant mean function #[derive(Clone, Copy, Debug)] pub struct ConstMean { a: f64, } /// Constructs the zero function. impl Default for ConstMean { fn default() -> ConstMean { ConstMean { a: 0f64 } } } impl MeanFunc for ConstMean { fn
(&self, x: Matrix<f64>) -> Vector<f64> { Vector::zeros(x.rows()) + self.a } } /// Gaussian Process struct /// /// Gaussian process with generic kernel and deterministic mean function. /// Can be used for gaussian process regression with noise. /// Currently does not support classification. #[derive(Debug)] pub struct GaussianProcess<T: Kernel, U: MeanFunc> { ker: T, mean: U, /// The observation noise of the GP. pub noise: f64, alpha: Option<Vector<f64>>, train_mat: Option<Matrix<f64>>, train_data: Option<Matrix<f64>>, } /// Construct a default Gaussian Process /// /// The defaults are: /// /// - Squared Exponential kernel. /// - Zero-mean function. /// - Zero noise. /// /// Note that zero noise can often lead to numerical instability. /// A small value for the noise may be a better alternative. impl Default for GaussianProcess<SquaredExp, ConstMean> { fn default() -> GaussianProcess<SquaredExp, ConstMean> { GaussianProcess { ker: SquaredExp::default(), mean: ConstMean::default(), noise: 0f64, train_mat: None, train_data: None, alpha: None, } } } impl<T: Kernel, U: MeanFunc> GaussianProcess<T, U> { /// Construct a new Gaussian Process. /// /// # Examples /// /// ``` /// use rusty_machine::learning::gp; /// use rusty_machine::learning::toolkit::kernel; /// /// let ker = kernel::SquaredExp::default(); /// let mean = gp::ConstMean::default(); /// let gaussp = gp::GaussianProcess::new(ker, mean, 1e-3f64); /// ``` pub fn new(ker: T, mean: U, noise: f64) -> GaussianProcess<T, U> { GaussianProcess { ker: ker, mean: mean, noise: noise, train_mat: None, train_data: None, alpha: None, } } /// Construct a kernel matrix fn ker_mat(&self, m1: &Matrix<f64>, m2: &Matrix<f64>) -> Matrix<f64> { assert_eq!(m1.cols(), m2.cols()); let dim1 = m1.rows(); let dim2 = m2.rows(); let mut ker_data = Vec::with_capacity(dim1 * dim2); ker_data.extend( m1.iter_rows().flat_map(|row1| m2.iter_rows() .map(move |row2| self.ker.kernel(row1, row2)))); Matrix::new(dim1, dim2, ker_data) } } impl<T: Kernel, U: MeanFunc> SupModel<Matrix<f64>, Vector<f64>> for GaussianProcess<T, U> { /// Predict output from inputs. fn predict(&self, inputs: &Matrix<f64>) -> Vector<f64> { // Messy referencing for succint syntax if let (&Some(ref alpha), &Some(ref t_data)) = (&self.alpha, &self.train_data) { let mean = self.mean.func(inputs.clone()); let post_mean = self.ker_mat(inputs, t_data) * alpha; return mean + post_mean; } panic!("The model has not been trained."); } /// Train the model using data and outputs. fn train(&mut self, inputs: &Matrix<f64>, targets: &Vector<f64>) { let noise_mat = Matrix::identity(inputs.rows()) * self.noise; let ker_mat = self.ker_mat(inputs, inputs); let train_mat = (ker_mat + noise_mat).cholesky().expect("Could not compute Cholesky decomposition."); let x = train_mat.solve_l_triangular(targets - self.mean.func(inputs.clone())).unwrap(); let alpha = train_mat.transpose().solve_u_triangular(x).unwrap(); self.train_mat = Some(train_mat); self.train_data = Some(inputs.clone()); self.alpha = Some(alpha); } } impl<T: Kernel, U: MeanFunc> GaussianProcess<T, U> { /// Compute the posterior distribution [UNSTABLE] /// /// Requires the model to be trained first. /// /// Outputs the posterior mean and covariance matrix. pub fn get_posterior(&self, inputs: &Matrix<f64>) -> (Vector<f64>, Matrix<f64>) { if let (&Some(ref t_mat), &Some(ref alpha), &Some(ref t_data)) = (&self.train_mat, &self.alpha, &self.train_data) { let mean = self.mean.func(inputs.clone()); let post_mean = mean + self.ker_mat(inputs, t_data) * alpha; let test_mat = self.ker_mat(inputs, t_data); let mut var_data = Vec::with_capacity(inputs.rows() * inputs.cols()); for row in test_mat.iter_rows() { let test_point = Vector::new(row.to_vec()); var_data.append(&mut t_mat.solve_l_triangular(test_point).unwrap().into_vec()); } let v_mat = Matrix::new(test_mat.rows(), test_mat.cols(), var_data); let post_var = self.ker_mat(inputs, inputs) - &v_mat * v_mat.transpose(); return (post_mean, post_var); } panic!("The model has not been trained."); } }
func
identifier_name
cargo_output_metadata.rs
use std::path::Path; use rustc_serialize::{Encodable, Encoder}; use core::resolver::Resolve; use core::{Package, PackageId, PackageSet}; use ops; use util::config::Config; use util::CargoResult; const VERSION: u32 = 1; pub struct OutputMetadataOptions<'a> { pub features: Vec<String>, pub manifest_path: &'a Path, pub no_default_features: bool, pub no_deps: bool, pub version: u32, } /// Loads the manifest, resolves the dependencies of the project to the concrete /// used versions - considering overrides - and writes all dependencies in a JSON /// format to stdout. pub fn output_metadata(opt: OutputMetadataOptions, config: &Config) -> CargoResult<ExportInfo> { if opt.version!= VERSION { bail!("metadata version {} not supported, only {} is currently supported", opt.version, VERSION); } if opt.no_deps { metadata_no_deps(opt, config) } else { metadata_full(opt, config) } } fn metadata_no_deps(opt: OutputMetadataOptions, config: &Config) -> CargoResult<ExportInfo> { let root = try!(Package::for_path(opt.manifest_path, config)); Ok(ExportInfo { packages: vec![root], resolve: None, version: VERSION, }) } fn metadata_full(opt: OutputMetadataOptions, config: &Config) -> CargoResult<ExportInfo> { let deps = try!(resolve_dependencies(opt.manifest_path, config, opt.features, opt.no_default_features)); let (packages, resolve) = deps; let packages = try!(packages.package_ids() .map(|i| packages.get(i).map(|p| p.clone())) .collect()); Ok(ExportInfo { packages: packages, resolve: Some(MetadataResolve(resolve)), version: VERSION, }) } #[derive(RustcEncodable)] pub struct ExportInfo { packages: Vec<Package>, resolve: Option<MetadataResolve>, version: u32, } /// Newtype wrapper to provide a custom `Encodable` implementation. /// The one from lockfile does not fit because it uses a non-standard /// format for `PackageId`s struct
(Resolve); impl Encodable for MetadataResolve { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { #[derive(RustcEncodable)] struct EncodableResolve<'a> { root: &'a PackageId, nodes: Vec<Node<'a>>, } #[derive(RustcEncodable)] struct Node<'a> { id: &'a PackageId, dependencies: Vec<&'a PackageId>, } let resolve = &self.0; let encodable = EncodableResolve { root: resolve.root(), nodes: resolve.iter().map(|id| { Node { id: id, dependencies: resolve.deps(id) .map(|it| it.collect()) .unwrap_or(Vec::new()), } }).collect(), }; encodable.encode(s) } } /// Loads the manifest and resolves the dependencies of the project to the /// concrete used versions. Afterwards available overrides of dependencies are applied. fn resolve_dependencies<'a>(manifest: &Path, config: &'a Config, features: Vec<String>, no_default_features: bool) -> CargoResult<(PackageSet<'a>, Resolve)> { let package = try!(Package::for_path(manifest, config)); ops::resolve_dependencies(&package, config, None, features, no_default_features) }
MetadataResolve
identifier_name
cargo_output_metadata.rs
use std::path::Path; use rustc_serialize::{Encodable, Encoder}; use core::resolver::Resolve; use core::{Package, PackageId, PackageSet}; use ops; use util::config::Config; use util::CargoResult; const VERSION: u32 = 1; pub struct OutputMetadataOptions<'a> { pub features: Vec<String>, pub manifest_path: &'a Path, pub no_default_features: bool, pub no_deps: bool, pub version: u32, } /// Loads the manifest, resolves the dependencies of the project to the concrete /// used versions - considering overrides - and writes all dependencies in a JSON /// format to stdout. pub fn output_metadata(opt: OutputMetadataOptions, config: &Config) -> CargoResult<ExportInfo> { if opt.version!= VERSION
if opt.no_deps { metadata_no_deps(opt, config) } else { metadata_full(opt, config) } } fn metadata_no_deps(opt: OutputMetadataOptions, config: &Config) -> CargoResult<ExportInfo> { let root = try!(Package::for_path(opt.manifest_path, config)); Ok(ExportInfo { packages: vec![root], resolve: None, version: VERSION, }) } fn metadata_full(opt: OutputMetadataOptions, config: &Config) -> CargoResult<ExportInfo> { let deps = try!(resolve_dependencies(opt.manifest_path, config, opt.features, opt.no_default_features)); let (packages, resolve) = deps; let packages = try!(packages.package_ids() .map(|i| packages.get(i).map(|p| p.clone())) .collect()); Ok(ExportInfo { packages: packages, resolve: Some(MetadataResolve(resolve)), version: VERSION, }) } #[derive(RustcEncodable)] pub struct ExportInfo { packages: Vec<Package>, resolve: Option<MetadataResolve>, version: u32, } /// Newtype wrapper to provide a custom `Encodable` implementation. /// The one from lockfile does not fit because it uses a non-standard /// format for `PackageId`s struct MetadataResolve(Resolve); impl Encodable for MetadataResolve { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { #[derive(RustcEncodable)] struct EncodableResolve<'a> { root: &'a PackageId, nodes: Vec<Node<'a>>, } #[derive(RustcEncodable)] struct Node<'a> { id: &'a PackageId, dependencies: Vec<&'a PackageId>, } let resolve = &self.0; let encodable = EncodableResolve { root: resolve.root(), nodes: resolve.iter().map(|id| { Node { id: id, dependencies: resolve.deps(id) .map(|it| it.collect()) .unwrap_or(Vec::new()), } }).collect(), }; encodable.encode(s) } } /// Loads the manifest and resolves the dependencies of the project to the /// concrete used versions. Afterwards available overrides of dependencies are applied. fn resolve_dependencies<'a>(manifest: &Path, config: &'a Config, features: Vec<String>, no_default_features: bool) -> CargoResult<(PackageSet<'a>, Resolve)> { let package = try!(Package::for_path(manifest, config)); ops::resolve_dependencies(&package, config, None, features, no_default_features) }
{ bail!("metadata version {} not supported, only {} is currently supported", opt.version, VERSION); }
conditional_block
cargo_output_metadata.rs
use std::path::Path; use rustc_serialize::{Encodable, Encoder}; use core::resolver::Resolve; use core::{Package, PackageId, PackageSet}; use ops; use util::config::Config; use util::CargoResult; const VERSION: u32 = 1; pub struct OutputMetadataOptions<'a> { pub features: Vec<String>, pub manifest_path: &'a Path, pub no_default_features: bool, pub no_deps: bool, pub version: u32, } /// Loads the manifest, resolves the dependencies of the project to the concrete /// used versions - considering overrides - and writes all dependencies in a JSON /// format to stdout. pub fn output_metadata(opt: OutputMetadataOptions, config: &Config) -> CargoResult<ExportInfo> { if opt.version!= VERSION { bail!("metadata version {} not supported, only {} is currently supported", opt.version, VERSION); } if opt.no_deps { metadata_no_deps(opt, config) } else { metadata_full(opt, config) } } fn metadata_no_deps(opt: OutputMetadataOptions, config: &Config) -> CargoResult<ExportInfo> { let root = try!(Package::for_path(opt.manifest_path, config)); Ok(ExportInfo { packages: vec![root], resolve: None, version: VERSION, }) } fn metadata_full(opt: OutputMetadataOptions, config: &Config) -> CargoResult<ExportInfo> { let deps = try!(resolve_dependencies(opt.manifest_path, config, opt.features, opt.no_default_features)); let (packages, resolve) = deps; let packages = try!(packages.package_ids() .map(|i| packages.get(i).map(|p| p.clone())) .collect()); Ok(ExportInfo { packages: packages, resolve: Some(MetadataResolve(resolve)), version: VERSION, }) } #[derive(RustcEncodable)] pub struct ExportInfo { packages: Vec<Package>, resolve: Option<MetadataResolve>, version: u32, } /// Newtype wrapper to provide a custom `Encodable` implementation. /// The one from lockfile does not fit because it uses a non-standard /// format for `PackageId`s struct MetadataResolve(Resolve); impl Encodable for MetadataResolve { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { #[derive(RustcEncodable)] struct EncodableResolve<'a> { root: &'a PackageId, nodes: Vec<Node<'a>>, } #[derive(RustcEncodable)] struct Node<'a> { id: &'a PackageId, dependencies: Vec<&'a PackageId>, } let resolve = &self.0; let encodable = EncodableResolve { root: resolve.root(), nodes: resolve.iter().map(|id| { Node { id: id, dependencies: resolve.deps(id) .map(|it| it.collect()) .unwrap_or(Vec::new()), } }).collect(), }; encodable.encode(s) } } /// Loads the manifest and resolves the dependencies of the project to the /// concrete used versions. Afterwards available overrides of dependencies are applied. fn resolve_dependencies<'a>(manifest: &Path, config: &'a Config, features: Vec<String>, no_default_features: bool) -> CargoResult<(PackageSet<'a>, Resolve)> {
no_default_features) }
let package = try!(Package::for_path(manifest, config)); ops::resolve_dependencies(&package, config, None, features,
random_line_split
cargo_output_metadata.rs
use std::path::Path; use rustc_serialize::{Encodable, Encoder}; use core::resolver::Resolve; use core::{Package, PackageId, PackageSet}; use ops; use util::config::Config; use util::CargoResult; const VERSION: u32 = 1; pub struct OutputMetadataOptions<'a> { pub features: Vec<String>, pub manifest_path: &'a Path, pub no_default_features: bool, pub no_deps: bool, pub version: u32, } /// Loads the manifest, resolves the dependencies of the project to the concrete /// used versions - considering overrides - and writes all dependencies in a JSON /// format to stdout. pub fn output_metadata(opt: OutputMetadataOptions, config: &Config) -> CargoResult<ExportInfo> { if opt.version!= VERSION { bail!("metadata version {} not supported, only {} is currently supported", opt.version, VERSION); } if opt.no_deps { metadata_no_deps(opt, config) } else { metadata_full(opt, config) } } fn metadata_no_deps(opt: OutputMetadataOptions, config: &Config) -> CargoResult<ExportInfo> { let root = try!(Package::for_path(opt.manifest_path, config)); Ok(ExportInfo { packages: vec![root], resolve: None, version: VERSION, }) } fn metadata_full(opt: OutputMetadataOptions, config: &Config) -> CargoResult<ExportInfo>
#[derive(RustcEncodable)] pub struct ExportInfo { packages: Vec<Package>, resolve: Option<MetadataResolve>, version: u32, } /// Newtype wrapper to provide a custom `Encodable` implementation. /// The one from lockfile does not fit because it uses a non-standard /// format for `PackageId`s struct MetadataResolve(Resolve); impl Encodable for MetadataResolve { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { #[derive(RustcEncodable)] struct EncodableResolve<'a> { root: &'a PackageId, nodes: Vec<Node<'a>>, } #[derive(RustcEncodable)] struct Node<'a> { id: &'a PackageId, dependencies: Vec<&'a PackageId>, } let resolve = &self.0; let encodable = EncodableResolve { root: resolve.root(), nodes: resolve.iter().map(|id| { Node { id: id, dependencies: resolve.deps(id) .map(|it| it.collect()) .unwrap_or(Vec::new()), } }).collect(), }; encodable.encode(s) } } /// Loads the manifest and resolves the dependencies of the project to the /// concrete used versions. Afterwards available overrides of dependencies are applied. fn resolve_dependencies<'a>(manifest: &Path, config: &'a Config, features: Vec<String>, no_default_features: bool) -> CargoResult<(PackageSet<'a>, Resolve)> { let package = try!(Package::for_path(manifest, config)); ops::resolve_dependencies(&package, config, None, features, no_default_features) }
{ let deps = try!(resolve_dependencies(opt.manifest_path, config, opt.features, opt.no_default_features)); let (packages, resolve) = deps; let packages = try!(packages.package_ids() .map(|i| packages.get(i).map(|p| p.clone())) .collect()); Ok(ExportInfo { packages: packages, resolve: Some(MetadataResolve(resolve)), version: VERSION, }) }
identifier_body
output.rs
use raii::Raii; use {ffi, Handle, Return}; use super::types::OdbcType; /// Indicates that a type can be retrieved using `Cursor::get_data` pub unsafe trait Output<'a>: Sized { fn get_data( stmt: &mut Raii<ffi::Stmt>, col_or_param_num: u16, buffer: &'a mut Vec<u8>, ) -> Return<Option<Self>>; } unsafe impl<'a, T> Output<'a> for T where T: OdbcType<'a>, { fn get_data( stmt: &mut Raii<ffi::Stmt>, col_or_param_num: u16, buffer: &'a mut Vec<u8>, ) -> Return<Option<Self>> { stmt.get_data(col_or_param_num, buffer) } } impl<'p> Raii<'p, ffi::Stmt> { fn get_data<'a, T>( &mut self, col_or_param_num: u16, buffer: &'a mut Vec<u8> ) -> Return<Option<T>> where T: OdbcType<'a>, { self.get_partial_data(col_or_param_num, buffer, 0) } fn get_partial_data<'a, T>( &mut self, col_or_param_num: u16, buffer: &'a mut Vec<u8>, start_pos: usize ) -> Return<Option<T>> where T: OdbcType<'a>, { if buffer.len() - start_pos == 0 { panic!("buffer length may not be zero"); } if buffer.len() - start_pos > ffi::SQLLEN::max_value() as usize { panic!("buffer is larger than {} bytes", ffi::SQLLEN::max_value()); } let mut indicator: ffi::SQLLEN = 0; // Get buffer length... let result = unsafe { ffi::SQLGetData( self.handle(), col_or_param_num, T::c_data_type(), buffer.as_mut_ptr().offset(start_pos as isize) as ffi::SQLPOINTER, (buffer.len() - start_pos) as ffi::SQLLEN, &mut indicator as *mut ffi::SQLLEN, ) }; match result { ffi::SQL_SUCCESS => { if indicator == ffi::SQL_NULL_DATA { Return::Success(None) } else { assert!(start_pos + indicator as usize <= buffer.len(), "no more data but indicatior outside of data buffer"); let slice = &buffer[..(start_pos + indicator as usize)]; Return::Success(Some(T::convert(slice))) } } ffi::SQL_SUCCESS_WITH_INFO => { let initial_len = buffer.len(); // // As a workaround for drivers that don't include tailing null(s) check if last bytes are null // let null_offset = if buffer.ends_with(T::null_bytes()) { T::null_bytes().len() } else { 0 }; // (Alexander Yekimov <[email protected]>) It's a bad idea to do such workarounds // for buggy drivers here. They always can implement OdbcType trait and set any // amount of null-terminators to do the workaround. let null_offset = T::null_bytes_count(); if indicator == ffi::SQL_NO_TOTAL { buffer.resize(initial_len * 2, 0); return self.get_partial_data(col_or_param_num, buffer, initial_len - null_offset); } else { // Check if string has been truncated. if indicator >= initial_len as ffi::SQLLEN
else { let slice = &buffer[..(start_pos + indicator as usize)]; // No truncation. Warning may be due to some other issue. Return::SuccessWithInfo(Some(T::convert(slice))) } } } ffi::SQL_ERROR => Return::Error, ffi::SQL_NO_DATA => panic!("SQLGetData has already returned the colmun data"), r => panic!("unexpected return value from SQLGetData: {:?}", r), } } }
{ buffer.resize(indicator as usize + T::null_bytes_count(), 0); return self.get_partial_data(col_or_param_num, buffer, initial_len - null_offset); }
conditional_block
output.rs
use raii::Raii; use {ffi, Handle, Return}; use super::types::OdbcType; /// Indicates that a type can be retrieved using `Cursor::get_data` pub unsafe trait Output<'a>: Sized { fn get_data( stmt: &mut Raii<ffi::Stmt>, col_or_param_num: u16, buffer: &'a mut Vec<u8>, ) -> Return<Option<Self>>; } unsafe impl<'a, T> Output<'a> for T where T: OdbcType<'a>, { fn get_data( stmt: &mut Raii<ffi::Stmt>, col_or_param_num: u16, buffer: &'a mut Vec<u8>, ) -> Return<Option<Self>>
} impl<'p> Raii<'p, ffi::Stmt> { fn get_data<'a, T>( &mut self, col_or_param_num: u16, buffer: &'a mut Vec<u8> ) -> Return<Option<T>> where T: OdbcType<'a>, { self.get_partial_data(col_or_param_num, buffer, 0) } fn get_partial_data<'a, T>( &mut self, col_or_param_num: u16, buffer: &'a mut Vec<u8>, start_pos: usize ) -> Return<Option<T>> where T: OdbcType<'a>, { if buffer.len() - start_pos == 0 { panic!("buffer length may not be zero"); } if buffer.len() - start_pos > ffi::SQLLEN::max_value() as usize { panic!("buffer is larger than {} bytes", ffi::SQLLEN::max_value()); } let mut indicator: ffi::SQLLEN = 0; // Get buffer length... let result = unsafe { ffi::SQLGetData( self.handle(), col_or_param_num, T::c_data_type(), buffer.as_mut_ptr().offset(start_pos as isize) as ffi::SQLPOINTER, (buffer.len() - start_pos) as ffi::SQLLEN, &mut indicator as *mut ffi::SQLLEN, ) }; match result { ffi::SQL_SUCCESS => { if indicator == ffi::SQL_NULL_DATA { Return::Success(None) } else { assert!(start_pos + indicator as usize <= buffer.len(), "no more data but indicatior outside of data buffer"); let slice = &buffer[..(start_pos + indicator as usize)]; Return::Success(Some(T::convert(slice))) } } ffi::SQL_SUCCESS_WITH_INFO => { let initial_len = buffer.len(); // // As a workaround for drivers that don't include tailing null(s) check if last bytes are null // let null_offset = if buffer.ends_with(T::null_bytes()) { T::null_bytes().len() } else { 0 }; // (Alexander Yekimov <[email protected]>) It's a bad idea to do such workarounds // for buggy drivers here. They always can implement OdbcType trait and set any // amount of null-terminators to do the workaround. let null_offset = T::null_bytes_count(); if indicator == ffi::SQL_NO_TOTAL { buffer.resize(initial_len * 2, 0); return self.get_partial_data(col_or_param_num, buffer, initial_len - null_offset); } else { // Check if string has been truncated. if indicator >= initial_len as ffi::SQLLEN { buffer.resize(indicator as usize + T::null_bytes_count(), 0); return self.get_partial_data(col_or_param_num, buffer, initial_len - null_offset); } else { let slice = &buffer[..(start_pos + indicator as usize)]; // No truncation. Warning may be due to some other issue. Return::SuccessWithInfo(Some(T::convert(slice))) } } } ffi::SQL_ERROR => Return::Error, ffi::SQL_NO_DATA => panic!("SQLGetData has already returned the colmun data"), r => panic!("unexpected return value from SQLGetData: {:?}", r), } } }
{ stmt.get_data(col_or_param_num, buffer) }
identifier_body
output.rs
use raii::Raii; use {ffi, Handle, Return}; use super::types::OdbcType; /// Indicates that a type can be retrieved using `Cursor::get_data` pub unsafe trait Output<'a>: Sized { fn get_data( stmt: &mut Raii<ffi::Stmt>, col_or_param_num: u16, buffer: &'a mut Vec<u8>, ) -> Return<Option<Self>>; } unsafe impl<'a, T> Output<'a> for T where T: OdbcType<'a>, { fn get_data( stmt: &mut Raii<ffi::Stmt>, col_or_param_num: u16, buffer: &'a mut Vec<u8>, ) -> Return<Option<Self>> { stmt.get_data(col_or_param_num, buffer) } } impl<'p> Raii<'p, ffi::Stmt> { fn get_data<'a, T>( &mut self, col_or_param_num: u16, buffer: &'a mut Vec<u8> ) -> Return<Option<T>> where T: OdbcType<'a>, { self.get_partial_data(col_or_param_num, buffer, 0) } fn get_partial_data<'a, T>( &mut self, col_or_param_num: u16, buffer: &'a mut Vec<u8>, start_pos: usize
T: OdbcType<'a>, { if buffer.len() - start_pos == 0 { panic!("buffer length may not be zero"); } if buffer.len() - start_pos > ffi::SQLLEN::max_value() as usize { panic!("buffer is larger than {} bytes", ffi::SQLLEN::max_value()); } let mut indicator: ffi::SQLLEN = 0; // Get buffer length... let result = unsafe { ffi::SQLGetData( self.handle(), col_or_param_num, T::c_data_type(), buffer.as_mut_ptr().offset(start_pos as isize) as ffi::SQLPOINTER, (buffer.len() - start_pos) as ffi::SQLLEN, &mut indicator as *mut ffi::SQLLEN, ) }; match result { ffi::SQL_SUCCESS => { if indicator == ffi::SQL_NULL_DATA { Return::Success(None) } else { assert!(start_pos + indicator as usize <= buffer.len(), "no more data but indicatior outside of data buffer"); let slice = &buffer[..(start_pos + indicator as usize)]; Return::Success(Some(T::convert(slice))) } } ffi::SQL_SUCCESS_WITH_INFO => { let initial_len = buffer.len(); // // As a workaround for drivers that don't include tailing null(s) check if last bytes are null // let null_offset = if buffer.ends_with(T::null_bytes()) { T::null_bytes().len() } else { 0 }; // (Alexander Yekimov <[email protected]>) It's a bad idea to do such workarounds // for buggy drivers here. They always can implement OdbcType trait and set any // amount of null-terminators to do the workaround. let null_offset = T::null_bytes_count(); if indicator == ffi::SQL_NO_TOTAL { buffer.resize(initial_len * 2, 0); return self.get_partial_data(col_or_param_num, buffer, initial_len - null_offset); } else { // Check if string has been truncated. if indicator >= initial_len as ffi::SQLLEN { buffer.resize(indicator as usize + T::null_bytes_count(), 0); return self.get_partial_data(col_or_param_num, buffer, initial_len - null_offset); } else { let slice = &buffer[..(start_pos + indicator as usize)]; // No truncation. Warning may be due to some other issue. Return::SuccessWithInfo(Some(T::convert(slice))) } } } ffi::SQL_ERROR => Return::Error, ffi::SQL_NO_DATA => panic!("SQLGetData has already returned the colmun data"), r => panic!("unexpected return value from SQLGetData: {:?}", r), } } }
) -> Return<Option<T>> where
random_line_split
output.rs
use raii::Raii; use {ffi, Handle, Return}; use super::types::OdbcType; /// Indicates that a type can be retrieved using `Cursor::get_data` pub unsafe trait Output<'a>: Sized { fn get_data( stmt: &mut Raii<ffi::Stmt>, col_or_param_num: u16, buffer: &'a mut Vec<u8>, ) -> Return<Option<Self>>; } unsafe impl<'a, T> Output<'a> for T where T: OdbcType<'a>, { fn get_data( stmt: &mut Raii<ffi::Stmt>, col_or_param_num: u16, buffer: &'a mut Vec<u8>, ) -> Return<Option<Self>> { stmt.get_data(col_or_param_num, buffer) } } impl<'p> Raii<'p, ffi::Stmt> { fn get_data<'a, T>( &mut self, col_or_param_num: u16, buffer: &'a mut Vec<u8> ) -> Return<Option<T>> where T: OdbcType<'a>, { self.get_partial_data(col_or_param_num, buffer, 0) } fn
<'a, T>( &mut self, col_or_param_num: u16, buffer: &'a mut Vec<u8>, start_pos: usize ) -> Return<Option<T>> where T: OdbcType<'a>, { if buffer.len() - start_pos == 0 { panic!("buffer length may not be zero"); } if buffer.len() - start_pos > ffi::SQLLEN::max_value() as usize { panic!("buffer is larger than {} bytes", ffi::SQLLEN::max_value()); } let mut indicator: ffi::SQLLEN = 0; // Get buffer length... let result = unsafe { ffi::SQLGetData( self.handle(), col_or_param_num, T::c_data_type(), buffer.as_mut_ptr().offset(start_pos as isize) as ffi::SQLPOINTER, (buffer.len() - start_pos) as ffi::SQLLEN, &mut indicator as *mut ffi::SQLLEN, ) }; match result { ffi::SQL_SUCCESS => { if indicator == ffi::SQL_NULL_DATA { Return::Success(None) } else { assert!(start_pos + indicator as usize <= buffer.len(), "no more data but indicatior outside of data buffer"); let slice = &buffer[..(start_pos + indicator as usize)]; Return::Success(Some(T::convert(slice))) } } ffi::SQL_SUCCESS_WITH_INFO => { let initial_len = buffer.len(); // // As a workaround for drivers that don't include tailing null(s) check if last bytes are null // let null_offset = if buffer.ends_with(T::null_bytes()) { T::null_bytes().len() } else { 0 }; // (Alexander Yekimov <[email protected]>) It's a bad idea to do such workarounds // for buggy drivers here. They always can implement OdbcType trait and set any // amount of null-terminators to do the workaround. let null_offset = T::null_bytes_count(); if indicator == ffi::SQL_NO_TOTAL { buffer.resize(initial_len * 2, 0); return self.get_partial_data(col_or_param_num, buffer, initial_len - null_offset); } else { // Check if string has been truncated. if indicator >= initial_len as ffi::SQLLEN { buffer.resize(indicator as usize + T::null_bytes_count(), 0); return self.get_partial_data(col_or_param_num, buffer, initial_len - null_offset); } else { let slice = &buffer[..(start_pos + indicator as usize)]; // No truncation. Warning may be due to some other issue. Return::SuccessWithInfo(Some(T::convert(slice))) } } } ffi::SQL_ERROR => Return::Error, ffi::SQL_NO_DATA => panic!("SQLGetData has already returned the colmun data"), r => panic!("unexpected return value from SQLGetData: {:?}", r), } } }
get_partial_data
identifier_name
text.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <%helpers:shorthand name="text-decoration" engines="gecko servo-2013" flags="SHORTHAND_IN_GETCS" sub_properties="text-decoration-line ${' text-decoration-style text-decoration-color text-decoration-thickness' if engine == 'gecko' else ''}" spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration"> % if engine == "gecko": use crate::values::specified; use crate::properties::longhands::{text_decoration_style, text_decoration_color, text_decoration_thickness}; use crate::properties::{PropertyId, LonghandId}; % endif use crate::properties::longhands::text_decoration_line; pub fn parse_value<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Longhands, ParseError<'i>>
) } parse_component!(line, text_decoration_line); % if engine == "gecko": parse_component!(style, text_decoration_style); parse_component!(color, text_decoration_color); if text_decoration_thickness_enabled { parse_component!(thickness, text_decoration_thickness); } % endif break; } if!any { return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } Ok(expanded! { text_decoration_line: unwrap_or_initial!(text_decoration_line, line), % if engine == "gecko": text_decoration_style: unwrap_or_initial!(text_decoration_style, style), text_decoration_color: unwrap_or_initial!(text_decoration_color, color), text_decoration_thickness: unwrap_or_initial!(text_decoration_thickness, thickness), % endif }) } impl<'a> ToCss for LonghandsToSerialize<'a> { #[allow(unused)] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write { use crate::values::specified::TextDecorationLine; let (is_solid_style, is_current_color, is_auto_thickness) = ( % if engine == "gecko": *self.text_decoration_style == text_decoration_style::SpecifiedValue::Solid, *self.text_decoration_color == specified::Color::CurrentColor, self.text_decoration_thickness.map_or(true, |t| t.is_auto()) % else: true, true, true % endif ); let mut has_value = false; let is_none = *self.text_decoration_line == TextDecorationLine::none(); if (is_solid_style && is_current_color && is_auto_thickness) ||!is_none { self.text_decoration_line.to_css(dest)?; has_value = true; } % if engine == "gecko": if!is_solid_style { if has_value { dest.write_str(" ")?; } self.text_decoration_style.to_css(dest)?; has_value = true; } if!is_current_color { if has_value { dest.write_str(" ")?; } self.text_decoration_color.to_css(dest)?; has_value = true; } if!is_auto_thickness { if has_value { dest.write_str(" ")?; } self.text_decoration_thickness.to_css(dest)?; } % endif Ok(()) } } </%helpers:shorthand>
{ % if engine == "gecko": let text_decoration_thickness_enabled = PropertyId::Longhand(LonghandId::TextDecorationThickness).enabled_for_all_content(); let (mut line, mut style, mut color, mut thickness, mut any) = (None, None, None, None, false); % else: let (mut line, mut any) = (None, false); % endif loop { macro_rules! parse_component { ($value:ident, $module:ident) => ( if $value.is_none() { if let Ok(value) = input.try(|input| $module::parse(context, input)) { $value = Some(value); any = true; continue; } }
identifier_body
text.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <%helpers:shorthand name="text-decoration" engines="gecko servo-2013" flags="SHORTHAND_IN_GETCS" sub_properties="text-decoration-line ${' text-decoration-style text-decoration-color text-decoration-thickness' if engine == 'gecko' else ''}" spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration"> % if engine == "gecko": use crate::values::specified; use crate::properties::longhands::{text_decoration_style, text_decoration_color, text_decoration_thickness}; use crate::properties::{PropertyId, LonghandId}; % endif use crate::properties::longhands::text_decoration_line; pub fn parse_value<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Longhands, ParseError<'i>> { % if engine == "gecko": let text_decoration_thickness_enabled = PropertyId::Longhand(LonghandId::TextDecorationThickness).enabled_for_all_content(); let (mut line, mut style, mut color, mut thickness, mut any) = (None, None, None, None, false); % else: let (mut line, mut any) = (None, false); % endif loop { macro_rules! parse_component { ($value:ident, $module:ident) => ( if $value.is_none() { if let Ok(value) = input.try(|input| $module::parse(context, input)) { $value = Some(value); any = true; continue; } } ) } parse_component!(line, text_decoration_line); % if engine == "gecko": parse_component!(style, text_decoration_style); parse_component!(color, text_decoration_color); if text_decoration_thickness_enabled { parse_component!(thickness, text_decoration_thickness); } % endif break; } if!any
Ok(expanded! { text_decoration_line: unwrap_or_initial!(text_decoration_line, line), % if engine == "gecko": text_decoration_style: unwrap_or_initial!(text_decoration_style, style), text_decoration_color: unwrap_or_initial!(text_decoration_color, color), text_decoration_thickness: unwrap_or_initial!(text_decoration_thickness, thickness), % endif }) } impl<'a> ToCss for LonghandsToSerialize<'a> { #[allow(unused)] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write { use crate::values::specified::TextDecorationLine; let (is_solid_style, is_current_color, is_auto_thickness) = ( % if engine == "gecko": *self.text_decoration_style == text_decoration_style::SpecifiedValue::Solid, *self.text_decoration_color == specified::Color::CurrentColor, self.text_decoration_thickness.map_or(true, |t| t.is_auto()) % else: true, true, true % endif ); let mut has_value = false; let is_none = *self.text_decoration_line == TextDecorationLine::none(); if (is_solid_style && is_current_color && is_auto_thickness) ||!is_none { self.text_decoration_line.to_css(dest)?; has_value = true; } % if engine == "gecko": if!is_solid_style { if has_value { dest.write_str(" ")?; } self.text_decoration_style.to_css(dest)?; has_value = true; } if!is_current_color { if has_value { dest.write_str(" ")?; } self.text_decoration_color.to_css(dest)?; has_value = true; } if!is_auto_thickness { if has_value { dest.write_str(" ")?; } self.text_decoration_thickness.to_css(dest)?; } % endif Ok(()) } } </%helpers:shorthand>
{ return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); }
conditional_block
text.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <%helpers:shorthand name="text-decoration" engines="gecko servo-2013" flags="SHORTHAND_IN_GETCS" sub_properties="text-decoration-line ${' text-decoration-style text-decoration-color text-decoration-thickness' if engine == 'gecko' else ''}" spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration"> % if engine == "gecko": use crate::values::specified; use crate::properties::longhands::{text_decoration_style, text_decoration_color, text_decoration_thickness}; use crate::properties::{PropertyId, LonghandId}; % endif use crate::properties::longhands::text_decoration_line; pub fn parse_value<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Longhands, ParseError<'i>> { % if engine == "gecko": let text_decoration_thickness_enabled = PropertyId::Longhand(LonghandId::TextDecorationThickness).enabled_for_all_content(); let (mut line, mut style, mut color, mut thickness, mut any) = (None, None, None, None, false); % else: let (mut line, mut any) = (None, false); % endif loop { macro_rules! parse_component { ($value:ident, $module:ident) => ( if $value.is_none() { if let Ok(value) = input.try(|input| $module::parse(context, input)) { $value = Some(value); any = true;
continue; } } ) } parse_component!(line, text_decoration_line); % if engine == "gecko": parse_component!(style, text_decoration_style); parse_component!(color, text_decoration_color); if text_decoration_thickness_enabled { parse_component!(thickness, text_decoration_thickness); } % endif break; } if!any { return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } Ok(expanded! { text_decoration_line: unwrap_or_initial!(text_decoration_line, line), % if engine == "gecko": text_decoration_style: unwrap_or_initial!(text_decoration_style, style), text_decoration_color: unwrap_or_initial!(text_decoration_color, color), text_decoration_thickness: unwrap_or_initial!(text_decoration_thickness, thickness), % endif }) } impl<'a> ToCss for LonghandsToSerialize<'a> { #[allow(unused)] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write { use crate::values::specified::TextDecorationLine; let (is_solid_style, is_current_color, is_auto_thickness) = ( % if engine == "gecko": *self.text_decoration_style == text_decoration_style::SpecifiedValue::Solid, *self.text_decoration_color == specified::Color::CurrentColor, self.text_decoration_thickness.map_or(true, |t| t.is_auto()) % else: true, true, true % endif ); let mut has_value = false; let is_none = *self.text_decoration_line == TextDecorationLine::none(); if (is_solid_style && is_current_color && is_auto_thickness) ||!is_none { self.text_decoration_line.to_css(dest)?; has_value = true; } % if engine == "gecko": if!is_solid_style { if has_value { dest.write_str(" ")?; } self.text_decoration_style.to_css(dest)?; has_value = true; } if!is_current_color { if has_value { dest.write_str(" ")?; } self.text_decoration_color.to_css(dest)?; has_value = true; } if!is_auto_thickness { if has_value { dest.write_str(" ")?; } self.text_decoration_thickness.to_css(dest)?; } % endif Ok(()) } } </%helpers:shorthand>
random_line_split
text.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <%helpers:shorthand name="text-decoration" engines="gecko servo-2013" flags="SHORTHAND_IN_GETCS" sub_properties="text-decoration-line ${' text-decoration-style text-decoration-color text-decoration-thickness' if engine == 'gecko' else ''}" spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration"> % if engine == "gecko": use crate::values::specified; use crate::properties::longhands::{text_decoration_style, text_decoration_color, text_decoration_thickness}; use crate::properties::{PropertyId, LonghandId}; % endif use crate::properties::longhands::text_decoration_line; pub fn
<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Longhands, ParseError<'i>> { % if engine == "gecko": let text_decoration_thickness_enabled = PropertyId::Longhand(LonghandId::TextDecorationThickness).enabled_for_all_content(); let (mut line, mut style, mut color, mut thickness, mut any) = (None, None, None, None, false); % else: let (mut line, mut any) = (None, false); % endif loop { macro_rules! parse_component { ($value:ident, $module:ident) => ( if $value.is_none() { if let Ok(value) = input.try(|input| $module::parse(context, input)) { $value = Some(value); any = true; continue; } } ) } parse_component!(line, text_decoration_line); % if engine == "gecko": parse_component!(style, text_decoration_style); parse_component!(color, text_decoration_color); if text_decoration_thickness_enabled { parse_component!(thickness, text_decoration_thickness); } % endif break; } if!any { return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } Ok(expanded! { text_decoration_line: unwrap_or_initial!(text_decoration_line, line), % if engine == "gecko": text_decoration_style: unwrap_or_initial!(text_decoration_style, style), text_decoration_color: unwrap_or_initial!(text_decoration_color, color), text_decoration_thickness: unwrap_or_initial!(text_decoration_thickness, thickness), % endif }) } impl<'a> ToCss for LonghandsToSerialize<'a> { #[allow(unused)] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write { use crate::values::specified::TextDecorationLine; let (is_solid_style, is_current_color, is_auto_thickness) = ( % if engine == "gecko": *self.text_decoration_style == text_decoration_style::SpecifiedValue::Solid, *self.text_decoration_color == specified::Color::CurrentColor, self.text_decoration_thickness.map_or(true, |t| t.is_auto()) % else: true, true, true % endif ); let mut has_value = false; let is_none = *self.text_decoration_line == TextDecorationLine::none(); if (is_solid_style && is_current_color && is_auto_thickness) ||!is_none { self.text_decoration_line.to_css(dest)?; has_value = true; } % if engine == "gecko": if!is_solid_style { if has_value { dest.write_str(" ")?; } self.text_decoration_style.to_css(dest)?; has_value = true; } if!is_current_color { if has_value { dest.write_str(" ")?; } self.text_decoration_color.to_css(dest)?; has_value = true; } if!is_auto_thickness { if has_value { dest.write_str(" ")?; } self.text_decoration_thickness.to_css(dest)?; } % endif Ok(()) } } </%helpers:shorthand>
parse_value
identifier_name
tests.rs
use crate::Server; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; use futures::future; use nails::execution::{child_channel, ChildInput, Command, ExitCode}; use nails::Config; use task_executor::Executor; use tokio::net::TcpStream; use tokio::runtime::Handle; use tokio::sync::Notify; use tokio::time::delay_for; #[tokio::test] async fn spawn_and_bind() { let server = Server::new(Executor::new(), 0, |_| ExitCode(0)) .await .unwrap(); // Should have bound a random port. assert!(0!= server.port()); server.shutdown().await.unwrap(); } #[tokio::test] async fn accept() { let exit_code = ExitCode(42); let server = Server::new(Executor::new(), 0, move |_| exit_code) .await .unwrap(); // And connect with a client. This Nail will ignore the content of the command, so we're // only validating the exit code. let actual_exit_code = run_client(server.port()).await.unwrap(); assert_eq!(exit_code, actual_exit_code); server.shutdown().await.unwrap(); } #[tokio::test] async fn
() { // A server that waits for a signal to complete a connection. let connection_accepted = Arc::new(Notify::new()); let should_complete_connection = Arc::new(Notify::new()); let exit_code = ExitCode(42); let server = Server::new(Executor::new(), 0, { let connection_accepted = connection_accepted.clone(); let should_complete_connection = should_complete_connection.clone(); move |_| { connection_accepted.notify(); Handle::current().block_on(should_complete_connection.notified()); exit_code } }) .await .unwrap(); // Spawn a connection in the background, and once it has been established, kick off shutdown of // the server. let mut client_completed = tokio::spawn(run_client(server.port())); connection_accepted.notified().await; let mut server_shutdown = tokio::spawn(server.shutdown()); // Confirm that the client doesn't return, and that the server doesn't shutdown. match future::select(client_completed, delay_for(Duration::from_millis(500))).await { future::Either::Right((_, c_c)) => client_completed = c_c, x => panic!("Client should not have completed: {:?}", x), } match future::select(server_shutdown, delay_for(Duration::from_millis(500))).await { future::Either::Right((_, s_s)) => server_shutdown = s_s, x => panic!("Server should not have shut down: {:?}", x), } // Then signal completion of the connection, and confirm that both the client and server exit // cleanly. should_complete_connection.notify(); assert_eq!(exit_code, client_completed.await.unwrap().unwrap()); server_shutdown.await.unwrap().unwrap(); } async fn run_client(port: u16) -> Result<ExitCode, String> { let cmd = Command { command: "nothing".to_owned(), args: vec![], env: vec![], working_dir: PathBuf::from("/dev/null"), }; let stream = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); let child = nails::client::handle_connection(Config::default(), stream, cmd, async { let (_stdin_write, stdin_read) = child_channel::<ChildInput>(); stdin_read }) .await .map_err(|e| e.to_string())?; child.wait().await.map_err(|e| e.to_string()) }
shutdown_awaits_ongoing
identifier_name
tests.rs
use crate::Server; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; use futures::future; use nails::execution::{child_channel, ChildInput, Command, ExitCode}; use nails::Config; use task_executor::Executor; use tokio::net::TcpStream; use tokio::runtime::Handle; use tokio::sync::Notify; use tokio::time::delay_for; #[tokio::test] async fn spawn_and_bind()
#[tokio::test] async fn accept() { let exit_code = ExitCode(42); let server = Server::new(Executor::new(), 0, move |_| exit_code) .await .unwrap(); // And connect with a client. This Nail will ignore the content of the command, so we're // only validating the exit code. let actual_exit_code = run_client(server.port()).await.unwrap(); assert_eq!(exit_code, actual_exit_code); server.shutdown().await.unwrap(); } #[tokio::test] async fn shutdown_awaits_ongoing() { // A server that waits for a signal to complete a connection. let connection_accepted = Arc::new(Notify::new()); let should_complete_connection = Arc::new(Notify::new()); let exit_code = ExitCode(42); let server = Server::new(Executor::new(), 0, { let connection_accepted = connection_accepted.clone(); let should_complete_connection = should_complete_connection.clone(); move |_| { connection_accepted.notify(); Handle::current().block_on(should_complete_connection.notified()); exit_code } }) .await .unwrap(); // Spawn a connection in the background, and once it has been established, kick off shutdown of // the server. let mut client_completed = tokio::spawn(run_client(server.port())); connection_accepted.notified().await; let mut server_shutdown = tokio::spawn(server.shutdown()); // Confirm that the client doesn't return, and that the server doesn't shutdown. match future::select(client_completed, delay_for(Duration::from_millis(500))).await { future::Either::Right((_, c_c)) => client_completed = c_c, x => panic!("Client should not have completed: {:?}", x), } match future::select(server_shutdown, delay_for(Duration::from_millis(500))).await { future::Either::Right((_, s_s)) => server_shutdown = s_s, x => panic!("Server should not have shut down: {:?}", x), } // Then signal completion of the connection, and confirm that both the client and server exit // cleanly. should_complete_connection.notify(); assert_eq!(exit_code, client_completed.await.unwrap().unwrap()); server_shutdown.await.unwrap().unwrap(); } async fn run_client(port: u16) -> Result<ExitCode, String> { let cmd = Command { command: "nothing".to_owned(), args: vec![], env: vec![], working_dir: PathBuf::from("/dev/null"), }; let stream = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); let child = nails::client::handle_connection(Config::default(), stream, cmd, async { let (_stdin_write, stdin_read) = child_channel::<ChildInput>(); stdin_read }) .await .map_err(|e| e.to_string())?; child.wait().await.map_err(|e| e.to_string()) }
{ let server = Server::new(Executor::new(), 0, |_| ExitCode(0)) .await .unwrap(); // Should have bound a random port. assert!(0 != server.port()); server.shutdown().await.unwrap(); }
identifier_body
tests.rs
use crate::Server; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; use futures::future; use nails::execution::{child_channel, ChildInput, Command, ExitCode}; use nails::Config; use task_executor::Executor; use tokio::net::TcpStream; use tokio::runtime::Handle; use tokio::sync::Notify; use tokio::time::delay_for; #[tokio::test] async fn spawn_and_bind() { let server = Server::new(Executor::new(), 0, |_| ExitCode(0)) .await .unwrap(); // Should have bound a random port. assert!(0!= server.port()); server.shutdown().await.unwrap(); } #[tokio::test] async fn accept() { let exit_code = ExitCode(42); let server = Server::new(Executor::new(), 0, move |_| exit_code) .await .unwrap(); // And connect with a client. This Nail will ignore the content of the command, so we're // only validating the exit code. let actual_exit_code = run_client(server.port()).await.unwrap(); assert_eq!(exit_code, actual_exit_code); server.shutdown().await.unwrap(); } #[tokio::test] async fn shutdown_awaits_ongoing() { // A server that waits for a signal to complete a connection. let connection_accepted = Arc::new(Notify::new()); let should_complete_connection = Arc::new(Notify::new()); let exit_code = ExitCode(42); let server = Server::new(Executor::new(), 0, { let connection_accepted = connection_accepted.clone(); let should_complete_connection = should_complete_connection.clone(); move |_| { connection_accepted.notify(); Handle::current().block_on(should_complete_connection.notified());
}) .await .unwrap(); // Spawn a connection in the background, and once it has been established, kick off shutdown of // the server. let mut client_completed = tokio::spawn(run_client(server.port())); connection_accepted.notified().await; let mut server_shutdown = tokio::spawn(server.shutdown()); // Confirm that the client doesn't return, and that the server doesn't shutdown. match future::select(client_completed, delay_for(Duration::from_millis(500))).await { future::Either::Right((_, c_c)) => client_completed = c_c, x => panic!("Client should not have completed: {:?}", x), } match future::select(server_shutdown, delay_for(Duration::from_millis(500))).await { future::Either::Right((_, s_s)) => server_shutdown = s_s, x => panic!("Server should not have shut down: {:?}", x), } // Then signal completion of the connection, and confirm that both the client and server exit // cleanly. should_complete_connection.notify(); assert_eq!(exit_code, client_completed.await.unwrap().unwrap()); server_shutdown.await.unwrap().unwrap(); } async fn run_client(port: u16) -> Result<ExitCode, String> { let cmd = Command { command: "nothing".to_owned(), args: vec![], env: vec![], working_dir: PathBuf::from("/dev/null"), }; let stream = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); let child = nails::client::handle_connection(Config::default(), stream, cmd, async { let (_stdin_write, stdin_read) = child_channel::<ChildInput>(); stdin_read }) .await .map_err(|e| e.to_string())?; child.wait().await.map_err(|e| e.to_string()) }
exit_code }
random_line_split
vrdisplaycapabilities.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::VRDisplayCapabilitiesBinding; use dom::bindings::codegen::Bindings::VRDisplayCapabilitiesBinding::VRDisplayCapabilitiesMethods; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use webvr_traits::WebVRDisplayCapabilities; #[dom_struct] pub struct VRDisplayCapabilities { reflector_: Reflector, #[ignore_malloc_size_of = "Defined in rust-webvr"] capabilities: DomRefCell<WebVRDisplayCapabilities>, } unsafe_no_jsmanaged_fields!(WebVRDisplayCapabilities); impl VRDisplayCapabilities { fn new_inherited(capabilities: WebVRDisplayCapabilities) -> VRDisplayCapabilities { VRDisplayCapabilities { reflector_: Reflector::new(), capabilities: DomRefCell::new(capabilities), } } pub fn new( capabilities: WebVRDisplayCapabilities, global: &GlobalScope, ) -> DomRoot<VRDisplayCapabilities> { reflect_dom_object( Box::new(VRDisplayCapabilities::new_inherited(capabilities)), global, VRDisplayCapabilitiesBinding::Wrap, ) } } impl VRDisplayCapabilitiesMethods for VRDisplayCapabilities { // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-hasposition fn HasPosition(&self) -> bool { self.capabilities.borrow().has_position } // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-hasorientation fn HasOrientation(&self) -> bool { self.capabilities.borrow().has_orientation } // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-hasexternaldisplay fn HasExternalDisplay(&self) -> bool
// https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-canpresent fn CanPresent(&self) -> bool { self.capabilities.borrow().can_present } // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-maxlayers fn MaxLayers(&self) -> u32 { if self.CanPresent() { 1 } else { 0 } } }
{ self.capabilities.borrow().has_external_display }
identifier_body
vrdisplaycapabilities.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::VRDisplayCapabilitiesBinding; use dom::bindings::codegen::Bindings::VRDisplayCapabilitiesBinding::VRDisplayCapabilitiesMethods; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use webvr_traits::WebVRDisplayCapabilities; #[dom_struct] pub struct VRDisplayCapabilities { reflector_: Reflector, #[ignore_malloc_size_of = "Defined in rust-webvr"] capabilities: DomRefCell<WebVRDisplayCapabilities>, } unsafe_no_jsmanaged_fields!(WebVRDisplayCapabilities); impl VRDisplayCapabilities { fn new_inherited(capabilities: WebVRDisplayCapabilities) -> VRDisplayCapabilities { VRDisplayCapabilities { reflector_: Reflector::new(), capabilities: DomRefCell::new(capabilities), } } pub fn new( capabilities: WebVRDisplayCapabilities, global: &GlobalScope, ) -> DomRoot<VRDisplayCapabilities> { reflect_dom_object( Box::new(VRDisplayCapabilities::new_inherited(capabilities)), global, VRDisplayCapabilitiesBinding::Wrap, ) } } impl VRDisplayCapabilitiesMethods for VRDisplayCapabilities { // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-hasposition fn HasPosition(&self) -> bool { self.capabilities.borrow().has_position } // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-hasorientation fn HasOrientation(&self) -> bool { self.capabilities.borrow().has_orientation } // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-hasexternaldisplay fn HasExternalDisplay(&self) -> bool { self.capabilities.borrow().has_external_display } // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-canpresent fn CanPresent(&self) -> bool { self.capabilities.borrow().can_present } // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-maxlayers fn MaxLayers(&self) -> u32 { if self.CanPresent() { 1 } else
} }
{ 0 }
conditional_block
vrdisplaycapabilities.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::VRDisplayCapabilitiesBinding; use dom::bindings::codegen::Bindings::VRDisplayCapabilitiesBinding::VRDisplayCapabilitiesMethods; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use webvr_traits::WebVRDisplayCapabilities; #[dom_struct] pub struct VRDisplayCapabilities { reflector_: Reflector, #[ignore_malloc_size_of = "Defined in rust-webvr"] capabilities: DomRefCell<WebVRDisplayCapabilities>, } unsafe_no_jsmanaged_fields!(WebVRDisplayCapabilities); impl VRDisplayCapabilities { fn new_inherited(capabilities: WebVRDisplayCapabilities) -> VRDisplayCapabilities { VRDisplayCapabilities { reflector_: Reflector::new(), capabilities: DomRefCell::new(capabilities), } } pub fn new( capabilities: WebVRDisplayCapabilities, global: &GlobalScope, ) -> DomRoot<VRDisplayCapabilities> { reflect_dom_object( Box::new(VRDisplayCapabilities::new_inherited(capabilities)), global, VRDisplayCapabilitiesBinding::Wrap, ) } } impl VRDisplayCapabilitiesMethods for VRDisplayCapabilities { // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-hasposition fn HasPosition(&self) -> bool { self.capabilities.borrow().has_position } // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-hasorientation fn HasOrientation(&self) -> bool { self.capabilities.borrow().has_orientation } // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-hasexternaldisplay fn
(&self) -> bool { self.capabilities.borrow().has_external_display } // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-canpresent fn CanPresent(&self) -> bool { self.capabilities.borrow().can_present } // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-maxlayers fn MaxLayers(&self) -> u32 { if self.CanPresent() { 1 } else { 0 } } }
HasExternalDisplay
identifier_name
vrdisplaycapabilities.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::VRDisplayCapabilitiesBinding; use dom::bindings::codegen::Bindings::VRDisplayCapabilitiesBinding::VRDisplayCapabilitiesMethods; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use webvr_traits::WebVRDisplayCapabilities; #[dom_struct] pub struct VRDisplayCapabilities { reflector_: Reflector, #[ignore_malloc_size_of = "Defined in rust-webvr"] capabilities: DomRefCell<WebVRDisplayCapabilities>, } unsafe_no_jsmanaged_fields!(WebVRDisplayCapabilities); impl VRDisplayCapabilities { fn new_inherited(capabilities: WebVRDisplayCapabilities) -> VRDisplayCapabilities { VRDisplayCapabilities { reflector_: Reflector::new(), capabilities: DomRefCell::new(capabilities), } } pub fn new( capabilities: WebVRDisplayCapabilities, global: &GlobalScope, ) -> DomRoot<VRDisplayCapabilities> { reflect_dom_object( Box::new(VRDisplayCapabilities::new_inherited(capabilities)), global, VRDisplayCapabilitiesBinding::Wrap,
) } } impl VRDisplayCapabilitiesMethods for VRDisplayCapabilities { // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-hasposition fn HasPosition(&self) -> bool { self.capabilities.borrow().has_position } // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-hasorientation fn HasOrientation(&self) -> bool { self.capabilities.borrow().has_orientation } // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-hasexternaldisplay fn HasExternalDisplay(&self) -> bool { self.capabilities.borrow().has_external_display } // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-canpresent fn CanPresent(&self) -> bool { self.capabilities.borrow().can_present } // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-maxlayers fn MaxLayers(&self) -> u32 { if self.CanPresent() { 1 } else { 0 } } }
random_line_split
mod.rs
//! Multiplexed RPC protocols. //! //! See the crate-level docs for an overview. mod client; pub use self::client::ClientProto; pub use self::client::ClientService; mod server; pub use self::server::ServerProto; /// Identifies a request / response thread pub type RequestId = u64; /// A marker used to flag protocols as being multiplexed RPC. /// /// This is an implementation detail; to actually implement a protocol, /// implement the `ClientProto` or `ServerProto` traits in this module. #[derive(Debug)] pub struct Multiplex; // This is a submodule so that `LiftTransport` can be marked `pub`, to satisfy // the no-private-in-public checker. mod lift { use std::io; use std::marker::PhantomData; use super::RequestId; use streaming::multiplex::{Frame, Transport}; use futures::{Future, Stream, Sink, StartSend, Poll, Async, AsyncSink}; // Lifts an implementation of RPC-style transport to streaming-style transport pub struct LiftTransport<T, E>(pub T, pub PhantomData<E>); // Lifts the Bind from the underlying transport pub struct LiftBind<A, F, E> {
} impl<T, InnerItem, E> Stream for LiftTransport<T, E> where E:'static, T: Stream<Item = (RequestId, InnerItem), Error = io::Error>, { type Item = Frame<InnerItem, (), E>; type Error = io::Error; fn poll(&mut self) -> Poll<Option<Self::Item>, io::Error> { let (id, msg) = match try_ready!(self.0.poll()) { Some(msg) => msg, None => return Ok(None.into()), }; Ok(Some(Frame::Message { message: msg, body: false, solo: false, id: id, }).into()) } } impl<T, InnerSink, E> Sink for LiftTransport<T, E> where E:'static, T: Sink<SinkItem = (RequestId, InnerSink), SinkError = io::Error> { type SinkItem = Frame<InnerSink, (), E>; type SinkError = io::Error; fn start_send(&mut self, request: Self::SinkItem) -> StartSend<Self::SinkItem, io::Error> { if let Frame::Message { message, id, body, solo } = request { if!body &&!solo { match try!(self.0.start_send((id, message))) { AsyncSink::Ready => return Ok(AsyncSink::Ready), AsyncSink::NotReady((id, msg)) => { let msg = Frame::Message { message: msg, id: id, body: false, solo: false, }; return Ok(AsyncSink::NotReady(msg)) } } } } Err(io::Error::new(io::ErrorKind::Other, "no support for streaming")) } fn poll_complete(&mut self) -> Poll<(), io::Error> { self.0.poll_complete() } fn close(&mut self) -> Poll<(), io::Error> { self.0.close() } } impl<T, InnerItem, InnerSink, E> Transport<()> for LiftTransport<T, E> where E:'static, T:'static, T: Stream<Item = (RequestId, InnerItem), Error = io::Error>, T: Sink<SinkItem = (RequestId, InnerSink), SinkError = io::Error> {} impl<A, F, E> LiftBind<A, F, E> { pub fn lift(f: F) -> LiftBind<A, F, E> { LiftBind { fut: f, marker: PhantomData, } } } impl<A, F, E> Future for LiftBind<A, F, E> where F: Future<Error = io::Error> { type Item = LiftTransport<F::Item, E>; type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, io::Error> { Ok(Async::Ready(LiftTransport(try_ready!(self.fut.poll()), PhantomData))) } } }
fut: F, marker: PhantomData<(A, E)>,
random_line_split
mod.rs
//! Multiplexed RPC protocols. //! //! See the crate-level docs for an overview. mod client; pub use self::client::ClientProto; pub use self::client::ClientService; mod server; pub use self::server::ServerProto; /// Identifies a request / response thread pub type RequestId = u64; /// A marker used to flag protocols as being multiplexed RPC. /// /// This is an implementation detail; to actually implement a protocol, /// implement the `ClientProto` or `ServerProto` traits in this module. #[derive(Debug)] pub struct Multiplex; // This is a submodule so that `LiftTransport` can be marked `pub`, to satisfy // the no-private-in-public checker. mod lift { use std::io; use std::marker::PhantomData; use super::RequestId; use streaming::multiplex::{Frame, Transport}; use futures::{Future, Stream, Sink, StartSend, Poll, Async, AsyncSink}; // Lifts an implementation of RPC-style transport to streaming-style transport pub struct LiftTransport<T, E>(pub T, pub PhantomData<E>); // Lifts the Bind from the underlying transport pub struct LiftBind<A, F, E> { fut: F, marker: PhantomData<(A, E)>, } impl<T, InnerItem, E> Stream for LiftTransport<T, E> where E:'static, T: Stream<Item = (RequestId, InnerItem), Error = io::Error>, { type Item = Frame<InnerItem, (), E>; type Error = io::Error; fn poll(&mut self) -> Poll<Option<Self::Item>, io::Error>
} impl<T, InnerSink, E> Sink for LiftTransport<T, E> where E:'static, T: Sink<SinkItem = (RequestId, InnerSink), SinkError = io::Error> { type SinkItem = Frame<InnerSink, (), E>; type SinkError = io::Error; fn start_send(&mut self, request: Self::SinkItem) -> StartSend<Self::SinkItem, io::Error> { if let Frame::Message { message, id, body, solo } = request { if!body &&!solo { match try!(self.0.start_send((id, message))) { AsyncSink::Ready => return Ok(AsyncSink::Ready), AsyncSink::NotReady((id, msg)) => { let msg = Frame::Message { message: msg, id: id, body: false, solo: false, }; return Ok(AsyncSink::NotReady(msg)) } } } } Err(io::Error::new(io::ErrorKind::Other, "no support for streaming")) } fn poll_complete(&mut self) -> Poll<(), io::Error> { self.0.poll_complete() } fn close(&mut self) -> Poll<(), io::Error> { self.0.close() } } impl<T, InnerItem, InnerSink, E> Transport<()> for LiftTransport<T, E> where E:'static, T:'static, T: Stream<Item = (RequestId, InnerItem), Error = io::Error>, T: Sink<SinkItem = (RequestId, InnerSink), SinkError = io::Error> {} impl<A, F, E> LiftBind<A, F, E> { pub fn lift(f: F) -> LiftBind<A, F, E> { LiftBind { fut: f, marker: PhantomData, } } } impl<A, F, E> Future for LiftBind<A, F, E> where F: Future<Error = io::Error> { type Item = LiftTransport<F::Item, E>; type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, io::Error> { Ok(Async::Ready(LiftTransport(try_ready!(self.fut.poll()), PhantomData))) } } }
{ let (id, msg) = match try_ready!(self.0.poll()) { Some(msg) => msg, None => return Ok(None.into()), }; Ok(Some(Frame::Message { message: msg, body: false, solo: false, id: id, }).into()) }
identifier_body
mod.rs
//! Multiplexed RPC protocols. //! //! See the crate-level docs for an overview. mod client; pub use self::client::ClientProto; pub use self::client::ClientService; mod server; pub use self::server::ServerProto; /// Identifies a request / response thread pub type RequestId = u64; /// A marker used to flag protocols as being multiplexed RPC. /// /// This is an implementation detail; to actually implement a protocol, /// implement the `ClientProto` or `ServerProto` traits in this module. #[derive(Debug)] pub struct
; // This is a submodule so that `LiftTransport` can be marked `pub`, to satisfy // the no-private-in-public checker. mod lift { use std::io; use std::marker::PhantomData; use super::RequestId; use streaming::multiplex::{Frame, Transport}; use futures::{Future, Stream, Sink, StartSend, Poll, Async, AsyncSink}; // Lifts an implementation of RPC-style transport to streaming-style transport pub struct LiftTransport<T, E>(pub T, pub PhantomData<E>); // Lifts the Bind from the underlying transport pub struct LiftBind<A, F, E> { fut: F, marker: PhantomData<(A, E)>, } impl<T, InnerItem, E> Stream for LiftTransport<T, E> where E:'static, T: Stream<Item = (RequestId, InnerItem), Error = io::Error>, { type Item = Frame<InnerItem, (), E>; type Error = io::Error; fn poll(&mut self) -> Poll<Option<Self::Item>, io::Error> { let (id, msg) = match try_ready!(self.0.poll()) { Some(msg) => msg, None => return Ok(None.into()), }; Ok(Some(Frame::Message { message: msg, body: false, solo: false, id: id, }).into()) } } impl<T, InnerSink, E> Sink for LiftTransport<T, E> where E:'static, T: Sink<SinkItem = (RequestId, InnerSink), SinkError = io::Error> { type SinkItem = Frame<InnerSink, (), E>; type SinkError = io::Error; fn start_send(&mut self, request: Self::SinkItem) -> StartSend<Self::SinkItem, io::Error> { if let Frame::Message { message, id, body, solo } = request { if!body &&!solo { match try!(self.0.start_send((id, message))) { AsyncSink::Ready => return Ok(AsyncSink::Ready), AsyncSink::NotReady((id, msg)) => { let msg = Frame::Message { message: msg, id: id, body: false, solo: false, }; return Ok(AsyncSink::NotReady(msg)) } } } } Err(io::Error::new(io::ErrorKind::Other, "no support for streaming")) } fn poll_complete(&mut self) -> Poll<(), io::Error> { self.0.poll_complete() } fn close(&mut self) -> Poll<(), io::Error> { self.0.close() } } impl<T, InnerItem, InnerSink, E> Transport<()> for LiftTransport<T, E> where E:'static, T:'static, T: Stream<Item = (RequestId, InnerItem), Error = io::Error>, T: Sink<SinkItem = (RequestId, InnerSink), SinkError = io::Error> {} impl<A, F, E> LiftBind<A, F, E> { pub fn lift(f: F) -> LiftBind<A, F, E> { LiftBind { fut: f, marker: PhantomData, } } } impl<A, F, E> Future for LiftBind<A, F, E> where F: Future<Error = io::Error> { type Item = LiftTransport<F::Item, E>; type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, io::Error> { Ok(Async::Ready(LiftTransport(try_ready!(self.fut.poll()), PhantomData))) } } }
Multiplex
identifier_name
rule_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A list of CSS rules. #[cfg(feature = "gecko")] use malloc_size_of::{MallocShallowSizeOf, MallocSizeOfOps}; use servo_arc::{Arc, RawOffsetArc}; use shared_lock::{DeepCloneParams, DeepCloneWithLock, Locked}; use shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard}; use std::fmt::{self, Write}; use str::CssStringWriter; use stylesheets::{CssRule, RulesMutateError}; use stylesheets::loader::StylesheetLoader; use stylesheets::rule_parser::{InsertRuleContext, State}; use stylesheets::stylesheet::StylesheetContents; /// A list of CSS rules. #[derive(Debug)] pub struct CssRules(pub Vec<CssRule>); impl CssRules { /// Whether this CSS rules is empty. pub fn is_empty(&self) -> bool { self.0.is_empty() } } impl DeepCloneWithLock for CssRules { fn deep_clone_with_lock( &self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard, params: &DeepCloneParams, ) -> Self { CssRules( self.0 .iter() .map(|x| x.deep_clone_with_lock(lock, guard, params)) .collect(), ) } } impl CssRules { /// Measure heap usage. #[cfg(feature = "gecko")] pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize { let mut n = self.0.shallow_size_of(ops); for rule in self.0.iter() { n += rule.size_of(guard, ops); } n } /// Trivially construct a new set of CSS rules. pub fn new(rules: Vec<CssRule>, shared_lock: &SharedRwLock) -> Arc<Locked<CssRules>> { Arc::new(shared_lock.wrap(CssRules(rules))) } /// Returns whether all the rules in this list are namespace or import /// rules. fn
(&self) -> bool { self.0.iter().all(|r| match *r { CssRule::Namespace(..) | CssRule::Import(..) => true, _ => false, }) } /// <https://drafts.csswg.org/cssom/#remove-a-css-rule> pub fn remove_rule(&mut self, index: usize) -> Result<(), RulesMutateError> { // Step 1, 2 if index >= self.0.len() { return Err(RulesMutateError::IndexSize); } { // Step 3 let ref rule = self.0[index]; // Step 4 if let CssRule::Namespace(..) = *rule { if!self.only_ns_or_import() { return Err(RulesMutateError::InvalidState); } } } // Step 5, 6 self.0.remove(index); Ok(()) } /// Serializes this CSSRules to CSS text as a block of rules. /// /// This should be speced into CSSOM spec at some point. See /// <https://github.com/w3c/csswg-drafts/issues/1985> pub fn to_css_block( &self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter, ) -> fmt::Result { dest.write_str(" {")?; for rule in self.0.iter() { dest.write_str("\n ")?; rule.to_css(guard, dest)?; } dest.write_str("\n}") } } /// A trait to implement helpers for `Arc<Locked<CssRules>>`. pub trait CssRulesHelpers { /// <https://drafts.csswg.org/cssom/#insert-a-css-rule> /// /// Written in this funky way because parsing an @import rule may cause us /// to clone a stylesheet from the same document due to caching in the CSS /// loader. /// /// TODO(emilio): We could also pass the write guard down into the loader /// instead, but that seems overkill. fn insert_rule( &self, lock: &SharedRwLock, rule: &str, parent_stylesheet_contents: &StylesheetContents, index: usize, nested: bool, loader: Option<&StylesheetLoader>, ) -> Result<CssRule, RulesMutateError>; } impl CssRulesHelpers for RawOffsetArc<Locked<CssRules>> { fn insert_rule( &self, lock: &SharedRwLock, rule: &str, parent_stylesheet_contents: &StylesheetContents, index: usize, nested: bool, loader: Option<&StylesheetLoader>, ) -> Result<CssRule, RulesMutateError> { let new_rule = { let read_guard = lock.read(); let rules = self.read_with(&read_guard); // Step 1, 2 if index > rules.0.len() { return Err(RulesMutateError::IndexSize); } // Computes the parser state at the given index let state = if nested { State::Body } else if index == 0 { State::Start } else { rules .0 .get(index - 1) .map(CssRule::rule_state) .unwrap_or(State::Body) }; let insert_rule_context = InsertRuleContext { rule_list: &rules.0, index, }; // Steps 3, 4, 5, 6 CssRule::parse( &rule, insert_rule_context, parent_stylesheet_contents, lock, state, loader, )? }; { let mut write_guard = lock.write(); let rules = self.write_with(&mut write_guard); rules.0.insert(index, new_rule.clone()); } Ok(new_rule) } }
only_ns_or_import
identifier_name
rule_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A list of CSS rules. #[cfg(feature = "gecko")] use malloc_size_of::{MallocShallowSizeOf, MallocSizeOfOps}; use servo_arc::{Arc, RawOffsetArc}; use shared_lock::{DeepCloneParams, DeepCloneWithLock, Locked}; use shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard}; use std::fmt::{self, Write}; use str::CssStringWriter; use stylesheets::{CssRule, RulesMutateError}; use stylesheets::loader::StylesheetLoader; use stylesheets::rule_parser::{InsertRuleContext, State}; use stylesheets::stylesheet::StylesheetContents; /// A list of CSS rules. #[derive(Debug)] pub struct CssRules(pub Vec<CssRule>); impl CssRules { /// Whether this CSS rules is empty. pub fn is_empty(&self) -> bool { self.0.is_empty() } } impl DeepCloneWithLock for CssRules { fn deep_clone_with_lock( &self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard, params: &DeepCloneParams, ) -> Self { CssRules( self.0 .iter() .map(|x| x.deep_clone_with_lock(lock, guard, params)) .collect(), ) } } impl CssRules { /// Measure heap usage. #[cfg(feature = "gecko")] pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize { let mut n = self.0.shallow_size_of(ops); for rule in self.0.iter() { n += rule.size_of(guard, ops); } n } /// Trivially construct a new set of CSS rules. pub fn new(rules: Vec<CssRule>, shared_lock: &SharedRwLock) -> Arc<Locked<CssRules>> { Arc::new(shared_lock.wrap(CssRules(rules))) } /// Returns whether all the rules in this list are namespace or import /// rules. fn only_ns_or_import(&self) -> bool { self.0.iter().all(|r| match *r { CssRule::Namespace(..) | CssRule::Import(..) => true, _ => false, }) } /// <https://drafts.csswg.org/cssom/#remove-a-css-rule> pub fn remove_rule(&mut self, index: usize) -> Result<(), RulesMutateError> { // Step 1, 2 if index >= self.0.len() { return Err(RulesMutateError::IndexSize); } { // Step 3 let ref rule = self.0[index]; // Step 4 if let CssRule::Namespace(..) = *rule { if!self.only_ns_or_import() { return Err(RulesMutateError::InvalidState); } } } // Step 5, 6 self.0.remove(index); Ok(()) } /// Serializes this CSSRules to CSS text as a block of rules. /// /// This should be speced into CSSOM spec at some point. See /// <https://github.com/w3c/csswg-drafts/issues/1985> pub fn to_css_block( &self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter, ) -> fmt::Result { dest.write_str(" {")?; for rule in self.0.iter() { dest.write_str("\n ")?; rule.to_css(guard, dest)?; } dest.write_str("\n}") } } /// A trait to implement helpers for `Arc<Locked<CssRules>>`. pub trait CssRulesHelpers { /// <https://drafts.csswg.org/cssom/#insert-a-css-rule> /// /// Written in this funky way because parsing an @import rule may cause us /// to clone a stylesheet from the same document due to caching in the CSS /// loader. /// /// TODO(emilio): We could also pass the write guard down into the loader /// instead, but that seems overkill. fn insert_rule( &self, lock: &SharedRwLock, rule: &str, parent_stylesheet_contents: &StylesheetContents, index: usize, nested: bool, loader: Option<&StylesheetLoader>, ) -> Result<CssRule, RulesMutateError>; } impl CssRulesHelpers for RawOffsetArc<Locked<CssRules>> { fn insert_rule( &self, lock: &SharedRwLock, rule: &str, parent_stylesheet_contents: &StylesheetContents, index: usize, nested: bool, loader: Option<&StylesheetLoader>, ) -> Result<CssRule, RulesMutateError> { let new_rule = {
let read_guard = lock.read(); let rules = self.read_with(&read_guard); // Step 1, 2 if index > rules.0.len() { return Err(RulesMutateError::IndexSize); } // Computes the parser state at the given index let state = if nested { State::Body } else if index == 0 { State::Start } else { rules .0 .get(index - 1) .map(CssRule::rule_state) .unwrap_or(State::Body) }; let insert_rule_context = InsertRuleContext { rule_list: &rules.0, index, }; // Steps 3, 4, 5, 6 CssRule::parse( &rule, insert_rule_context, parent_stylesheet_contents, lock, state, loader, )? }; { let mut write_guard = lock.write(); let rules = self.write_with(&mut write_guard); rules.0.insert(index, new_rule.clone()); } Ok(new_rule) } }
random_line_split
rule_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A list of CSS rules. #[cfg(feature = "gecko")] use malloc_size_of::{MallocShallowSizeOf, MallocSizeOfOps}; use servo_arc::{Arc, RawOffsetArc}; use shared_lock::{DeepCloneParams, DeepCloneWithLock, Locked}; use shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard}; use std::fmt::{self, Write}; use str::CssStringWriter; use stylesheets::{CssRule, RulesMutateError}; use stylesheets::loader::StylesheetLoader; use stylesheets::rule_parser::{InsertRuleContext, State}; use stylesheets::stylesheet::StylesheetContents; /// A list of CSS rules. #[derive(Debug)] pub struct CssRules(pub Vec<CssRule>); impl CssRules { /// Whether this CSS rules is empty. pub fn is_empty(&self) -> bool { self.0.is_empty() } } impl DeepCloneWithLock for CssRules { fn deep_clone_with_lock( &self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard, params: &DeepCloneParams, ) -> Self { CssRules( self.0 .iter() .map(|x| x.deep_clone_with_lock(lock, guard, params)) .collect(), ) } } impl CssRules { /// Measure heap usage. #[cfg(feature = "gecko")] pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize { let mut n = self.0.shallow_size_of(ops); for rule in self.0.iter() { n += rule.size_of(guard, ops); } n } /// Trivially construct a new set of CSS rules. pub fn new(rules: Vec<CssRule>, shared_lock: &SharedRwLock) -> Arc<Locked<CssRules>> { Arc::new(shared_lock.wrap(CssRules(rules))) } /// Returns whether all the rules in this list are namespace or import /// rules. fn only_ns_or_import(&self) -> bool { self.0.iter().all(|r| match *r { CssRule::Namespace(..) | CssRule::Import(..) => true, _ => false, }) } /// <https://drafts.csswg.org/cssom/#remove-a-css-rule> pub fn remove_rule(&mut self, index: usize) -> Result<(), RulesMutateError> { // Step 1, 2 if index >= self.0.len()
{ // Step 3 let ref rule = self.0[index]; // Step 4 if let CssRule::Namespace(..) = *rule { if!self.only_ns_or_import() { return Err(RulesMutateError::InvalidState); } } } // Step 5, 6 self.0.remove(index); Ok(()) } /// Serializes this CSSRules to CSS text as a block of rules. /// /// This should be speced into CSSOM spec at some point. See /// <https://github.com/w3c/csswg-drafts/issues/1985> pub fn to_css_block( &self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter, ) -> fmt::Result { dest.write_str(" {")?; for rule in self.0.iter() { dest.write_str("\n ")?; rule.to_css(guard, dest)?; } dest.write_str("\n}") } } /// A trait to implement helpers for `Arc<Locked<CssRules>>`. pub trait CssRulesHelpers { /// <https://drafts.csswg.org/cssom/#insert-a-css-rule> /// /// Written in this funky way because parsing an @import rule may cause us /// to clone a stylesheet from the same document due to caching in the CSS /// loader. /// /// TODO(emilio): We could also pass the write guard down into the loader /// instead, but that seems overkill. fn insert_rule( &self, lock: &SharedRwLock, rule: &str, parent_stylesheet_contents: &StylesheetContents, index: usize, nested: bool, loader: Option<&StylesheetLoader>, ) -> Result<CssRule, RulesMutateError>; } impl CssRulesHelpers for RawOffsetArc<Locked<CssRules>> { fn insert_rule( &self, lock: &SharedRwLock, rule: &str, parent_stylesheet_contents: &StylesheetContents, index: usize, nested: bool, loader: Option<&StylesheetLoader>, ) -> Result<CssRule, RulesMutateError> { let new_rule = { let read_guard = lock.read(); let rules = self.read_with(&read_guard); // Step 1, 2 if index > rules.0.len() { return Err(RulesMutateError::IndexSize); } // Computes the parser state at the given index let state = if nested { State::Body } else if index == 0 { State::Start } else { rules .0 .get(index - 1) .map(CssRule::rule_state) .unwrap_or(State::Body) }; let insert_rule_context = InsertRuleContext { rule_list: &rules.0, index, }; // Steps 3, 4, 5, 6 CssRule::parse( &rule, insert_rule_context, parent_stylesheet_contents, lock, state, loader, )? }; { let mut write_guard = lock.write(); let rules = self.write_with(&mut write_guard); rules.0.insert(index, new_rule.clone()); } Ok(new_rule) } }
{ return Err(RulesMutateError::IndexSize); }
conditional_block
rule_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A list of CSS rules. #[cfg(feature = "gecko")] use malloc_size_of::{MallocShallowSizeOf, MallocSizeOfOps}; use servo_arc::{Arc, RawOffsetArc}; use shared_lock::{DeepCloneParams, DeepCloneWithLock, Locked}; use shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard}; use std::fmt::{self, Write}; use str::CssStringWriter; use stylesheets::{CssRule, RulesMutateError}; use stylesheets::loader::StylesheetLoader; use stylesheets::rule_parser::{InsertRuleContext, State}; use stylesheets::stylesheet::StylesheetContents; /// A list of CSS rules. #[derive(Debug)] pub struct CssRules(pub Vec<CssRule>); impl CssRules { /// Whether this CSS rules is empty. pub fn is_empty(&self) -> bool { self.0.is_empty() } } impl DeepCloneWithLock for CssRules { fn deep_clone_with_lock( &self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard, params: &DeepCloneParams, ) -> Self { CssRules( self.0 .iter() .map(|x| x.deep_clone_with_lock(lock, guard, params)) .collect(), ) } } impl CssRules { /// Measure heap usage. #[cfg(feature = "gecko")] pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize { let mut n = self.0.shallow_size_of(ops); for rule in self.0.iter() { n += rule.size_of(guard, ops); } n } /// Trivially construct a new set of CSS rules. pub fn new(rules: Vec<CssRule>, shared_lock: &SharedRwLock) -> Arc<Locked<CssRules>> { Arc::new(shared_lock.wrap(CssRules(rules))) } /// Returns whether all the rules in this list are namespace or import /// rules. fn only_ns_or_import(&self) -> bool { self.0.iter().all(|r| match *r { CssRule::Namespace(..) | CssRule::Import(..) => true, _ => false, }) } /// <https://drafts.csswg.org/cssom/#remove-a-css-rule> pub fn remove_rule(&mut self, index: usize) -> Result<(), RulesMutateError> { // Step 1, 2 if index >= self.0.len() { return Err(RulesMutateError::IndexSize); } { // Step 3 let ref rule = self.0[index]; // Step 4 if let CssRule::Namespace(..) = *rule { if!self.only_ns_or_import() { return Err(RulesMutateError::InvalidState); } } } // Step 5, 6 self.0.remove(index); Ok(()) } /// Serializes this CSSRules to CSS text as a block of rules. /// /// This should be speced into CSSOM spec at some point. See /// <https://github.com/w3c/csswg-drafts/issues/1985> pub fn to_css_block( &self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter, ) -> fmt::Result { dest.write_str(" {")?; for rule in self.0.iter() { dest.write_str("\n ")?; rule.to_css(guard, dest)?; } dest.write_str("\n}") } } /// A trait to implement helpers for `Arc<Locked<CssRules>>`. pub trait CssRulesHelpers { /// <https://drafts.csswg.org/cssom/#insert-a-css-rule> /// /// Written in this funky way because parsing an @import rule may cause us /// to clone a stylesheet from the same document due to caching in the CSS /// loader. /// /// TODO(emilio): We could also pass the write guard down into the loader /// instead, but that seems overkill. fn insert_rule( &self, lock: &SharedRwLock, rule: &str, parent_stylesheet_contents: &StylesheetContents, index: usize, nested: bool, loader: Option<&StylesheetLoader>, ) -> Result<CssRule, RulesMutateError>; } impl CssRulesHelpers for RawOffsetArc<Locked<CssRules>> { fn insert_rule( &self, lock: &SharedRwLock, rule: &str, parent_stylesheet_contents: &StylesheetContents, index: usize, nested: bool, loader: Option<&StylesheetLoader>, ) -> Result<CssRule, RulesMutateError>
.unwrap_or(State::Body) }; let insert_rule_context = InsertRuleContext { rule_list: &rules.0, index, }; // Steps 3, 4, 5, 6 CssRule::parse( &rule, insert_rule_context, parent_stylesheet_contents, lock, state, loader, )? }; { let mut write_guard = lock.write(); let rules = self.write_with(&mut write_guard); rules.0.insert(index, new_rule.clone()); } Ok(new_rule) } }
{ let new_rule = { let read_guard = lock.read(); let rules = self.read_with(&read_guard); // Step 1, 2 if index > rules.0.len() { return Err(RulesMutateError::IndexSize); } // Computes the parser state at the given index let state = if nested { State::Body } else if index == 0 { State::Start } else { rules .0 .get(index - 1) .map(CssRule::rule_state)
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![deny(unsafe_code)] extern crate euclid; extern crate gfx_traits; extern crate gleam; extern crate image; extern crate ipc_channel; extern crate libc; #[macro_use] extern crate log; extern crate msg; extern crate net_traits; extern crate nonzero; extern crate profile_traits; extern crate script_traits; extern crate servo_config; extern crate servo_geometry; extern crate servo_url; extern crate style_traits; extern crate time; extern crate webrender; extern crate webrender_api; pub use compositor_thread::CompositorProxy; pub use compositor::IOCompositor; pub use compositor::RenderNotifier; pub use compositor::ShutdownState; use euclid::TypedSize2D; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; use msg::constellation_msg::TopLevelBrowsingContextId; use script_traits::{ConstellationControlMsg, LayoutControlMsg}; use style_traits::CSSPixel; mod compositor; pub mod compositor_thread; mod touch; pub mod windowing; pub struct
{ pub pipeline: CompositionPipeline, pub size: Option<TypedSize2D<f32, CSSPixel>>, pub children: Vec<SendableFrameTree>, } /// The subset of the pipeline that is needed for layer composition. #[derive(Clone)] pub struct CompositionPipeline { pub id: PipelineId, pub top_level_browsing_context_id: TopLevelBrowsingContextId, pub script_chan: IpcSender<ConstellationControlMsg>, pub layout_chan: IpcSender<LayoutControlMsg>, }
SendableFrameTree
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![deny(unsafe_code)] extern crate euclid; extern crate gfx_traits; extern crate gleam; extern crate image; extern crate ipc_channel; extern crate libc; #[macro_use] extern crate log; extern crate msg; extern crate net_traits; extern crate nonzero; extern crate profile_traits; extern crate script_traits; extern crate servo_config; extern crate servo_geometry; extern crate servo_url; extern crate style_traits; extern crate time; extern crate webrender; extern crate webrender_api; pub use compositor_thread::CompositorProxy; pub use compositor::IOCompositor; pub use compositor::RenderNotifier; pub use compositor::ShutdownState; use euclid::TypedSize2D; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; use msg::constellation_msg::TopLevelBrowsingContextId; use script_traits::{ConstellationControlMsg, LayoutControlMsg}; use style_traits::CSSPixel; mod compositor; pub mod compositor_thread; mod touch; pub mod windowing; pub struct SendableFrameTree { pub pipeline: CompositionPipeline, pub size: Option<TypedSize2D<f32, CSSPixel>>, pub children: Vec<SendableFrameTree>, }
pub struct CompositionPipeline { pub id: PipelineId, pub top_level_browsing_context_id: TopLevelBrowsingContextId, pub script_chan: IpcSender<ConstellationControlMsg>, pub layout_chan: IpcSender<LayoutControlMsg>, }
/// The subset of the pipeline that is needed for layer composition. #[derive(Clone)]
random_line_split
cleanup-shortcircuit.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. // 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. // Test that cleanups for the RHS of shortcircuiting operators work. use std::env; pub fn
() { let args: Vec<String> = env::args().collect(); // Here, the rvalue `"signal".to_string()` requires cleanup. Older versions // of the code had a problem that the cleanup scope for this // expression was the end of the `if`, and as the `"signal".to_string()` // expression was never evaluated, we wound up trying to clean // uninitialized memory. if args.len() >= 2 && args[1] == "signal" { // Raise a segfault. unsafe { *(0 as *mut int) = 0; } } }
main
identifier_name
cleanup-shortcircuit.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. // 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. // Test that cleanups for the RHS of shortcircuiting operators work. use std::env; pub fn main() { let args: Vec<String> = env::args().collect(); // Here, the rvalue `"signal".to_string()` requires cleanup. Older versions // of the code had a problem that the cleanup scope for this // expression was the end of the `if`, and as the `"signal".to_string()` // expression was never evaluated, we wound up trying to clean // uninitialized memory.
// Raise a segfault. unsafe { *(0 as *mut int) = 0; } } }
if args.len() >= 2 && args[1] == "signal" {
random_line_split
cleanup-shortcircuit.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. // 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. // Test that cleanups for the RHS of shortcircuiting operators work. use std::env; pub fn main()
{ let args: Vec<String> = env::args().collect(); // Here, the rvalue `"signal".to_string()` requires cleanup. Older versions // of the code had a problem that the cleanup scope for this // expression was the end of the `if`, and as the `"signal".to_string()` // expression was never evaluated, we wound up trying to clean // uninitialized memory. if args.len() >= 2 && args[1] == "signal" { // Raise a segfault. unsafe { *(0 as *mut int) = 0; } } }
identifier_body
cleanup-shortcircuit.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. // 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. // Test that cleanups for the RHS of shortcircuiting operators work. use std::env; pub fn main() { let args: Vec<String> = env::args().collect(); // Here, the rvalue `"signal".to_string()` requires cleanup. Older versions // of the code had a problem that the cleanup scope for this // expression was the end of the `if`, and as the `"signal".to_string()` // expression was never evaluated, we wound up trying to clean // uninitialized memory. if args.len() >= 2 && args[1] == "signal"
}
{ // Raise a segfault. unsafe { *(0 as *mut int) = 0; } }
conditional_block
shootout-spectralnorm.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // - Neither the name of "The Computer Language Benchmarks Game" nor // the name of "The Computer Language Shootout Benchmarks" nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. // no-pretty-expanded FIXME #15189 #![allow(non_snake_case)] #![feature(unboxed_closures, core, os, scoped)] use std::iter::repeat; use std::thread; use std::mem; use std::os; use std::env; use std::raw::Repr; use std::simd::f64x2; fn main() { let mut args = env::args(); let answer = spectralnorm(if env::var_os("RUST_BENCH").is_some() { 5500 } else if args.len() < 2 { 2000 } else { args.nth(1).unwrap().parse().unwrap() }); println!("{:.9}", answer); } fn spectralnorm(n: usize) -> f64 { assert!(n % 2 == 0, "only even lengths are accepted"); let mut u = repeat(1.0).take(n).collect::<Vec<_>>(); let mut v = u.clone(); let mut tmp = v.clone(); for _ in 0..10 { mult_AtAv(&u, &mut v, &mut tmp); mult_AtAv(&v, &mut u, &mut tmp); } (dot(&u, &v) / dot(&v, &v)).sqrt() } fn mult_AtAv(v: &[f64], out: &mut [f64], tmp: &mut [f64])
fn mult_Av(v: &[f64], out: &mut [f64]) { parallel(out, |start, out| mult(v, out, start, |i, j| A(i, j))); } fn mult_Atv(v: &[f64], out: &mut [f64]) { parallel(out, |start, out| mult(v, out, start, |i, j| A(j, i))); } fn mult<F>(v: &[f64], out: &mut [f64], start: usize, a: F) where F: Fn(usize, usize) -> f64 { for (i, slot) in out.iter_mut().enumerate().map(|(i, s)| (i + start, s)) { let mut sum = f64x2(0.0, 0.0); for (j, chunk) in v.chunks(2).enumerate().map(|(j, s)| (2 * j, s)) { let top = f64x2(chunk[0], chunk[1]); let bot = f64x2(a(i, j), a(i, j + 1)); sum += top / bot; } let f64x2(a, b) = sum; *slot = a + b; } } fn A(i: usize, j: usize) -> f64 { ((i + j) * (i + j + 1) / 2 + i + 1) as f64 } fn dot(v: &[f64], u: &[f64]) -> f64 { v.iter().zip(u).map(|(a, b)| *a * *b).sum() } // Executes a closure in parallel over the given mutable slice. The closure `f` // is run in parallel and yielded the starting index within `v` as well as a // sub-slice of `v`. fn parallel<'a,T, F>(v: &mut [T], ref f: F) where T: Send + Sync + 'a, F: Fn(usize, &mut [T]) + Sync + 'a { // FIXME: pick a more appropriate parallel factor let parallelism = 4; let size = v.len() / parallelism + 1; v.chunks_mut(size).enumerate().map(|(i, chunk)| { thread::scoped(move|| { f(i * size, chunk) }) }).collect::<Vec<_>>(); }
{ mult_Av(v, tmp); mult_Atv(tmp, out); }
identifier_body
shootout-spectralnorm.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // - Neither the name of "The Computer Language Benchmarks Game" nor // the name of "The Computer Language Shootout Benchmarks" nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. // no-pretty-expanded FIXME #15189 #![allow(non_snake_case)] #![feature(unboxed_closures, core, os, scoped)] use std::iter::repeat; use std::thread; use std::mem; use std::os; use std::env; use std::raw::Repr; use std::simd::f64x2; fn main() { let mut args = env::args(); let answer = spectralnorm(if env::var_os("RUST_BENCH").is_some() { 5500 } else if args.len() < 2 { 2000 } else { args.nth(1).unwrap().parse().unwrap() }); println!("{:.9}", answer); } fn spectralnorm(n: usize) -> f64 { assert!(n % 2 == 0, "only even lengths are accepted"); let mut u = repeat(1.0).take(n).collect::<Vec<_>>(); let mut v = u.clone(); let mut tmp = v.clone(); for _ in 0..10 { mult_AtAv(&u, &mut v, &mut tmp); mult_AtAv(&v, &mut u, &mut tmp); } (dot(&u, &v) / dot(&v, &v)).sqrt() } fn mult_AtAv(v: &[f64], out: &mut [f64], tmp: &mut [f64]) { mult_Av(v, tmp); mult_Atv(tmp, out); } fn
(v: &[f64], out: &mut [f64]) { parallel(out, |start, out| mult(v, out, start, |i, j| A(i, j))); } fn mult_Atv(v: &[f64], out: &mut [f64]) { parallel(out, |start, out| mult(v, out, start, |i, j| A(j, i))); } fn mult<F>(v: &[f64], out: &mut [f64], start: usize, a: F) where F: Fn(usize, usize) -> f64 { for (i, slot) in out.iter_mut().enumerate().map(|(i, s)| (i + start, s)) { let mut sum = f64x2(0.0, 0.0); for (j, chunk) in v.chunks(2).enumerate().map(|(j, s)| (2 * j, s)) { let top = f64x2(chunk[0], chunk[1]); let bot = f64x2(a(i, j), a(i, j + 1)); sum += top / bot; } let f64x2(a, b) = sum; *slot = a + b; } } fn A(i: usize, j: usize) -> f64 { ((i + j) * (i + j + 1) / 2 + i + 1) as f64 } fn dot(v: &[f64], u: &[f64]) -> f64 { v.iter().zip(u).map(|(a, b)| *a * *b).sum() } // Executes a closure in parallel over the given mutable slice. The closure `f` // is run in parallel and yielded the starting index within `v` as well as a // sub-slice of `v`. fn parallel<'a,T, F>(v: &mut [T], ref f: F) where T: Send + Sync + 'a, F: Fn(usize, &mut [T]) + Sync + 'a { // FIXME: pick a more appropriate parallel factor let parallelism = 4; let size = v.len() / parallelism + 1; v.chunks_mut(size).enumerate().map(|(i, chunk)| { thread::scoped(move|| { f(i * size, chunk) }) }).collect::<Vec<_>>(); }
mult_Av
identifier_name
shootout-spectralnorm.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // - Neither the name of "The Computer Language Benchmarks Game" nor
// written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. // no-pretty-expanded FIXME #15189 #![allow(non_snake_case)] #![feature(unboxed_closures, core, os, scoped)] use std::iter::repeat; use std::thread; use std::mem; use std::os; use std::env; use std::raw::Repr; use std::simd::f64x2; fn main() { let mut args = env::args(); let answer = spectralnorm(if env::var_os("RUST_BENCH").is_some() { 5500 } else if args.len() < 2 { 2000 } else { args.nth(1).unwrap().parse().unwrap() }); println!("{:.9}", answer); } fn spectralnorm(n: usize) -> f64 { assert!(n % 2 == 0, "only even lengths are accepted"); let mut u = repeat(1.0).take(n).collect::<Vec<_>>(); let mut v = u.clone(); let mut tmp = v.clone(); for _ in 0..10 { mult_AtAv(&u, &mut v, &mut tmp); mult_AtAv(&v, &mut u, &mut tmp); } (dot(&u, &v) / dot(&v, &v)).sqrt() } fn mult_AtAv(v: &[f64], out: &mut [f64], tmp: &mut [f64]) { mult_Av(v, tmp); mult_Atv(tmp, out); } fn mult_Av(v: &[f64], out: &mut [f64]) { parallel(out, |start, out| mult(v, out, start, |i, j| A(i, j))); } fn mult_Atv(v: &[f64], out: &mut [f64]) { parallel(out, |start, out| mult(v, out, start, |i, j| A(j, i))); } fn mult<F>(v: &[f64], out: &mut [f64], start: usize, a: F) where F: Fn(usize, usize) -> f64 { for (i, slot) in out.iter_mut().enumerate().map(|(i, s)| (i + start, s)) { let mut sum = f64x2(0.0, 0.0); for (j, chunk) in v.chunks(2).enumerate().map(|(j, s)| (2 * j, s)) { let top = f64x2(chunk[0], chunk[1]); let bot = f64x2(a(i, j), a(i, j + 1)); sum += top / bot; } let f64x2(a, b) = sum; *slot = a + b; } } fn A(i: usize, j: usize) -> f64 { ((i + j) * (i + j + 1) / 2 + i + 1) as f64 } fn dot(v: &[f64], u: &[f64]) -> f64 { v.iter().zip(u).map(|(a, b)| *a * *b).sum() } // Executes a closure in parallel over the given mutable slice. The closure `f` // is run in parallel and yielded the starting index within `v` as well as a // sub-slice of `v`. fn parallel<'a,T, F>(v: &mut [T], ref f: F) where T: Send + Sync + 'a, F: Fn(usize, &mut [T]) + Sync + 'a { // FIXME: pick a more appropriate parallel factor let parallelism = 4; let size = v.len() / parallelism + 1; v.chunks_mut(size).enumerate().map(|(i, chunk)| { thread::scoped(move|| { f(i * size, chunk) }) }).collect::<Vec<_>>(); }
// the name of "The Computer Language Shootout Benchmarks" nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior
random_line_split
tempfile.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-win32 TempDir may cause IoError on windows: #10463 // These tests are here to exercise the functionality of the `tempfile` module. // One might expect these tests to be located in that module, but sadly they // cannot. The tests need to invoke `os::change_dir` which cannot be done in the // normal test infrastructure. If the tests change the current working // directory, then *all* tests which require relative paths suddenly break b/c // they're in a different location than before. Hence, these tests are all run // serially here. use std::io::{fs, TempDir}; use std::io; use std::os; use std::task; fn test_tempdir() { let path = { let p = TempDir::new_in(&Path::new("."), "foobar").unwrap(); let p = p.path(); assert!(p.as_vec().ends_with(bytes!("foobar"))); p.clone() }; assert!(!path.exists()); } fn test_rm_tempdir() { let (tx, rx) = channel(); let f: proc():Send = proc() { let tmp = TempDir::new("test_rm_tempdir").unwrap(); tx.send(tmp.path().clone()); fail!("fail to unwind past `tmp`"); }; task::try(f); let path = rx.recv(); assert!(!path.exists()); let tmp = TempDir::new("test_rm_tempdir").unwrap(); let path = tmp.path().clone(); let f: proc():Send = proc() { let _tmp = tmp; fail!("fail to unwind past `tmp`"); }; task::try(f); assert!(!path.exists()); let path; { let f = proc() { TempDir::new("test_rm_tempdir").unwrap() }; let tmp = task::try(f).ok().expect("test_rm_tmdir"); path = tmp.path().clone(); assert!(path.exists()); } assert!(!path.exists()); let path; { let tmp = TempDir::new("test_rm_tempdir").unwrap(); path = tmp.unwrap(); } assert!(path.exists()); fs::rmdir_recursive(&path); assert!(!path.exists()); } fn test_rm_tempdir_close() { let (tx, rx) = channel(); let f: proc():Send = proc() { let tmp = TempDir::new("test_rm_tempdir").unwrap(); tx.send(tmp.path().clone()); tmp.close(); fail!("fail to unwind past `tmp`"); }; task::try(f); let path = rx.recv(); assert!(!path.exists()); let tmp = TempDir::new("test_rm_tempdir").unwrap(); let path = tmp.path().clone(); let f: proc():Send = proc() { let tmp = tmp; tmp.close(); fail!("fail to unwind past `tmp`"); }; task::try(f); assert!(!path.exists()); let path; { let f = proc() { TempDir::new("test_rm_tempdir").unwrap() }; let tmp = task::try(f).ok().expect("test_rm_tmdir"); path = tmp.path().clone(); assert!(path.exists()); tmp.close(); } assert!(!path.exists()); let path; { let tmp = TempDir::new("test_rm_tempdir").unwrap(); path = tmp.unwrap(); } assert!(path.exists()); fs::rmdir_recursive(&path); assert!(!path.exists()); } // Ideally these would be in std::os but then core would need // to depend on std fn recursive_mkdir_rel() { let path = Path::new("frob"); let cwd = os::getcwd(); println!("recursive_mkdir_rel: Making: {} in cwd {} [{:?}]", path.display(), cwd.display(), path.exists()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); } fn recursive_mkdir_dot() { let dot = Path::new("."); fs::mkdir_recursive(&dot, io::UserRWX); let dotdot = Path::new(".."); fs::mkdir_recursive(&dotdot, io::UserRWX); } fn recursive_mkdir_rel_2()
// Ideally this would be in core, but needs TempFile pub fn test_rmdir_recursive_ok() { let rwx = io::UserRWX; let tmpdir = TempDir::new("test").expect("test_rmdir_recursive_ok: \ couldn't create temp dir"); let tmpdir = tmpdir.path(); let root = tmpdir.join("foo"); println!("making {}", root.display()); fs::mkdir(&root, rwx); fs::mkdir(&root.join("foo"), rwx); fs::mkdir(&root.join("foo").join("bar"), rwx); fs::mkdir(&root.join("foo").join("bar").join("blat"), rwx); fs::rmdir_recursive(&root); assert!(!root.exists()); assert!(!root.join("bar").exists()); assert!(!root.join("bar").join("blat").exists()); } pub fn dont_double_fail() { let r: Result<(), _> = task::try(proc() { let tmpdir = TempDir::new("test").unwrap(); // Remove the temporary directory so that TempDir sees // an error on drop fs::rmdir(tmpdir.path()); // Trigger failure. If TempDir fails *again* due to the rmdir // error then the process will abort. fail!(); }); assert!(r.is_err()); } fn in_tmpdir(f: ||) { let tmpdir = TempDir::new("test").expect("can't make tmpdir"); assert!(os::change_dir(tmpdir.path())); f(); } pub fn main() { in_tmpdir(test_tempdir); in_tmpdir(test_rm_tempdir); in_tmpdir(test_rm_tempdir_close); in_tmpdir(recursive_mkdir_rel); in_tmpdir(recursive_mkdir_dot); in_tmpdir(recursive_mkdir_rel_2); in_tmpdir(test_rmdir_recursive_ok); in_tmpdir(dont_double_fail); }
{ let path = Path::new("./frob/baz"); let cwd = os::getcwd(); println!("recursive_mkdir_rel_2: Making: {} in cwd {} [{:?}]", path.display(), cwd.display(), path.exists()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); assert!(path.dir_path().is_dir()); let path2 = Path::new("quux/blat"); println!("recursive_mkdir_rel_2: Making: {} in cwd {}", path2.display(), cwd.display()); fs::mkdir_recursive(&path2, io::UserRWX); assert!(path2.is_dir()); assert!(path2.dir_path().is_dir()); }
identifier_body
tempfile.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-win32 TempDir may cause IoError on windows: #10463 // These tests are here to exercise the functionality of the `tempfile` module. // One might expect these tests to be located in that module, but sadly they // cannot. The tests need to invoke `os::change_dir` which cannot be done in the // normal test infrastructure. If the tests change the current working // directory, then *all* tests which require relative paths suddenly break b/c // they're in a different location than before. Hence, these tests are all run // serially here. use std::io::{fs, TempDir}; use std::io; use std::os; use std::task; fn
() { let path = { let p = TempDir::new_in(&Path::new("."), "foobar").unwrap(); let p = p.path(); assert!(p.as_vec().ends_with(bytes!("foobar"))); p.clone() }; assert!(!path.exists()); } fn test_rm_tempdir() { let (tx, rx) = channel(); let f: proc():Send = proc() { let tmp = TempDir::new("test_rm_tempdir").unwrap(); tx.send(tmp.path().clone()); fail!("fail to unwind past `tmp`"); }; task::try(f); let path = rx.recv(); assert!(!path.exists()); let tmp = TempDir::new("test_rm_tempdir").unwrap(); let path = tmp.path().clone(); let f: proc():Send = proc() { let _tmp = tmp; fail!("fail to unwind past `tmp`"); }; task::try(f); assert!(!path.exists()); let path; { let f = proc() { TempDir::new("test_rm_tempdir").unwrap() }; let tmp = task::try(f).ok().expect("test_rm_tmdir"); path = tmp.path().clone(); assert!(path.exists()); } assert!(!path.exists()); let path; { let tmp = TempDir::new("test_rm_tempdir").unwrap(); path = tmp.unwrap(); } assert!(path.exists()); fs::rmdir_recursive(&path); assert!(!path.exists()); } fn test_rm_tempdir_close() { let (tx, rx) = channel(); let f: proc():Send = proc() { let tmp = TempDir::new("test_rm_tempdir").unwrap(); tx.send(tmp.path().clone()); tmp.close(); fail!("fail to unwind past `tmp`"); }; task::try(f); let path = rx.recv(); assert!(!path.exists()); let tmp = TempDir::new("test_rm_tempdir").unwrap(); let path = tmp.path().clone(); let f: proc():Send = proc() { let tmp = tmp; tmp.close(); fail!("fail to unwind past `tmp`"); }; task::try(f); assert!(!path.exists()); let path; { let f = proc() { TempDir::new("test_rm_tempdir").unwrap() }; let tmp = task::try(f).ok().expect("test_rm_tmdir"); path = tmp.path().clone(); assert!(path.exists()); tmp.close(); } assert!(!path.exists()); let path; { let tmp = TempDir::new("test_rm_tempdir").unwrap(); path = tmp.unwrap(); } assert!(path.exists()); fs::rmdir_recursive(&path); assert!(!path.exists()); } // Ideally these would be in std::os but then core would need // to depend on std fn recursive_mkdir_rel() { let path = Path::new("frob"); let cwd = os::getcwd(); println!("recursive_mkdir_rel: Making: {} in cwd {} [{:?}]", path.display(), cwd.display(), path.exists()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); } fn recursive_mkdir_dot() { let dot = Path::new("."); fs::mkdir_recursive(&dot, io::UserRWX); let dotdot = Path::new(".."); fs::mkdir_recursive(&dotdot, io::UserRWX); } fn recursive_mkdir_rel_2() { let path = Path::new("./frob/baz"); let cwd = os::getcwd(); println!("recursive_mkdir_rel_2: Making: {} in cwd {} [{:?}]", path.display(), cwd.display(), path.exists()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); assert!(path.dir_path().is_dir()); let path2 = Path::new("quux/blat"); println!("recursive_mkdir_rel_2: Making: {} in cwd {}", path2.display(), cwd.display()); fs::mkdir_recursive(&path2, io::UserRWX); assert!(path2.is_dir()); assert!(path2.dir_path().is_dir()); } // Ideally this would be in core, but needs TempFile pub fn test_rmdir_recursive_ok() { let rwx = io::UserRWX; let tmpdir = TempDir::new("test").expect("test_rmdir_recursive_ok: \ couldn't create temp dir"); let tmpdir = tmpdir.path(); let root = tmpdir.join("foo"); println!("making {}", root.display()); fs::mkdir(&root, rwx); fs::mkdir(&root.join("foo"), rwx); fs::mkdir(&root.join("foo").join("bar"), rwx); fs::mkdir(&root.join("foo").join("bar").join("blat"), rwx); fs::rmdir_recursive(&root); assert!(!root.exists()); assert!(!root.join("bar").exists()); assert!(!root.join("bar").join("blat").exists()); } pub fn dont_double_fail() { let r: Result<(), _> = task::try(proc() { let tmpdir = TempDir::new("test").unwrap(); // Remove the temporary directory so that TempDir sees // an error on drop fs::rmdir(tmpdir.path()); // Trigger failure. If TempDir fails *again* due to the rmdir // error then the process will abort. fail!(); }); assert!(r.is_err()); } fn in_tmpdir(f: ||) { let tmpdir = TempDir::new("test").expect("can't make tmpdir"); assert!(os::change_dir(tmpdir.path())); f(); } pub fn main() { in_tmpdir(test_tempdir); in_tmpdir(test_rm_tempdir); in_tmpdir(test_rm_tempdir_close); in_tmpdir(recursive_mkdir_rel); in_tmpdir(recursive_mkdir_dot); in_tmpdir(recursive_mkdir_rel_2); in_tmpdir(test_rmdir_recursive_ok); in_tmpdir(dont_double_fail); }
test_tempdir
identifier_name
tempfile.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-win32 TempDir may cause IoError on windows: #10463
// normal test infrastructure. If the tests change the current working // directory, then *all* tests which require relative paths suddenly break b/c // they're in a different location than before. Hence, these tests are all run // serially here. use std::io::{fs, TempDir}; use std::io; use std::os; use std::task; fn test_tempdir() { let path = { let p = TempDir::new_in(&Path::new("."), "foobar").unwrap(); let p = p.path(); assert!(p.as_vec().ends_with(bytes!("foobar"))); p.clone() }; assert!(!path.exists()); } fn test_rm_tempdir() { let (tx, rx) = channel(); let f: proc():Send = proc() { let tmp = TempDir::new("test_rm_tempdir").unwrap(); tx.send(tmp.path().clone()); fail!("fail to unwind past `tmp`"); }; task::try(f); let path = rx.recv(); assert!(!path.exists()); let tmp = TempDir::new("test_rm_tempdir").unwrap(); let path = tmp.path().clone(); let f: proc():Send = proc() { let _tmp = tmp; fail!("fail to unwind past `tmp`"); }; task::try(f); assert!(!path.exists()); let path; { let f = proc() { TempDir::new("test_rm_tempdir").unwrap() }; let tmp = task::try(f).ok().expect("test_rm_tmdir"); path = tmp.path().clone(); assert!(path.exists()); } assert!(!path.exists()); let path; { let tmp = TempDir::new("test_rm_tempdir").unwrap(); path = tmp.unwrap(); } assert!(path.exists()); fs::rmdir_recursive(&path); assert!(!path.exists()); } fn test_rm_tempdir_close() { let (tx, rx) = channel(); let f: proc():Send = proc() { let tmp = TempDir::new("test_rm_tempdir").unwrap(); tx.send(tmp.path().clone()); tmp.close(); fail!("fail to unwind past `tmp`"); }; task::try(f); let path = rx.recv(); assert!(!path.exists()); let tmp = TempDir::new("test_rm_tempdir").unwrap(); let path = tmp.path().clone(); let f: proc():Send = proc() { let tmp = tmp; tmp.close(); fail!("fail to unwind past `tmp`"); }; task::try(f); assert!(!path.exists()); let path; { let f = proc() { TempDir::new("test_rm_tempdir").unwrap() }; let tmp = task::try(f).ok().expect("test_rm_tmdir"); path = tmp.path().clone(); assert!(path.exists()); tmp.close(); } assert!(!path.exists()); let path; { let tmp = TempDir::new("test_rm_tempdir").unwrap(); path = tmp.unwrap(); } assert!(path.exists()); fs::rmdir_recursive(&path); assert!(!path.exists()); } // Ideally these would be in std::os but then core would need // to depend on std fn recursive_mkdir_rel() { let path = Path::new("frob"); let cwd = os::getcwd(); println!("recursive_mkdir_rel: Making: {} in cwd {} [{:?}]", path.display(), cwd.display(), path.exists()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); } fn recursive_mkdir_dot() { let dot = Path::new("."); fs::mkdir_recursive(&dot, io::UserRWX); let dotdot = Path::new(".."); fs::mkdir_recursive(&dotdot, io::UserRWX); } fn recursive_mkdir_rel_2() { let path = Path::new("./frob/baz"); let cwd = os::getcwd(); println!("recursive_mkdir_rel_2: Making: {} in cwd {} [{:?}]", path.display(), cwd.display(), path.exists()); fs::mkdir_recursive(&path, io::UserRWX); assert!(path.is_dir()); assert!(path.dir_path().is_dir()); let path2 = Path::new("quux/blat"); println!("recursive_mkdir_rel_2: Making: {} in cwd {}", path2.display(), cwd.display()); fs::mkdir_recursive(&path2, io::UserRWX); assert!(path2.is_dir()); assert!(path2.dir_path().is_dir()); } // Ideally this would be in core, but needs TempFile pub fn test_rmdir_recursive_ok() { let rwx = io::UserRWX; let tmpdir = TempDir::new("test").expect("test_rmdir_recursive_ok: \ couldn't create temp dir"); let tmpdir = tmpdir.path(); let root = tmpdir.join("foo"); println!("making {}", root.display()); fs::mkdir(&root, rwx); fs::mkdir(&root.join("foo"), rwx); fs::mkdir(&root.join("foo").join("bar"), rwx); fs::mkdir(&root.join("foo").join("bar").join("blat"), rwx); fs::rmdir_recursive(&root); assert!(!root.exists()); assert!(!root.join("bar").exists()); assert!(!root.join("bar").join("blat").exists()); } pub fn dont_double_fail() { let r: Result<(), _> = task::try(proc() { let tmpdir = TempDir::new("test").unwrap(); // Remove the temporary directory so that TempDir sees // an error on drop fs::rmdir(tmpdir.path()); // Trigger failure. If TempDir fails *again* due to the rmdir // error then the process will abort. fail!(); }); assert!(r.is_err()); } fn in_tmpdir(f: ||) { let tmpdir = TempDir::new("test").expect("can't make tmpdir"); assert!(os::change_dir(tmpdir.path())); f(); } pub fn main() { in_tmpdir(test_tempdir); in_tmpdir(test_rm_tempdir); in_tmpdir(test_rm_tempdir_close); in_tmpdir(recursive_mkdir_rel); in_tmpdir(recursive_mkdir_dot); in_tmpdir(recursive_mkdir_rel_2); in_tmpdir(test_rmdir_recursive_ok); in_tmpdir(dont_double_fail); }
// These tests are here to exercise the functionality of the `tempfile` module. // One might expect these tests to be located in that module, but sadly they // cannot. The tests need to invoke `os::change_dir` which cannot be done in the
random_line_split
merge_parallel.rs
#![crate_id = "Parallel_merge"] #![crate_type = "bin"] //! Parallel merge sort, using the green library to get scheduled threads. extern crate getopts; extern crate green; use green::{SchedPool, PoolConfig}; use green::sched::PinnedTask; use getopts::{reqopt, optflag, getopts, OptGroup}; use std::os; use std::task::TaskOpts; use common::utils::number_array_from_file; use common::sort::{insertion_sort, merge}; pub mod common { pub mod utils; pub mod sort; } /// Takes an array of type T which is cloneable (Clone), can be compared with /// binary operators like > and < (Ord), is sendable for channels (Send), and /// showable with println! (Show). Also takes a number of sub arrays as a power /// of two to split the array into. Returns a sorted array of the same type T. pub fn merge_sort_parallel<T: Clone + Ord + Send>(mut array: Vec<T>) -> Vec<T> { let config = PoolConfig::new(); let mut pool = SchedPool::new(config); // setting up the scheduling pool for handles to threads let array_refs = split(array); let mut sorted_subarrays : Vec<Vec<T>> = Vec::new(); let length = array_refs.len(); let (tx, rx): (Sender<~[T]>, Receiver<~[T]>) = channel(); // Threads need a sender and a receiver in a channel to communicate let mut i = 0; while i < length { let mut handle = pool.spawn_sched(); //create a new handle let (subarray_begin, subarray_end) = array_refs.as_slice()[0]; let subarray_unsort = array.slice(subarray_begin, subarray_end + 1).to_owned(); let child_tx = tx.clone(); // you can't overload one sending channel let task = pool.task(TaskOpts::new(), proc() { //sets up a task for the handle let subarray = insertion_sort(subarray_unsort); //let subarray_refs = (sorted_sub[0], sorted_sub[sorted_sub.len() - 1]); child_tx.send(subarray); // sends the sorted sub array to rx }); handle.send(PinnedTask(task)); // the handle takes the task drop(handle); // the handle is destroyed after doing its job sorted_subarrays.push(rx.recv()); // get the sorted sub array i += 1; } pool.shutdown(); // the pool must shutdown after it has done its duty let sorted_array_wrapped = merge_wrapper(sorted_subarrays); array = sorted_array_wrapped[0]; // merge wrapper returns ~[~[T]] return array; } /// merge_wrapper will repeatedly merge arrays in an array until there /// is only one remaining element. Takes an array of arrays of type T which /// has the traits Clone and Ord, and returns a single array in an array. pub fn merge_wrapper<T: Ord + Clone + Send>(mut array_array: ~[~[T]]) -> ~[~[T]] { let array_n = array_array.len(); if array_n == 1 { return array_array.to_owned() } let config = PoolConfig::new(); let mut pool = SchedPool::new(config); let (tx, rx): (Sender<~[T]>, Receiver<~[T]>) = channel(); let mut i = 0; let mut j = 0; while i < array_n - 1 { let mut handle = pool.spawn_sched(); let sub_array1 = array_array[i].clone(); let sub_array2 = array_array[i + 1].clone(); let child_tx = tx.clone(); let task = pool.task(TaskOpts::new(), proc() { let merged_sub = merge(sub_array1.clone(), sub_array2.clone()); child_tx.send(merged_sub); }); handle.send(PinnedTask(task)); drop(handle); array_array[j] = rx.recv(); i += 2; j += 1; } pool.shutdown(); array_array = array_array.slice(0, j).to_owned(); return merge_wrapper(array_array); } /// Takes an array of type T which can be Cloned, and the number of subarrays /// for it to be broken into. Returns an array of tuples of uints for the array /// to be split into. pub fn split<T: Clone>(array: Vec<T>) -> ~[(uint, uint)]
i += min_size; } split_array.push((i, length - 1)); split_array.shift(); //removes first value that initialized split_array return split_array; } /// prints a help message pub fn print_usage(program: &str, _opts: &[OptGroup]) { println!("Usage: {} [options]", program); println!("-f,\t--file\t\t Input file"); } fn main() { let args = os::args(); let program = args[0].clone(); let opts = ~[ reqopt("f", "file", "input file name", "FILENAME"), optflag("h", "help", "print this help message") ]; let matches = match getopts(args.tail(), opts) { Ok(m) => { m } Err(f) => { fail!(f.to_err_msg()) } }; if matches.opt_present("h") { print_usage(program, opts); return; } let input_filename = match matches.opt_str("f") { Some(string) => string, _ => ~"Invalid" }; if input_filename == ~"Invalid" { println!("Invalid paramater."); return; } let array = number_array_from_file(input_filename, 0i); let sorted_array = merge_sort_parallel(array.clone()); for elem in sorted_array.iter() { println!("{}", elem); } println!("\n{}", sorted_array.len()); }
{ let mut number_of_sub_arrays = 1; loop { if array.len() % (number_of_sub_arrays * 2) != 0 { break } if number_of_sub_arrays > 256 { break } number_of_sub_arrays *= 2; } let mut i = 0; let length = array.len(); let min_size = length / number_of_sub_arrays; let mut split_array: ~[(uint, uint)] = ~[(0, 0)]; //initializes array while i + min_size < length { let sub_array2 = i + min_size - 1; split_array.push((i, sub_array2));
identifier_body
merge_parallel.rs
#![crate_id = "Parallel_merge"] #![crate_type = "bin"] //! Parallel merge sort, using the green library to get scheduled threads. extern crate getopts; extern crate green; use green::{SchedPool, PoolConfig}; use green::sched::PinnedTask; use getopts::{reqopt, optflag, getopts, OptGroup}; use std::os; use std::task::TaskOpts; use common::utils::number_array_from_file; use common::sort::{insertion_sort, merge}; pub mod common { pub mod utils; pub mod sort; } /// Takes an array of type T which is cloneable (Clone), can be compared with /// binary operators like > and < (Ord), is sendable for channels (Send), and /// showable with println! (Show). Also takes a number of sub arrays as a power /// of two to split the array into. Returns a sorted array of the same type T. pub fn merge_sort_parallel<T: Clone + Ord + Send>(mut array: Vec<T>) -> Vec<T> { let config = PoolConfig::new(); let mut pool = SchedPool::new(config); // setting up the scheduling pool for handles to threads let array_refs = split(array); let mut sorted_subarrays : Vec<Vec<T>> = Vec::new(); let length = array_refs.len(); let (tx, rx): (Sender<~[T]>, Receiver<~[T]>) = channel(); // Threads need a sender and a receiver in a channel to communicate let mut i = 0; while i < length { let mut handle = pool.spawn_sched(); //create a new handle let (subarray_begin, subarray_end) = array_refs.as_slice()[0]; let subarray_unsort = array.slice(subarray_begin, subarray_end + 1).to_owned(); let child_tx = tx.clone(); // you can't overload one sending channel let task = pool.task(TaskOpts::new(), proc() { //sets up a task for the handle let subarray = insertion_sort(subarray_unsort); //let subarray_refs = (sorted_sub[0], sorted_sub[sorted_sub.len() - 1]); child_tx.send(subarray); // sends the sorted sub array to rx }); handle.send(PinnedTask(task)); // the handle takes the task drop(handle); // the handle is destroyed after doing its job sorted_subarrays.push(rx.recv()); // get the sorted sub array i += 1; } pool.shutdown(); // the pool must shutdown after it has done its duty let sorted_array_wrapped = merge_wrapper(sorted_subarrays); array = sorted_array_wrapped[0]; // merge wrapper returns ~[~[T]] return array; } /// merge_wrapper will repeatedly merge arrays in an array until there /// is only one remaining element. Takes an array of arrays of type T which /// has the traits Clone and Ord, and returns a single array in an array. pub fn merge_wrapper<T: Ord + Clone + Send>(mut array_array: ~[~[T]]) -> ~[~[T]] { let array_n = array_array.len(); if array_n == 1 { return array_array.to_owned() } let config = PoolConfig::new(); let mut pool = SchedPool::new(config); let (tx, rx): (Sender<~[T]>, Receiver<~[T]>) = channel(); let mut i = 0; let mut j = 0; while i < array_n - 1 { let mut handle = pool.spawn_sched(); let sub_array1 = array_array[i].clone();
child_tx.send(merged_sub); }); handle.send(PinnedTask(task)); drop(handle); array_array[j] = rx.recv(); i += 2; j += 1; } pool.shutdown(); array_array = array_array.slice(0, j).to_owned(); return merge_wrapper(array_array); } /// Takes an array of type T which can be Cloned, and the number of subarrays /// for it to be broken into. Returns an array of tuples of uints for the array /// to be split into. pub fn split<T: Clone>(array: Vec<T>) -> ~[(uint, uint)] { let mut number_of_sub_arrays = 1; loop { if array.len() % (number_of_sub_arrays * 2)!= 0 { break } if number_of_sub_arrays > 256 { break } number_of_sub_arrays *= 2; } let mut i = 0; let length = array.len(); let min_size = length / number_of_sub_arrays; let mut split_array: ~[(uint, uint)] = ~[(0, 0)]; //initializes array while i + min_size < length { let sub_array2 = i + min_size - 1; split_array.push((i, sub_array2)); i += min_size; } split_array.push((i, length - 1)); split_array.shift(); //removes first value that initialized split_array return split_array; } /// prints a help message pub fn print_usage(program: &str, _opts: &[OptGroup]) { println!("Usage: {} [options]", program); println!("-f,\t--file\t\t Input file"); } fn main() { let args = os::args(); let program = args[0].clone(); let opts = ~[ reqopt("f", "file", "input file name", "FILENAME"), optflag("h", "help", "print this help message") ]; let matches = match getopts(args.tail(), opts) { Ok(m) => { m } Err(f) => { fail!(f.to_err_msg()) } }; if matches.opt_present("h") { print_usage(program, opts); return; } let input_filename = match matches.opt_str("f") { Some(string) => string, _ => ~"Invalid" }; if input_filename == ~"Invalid" { println!("Invalid paramater."); return; } let array = number_array_from_file(input_filename, 0i); let sorted_array = merge_sort_parallel(array.clone()); for elem in sorted_array.iter() { println!("{}", elem); } println!("\n{}", sorted_array.len()); }
let sub_array2 = array_array[i + 1].clone(); let child_tx = tx.clone(); let task = pool.task(TaskOpts::new(), proc() { let merged_sub = merge(sub_array1.clone(), sub_array2.clone());
random_line_split
merge_parallel.rs
#![crate_id = "Parallel_merge"] #![crate_type = "bin"] //! Parallel merge sort, using the green library to get scheduled threads. extern crate getopts; extern crate green; use green::{SchedPool, PoolConfig}; use green::sched::PinnedTask; use getopts::{reqopt, optflag, getopts, OptGroup}; use std::os; use std::task::TaskOpts; use common::utils::number_array_from_file; use common::sort::{insertion_sort, merge}; pub mod common { pub mod utils; pub mod sort; } /// Takes an array of type T which is cloneable (Clone), can be compared with /// binary operators like > and < (Ord), is sendable for channels (Send), and /// showable with println! (Show). Also takes a number of sub arrays as a power /// of two to split the array into. Returns a sorted array of the same type T. pub fn merge_sort_parallel<T: Clone + Ord + Send>(mut array: Vec<T>) -> Vec<T> { let config = PoolConfig::new(); let mut pool = SchedPool::new(config); // setting up the scheduling pool for handles to threads let array_refs = split(array); let mut sorted_subarrays : Vec<Vec<T>> = Vec::new(); let length = array_refs.len(); let (tx, rx): (Sender<~[T]>, Receiver<~[T]>) = channel(); // Threads need a sender and a receiver in a channel to communicate let mut i = 0; while i < length { let mut handle = pool.spawn_sched(); //create a new handle let (subarray_begin, subarray_end) = array_refs.as_slice()[0]; let subarray_unsort = array.slice(subarray_begin, subarray_end + 1).to_owned(); let child_tx = tx.clone(); // you can't overload one sending channel let task = pool.task(TaskOpts::new(), proc() { //sets up a task for the handle let subarray = insertion_sort(subarray_unsort); //let subarray_refs = (sorted_sub[0], sorted_sub[sorted_sub.len() - 1]); child_tx.send(subarray); // sends the sorted sub array to rx }); handle.send(PinnedTask(task)); // the handle takes the task drop(handle); // the handle is destroyed after doing its job sorted_subarrays.push(rx.recv()); // get the sorted sub array i += 1; } pool.shutdown(); // the pool must shutdown after it has done its duty let sorted_array_wrapped = merge_wrapper(sorted_subarrays); array = sorted_array_wrapped[0]; // merge wrapper returns ~[~[T]] return array; } /// merge_wrapper will repeatedly merge arrays in an array until there /// is only one remaining element. Takes an array of arrays of type T which /// has the traits Clone and Ord, and returns a single array in an array. pub fn merge_wrapper<T: Ord + Clone + Send>(mut array_array: ~[~[T]]) -> ~[~[T]] { let array_n = array_array.len(); if array_n == 1 { return array_array.to_owned() } let config = PoolConfig::new(); let mut pool = SchedPool::new(config); let (tx, rx): (Sender<~[T]>, Receiver<~[T]>) = channel(); let mut i = 0; let mut j = 0; while i < array_n - 1 { let mut handle = pool.spawn_sched(); let sub_array1 = array_array[i].clone(); let sub_array2 = array_array[i + 1].clone(); let child_tx = tx.clone(); let task = pool.task(TaskOpts::new(), proc() { let merged_sub = merge(sub_array1.clone(), sub_array2.clone()); child_tx.send(merged_sub); }); handle.send(PinnedTask(task)); drop(handle); array_array[j] = rx.recv(); i += 2; j += 1; } pool.shutdown(); array_array = array_array.slice(0, j).to_owned(); return merge_wrapper(array_array); } /// Takes an array of type T which can be Cloned, and the number of subarrays /// for it to be broken into. Returns an array of tuples of uints for the array /// to be split into. pub fn split<T: Clone>(array: Vec<T>) -> ~[(uint, uint)] { let mut number_of_sub_arrays = 1; loop { if array.len() % (number_of_sub_arrays * 2)!= 0 { break } if number_of_sub_arrays > 256 { break } number_of_sub_arrays *= 2; } let mut i = 0; let length = array.len(); let min_size = length / number_of_sub_arrays; let mut split_array: ~[(uint, uint)] = ~[(0, 0)]; //initializes array while i + min_size < length { let sub_array2 = i + min_size - 1; split_array.push((i, sub_array2)); i += min_size; } split_array.push((i, length - 1)); split_array.shift(); //removes first value that initialized split_array return split_array; } /// prints a help message pub fn
(program: &str, _opts: &[OptGroup]) { println!("Usage: {} [options]", program); println!("-f,\t--file\t\t Input file"); } fn main() { let args = os::args(); let program = args[0].clone(); let opts = ~[ reqopt("f", "file", "input file name", "FILENAME"), optflag("h", "help", "print this help message") ]; let matches = match getopts(args.tail(), opts) { Ok(m) => { m } Err(f) => { fail!(f.to_err_msg()) } }; if matches.opt_present("h") { print_usage(program, opts); return; } let input_filename = match matches.opt_str("f") { Some(string) => string, _ => ~"Invalid" }; if input_filename == ~"Invalid" { println!("Invalid paramater."); return; } let array = number_array_from_file(input_filename, 0i); let sorted_array = merge_sort_parallel(array.clone()); for elem in sorted_array.iter() { println!("{}", elem); } println!("\n{}", sorted_array.len()); }
print_usage
identifier_name
merge_parallel.rs
#![crate_id = "Parallel_merge"] #![crate_type = "bin"] //! Parallel merge sort, using the green library to get scheduled threads. extern crate getopts; extern crate green; use green::{SchedPool, PoolConfig}; use green::sched::PinnedTask; use getopts::{reqopt, optflag, getopts, OptGroup}; use std::os; use std::task::TaskOpts; use common::utils::number_array_from_file; use common::sort::{insertion_sort, merge}; pub mod common { pub mod utils; pub mod sort; } /// Takes an array of type T which is cloneable (Clone), can be compared with /// binary operators like > and < (Ord), is sendable for channels (Send), and /// showable with println! (Show). Also takes a number of sub arrays as a power /// of two to split the array into. Returns a sorted array of the same type T. pub fn merge_sort_parallel<T: Clone + Ord + Send>(mut array: Vec<T>) -> Vec<T> { let config = PoolConfig::new(); let mut pool = SchedPool::new(config); // setting up the scheduling pool for handles to threads let array_refs = split(array); let mut sorted_subarrays : Vec<Vec<T>> = Vec::new(); let length = array_refs.len(); let (tx, rx): (Sender<~[T]>, Receiver<~[T]>) = channel(); // Threads need a sender and a receiver in a channel to communicate let mut i = 0; while i < length { let mut handle = pool.spawn_sched(); //create a new handle let (subarray_begin, subarray_end) = array_refs.as_slice()[0]; let subarray_unsort = array.slice(subarray_begin, subarray_end + 1).to_owned(); let child_tx = tx.clone(); // you can't overload one sending channel let task = pool.task(TaskOpts::new(), proc() { //sets up a task for the handle let subarray = insertion_sort(subarray_unsort); //let subarray_refs = (sorted_sub[0], sorted_sub[sorted_sub.len() - 1]); child_tx.send(subarray); // sends the sorted sub array to rx }); handle.send(PinnedTask(task)); // the handle takes the task drop(handle); // the handle is destroyed after doing its job sorted_subarrays.push(rx.recv()); // get the sorted sub array i += 1; } pool.shutdown(); // the pool must shutdown after it has done its duty let sorted_array_wrapped = merge_wrapper(sorted_subarrays); array = sorted_array_wrapped[0]; // merge wrapper returns ~[~[T]] return array; } /// merge_wrapper will repeatedly merge arrays in an array until there /// is only one remaining element. Takes an array of arrays of type T which /// has the traits Clone and Ord, and returns a single array in an array. pub fn merge_wrapper<T: Ord + Clone + Send>(mut array_array: ~[~[T]]) -> ~[~[T]] { let array_n = array_array.len(); if array_n == 1 { return array_array.to_owned() } let config = PoolConfig::new(); let mut pool = SchedPool::new(config); let (tx, rx): (Sender<~[T]>, Receiver<~[T]>) = channel(); let mut i = 0; let mut j = 0; while i < array_n - 1 { let mut handle = pool.spawn_sched(); let sub_array1 = array_array[i].clone(); let sub_array2 = array_array[i + 1].clone(); let child_tx = tx.clone(); let task = pool.task(TaskOpts::new(), proc() { let merged_sub = merge(sub_array1.clone(), sub_array2.clone()); child_tx.send(merged_sub); }); handle.send(PinnedTask(task)); drop(handle); array_array[j] = rx.recv(); i += 2; j += 1; } pool.shutdown(); array_array = array_array.slice(0, j).to_owned(); return merge_wrapper(array_array); } /// Takes an array of type T which can be Cloned, and the number of subarrays /// for it to be broken into. Returns an array of tuples of uints for the array /// to be split into. pub fn split<T: Clone>(array: Vec<T>) -> ~[(uint, uint)] { let mut number_of_sub_arrays = 1; loop { if array.len() % (number_of_sub_arrays * 2)!= 0 { break } if number_of_sub_arrays > 256
number_of_sub_arrays *= 2; } let mut i = 0; let length = array.len(); let min_size = length / number_of_sub_arrays; let mut split_array: ~[(uint, uint)] = ~[(0, 0)]; //initializes array while i + min_size < length { let sub_array2 = i + min_size - 1; split_array.push((i, sub_array2)); i += min_size; } split_array.push((i, length - 1)); split_array.shift(); //removes first value that initialized split_array return split_array; } /// prints a help message pub fn print_usage(program: &str, _opts: &[OptGroup]) { println!("Usage: {} [options]", program); println!("-f,\t--file\t\t Input file"); } fn main() { let args = os::args(); let program = args[0].clone(); let opts = ~[ reqopt("f", "file", "input file name", "FILENAME"), optflag("h", "help", "print this help message") ]; let matches = match getopts(args.tail(), opts) { Ok(m) => { m } Err(f) => { fail!(f.to_err_msg()) } }; if matches.opt_present("h") { print_usage(program, opts); return; } let input_filename = match matches.opt_str("f") { Some(string) => string, _ => ~"Invalid" }; if input_filename == ~"Invalid" { println!("Invalid paramater."); return; } let array = number_array_from_file(input_filename, 0i); let sorted_array = merge_sort_parallel(array.clone()); for elem in sorted_array.iter() { println!("{}", elem); } println!("\n{}", sorted_array.len()); }
{ break }
conditional_block
tcpclientsrc.rs
// Copyright (C) 2018 Sebastian Dröge <[email protected]> // Copyright (C) 2018 LEE Dongjun <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // 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 // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin Street, Suite 500, // Boston, MA 02110-1335, USA. use glib::prelude::*; use gst::prelude::*; use std::io::Write; use std::sync::mpsc; use std::sync::{Arc, Mutex}; use std::{thread, time}; fn init() { use std::sync::Once; static INIT: Once = Once::new(); INIT.call_once(|| { gst::init().unwrap(); gstthreadshare::plugin_register_static().expect("gstthreadshare tcpclientsrc test"); }); } #[test] fn t
) { init(); let (listening_tx, listening_rx) = mpsc::channel(); let handler = thread::spawn(move || { use std::net; let listener = net::TcpListener::bind("0.0.0.0:5000").unwrap(); listening_tx.send(()).unwrap(); let stream = listener.incoming().next().unwrap(); let buffer = [0; 160]; let mut socket = stream.unwrap(); for _ in 0..3 { let _ = socket.write(&buffer); thread::sleep(time::Duration::from_millis(20)); } }); let pipeline = gst::Pipeline::new(None); let tcpclientsrc = gst::ElementFactory::make("ts-tcpclientsrc", None).unwrap(); let appsink = gst::ElementFactory::make("appsink", None).unwrap(); appsink.set_property("sync", &false).unwrap(); appsink.set_property("async", &false).unwrap(); pipeline.add_many(&[&tcpclientsrc, &appsink]).unwrap(); tcpclientsrc.link(&appsink).unwrap(); let caps = gst::Caps::new_simple("foo/bar", &[]); tcpclientsrc.set_property("caps", &caps).unwrap(); tcpclientsrc.set_property("port", &5000i32).unwrap(); appsink.set_property("emit-signals", &true).unwrap(); let samples = Arc::new(Mutex::new(Vec::new())); let appsink = appsink.dynamic_cast::<gst_app::AppSink>().unwrap(); let samples_clone = samples.clone(); appsink.connect_new_sample(move |appsink| { let sample = appsink .emit("pull-sample", &[]) .unwrap() .unwrap() .get::<gst::Sample>() .unwrap() .unwrap(); let mut samples = samples_clone.lock().unwrap(); samples.push(sample); Ok(gst::FlowSuccess::Ok) }); // Wait for the server to listen listening_rx.recv().unwrap(); pipeline.set_state(gst::State::Playing).unwrap(); let mut eos = false; let bus = pipeline.get_bus().unwrap(); while let Some(msg) = bus.timed_pop(5 * gst::SECOND) { use gst::MessageView; match msg.view() { MessageView::Eos(..) => { eos = true; break; } MessageView::Error(err) => panic!("{:?}", err), _ => (), } } assert!(eos); let samples = samples.lock().unwrap(); for sample in samples.iter() { assert_eq!(Some(caps.as_ref()), sample.get_caps()); } let total_received_size = samples.iter().fold(0, |acc, sample| { acc + sample.get_buffer().unwrap().get_size() }); assert_eq!(total_received_size, 3 * 160); pipeline.set_state(gst::State::Null).unwrap(); handler.join().unwrap(); }
est_push(
identifier_name
tcpclientsrc.rs
// Copyright (C) 2018 Sebastian Dröge <[email protected]> // Copyright (C) 2018 LEE Dongjun <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // 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 // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin Street, Suite 500, // Boston, MA 02110-1335, USA. use glib::prelude::*; use gst::prelude::*; use std::io::Write; use std::sync::mpsc; use std::sync::{Arc, Mutex}; use std::{thread, time}; fn init() { use std::sync::Once; static INIT: Once = Once::new(); INIT.call_once(|| { gst::init().unwrap(); gstthreadshare::plugin_register_static().expect("gstthreadshare tcpclientsrc test"); }); } #[test] fn test_push() { init();
let listener = net::TcpListener::bind("0.0.0.0:5000").unwrap(); listening_tx.send(()).unwrap(); let stream = listener.incoming().next().unwrap(); let buffer = [0; 160]; let mut socket = stream.unwrap(); for _ in 0..3 { let _ = socket.write(&buffer); thread::sleep(time::Duration::from_millis(20)); } }); let pipeline = gst::Pipeline::new(None); let tcpclientsrc = gst::ElementFactory::make("ts-tcpclientsrc", None).unwrap(); let appsink = gst::ElementFactory::make("appsink", None).unwrap(); appsink.set_property("sync", &false).unwrap(); appsink.set_property("async", &false).unwrap(); pipeline.add_many(&[&tcpclientsrc, &appsink]).unwrap(); tcpclientsrc.link(&appsink).unwrap(); let caps = gst::Caps::new_simple("foo/bar", &[]); tcpclientsrc.set_property("caps", &caps).unwrap(); tcpclientsrc.set_property("port", &5000i32).unwrap(); appsink.set_property("emit-signals", &true).unwrap(); let samples = Arc::new(Mutex::new(Vec::new())); let appsink = appsink.dynamic_cast::<gst_app::AppSink>().unwrap(); let samples_clone = samples.clone(); appsink.connect_new_sample(move |appsink| { let sample = appsink .emit("pull-sample", &[]) .unwrap() .unwrap() .get::<gst::Sample>() .unwrap() .unwrap(); let mut samples = samples_clone.lock().unwrap(); samples.push(sample); Ok(gst::FlowSuccess::Ok) }); // Wait for the server to listen listening_rx.recv().unwrap(); pipeline.set_state(gst::State::Playing).unwrap(); let mut eos = false; let bus = pipeline.get_bus().unwrap(); while let Some(msg) = bus.timed_pop(5 * gst::SECOND) { use gst::MessageView; match msg.view() { MessageView::Eos(..) => { eos = true; break; } MessageView::Error(err) => panic!("{:?}", err), _ => (), } } assert!(eos); let samples = samples.lock().unwrap(); for sample in samples.iter() { assert_eq!(Some(caps.as_ref()), sample.get_caps()); } let total_received_size = samples.iter().fold(0, |acc, sample| { acc + sample.get_buffer().unwrap().get_size() }); assert_eq!(total_received_size, 3 * 160); pipeline.set_state(gst::State::Null).unwrap(); handler.join().unwrap(); }
let (listening_tx, listening_rx) = mpsc::channel(); let handler = thread::spawn(move || { use std::net;
random_line_split
tcpclientsrc.rs
// Copyright (C) 2018 Sebastian Dröge <[email protected]> // Copyright (C) 2018 LEE Dongjun <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // 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 // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin Street, Suite 500, // Boston, MA 02110-1335, USA. use glib::prelude::*; use gst::prelude::*; use std::io::Write; use std::sync::mpsc; use std::sync::{Arc, Mutex}; use std::{thread, time}; fn init() { use std::sync::Once; static INIT: Once = Once::new(); INIT.call_once(|| { gst::init().unwrap(); gstthreadshare::plugin_register_static().expect("gstthreadshare tcpclientsrc test"); }); } #[test] fn test_push() {
let tcpclientsrc = gst::ElementFactory::make("ts-tcpclientsrc", None).unwrap(); let appsink = gst::ElementFactory::make("appsink", None).unwrap(); appsink.set_property("sync", &false).unwrap(); appsink.set_property("async", &false).unwrap(); pipeline.add_many(&[&tcpclientsrc, &appsink]).unwrap(); tcpclientsrc.link(&appsink).unwrap(); let caps = gst::Caps::new_simple("foo/bar", &[]); tcpclientsrc.set_property("caps", &caps).unwrap(); tcpclientsrc.set_property("port", &5000i32).unwrap(); appsink.set_property("emit-signals", &true).unwrap(); let samples = Arc::new(Mutex::new(Vec::new())); let appsink = appsink.dynamic_cast::<gst_app::AppSink>().unwrap(); let samples_clone = samples.clone(); appsink.connect_new_sample(move |appsink| { let sample = appsink .emit("pull-sample", &[]) .unwrap() .unwrap() .get::<gst::Sample>() .unwrap() .unwrap(); let mut samples = samples_clone.lock().unwrap(); samples.push(sample); Ok(gst::FlowSuccess::Ok) }); // Wait for the server to listen listening_rx.recv().unwrap(); pipeline.set_state(gst::State::Playing).unwrap(); let mut eos = false; let bus = pipeline.get_bus().unwrap(); while let Some(msg) = bus.timed_pop(5 * gst::SECOND) { use gst::MessageView; match msg.view() { MessageView::Eos(..) => { eos = true; break; } MessageView::Error(err) => panic!("{:?}", err), _ => (), } } assert!(eos); let samples = samples.lock().unwrap(); for sample in samples.iter() { assert_eq!(Some(caps.as_ref()), sample.get_caps()); } let total_received_size = samples.iter().fold(0, |acc, sample| { acc + sample.get_buffer().unwrap().get_size() }); assert_eq!(total_received_size, 3 * 160); pipeline.set_state(gst::State::Null).unwrap(); handler.join().unwrap(); }
init(); let (listening_tx, listening_rx) = mpsc::channel(); let handler = thread::spawn(move || { use std::net; let listener = net::TcpListener::bind("0.0.0.0:5000").unwrap(); listening_tx.send(()).unwrap(); let stream = listener.incoming().next().unwrap(); let buffer = [0; 160]; let mut socket = stream.unwrap(); for _ in 0..3 { let _ = socket.write(&buffer); thread::sleep(time::Duration::from_millis(20)); } }); let pipeline = gst::Pipeline::new(None);
identifier_body
console.rs
extern crate libc; use self::libc::c_void; use self::libc::{__errno_location, read, write, STDIN_FILENO, STDOUT_FILENO}; use containers::String; use io::{Disposable, IoError, Stream}; use memory::{Page, Region}; pub struct Console {} impl Console { pub fn write(_pr: &Region, s: String) { let _r = Region::create(_pr); unsafe { write( STDOUT_FILENO, s.to_c_string(_r.page) as *const c_void, s.get_length(), ); }
pub fn open_standard_output(_rp: *mut Page) -> *mut Stream { unsafe { (*_rp).allocate(ConsoleStream {}) } } } pub struct ConsoleStream {} impl Disposable for ConsoleStream { fn dispose(&self) {} } impl Stream for ConsoleStream { fn read_byte(&mut self) -> Result<i32, IoError> { let mut the_byte: u8 = 0; unsafe { let bytes_read = read(STDIN_FILENO, &mut the_byte as *mut u8 as *mut c_void, 1); if bytes_read == -1 { return Err(IoError { error_code: (*__errno_location() as i32), }); } if bytes_read == 0 { return Ok(-1); } } Ok(the_byte as i32) } fn write_byte(&mut self, the_byte: u8) -> Result<(), IoError> { unsafe { let bytes_written = write(STDOUT_FILENO, &the_byte as *const u8 as *const c_void, 1); if bytes_written == 1 { Ok(()) } else { Err(IoError { error_code: (*__errno_location() as i32), }) } } } } #[test] fn test_console() { use memory::Heap; use memory::StackBucket; let mut heap = Heap::create(); let root_stack_bucket = StackBucket::create(&mut heap); let r1 = Region::create_from_page(Page::get(root_stack_bucket as usize)); { let root_page = Page::get(root_stack_bucket as usize); Console::write(&r1, String::from_string_slice(root_page, "Scaly>")); // let stdout = Console::open_standard_output(root_page); // unsafe { // let byte1 = (*stdout).read_byte(); // let byte2 = (*stdout).read_byte(); // let byte3 = (*stdout).read_byte(); // (*stdout).write_byte(byte1); // (*stdout).write_byte(byte2); // (*stdout).write_byte(byte3); // } } }
}
random_line_split
console.rs
extern crate libc; use self::libc::c_void; use self::libc::{__errno_location, read, write, STDIN_FILENO, STDOUT_FILENO}; use containers::String; use io::{Disposable, IoError, Stream}; use memory::{Page, Region}; pub struct Console {} impl Console { pub fn write(_pr: &Region, s: String) { let _r = Region::create(_pr); unsafe { write( STDOUT_FILENO, s.to_c_string(_r.page) as *const c_void, s.get_length(), ); } } pub fn open_standard_output(_rp: *mut Page) -> *mut Stream { unsafe { (*_rp).allocate(ConsoleStream {}) } } } pub struct ConsoleStream {} impl Disposable for ConsoleStream { fn dispose(&self) {} } impl Stream for ConsoleStream { fn read_byte(&mut self) -> Result<i32, IoError> { let mut the_byte: u8 = 0; unsafe { let bytes_read = read(STDIN_FILENO, &mut the_byte as *mut u8 as *mut c_void, 1); if bytes_read == -1 { return Err(IoError { error_code: (*__errno_location() as i32), }); } if bytes_read == 0 { return Ok(-1); } } Ok(the_byte as i32) } fn write_byte(&mut self, the_byte: u8) -> Result<(), IoError>
} #[test] fn test_console() { use memory::Heap; use memory::StackBucket; let mut heap = Heap::create(); let root_stack_bucket = StackBucket::create(&mut heap); let r1 = Region::create_from_page(Page::get(root_stack_bucket as usize)); { let root_page = Page::get(root_stack_bucket as usize); Console::write(&r1, String::from_string_slice(root_page, "Scaly>")); // let stdout = Console::open_standard_output(root_page); // unsafe { // let byte1 = (*stdout).read_byte(); // let byte2 = (*stdout).read_byte(); // let byte3 = (*stdout).read_byte(); // (*stdout).write_byte(byte1); // (*stdout).write_byte(byte2); // (*stdout).write_byte(byte3); // } } }
{ unsafe { let bytes_written = write(STDOUT_FILENO, &the_byte as *const u8 as *const c_void, 1); if bytes_written == 1 { Ok(()) } else { Err(IoError { error_code: (*__errno_location() as i32), }) } } }
identifier_body
console.rs
extern crate libc; use self::libc::c_void; use self::libc::{__errno_location, read, write, STDIN_FILENO, STDOUT_FILENO}; use containers::String; use io::{Disposable, IoError, Stream}; use memory::{Page, Region}; pub struct Console {} impl Console { pub fn write(_pr: &Region, s: String) { let _r = Region::create(_pr); unsafe { write( STDOUT_FILENO, s.to_c_string(_r.page) as *const c_void, s.get_length(), ); } } pub fn open_standard_output(_rp: *mut Page) -> *mut Stream { unsafe { (*_rp).allocate(ConsoleStream {}) } } } pub struct
{} impl Disposable for ConsoleStream { fn dispose(&self) {} } impl Stream for ConsoleStream { fn read_byte(&mut self) -> Result<i32, IoError> { let mut the_byte: u8 = 0; unsafe { let bytes_read = read(STDIN_FILENO, &mut the_byte as *mut u8 as *mut c_void, 1); if bytes_read == -1 { return Err(IoError { error_code: (*__errno_location() as i32), }); } if bytes_read == 0 { return Ok(-1); } } Ok(the_byte as i32) } fn write_byte(&mut self, the_byte: u8) -> Result<(), IoError> { unsafe { let bytes_written = write(STDOUT_FILENO, &the_byte as *const u8 as *const c_void, 1); if bytes_written == 1 { Ok(()) } else { Err(IoError { error_code: (*__errno_location() as i32), }) } } } } #[test] fn test_console() { use memory::Heap; use memory::StackBucket; let mut heap = Heap::create(); let root_stack_bucket = StackBucket::create(&mut heap); let r1 = Region::create_from_page(Page::get(root_stack_bucket as usize)); { let root_page = Page::get(root_stack_bucket as usize); Console::write(&r1, String::from_string_slice(root_page, "Scaly>")); // let stdout = Console::open_standard_output(root_page); // unsafe { // let byte1 = (*stdout).read_byte(); // let byte2 = (*stdout).read_byte(); // let byte3 = (*stdout).read_byte(); // (*stdout).write_byte(byte1); // (*stdout).write_byte(byte2); // (*stdout).write_byte(byte3); // } } }
ConsoleStream
identifier_name
console.rs
extern crate libc; use self::libc::c_void; use self::libc::{__errno_location, read, write, STDIN_FILENO, STDOUT_FILENO}; use containers::String; use io::{Disposable, IoError, Stream}; use memory::{Page, Region}; pub struct Console {} impl Console { pub fn write(_pr: &Region, s: String) { let _r = Region::create(_pr); unsafe { write( STDOUT_FILENO, s.to_c_string(_r.page) as *const c_void, s.get_length(), ); } } pub fn open_standard_output(_rp: *mut Page) -> *mut Stream { unsafe { (*_rp).allocate(ConsoleStream {}) } } } pub struct ConsoleStream {} impl Disposable for ConsoleStream { fn dispose(&self) {} } impl Stream for ConsoleStream { fn read_byte(&mut self) -> Result<i32, IoError> { let mut the_byte: u8 = 0; unsafe { let bytes_read = read(STDIN_FILENO, &mut the_byte as *mut u8 as *mut c_void, 1); if bytes_read == -1
if bytes_read == 0 { return Ok(-1); } } Ok(the_byte as i32) } fn write_byte(&mut self, the_byte: u8) -> Result<(), IoError> { unsafe { let bytes_written = write(STDOUT_FILENO, &the_byte as *const u8 as *const c_void, 1); if bytes_written == 1 { Ok(()) } else { Err(IoError { error_code: (*__errno_location() as i32), }) } } } } #[test] fn test_console() { use memory::Heap; use memory::StackBucket; let mut heap = Heap::create(); let root_stack_bucket = StackBucket::create(&mut heap); let r1 = Region::create_from_page(Page::get(root_stack_bucket as usize)); { let root_page = Page::get(root_stack_bucket as usize); Console::write(&r1, String::from_string_slice(root_page, "Scaly>")); // let stdout = Console::open_standard_output(root_page); // unsafe { // let byte1 = (*stdout).read_byte(); // let byte2 = (*stdout).read_byte(); // let byte3 = (*stdout).read_byte(); // (*stdout).write_byte(byte1); // (*stdout).write_byte(byte2); // (*stdout).write_byte(byte3); // } } }
{ return Err(IoError { error_code: (*__errno_location() as i32), }); }
conditional_block
stream.rs
// // Test vectors adapted from libsodium // #![allow(non_upper_case_globals)] extern crate tweetnacl; const firstkey: [u8; 32] = [ 0x1b, 0x27, 0x55, 0x64, 0x73, 0xe9, 0x85, 0xd4, 0x62, 0xcd, 0x51, 0x19, 0x7a, 0x9a, 0x46, 0xc7, 0x60, 0x09, 0x54, 0x9e, 0xac, 0x64, 0x74, 0xf2, 0x06, 0xc4, 0xee, 0x08, 0x44, 0xf6, 0x83, 0x89 ]; const nonce: [u8; 24] = [ 0x69, 0x69, 0x6e, 0xe9, 0x55, 0xb6, 0x2b, 0x73, 0xcd, 0x62, 0xbd, 0xa8, 0x75, 0xfc, 0x73, 0xd6, 0x82, 0x19, 0xe0, 0x03, 0x6b, 0x7a, 0x0b, 0x37 ]; #[test] fn stream3() { let mut rs = [0u8; 32]; let test: [u8; 32] = [ 0xee, 0xa6, 0xa7, 0x25, 0x1c, 0x1e, 0x72, 0x91, 0x6d, 0x11, 0xc2, 0xcb, 0x21, 0x4d, 0x3c, 0x25, 0x25, 0x39, 0x12, 0x1d, 0x8e, 0x23, 0x4e, 0x65, 0x2d, 0x65, 0x1f, 0xa4, 0xc8, 0xcf, 0xf8, 0x80 ]; assert!(tweetnacl::crypto_stream(&mut rs, &nonce, &firstkey).is_ok()); assert_eq!(rs, test); } #[test] fn stream4()
0x32, 0xfc, 0x76, 0xce, 0x48, 0x33, 0x2e, 0xa7, 0x16, 0x4d, 0x96, 0xa4, 0x47, 0x6f, 0xb8, 0xc5, 0x31, 0xa1, 0x18, 0x6a, 0xc0, 0xdf, 0xc1, 0x7c, 0x98, 0xdc, 0xe8, 0x7b, 0x4d, 0xa7, 0xf0, 0x11, 0xec, 0x48, 0xc9, 0x72, 0x71, 0xd2, 0xc2, 0x0f, 0x9b, 0x92, 0x8f, 0xe2, 0x27, 0x0d, 0x6f, 0xb8, 0x63, 0xd5, 0x17, 0x38, 0xb4, 0x8e, 0xee, 0xe3, 0x14, 0xa7, 0xcc, 0x8a, 0xb9, 0x32, 0x16, 0x45, 0x48, 0xe5, 0x26, 0xae, 0x90, 0x22, 0x43, 0x68, 0x51, 0x7a, 0xcf, 0xea, 0xbd, 0x6b, 0xb3, 0x73, 0x2b, 0xc0, 0xe9, 0xda, 0x99, 0x83, 0x2b, 0x61, 0xca, 0x01, 0xb6, 0xde, 0x56, 0x24, 0x4a, 0x9e, 0x88, 0xd5, 0xf9, 0xb3, 0x79, 0x73, 0xf6, 0x22, 0xa4, 0x3d, 0x14, 0xa6, 0x59, 0x9b, 0x1f, 0x65, 0x4c, 0xb4, 0x5a, 0x74, 0xe3, 0x55, 0xa5 ]; assert!(tweetnacl::crypto_stream_xor(&mut c, Some(&m), &nonce, &firstkey).is_ok()); assert_eq!(&c[32..], &test[..]); }
{ let m: [u8; 163] = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xbe, 0x07, 0x5f, 0xc5, 0x3c, 0x81, 0xf2, 0xd5, 0xcf, 0x14, 0x13, 0x16, 0xeb, 0xeb, 0x0c, 0x7b, 0x52, 0x28, 0xc5, 0x2a, 0x4c, 0x62, 0xcb, 0xd4, 0x4b, 0x66, 0x84, 0x9b, 0x64, 0x24, 0x4f, 0xfc, 0xe5, 0xec, 0xba, 0xaf, 0x33, 0xbd, 0x75, 0x1a, 0x1a, 0xc7, 0x28, 0xd4, 0x5e, 0x6c, 0x61, 0x29, 0x6c, 0xdc, 0x3c, 0x01, 0x23, 0x35, 0x61, 0xf4, 0x1d, 0xb6, 0x6c, 0xce, 0x31, 0x4a, 0xdb, 0x31, 0x0e, 0x3b, 0xe8, 0x25, 0x0c, 0x46, 0xf0, 0x6d, 0xce, 0xea, 0x3a, 0x7f, 0xa1, 0x34, 0x80, 0x57, 0xe2, 0xf6, 0x55, 0x6a, 0xd6, 0xb1, 0x31, 0x8a, 0x02, 0x4a, 0x83, 0x8f, 0x21, 0xaf, 0x1f, 0xde, 0x04, 0x89, 0x77, 0xeb, 0x48, 0xf5, 0x9f, 0xfd, 0x49, 0x24, 0xca, 0x1c, 0x60, 0x90, 0x2e, 0x52, 0xf0, 0xa0, 0x89, 0xbc, 0x76, 0x89, 0x70, 0x40, 0xe0, 0x82, 0xf9, 0x37, 0x76, 0x38, 0x48, 0x64, 0x5e, 0x07, 0x05 ]; let mut c = [0u8; 163]; let test: [u8; 131] = [ 0x8e, 0x99, 0x3b, 0x9f, 0x48, 0x68, 0x12, 0x73, 0xc2, 0x96, 0x50, 0xba,
identifier_body
stream.rs
// // Test vectors adapted from libsodium // #![allow(non_upper_case_globals)] extern crate tweetnacl; const firstkey: [u8; 32] = [ 0x1b, 0x27, 0x55, 0x64, 0x73, 0xe9, 0x85, 0xd4, 0x62, 0xcd, 0x51, 0x19, 0x7a, 0x9a, 0x46, 0xc7, 0x60, 0x09, 0x54, 0x9e, 0xac, 0x64, 0x74, 0xf2, 0x06, 0xc4, 0xee, 0x08, 0x44, 0xf6, 0x83, 0x89 ]; const nonce: [u8; 24] = [ 0x69, 0x69, 0x6e, 0xe9, 0x55, 0xb6, 0x2b, 0x73, 0xcd, 0x62, 0xbd, 0xa8, 0x75, 0xfc, 0x73, 0xd6, 0x82, 0x19, 0xe0, 0x03, 0x6b, 0x7a, 0x0b, 0x37 ]; #[test] fn stream3() { let mut rs = [0u8; 32]; let test: [u8; 32] = [ 0xee, 0xa6, 0xa7, 0x25, 0x1c, 0x1e, 0x72, 0x91, 0x6d, 0x11, 0xc2, 0xcb, 0x21, 0x4d, 0x3c, 0x25, 0x25, 0x39, 0x12, 0x1d, 0x8e, 0x23, 0x4e, 0x65, 0x2d, 0x65, 0x1f, 0xa4, 0xc8, 0xcf, 0xf8, 0x80 ]; assert!(tweetnacl::crypto_stream(&mut rs, &nonce, &firstkey).is_ok()); assert_eq!(rs, test); } #[test] fn stream4() { let m: [u8; 163] = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xbe, 0x07, 0x5f, 0xc5, 0x3c, 0x81, 0xf2, 0xd5, 0xcf, 0x14, 0x13, 0x16, 0xeb, 0xeb, 0x0c, 0x7b, 0x52, 0x28, 0xc5, 0x2a, 0x4c, 0x62, 0xcb, 0xd4, 0x4b, 0x66, 0x84, 0x9b, 0x64, 0x24, 0x4f, 0xfc, 0xe5, 0xec, 0xba, 0xaf, 0x33, 0xbd, 0x75, 0x1a, 0x1a, 0xc7, 0x28, 0xd4, 0x5e, 0x6c, 0x61, 0x29, 0x6c, 0xdc, 0x3c, 0x01, 0x23, 0x35, 0x61, 0xf4, 0x1d, 0xb6, 0x6c, 0xce, 0x31, 0x4a, 0xdb, 0x31, 0x0e, 0x3b, 0xe8, 0x25, 0x0c, 0x46, 0xf0, 0x6d, 0xce, 0xea, 0x3a, 0x7f, 0xa1, 0x34, 0x80, 0x57, 0xe2, 0xf6, 0x55, 0x6a, 0xd6, 0xb1, 0x31, 0x8a, 0x02, 0x4a, 0x83, 0x8f, 0x21, 0xaf, 0x1f, 0xde, 0x04, 0x89, 0x77, 0xeb, 0x48, 0xf5, 0x9f, 0xfd, 0x49, 0x24, 0xca, 0x1c, 0x60, 0x90, 0x2e, 0x52, 0xf0, 0xa0, 0x89, 0xbc, 0x76, 0x89, 0x70, 0x40, 0xe0, 0x82, 0xf9, 0x37, 0x76, 0x38, 0x48, 0x64, 0x5e, 0x07, 0x05 ]; let mut c = [0u8; 163];
0x98, 0xdc, 0xe8, 0x7b, 0x4d, 0xa7, 0xf0, 0x11, 0xec, 0x48, 0xc9, 0x72, 0x71, 0xd2, 0xc2, 0x0f, 0x9b, 0x92, 0x8f, 0xe2, 0x27, 0x0d, 0x6f, 0xb8, 0x63, 0xd5, 0x17, 0x38, 0xb4, 0x8e, 0xee, 0xe3, 0x14, 0xa7, 0xcc, 0x8a, 0xb9, 0x32, 0x16, 0x45, 0x48, 0xe5, 0x26, 0xae, 0x90, 0x22, 0x43, 0x68, 0x51, 0x7a, 0xcf, 0xea, 0xbd, 0x6b, 0xb3, 0x73, 0x2b, 0xc0, 0xe9, 0xda, 0x99, 0x83, 0x2b, 0x61, 0xca, 0x01, 0xb6, 0xde, 0x56, 0x24, 0x4a, 0x9e, 0x88, 0xd5, 0xf9, 0xb3, 0x79, 0x73, 0xf6, 0x22, 0xa4, 0x3d, 0x14, 0xa6, 0x59, 0x9b, 0x1f, 0x65, 0x4c, 0xb4, 0x5a, 0x74, 0xe3, 0x55, 0xa5 ]; assert!(tweetnacl::crypto_stream_xor(&mut c, Some(&m), &nonce, &firstkey).is_ok()); assert_eq!(&c[32..], &test[..]); }
let test: [u8; 131] = [ 0x8e, 0x99, 0x3b, 0x9f, 0x48, 0x68, 0x12, 0x73, 0xc2, 0x96, 0x50, 0xba, 0x32, 0xfc, 0x76, 0xce, 0x48, 0x33, 0x2e, 0xa7, 0x16, 0x4d, 0x96, 0xa4, 0x47, 0x6f, 0xb8, 0xc5, 0x31, 0xa1, 0x18, 0x6a, 0xc0, 0xdf, 0xc1, 0x7c,
random_line_split
stream.rs
// // Test vectors adapted from libsodium // #![allow(non_upper_case_globals)] extern crate tweetnacl; const firstkey: [u8; 32] = [ 0x1b, 0x27, 0x55, 0x64, 0x73, 0xe9, 0x85, 0xd4, 0x62, 0xcd, 0x51, 0x19, 0x7a, 0x9a, 0x46, 0xc7, 0x60, 0x09, 0x54, 0x9e, 0xac, 0x64, 0x74, 0xf2, 0x06, 0xc4, 0xee, 0x08, 0x44, 0xf6, 0x83, 0x89 ]; const nonce: [u8; 24] = [ 0x69, 0x69, 0x6e, 0xe9, 0x55, 0xb6, 0x2b, 0x73, 0xcd, 0x62, 0xbd, 0xa8, 0x75, 0xfc, 0x73, 0xd6, 0x82, 0x19, 0xe0, 0x03, 0x6b, 0x7a, 0x0b, 0x37 ]; #[test] fn stream3() { let mut rs = [0u8; 32]; let test: [u8; 32] = [ 0xee, 0xa6, 0xa7, 0x25, 0x1c, 0x1e, 0x72, 0x91, 0x6d, 0x11, 0xc2, 0xcb, 0x21, 0x4d, 0x3c, 0x25, 0x25, 0x39, 0x12, 0x1d, 0x8e, 0x23, 0x4e, 0x65, 0x2d, 0x65, 0x1f, 0xa4, 0xc8, 0xcf, 0xf8, 0x80 ]; assert!(tweetnacl::crypto_stream(&mut rs, &nonce, &firstkey).is_ok()); assert_eq!(rs, test); } #[test] fn
() { let m: [u8; 163] = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xbe, 0x07, 0x5f, 0xc5, 0x3c, 0x81, 0xf2, 0xd5, 0xcf, 0x14, 0x13, 0x16, 0xeb, 0xeb, 0x0c, 0x7b, 0x52, 0x28, 0xc5, 0x2a, 0x4c, 0x62, 0xcb, 0xd4, 0x4b, 0x66, 0x84, 0x9b, 0x64, 0x24, 0x4f, 0xfc, 0xe5, 0xec, 0xba, 0xaf, 0x33, 0xbd, 0x75, 0x1a, 0x1a, 0xc7, 0x28, 0xd4, 0x5e, 0x6c, 0x61, 0x29, 0x6c, 0xdc, 0x3c, 0x01, 0x23, 0x35, 0x61, 0xf4, 0x1d, 0xb6, 0x6c, 0xce, 0x31, 0x4a, 0xdb, 0x31, 0x0e, 0x3b, 0xe8, 0x25, 0x0c, 0x46, 0xf0, 0x6d, 0xce, 0xea, 0x3a, 0x7f, 0xa1, 0x34, 0x80, 0x57, 0xe2, 0xf6, 0x55, 0x6a, 0xd6, 0xb1, 0x31, 0x8a, 0x02, 0x4a, 0x83, 0x8f, 0x21, 0xaf, 0x1f, 0xde, 0x04, 0x89, 0x77, 0xeb, 0x48, 0xf5, 0x9f, 0xfd, 0x49, 0x24, 0xca, 0x1c, 0x60, 0x90, 0x2e, 0x52, 0xf0, 0xa0, 0x89, 0xbc, 0x76, 0x89, 0x70, 0x40, 0xe0, 0x82, 0xf9, 0x37, 0x76, 0x38, 0x48, 0x64, 0x5e, 0x07, 0x05 ]; let mut c = [0u8; 163]; let test: [u8; 131] = [ 0x8e, 0x99, 0x3b, 0x9f, 0x48, 0x68, 0x12, 0x73, 0xc2, 0x96, 0x50, 0xba, 0x32, 0xfc, 0x76, 0xce, 0x48, 0x33, 0x2e, 0xa7, 0x16, 0x4d, 0x96, 0xa4, 0x47, 0x6f, 0xb8, 0xc5, 0x31, 0xa1, 0x18, 0x6a, 0xc0, 0xdf, 0xc1, 0x7c, 0x98, 0xdc, 0xe8, 0x7b, 0x4d, 0xa7, 0xf0, 0x11, 0xec, 0x48, 0xc9, 0x72, 0x71, 0xd2, 0xc2, 0x0f, 0x9b, 0x92, 0x8f, 0xe2, 0x27, 0x0d, 0x6f, 0xb8, 0x63, 0xd5, 0x17, 0x38, 0xb4, 0x8e, 0xee, 0xe3, 0x14, 0xa7, 0xcc, 0x8a, 0xb9, 0x32, 0x16, 0x45, 0x48, 0xe5, 0x26, 0xae, 0x90, 0x22, 0x43, 0x68, 0x51, 0x7a, 0xcf, 0xea, 0xbd, 0x6b, 0xb3, 0x73, 0x2b, 0xc0, 0xe9, 0xda, 0x99, 0x83, 0x2b, 0x61, 0xca, 0x01, 0xb6, 0xde, 0x56, 0x24, 0x4a, 0x9e, 0x88, 0xd5, 0xf9, 0xb3, 0x79, 0x73, 0xf6, 0x22, 0xa4, 0x3d, 0x14, 0xa6, 0x59, 0x9b, 0x1f, 0x65, 0x4c, 0xb4, 0x5a, 0x74, 0xe3, 0x55, 0xa5 ]; assert!(tweetnacl::crypto_stream_xor(&mut c, Some(&m), &nonce, &firstkey).is_ok()); assert_eq!(&c[32..], &test[..]); }
stream4
identifier_name
regions-lifetime-of-struct-or-enum-variant.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.
struct Test; enum MyEnum { Variant1 } fn structLifetime<'a>() -> &'a Test { let testValue = &Test; //~ ERROR borrowed value does not live long enough testValue } fn variantLifetime<'a>() -> &'a MyEnum { let testValue = &Variant1; //~ ERROR borrowed value does not live long enough testValue } fn main() {}
// This tests verifies that unary structs and enum variants // are treated as rvalues and their lifetime is not bounded to // the static scope.
random_line_split
regions-lifetime-of-struct-or-enum-variant.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. // This tests verifies that unary structs and enum variants // are treated as rvalues and their lifetime is not bounded to // the static scope. struct Test; enum
{ Variant1 } fn structLifetime<'a>() -> &'a Test { let testValue = &Test; //~ ERROR borrowed value does not live long enough testValue } fn variantLifetime<'a>() -> &'a MyEnum { let testValue = &Variant1; //~ ERROR borrowed value does not live long enough testValue } fn main() {}
MyEnum
identifier_name
regions-lifetime-of-struct-or-enum-variant.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. // This tests verifies that unary structs and enum variants // are treated as rvalues and their lifetime is not bounded to // the static scope. struct Test; enum MyEnum { Variant1 } fn structLifetime<'a>() -> &'a Test { let testValue = &Test; //~ ERROR borrowed value does not live long enough testValue } fn variantLifetime<'a>() -> &'a MyEnum { let testValue = &Variant1; //~ ERROR borrowed value does not live long enough testValue } fn main()
{}
identifier_body
minwindef.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> //! Basic Windows Type Definitions for minwin partition pub type ULONG = ::c_ulong; pub type PULONG = *mut ULONG; pub type USHORT = ::c_ushort; pub type PUSHORT = *mut USHORT; pub type UCHAR = ::c_uchar; pub type PUCHAR = *mut UCHAR; pub type PSZ = *mut ::c_char; pub const MAX_PATH: usize = 260; pub const FALSE: BOOL = 0; pub const TRUE: BOOL = 1; pub type DWORD = ::c_ulong; pub type BOOL = ::c_int; pub type BYTE = ::c_uchar; pub type WORD = ::c_ushort; pub type FLOAT = ::c_float; pub type PFLOAT = *mut FLOAT; pub type PBOOL = *mut BOOL; pub type LPBOOL = *mut BOOL; pub type PBYTE = *mut BYTE; pub type LPBYTE = *mut BYTE; pub type PINT = *mut ::c_int; pub type LPINT = *mut ::c_int; pub type PWORD = *mut WORD; pub type LPWORD = *mut WORD; pub type LPLONG = *mut ::c_long; pub type PDWORD = *mut DWORD; pub type LPDWORD = *mut DWORD; pub type LPVOID = *mut ::c_void; pub type LPCVOID = *const ::c_void; pub type INT = ::c_int; pub type UINT = ::c_uint; pub type PUINT = *mut ::c_uint; pub type WPARAM = ::UINT_PTR; pub type LPARAM = ::LONG_PTR; pub type LRESULT = ::LONG_PTR; pub fn MAKEWORD(a: BYTE, b: BYTE) -> WORD { (a as WORD) | ((b as WORD) << 8) } pub fn MAKELONG(a: WORD, b: WORD) -> ::LONG { ((a as DWORD) | ((b as DWORD) << 16)) as ::LONG } pub fn LOWORD(l: DWORD) -> WORD {
pub fn HIWORD(l: DWORD) -> WORD { ((l >> 16) & 0xffff) as WORD } pub fn LOBYTE(l: WORD) -> BYTE { (l & 0xff) as BYTE } pub fn HIBYTE(l: WORD) -> BYTE { ((l >> 8) & 0xff) as BYTE } pub type SPHANDLE = *mut ::HANDLE; pub type LPHANDLE = *mut ::HANDLE; pub type HGLOBAL = ::HANDLE; pub type HLOCAL = ::HANDLE; pub type GLOBALHANDLE = ::HANDLE; pub type LOCALHANDLE = ::HANDLE; /// Pointer to probably a function with unknown type signature. pub type FARPROC = *const ::c_void; /// Pointer to probably a function with unknown type signature. pub type NEARPROC = *const ::c_void; /// Pointer to probably a function with unknown type signature. pub type PROC = *const ::c_void; pub type ATOM = WORD; DECLARE_HANDLE!(HKEY, HKEY__); pub type PHKEY = *mut HKEY; DECLARE_HANDLE!(HMETAFILE, HMETAFILE__); DECLARE_HANDLE!(HINSTANCE, HINSTANCE__); pub type HMODULE = HINSTANCE; DECLARE_HANDLE!(HRGN, HRGN__); DECLARE_HANDLE!(HRSRC, HRSRC__); DECLARE_HANDLE!(HSPRITE, HSPRITE__); DECLARE_HANDLE!(HLSURF, HLSURF__); DECLARE_HANDLE!(HSTR, HSTR__); DECLARE_HANDLE!(HTASK, HTASK__); DECLARE_HANDLE!(HWINSTA, HWINSTA__); DECLARE_HANDLE!(HKL, HKL__); pub type HFILE = ::c_int; STRUCT!{struct FILETIME { dwLowDateTime: DWORD, dwHighDateTime: DWORD, }} pub type PFILETIME = *mut FILETIME; pub type LPFILETIME = *mut FILETIME;
(l & 0xffff) as WORD }
identifier_body
minwindef.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> //! Basic Windows Type Definitions for minwin partition pub type ULONG = ::c_ulong; pub type PULONG = *mut ULONG; pub type USHORT = ::c_ushort; pub type PUSHORT = *mut USHORT; pub type UCHAR = ::c_uchar; pub type PUCHAR = *mut UCHAR; pub type PSZ = *mut ::c_char; pub const MAX_PATH: usize = 260; pub const FALSE: BOOL = 0; pub const TRUE: BOOL = 1; pub type DWORD = ::c_ulong; pub type BOOL = ::c_int; pub type BYTE = ::c_uchar; pub type WORD = ::c_ushort; pub type FLOAT = ::c_float; pub type PFLOAT = *mut FLOAT; pub type PBOOL = *mut BOOL; pub type LPBOOL = *mut BOOL; pub type PBYTE = *mut BYTE; pub type LPBYTE = *mut BYTE; pub type PINT = *mut ::c_int; pub type LPINT = *mut ::c_int; pub type PWORD = *mut WORD; pub type LPWORD = *mut WORD; pub type LPLONG = *mut ::c_long; pub type PDWORD = *mut DWORD; pub type LPDWORD = *mut DWORD; pub type LPVOID = *mut ::c_void; pub type LPCVOID = *const ::c_void; pub type INT = ::c_int; pub type UINT = ::c_uint; pub type PUINT = *mut ::c_uint; pub type WPARAM = ::UINT_PTR; pub type LPARAM = ::LONG_PTR; pub type LRESULT = ::LONG_PTR; pub fn MAKEWORD(a: BYTE, b: BYTE) -> WORD { (a as WORD) | ((b as WORD) << 8) } pub fn MAKELONG(a: WORD, b: WORD) -> ::LONG { ((a as DWORD) | ((b as DWORD) << 16)) as ::LONG } pub fn L
l: DWORD) -> WORD { (l & 0xffff) as WORD } pub fn HIWORD(l: DWORD) -> WORD { ((l >> 16) & 0xffff) as WORD } pub fn LOBYTE(l: WORD) -> BYTE { (l & 0xff) as BYTE } pub fn HIBYTE(l: WORD) -> BYTE { ((l >> 8) & 0xff) as BYTE } pub type SPHANDLE = *mut ::HANDLE; pub type LPHANDLE = *mut ::HANDLE; pub type HGLOBAL = ::HANDLE; pub type HLOCAL = ::HANDLE; pub type GLOBALHANDLE = ::HANDLE; pub type LOCALHANDLE = ::HANDLE; /// Pointer to probably a function with unknown type signature. pub type FARPROC = *const ::c_void; /// Pointer to probably a function with unknown type signature. pub type NEARPROC = *const ::c_void; /// Pointer to probably a function with unknown type signature. pub type PROC = *const ::c_void; pub type ATOM = WORD; DECLARE_HANDLE!(HKEY, HKEY__); pub type PHKEY = *mut HKEY; DECLARE_HANDLE!(HMETAFILE, HMETAFILE__); DECLARE_HANDLE!(HINSTANCE, HINSTANCE__); pub type HMODULE = HINSTANCE; DECLARE_HANDLE!(HRGN, HRGN__); DECLARE_HANDLE!(HRSRC, HRSRC__); DECLARE_HANDLE!(HSPRITE, HSPRITE__); DECLARE_HANDLE!(HLSURF, HLSURF__); DECLARE_HANDLE!(HSTR, HSTR__); DECLARE_HANDLE!(HTASK, HTASK__); DECLARE_HANDLE!(HWINSTA, HWINSTA__); DECLARE_HANDLE!(HKL, HKL__); pub type HFILE = ::c_int; STRUCT!{struct FILETIME { dwLowDateTime: DWORD, dwHighDateTime: DWORD, }} pub type PFILETIME = *mut FILETIME; pub type LPFILETIME = *mut FILETIME;
OWORD(
identifier_name
minwindef.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> //! Basic Windows Type Definitions for minwin partition pub type ULONG = ::c_ulong; pub type PULONG = *mut ULONG; pub type USHORT = ::c_ushort; pub type PUSHORT = *mut USHORT; pub type UCHAR = ::c_uchar; pub type PUCHAR = *mut UCHAR; pub type PSZ = *mut ::c_char; pub const MAX_PATH: usize = 260; pub const FALSE: BOOL = 0; pub const TRUE: BOOL = 1; pub type DWORD = ::c_ulong; pub type BOOL = ::c_int; pub type BYTE = ::c_uchar; pub type WORD = ::c_ushort; pub type FLOAT = ::c_float; pub type PFLOAT = *mut FLOAT; pub type PBOOL = *mut BOOL; pub type LPBOOL = *mut BOOL; pub type PBYTE = *mut BYTE; pub type LPBYTE = *mut BYTE; pub type PINT = *mut ::c_int; pub type LPINT = *mut ::c_int; pub type PWORD = *mut WORD; pub type LPWORD = *mut WORD; pub type LPLONG = *mut ::c_long; pub type PDWORD = *mut DWORD; pub type LPDWORD = *mut DWORD; pub type LPVOID = *mut ::c_void; pub type LPCVOID = *const ::c_void; pub type INT = ::c_int; pub type UINT = ::c_uint; pub type PUINT = *mut ::c_uint; pub type WPARAM = ::UINT_PTR; pub type LPARAM = ::LONG_PTR; pub type LRESULT = ::LONG_PTR; pub fn MAKEWORD(a: BYTE, b: BYTE) -> WORD { (a as WORD) | ((b as WORD) << 8) } pub fn MAKELONG(a: WORD, b: WORD) -> ::LONG { ((a as DWORD) | ((b as DWORD) << 16)) as ::LONG } pub fn LOWORD(l: DWORD) -> WORD { (l & 0xffff) as WORD } pub fn HIWORD(l: DWORD) -> WORD { ((l >> 16) & 0xffff) as WORD } pub fn LOBYTE(l: WORD) -> BYTE { (l & 0xff) as BYTE } pub fn HIBYTE(l: WORD) -> BYTE { ((l >> 8) & 0xff) as BYTE } pub type SPHANDLE = *mut ::HANDLE; pub type LPHANDLE = *mut ::HANDLE; pub type HGLOBAL = ::HANDLE; pub type HLOCAL = ::HANDLE; pub type GLOBALHANDLE = ::HANDLE; pub type LOCALHANDLE = ::HANDLE; /// Pointer to probably a function with unknown type signature. pub type FARPROC = *const ::c_void; /// Pointer to probably a function with unknown type signature. pub type NEARPROC = *const ::c_void; /// Pointer to probably a function with unknown type signature. pub type PROC = *const ::c_void; pub type ATOM = WORD; DECLARE_HANDLE!(HKEY, HKEY__); pub type PHKEY = *mut HKEY;
DECLARE_HANDLE!(HSPRITE, HSPRITE__); DECLARE_HANDLE!(HLSURF, HLSURF__); DECLARE_HANDLE!(HSTR, HSTR__); DECLARE_HANDLE!(HTASK, HTASK__); DECLARE_HANDLE!(HWINSTA, HWINSTA__); DECLARE_HANDLE!(HKL, HKL__); pub type HFILE = ::c_int; STRUCT!{struct FILETIME { dwLowDateTime: DWORD, dwHighDateTime: DWORD, }} pub type PFILETIME = *mut FILETIME; pub type LPFILETIME = *mut FILETIME;
DECLARE_HANDLE!(HMETAFILE, HMETAFILE__); DECLARE_HANDLE!(HINSTANCE, HINSTANCE__); pub type HMODULE = HINSTANCE; DECLARE_HANDLE!(HRGN, HRGN__); DECLARE_HANDLE!(HRSRC, HRSRC__);
random_line_split
kahansum.rs
// Implements http://rosettacode.org/wiki/Kahan_summation #![feature(permutations)] extern crate num;
fn find_max(lst: &[f32]) -> Option<f32> { if lst.is_empty() { return None } let max = lst.iter().fold(f32::NEG_INFINITY, |a, &b| Float::max(a, b)); Some(max) } fn with_bits(val: f32, digits: usize) -> f32 { let num = format!("{:.*}", digits, val); num.parse::<f32>().unwrap() } fn kahan_sum(lst: &[f32]) -> Option<f32> { let mut sum = 0.0f32; let mut c = 0.0f32; for i in lst { let y = *i - c; let t = sum + y; c = (t - sum) - y; sum = t; } Some(with_bits(sum, 1)) } fn all_sums(vec: &[f32]) -> Vec<f32> { let mut res = Vec::new(); let mut perms = vec.permutations(); loop { let v = perms.next(); match v { Some(_v) => { let mut sum = 0.0f32; for e in &_v { sum += with_bits(*e, 1); } res.push(with_bits(sum, 1)); } None => break } } res } #[cfg(not(test))] fn main() { let v = [10000.0f32, 3.14159, 2.71828]; let sums = all_sums(&v); let res = kahan_sum(&v).unwrap(); let max = find_max(&sums[..]).unwrap(); println!("max: {} res: {}", max, res); } #[test] fn test_kahansum() { let v = [10000.0f32, 3.14159, 2.71828]; let sums = all_sums(&v); let res = kahan_sum(&v).unwrap(); let max = find_max(&sums[..]).unwrap(); assert!(max < res); } #[test] fn test_withbits() { let v = 3.123345f32; let res = with_bits(v, 3); assert!(res == 3.123f32); }
use std::f32; use num::Float;
random_line_split
kahansum.rs
// Implements http://rosettacode.org/wiki/Kahan_summation #![feature(permutations)] extern crate num; use std::f32; use num::Float; fn find_max(lst: &[f32]) -> Option<f32> { if lst.is_empty() { return None } let max = lst.iter().fold(f32::NEG_INFINITY, |a, &b| Float::max(a, b)); Some(max) } fn with_bits(val: f32, digits: usize) -> f32 { let num = format!("{:.*}", digits, val); num.parse::<f32>().unwrap() } fn kahan_sum(lst: &[f32]) -> Option<f32> { let mut sum = 0.0f32; let mut c = 0.0f32; for i in lst { let y = *i - c; let t = sum + y; c = (t - sum) - y; sum = t; } Some(with_bits(sum, 1)) } fn
(vec: &[f32]) -> Vec<f32> { let mut res = Vec::new(); let mut perms = vec.permutations(); loop { let v = perms.next(); match v { Some(_v) => { let mut sum = 0.0f32; for e in &_v { sum += with_bits(*e, 1); } res.push(with_bits(sum, 1)); } None => break } } res } #[cfg(not(test))] fn main() { let v = [10000.0f32, 3.14159, 2.71828]; let sums = all_sums(&v); let res = kahan_sum(&v).unwrap(); let max = find_max(&sums[..]).unwrap(); println!("max: {} res: {}", max, res); } #[test] fn test_kahansum() { let v = [10000.0f32, 3.14159, 2.71828]; let sums = all_sums(&v); let res = kahan_sum(&v).unwrap(); let max = find_max(&sums[..]).unwrap(); assert!(max < res); } #[test] fn test_withbits() { let v = 3.123345f32; let res = with_bits(v, 3); assert!(res == 3.123f32); }
all_sums
identifier_name
kahansum.rs
// Implements http://rosettacode.org/wiki/Kahan_summation #![feature(permutations)] extern crate num; use std::f32; use num::Float; fn find_max(lst: &[f32]) -> Option<f32> { if lst.is_empty() { return None } let max = lst.iter().fold(f32::NEG_INFINITY, |a, &b| Float::max(a, b)); Some(max) } fn with_bits(val: f32, digits: usize) -> f32 { let num = format!("{:.*}", digits, val); num.parse::<f32>().unwrap() } fn kahan_sum(lst: &[f32]) -> Option<f32> { let mut sum = 0.0f32; let mut c = 0.0f32; for i in lst { let y = *i - c; let t = sum + y; c = (t - sum) - y; sum = t; } Some(with_bits(sum, 1)) } fn all_sums(vec: &[f32]) -> Vec<f32> { let mut res = Vec::new(); let mut perms = vec.permutations(); loop { let v = perms.next(); match v { Some(_v) => { let mut sum = 0.0f32; for e in &_v { sum += with_bits(*e, 1); } res.push(with_bits(sum, 1)); } None => break } } res } #[cfg(not(test))] fn main()
#[test] fn test_kahansum() { let v = [10000.0f32, 3.14159, 2.71828]; let sums = all_sums(&v); let res = kahan_sum(&v).unwrap(); let max = find_max(&sums[..]).unwrap(); assert!(max < res); } #[test] fn test_withbits() { let v = 3.123345f32; let res = with_bits(v, 3); assert!(res == 3.123f32); }
{ let v = [10000.0f32, 3.14159, 2.71828]; let sums = all_sums(&v); let res = kahan_sum(&v).unwrap(); let max = find_max(&sums[..]).unwrap(); println!("max: {} res: {}", max, res); }
identifier_body
cache.rs
// Copyright 2015, 2016 Ethcore (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/>. use std::cmp::max; const MIN_BC_CACHE_MB: u32 = 4; const MIN_DB_CACHE_MB: u32 = 2; const MIN_BLOCK_QUEUE_SIZE_LIMIT_MB: u32 = 16; const DEFAULT_BLOCK_QUEUE_SIZE_LIMIT_MB: u32 = 50; const DEFAULT_TRACE_CACHE_SIZE: u32 = 20; const DEFAULT_STATE_CACHE_SIZE: u32 = 25; /// Configuration for application cache sizes. /// All values are represented in MB. #[derive(Debug, PartialEq)] pub struct
{ /// Size of rocksDB cache. Almost all goes to the state column. db: u32, /// Size of blockchain cache. blockchain: u32, /// Size of transaction queue cache. queue: u32, /// Size of traces cache. traces: u32, /// Size of the state cache. state: u32, } impl Default for CacheConfig { fn default() -> Self { CacheConfig::new(64, 8, DEFAULT_BLOCK_QUEUE_SIZE_LIMIT_MB, DEFAULT_STATE_CACHE_SIZE) } } impl CacheConfig { /// Creates new cache config with cumulative size equal `total`. pub fn new_with_total_cache_size(total: u32) -> Self { CacheConfig { db: total * 7 / 10, blockchain: total / 10, queue: DEFAULT_BLOCK_QUEUE_SIZE_LIMIT_MB, traces: DEFAULT_TRACE_CACHE_SIZE, state: total * 2 / 10, } } /// Creates new cache config with gitven details. pub fn new(db: u32, blockchain: u32, queue: u32, state: u32) -> Self { CacheConfig { db: db, blockchain: blockchain, queue: queue, traces: DEFAULT_TRACE_CACHE_SIZE, state: state, } } /// Size of db cache for blockchain. pub fn db_blockchain_cache_size(&self) -> u32 { max(MIN_DB_CACHE_MB, self.db / 4) } /// Size of db cache for state. pub fn db_state_cache_size(&self) -> u32 { max(MIN_DB_CACHE_MB, self.db * 3 / 4) } /// Size of block queue size limit pub fn queue(&self) -> u32 { max(self.queue, MIN_BLOCK_QUEUE_SIZE_LIMIT_MB) } /// Size of the blockchain cache. pub fn blockchain(&self) -> u32 { max(self.blockchain, MIN_BC_CACHE_MB) } /// Size of the traces cache. pub fn traces(&self) -> u32 { self.traces } /// Size of the state cache. pub fn state(&self) -> u32 { self.state * 3 / 4 } /// Size of the jump-tables cache. pub fn jump_tables(&self) -> u32 { self.state / 4 } } #[cfg(test)] mod tests { use super::CacheConfig; #[test] fn test_cache_config_constructor() { let config = CacheConfig::new_with_total_cache_size(200); assert_eq!(config.db, 140); assert_eq!(config.blockchain(), 20); assert_eq!(config.queue(), 50); assert_eq!(config.state(), 30); assert_eq!(config.jump_tables(), 10); } #[test] fn test_cache_config_db_cache_sizes() { let config = CacheConfig::new_with_total_cache_size(400); assert_eq!(config.db, 280); assert_eq!(config.db_blockchain_cache_size(), 70); assert_eq!(config.db_state_cache_size(), 210); } #[test] fn test_cache_config_default() { assert_eq!(CacheConfig::default(), CacheConfig::new(64, 8, super::DEFAULT_BLOCK_QUEUE_SIZE_LIMIT_MB, super::DEFAULT_STATE_CACHE_SIZE)); } }
CacheConfig
identifier_name
cache.rs
// Copyright 2015, 2016 Ethcore (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
// You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::cmp::max; const MIN_BC_CACHE_MB: u32 = 4; const MIN_DB_CACHE_MB: u32 = 2; const MIN_BLOCK_QUEUE_SIZE_LIMIT_MB: u32 = 16; const DEFAULT_BLOCK_QUEUE_SIZE_LIMIT_MB: u32 = 50; const DEFAULT_TRACE_CACHE_SIZE: u32 = 20; const DEFAULT_STATE_CACHE_SIZE: u32 = 25; /// Configuration for application cache sizes. /// All values are represented in MB. #[derive(Debug, PartialEq)] pub struct CacheConfig { /// Size of rocksDB cache. Almost all goes to the state column. db: u32, /// Size of blockchain cache. blockchain: u32, /// Size of transaction queue cache. queue: u32, /// Size of traces cache. traces: u32, /// Size of the state cache. state: u32, } impl Default for CacheConfig { fn default() -> Self { CacheConfig::new(64, 8, DEFAULT_BLOCK_QUEUE_SIZE_LIMIT_MB, DEFAULT_STATE_CACHE_SIZE) } } impl CacheConfig { /// Creates new cache config with cumulative size equal `total`. pub fn new_with_total_cache_size(total: u32) -> Self { CacheConfig { db: total * 7 / 10, blockchain: total / 10, queue: DEFAULT_BLOCK_QUEUE_SIZE_LIMIT_MB, traces: DEFAULT_TRACE_CACHE_SIZE, state: total * 2 / 10, } } /// Creates new cache config with gitven details. pub fn new(db: u32, blockchain: u32, queue: u32, state: u32) -> Self { CacheConfig { db: db, blockchain: blockchain, queue: queue, traces: DEFAULT_TRACE_CACHE_SIZE, state: state, } } /// Size of db cache for blockchain. pub fn db_blockchain_cache_size(&self) -> u32 { max(MIN_DB_CACHE_MB, self.db / 4) } /// Size of db cache for state. pub fn db_state_cache_size(&self) -> u32 { max(MIN_DB_CACHE_MB, self.db * 3 / 4) } /// Size of block queue size limit pub fn queue(&self) -> u32 { max(self.queue, MIN_BLOCK_QUEUE_SIZE_LIMIT_MB) } /// Size of the blockchain cache. pub fn blockchain(&self) -> u32 { max(self.blockchain, MIN_BC_CACHE_MB) } /// Size of the traces cache. pub fn traces(&self) -> u32 { self.traces } /// Size of the state cache. pub fn state(&self) -> u32 { self.state * 3 / 4 } /// Size of the jump-tables cache. pub fn jump_tables(&self) -> u32 { self.state / 4 } } #[cfg(test)] mod tests { use super::CacheConfig; #[test] fn test_cache_config_constructor() { let config = CacheConfig::new_with_total_cache_size(200); assert_eq!(config.db, 140); assert_eq!(config.blockchain(), 20); assert_eq!(config.queue(), 50); assert_eq!(config.state(), 30); assert_eq!(config.jump_tables(), 10); } #[test] fn test_cache_config_db_cache_sizes() { let config = CacheConfig::new_with_total_cache_size(400); assert_eq!(config.db, 280); assert_eq!(config.db_blockchain_cache_size(), 70); assert_eq!(config.db_state_cache_size(), 210); } #[test] fn test_cache_config_default() { assert_eq!(CacheConfig::default(), CacheConfig::new(64, 8, super::DEFAULT_BLOCK_QUEUE_SIZE_LIMIT_MB, super::DEFAULT_STATE_CACHE_SIZE)); } }
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details.
random_line_split
svgelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::inheritance::Castable; use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use style::element_state::ElementState; #[dom_struct] pub struct
{ element: Element, } impl SVGElement { pub fn new_inherited_with_state( state: ElementState, tag_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> SVGElement { SVGElement { element: Element::new_inherited_with_state(state, tag_name, ns!(svg), prefix, document), } } } impl VirtualMethods for SVGElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<Element>() as &dyn VirtualMethods) } }
SVGElement
identifier_name
svgelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::inheritance::Castable; use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix};
pub struct SVGElement { element: Element, } impl SVGElement { pub fn new_inherited_with_state( state: ElementState, tag_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> SVGElement { SVGElement { element: Element::new_inherited_with_state(state, tag_name, ns!(svg), prefix, document), } } } impl VirtualMethods for SVGElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<Element>() as &dyn VirtualMethods) } }
use style::element_state::ElementState; #[dom_struct]
random_line_split
svgelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::inheritance::Castable; use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use style::element_state::ElementState; #[dom_struct] pub struct SVGElement { element: Element, } impl SVGElement { pub fn new_inherited_with_state( state: ElementState, tag_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> SVGElement
} impl VirtualMethods for SVGElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<Element>() as &dyn VirtualMethods) } }
{ SVGElement { element: Element::new_inherited_with_state(state, tag_name, ns!(svg), prefix, document), } }
identifier_body
preview.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use crate::{ card::CardQueue, config::SchedulerVersion, prelude::*, scheduler::states::{CardState, IntervalKind, PreviewState}, }; use super::{CardStateUpdater, RevlogEntryPartial}; impl CardStateUpdater { // fixme: check learning card moved into preview // restores correctly in both learn and day-learn case pub(super) fn apply_preview_state( &mut self, current: CardState, next: PreviewState, ) -> Result<Option<RevlogEntryPartial>> { if next.finished { self.card .remove_from_filtered_deck_restoring_queue(SchedulerVersion::V2); return Ok(None); } self.card.queue = CardQueue::PreviewRepeat; let interval = next.interval_kind(); match interval { IntervalKind::InSecs(secs) => { self.card.due = self.now.0 as i32 + secs as i32; } IntervalKind::InDays(_days) =>
} Ok(RevlogEntryPartial::maybe_new( current, next.into(), 0.0, self.secs_until_rollover(), )) } } #[cfg(test)] mod test { use crate::collection::open_test_collection; use super::*; use crate::{ card::CardType, scheduler::{ answering::{CardAnswer, Rating}, states::{CardState, FilteredState}, }, timestamp::TimestampMillis, }; #[test] fn preview() -> Result<()> { let mut col = open_test_collection(); let mut c = Card { deck_id: DeckID(1), ctype: CardType::Learn, queue: CardQueue::DayLearn, remaining_steps: 2, due: 123, ..Default::default() }; col.add_card(&mut c)?; // pull the card into a preview deck let mut filtered_deck = Deck::new_filtered(); filtered_deck.filtered_mut()?.reschedule = false; col.add_or_update_deck(&mut filtered_deck)?; assert_eq!(col.rebuild_filtered_deck(filtered_deck.id)?, 1); let next = col.get_next_card_states(c.id)?; assert!(matches!( next.current, CardState::Filtered(FilteredState::Preview(_)) )); // the exit state should have a 0 second interval, which will show up as (end) assert!(matches!( next.easy, CardState::Filtered(FilteredState::Preview(PreviewState { scheduled_secs: 0, finished: true })) )); // use Again on the preview col.answer_card(&CardAnswer { card_id: c.id, current_state: next.current, new_state: next.again, rating: Rating::Again, answered_at: TimestampMillis::now(), milliseconds_taken: 0, })?; c = col.storage.get_card(c.id)?.unwrap(); assert_eq!(c.queue, CardQueue::PreviewRepeat); // hard let next = col.get_next_card_states(c.id)?; col.answer_card(&CardAnswer { card_id: c.id, current_state: next.current, new_state: next.hard, rating: Rating::Hard, answered_at: TimestampMillis::now(), milliseconds_taken: 0, })?; c = col.storage.get_card(c.id)?.unwrap(); assert_eq!(c.queue, CardQueue::PreviewRepeat); // good let next = col.get_next_card_states(c.id)?; col.answer_card(&CardAnswer { card_id: c.id, current_state: next.current, new_state: next.good, rating: Rating::Good, answered_at: TimestampMillis::now(), milliseconds_taken: 0, })?; c = col.storage.get_card(c.id)?.unwrap(); assert_eq!(c.queue, CardQueue::PreviewRepeat); // and then it should return to its old state once easy selected let next = col.get_next_card_states(c.id)?; col.answer_card(&CardAnswer { card_id: c.id, current_state: next.current, new_state: next.easy, rating: Rating::Easy, answered_at: TimestampMillis::now(), milliseconds_taken: 0, })?; c = col.storage.get_card(c.id)?.unwrap(); assert_eq!(c.queue, CardQueue::DayLearn); assert_eq!(c.due, 123); Ok(()) } }
{ // unsupported }
conditional_block
preview.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use crate::{ card::CardQueue, config::SchedulerVersion, prelude::*, scheduler::states::{CardState, IntervalKind, PreviewState}, }; use super::{CardStateUpdater, RevlogEntryPartial}; impl CardStateUpdater { // fixme: check learning card moved into preview // restores correctly in both learn and day-learn case pub(super) fn apply_preview_state( &mut self, current: CardState, next: PreviewState, ) -> Result<Option<RevlogEntryPartial>> { if next.finished { self.card .remove_from_filtered_deck_restoring_queue(SchedulerVersion::V2); return Ok(None); } self.card.queue = CardQueue::PreviewRepeat; let interval = next.interval_kind(); match interval { IntervalKind::InSecs(secs) => { self.card.due = self.now.0 as i32 + secs as i32; } IntervalKind::InDays(_days) => { // unsupported } } Ok(RevlogEntryPartial::maybe_new( current, next.into(), 0.0, self.secs_until_rollover(), )) } } #[cfg(test)] mod test { use crate::collection::open_test_collection; use super::*; use crate::{ card::CardType, scheduler::{ answering::{CardAnswer, Rating}, states::{CardState, FilteredState}, }, timestamp::TimestampMillis, }; #[test] fn preview() -> Result<()>
next.current, CardState::Filtered(FilteredState::Preview(_)) )); // the exit state should have a 0 second interval, which will show up as (end) assert!(matches!( next.easy, CardState::Filtered(FilteredState::Preview(PreviewState { scheduled_secs: 0, finished: true })) )); // use Again on the preview col.answer_card(&CardAnswer { card_id: c.id, current_state: next.current, new_state: next.again, rating: Rating::Again, answered_at: TimestampMillis::now(), milliseconds_taken: 0, })?; c = col.storage.get_card(c.id)?.unwrap(); assert_eq!(c.queue, CardQueue::PreviewRepeat); // hard let next = col.get_next_card_states(c.id)?; col.answer_card(&CardAnswer { card_id: c.id, current_state: next.current, new_state: next.hard, rating: Rating::Hard, answered_at: TimestampMillis::now(), milliseconds_taken: 0, })?; c = col.storage.get_card(c.id)?.unwrap(); assert_eq!(c.queue, CardQueue::PreviewRepeat); // good let next = col.get_next_card_states(c.id)?; col.answer_card(&CardAnswer { card_id: c.id, current_state: next.current, new_state: next.good, rating: Rating::Good, answered_at: TimestampMillis::now(), milliseconds_taken: 0, })?; c = col.storage.get_card(c.id)?.unwrap(); assert_eq!(c.queue, CardQueue::PreviewRepeat); // and then it should return to its old state once easy selected let next = col.get_next_card_states(c.id)?; col.answer_card(&CardAnswer { card_id: c.id, current_state: next.current, new_state: next.easy, rating: Rating::Easy, answered_at: TimestampMillis::now(), milliseconds_taken: 0, })?; c = col.storage.get_card(c.id)?.unwrap(); assert_eq!(c.queue, CardQueue::DayLearn); assert_eq!(c.due, 123); Ok(()) } }
{ let mut col = open_test_collection(); let mut c = Card { deck_id: DeckID(1), ctype: CardType::Learn, queue: CardQueue::DayLearn, remaining_steps: 2, due: 123, ..Default::default() }; col.add_card(&mut c)?; // pull the card into a preview deck let mut filtered_deck = Deck::new_filtered(); filtered_deck.filtered_mut()?.reschedule = false; col.add_or_update_deck(&mut filtered_deck)?; assert_eq!(col.rebuild_filtered_deck(filtered_deck.id)?, 1); let next = col.get_next_card_states(c.id)?; assert!(matches!(
identifier_body
preview.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use crate::{ card::CardQueue, config::SchedulerVersion, prelude::*, scheduler::states::{CardState, IntervalKind, PreviewState}, }; use super::{CardStateUpdater, RevlogEntryPartial}; impl CardStateUpdater { // fixme: check learning card moved into preview // restores correctly in both learn and day-learn case pub(super) fn apply_preview_state( &mut self, current: CardState, next: PreviewState, ) -> Result<Option<RevlogEntryPartial>> { if next.finished { self.card .remove_from_filtered_deck_restoring_queue(SchedulerVersion::V2); return Ok(None); } self.card.queue = CardQueue::PreviewRepeat; let interval = next.interval_kind(); match interval { IntervalKind::InSecs(secs) => { self.card.due = self.now.0 as i32 + secs as i32; } IntervalKind::InDays(_days) => { // unsupported } } Ok(RevlogEntryPartial::maybe_new( current, next.into(), 0.0, self.secs_until_rollover(), )) } } #[cfg(test)] mod test { use crate::collection::open_test_collection; use super::*; use crate::{ card::CardType, scheduler::{ answering::{CardAnswer, Rating}, states::{CardState, FilteredState}, }, timestamp::TimestampMillis, }; #[test] fn preview() -> Result<()> { let mut col = open_test_collection(); let mut c = Card { deck_id: DeckID(1), ctype: CardType::Learn, queue: CardQueue::DayLearn, remaining_steps: 2, due: 123, ..Default::default() }; col.add_card(&mut c)?;
assert_eq!(col.rebuild_filtered_deck(filtered_deck.id)?, 1); let next = col.get_next_card_states(c.id)?; assert!(matches!( next.current, CardState::Filtered(FilteredState::Preview(_)) )); // the exit state should have a 0 second interval, which will show up as (end) assert!(matches!( next.easy, CardState::Filtered(FilteredState::Preview(PreviewState { scheduled_secs: 0, finished: true })) )); // use Again on the preview col.answer_card(&CardAnswer { card_id: c.id, current_state: next.current, new_state: next.again, rating: Rating::Again, answered_at: TimestampMillis::now(), milliseconds_taken: 0, })?; c = col.storage.get_card(c.id)?.unwrap(); assert_eq!(c.queue, CardQueue::PreviewRepeat); // hard let next = col.get_next_card_states(c.id)?; col.answer_card(&CardAnswer { card_id: c.id, current_state: next.current, new_state: next.hard, rating: Rating::Hard, answered_at: TimestampMillis::now(), milliseconds_taken: 0, })?; c = col.storage.get_card(c.id)?.unwrap(); assert_eq!(c.queue, CardQueue::PreviewRepeat); // good let next = col.get_next_card_states(c.id)?; col.answer_card(&CardAnswer { card_id: c.id, current_state: next.current, new_state: next.good, rating: Rating::Good, answered_at: TimestampMillis::now(), milliseconds_taken: 0, })?; c = col.storage.get_card(c.id)?.unwrap(); assert_eq!(c.queue, CardQueue::PreviewRepeat); // and then it should return to its old state once easy selected let next = col.get_next_card_states(c.id)?; col.answer_card(&CardAnswer { card_id: c.id, current_state: next.current, new_state: next.easy, rating: Rating::Easy, answered_at: TimestampMillis::now(), milliseconds_taken: 0, })?; c = col.storage.get_card(c.id)?.unwrap(); assert_eq!(c.queue, CardQueue::DayLearn); assert_eq!(c.due, 123); Ok(()) } }
// pull the card into a preview deck let mut filtered_deck = Deck::new_filtered(); filtered_deck.filtered_mut()?.reschedule = false; col.add_or_update_deck(&mut filtered_deck)?;
random_line_split
preview.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use crate::{ card::CardQueue, config::SchedulerVersion, prelude::*, scheduler::states::{CardState, IntervalKind, PreviewState}, }; use super::{CardStateUpdater, RevlogEntryPartial}; impl CardStateUpdater { // fixme: check learning card moved into preview // restores correctly in both learn and day-learn case pub(super) fn
( &mut self, current: CardState, next: PreviewState, ) -> Result<Option<RevlogEntryPartial>> { if next.finished { self.card .remove_from_filtered_deck_restoring_queue(SchedulerVersion::V2); return Ok(None); } self.card.queue = CardQueue::PreviewRepeat; let interval = next.interval_kind(); match interval { IntervalKind::InSecs(secs) => { self.card.due = self.now.0 as i32 + secs as i32; } IntervalKind::InDays(_days) => { // unsupported } } Ok(RevlogEntryPartial::maybe_new( current, next.into(), 0.0, self.secs_until_rollover(), )) } } #[cfg(test)] mod test { use crate::collection::open_test_collection; use super::*; use crate::{ card::CardType, scheduler::{ answering::{CardAnswer, Rating}, states::{CardState, FilteredState}, }, timestamp::TimestampMillis, }; #[test] fn preview() -> Result<()> { let mut col = open_test_collection(); let mut c = Card { deck_id: DeckID(1), ctype: CardType::Learn, queue: CardQueue::DayLearn, remaining_steps: 2, due: 123, ..Default::default() }; col.add_card(&mut c)?; // pull the card into a preview deck let mut filtered_deck = Deck::new_filtered(); filtered_deck.filtered_mut()?.reschedule = false; col.add_or_update_deck(&mut filtered_deck)?; assert_eq!(col.rebuild_filtered_deck(filtered_deck.id)?, 1); let next = col.get_next_card_states(c.id)?; assert!(matches!( next.current, CardState::Filtered(FilteredState::Preview(_)) )); // the exit state should have a 0 second interval, which will show up as (end) assert!(matches!( next.easy, CardState::Filtered(FilteredState::Preview(PreviewState { scheduled_secs: 0, finished: true })) )); // use Again on the preview col.answer_card(&CardAnswer { card_id: c.id, current_state: next.current, new_state: next.again, rating: Rating::Again, answered_at: TimestampMillis::now(), milliseconds_taken: 0, })?; c = col.storage.get_card(c.id)?.unwrap(); assert_eq!(c.queue, CardQueue::PreviewRepeat); // hard let next = col.get_next_card_states(c.id)?; col.answer_card(&CardAnswer { card_id: c.id, current_state: next.current, new_state: next.hard, rating: Rating::Hard, answered_at: TimestampMillis::now(), milliseconds_taken: 0, })?; c = col.storage.get_card(c.id)?.unwrap(); assert_eq!(c.queue, CardQueue::PreviewRepeat); // good let next = col.get_next_card_states(c.id)?; col.answer_card(&CardAnswer { card_id: c.id, current_state: next.current, new_state: next.good, rating: Rating::Good, answered_at: TimestampMillis::now(), milliseconds_taken: 0, })?; c = col.storage.get_card(c.id)?.unwrap(); assert_eq!(c.queue, CardQueue::PreviewRepeat); // and then it should return to its old state once easy selected let next = col.get_next_card_states(c.id)?; col.answer_card(&CardAnswer { card_id: c.id, current_state: next.current, new_state: next.easy, rating: Rating::Easy, answered_at: TimestampMillis::now(), milliseconds_taken: 0, })?; c = col.storage.get_card(c.id)?.unwrap(); assert_eq!(c.queue, CardQueue::DayLearn); assert_eq!(c.due, 123); Ok(()) } }
apply_preview_state
identifier_name
cleanup-copy-mode.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. use std::task; use std::gc::{GC, Gc}; fn adder(x: Gc<int>, y: Gc<int>) -> int { return *x + *y; } fn failer() -> Gc<int> { fail!(); } pub fn
() { assert!(task::try(proc() { adder(box(GC) 2, failer()); () }).is_err()); }
main
identifier_name
cleanup-copy-mode.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. use std::task; use std::gc::{GC, Gc}; fn adder(x: Gc<int>, y: Gc<int>) -> int
fn failer() -> Gc<int> { fail!(); } pub fn main() { assert!(task::try(proc() { adder(box(GC) 2, failer()); () }).is_err()); }
{ return *x + *y; }
identifier_body
cleanup-copy-mode.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
// option. This file may not be copied, modified, or distributed // except according to those terms. use std::task; use std::gc::{GC, Gc}; fn adder(x: Gc<int>, y: Gc<int>) -> int { return *x + *y; } fn failer() -> Gc<int> { fail!(); } pub fn main() { assert!(task::try(proc() { adder(box(GC) 2, failer()); () }).is_err()); }
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
random_line_split
process.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. use prelude::*; use cell::Cell; use libc; use ptr; use util; use vec; use rt::io::process::*; use rt::uv; use rt::uv::uvio::UvPipeStream; use rt::uv::uvll; /// A process wraps the handle of the underlying uv_process_t. pub struct Process(*uvll::uv_process_t); impl uv::Watcher for Process {} impl Process { /// Creates a new process, ready to spawn inside an event loop pub fn new() -> Process { let handle = unsafe { uvll::malloc_handle(uvll::UV_PROCESS) }; assert!(handle.is_not_null()); let mut ret: Process = uv::NativeHandle::from_native_handle(handle); ret.install_watcher_data(); return ret; } /// Spawn a new process inside the specified event loop. /// /// The `config` variable will be passed down to libuv, and the `exit_cb` /// will be run only once, when the process exits. /// /// Returns either the corresponding process object or an error which /// occurred. pub fn spawn(&mut self, loop_: &uv::Loop, mut config: ProcessConfig, exit_cb: uv::ExitCallback) -> Result<~[Option<UvPipeStream>], uv::UvError> { let cwd = config.cwd.map_move(|s| s.to_c_str()); extern fn on_exit(p: *uvll::uv_process_t, exit_status: libc::c_int, term_signal: libc::c_int) { let mut p: Process = uv::NativeHandle::from_native_handle(p); let err = match exit_status { 0 => None, _ => uv::status_to_maybe_uv_error(-1) }; p.get_watcher_data().exit_cb.take_unwrap()(p, exit_status as int, term_signal as int, err); } let io = util::replace(&mut config.io, ~[]); let mut stdio = vec::with_capacity::<uvll::uv_stdio_container_t>(io.len()); let mut ret_io = vec::with_capacity(io.len()); unsafe { vec::raw::set_len(&mut stdio, io.len()); for (slot, other) in stdio.iter().zip(io.move_iter()) { let io = set_stdio(slot as *uvll::uv_stdio_container_t, other); ret_io.push(io); } } let exit_cb = Cell::new(exit_cb); let ret_io = Cell::new(ret_io); do with_argv(config.program, config.args) |argv| { do with_env(config.env) |envp| { let options = uvll::uv_process_options_t { exit_cb: on_exit, file: unsafe { *argv }, args: argv, env: envp, cwd: match cwd { Some(ref cwd) => cwd.with_ref(|p| p), None => ptr::null(), }, flags: 0, stdio_count: stdio.len() as libc::c_int, stdio: stdio.as_imm_buf(|p, _| p), uid: 0, gid: 0, }; match unsafe { uvll::spawn(loop_.native_handle(), **self, options) } { 0 => { (*self).get_watcher_data().exit_cb = Some(exit_cb.take()); Ok(ret_io.take()) } err => Err(uv::UvError(err)) } } } } /// Sends a signal to this process. /// /// This is a wrapper around `uv_process_kill` pub fn kill(&self, signum: int) -> Result<(), uv::UvError> { match unsafe { uvll::process_kill(self.native_handle(), signum as libc::c_int) } { 0 => Ok(()), err => Err(uv::UvError(err)) } } /// Returns the process id of a spawned process pub fn pid(&self) -> libc::pid_t { unsafe { uvll::process_pid(**self) as libc::pid_t } } /// Closes this handle, invoking the specified callback once closed pub fn close(self, cb: uv::NullCallback) { { let mut this = self; let data = this.get_watcher_data(); assert!(data.close_cb.is_none()); data.close_cb = Some(cb); } unsafe { uvll::close(self.native_handle(), close_cb); } extern fn close_cb(handle: *uvll::uv_process_t) { let mut process: Process = uv::NativeHandle::from_native_handle(handle); process.get_watcher_data().close_cb.take_unwrap()(); process.drop_watcher_data(); unsafe { uvll::free_handle(handle as *libc::c_void) } } } } unsafe fn set_stdio(dst: *uvll::uv_stdio_container_t, io: StdioContainer) -> Option<UvPipeStream> { match io { Ignored => { uvll::set_stdio_container_flags(dst, uvll::STDIO_IGNORE); None } InheritFd(fd) => { uvll::set_stdio_container_flags(dst, uvll::STDIO_INHERIT_FD); uvll::set_stdio_container_fd(dst, fd); None } CreatePipe(pipe, readable, writable) => { let mut flags = uvll::STDIO_CREATE_PIPE as libc::c_int; if readable
if writable { flags |= uvll::STDIO_WRITABLE_PIPE as libc::c_int; } let handle = pipe.pipe.as_stream().native_handle(); uvll::set_stdio_container_flags(dst, flags); uvll::set_stdio_container_stream(dst, handle); Some(pipe.bind()) } } } /// Converts the program and arguments to the argv array expected by libuv fn with_argv<T>(prog: &str, args: &[~str], f: &fn(**libc::c_char) -> T) -> T { // First, allocation space to put all the C-strings (we need to have // ownership of them somewhere let mut c_strs = vec::with_capacity(args.len() + 1); c_strs.push(prog.to_c_str()); for arg in args.iter() { c_strs.push(arg.to_c_str()); } // Next, create the char** array let mut c_args = vec::with_capacity(c_strs.len() + 1); for s in c_strs.iter() { c_args.push(s.with_ref(|p| p)); } c_args.push(ptr::null()); c_args.as_imm_buf(|buf, _| f(buf)) } /// Converts the environment to the env array expected by libuv fn with_env<T>(env: Option<&[(~str, ~str)]>, f: &fn(**libc::c_char) -> T) -> T { let env = match env { Some(s) => s, None => { return f(ptr::null()); } }; // As with argv, create some temporary storage and then the actual array let mut envp = vec::with_capacity(env.len()); for &(ref key, ref value) in env.iter() { envp.push(fmt!("%s=%s", *key, *value).to_c_str()); } let mut c_envp = vec::with_capacity(envp.len() + 1); for s in envp.iter() { c_envp.push(s.with_ref(|p| p)); } c_envp.push(ptr::null()); c_envp.as_imm_buf(|buf, _| f(buf)) } impl uv::NativeHandle<*uvll::uv_process_t> for Process { fn from_native_handle(handle: *uvll::uv_process_t) -> Process { Process(handle) } fn native_handle(&self) -> *uvll::uv_process_t { match self { &Process(ptr) => ptr } } }
{ flags |= uvll::STDIO_READABLE_PIPE as libc::c_int; }
conditional_block
process.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. use prelude::*; use cell::Cell; use libc; use ptr; use util; use vec; use rt::io::process::*; use rt::uv; use rt::uv::uvio::UvPipeStream; use rt::uv::uvll; /// A process wraps the handle of the underlying uv_process_t. pub struct Process(*uvll::uv_process_t); impl uv::Watcher for Process {} impl Process { /// Creates a new process, ready to spawn inside an event loop pub fn new() -> Process { let handle = unsafe { uvll::malloc_handle(uvll::UV_PROCESS) }; assert!(handle.is_not_null()); let mut ret: Process = uv::NativeHandle::from_native_handle(handle); ret.install_watcher_data(); return ret; } /// Spawn a new process inside the specified event loop. /// /// The `config` variable will be passed down to libuv, and the `exit_cb` /// will be run only once, when the process exits. /// /// Returns either the corresponding process object or an error which /// occurred. pub fn spawn(&mut self, loop_: &uv::Loop, mut config: ProcessConfig, exit_cb: uv::ExitCallback) -> Result<~[Option<UvPipeStream>], uv::UvError> { let cwd = config.cwd.map_move(|s| s.to_c_str()); extern fn on_exit(p: *uvll::uv_process_t, exit_status: libc::c_int, term_signal: libc::c_int) { let mut p: Process = uv::NativeHandle::from_native_handle(p); let err = match exit_status { 0 => None, _ => uv::status_to_maybe_uv_error(-1) }; p.get_watcher_data().exit_cb.take_unwrap()(p, exit_status as int, term_signal as int, err); } let io = util::replace(&mut config.io, ~[]); let mut stdio = vec::with_capacity::<uvll::uv_stdio_container_t>(io.len()); let mut ret_io = vec::with_capacity(io.len()); unsafe { vec::raw::set_len(&mut stdio, io.len()); for (slot, other) in stdio.iter().zip(io.move_iter()) { let io = set_stdio(slot as *uvll::uv_stdio_container_t, other); ret_io.push(io); } } let exit_cb = Cell::new(exit_cb); let ret_io = Cell::new(ret_io); do with_argv(config.program, config.args) |argv| { do with_env(config.env) |envp| { let options = uvll::uv_process_options_t { exit_cb: on_exit, file: unsafe { *argv }, args: argv, env: envp, cwd: match cwd { Some(ref cwd) => cwd.with_ref(|p| p), None => ptr::null(), }, flags: 0, stdio_count: stdio.len() as libc::c_int, stdio: stdio.as_imm_buf(|p, _| p), uid: 0, gid: 0, }; match unsafe { uvll::spawn(loop_.native_handle(), **self, options) } { 0 => { (*self).get_watcher_data().exit_cb = Some(exit_cb.take()); Ok(ret_io.take()) } err => Err(uv::UvError(err)) } } } } /// Sends a signal to this process. /// /// This is a wrapper around `uv_process_kill` pub fn kill(&self, signum: int) -> Result<(), uv::UvError> { match unsafe { uvll::process_kill(self.native_handle(), signum as libc::c_int) } { 0 => Ok(()), err => Err(uv::UvError(err)) } } /// Returns the process id of a spawned process pub fn pid(&self) -> libc::pid_t { unsafe { uvll::process_pid(**self) as libc::pid_t } } /// Closes this handle, invoking the specified callback once closed pub fn close(self, cb: uv::NullCallback)
} unsafe fn set_stdio(dst: *uvll::uv_stdio_container_t, io: StdioContainer) -> Option<UvPipeStream> { match io { Ignored => { uvll::set_stdio_container_flags(dst, uvll::STDIO_IGNORE); None } InheritFd(fd) => { uvll::set_stdio_container_flags(dst, uvll::STDIO_INHERIT_FD); uvll::set_stdio_container_fd(dst, fd); None } CreatePipe(pipe, readable, writable) => { let mut flags = uvll::STDIO_CREATE_PIPE as libc::c_int; if readable { flags |= uvll::STDIO_READABLE_PIPE as libc::c_int; } if writable { flags |= uvll::STDIO_WRITABLE_PIPE as libc::c_int; } let handle = pipe.pipe.as_stream().native_handle(); uvll::set_stdio_container_flags(dst, flags); uvll::set_stdio_container_stream(dst, handle); Some(pipe.bind()) } } } /// Converts the program and arguments to the argv array expected by libuv fn with_argv<T>(prog: &str, args: &[~str], f: &fn(**libc::c_char) -> T) -> T { // First, allocation space to put all the C-strings (we need to have // ownership of them somewhere let mut c_strs = vec::with_capacity(args.len() + 1); c_strs.push(prog.to_c_str()); for arg in args.iter() { c_strs.push(arg.to_c_str()); } // Next, create the char** array let mut c_args = vec::with_capacity(c_strs.len() + 1); for s in c_strs.iter() { c_args.push(s.with_ref(|p| p)); } c_args.push(ptr::null()); c_args.as_imm_buf(|buf, _| f(buf)) } /// Converts the environment to the env array expected by libuv fn with_env<T>(env: Option<&[(~str, ~str)]>, f: &fn(**libc::c_char) -> T) -> T { let env = match env { Some(s) => s, None => { return f(ptr::null()); } }; // As with argv, create some temporary storage and then the actual array let mut envp = vec::with_capacity(env.len()); for &(ref key, ref value) in env.iter() { envp.push(fmt!("%s=%s", *key, *value).to_c_str()); } let mut c_envp = vec::with_capacity(envp.len() + 1); for s in envp.iter() { c_envp.push(s.with_ref(|p| p)); } c_envp.push(ptr::null()); c_envp.as_imm_buf(|buf, _| f(buf)) } impl uv::NativeHandle<*uvll::uv_process_t> for Process { fn from_native_handle(handle: *uvll::uv_process_t) -> Process { Process(handle) } fn native_handle(&self) -> *uvll::uv_process_t { match self { &Process(ptr) => ptr } } }
{ { let mut this = self; let data = this.get_watcher_data(); assert!(data.close_cb.is_none()); data.close_cb = Some(cb); } unsafe { uvll::close(self.native_handle(), close_cb); } extern fn close_cb(handle: *uvll::uv_process_t) { let mut process: Process = uv::NativeHandle::from_native_handle(handle); process.get_watcher_data().close_cb.take_unwrap()(); process.drop_watcher_data(); unsafe { uvll::free_handle(handle as *libc::c_void) } } }
identifier_body
process.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. use prelude::*; use cell::Cell; use libc; use ptr; use util; use vec; use rt::io::process::*; use rt::uv; use rt::uv::uvio::UvPipeStream; use rt::uv::uvll; /// A process wraps the handle of the underlying uv_process_t. pub struct Process(*uvll::uv_process_t); impl uv::Watcher for Process {} impl Process { /// Creates a new process, ready to spawn inside an event loop pub fn new() -> Process { let handle = unsafe { uvll::malloc_handle(uvll::UV_PROCESS) }; assert!(handle.is_not_null()); let mut ret: Process = uv::NativeHandle::from_native_handle(handle); ret.install_watcher_data(); return ret; } /// Spawn a new process inside the specified event loop. /// /// The `config` variable will be passed down to libuv, and the `exit_cb` /// will be run only once, when the process exits. /// /// Returns either the corresponding process object or an error which /// occurred. pub fn spawn(&mut self, loop_: &uv::Loop, mut config: ProcessConfig, exit_cb: uv::ExitCallback) -> Result<~[Option<UvPipeStream>], uv::UvError> { let cwd = config.cwd.map_move(|s| s.to_c_str()); extern fn on_exit(p: *uvll::uv_process_t, exit_status: libc::c_int, term_signal: libc::c_int) { let mut p: Process = uv::NativeHandle::from_native_handle(p); let err = match exit_status { 0 => None, _ => uv::status_to_maybe_uv_error(-1) }; p.get_watcher_data().exit_cb.take_unwrap()(p, exit_status as int, term_signal as int, err); } let io = util::replace(&mut config.io, ~[]); let mut stdio = vec::with_capacity::<uvll::uv_stdio_container_t>(io.len()); let mut ret_io = vec::with_capacity(io.len()); unsafe { vec::raw::set_len(&mut stdio, io.len()); for (slot, other) in stdio.iter().zip(io.move_iter()) { let io = set_stdio(slot as *uvll::uv_stdio_container_t, other); ret_io.push(io); } } let exit_cb = Cell::new(exit_cb); let ret_io = Cell::new(ret_io); do with_argv(config.program, config.args) |argv| { do with_env(config.env) |envp| { let options = uvll::uv_process_options_t { exit_cb: on_exit, file: unsafe { *argv }, args: argv, env: envp, cwd: match cwd { Some(ref cwd) => cwd.with_ref(|p| p), None => ptr::null(), }, flags: 0, stdio_count: stdio.len() as libc::c_int, stdio: stdio.as_imm_buf(|p, _| p), uid: 0, gid: 0, }; match unsafe { uvll::spawn(loop_.native_handle(), **self, options) } { 0 => { (*self).get_watcher_data().exit_cb = Some(exit_cb.take()); Ok(ret_io.take()) } err => Err(uv::UvError(err)) } } } } /// Sends a signal to this process. /// /// This is a wrapper around `uv_process_kill` pub fn kill(&self, signum: int) -> Result<(), uv::UvError> { match unsafe { uvll::process_kill(self.native_handle(), signum as libc::c_int) } { 0 => Ok(()), err => Err(uv::UvError(err)) } } /// Returns the process id of a spawned process pub fn pid(&self) -> libc::pid_t { unsafe { uvll::process_pid(**self) as libc::pid_t } } /// Closes this handle, invoking the specified callback once closed pub fn close(self, cb: uv::NullCallback) { { let mut this = self; let data = this.get_watcher_data(); assert!(data.close_cb.is_none()); data.close_cb = Some(cb); } unsafe { uvll::close(self.native_handle(), close_cb); } extern fn close_cb(handle: *uvll::uv_process_t) { let mut process: Process = uv::NativeHandle::from_native_handle(handle); process.get_watcher_data().close_cb.take_unwrap()(); process.drop_watcher_data(); unsafe { uvll::free_handle(handle as *libc::c_void) } } } } unsafe fn set_stdio(dst: *uvll::uv_stdio_container_t, io: StdioContainer) -> Option<UvPipeStream> { match io { Ignored => { uvll::set_stdio_container_flags(dst, uvll::STDIO_IGNORE); None } InheritFd(fd) => { uvll::set_stdio_container_flags(dst, uvll::STDIO_INHERIT_FD); uvll::set_stdio_container_fd(dst, fd); None } CreatePipe(pipe, readable, writable) => { let mut flags = uvll::STDIO_CREATE_PIPE as libc::c_int; if readable { flags |= uvll::STDIO_READABLE_PIPE as libc::c_int; } if writable { flags |= uvll::STDIO_WRITABLE_PIPE as libc::c_int; } let handle = pipe.pipe.as_stream().native_handle(); uvll::set_stdio_container_flags(dst, flags); uvll::set_stdio_container_stream(dst, handle); Some(pipe.bind()) } } } /// Converts the program and arguments to the argv array expected by libuv fn with_argv<T>(prog: &str, args: &[~str], f: &fn(**libc::c_char) -> T) -> T { // First, allocation space to put all the C-strings (we need to have // ownership of them somewhere let mut c_strs = vec::with_capacity(args.len() + 1); c_strs.push(prog.to_c_str()); for arg in args.iter() { c_strs.push(arg.to_c_str()); } // Next, create the char** array let mut c_args = vec::with_capacity(c_strs.len() + 1); for s in c_strs.iter() { c_args.push(s.with_ref(|p| p)); } c_args.push(ptr::null()); c_args.as_imm_buf(|buf, _| f(buf)) } /// Converts the environment to the env array expected by libuv fn with_env<T>(env: Option<&[(~str, ~str)]>, f: &fn(**libc::c_char) -> T) -> T { let env = match env { Some(s) => s, None => { return f(ptr::null()); } }; // As with argv, create some temporary storage and then the actual array let mut envp = vec::with_capacity(env.len()); for &(ref key, ref value) in env.iter() { envp.push(fmt!("%s=%s", *key, *value).to_c_str()); } let mut c_envp = vec::with_capacity(envp.len() + 1); for s in envp.iter() { c_envp.push(s.with_ref(|p| p)); } c_envp.push(ptr::null()); c_envp.as_imm_buf(|buf, _| f(buf)) } impl uv::NativeHandle<*uvll::uv_process_t> for Process { fn
(handle: *uvll::uv_process_t) -> Process { Process(handle) } fn native_handle(&self) -> *uvll::uv_process_t { match self { &Process(ptr) => ptr } } }
from_native_handle
identifier_name
process.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. use prelude::*; use cell::Cell; use libc; use ptr; use util; use vec; use rt::io::process::*; use rt::uv; use rt::uv::uvio::UvPipeStream; use rt::uv::uvll; /// A process wraps the handle of the underlying uv_process_t. pub struct Process(*uvll::uv_process_t); impl uv::Watcher for Process {} impl Process { /// Creates a new process, ready to spawn inside an event loop pub fn new() -> Process { let handle = unsafe { uvll::malloc_handle(uvll::UV_PROCESS) }; assert!(handle.is_not_null()); let mut ret: Process = uv::NativeHandle::from_native_handle(handle); ret.install_watcher_data(); return ret; } /// Spawn a new process inside the specified event loop. /// /// The `config` variable will be passed down to libuv, and the `exit_cb` /// will be run only once, when the process exits. /// /// Returns either the corresponding process object or an error which /// occurred. pub fn spawn(&mut self, loop_: &uv::Loop, mut config: ProcessConfig, exit_cb: uv::ExitCallback) -> Result<~[Option<UvPipeStream>], uv::UvError> { let cwd = config.cwd.map_move(|s| s.to_c_str()); extern fn on_exit(p: *uvll::uv_process_t, exit_status: libc::c_int, term_signal: libc::c_int) { let mut p: Process = uv::NativeHandle::from_native_handle(p); let err = match exit_status { 0 => None, _ => uv::status_to_maybe_uv_error(-1) }; p.get_watcher_data().exit_cb.take_unwrap()(p, exit_status as int, term_signal as int, err); } let io = util::replace(&mut config.io, ~[]); let mut stdio = vec::with_capacity::<uvll::uv_stdio_container_t>(io.len()); let mut ret_io = vec::with_capacity(io.len()); unsafe { vec::raw::set_len(&mut stdio, io.len()); for (slot, other) in stdio.iter().zip(io.move_iter()) { let io = set_stdio(slot as *uvll::uv_stdio_container_t, other); ret_io.push(io); } } let exit_cb = Cell::new(exit_cb); let ret_io = Cell::new(ret_io); do with_argv(config.program, config.args) |argv| { do with_env(config.env) |envp| { let options = uvll::uv_process_options_t { exit_cb: on_exit, file: unsafe { *argv }, args: argv, env: envp, cwd: match cwd { Some(ref cwd) => cwd.with_ref(|p| p), None => ptr::null(), }, flags: 0, stdio_count: stdio.len() as libc::c_int, stdio: stdio.as_imm_buf(|p, _| p), uid: 0, gid: 0, }; match unsafe { uvll::spawn(loop_.native_handle(), **self, options) } { 0 => { (*self).get_watcher_data().exit_cb = Some(exit_cb.take()); Ok(ret_io.take()) } err => Err(uv::UvError(err)) } } } } /// Sends a signal to this process. /// /// This is a wrapper around `uv_process_kill` pub fn kill(&self, signum: int) -> Result<(), uv::UvError> { match unsafe { uvll::process_kill(self.native_handle(), signum as libc::c_int) } { 0 => Ok(()), err => Err(uv::UvError(err)) } } /// Returns the process id of a spawned process pub fn pid(&self) -> libc::pid_t { unsafe { uvll::process_pid(**self) as libc::pid_t } } /// Closes this handle, invoking the specified callback once closed pub fn close(self, cb: uv::NullCallback) { { let mut this = self; let data = this.get_watcher_data(); assert!(data.close_cb.is_none()); data.close_cb = Some(cb); } unsafe { uvll::close(self.native_handle(), close_cb); } extern fn close_cb(handle: *uvll::uv_process_t) { let mut process: Process = uv::NativeHandle::from_native_handle(handle); process.get_watcher_data().close_cb.take_unwrap()(); process.drop_watcher_data(); unsafe { uvll::free_handle(handle as *libc::c_void) } } } } unsafe fn set_stdio(dst: *uvll::uv_stdio_container_t, io: StdioContainer) -> Option<UvPipeStream> { match io { Ignored => { uvll::set_stdio_container_flags(dst, uvll::STDIO_IGNORE); None } InheritFd(fd) => { uvll::set_stdio_container_flags(dst, uvll::STDIO_INHERIT_FD); uvll::set_stdio_container_fd(dst, fd); None } CreatePipe(pipe, readable, writable) => { let mut flags = uvll::STDIO_CREATE_PIPE as libc::c_int; if readable { flags |= uvll::STDIO_READABLE_PIPE as libc::c_int; } if writable { flags |= uvll::STDIO_WRITABLE_PIPE as libc::c_int; } let handle = pipe.pipe.as_stream().native_handle(); uvll::set_stdio_container_flags(dst, flags); uvll::set_stdio_container_stream(dst, handle); Some(pipe.bind()) } } } /// Converts the program and arguments to the argv array expected by libuv fn with_argv<T>(prog: &str, args: &[~str], f: &fn(**libc::c_char) -> T) -> T { // First, allocation space to put all the C-strings (we need to have // ownership of them somewhere let mut c_strs = vec::with_capacity(args.len() + 1); c_strs.push(prog.to_c_str()); for arg in args.iter() { c_strs.push(arg.to_c_str()); } // Next, create the char** array let mut c_args = vec::with_capacity(c_strs.len() + 1); for s in c_strs.iter() { c_args.push(s.with_ref(|p| p)); } c_args.push(ptr::null()); c_args.as_imm_buf(|buf, _| f(buf)) } /// Converts the environment to the env array expected by libuv fn with_env<T>(env: Option<&[(~str, ~str)]>, f: &fn(**libc::c_char) -> T) -> T { let env = match env { Some(s) => s, None => { return f(ptr::null()); } }; // As with argv, create some temporary storage and then the actual array let mut envp = vec::with_capacity(env.len()); for &(ref key, ref value) in env.iter() { envp.push(fmt!("%s=%s", *key, *value).to_c_str()); } let mut c_envp = vec::with_capacity(envp.len() + 1);
} impl uv::NativeHandle<*uvll::uv_process_t> for Process { fn from_native_handle(handle: *uvll::uv_process_t) -> Process { Process(handle) } fn native_handle(&self) -> *uvll::uv_process_t { match self { &Process(ptr) => ptr } } }
for s in envp.iter() { c_envp.push(s.with_ref(|p| p)); } c_envp.push(ptr::null()); c_envp.as_imm_buf(|buf, _| f(buf))
random_line_split