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
led.rs
//! LED *(Dialog-specification language)* functionalities. //! //! LED is a dialog-specification language whose purpose is not to be a complete programming language, //! but rather to make dialog specification simpler than in C. Additionally it allows users to easily //! edit your application layout from external files without touching any source code. //! //! In LED, attributes and expressions follow this form: //! //! `elem = element[attribute1=value1,attribute2=value2,...](...expression...)` //! //! The names of the elements must not contain the “iup” prefix. //! Attribute values are always interpreted as strings, but they need to be in quotes (“…”) only //! when they include spaces. The “IUP_” prefix must not be added to the names of the attributes //! and predefined values. Expressions contain parameters for creating the element. //! //! In LED there is no distinction between upper and lower case, except for attribute names. //! //! Also there is no optional parameters, in arrays at least one parameter must exist. //! //! To simply view a LED file objects use the LED Viewer application called [IupView][1], in the //! applications included in the distribution. Pre-compiled binaries are available at the //! [Download][2]. //! //! You need to check out the [IUP documentation][0] for each control to see their //! respective function signatures in LED. //! //! **Note:** Using LED may allow you to create controls not yet implemented in iup-rust and //! that's *fine*. Use a `Handle` to have access to controls created from LED. //! //! [0]: http://webserver2.tecgraf.puc-rio.br/iup/ //! [1]: http://webserver2.tecgraf.puc-rio.br/iup/en/led.html //! [2]: http://webserver2.tecgraf.puc-rio.br/iup/en/download.html use iup_sys; use std::path::Path; use std::result::Result; use std::ffi::CString; /// Compiles a LED specification from a file. /// /// Each time the function loads a LED file, the elements contained in it are created. /// Therefore, the same LED file cannot be loaded several times, otherwise the elements will also /// be created several times. /// /// In case of failure returns the compilation error message. pub fn load<P: AsRef<Path>>(path: P) -> Result<(), String> { let path = path.as_ref(); let str = path.to_str().ok_or_else(|| "Failed to convert Path to string".to_string())?; let cstr = CString::new(str).unwrap(); match unsafe { iup_sys::IupLoad(cstr.as_ptr()) } { err if err.is_null() => Ok(()), err => Err(string_from_cstr!(err)), } } /// Compiles a LED specification from a string. /// /// See the `load` function for additional semantic details. pub fn load_buffer<S: Into<String>>(buf: S) -> Result<(), String> { let cstr
= CString::new(buf.into()).unwrap(); match unsafe { iup_sys::IupLoadBuffer(cstr.as_ptr()) } { err if err.is_null() => Ok(()), err => Err(string_from_cstr!(err)), } }
identifier_body
led.rs
//! LED *(Dialog-specification language)* functionalities. //! //! LED is a dialog-specification language whose purpose is not to be a complete programming language, //! but rather to make dialog specification simpler than in C. Additionally it allows users to easily //! edit your application layout from external files without touching any source code. //! //! In LED, attributes and expressions follow this form: //! //! `elem = element[attribute1=value1,attribute2=value2,...](...expression...)` //! //! The names of the elements must not contain the “iup” prefix. //! Attribute values are always interpreted as strings, but they need to be in quotes (“…”) only //! when they include spaces. The “IUP_” prefix must not be added to the names of the attributes //! and predefined values. Expressions contain parameters for creating the element. //! //! In LED there is no distinction between upper and lower case, except for attribute names. //! //! Also there is no optional parameters, in arrays at least one parameter must exist. //! //! To simply view a LED file objects use the LED Viewer application called [IupView][1], in the //! applications included in the distribution. Pre-compiled binaries are available at the //! [Download][2]. //! //! You need to check out the [IUP documentation][0] for each control to see their //! respective function signatures in LED. //! //! **Note:** Using LED may allow you to create controls not yet implemented in iup-rust and //! that's *fine*. Use a `Handle` to have access to controls created from LED. //! //! [0]: http://webserver2.tecgraf.puc-rio.br/iup/ //! [1]: http://webserver2.tecgraf.puc-rio.br/iup/en/led.html //! [2]: http://webserver2.tecgraf.puc-rio.br/iup/en/download.html use iup_sys; use std::path::Path; use std::result::Result; use std::ffi::CString; /// Compiles a LED specification from a file. /// /// Each time the function loads a LED file, the elements contained in it are created. /// Therefore, the same LED file cannot be loaded several times, otherwise the elements will also /// be created several times. /// /// In case of failure returns the compilation error message. pub fn load<P: AsRef<
>>(path: P) -> Result<(), String> { let path = path.as_ref(); let str = path.to_str().ok_or_else(|| "Failed to convert Path to string".to_string())?; let cstr = CString::new(str).unwrap(); match unsafe { iup_sys::IupLoad(cstr.as_ptr()) } { err if err.is_null() => Ok(()), err => Err(string_from_cstr!(err)), } } /// Compiles a LED specification from a string. /// /// See the `load` function for additional semantic details. pub fn load_buffer<S: Into<String>>(buf: S) -> Result<(), String> { let cstr = CString::new(buf.into()).unwrap(); match unsafe { iup_sys::IupLoadBuffer(cstr.as_ptr()) } { err if err.is_null() => Ok(()), err => Err(string_from_cstr!(err)), } }
Path
identifier_name
dnode.rs
use std::fmt; use std::mem; use super::block_ptr::BlockPtr; use super::from_bytes::FromBytes; use super::zil_header::ZilHeader; #[repr(u8)] #[derive(Debug, Eq, PartialEq)] pub enum
{ None, ObjectDirectory, ObjectArray, PackedNvList, NvListSize, BlockPtrList, BlockPtrListHdr, SpaceMapHeader, SpaceMap, IntentLog, DNode, ObjSet, DataSet, DataSetChildMap, ObjSetSnapMap, DslProps, DslObjSet, ZNode, Acl, PlainFileContents, DirectoryContents, MasterNode, DeleteQueue, ZVol, ZVolProp, } #[repr(packed)] pub struct DNodePhys { pub object_type: ObjectType, pub indblkshift: u8, // ln2(indirect block size) pub nlevels: u8, // 1=blkptr->data blocks pub nblkptr: u8, // length of blkptr pub bonus_type: u8, // type of data in bonus buffer pub checksum: u8, // ZIO_CHECKSUM type pub compress: u8, // ZIO_COMPRESS type pub flags: u8, // DNODE_FLAG_* pub data_blk_sz_sec: u16, // data block size in 512b sectors pub bonus_len: u16, // length of bonus pub pad2: [u8; 4], // accounting is protected by dirty_mtx pub maxblkid: u64, // largest allocated block ID pub used: u64, // bytes (or sectors) of disk space pub pad3: [u64; 4], blkptr_bonus: [u8; 448], } impl DNodePhys { pub fn get_blockptr<'a>(&self, i: usize) -> &'a BlockPtr { unsafe { mem::transmute(&self.blkptr_bonus[i * 128]) } } pub fn get_bonus(&self) -> &[u8] { &self.blkptr_bonus[(self.nblkptr as usize) * 128..] } } impl FromBytes for DNodePhys {} impl fmt::Debug for DNodePhys { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "DNodePhys {{ object_type: {:?}, nlevels: {:X}, nblkptr: {:X}, bonus_type: \ {:X}, bonus_len: {:X}}}\n", self.object_type, self.nlevels, self.nblkptr, self.bonus_type, self.bonus_len)); Ok(()) } }
ObjectType
identifier_name
dnode.rs
use std::fmt; use std::mem; use super::block_ptr::BlockPtr; use super::from_bytes::FromBytes; use super::zil_header::ZilHeader; #[repr(u8)] #[derive(Debug, Eq, PartialEq)] pub enum ObjectType { None, ObjectDirectory, ObjectArray, PackedNvList, NvListSize, BlockPtrList, BlockPtrListHdr, SpaceMapHeader, SpaceMap, IntentLog, DNode, ObjSet,
DslProps, DslObjSet, ZNode, Acl, PlainFileContents, DirectoryContents, MasterNode, DeleteQueue, ZVol, ZVolProp, } #[repr(packed)] pub struct DNodePhys { pub object_type: ObjectType, pub indblkshift: u8, // ln2(indirect block size) pub nlevels: u8, // 1=blkptr->data blocks pub nblkptr: u8, // length of blkptr pub bonus_type: u8, // type of data in bonus buffer pub checksum: u8, // ZIO_CHECKSUM type pub compress: u8, // ZIO_COMPRESS type pub flags: u8, // DNODE_FLAG_* pub data_blk_sz_sec: u16, // data block size in 512b sectors pub bonus_len: u16, // length of bonus pub pad2: [u8; 4], // accounting is protected by dirty_mtx pub maxblkid: u64, // largest allocated block ID pub used: u64, // bytes (or sectors) of disk space pub pad3: [u64; 4], blkptr_bonus: [u8; 448], } impl DNodePhys { pub fn get_blockptr<'a>(&self, i: usize) -> &'a BlockPtr { unsafe { mem::transmute(&self.blkptr_bonus[i * 128]) } } pub fn get_bonus(&self) -> &[u8] { &self.blkptr_bonus[(self.nblkptr as usize) * 128..] } } impl FromBytes for DNodePhys {} impl fmt::Debug for DNodePhys { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "DNodePhys {{ object_type: {:?}, nlevels: {:X}, nblkptr: {:X}, bonus_type: \ {:X}, bonus_len: {:X}}}\n", self.object_type, self.nlevels, self.nblkptr, self.bonus_type, self.bonus_len)); Ok(()) } }
DataSet, DataSetChildMap, ObjSetSnapMap,
random_line_split
hrtb-precedence-of-plus.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. #![allow(unknown_features)] #![feature(box_syntax)] #![feature(unboxed_closures)] // Test that `Fn(int) -> int +'static` parses as `(Fn(int) -> int) + //'static` and not `Fn(int) -> (int +'static)`. The latter would // cause a compilation error. Issue #18772. fn adder(y: int) -> Box<Fn(int) -> int +'static> { box move |x| y + x } fn main()
{}
identifier_body
hrtb-precedence-of-plus.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. #![allow(unknown_features)] #![feature(box_syntax)] #![feature(unboxed_closures)] // Test that `Fn(int) -> int +'static` parses as `(Fn(int) -> int) + //'static` and not `Fn(int) -> (int +'static)`. The latter would // cause a compilation error. Issue #18772. fn adder(y: int) -> Box<Fn(int) -> int +'static> { box move |x| y + x } fn
() {}
main
identifier_name
hrtb-precedence-of-plus.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.
#![allow(unknown_features)] #![feature(box_syntax)] #![feature(unboxed_closures)] // Test that `Fn(int) -> int +'static` parses as `(Fn(int) -> int) + //'static` and not `Fn(int) -> (int +'static)`. The latter would // cause a compilation error. Issue #18772. fn adder(y: int) -> Box<Fn(int) -> int +'static> { box move |x| y + x } fn main() {}
random_line_split
wrapper.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 safe wrapper for DOM nodes that prevents layout from mutating the DOM, from letting DOM nodes //! escape, and from generally doing anything that it isn't supposed to. This is accomplished via //! a simple whitelist of allowed operations, along with some lifetime magic to prevent nodes from //! escaping. //! //! As a security wrapper is only as good as its whitelist, be careful when adding operations to //! this list. The cardinal rules are: //! //! 1. Layout is not allowed to mutate the DOM. //! //! 2. Layout is not allowed to see anything with `LayoutJS` in the name, because it could hang //! onto these objects and cause use-after-free. //! //! When implementing wrapper functions, be careful that you do not touch the borrow flags, or you //! will race and cause spurious thread failure. (Note that I do not believe these races are //! exploitable, but they'll result in brokenness nonetheless.) //! //! Rules of the road for this file: //! //! * Do not call any methods on DOM nodes without checking to see whether they use borrow flags. //! //! o Instead of `get_attr()`, use `.get_attr_val_for_layout()`. //! //! o Instead of `html_element_in_html_document()`, use //! `html_element_in_html_document_for_layout()`. #![allow(unsafe_code)] use atomic_refcell::{AtomicRef, AtomicRefMut}; use core::nonzero::NonZero; use data::{LayoutData, LayoutDataFlags, StyleAndLayoutData}; use script_layout_interface::{OpaqueStyleAndLayoutData, StyleData}; use script_layout_interface::wrapper_traits::{LayoutNode, ThreadSafeLayoutElement, ThreadSafeLayoutNode}; use script_layout_interface::wrapper_traits::GetLayoutData; use style::computed_values::content::{self, ContentItem}; use style::dom::{NodeInfo, TNode}; use style::selector_parser::RestyleDamage; pub unsafe fn drop_style_and_layout_data(data: OpaqueStyleAndLayoutData) { let ptr: *mut StyleData = data.ptr.get(); let non_opaque: *mut StyleAndLayoutData = ptr as *mut _; let _ = Box::from_raw(non_opaque); } pub trait LayoutNodeLayoutData { /// Similar to borrow_data*, but returns the full PersistentLayoutData rather /// than only the style::data::ElementData. fn borrow_layout_data(&self) -> Option<AtomicRef<LayoutData>>; fn mutate_layout_data(&self) -> Option<AtomicRefMut<LayoutData>>; fn flow_debug_id(self) -> usize; } impl<T: GetLayoutData> LayoutNodeLayoutData for T { fn borrow_layout_data(&self) -> Option<AtomicRef<LayoutData>> { self.get_raw_data().map(|d| d.layout_data.borrow()) } fn mutate_layout_data(&self) -> Option<AtomicRefMut<LayoutData>> { self.get_raw_data().map(|d| d.layout_data.borrow_mut()) } fn flow_debug_id(self) -> usize { self.borrow_layout_data().map_or(0, |d| d.flow_construction_result.debug_id()) } } pub trait GetRawData { fn get_raw_data(&self) -> Option<&StyleAndLayoutData>; } impl<T: GetLayoutData> GetRawData for T { fn get_raw_data(&self) -> Option<&StyleAndLayoutData> { self.get_style_and_layout_data().map(|opaque| { let container = opaque.ptr.get() as *mut StyleAndLayoutData; unsafe { &*container } }) } } pub trait LayoutNodeHelpers { fn initialize_data(&self); fn clear_data(&self); } impl<T: LayoutNode> LayoutNodeHelpers for T { fn initialize_data(&self) { if self.get_raw_data().is_none() { let ptr: *mut StyleAndLayoutData = Box::into_raw(Box::new(StyleAndLayoutData::new())); let opaque = OpaqueStyleAndLayoutData { ptr: unsafe { NonZero::new(ptr as *mut StyleData) } }; unsafe { self.init_style_and_layout_data(opaque) }; }; } fn clear_data(&self) { if self.get_raw_data().is_some() { unsafe { drop_style_and_layout_data(self.take_style_and_layout_data()) }; } } } pub trait ThreadSafeLayoutNodeHelpers { /// Returns the layout data flags for this node. fn flags(self) -> LayoutDataFlags; /// Adds the given flags to this node. fn insert_flags(self, new_flags: LayoutDataFlags); /// Removes the given flags from this node. fn remove_flags(self, flags: LayoutDataFlags); /// If this is a text node, generated content, or a form element, copies out /// its content. Otherwise, panics. /// /// FIXME(pcwalton): This might have too much copying and/or allocation. Profile this. fn text_content(&self) -> TextContent; /// The RestyleDamage from any restyling, or RestyleDamage::rebuild_and_reflow() if this /// is the first time layout is visiting this node. We implement this here, rather than /// with the rest of the wrapper layer, because we need layout code to determine whether /// layout has visited the node. fn restyle_damage(self) -> RestyleDamage; } impl<T: ThreadSafeLayoutNode> ThreadSafeLayoutNodeHelpers for T { fn flags(self) -> LayoutDataFlags { self.borrow_layout_data().as_ref().unwrap().flags } fn insert_flags(self, new_flags: LayoutDataFlags) { self.mutate_layout_data().unwrap().flags.insert(new_flags); } fn remove_flags(self, flags: LayoutDataFlags) { self.mutate_layout_data().unwrap().flags.remove(flags); }
let style = self.as_element().unwrap().resolved_style(); return match style.as_ref().get_counters().content { content::T::Items(ref value) if!value.is_empty() => { TextContent::GeneratedContent((*value).clone()) } _ => TextContent::GeneratedContent(vec![]), }; } return TextContent::Text(self.node_text_content()); } fn restyle_damage(self) -> RestyleDamage { // We need the underlying node to potentially access the parent in the // case of text nodes. This is safe as long as we don't let the parent // escape and never access its descendants. let mut node = unsafe { self.unsafe_get() }; // If this is a text node, use the parent element, since that's what // controls our style. if node.is_text_node() { node = node.parent_node().unwrap(); debug_assert!(node.is_element()); } let damage = { let data = node.get_raw_data().unwrap(); if let Some(r) = data.style_data.element_data.borrow().get_restyle() { // We're reflowing a node that just got a restyle, and so the // damage has been computed and stored in the RestyleData. r.damage } else if!data.layout_data.borrow().flags.contains(::data::HAS_BEEN_TRAVERSED) { // We're reflowing a node that was styled for the first time and // has never been visited by layout. Return rebuild_and_reflow, // because that's what the code expects. RestyleDamage::rebuild_and_reflow() } else { // We're reflowing a node whose style data didn't change, but whose // layout may change due to changes in ancestors or descendants. RestyleDamage::empty() } }; damage } } pub enum TextContent { Text(String), GeneratedContent(Vec<ContentItem>), } impl TextContent { pub fn is_empty(&self) -> bool { match *self { TextContent::Text(_) => false, TextContent::GeneratedContent(ref content) => content.is_empty(), } } }
fn text_content(&self) -> TextContent { if self.get_pseudo_element_type().is_replaced_content() {
random_line_split
wrapper.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 safe wrapper for DOM nodes that prevents layout from mutating the DOM, from letting DOM nodes //! escape, and from generally doing anything that it isn't supposed to. This is accomplished via //! a simple whitelist of allowed operations, along with some lifetime magic to prevent nodes from //! escaping. //! //! As a security wrapper is only as good as its whitelist, be careful when adding operations to //! this list. The cardinal rules are: //! //! 1. Layout is not allowed to mutate the DOM. //! //! 2. Layout is not allowed to see anything with `LayoutJS` in the name, because it could hang //! onto these objects and cause use-after-free. //! //! When implementing wrapper functions, be careful that you do not touch the borrow flags, or you //! will race and cause spurious thread failure. (Note that I do not believe these races are //! exploitable, but they'll result in brokenness nonetheless.) //! //! Rules of the road for this file: //! //! * Do not call any methods on DOM nodes without checking to see whether they use borrow flags. //! //! o Instead of `get_attr()`, use `.get_attr_val_for_layout()`. //! //! o Instead of `html_element_in_html_document()`, use //! `html_element_in_html_document_for_layout()`. #![allow(unsafe_code)] use atomic_refcell::{AtomicRef, AtomicRefMut}; use core::nonzero::NonZero; use data::{LayoutData, LayoutDataFlags, StyleAndLayoutData}; use script_layout_interface::{OpaqueStyleAndLayoutData, StyleData}; use script_layout_interface::wrapper_traits::{LayoutNode, ThreadSafeLayoutElement, ThreadSafeLayoutNode}; use script_layout_interface::wrapper_traits::GetLayoutData; use style::computed_values::content::{self, ContentItem}; use style::dom::{NodeInfo, TNode}; use style::selector_parser::RestyleDamage; pub unsafe fn drop_style_and_layout_data(data: OpaqueStyleAndLayoutData) { let ptr: *mut StyleData = data.ptr.get(); let non_opaque: *mut StyleAndLayoutData = ptr as *mut _; let _ = Box::from_raw(non_opaque); } pub trait LayoutNodeLayoutData { /// Similar to borrow_data*, but returns the full PersistentLayoutData rather /// than only the style::data::ElementData. fn borrow_layout_data(&self) -> Option<AtomicRef<LayoutData>>; fn mutate_layout_data(&self) -> Option<AtomicRefMut<LayoutData>>; fn flow_debug_id(self) -> usize; } impl<T: GetLayoutData> LayoutNodeLayoutData for T { fn borrow_layout_data(&self) -> Option<AtomicRef<LayoutData>> { self.get_raw_data().map(|d| d.layout_data.borrow()) } fn mutate_layout_data(&self) -> Option<AtomicRefMut<LayoutData>> { self.get_raw_data().map(|d| d.layout_data.borrow_mut()) } fn flow_debug_id(self) -> usize { self.borrow_layout_data().map_or(0, |d| d.flow_construction_result.debug_id()) } } pub trait GetRawData { fn get_raw_data(&self) -> Option<&StyleAndLayoutData>; } impl<T: GetLayoutData> GetRawData for T { fn get_raw_data(&self) -> Option<&StyleAndLayoutData> { self.get_style_and_layout_data().map(|opaque| { let container = opaque.ptr.get() as *mut StyleAndLayoutData; unsafe { &*container } }) } } pub trait LayoutNodeHelpers { fn initialize_data(&self); fn clear_data(&self); } impl<T: LayoutNode> LayoutNodeHelpers for T { fn initialize_data(&self) { if self.get_raw_data().is_none() { let ptr: *mut StyleAndLayoutData = Box::into_raw(Box::new(StyleAndLayoutData::new())); let opaque = OpaqueStyleAndLayoutData { ptr: unsafe { NonZero::new(ptr as *mut StyleData) } }; unsafe { self.init_style_and_layout_data(opaque) }; }; } fn clear_data(&self) { if self.get_raw_data().is_some() { unsafe { drop_style_and_layout_data(self.take_style_and_layout_data()) }; } } } pub trait ThreadSafeLayoutNodeHelpers { /// Returns the layout data flags for this node. fn flags(self) -> LayoutDataFlags; /// Adds the given flags to this node. fn insert_flags(self, new_flags: LayoutDataFlags); /// Removes the given flags from this node. fn remove_flags(self, flags: LayoutDataFlags); /// If this is a text node, generated content, or a form element, copies out /// its content. Otherwise, panics. /// /// FIXME(pcwalton): This might have too much copying and/or allocation. Profile this. fn text_content(&self) -> TextContent; /// The RestyleDamage from any restyling, or RestyleDamage::rebuild_and_reflow() if this /// is the first time layout is visiting this node. We implement this here, rather than /// with the rest of the wrapper layer, because we need layout code to determine whether /// layout has visited the node. fn restyle_damage(self) -> RestyleDamage; } impl<T: ThreadSafeLayoutNode> ThreadSafeLayoutNodeHelpers for T { fn flags(self) -> LayoutDataFlags { self.borrow_layout_data().as_ref().unwrap().flags } fn
(self, new_flags: LayoutDataFlags) { self.mutate_layout_data().unwrap().flags.insert(new_flags); } fn remove_flags(self, flags: LayoutDataFlags) { self.mutate_layout_data().unwrap().flags.remove(flags); } fn text_content(&self) -> TextContent { if self.get_pseudo_element_type().is_replaced_content() { let style = self.as_element().unwrap().resolved_style(); return match style.as_ref().get_counters().content { content::T::Items(ref value) if!value.is_empty() => { TextContent::GeneratedContent((*value).clone()) } _ => TextContent::GeneratedContent(vec![]), }; } return TextContent::Text(self.node_text_content()); } fn restyle_damage(self) -> RestyleDamage { // We need the underlying node to potentially access the parent in the // case of text nodes. This is safe as long as we don't let the parent // escape and never access its descendants. let mut node = unsafe { self.unsafe_get() }; // If this is a text node, use the parent element, since that's what // controls our style. if node.is_text_node() { node = node.parent_node().unwrap(); debug_assert!(node.is_element()); } let damage = { let data = node.get_raw_data().unwrap(); if let Some(r) = data.style_data.element_data.borrow().get_restyle() { // We're reflowing a node that just got a restyle, and so the // damage has been computed and stored in the RestyleData. r.damage } else if!data.layout_data.borrow().flags.contains(::data::HAS_BEEN_TRAVERSED) { // We're reflowing a node that was styled for the first time and // has never been visited by layout. Return rebuild_and_reflow, // because that's what the code expects. RestyleDamage::rebuild_and_reflow() } else { // We're reflowing a node whose style data didn't change, but whose // layout may change due to changes in ancestors or descendants. RestyleDamage::empty() } }; damage } } pub enum TextContent { Text(String), GeneratedContent(Vec<ContentItem>), } impl TextContent { pub fn is_empty(&self) -> bool { match *self { TextContent::Text(_) => false, TextContent::GeneratedContent(ref content) => content.is_empty(), } } }
insert_flags
identifier_name
wrapper.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 safe wrapper for DOM nodes that prevents layout from mutating the DOM, from letting DOM nodes //! escape, and from generally doing anything that it isn't supposed to. This is accomplished via //! a simple whitelist of allowed operations, along with some lifetime magic to prevent nodes from //! escaping. //! //! As a security wrapper is only as good as its whitelist, be careful when adding operations to //! this list. The cardinal rules are: //! //! 1. Layout is not allowed to mutate the DOM. //! //! 2. Layout is not allowed to see anything with `LayoutJS` in the name, because it could hang //! onto these objects and cause use-after-free. //! //! When implementing wrapper functions, be careful that you do not touch the borrow flags, or you //! will race and cause spurious thread failure. (Note that I do not believe these races are //! exploitable, but they'll result in brokenness nonetheless.) //! //! Rules of the road for this file: //! //! * Do not call any methods on DOM nodes without checking to see whether they use borrow flags. //! //! o Instead of `get_attr()`, use `.get_attr_val_for_layout()`. //! //! o Instead of `html_element_in_html_document()`, use //! `html_element_in_html_document_for_layout()`. #![allow(unsafe_code)] use atomic_refcell::{AtomicRef, AtomicRefMut}; use core::nonzero::NonZero; use data::{LayoutData, LayoutDataFlags, StyleAndLayoutData}; use script_layout_interface::{OpaqueStyleAndLayoutData, StyleData}; use script_layout_interface::wrapper_traits::{LayoutNode, ThreadSafeLayoutElement, ThreadSafeLayoutNode}; use script_layout_interface::wrapper_traits::GetLayoutData; use style::computed_values::content::{self, ContentItem}; use style::dom::{NodeInfo, TNode}; use style::selector_parser::RestyleDamage; pub unsafe fn drop_style_and_layout_data(data: OpaqueStyleAndLayoutData) { let ptr: *mut StyleData = data.ptr.get(); let non_opaque: *mut StyleAndLayoutData = ptr as *mut _; let _ = Box::from_raw(non_opaque); } pub trait LayoutNodeLayoutData { /// Similar to borrow_data*, but returns the full PersistentLayoutData rather /// than only the style::data::ElementData. fn borrow_layout_data(&self) -> Option<AtomicRef<LayoutData>>; fn mutate_layout_data(&self) -> Option<AtomicRefMut<LayoutData>>; fn flow_debug_id(self) -> usize; } impl<T: GetLayoutData> LayoutNodeLayoutData for T { fn borrow_layout_data(&self) -> Option<AtomicRef<LayoutData>> { self.get_raw_data().map(|d| d.layout_data.borrow()) } fn mutate_layout_data(&self) -> Option<AtomicRefMut<LayoutData>> { self.get_raw_data().map(|d| d.layout_data.borrow_mut()) } fn flow_debug_id(self) -> usize { self.borrow_layout_data().map_or(0, |d| d.flow_construction_result.debug_id()) } } pub trait GetRawData { fn get_raw_data(&self) -> Option<&StyleAndLayoutData>; } impl<T: GetLayoutData> GetRawData for T { fn get_raw_data(&self) -> Option<&StyleAndLayoutData> { self.get_style_and_layout_data().map(|opaque| { let container = opaque.ptr.get() as *mut StyleAndLayoutData; unsafe { &*container } }) } } pub trait LayoutNodeHelpers { fn initialize_data(&self); fn clear_data(&self); } impl<T: LayoutNode> LayoutNodeHelpers for T { fn initialize_data(&self) { if self.get_raw_data().is_none() { let ptr: *mut StyleAndLayoutData = Box::into_raw(Box::new(StyleAndLayoutData::new())); let opaque = OpaqueStyleAndLayoutData { ptr: unsafe { NonZero::new(ptr as *mut StyleData) } }; unsafe { self.init_style_and_layout_data(opaque) }; }; } fn clear_data(&self) { if self.get_raw_data().is_some()
} } pub trait ThreadSafeLayoutNodeHelpers { /// Returns the layout data flags for this node. fn flags(self) -> LayoutDataFlags; /// Adds the given flags to this node. fn insert_flags(self, new_flags: LayoutDataFlags); /// Removes the given flags from this node. fn remove_flags(self, flags: LayoutDataFlags); /// If this is a text node, generated content, or a form element, copies out /// its content. Otherwise, panics. /// /// FIXME(pcwalton): This might have too much copying and/or allocation. Profile this. fn text_content(&self) -> TextContent; /// The RestyleDamage from any restyling, or RestyleDamage::rebuild_and_reflow() if this /// is the first time layout is visiting this node. We implement this here, rather than /// with the rest of the wrapper layer, because we need layout code to determine whether /// layout has visited the node. fn restyle_damage(self) -> RestyleDamage; } impl<T: ThreadSafeLayoutNode> ThreadSafeLayoutNodeHelpers for T { fn flags(self) -> LayoutDataFlags { self.borrow_layout_data().as_ref().unwrap().flags } fn insert_flags(self, new_flags: LayoutDataFlags) { self.mutate_layout_data().unwrap().flags.insert(new_flags); } fn remove_flags(self, flags: LayoutDataFlags) { self.mutate_layout_data().unwrap().flags.remove(flags); } fn text_content(&self) -> TextContent { if self.get_pseudo_element_type().is_replaced_content() { let style = self.as_element().unwrap().resolved_style(); return match style.as_ref().get_counters().content { content::T::Items(ref value) if!value.is_empty() => { TextContent::GeneratedContent((*value).clone()) } _ => TextContent::GeneratedContent(vec![]), }; } return TextContent::Text(self.node_text_content()); } fn restyle_damage(self) -> RestyleDamage { // We need the underlying node to potentially access the parent in the // case of text nodes. This is safe as long as we don't let the parent // escape and never access its descendants. let mut node = unsafe { self.unsafe_get() }; // If this is a text node, use the parent element, since that's what // controls our style. if node.is_text_node() { node = node.parent_node().unwrap(); debug_assert!(node.is_element()); } let damage = { let data = node.get_raw_data().unwrap(); if let Some(r) = data.style_data.element_data.borrow().get_restyle() { // We're reflowing a node that just got a restyle, and so the // damage has been computed and stored in the RestyleData. r.damage } else if!data.layout_data.borrow().flags.contains(::data::HAS_BEEN_TRAVERSED) { // We're reflowing a node that was styled for the first time and // has never been visited by layout. Return rebuild_and_reflow, // because that's what the code expects. RestyleDamage::rebuild_and_reflow() } else { // We're reflowing a node whose style data didn't change, but whose // layout may change due to changes in ancestors or descendants. RestyleDamage::empty() } }; damage } } pub enum TextContent { Text(String), GeneratedContent(Vec<ContentItem>), } impl TextContent { pub fn is_empty(&self) -> bool { match *self { TextContent::Text(_) => false, TextContent::GeneratedContent(ref content) => content.is_empty(), } } }
{ unsafe { drop_style_and_layout_data(self.take_style_and_layout_data()) }; }
conditional_block
wrapper.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 safe wrapper for DOM nodes that prevents layout from mutating the DOM, from letting DOM nodes //! escape, and from generally doing anything that it isn't supposed to. This is accomplished via //! a simple whitelist of allowed operations, along with some lifetime magic to prevent nodes from //! escaping. //! //! As a security wrapper is only as good as its whitelist, be careful when adding operations to //! this list. The cardinal rules are: //! //! 1. Layout is not allowed to mutate the DOM. //! //! 2. Layout is not allowed to see anything with `LayoutJS` in the name, because it could hang //! onto these objects and cause use-after-free. //! //! When implementing wrapper functions, be careful that you do not touch the borrow flags, or you //! will race and cause spurious thread failure. (Note that I do not believe these races are //! exploitable, but they'll result in brokenness nonetheless.) //! //! Rules of the road for this file: //! //! * Do not call any methods on DOM nodes without checking to see whether they use borrow flags. //! //! o Instead of `get_attr()`, use `.get_attr_val_for_layout()`. //! //! o Instead of `html_element_in_html_document()`, use //! `html_element_in_html_document_for_layout()`. #![allow(unsafe_code)] use atomic_refcell::{AtomicRef, AtomicRefMut}; use core::nonzero::NonZero; use data::{LayoutData, LayoutDataFlags, StyleAndLayoutData}; use script_layout_interface::{OpaqueStyleAndLayoutData, StyleData}; use script_layout_interface::wrapper_traits::{LayoutNode, ThreadSafeLayoutElement, ThreadSafeLayoutNode}; use script_layout_interface::wrapper_traits::GetLayoutData; use style::computed_values::content::{self, ContentItem}; use style::dom::{NodeInfo, TNode}; use style::selector_parser::RestyleDamage; pub unsafe fn drop_style_and_layout_data(data: OpaqueStyleAndLayoutData) { let ptr: *mut StyleData = data.ptr.get(); let non_opaque: *mut StyleAndLayoutData = ptr as *mut _; let _ = Box::from_raw(non_opaque); } pub trait LayoutNodeLayoutData { /// Similar to borrow_data*, but returns the full PersistentLayoutData rather /// than only the style::data::ElementData. fn borrow_layout_data(&self) -> Option<AtomicRef<LayoutData>>; fn mutate_layout_data(&self) -> Option<AtomicRefMut<LayoutData>>; fn flow_debug_id(self) -> usize; } impl<T: GetLayoutData> LayoutNodeLayoutData for T { fn borrow_layout_data(&self) -> Option<AtomicRef<LayoutData>>
fn mutate_layout_data(&self) -> Option<AtomicRefMut<LayoutData>> { self.get_raw_data().map(|d| d.layout_data.borrow_mut()) } fn flow_debug_id(self) -> usize { self.borrow_layout_data().map_or(0, |d| d.flow_construction_result.debug_id()) } } pub trait GetRawData { fn get_raw_data(&self) -> Option<&StyleAndLayoutData>; } impl<T: GetLayoutData> GetRawData for T { fn get_raw_data(&self) -> Option<&StyleAndLayoutData> { self.get_style_and_layout_data().map(|opaque| { let container = opaque.ptr.get() as *mut StyleAndLayoutData; unsafe { &*container } }) } } pub trait LayoutNodeHelpers { fn initialize_data(&self); fn clear_data(&self); } impl<T: LayoutNode> LayoutNodeHelpers for T { fn initialize_data(&self) { if self.get_raw_data().is_none() { let ptr: *mut StyleAndLayoutData = Box::into_raw(Box::new(StyleAndLayoutData::new())); let opaque = OpaqueStyleAndLayoutData { ptr: unsafe { NonZero::new(ptr as *mut StyleData) } }; unsafe { self.init_style_and_layout_data(opaque) }; }; } fn clear_data(&self) { if self.get_raw_data().is_some() { unsafe { drop_style_and_layout_data(self.take_style_and_layout_data()) }; } } } pub trait ThreadSafeLayoutNodeHelpers { /// Returns the layout data flags for this node. fn flags(self) -> LayoutDataFlags; /// Adds the given flags to this node. fn insert_flags(self, new_flags: LayoutDataFlags); /// Removes the given flags from this node. fn remove_flags(self, flags: LayoutDataFlags); /// If this is a text node, generated content, or a form element, copies out /// its content. Otherwise, panics. /// /// FIXME(pcwalton): This might have too much copying and/or allocation. Profile this. fn text_content(&self) -> TextContent; /// The RestyleDamage from any restyling, or RestyleDamage::rebuild_and_reflow() if this /// is the first time layout is visiting this node. We implement this here, rather than /// with the rest of the wrapper layer, because we need layout code to determine whether /// layout has visited the node. fn restyle_damage(self) -> RestyleDamage; } impl<T: ThreadSafeLayoutNode> ThreadSafeLayoutNodeHelpers for T { fn flags(self) -> LayoutDataFlags { self.borrow_layout_data().as_ref().unwrap().flags } fn insert_flags(self, new_flags: LayoutDataFlags) { self.mutate_layout_data().unwrap().flags.insert(new_flags); } fn remove_flags(self, flags: LayoutDataFlags) { self.mutate_layout_data().unwrap().flags.remove(flags); } fn text_content(&self) -> TextContent { if self.get_pseudo_element_type().is_replaced_content() { let style = self.as_element().unwrap().resolved_style(); return match style.as_ref().get_counters().content { content::T::Items(ref value) if!value.is_empty() => { TextContent::GeneratedContent((*value).clone()) } _ => TextContent::GeneratedContent(vec![]), }; } return TextContent::Text(self.node_text_content()); } fn restyle_damage(self) -> RestyleDamage { // We need the underlying node to potentially access the parent in the // case of text nodes. This is safe as long as we don't let the parent // escape and never access its descendants. let mut node = unsafe { self.unsafe_get() }; // If this is a text node, use the parent element, since that's what // controls our style. if node.is_text_node() { node = node.parent_node().unwrap(); debug_assert!(node.is_element()); } let damage = { let data = node.get_raw_data().unwrap(); if let Some(r) = data.style_data.element_data.borrow().get_restyle() { // We're reflowing a node that just got a restyle, and so the // damage has been computed and stored in the RestyleData. r.damage } else if!data.layout_data.borrow().flags.contains(::data::HAS_BEEN_TRAVERSED) { // We're reflowing a node that was styled for the first time and // has never been visited by layout. Return rebuild_and_reflow, // because that's what the code expects. RestyleDamage::rebuild_and_reflow() } else { // We're reflowing a node whose style data didn't change, but whose // layout may change due to changes in ancestors or descendants. RestyleDamage::empty() } }; damage } } pub enum TextContent { Text(String), GeneratedContent(Vec<ContentItem>), } impl TextContent { pub fn is_empty(&self) -> bool { match *self { TextContent::Text(_) => false, TextContent::GeneratedContent(ref content) => content.is_empty(), } } }
{ self.get_raw_data().map(|d| d.layout_data.borrow()) }
identifier_body
subresource_integrity.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 base64; use net_traits::response::{Response, ResponseBody, ResponseType}; use openssl::hash::{MessageDigest, hash}; use std::iter::Filter; use std::str::Split; use std::sync::MutexGuard; const SUPPORTED_ALGORITHM: &'static [&'static str] = &[ "sha256", "sha384", "sha512", ]; pub type StaticCharVec = &'static [char]; /// A "space character" according to: /// /// https://html.spec.whatwg.org/multipage/#space-character pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[ '\u{0020}', '\u{0009}', '\u{000a}', '\u{000c}', '\u{000d}', ]; #[derive(Clone)] pub struct SriEntry { pub alg: String, pub val: String, // TODO : Current version of spec does not define any option. // Can be refactored into appropriate datastructure when future // spec has more details. pub opt: Option<String>, } impl SriEntry { pub fn new(alg: &str, val: &str, opt: Option<String>) -> SriEntry { SriEntry { alg: alg.to_owned(), val: val.to_owned(), opt: opt, } } } /// https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata pub fn parsed_metadata(integrity_metadata: &str) -> Vec<SriEntry> { // Step 1 let mut result = vec![]; // Step 3 let tokens = split_html_space_chars(integrity_metadata); for token in tokens { let parsed_data: Vec<&str> = token.split("-").collect(); if parsed_data.len() > 1 { let alg = parsed_data[0]; if!SUPPORTED_ALGORITHM.contains(&alg) { continue; } let data: Vec<&str> = parsed_data[1].split("?").collect(); let digest = data[0]; let opt = if data.len() > 1 { Some(data[1].to_owned()) } else { None }; result.push(SriEntry::new(alg, digest, opt)); } } return result; } /// https://w3c.github.io/webappsec-subresource-integrity/#getprioritizedhashfunction pub fn get_prioritized_hash_function(hash_func_left: &str, hash_func_right: &str) -> Option<String> { let left_priority = SUPPORTED_ALGORITHM.iter().position(|s| s.to_owned() == hash_func_left).unwrap(); let right_priority = SUPPORTED_ALGORITHM.iter().position(|s| s.to_owned() == hash_func_right).unwrap(); if left_priority == right_priority { return None; } if left_priority > right_priority { Some(hash_func_left.to_owned()) } else { Some(hash_func_right.to_owned()) } } /// https://w3c.github.io/webappsec-subresource-integrity/#get-the-strongest-metadata pub fn get_strongest_metadata(integrity_metadata_list: Vec<SriEntry>) -> Vec<SriEntry> { let mut result: Vec<SriEntry> = vec![integrity_metadata_list[0].clone()]; let mut current_algorithm = result[0].alg.clone(); for integrity_metadata in &integrity_metadata_list[1..] { let prioritized_hash = get_prioritized_hash_function(&integrity_metadata.alg, &*current_algorithm); if prioritized_hash.is_none() { result.push(integrity_metadata.clone()); } else if let Some(algorithm) = prioritized_hash { if algorithm!= current_algorithm { result = vec![integrity_metadata.clone()]; current_algorithm = algorithm; } } } result } /// https://w3c.github.io/webappsec-subresource-integrity/#apply-algorithm-to-response fn apply_algorithm_to_response(body: MutexGuard<ResponseBody>, message_digest: MessageDigest) -> String { if let ResponseBody::Done(ref vec) = *body { let response_digest = hash(message_digest, vec).unwrap(); base64::encode(&response_digest) } else { unreachable!("Tried to calculate digest of incomplete response body") } } /// https://w3c.github.io/webappsec-subresource-integrity/#is-response-eligible fn is_eligible_for_integrity_validation(response: &Response) -> bool { match response.response_type { ResponseType::Basic | ResponseType::Default | ResponseType::Cors => true, _ => false, } } /// https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist pub fn is_response_integrity_valid(integrity_metadata: &str, response: &Response) -> bool { let parsed_metadata_list: Vec<SriEntry> = parsed_metadata(integrity_metadata); // Step 2 & 4 if parsed_metadata_list.is_empty() { return true; } // Step 3 if!is_eligible_for_integrity_validation(response) { return false; } // Step 5 let metadata: Vec<SriEntry> = get_strongest_metadata(parsed_metadata_list); for item in metadata { let body = response.body.lock().unwrap(); let algorithm = item.alg; let digest = item.val; let message_digest = match &*algorithm { "sha256" => MessageDigest::sha256(), "sha384" => MessageDigest::sha384(), "sha512" => MessageDigest::sha512(), _ => continue, }; if apply_algorithm_to_response(body, message_digest) == digest { return true; } } false } pub fn split_html_space_chars<'a>(s: &'a str) ->
fn not_empty(&split: &&str) -> bool {!split.is_empty() } s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool) }
Filter<Split<'a, StaticCharVec>, fn(&&str) -> bool> {
random_line_split
subresource_integrity.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 base64; use net_traits::response::{Response, ResponseBody, ResponseType}; use openssl::hash::{MessageDigest, hash}; use std::iter::Filter; use std::str::Split; use std::sync::MutexGuard; const SUPPORTED_ALGORITHM: &'static [&'static str] = &[ "sha256", "sha384", "sha512", ]; pub type StaticCharVec = &'static [char]; /// A "space character" according to: /// /// https://html.spec.whatwg.org/multipage/#space-character pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[ '\u{0020}', '\u{0009}', '\u{000a}', '\u{000c}', '\u{000d}', ]; #[derive(Clone)] pub struct SriEntry { pub alg: String, pub val: String, // TODO : Current version of spec does not define any option. // Can be refactored into appropriate datastructure when future // spec has more details. pub opt: Option<String>, } impl SriEntry { pub fn new(alg: &str, val: &str, opt: Option<String>) -> SriEntry { SriEntry { alg: alg.to_owned(), val: val.to_owned(), opt: opt, } } } /// https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata pub fn parsed_metadata(integrity_metadata: &str) -> Vec<SriEntry> { // Step 1 let mut result = vec![]; // Step 3 let tokens = split_html_space_chars(integrity_metadata); for token in tokens { let parsed_data: Vec<&str> = token.split("-").collect(); if parsed_data.len() > 1 { let alg = parsed_data[0]; if!SUPPORTED_ALGORITHM.contains(&alg) { continue; } let data: Vec<&str> = parsed_data[1].split("?").collect(); let digest = data[0]; let opt = if data.len() > 1 { Some(data[1].to_owned()) } else { None }; result.push(SriEntry::new(alg, digest, opt)); } } return result; } /// https://w3c.github.io/webappsec-subresource-integrity/#getprioritizedhashfunction pub fn get_prioritized_hash_function(hash_func_left: &str, hash_func_right: &str) -> Option<String> { let left_priority = SUPPORTED_ALGORITHM.iter().position(|s| s.to_owned() == hash_func_left).unwrap(); let right_priority = SUPPORTED_ALGORITHM.iter().position(|s| s.to_owned() == hash_func_right).unwrap(); if left_priority == right_priority { return None; } if left_priority > right_priority
else { Some(hash_func_right.to_owned()) } } /// https://w3c.github.io/webappsec-subresource-integrity/#get-the-strongest-metadata pub fn get_strongest_metadata(integrity_metadata_list: Vec<SriEntry>) -> Vec<SriEntry> { let mut result: Vec<SriEntry> = vec![integrity_metadata_list[0].clone()]; let mut current_algorithm = result[0].alg.clone(); for integrity_metadata in &integrity_metadata_list[1..] { let prioritized_hash = get_prioritized_hash_function(&integrity_metadata.alg, &*current_algorithm); if prioritized_hash.is_none() { result.push(integrity_metadata.clone()); } else if let Some(algorithm) = prioritized_hash { if algorithm!= current_algorithm { result = vec![integrity_metadata.clone()]; current_algorithm = algorithm; } } } result } /// https://w3c.github.io/webappsec-subresource-integrity/#apply-algorithm-to-response fn apply_algorithm_to_response(body: MutexGuard<ResponseBody>, message_digest: MessageDigest) -> String { if let ResponseBody::Done(ref vec) = *body { let response_digest = hash(message_digest, vec).unwrap(); base64::encode(&response_digest) } else { unreachable!("Tried to calculate digest of incomplete response body") } } /// https://w3c.github.io/webappsec-subresource-integrity/#is-response-eligible fn is_eligible_for_integrity_validation(response: &Response) -> bool { match response.response_type { ResponseType::Basic | ResponseType::Default | ResponseType::Cors => true, _ => false, } } /// https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist pub fn is_response_integrity_valid(integrity_metadata: &str, response: &Response) -> bool { let parsed_metadata_list: Vec<SriEntry> = parsed_metadata(integrity_metadata); // Step 2 & 4 if parsed_metadata_list.is_empty() { return true; } // Step 3 if!is_eligible_for_integrity_validation(response) { return false; } // Step 5 let metadata: Vec<SriEntry> = get_strongest_metadata(parsed_metadata_list); for item in metadata { let body = response.body.lock().unwrap(); let algorithm = item.alg; let digest = item.val; let message_digest = match &*algorithm { "sha256" => MessageDigest::sha256(), "sha384" => MessageDigest::sha384(), "sha512" => MessageDigest::sha512(), _ => continue, }; if apply_algorithm_to_response(body, message_digest) == digest { return true; } } false } pub fn split_html_space_chars<'a>(s: &'a str) -> Filter<Split<'a, StaticCharVec>, fn(&&str) -> bool> { fn not_empty(&split: &&str) -> bool {!split.is_empty() } s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool) }
{ Some(hash_func_left.to_owned()) }
conditional_block
subresource_integrity.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 base64; use net_traits::response::{Response, ResponseBody, ResponseType}; use openssl::hash::{MessageDigest, hash}; use std::iter::Filter; use std::str::Split; use std::sync::MutexGuard; const SUPPORTED_ALGORITHM: &'static [&'static str] = &[ "sha256", "sha384", "sha512", ]; pub type StaticCharVec = &'static [char]; /// A "space character" according to: /// /// https://html.spec.whatwg.org/multipage/#space-character pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[ '\u{0020}', '\u{0009}', '\u{000a}', '\u{000c}', '\u{000d}', ]; #[derive(Clone)] pub struct SriEntry { pub alg: String, pub val: String, // TODO : Current version of spec does not define any option. // Can be refactored into appropriate datastructure when future // spec has more details. pub opt: Option<String>, } impl SriEntry { pub fn new(alg: &str, val: &str, opt: Option<String>) -> SriEntry { SriEntry { alg: alg.to_owned(), val: val.to_owned(), opt: opt, } } } /// https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata pub fn parsed_metadata(integrity_metadata: &str) -> Vec<SriEntry> { // Step 1 let mut result = vec![]; // Step 3 let tokens = split_html_space_chars(integrity_metadata); for token in tokens { let parsed_data: Vec<&str> = token.split("-").collect(); if parsed_data.len() > 1 { let alg = parsed_data[0]; if!SUPPORTED_ALGORITHM.contains(&alg) { continue; } let data: Vec<&str> = parsed_data[1].split("?").collect(); let digest = data[0]; let opt = if data.len() > 1 { Some(data[1].to_owned()) } else { None }; result.push(SriEntry::new(alg, digest, opt)); } } return result; } /// https://w3c.github.io/webappsec-subresource-integrity/#getprioritizedhashfunction pub fn get_prioritized_hash_function(hash_func_left: &str, hash_func_right: &str) -> Option<String> { let left_priority = SUPPORTED_ALGORITHM.iter().position(|s| s.to_owned() == hash_func_left).unwrap(); let right_priority = SUPPORTED_ALGORITHM.iter().position(|s| s.to_owned() == hash_func_right).unwrap(); if left_priority == right_priority { return None; } if left_priority > right_priority { Some(hash_func_left.to_owned()) } else { Some(hash_func_right.to_owned()) } } /// https://w3c.github.io/webappsec-subresource-integrity/#get-the-strongest-metadata pub fn get_strongest_metadata(integrity_metadata_list: Vec<SriEntry>) -> Vec<SriEntry> { let mut result: Vec<SriEntry> = vec![integrity_metadata_list[0].clone()]; let mut current_algorithm = result[0].alg.clone(); for integrity_metadata in &integrity_metadata_list[1..] { let prioritized_hash = get_prioritized_hash_function(&integrity_metadata.alg, &*current_algorithm); if prioritized_hash.is_none() { result.push(integrity_metadata.clone()); } else if let Some(algorithm) = prioritized_hash { if algorithm!= current_algorithm { result = vec![integrity_metadata.clone()]; current_algorithm = algorithm; } } } result } /// https://w3c.github.io/webappsec-subresource-integrity/#apply-algorithm-to-response fn apply_algorithm_to_response(body: MutexGuard<ResponseBody>, message_digest: MessageDigest) -> String { if let ResponseBody::Done(ref vec) = *body { let response_digest = hash(message_digest, vec).unwrap(); base64::encode(&response_digest) } else { unreachable!("Tried to calculate digest of incomplete response body") } } /// https://w3c.github.io/webappsec-subresource-integrity/#is-response-eligible fn is_eligible_for_integrity_validation(response: &Response) -> bool { match response.response_type { ResponseType::Basic | ResponseType::Default | ResponseType::Cors => true, _ => false, } } /// https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist pub fn
(integrity_metadata: &str, response: &Response) -> bool { let parsed_metadata_list: Vec<SriEntry> = parsed_metadata(integrity_metadata); // Step 2 & 4 if parsed_metadata_list.is_empty() { return true; } // Step 3 if!is_eligible_for_integrity_validation(response) { return false; } // Step 5 let metadata: Vec<SriEntry> = get_strongest_metadata(parsed_metadata_list); for item in metadata { let body = response.body.lock().unwrap(); let algorithm = item.alg; let digest = item.val; let message_digest = match &*algorithm { "sha256" => MessageDigest::sha256(), "sha384" => MessageDigest::sha384(), "sha512" => MessageDigest::sha512(), _ => continue, }; if apply_algorithm_to_response(body, message_digest) == digest { return true; } } false } pub fn split_html_space_chars<'a>(s: &'a str) -> Filter<Split<'a, StaticCharVec>, fn(&&str) -> bool> { fn not_empty(&split: &&str) -> bool {!split.is_empty() } s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool) }
is_response_integrity_valid
identifier_name
htmldialogelement.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::HTMLDialogElementBinding; use dom::bindings::codegen::Bindings::HTMLDialogElementBinding::HTMLDialogElementMethods; use dom::bindings::js::Root; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use string_cache::Atom; use util::str::DOMString; #[dom_struct] pub struct HTMLDialogElement { htmlelement: HTMLElement, return_value: DOMRefCell<DOMString>, } impl HTMLDialogElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLDialogElement { HTMLDialogElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document), return_value: DOMRefCell::new(DOMString::new()), } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>,
document: &Document) -> Root<HTMLDialogElement> { let element = HTMLDialogElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLDialogElementBinding::Wrap) } } impl HTMLDialogElementMethods for HTMLDialogElement { // https://html.spec.whatwg.org/multipage/#dom-dialog-open make_bool_getter!(Open, "open"); // https://html.spec.whatwg.org/multipage/#dom-dialog-open make_bool_setter!(SetOpen, "open"); // https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue fn ReturnValue(&self) -> DOMString { let return_value = self.return_value.borrow(); return_value.clone() } // https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue fn SetReturnValue(&self, return_value: DOMString) { *self.return_value.borrow_mut() = return_value; } }
random_line_split
htmldialogelement.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::HTMLDialogElementBinding; use dom::bindings::codegen::Bindings::HTMLDialogElementBinding::HTMLDialogElementMethods; use dom::bindings::js::Root; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use string_cache::Atom; use util::str::DOMString; #[dom_struct] pub struct HTMLDialogElement { htmlelement: HTMLElement, return_value: DOMRefCell<DOMString>, } impl HTMLDialogElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLDialogElement { HTMLDialogElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document), return_value: DOMRefCell::new(DOMString::new()), } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLDialogElement> { let element = HTMLDialogElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLDialogElementBinding::Wrap) } } impl HTMLDialogElementMethods for HTMLDialogElement { // https://html.spec.whatwg.org/multipage/#dom-dialog-open make_bool_getter!(Open, "open"); // https://html.spec.whatwg.org/multipage/#dom-dialog-open make_bool_setter!(SetOpen, "open"); // https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue fn ReturnValue(&self) -> DOMString { let return_value = self.return_value.borrow(); return_value.clone() } // https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue fn
(&self, return_value: DOMString) { *self.return_value.borrow_mut() = return_value; } }
SetReturnValue
identifier_name
htmldialogelement.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::HTMLDialogElementBinding; use dom::bindings::codegen::Bindings::HTMLDialogElementBinding::HTMLDialogElementMethods; use dom::bindings::js::Root; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use string_cache::Atom; use util::str::DOMString; #[dom_struct] pub struct HTMLDialogElement { htmlelement: HTMLElement, return_value: DOMRefCell<DOMString>, } impl HTMLDialogElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLDialogElement { HTMLDialogElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document), return_value: DOMRefCell::new(DOMString::new()), } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLDialogElement> { let element = HTMLDialogElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLDialogElementBinding::Wrap) } } impl HTMLDialogElementMethods for HTMLDialogElement { // https://html.spec.whatwg.org/multipage/#dom-dialog-open make_bool_getter!(Open, "open"); // https://html.spec.whatwg.org/multipage/#dom-dialog-open make_bool_setter!(SetOpen, "open"); // https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue fn ReturnValue(&self) -> DOMString { let return_value = self.return_value.borrow(); return_value.clone() } // https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue fn SetReturnValue(&self, return_value: DOMString)
}
{ *self.return_value.borrow_mut() = return_value; }
identifier_body
tokens.rs
use slp_shared::*; #[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Debug, Clone)] pub struct Identifier(pub String); #[derive(PartialEq, Debug, Clone)] pub enum FollowedBy { Token, Whitespace, } #[derive(PartialEq, Debug, Clone)] pub enum RegisterSlot { T(u32), U(u32), B(u32), S(u32), } #[derive(PartialEq, Debug, Clone)] pub enum OffsetSlot { T(u32), U(u32), B(u32), } #[derive(PartialEq, Debug, Clone)] pub enum Token { Eof, // Marks the end of a stream Id(Identifier), LiteralInt(u64), // Int (Hlsl ints do not have sign, the - is an operator on the literal) LiteralUInt(u64), // Int with explicit unsigned type LiteralLong(u64), // Int with explicit long type LiteralHalf(f32), LiteralFloat(f32), LiteralDouble(f64), True, False, LeftBrace, RightBrace, LeftParen, RightParen, LeftSquareBracket, RightSquareBracket, LeftAngleBracket(FollowedBy), RightAngleBracket(FollowedBy), Semicolon, Comma, QuestionMark, Plus, Minus, ForwardSlash, Percent, Asterix, VerticalBar(FollowedBy), Ampersand(FollowedBy), Hat, Equals, Hash, At, ExclamationPoint, Tilde, Period, DoubleEquals, ExclamationEquals, If, Else, For, While, Switch, Return, Break, Continue, Struct, SamplerState, ConstantBuffer, Register(RegisterSlot), PackOffset(OffsetSlot), Colon, In, Out, InOut, Const, Extern, Static, GroupShared, Auto, Case, Catch, Char, Class, ConstCast, Default, Delete, DynamicCast, Enum, Explicit, Friend, Goto, Long, Mutable, New, Operator, Private, Protected, Public, ReinterpretCast, Short, Signed, SizeOf, StaticCast, Template, This, Throw, Try, Typename, Union, Unsigned, Using, Virtual, } #[derive(PartialEq, Debug, Clone)] pub struct LexToken(pub Token, pub FileLocation); impl LexToken { pub fn to_loc(self) -> FileLocation { self.1 } pub fn with_no_loc(token: Token) -> LexToken
} #[derive(PartialEq, Debug, Clone)] pub struct Tokens { pub stream: Vec<LexToken>, }
{ LexToken(token, FileLocation::none()) }
identifier_body
tokens.rs
use slp_shared::*; #[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Debug, Clone)] pub struct
(pub String); #[derive(PartialEq, Debug, Clone)] pub enum FollowedBy { Token, Whitespace, } #[derive(PartialEq, Debug, Clone)] pub enum RegisterSlot { T(u32), U(u32), B(u32), S(u32), } #[derive(PartialEq, Debug, Clone)] pub enum OffsetSlot { T(u32), U(u32), B(u32), } #[derive(PartialEq, Debug, Clone)] pub enum Token { Eof, // Marks the end of a stream Id(Identifier), LiteralInt(u64), // Int (Hlsl ints do not have sign, the - is an operator on the literal) LiteralUInt(u64), // Int with explicit unsigned type LiteralLong(u64), // Int with explicit long type LiteralHalf(f32), LiteralFloat(f32), LiteralDouble(f64), True, False, LeftBrace, RightBrace, LeftParen, RightParen, LeftSquareBracket, RightSquareBracket, LeftAngleBracket(FollowedBy), RightAngleBracket(FollowedBy), Semicolon, Comma, QuestionMark, Plus, Minus, ForwardSlash, Percent, Asterix, VerticalBar(FollowedBy), Ampersand(FollowedBy), Hat, Equals, Hash, At, ExclamationPoint, Tilde, Period, DoubleEquals, ExclamationEquals, If, Else, For, While, Switch, Return, Break, Continue, Struct, SamplerState, ConstantBuffer, Register(RegisterSlot), PackOffset(OffsetSlot), Colon, In, Out, InOut, Const, Extern, Static, GroupShared, Auto, Case, Catch, Char, Class, ConstCast, Default, Delete, DynamicCast, Enum, Explicit, Friend, Goto, Long, Mutable, New, Operator, Private, Protected, Public, ReinterpretCast, Short, Signed, SizeOf, StaticCast, Template, This, Throw, Try, Typename, Union, Unsigned, Using, Virtual, } #[derive(PartialEq, Debug, Clone)] pub struct LexToken(pub Token, pub FileLocation); impl LexToken { pub fn to_loc(self) -> FileLocation { self.1 } pub fn with_no_loc(token: Token) -> LexToken { LexToken(token, FileLocation::none()) } } #[derive(PartialEq, Debug, Clone)] pub struct Tokens { pub stream: Vec<LexToken>, }
Identifier
identifier_name
tokens.rs
use slp_shared::*; #[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Debug, Clone)] pub struct Identifier(pub String); #[derive(PartialEq, Debug, Clone)] pub enum FollowedBy { Token, Whitespace, } #[derive(PartialEq, Debug, Clone)] pub enum RegisterSlot { T(u32), U(u32), B(u32), S(u32), } #[derive(PartialEq, Debug, Clone)] pub enum OffsetSlot { T(u32), U(u32),
#[derive(PartialEq, Debug, Clone)] pub enum Token { Eof, // Marks the end of a stream Id(Identifier), LiteralInt(u64), // Int (Hlsl ints do not have sign, the - is an operator on the literal) LiteralUInt(u64), // Int with explicit unsigned type LiteralLong(u64), // Int with explicit long type LiteralHalf(f32), LiteralFloat(f32), LiteralDouble(f64), True, False, LeftBrace, RightBrace, LeftParen, RightParen, LeftSquareBracket, RightSquareBracket, LeftAngleBracket(FollowedBy), RightAngleBracket(FollowedBy), Semicolon, Comma, QuestionMark, Plus, Minus, ForwardSlash, Percent, Asterix, VerticalBar(FollowedBy), Ampersand(FollowedBy), Hat, Equals, Hash, At, ExclamationPoint, Tilde, Period, DoubleEquals, ExclamationEquals, If, Else, For, While, Switch, Return, Break, Continue, Struct, SamplerState, ConstantBuffer, Register(RegisterSlot), PackOffset(OffsetSlot), Colon, In, Out, InOut, Const, Extern, Static, GroupShared, Auto, Case, Catch, Char, Class, ConstCast, Default, Delete, DynamicCast, Enum, Explicit, Friend, Goto, Long, Mutable, New, Operator, Private, Protected, Public, ReinterpretCast, Short, Signed, SizeOf, StaticCast, Template, This, Throw, Try, Typename, Union, Unsigned, Using, Virtual, } #[derive(PartialEq, Debug, Clone)] pub struct LexToken(pub Token, pub FileLocation); impl LexToken { pub fn to_loc(self) -> FileLocation { self.1 } pub fn with_no_loc(token: Token) -> LexToken { LexToken(token, FileLocation::none()) } } #[derive(PartialEq, Debug, Clone)] pub struct Tokens { pub stream: Vec<LexToken>, }
B(u32), }
random_line_split
unrooted_must_root.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 rustc::hir; use rustc::hir::intravisit as visit; use rustc::hir::map as ast_map; use rustc::lint::{LateContext, LintPass, LintArray, LateLintPass, LintContext}; use rustc::ty; use syntax::{ast, codemap}; use utils::{match_def_path, in_derive_expn}; declare_lint!(UNROOTED_MUST_ROOT, Deny, "Warn and report usage of unrooted jsmanaged objects"); /// Lint for ensuring safe usage of unrooted pointers /// /// This lint (disable with `-A unrooted-must-root`/`#[allow(unrooted_must_root)]`) ensures that `#[must_root]` /// values are used correctly. /// /// "Incorrect" usage includes: /// /// - Not being used in a struct/enum field which is not `#[must_root]` itself /// - Not being used as an argument to a function (Except onces named `new` and `new_inherited`) /// - Not being bound locally in a `let` statement, assignment, `for` loop, or `match` statement. /// /// This helps catch most situations where pointers like `JS<T>` are used in a way that they can be invalidated by a /// GC pass. /// /// Structs which have their own mechanism of rooting their unrooted contents (e.g. `ScriptThread`) /// can be marked as `#[allow(unrooted_must_root)]`. Smart pointers which root their interior type /// can be marked as `#[allow_unrooted_interior]` pub struct UnrootedPass; impl UnrootedPass { pub fn new() -> UnrootedPass { UnrootedPass } } /// Checks if a type is unrooted or contains any owned unrooted types fn is_unrooted_ty(cx: &LateContext, ty: &ty::TyS, in_new_function: bool) -> bool { let mut ret = false; ty.maybe_walk(|t| { match t.sty { ty::TyAdt(did, _) => { if cx.tcx.has_attr(did.did, "must_root") { ret = true; false } else if cx.tcx.has_attr(did.did, "allow_unrooted_interior") { false } else if match_def_path(cx, did.did, &["core", "cell", "Ref"]) || match_def_path(cx, did.did, &["core", "cell", "RefMut"]) || match_def_path(cx, did.did, &["core", "slice", "Iter"]) || match_def_path(cx, did.did, &["std", "collections", "hash", "map", "Entry"]) || match_def_path(cx, did.did, &["std", "collections", "hash", "map", "OccupiedEntry"]) || match_def_path(cx, did.did, &["std", "collections", "hash", "map", "VacantEntry"]) || match_def_path(cx, did.did, &["std", "collections", "hash", "set", "Iter"]) { // Structures which are semantically similar to an &ptr. false } else if did.is_box() && in_new_function { // box in new() is okay false } else { true } }, ty::TyRef(..) => false, // don't recurse down &ptrs ty::TyRawPtr(..) => false, // don't recurse down *ptrs ty::TyFnDef(..) | ty::TyFnPtr(_) => false, _ => true } }); ret } impl LintPass for UnrootedPass { fn get_lints(&self) -> LintArray { lint_array!(UNROOTED_MUST_ROOT) } } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnrootedPass { /// All structs containing #[must_root] types must be #[must_root] themselves fn check_struct_def(&mut self, cx: &LateContext, def: &hir::VariantData, _n: ast::Name, _gen: &hir::Generics, id: ast::NodeId) { let item = match cx.tcx.hir.get(id) { ast_map::Node::NodeItem(item) => item, _ => cx.tcx.hir.expect_item(cx.tcx.hir.get_parent(id)), }; if item.attrs.iter().all(|a|!a.check_name("must_root")) { for ref field in def.fields() { let def_id = cx.tcx.hir.local_def_id(field.id); if is_unrooted_ty(cx, cx.tcx.item_type(def_id), false) { cx.span_lint(UNROOTED_MUST_ROOT, field.span, "Type must be rooted, use #[must_root] on the struct definition to propagate") } } } } /// All enums containing #[must_root] types must be #[must_root] themselves fn check_variant(&mut self, cx: &LateContext, var: &hir::Variant, _gen: &hir::Generics) { let ref map = cx.tcx.hir; if map.expect_item(map.get_parent(var.node.data.id())).attrs.iter().all(|a|!a.check_name("must_root")) { match var.node.data { hir::VariantData::Tuple(ref fields, _) => { for ref field in fields { let def_id = cx.tcx.hir.local_def_id(field.id); if is_unrooted_ty(cx, cx.tcx.item_type(def_id), false) { cx.span_lint(UNROOTED_MUST_ROOT, field.ty.span, "Type must be rooted, use #[must_root] on \ the enum definition to propagate") } } } _ => () // Struct variants already caught by check_struct_def } } } /// Function arguments that are #[must_root] types are not allowed fn check_fn(&mut self, cx: &LateContext<'a, 'tcx>, kind: visit::FnKind, decl: &'tcx hir::FnDecl, body: &'tcx hir::Body, span: codemap::Span, id: ast::NodeId) { let in_new_function = match kind { visit::FnKind::ItemFn(n, _, _, _, _, _, _) | visit::FnKind::Method(n, _, _, _) => { &*n.as_str() == "new" || n.as_str().starts_with("new_") } visit::FnKind::Closure(_) => return, }; if!in_derive_expn(span) { let def_id = cx.tcx.hir.local_def_id(id); let ty = cx.tcx.item_type(def_id); for (arg, ty) in decl.inputs.iter().zip(ty.fn_args().0.iter()) { if is_unrooted_ty(cx, ty, false) { cx.span_lint(UNROOTED_MUST_ROOT, arg.span, "Type must be rooted") } } if!in_new_function { if is_unrooted_ty(cx, ty.fn_ret().0, false) { cx.span_lint(UNROOTED_MUST_ROOT, decl.output.span(), "Type must be rooted") } } } let mut visitor = FnDefVisitor { cx: cx, in_new_function: in_new_function, }; visit::walk_expr(&mut visitor, &body.value); } } struct FnDefVisitor<'a, 'b: 'a, 'tcx: 'a+'b> { cx: &'a LateContext<'b, 'tcx>, in_new_function: bool, } impl<'a, 'b, 'tcx> visit::Visitor<'tcx> for FnDefVisitor<'a, 'b, 'tcx> { fn visit_expr(&mut self, expr: &'tcx hir::Expr) { let cx = self.cx; fn require_rooted(cx: &LateContext, in_new_function: bool, subexpr: &hir::Expr) { let ty = cx.tables.expr_ty(&subexpr); if is_unrooted_ty(cx, ty, in_new_function) { cx.span_lint(UNROOTED_MUST_ROOT, subexpr.span, &format!("Expression of type {:?} must be rooted", ty)) } } match expr.node { /// Trait casts from #[must_root] types are not allowed hir::ExprCast(ref subexpr, _) => require_rooted(cx, self.in_new_function, &*subexpr), // This catches assignments... the main point of this would be to catch mutable // references to `JS<T>`. // FIXME: Enable this? Triggers on certain kinds of uses of DOMRefCell. // hir::ExprAssign(_, ref rhs) => require_rooted(cx, self.in_new_function, &*rhs), // This catches calls; basically, this enforces the constraint that only constructors // can call other constructors. // FIXME: Enable this? Currently triggers with constructs involving DOMRefCell, and // constructs like Vec<JS<T>> and RootedVec<JS<T>>. // hir::ExprCall(..) if!self.in_new_function => { // require_rooted(cx, self.in_new_function, expr); // } _ => { // TODO(pcwalton): Check generics with a whitelist of allowed generics. } } visit::walk_expr(self, expr); } fn visit_pat(&mut self, pat: &'tcx hir::Pat) { let cx = self.cx; if let hir::PatKind::Binding(hir::BindingMode::BindByValue(_), _, _, _) = pat.node { let ty = cx.tables.pat_ty(pat); if is_unrooted_ty(cx, ty, self.in_new_function) { cx.span_lint(UNROOTED_MUST_ROOT, pat.span, &format!("Expression of type {:?} must be rooted", ty)) } } visit::walk_pat(self, pat); } fn visit_fn(&mut self, kind: visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl, body: hir::BodyId, span: codemap::Span, id: ast::NodeId) { if let visit::FnKind::Closure(_) = kind { visit::walk_fn(self, kind, decl, body, span, id); } } fn
(&mut self, _: &'tcx hir::ForeignItem) {} fn visit_ty(&mut self, _: &'tcx hir::Ty) { } fn nested_visit_map<'this>(&'this mut self) -> hir::intravisit::NestedVisitorMap<'this, 'tcx> { hir::intravisit::NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir) } }
visit_foreign_item
identifier_name
unrooted_must_root.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 rustc::hir; use rustc::hir::intravisit as visit; use rustc::hir::map as ast_map; use rustc::lint::{LateContext, LintPass, LintArray, LateLintPass, LintContext}; use rustc::ty; use syntax::{ast, codemap}; use utils::{match_def_path, in_derive_expn}; declare_lint!(UNROOTED_MUST_ROOT, Deny, "Warn and report usage of unrooted jsmanaged objects"); /// Lint for ensuring safe usage of unrooted pointers /// /// This lint (disable with `-A unrooted-must-root`/`#[allow(unrooted_must_root)]`) ensures that `#[must_root]` /// values are used correctly. /// /// "Incorrect" usage includes: /// /// - Not being used in a struct/enum field which is not `#[must_root]` itself /// - Not being used as an argument to a function (Except onces named `new` and `new_inherited`) /// - Not being bound locally in a `let` statement, assignment, `for` loop, or `match` statement. /// /// This helps catch most situations where pointers like `JS<T>` are used in a way that they can be invalidated by a /// GC pass. /// /// Structs which have their own mechanism of rooting their unrooted contents (e.g. `ScriptThread`) /// can be marked as `#[allow(unrooted_must_root)]`. Smart pointers which root their interior type /// can be marked as `#[allow_unrooted_interior]` pub struct UnrootedPass; impl UnrootedPass { pub fn new() -> UnrootedPass { UnrootedPass } } /// Checks if a type is unrooted or contains any owned unrooted types fn is_unrooted_ty(cx: &LateContext, ty: &ty::TyS, in_new_function: bool) -> bool { let mut ret = false; ty.maybe_walk(|t| { match t.sty { ty::TyAdt(did, _) => { if cx.tcx.has_attr(did.did, "must_root") { ret = true; false } else if cx.tcx.has_attr(did.did, "allow_unrooted_interior") { false } else if match_def_path(cx, did.did, &["core", "cell", "Ref"]) || match_def_path(cx, did.did, &["core", "cell", "RefMut"]) || match_def_path(cx, did.did, &["core", "slice", "Iter"]) || match_def_path(cx, did.did, &["std", "collections", "hash", "map", "Entry"]) || match_def_path(cx, did.did, &["std", "collections", "hash", "map", "OccupiedEntry"]) || match_def_path(cx, did.did, &["std", "collections", "hash", "map", "VacantEntry"]) || match_def_path(cx, did.did, &["std", "collections", "hash", "set", "Iter"]) { // Structures which are semantically similar to an &ptr. false } else if did.is_box() && in_new_function { // box in new() is okay false } else { true } }, ty::TyRef(..) => false, // don't recurse down &ptrs ty::TyRawPtr(..) => false, // don't recurse down *ptrs ty::TyFnDef(..) | ty::TyFnPtr(_) => false, _ => true } }); ret } impl LintPass for UnrootedPass { fn get_lints(&self) -> LintArray
} impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnrootedPass { /// All structs containing #[must_root] types must be #[must_root] themselves fn check_struct_def(&mut self, cx: &LateContext, def: &hir::VariantData, _n: ast::Name, _gen: &hir::Generics, id: ast::NodeId) { let item = match cx.tcx.hir.get(id) { ast_map::Node::NodeItem(item) => item, _ => cx.tcx.hir.expect_item(cx.tcx.hir.get_parent(id)), }; if item.attrs.iter().all(|a|!a.check_name("must_root")) { for ref field in def.fields() { let def_id = cx.tcx.hir.local_def_id(field.id); if is_unrooted_ty(cx, cx.tcx.item_type(def_id), false) { cx.span_lint(UNROOTED_MUST_ROOT, field.span, "Type must be rooted, use #[must_root] on the struct definition to propagate") } } } } /// All enums containing #[must_root] types must be #[must_root] themselves fn check_variant(&mut self, cx: &LateContext, var: &hir::Variant, _gen: &hir::Generics) { let ref map = cx.tcx.hir; if map.expect_item(map.get_parent(var.node.data.id())).attrs.iter().all(|a|!a.check_name("must_root")) { match var.node.data { hir::VariantData::Tuple(ref fields, _) => { for ref field in fields { let def_id = cx.tcx.hir.local_def_id(field.id); if is_unrooted_ty(cx, cx.tcx.item_type(def_id), false) { cx.span_lint(UNROOTED_MUST_ROOT, field.ty.span, "Type must be rooted, use #[must_root] on \ the enum definition to propagate") } } } _ => () // Struct variants already caught by check_struct_def } } } /// Function arguments that are #[must_root] types are not allowed fn check_fn(&mut self, cx: &LateContext<'a, 'tcx>, kind: visit::FnKind, decl: &'tcx hir::FnDecl, body: &'tcx hir::Body, span: codemap::Span, id: ast::NodeId) { let in_new_function = match kind { visit::FnKind::ItemFn(n, _, _, _, _, _, _) | visit::FnKind::Method(n, _, _, _) => { &*n.as_str() == "new" || n.as_str().starts_with("new_") } visit::FnKind::Closure(_) => return, }; if!in_derive_expn(span) { let def_id = cx.tcx.hir.local_def_id(id); let ty = cx.tcx.item_type(def_id); for (arg, ty) in decl.inputs.iter().zip(ty.fn_args().0.iter()) { if is_unrooted_ty(cx, ty, false) { cx.span_lint(UNROOTED_MUST_ROOT, arg.span, "Type must be rooted") } } if!in_new_function { if is_unrooted_ty(cx, ty.fn_ret().0, false) { cx.span_lint(UNROOTED_MUST_ROOT, decl.output.span(), "Type must be rooted") } } } let mut visitor = FnDefVisitor { cx: cx, in_new_function: in_new_function, }; visit::walk_expr(&mut visitor, &body.value); } } struct FnDefVisitor<'a, 'b: 'a, 'tcx: 'a+'b> { cx: &'a LateContext<'b, 'tcx>, in_new_function: bool, } impl<'a, 'b, 'tcx> visit::Visitor<'tcx> for FnDefVisitor<'a, 'b, 'tcx> { fn visit_expr(&mut self, expr: &'tcx hir::Expr) { let cx = self.cx; fn require_rooted(cx: &LateContext, in_new_function: bool, subexpr: &hir::Expr) { let ty = cx.tables.expr_ty(&subexpr); if is_unrooted_ty(cx, ty, in_new_function) { cx.span_lint(UNROOTED_MUST_ROOT, subexpr.span, &format!("Expression of type {:?} must be rooted", ty)) } } match expr.node { /// Trait casts from #[must_root] types are not allowed hir::ExprCast(ref subexpr, _) => require_rooted(cx, self.in_new_function, &*subexpr), // This catches assignments... the main point of this would be to catch mutable // references to `JS<T>`. // FIXME: Enable this? Triggers on certain kinds of uses of DOMRefCell. // hir::ExprAssign(_, ref rhs) => require_rooted(cx, self.in_new_function, &*rhs), // This catches calls; basically, this enforces the constraint that only constructors // can call other constructors. // FIXME: Enable this? Currently triggers with constructs involving DOMRefCell, and // constructs like Vec<JS<T>> and RootedVec<JS<T>>. // hir::ExprCall(..) if!self.in_new_function => { // require_rooted(cx, self.in_new_function, expr); // } _ => { // TODO(pcwalton): Check generics with a whitelist of allowed generics. } } visit::walk_expr(self, expr); } fn visit_pat(&mut self, pat: &'tcx hir::Pat) { let cx = self.cx; if let hir::PatKind::Binding(hir::BindingMode::BindByValue(_), _, _, _) = pat.node { let ty = cx.tables.pat_ty(pat); if is_unrooted_ty(cx, ty, self.in_new_function) { cx.span_lint(UNROOTED_MUST_ROOT, pat.span, &format!("Expression of type {:?} must be rooted", ty)) } } visit::walk_pat(self, pat); } fn visit_fn(&mut self, kind: visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl, body: hir::BodyId, span: codemap::Span, id: ast::NodeId) { if let visit::FnKind::Closure(_) = kind { visit::walk_fn(self, kind, decl, body, span, id); } } fn visit_foreign_item(&mut self, _: &'tcx hir::ForeignItem) {} fn visit_ty(&mut self, _: &'tcx hir::Ty) { } fn nested_visit_map<'this>(&'this mut self) -> hir::intravisit::NestedVisitorMap<'this, 'tcx> { hir::intravisit::NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir) } }
{ lint_array!(UNROOTED_MUST_ROOT) }
identifier_body
unrooted_must_root.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 rustc::hir; use rustc::hir::intravisit as visit; use rustc::hir::map as ast_map; use rustc::lint::{LateContext, LintPass, LintArray, LateLintPass, LintContext}; use rustc::ty; use syntax::{ast, codemap}; use utils::{match_def_path, in_derive_expn}; declare_lint!(UNROOTED_MUST_ROOT, Deny, "Warn and report usage of unrooted jsmanaged objects"); /// Lint for ensuring safe usage of unrooted pointers /// /// This lint (disable with `-A unrooted-must-root`/`#[allow(unrooted_must_root)]`) ensures that `#[must_root]` /// values are used correctly. /// /// "Incorrect" usage includes: /// /// - Not being used in a struct/enum field which is not `#[must_root]` itself /// - Not being used as an argument to a function (Except onces named `new` and `new_inherited`) /// - Not being bound locally in a `let` statement, assignment, `for` loop, or `match` statement. /// /// This helps catch most situations where pointers like `JS<T>` are used in a way that they can be invalidated by a /// GC pass. /// /// Structs which have their own mechanism of rooting their unrooted contents (e.g. `ScriptThread`) /// can be marked as `#[allow(unrooted_must_root)]`. Smart pointers which root their interior type /// can be marked as `#[allow_unrooted_interior]` pub struct UnrootedPass; impl UnrootedPass { pub fn new() -> UnrootedPass { UnrootedPass } } /// Checks if a type is unrooted or contains any owned unrooted types fn is_unrooted_ty(cx: &LateContext, ty: &ty::TyS, in_new_function: bool) -> bool { let mut ret = false; ty.maybe_walk(|t| { match t.sty { ty::TyAdt(did, _) => { if cx.tcx.has_attr(did.did, "must_root") { ret = true; false } else if cx.tcx.has_attr(did.did, "allow_unrooted_interior") { false } else if match_def_path(cx, did.did, &["core", "cell", "Ref"]) || match_def_path(cx, did.did, &["core", "cell", "RefMut"]) || match_def_path(cx, did.did, &["core", "slice", "Iter"]) || match_def_path(cx, did.did, &["std", "collections", "hash", "map", "Entry"]) || match_def_path(cx, did.did, &["std", "collections", "hash", "map", "OccupiedEntry"]) || match_def_path(cx, did.did, &["std", "collections", "hash", "map", "VacantEntry"]) || match_def_path(cx, did.did, &["std", "collections", "hash", "set", "Iter"]) { // Structures which are semantically similar to an &ptr. false } else if did.is_box() && in_new_function { // box in new() is okay false } else { true } }, ty::TyRef(..) => false, // don't recurse down &ptrs ty::TyRawPtr(..) => false, // don't recurse down *ptrs ty::TyFnDef(..) | ty::TyFnPtr(_) => false, _ => true } }); ret } impl LintPass for UnrootedPass { fn get_lints(&self) -> LintArray { lint_array!(UNROOTED_MUST_ROOT) } } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnrootedPass { /// All structs containing #[must_root] types must be #[must_root] themselves fn check_struct_def(&mut self, cx: &LateContext, def: &hir::VariantData, _n: ast::Name, _gen: &hir::Generics, id: ast::NodeId) { let item = match cx.tcx.hir.get(id) { ast_map::Node::NodeItem(item) => item, _ => cx.tcx.hir.expect_item(cx.tcx.hir.get_parent(id)), }; if item.attrs.iter().all(|a|!a.check_name("must_root")) { for ref field in def.fields() { let def_id = cx.tcx.hir.local_def_id(field.id); if is_unrooted_ty(cx, cx.tcx.item_type(def_id), false) { cx.span_lint(UNROOTED_MUST_ROOT, field.span, "Type must be rooted, use #[must_root] on the struct definition to propagate") } } } } /// All enums containing #[must_root] types must be #[must_root] themselves fn check_variant(&mut self, cx: &LateContext, var: &hir::Variant, _gen: &hir::Generics) { let ref map = cx.tcx.hir; if map.expect_item(map.get_parent(var.node.data.id())).attrs.iter().all(|a|!a.check_name("must_root")) { match var.node.data { hir::VariantData::Tuple(ref fields, _) => { for ref field in fields { let def_id = cx.tcx.hir.local_def_id(field.id); if is_unrooted_ty(cx, cx.tcx.item_type(def_id), false) { cx.span_lint(UNROOTED_MUST_ROOT, field.ty.span, "Type must be rooted, use #[must_root] on \ the enum definition to propagate") } } } _ => () // Struct variants already caught by check_struct_def } } } /// Function arguments that are #[must_root] types are not allowed fn check_fn(&mut self, cx: &LateContext<'a, 'tcx>, kind: visit::FnKind, decl: &'tcx hir::FnDecl, body: &'tcx hir::Body, span: codemap::Span, id: ast::NodeId) { let in_new_function = match kind { visit::FnKind::ItemFn(n, _, _, _, _, _, _) | visit::FnKind::Method(n, _, _, _) => { &*n.as_str() == "new" || n.as_str().starts_with("new_") } visit::FnKind::Closure(_) => return, }; if!in_derive_expn(span) { let def_id = cx.tcx.hir.local_def_id(id); let ty = cx.tcx.item_type(def_id); for (arg, ty) in decl.inputs.iter().zip(ty.fn_args().0.iter()) { if is_unrooted_ty(cx, ty, false) { cx.span_lint(UNROOTED_MUST_ROOT, arg.span, "Type must be rooted") } } if!in_new_function { if is_unrooted_ty(cx, ty.fn_ret().0, false) { cx.span_lint(UNROOTED_MUST_ROOT, decl.output.span(), "Type must be rooted") } } } let mut visitor = FnDefVisitor { cx: cx, in_new_function: in_new_function, }; visit::walk_expr(&mut visitor, &body.value); } } struct FnDefVisitor<'a, 'b: 'a, 'tcx: 'a+'b> { cx: &'a LateContext<'b, 'tcx>, in_new_function: bool, } impl<'a, 'b, 'tcx> visit::Visitor<'tcx> for FnDefVisitor<'a, 'b, 'tcx> { fn visit_expr(&mut self, expr: &'tcx hir::Expr) { let cx = self.cx; fn require_rooted(cx: &LateContext, in_new_function: bool, subexpr: &hir::Expr) { let ty = cx.tables.expr_ty(&subexpr); if is_unrooted_ty(cx, ty, in_new_function) { cx.span_lint(UNROOTED_MUST_ROOT, subexpr.span, &format!("Expression of type {:?} must be rooted", ty)) } } match expr.node { /// Trait casts from #[must_root] types are not allowed hir::ExprCast(ref subexpr, _) => require_rooted(cx, self.in_new_function, &*subexpr), // This catches assignments... the main point of this would be to catch mutable // references to `JS<T>`. // FIXME: Enable this? Triggers on certain kinds of uses of DOMRefCell. // hir::ExprAssign(_, ref rhs) => require_rooted(cx, self.in_new_function, &*rhs), // This catches calls; basically, this enforces the constraint that only constructors // can call other constructors. // FIXME: Enable this? Currently triggers with constructs involving DOMRefCell, and // constructs like Vec<JS<T>> and RootedVec<JS<T>>. // hir::ExprCall(..) if!self.in_new_function => { // require_rooted(cx, self.in_new_function, expr); // } _ => { // TODO(pcwalton): Check generics with a whitelist of allowed generics. } } visit::walk_expr(self, expr); } fn visit_pat(&mut self, pat: &'tcx hir::Pat) { let cx = self.cx; if let hir::PatKind::Binding(hir::BindingMode::BindByValue(_), _, _, _) = pat.node { let ty = cx.tables.pat_ty(pat); if is_unrooted_ty(cx, ty, self.in_new_function) { cx.span_lint(UNROOTED_MUST_ROOT, pat.span, &format!("Expression of type {:?} must be rooted", ty)) } }
if let visit::FnKind::Closure(_) = kind { visit::walk_fn(self, kind, decl, body, span, id); } } fn visit_foreign_item(&mut self, _: &'tcx hir::ForeignItem) {} fn visit_ty(&mut self, _: &'tcx hir::Ty) { } fn nested_visit_map<'this>(&'this mut self) -> hir::intravisit::NestedVisitorMap<'this, 'tcx> { hir::intravisit::NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir) } }
visit::walk_pat(self, pat); } fn visit_fn(&mut self, kind: visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl, body: hir::BodyId, span: codemap::Span, id: ast::NodeId) {
random_line_split
lib.rs
#![recursion_limit = "256"] #![forbid(unsafe_code)]
// // Core Stencila objects e.g `File`, `Article`, `Project` pub mod conversions; pub mod documents; pub mod files; pub use kernels; pub mod projects; pub mod sessions; pub mod sources; // Features // // Features that can be turned off #[cfg(feature = "cli")] pub mod cli; #[cfg(feature = "upgrade")] pub mod upgrade; #[cfg(feature = "server")] pub mod server; #[cfg(any(feature = "server"))] pub mod jwt; #[cfg(any(feature = "server"))] pub mod rpc; // Internal configuration, messaging etc pub mod config; pub mod errors; pub mod logging; pub mod telemetry; // Utilities // // Usually just small functions that are often wrappers around other crates. pub mod utils; // Re-export packages // // Mainly for use by stencila-* language packages in this workspace pub use eyre; pub use once_cell; pub use regex; pub use serde; pub use serde_json; pub use serde_yaml; pub use strum; pub use tokio; pub use tracing; pub use validator;
// Objects
random_line_split
term.rs
use crate::types::binary::OwnedBinary; use crate::wrapper::env::term_to_binary; use crate::wrapper::NIF_TERM; use crate::{Binary, Decoder, Env, NifResult}; use std::cmp::Ordering; use std::fmt::{self, Debug}; /// Term is used to represent all erlang terms. Terms are always lifetime limited by a Env. /// /// Term is cloneable and copyable, but it can not exist outside of the lifetime of the Env /// that owns it. #[derive(Clone, Copy)] pub struct Term<'a> { term: NIF_TERM, env: Env<'a>, } impl<'a> Debug for Term<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { crate::wrapper::term::fmt(self.as_c_arg(), f) } } impl<'a> Term<'a> { /// Create a `Term` from a raw `NIF_TERM`. /// /// # Unsafe /// The caller must ensure that `env` is the environment that `inner` belongs to, /// unless `inner` is an atom term. pub unsafe fn new(env: Env<'a>, inner: NIF_TERM) -> Self { Term { term: inner, env } } /// This extracts the raw term pointer. It is usually used in order to obtain a type that can /// be passed to calls into the erlang vm. pub fn as_c_arg(&self) -> NIF_TERM { self.term } pub fn get_env(&self) -> Env<'a> { self.env } /// Returns a representation of self in the given Env. /// /// If the term is already is in the provided env, it will be directly returned. Otherwise /// the term will be copied over. pub fn in_env<'b>(&self, env: Env<'b>) -> Term<'b> { if self.get_env() == env { // It's safe to create a new Term<'b> without copying because we // just proved that the same environment is associated with both 'a // and 'b. (They are either exactly the same lifetime, or the // lifetimes of two.run() calls on the same OwnedEnv.) unsafe { Term::new(env, self.as_c_arg()) } } else { unsafe { Term::new( env, rustler_sys::enif_make_copy(env.as_c_arg(), self.as_c_arg()), ) } } } /// Decodes the Term into type T. /// /// This should be used as the primary method of extracting the value from a Term. /// /// # Examples /// /// ```ignore /// let term: Term =...; /// let number: i32 = term.decode()?; /// ``` pub fn decode<T>(self) -> NifResult<T> where T: Decoder<'a>, { Decoder::decode(self) } /// Decodes the Term into Binary /// /// This could be used as a replacement for [`decode`] when decoding Binary from an iolist /// is needed. /// /// [`decode`]: #method.decode pub fn decode_as_binary(self) -> NifResult<Binary<'a>> { if self.is_binary() { return Binary::from_term(self); } Binary::from_iolist(self) } pub fn to_binary(self) -> OwnedBinary { let raw_binary = unsafe { term_to_binary(self.env.as_c_arg(), self.as_c_arg()) }.unwrap(); unsafe { OwnedBinary::from_raw(raw_binary) } } } impl<'a> PartialEq for Term<'a> { fn eq(&self, other: &Term) -> bool { unsafe { rustler_sys::enif_is_identical(self.as_c_arg(), other.as_c_arg()) == 1 } } } impl<'a> Eq for Term<'a> {} fn cmp(lhs: &Term, rhs: &Term) -> Ordering { let ord = unsafe { rustler_sys::enif_compare(lhs.as_c_arg(), rhs.as_c_arg()) }; match ord { 0 => Ordering::Equal, n if n < 0 => Ordering::Less, _ => Ordering::Greater, } } impl<'a> Ord for Term<'a> { fn cmp(&self, other: &Term) -> Ordering { cmp(self, other) } } impl<'a> PartialOrd for Term<'a> { fn
(&self, other: &Term<'a>) -> Option<Ordering> { Some(cmp(self, other)) } } unsafe impl<'a> Sync for Term<'a> {} unsafe impl<'a> Send for Term<'a> {}
partial_cmp
identifier_name
term.rs
use crate::types::binary::OwnedBinary; use crate::wrapper::env::term_to_binary; use crate::wrapper::NIF_TERM; use crate::{Binary, Decoder, Env, NifResult}; use std::cmp::Ordering; use std::fmt::{self, Debug}; /// Term is used to represent all erlang terms. Terms are always lifetime limited by a Env. /// /// Term is cloneable and copyable, but it can not exist outside of the lifetime of the Env /// that owns it. #[derive(Clone, Copy)] pub struct Term<'a> { term: NIF_TERM, env: Env<'a>, } impl<'a> Debug for Term<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { crate::wrapper::term::fmt(self.as_c_arg(), f) } } impl<'a> Term<'a> { /// Create a `Term` from a raw `NIF_TERM`. /// /// # Unsafe /// The caller must ensure that `env` is the environment that `inner` belongs to, /// unless `inner` is an atom term. pub unsafe fn new(env: Env<'a>, inner: NIF_TERM) -> Self { Term { term: inner, env } } /// This extracts the raw term pointer. It is usually used in order to obtain a type that can /// be passed to calls into the erlang vm. pub fn as_c_arg(&self) -> NIF_TERM { self.term } pub fn get_env(&self) -> Env<'a> { self.env } /// Returns a representation of self in the given Env. /// /// If the term is already is in the provided env, it will be directly returned. Otherwise /// the term will be copied over. pub fn in_env<'b>(&self, env: Env<'b>) -> Term<'b> { if self.get_env() == env { // It's safe to create a new Term<'b> without copying because we // just proved that the same environment is associated with both 'a // and 'b. (They are either exactly the same lifetime, or the // lifetimes of two.run() calls on the same OwnedEnv.) unsafe { Term::new(env, self.as_c_arg()) } } else { unsafe { Term::new( env, rustler_sys::enif_make_copy(env.as_c_arg(), self.as_c_arg()), ) } } } /// Decodes the Term into type T. /// /// This should be used as the primary method of extracting the value from a Term. /// /// # Examples /// /// ```ignore /// let term: Term =...; /// let number: i32 = term.decode()?; /// ``` pub fn decode<T>(self) -> NifResult<T> where T: Decoder<'a>, { Decoder::decode(self) } /// Decodes the Term into Binary /// /// This could be used as a replacement for [`decode`] when decoding Binary from an iolist /// is needed. /// /// [`decode`]: #method.decode pub fn decode_as_binary(self) -> NifResult<Binary<'a>> { if self.is_binary() { return Binary::from_term(self); } Binary::from_iolist(self) } pub fn to_binary(self) -> OwnedBinary { let raw_binary = unsafe { term_to_binary(self.env.as_c_arg(), self.as_c_arg()) }.unwrap(); unsafe { OwnedBinary::from_raw(raw_binary) } } } impl<'a> PartialEq for Term<'a> { fn eq(&self, other: &Term) -> bool { unsafe { rustler_sys::enif_is_identical(self.as_c_arg(), other.as_c_arg()) == 1 } }
let ord = unsafe { rustler_sys::enif_compare(lhs.as_c_arg(), rhs.as_c_arg()) }; match ord { 0 => Ordering::Equal, n if n < 0 => Ordering::Less, _ => Ordering::Greater, } } impl<'a> Ord for Term<'a> { fn cmp(&self, other: &Term) -> Ordering { cmp(self, other) } } impl<'a> PartialOrd for Term<'a> { fn partial_cmp(&self, other: &Term<'a>) -> Option<Ordering> { Some(cmp(self, other)) } } unsafe impl<'a> Sync for Term<'a> {} unsafe impl<'a> Send for Term<'a> {}
} impl<'a> Eq for Term<'a> {} fn cmp(lhs: &Term, rhs: &Term) -> Ordering {
random_line_split
inline.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. use llvm::{AvailableExternallyLinkage, InternalLinkage, SetLinkage}; use metadata::csearch; use middle::astencode; use middle::subst::Substs; use trans::base::{push_ctxt, trans_item, get_item_val, trans_fn}; use trans::common::*; use syntax::ast; use syntax::ast_util::local_def; fn
(ccx: &CrateContext, fn_id: ast::DefId) -> Option<ast::DefId> { debug!("instantiate_inline({:?})", fn_id); let _icx = push_ctxt("instantiate_inline"); match ccx.external().borrow().get(&fn_id) { Some(&Some(node_id)) => { // Already inline debug!("instantiate_inline({}): already inline as node id {}", ccx.tcx().item_path_str(fn_id), node_id); return Some(local_def(node_id)); } Some(&None) => { return None; // Not inlinable } None => { // Not seen yet } } let csearch_result = csearch::maybe_get_item_ast( ccx.tcx(), fn_id, Box::new(|a,b,c,d| astencode::decode_inlined_item(a, b, c, d))); let inline_id = match csearch_result { csearch::FoundAst::NotFound => { ccx.external().borrow_mut().insert(fn_id, None); return None; } csearch::FoundAst::Found(&ast::IIItem(ref item)) => { ccx.external().borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, fn_id); ccx.stats().n_inlines.set(ccx.stats().n_inlines.get() + 1); trans_item(ccx, item); let linkage = match item.node { ast::ItemFn(_, _, _, _, ref generics, _) => { if generics.is_type_parameterized() { // Generics have no symbol, so they can't be given any // linkage. None } else { if ccx.sess().opts.cg.codegen_units == 1 { // We could use AvailableExternallyLinkage here, // but InternalLinkage allows LLVM to optimize more // aggressively (at the cost of sometimes // duplicating code). Some(InternalLinkage) } else { // With multiple compilation units, duplicated code // is more of a problem. Also, `codegen_units > 1` // means the user is okay with losing some // performance. Some(AvailableExternallyLinkage) } } } ast::ItemConst(..) => None, _ => unreachable!(), }; match linkage { Some(linkage) => { let g = get_item_val(ccx, item.id); SetLinkage(g, linkage); } None => {} } item.id } csearch::FoundAst::Found(&ast::IIForeign(ref item)) => { ccx.external().borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, fn_id); item.id } csearch::FoundAst::FoundParent(parent_id, &ast::IIItem(ref item)) => { ccx.external().borrow_mut().insert(parent_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, parent_id); let mut my_id = 0; match item.node { ast::ItemEnum(ref ast_def, _) => { let ast_vs = &ast_def.variants; let ty_vs = &ccx.tcx().lookup_adt_def(parent_id).variants; assert_eq!(ast_vs.len(), ty_vs.len()); for (ast_v, ty_v) in ast_vs.iter().zip(ty_vs.iter()) { if ty_v.did == fn_id { my_id = ast_v.node.id; } ccx.external().borrow_mut().insert(ty_v.did, Some(ast_v.node.id)); } } ast::ItemStruct(ref struct_def, _) => { match struct_def.ctor_id { None => ccx.sess().bug("instantiate_inline: called on a \ non-tuple struct"), Some(ctor_id) => { ccx.external().borrow_mut().insert(fn_id, Some(ctor_id)); my_id = ctor_id; } } } _ => ccx.sess().bug("instantiate_inline: item has a \ non-enum, non-struct parent") } trans_item(ccx, &**item); my_id } csearch::FoundAst::FoundParent(_, _) => { ccx.sess().bug("maybe_get_item_ast returned a FoundParent \ with a non-item parent"); } csearch::FoundAst::Found(&ast::IITraitItem(_, ref trait_item)) => { ccx.external().borrow_mut().insert(fn_id, Some(trait_item.id)); ccx.external_srcs().borrow_mut().insert(trait_item.id, fn_id); ccx.stats().n_inlines.set(ccx.stats().n_inlines.get() + 1); // Associated consts already have to be evaluated in `typeck`, so // the logic to do that already exists in `middle`. In order to // reuse that code, it needs to be able to look up the traits for // inlined items. let ty_trait_item = ccx.tcx().impl_or_trait_item(fn_id).clone(); ccx.tcx().impl_or_trait_items.borrow_mut() .insert(local_def(trait_item.id), ty_trait_item); // If this is a default method, we can't look up the // impl type. But we aren't going to translate anyways, so // don't. trait_item.id } csearch::FoundAst::Found(&ast::IIImplItem(impl_did, ref impl_item)) => { ccx.external().borrow_mut().insert(fn_id, Some(impl_item.id)); ccx.external_srcs().borrow_mut().insert(impl_item.id, fn_id); ccx.stats().n_inlines.set(ccx.stats().n_inlines.get() + 1); // Translate monomorphic impl methods immediately. if let ast::MethodImplItem(ref sig, ref body) = impl_item.node { let impl_tpt = ccx.tcx().lookup_item_type(impl_did); if impl_tpt.generics.types.is_empty() && sig.generics.ty_params.is_empty() { let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty()); let llfn = get_item_val(ccx, impl_item.id); trans_fn(ccx, &sig.decl, body, llfn, empty_substs, impl_item.id, &[]); // See linkage comments on items. if ccx.sess().opts.cg.codegen_units == 1 { SetLinkage(llfn, InternalLinkage); } else { SetLinkage(llfn, AvailableExternallyLinkage); } } } impl_item.id } }; Some(local_def(inline_id)) } pub fn get_local_instance(ccx: &CrateContext, fn_id: ast::DefId) -> Option<ast::DefId> { if fn_id.krate == ast::LOCAL_CRATE { Some(fn_id) } else { instantiate_inline(ccx, fn_id) } } pub fn maybe_instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) -> ast::DefId { get_local_instance(ccx, fn_id).unwrap_or(fn_id) }
instantiate_inline
identifier_name
inline.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. use llvm::{AvailableExternallyLinkage, InternalLinkage, SetLinkage}; use metadata::csearch; use middle::astencode; use middle::subst::Substs; use trans::base::{push_ctxt, trans_item, get_item_val, trans_fn}; use trans::common::*; use syntax::ast; use syntax::ast_util::local_def; fn instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) -> Option<ast::DefId> { debug!("instantiate_inline({:?})", fn_id); let _icx = push_ctxt("instantiate_inline"); match ccx.external().borrow().get(&fn_id) { Some(&Some(node_id)) => { // Already inline debug!("instantiate_inline({}): already inline as node id {}", ccx.tcx().item_path_str(fn_id), node_id); return Some(local_def(node_id)); } Some(&None) => { return None; // Not inlinable } None => { // Not seen yet } } let csearch_result = csearch::maybe_get_item_ast( ccx.tcx(), fn_id, Box::new(|a,b,c,d| astencode::decode_inlined_item(a, b, c, d))); let inline_id = match csearch_result { csearch::FoundAst::NotFound => { ccx.external().borrow_mut().insert(fn_id, None); return None; } csearch::FoundAst::Found(&ast::IIItem(ref item)) => { ccx.external().borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, fn_id); ccx.stats().n_inlines.set(ccx.stats().n_inlines.get() + 1); trans_item(ccx, item); let linkage = match item.node { ast::ItemFn(_, _, _, _, ref generics, _) => { if generics.is_type_parameterized() { // Generics have no symbol, so they can't be given any // linkage. None } else { if ccx.sess().opts.cg.codegen_units == 1 { // We could use AvailableExternallyLinkage here, // but InternalLinkage allows LLVM to optimize more // aggressively (at the cost of sometimes // duplicating code). Some(InternalLinkage) } else { // With multiple compilation units, duplicated code // is more of a problem. Also, `codegen_units > 1` // means the user is okay with losing some // performance. Some(AvailableExternallyLinkage) } } } ast::ItemConst(..) => None, _ => unreachable!(), }; match linkage { Some(linkage) => { let g = get_item_val(ccx, item.id); SetLinkage(g, linkage); } None => {} } item.id } csearch::FoundAst::Found(&ast::IIForeign(ref item)) => { ccx.external().borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, fn_id); item.id } csearch::FoundAst::FoundParent(parent_id, &ast::IIItem(ref item)) => { ccx.external().borrow_mut().insert(parent_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, parent_id); let mut my_id = 0; match item.node { ast::ItemEnum(ref ast_def, _) => { let ast_vs = &ast_def.variants; let ty_vs = &ccx.tcx().lookup_adt_def(parent_id).variants; assert_eq!(ast_vs.len(), ty_vs.len()); for (ast_v, ty_v) in ast_vs.iter().zip(ty_vs.iter()) { if ty_v.did == fn_id { my_id = ast_v.node.id; } ccx.external().borrow_mut().insert(ty_v.did, Some(ast_v.node.id)); } } ast::ItemStruct(ref struct_def, _) => { match struct_def.ctor_id { None => ccx.sess().bug("instantiate_inline: called on a \ non-tuple struct"), Some(ctor_id) => { ccx.external().borrow_mut().insert(fn_id, Some(ctor_id)); my_id = ctor_id; } } } _ => ccx.sess().bug("instantiate_inline: item has a \ non-enum, non-struct parent") } trans_item(ccx, &**item); my_id } csearch::FoundAst::FoundParent(_, _) => { ccx.sess().bug("maybe_get_item_ast returned a FoundParent \ with a non-item parent"); } csearch::FoundAst::Found(&ast::IITraitItem(_, ref trait_item)) => { ccx.external().borrow_mut().insert(fn_id, Some(trait_item.id)); ccx.external_srcs().borrow_mut().insert(trait_item.id, fn_id); ccx.stats().n_inlines.set(ccx.stats().n_inlines.get() + 1); // Associated consts already have to be evaluated in `typeck`, so // the logic to do that already exists in `middle`. In order to // reuse that code, it needs to be able to look up the traits for // inlined items. let ty_trait_item = ccx.tcx().impl_or_trait_item(fn_id).clone(); ccx.tcx().impl_or_trait_items.borrow_mut() .insert(local_def(trait_item.id), ty_trait_item); // If this is a default method, we can't look up the // impl type. But we aren't going to translate anyways, so // don't. trait_item.id } csearch::FoundAst::Found(&ast::IIImplItem(impl_did, ref impl_item)) => { ccx.external().borrow_mut().insert(fn_id, Some(impl_item.id)); ccx.external_srcs().borrow_mut().insert(impl_item.id, fn_id); ccx.stats().n_inlines.set(ccx.stats().n_inlines.get() + 1); // Translate monomorphic impl methods immediately. if let ast::MethodImplItem(ref sig, ref body) = impl_item.node { let impl_tpt = ccx.tcx().lookup_item_type(impl_did); if impl_tpt.generics.types.is_empty() && sig.generics.ty_params.is_empty() { let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty()); let llfn = get_item_val(ccx, impl_item.id); trans_fn(ccx, &sig.decl, body, llfn, empty_substs, impl_item.id, &[]); // See linkage comments on items. if ccx.sess().opts.cg.codegen_units == 1 { SetLinkage(llfn, InternalLinkage); } else { SetLinkage(llfn, AvailableExternallyLinkage); } } } impl_item.id } }; Some(local_def(inline_id)) } pub fn get_local_instance(ccx: &CrateContext, fn_id: ast::DefId) -> Option<ast::DefId> { if fn_id.krate == ast::LOCAL_CRATE { Some(fn_id) } else { instantiate_inline(ccx, fn_id) } } pub fn maybe_instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) -> ast::DefId
{ get_local_instance(ccx, fn_id).unwrap_or(fn_id) }
identifier_body
inline.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. use llvm::{AvailableExternallyLinkage, InternalLinkage, SetLinkage}; use metadata::csearch; use middle::astencode; use middle::subst::Substs; use trans::base::{push_ctxt, trans_item, get_item_val, trans_fn}; use trans::common::*; use syntax::ast; use syntax::ast_util::local_def; fn instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) -> Option<ast::DefId> { debug!("instantiate_inline({:?})", fn_id); let _icx = push_ctxt("instantiate_inline"); match ccx.external().borrow().get(&fn_id) { Some(&Some(node_id)) => { // Already inline debug!("instantiate_inline({}): already inline as node id {}", ccx.tcx().item_path_str(fn_id), node_id); return Some(local_def(node_id)); } Some(&None) => { return None; // Not inlinable } None => { // Not seen yet } } let csearch_result = csearch::maybe_get_item_ast( ccx.tcx(), fn_id, Box::new(|a,b,c,d| astencode::decode_inlined_item(a, b, c, d))); let inline_id = match csearch_result { csearch::FoundAst::NotFound => { ccx.external().borrow_mut().insert(fn_id, None); return None; } csearch::FoundAst::Found(&ast::IIItem(ref item)) => { ccx.external().borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, fn_id); ccx.stats().n_inlines.set(ccx.stats().n_inlines.get() + 1); trans_item(ccx, item); let linkage = match item.node { ast::ItemFn(_, _, _, _, ref generics, _) => { if generics.is_type_parameterized() { // Generics have no symbol, so they can't be given any // linkage. None } else { if ccx.sess().opts.cg.codegen_units == 1 { // We could use AvailableExternallyLinkage here, // but InternalLinkage allows LLVM to optimize more // aggressively (at the cost of sometimes // duplicating code). Some(InternalLinkage) } else { // With multiple compilation units, duplicated code // is more of a problem. Also, `codegen_units > 1` // means the user is okay with losing some // performance. Some(AvailableExternallyLinkage) } } } ast::ItemConst(..) => None, _ => unreachable!(), }; match linkage { Some(linkage) => { let g = get_item_val(ccx, item.id); SetLinkage(g, linkage); } None => {} } item.id } csearch::FoundAst::Found(&ast::IIForeign(ref item)) => { ccx.external().borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, fn_id); item.id } csearch::FoundAst::FoundParent(parent_id, &ast::IIItem(ref item)) => { ccx.external().borrow_mut().insert(parent_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, parent_id); let mut my_id = 0; match item.node { ast::ItemEnum(ref ast_def, _) => { let ast_vs = &ast_def.variants; let ty_vs = &ccx.tcx().lookup_adt_def(parent_id).variants; assert_eq!(ast_vs.len(), ty_vs.len()); for (ast_v, ty_v) in ast_vs.iter().zip(ty_vs.iter()) { if ty_v.did == fn_id { my_id = ast_v.node.id; } ccx.external().borrow_mut().insert(ty_v.did, Some(ast_v.node.id)); } } ast::ItemStruct(ref struct_def, _) => { match struct_def.ctor_id { None => ccx.sess().bug("instantiate_inline: called on a \ non-tuple struct"), Some(ctor_id) => { ccx.external().borrow_mut().insert(fn_id, Some(ctor_id)); my_id = ctor_id; } } } _ => ccx.sess().bug("instantiate_inline: item has a \ non-enum, non-struct parent") } trans_item(ccx, &**item); my_id } csearch::FoundAst::FoundParent(_, _) => { ccx.sess().bug("maybe_get_item_ast returned a FoundParent \ with a non-item parent"); } csearch::FoundAst::Found(&ast::IITraitItem(_, ref trait_item)) => { ccx.external().borrow_mut().insert(fn_id, Some(trait_item.id)); ccx.external_srcs().borrow_mut().insert(trait_item.id, fn_id); ccx.stats().n_inlines.set(ccx.stats().n_inlines.get() + 1); // Associated consts already have to be evaluated in `typeck`, so // the logic to do that already exists in `middle`. In order to // reuse that code, it needs to be able to look up the traits for // inlined items. let ty_trait_item = ccx.tcx().impl_or_trait_item(fn_id).clone(); ccx.tcx().impl_or_trait_items.borrow_mut() .insert(local_def(trait_item.id), ty_trait_item); // If this is a default method, we can't look up the // impl type. But we aren't going to translate anyways, so // don't. trait_item.id } csearch::FoundAst::Found(&ast::IIImplItem(impl_did, ref impl_item)) => { ccx.external().borrow_mut().insert(fn_id, Some(impl_item.id)); ccx.external_srcs().borrow_mut().insert(impl_item.id, fn_id); ccx.stats().n_inlines.set(ccx.stats().n_inlines.get() + 1); // Translate monomorphic impl methods immediately. if let ast::MethodImplItem(ref sig, ref body) = impl_item.node { let impl_tpt = ccx.tcx().lookup_item_type(impl_did); if impl_tpt.generics.types.is_empty() && sig.generics.ty_params.is_empty() { let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty()); let llfn = get_item_val(ccx, impl_item.id); trans_fn(ccx, &sig.decl, body, llfn, empty_substs, impl_item.id, &[]); // See linkage comments on items. if ccx.sess().opts.cg.codegen_units == 1 { SetLinkage(llfn, InternalLinkage); } else { SetLinkage(llfn, AvailableExternallyLinkage); } }
Some(local_def(inline_id)) } pub fn get_local_instance(ccx: &CrateContext, fn_id: ast::DefId) -> Option<ast::DefId> { if fn_id.krate == ast::LOCAL_CRATE { Some(fn_id) } else { instantiate_inline(ccx, fn_id) } } pub fn maybe_instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) -> ast::DefId { get_local_instance(ccx, fn_id).unwrap_or(fn_id) }
} impl_item.id } };
random_line_split
bayesian.rs
// Copyright 2016 Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! Utilities for Bayesian statistics. use ordered_float::OrderedFloat; use itertools::Itertools; use stats::LogProb; /// For each of the hypothesis tests given as posterior error probabilities /// (PEPs, i.e. the posterior probability of the null hypothesis), estimate the FDR /// for the case that all null hypotheses with at most this PEP are rejected. /// FDR is calculated as presented by Müller, Parmigiani, and Rice, /// "FDR and Bayesian Multiple Comparisons Rules" (July 2006). /// Johns Hopkin's University, Dept. of Biostatistics Working Papers. Working Paper 115. /// /// # Returns /// /// A vector of expected FDRs in the same order as the given PEPs. pub fn expected_fdr(peps: &[LogProb]) -> Vec<LogProb> { // sort indices let sorted_idx = (0..peps.len()).sorted_by(|&i, &j| OrderedFloat(*peps[i]).cmp(&OrderedFloat(*peps[j]))); // estimate FDR let mut expected_fdr = vec![LogProb::ln_zero(); peps.len()]; for (i, expected_fp) in LogProb::ln_cumsum_exp(sorted_idx.iter().map(|&i| peps[i])) .enumerate() { let fdr = LogProb(*expected_fp - ((i + 1) as f64).ln()); expected_fdr[i] = if fdr <= LogProb::ln_one() { fdr } else {
} expected_fdr } #[cfg(test)] mod tests { use super::*; use stats::LogProb; #[test] fn test_expected_fdr() { let peps = [LogProb(0.1f64.ln()), LogProb::ln_zero(), LogProb(0.25f64.ln())]; let fdrs = expected_fdr(&peps); println!("{:?}", fdrs); assert_relative_eq!(*fdrs[1], *LogProb::ln_zero()); assert_relative_eq!(*fdrs[0], *LogProb(0.05f64.ln())); assert_relative_eq!(*fdrs[2], *LogProb((0.35 / 3.0f64).ln())); } }
LogProb::ln_one() };
conditional_block
bayesian.rs
// Copyright 2016 Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! Utilities for Bayesian statistics.
/// For each of the hypothesis tests given as posterior error probabilities /// (PEPs, i.e. the posterior probability of the null hypothesis), estimate the FDR /// for the case that all null hypotheses with at most this PEP are rejected. /// FDR is calculated as presented by Müller, Parmigiani, and Rice, /// "FDR and Bayesian Multiple Comparisons Rules" (July 2006). /// Johns Hopkin's University, Dept. of Biostatistics Working Papers. Working Paper 115. /// /// # Returns /// /// A vector of expected FDRs in the same order as the given PEPs. pub fn expected_fdr(peps: &[LogProb]) -> Vec<LogProb> { // sort indices let sorted_idx = (0..peps.len()).sorted_by(|&i, &j| OrderedFloat(*peps[i]).cmp(&OrderedFloat(*peps[j]))); // estimate FDR let mut expected_fdr = vec![LogProb::ln_zero(); peps.len()]; for (i, expected_fp) in LogProb::ln_cumsum_exp(sorted_idx.iter().map(|&i| peps[i])) .enumerate() { let fdr = LogProb(*expected_fp - ((i + 1) as f64).ln()); expected_fdr[i] = if fdr <= LogProb::ln_one() { fdr } else { LogProb::ln_one() }; } expected_fdr } #[cfg(test)] mod tests { use super::*; use stats::LogProb; #[test] fn test_expected_fdr() { let peps = [LogProb(0.1f64.ln()), LogProb::ln_zero(), LogProb(0.25f64.ln())]; let fdrs = expected_fdr(&peps); println!("{:?}", fdrs); assert_relative_eq!(*fdrs[1], *LogProb::ln_zero()); assert_relative_eq!(*fdrs[0], *LogProb(0.05f64.ln())); assert_relative_eq!(*fdrs[2], *LogProb((0.35 / 3.0f64).ln())); } }
use ordered_float::OrderedFloat; use itertools::Itertools; use stats::LogProb;
random_line_split
bayesian.rs
// Copyright 2016 Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! Utilities for Bayesian statistics. use ordered_float::OrderedFloat; use itertools::Itertools; use stats::LogProb; /// For each of the hypothesis tests given as posterior error probabilities /// (PEPs, i.e. the posterior probability of the null hypothesis), estimate the FDR /// for the case that all null hypotheses with at most this PEP are rejected. /// FDR is calculated as presented by Müller, Parmigiani, and Rice, /// "FDR and Bayesian Multiple Comparisons Rules" (July 2006). /// Johns Hopkin's University, Dept. of Biostatistics Working Papers. Working Paper 115. /// /// # Returns /// /// A vector of expected FDRs in the same order as the given PEPs. pub fn expected_fdr(peps: &[LogProb]) -> Vec<LogProb> {
#[cfg(test)] mod tests { use super::*; use stats::LogProb; #[test] fn test_expected_fdr() { let peps = [LogProb(0.1f64.ln()), LogProb::ln_zero(), LogProb(0.25f64.ln())]; let fdrs = expected_fdr(&peps); println!("{:?}", fdrs); assert_relative_eq!(*fdrs[1], *LogProb::ln_zero()); assert_relative_eq!(*fdrs[0], *LogProb(0.05f64.ln())); assert_relative_eq!(*fdrs[2], *LogProb((0.35 / 3.0f64).ln())); } }
// sort indices let sorted_idx = (0..peps.len()).sorted_by(|&i, &j| OrderedFloat(*peps[i]).cmp(&OrderedFloat(*peps[j]))); // estimate FDR let mut expected_fdr = vec![LogProb::ln_zero(); peps.len()]; for (i, expected_fp) in LogProb::ln_cumsum_exp(sorted_idx.iter().map(|&i| peps[i])) .enumerate() { let fdr = LogProb(*expected_fp - ((i + 1) as f64).ln()); expected_fdr[i] = if fdr <= LogProb::ln_one() { fdr } else { LogProb::ln_one() }; } expected_fdr }
identifier_body
bayesian.rs
// Copyright 2016 Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! Utilities for Bayesian statistics. use ordered_float::OrderedFloat; use itertools::Itertools; use stats::LogProb; /// For each of the hypothesis tests given as posterior error probabilities /// (PEPs, i.e. the posterior probability of the null hypothesis), estimate the FDR /// for the case that all null hypotheses with at most this PEP are rejected. /// FDR is calculated as presented by Müller, Parmigiani, and Rice, /// "FDR and Bayesian Multiple Comparisons Rules" (July 2006). /// Johns Hopkin's University, Dept. of Biostatistics Working Papers. Working Paper 115. /// /// # Returns /// /// A vector of expected FDRs in the same order as the given PEPs. pub fn expected_fdr(peps: &[LogProb]) -> Vec<LogProb> { // sort indices let sorted_idx = (0..peps.len()).sorted_by(|&i, &j| OrderedFloat(*peps[i]).cmp(&OrderedFloat(*peps[j]))); // estimate FDR let mut expected_fdr = vec![LogProb::ln_zero(); peps.len()]; for (i, expected_fp) in LogProb::ln_cumsum_exp(sorted_idx.iter().map(|&i| peps[i])) .enumerate() { let fdr = LogProb(*expected_fp - ((i + 1) as f64).ln()); expected_fdr[i] = if fdr <= LogProb::ln_one() { fdr } else { LogProb::ln_one() }; } expected_fdr } #[cfg(test)] mod tests { use super::*; use stats::LogProb; #[test] fn te
{ let peps = [LogProb(0.1f64.ln()), LogProb::ln_zero(), LogProb(0.25f64.ln())]; let fdrs = expected_fdr(&peps); println!("{:?}", fdrs); assert_relative_eq!(*fdrs[1], *LogProb::ln_zero()); assert_relative_eq!(*fdrs[0], *LogProb(0.05f64.ln())); assert_relative_eq!(*fdrs[2], *LogProb((0.35 / 3.0f64).ln())); } }
st_expected_fdr()
identifier_name
mod.rs
use std::sync::{Arc, RwLock}; use std::vec::IntoIter; use radix_trie::Trie; use crate::completion::Completer; use crate::config::{Config, EditMode}; use crate::edit::init_state; use crate::highlight::Highlighter; use crate::hint::Hinter; use crate::keymap::{Cmd, InputState}; use crate::keys::{KeyCode as K, KeyEvent, KeyEvent as E, Modifiers as M}; use crate::tty::Sink; use crate::validate::Validator; use crate::{apply_backspace_direct, readline_direct, Context, Editor, Helper, Result}; mod common; mod emacs; mod history; mod vi_cmd; mod vi_insert; fn init_editor(mode: EditMode, keys: &[KeyEvent]) -> Editor<()> { let config = Config::builder().edit_mode(mode).build(); let mut editor = Editor::<()>::with_config(config); editor.term.keys.extend(keys.iter().cloned()); editor } struct SimpleCompleter; impl Completer for SimpleCompleter { type Candidate = String; fn complete( &self, line: &str, _pos: usize, _ctx: &Context<'_>, ) -> Result<(usize, Vec<String>)> { Ok((0, vec![line.to_owned() + "t"])) } } impl Hinter for SimpleCompleter { type Hint = String; fn
(&self, _line: &str, _pos: usize, _ctx: &Context<'_>) -> Option<Self::Hint> { None } } impl Helper for SimpleCompleter {} impl Highlighter for SimpleCompleter {} impl Validator for SimpleCompleter {} #[test] fn complete_line() { let mut out = Sink::default(); let history = crate::history::History::new(); let helper = Some(SimpleCompleter); let mut s = init_state(&mut out, "rus", 3, helper.as_ref(), &history); let config = Config::default(); let mut input_state = InputState::new(&config, Arc::new(RwLock::new(Trie::new()))); let keys = vec![E::ENTER]; let mut rdr: IntoIter<KeyEvent> = keys.into_iter(); let cmd = super::complete_line(&mut rdr, &mut s, &mut input_state, &Config::default()).unwrap(); assert_eq!( Some(Cmd::AcceptOrInsertLine { accept_in_the_middle: true }), cmd ); assert_eq!("rust", s.line.as_str()); assert_eq!(4, s.line.pos()); } // `keys`: keys to press // `expected_line`: line after enter key fn assert_line(mode: EditMode, keys: &[KeyEvent], expected_line: &str) { let mut editor = init_editor(mode, keys); let actual_line = editor.readline(">>").unwrap(); assert_eq!(expected_line, actual_line); } // `initial`: line status before `keys` pressed: strings before and after cursor // `keys`: keys to press // `expected_line`: line after enter key fn assert_line_with_initial( mode: EditMode, initial: (&str, &str), keys: &[KeyEvent], expected_line: &str, ) { let mut editor = init_editor(mode, keys); let actual_line = editor.readline_with_initial(">>", initial).unwrap(); assert_eq!(expected_line, actual_line); } // `initial`: line status before `keys` pressed: strings before and after cursor // `keys`: keys to press // `expected`: line status before enter key: strings before and after cursor fn assert_cursor(mode: EditMode, initial: (&str, &str), keys: &[KeyEvent], expected: (&str, &str)) { let mut editor = init_editor(mode, keys); let actual_line = editor.readline_with_initial("", initial).unwrap(); assert_eq!(expected.0.to_owned() + expected.1, actual_line); assert_eq!(expected.0.len(), editor.term.cursor); } // `entries`: history entries before `keys` pressed // `keys`: keys to press // `expected`: line status before enter key: strings before and after cursor fn assert_history( mode: EditMode, entries: &[&str], keys: &[KeyEvent], prompt: &str, expected: (&str, &str), ) { let mut editor = init_editor(mode, keys); for entry in entries { editor.history.add(*entry); } let actual_line = editor.readline(prompt).unwrap(); assert_eq!(expected.0.to_owned() + expected.1, actual_line); if prompt.is_empty() { assert_eq!(expected.0.len(), editor.term.cursor); } } #[test] fn unknown_esc_key() { for mode in &[EditMode::Emacs, EditMode::Vi] { assert_line(*mode, &[E(K::UnknownEscSeq, M::NONE), E::ENTER], ""); } } #[test] fn test_send() { fn assert_send<T: Send>() {} assert_send::<Editor<()>>(); } #[test] fn test_sync() { fn assert_sync<T: Sync>() {} assert_sync::<Editor<()>>(); } #[test] fn test_apply_backspace_direct() { assert_eq!( &apply_backspace_direct("Hel\u{0008}\u{0008}el\u{0008}llo ☹\u{0008}☺"), "Hello ☺" ); } #[test] fn test_readline_direct() { use std::io::Cursor; let mut write_buf = vec![]; let output = readline_direct( Cursor::new("([)\n\u{0008}\n\n\r\n])".as_bytes()), Cursor::new(&mut write_buf), &Some(crate::validate::MatchingBracketValidator::new()), ); assert_eq!( &write_buf, b"Mismatched brackets: '[' is not properly closed" ); assert_eq!(&output.unwrap(), "([\n\n\r\n])"); }
hint
identifier_name
mod.rs
use std::sync::{Arc, RwLock}; use std::vec::IntoIter; use radix_trie::Trie; use crate::completion::Completer; use crate::config::{Config, EditMode}; use crate::edit::init_state; use crate::highlight::Highlighter; use crate::hint::Hinter; use crate::keymap::{Cmd, InputState}; use crate::keys::{KeyCode as K, KeyEvent, KeyEvent as E, Modifiers as M}; use crate::tty::Sink; use crate::validate::Validator; use crate::{apply_backspace_direct, readline_direct, Context, Editor, Helper, Result}; mod common; mod emacs; mod history; mod vi_cmd; mod vi_insert; fn init_editor(mode: EditMode, keys: &[KeyEvent]) -> Editor<()> { let config = Config::builder().edit_mode(mode).build(); let mut editor = Editor::<()>::with_config(config); editor.term.keys.extend(keys.iter().cloned()); editor } struct SimpleCompleter; impl Completer for SimpleCompleter { type Candidate = String; fn complete( &self, line: &str, _pos: usize, _ctx: &Context<'_>, ) -> Result<(usize, Vec<String>)> { Ok((0, vec![line.to_owned() + "t"])) } } impl Hinter for SimpleCompleter { type Hint = String; fn hint(&self, _line: &str, _pos: usize, _ctx: &Context<'_>) -> Option<Self::Hint> { None } } impl Helper for SimpleCompleter {} impl Highlighter for SimpleCompleter {} impl Validator for SimpleCompleter {} #[test] fn complete_line() { let mut out = Sink::default(); let history = crate::history::History::new(); let helper = Some(SimpleCompleter); let mut s = init_state(&mut out, "rus", 3, helper.as_ref(), &history); let config = Config::default(); let mut input_state = InputState::new(&config, Arc::new(RwLock::new(Trie::new()))); let keys = vec![E::ENTER]; let mut rdr: IntoIter<KeyEvent> = keys.into_iter(); let cmd = super::complete_line(&mut rdr, &mut s, &mut input_state, &Config::default()).unwrap(); assert_eq!( Some(Cmd::AcceptOrInsertLine { accept_in_the_middle: true }), cmd ); assert_eq!("rust", s.line.as_str()); assert_eq!(4, s.line.pos()); } // `keys`: keys to press // `expected_line`: line after enter key fn assert_line(mode: EditMode, keys: &[KeyEvent], expected_line: &str) { let mut editor = init_editor(mode, keys); let actual_line = editor.readline(">>").unwrap(); assert_eq!(expected_line, actual_line); } // `initial`: line status before `keys` pressed: strings before and after cursor // `keys`: keys to press // `expected_line`: line after enter key fn assert_line_with_initial( mode: EditMode, initial: (&str, &str), keys: &[KeyEvent], expected_line: &str, ) { let mut editor = init_editor(mode, keys); let actual_line = editor.readline_with_initial(">>", initial).unwrap(); assert_eq!(expected_line, actual_line); } // `initial`: line status before `keys` pressed: strings before and after cursor // `keys`: keys to press // `expected`: line status before enter key: strings before and after cursor fn assert_cursor(mode: EditMode, initial: (&str, &str), keys: &[KeyEvent], expected: (&str, &str)) { let mut editor = init_editor(mode, keys); let actual_line = editor.readline_with_initial("", initial).unwrap(); assert_eq!(expected.0.to_owned() + expected.1, actual_line); assert_eq!(expected.0.len(), editor.term.cursor); } // `entries`: history entries before `keys` pressed // `keys`: keys to press // `expected`: line status before enter key: strings before and after cursor fn assert_history( mode: EditMode, entries: &[&str], keys: &[KeyEvent], prompt: &str, expected: (&str, &str), ) { let mut editor = init_editor(mode, keys); for entry in entries { editor.history.add(*entry); } let actual_line = editor.readline(prompt).unwrap(); assert_eq!(expected.0.to_owned() + expected.1, actual_line); if prompt.is_empty() { assert_eq!(expected.0.len(), editor.term.cursor); } } #[test] fn unknown_esc_key() { for mode in &[EditMode::Emacs, EditMode::Vi] { assert_line(*mode, &[E(K::UnknownEscSeq, M::NONE), E::ENTER], ""); } } #[test] fn test_send() { fn assert_send<T: Send>() {} assert_send::<Editor<()>>(); } #[test] fn test_sync() { fn assert_sync<T: Sync>() {} assert_sync::<Editor<()>>(); } #[test] fn test_apply_backspace_direct() { assert_eq!( &apply_backspace_direct("Hel\u{0008}\u{0008}el\u{0008}llo ☹\u{0008}☺"), "Hello ☺" ); } #[test] fn test_readline_direct() { use std::io::Cursor; let mut write_buf = vec![]; let output = readline_direct( Cursor::new("([)\n\u{0008}\n\n\r\n])".as_bytes()), Cursor::new(&mut write_buf), &Some(crate::validate::MatchingBracketValidator::new()), ); assert_eq!( &write_buf, b"Mismatched brackets: '[' is not properly closed" ); assert_eq!(&output.unwrap(), "([\n\n\r\n])");
}
random_line_split
mod.rs
use std::sync::{Arc, RwLock}; use std::vec::IntoIter; use radix_trie::Trie; use crate::completion::Completer; use crate::config::{Config, EditMode}; use crate::edit::init_state; use crate::highlight::Highlighter; use crate::hint::Hinter; use crate::keymap::{Cmd, InputState}; use crate::keys::{KeyCode as K, KeyEvent, KeyEvent as E, Modifiers as M}; use crate::tty::Sink; use crate::validate::Validator; use crate::{apply_backspace_direct, readline_direct, Context, Editor, Helper, Result}; mod common; mod emacs; mod history; mod vi_cmd; mod vi_insert; fn init_editor(mode: EditMode, keys: &[KeyEvent]) -> Editor<()> { let config = Config::builder().edit_mode(mode).build(); let mut editor = Editor::<()>::with_config(config); editor.term.keys.extend(keys.iter().cloned()); editor } struct SimpleCompleter; impl Completer for SimpleCompleter { type Candidate = String; fn complete( &self, line: &str, _pos: usize, _ctx: &Context<'_>, ) -> Result<(usize, Vec<String>)> { Ok((0, vec![line.to_owned() + "t"])) } } impl Hinter for SimpleCompleter { type Hint = String; fn hint(&self, _line: &str, _pos: usize, _ctx: &Context<'_>) -> Option<Self::Hint> { None } } impl Helper for SimpleCompleter {} impl Highlighter for SimpleCompleter {} impl Validator for SimpleCompleter {} #[test] fn complete_line() { let mut out = Sink::default(); let history = crate::history::History::new(); let helper = Some(SimpleCompleter); let mut s = init_state(&mut out, "rus", 3, helper.as_ref(), &history); let config = Config::default(); let mut input_state = InputState::new(&config, Arc::new(RwLock::new(Trie::new()))); let keys = vec![E::ENTER]; let mut rdr: IntoIter<KeyEvent> = keys.into_iter(); let cmd = super::complete_line(&mut rdr, &mut s, &mut input_state, &Config::default()).unwrap(); assert_eq!( Some(Cmd::AcceptOrInsertLine { accept_in_the_middle: true }), cmd ); assert_eq!("rust", s.line.as_str()); assert_eq!(4, s.line.pos()); } // `keys`: keys to press // `expected_line`: line after enter key fn assert_line(mode: EditMode, keys: &[KeyEvent], expected_line: &str) { let mut editor = init_editor(mode, keys); let actual_line = editor.readline(">>").unwrap(); assert_eq!(expected_line, actual_line); } // `initial`: line status before `keys` pressed: strings before and after cursor // `keys`: keys to press // `expected_line`: line after enter key fn assert_line_with_initial( mode: EditMode, initial: (&str, &str), keys: &[KeyEvent], expected_line: &str, ) { let mut editor = init_editor(mode, keys); let actual_line = editor.readline_with_initial(">>", initial).unwrap(); assert_eq!(expected_line, actual_line); } // `initial`: line status before `keys` pressed: strings before and after cursor // `keys`: keys to press // `expected`: line status before enter key: strings before and after cursor fn assert_cursor(mode: EditMode, initial: (&str, &str), keys: &[KeyEvent], expected: (&str, &str)) { let mut editor = init_editor(mode, keys); let actual_line = editor.readline_with_initial("", initial).unwrap(); assert_eq!(expected.0.to_owned() + expected.1, actual_line); assert_eq!(expected.0.len(), editor.term.cursor); } // `entries`: history entries before `keys` pressed // `keys`: keys to press // `expected`: line status before enter key: strings before and after cursor fn assert_history( mode: EditMode, entries: &[&str], keys: &[KeyEvent], prompt: &str, expected: (&str, &str), ) { let mut editor = init_editor(mode, keys); for entry in entries { editor.history.add(*entry); } let actual_line = editor.readline(prompt).unwrap(); assert_eq!(expected.0.to_owned() + expected.1, actual_line); if prompt.is_empty()
} #[test] fn unknown_esc_key() { for mode in &[EditMode::Emacs, EditMode::Vi] { assert_line(*mode, &[E(K::UnknownEscSeq, M::NONE), E::ENTER], ""); } } #[test] fn test_send() { fn assert_send<T: Send>() {} assert_send::<Editor<()>>(); } #[test] fn test_sync() { fn assert_sync<T: Sync>() {} assert_sync::<Editor<()>>(); } #[test] fn test_apply_backspace_direct() { assert_eq!( &apply_backspace_direct("Hel\u{0008}\u{0008}el\u{0008}llo ☹\u{0008}☺"), "Hello ☺" ); } #[test] fn test_readline_direct() { use std::io::Cursor; let mut write_buf = vec![]; let output = readline_direct( Cursor::new("([)\n\u{0008}\n\n\r\n])".as_bytes()), Cursor::new(&mut write_buf), &Some(crate::validate::MatchingBracketValidator::new()), ); assert_eq!( &write_buf, b"Mismatched brackets: '[' is not properly closed" ); assert_eq!(&output.unwrap(), "([\n\n\r\n])"); }
{ assert_eq!(expected.0.len(), editor.term.cursor); }
conditional_block
mod.rs
use std::sync::{Arc, RwLock}; use std::vec::IntoIter; use radix_trie::Trie; use crate::completion::Completer; use crate::config::{Config, EditMode}; use crate::edit::init_state; use crate::highlight::Highlighter; use crate::hint::Hinter; use crate::keymap::{Cmd, InputState}; use crate::keys::{KeyCode as K, KeyEvent, KeyEvent as E, Modifiers as M}; use crate::tty::Sink; use crate::validate::Validator; use crate::{apply_backspace_direct, readline_direct, Context, Editor, Helper, Result}; mod common; mod emacs; mod history; mod vi_cmd; mod vi_insert; fn init_editor(mode: EditMode, keys: &[KeyEvent]) -> Editor<()> { let config = Config::builder().edit_mode(mode).build(); let mut editor = Editor::<()>::with_config(config); editor.term.keys.extend(keys.iter().cloned()); editor } struct SimpleCompleter; impl Completer for SimpleCompleter { type Candidate = String; fn complete( &self, line: &str, _pos: usize, _ctx: &Context<'_>, ) -> Result<(usize, Vec<String>)> { Ok((0, vec![line.to_owned() + "t"])) } } impl Hinter for SimpleCompleter { type Hint = String; fn hint(&self, _line: &str, _pos: usize, _ctx: &Context<'_>) -> Option<Self::Hint> { None } } impl Helper for SimpleCompleter {} impl Highlighter for SimpleCompleter {} impl Validator for SimpleCompleter {} #[test] fn complete_line() { let mut out = Sink::default(); let history = crate::history::History::new(); let helper = Some(SimpleCompleter); let mut s = init_state(&mut out, "rus", 3, helper.as_ref(), &history); let config = Config::default(); let mut input_state = InputState::new(&config, Arc::new(RwLock::new(Trie::new()))); let keys = vec![E::ENTER]; let mut rdr: IntoIter<KeyEvent> = keys.into_iter(); let cmd = super::complete_line(&mut rdr, &mut s, &mut input_state, &Config::default()).unwrap(); assert_eq!( Some(Cmd::AcceptOrInsertLine { accept_in_the_middle: true }), cmd ); assert_eq!("rust", s.line.as_str()); assert_eq!(4, s.line.pos()); } // `keys`: keys to press // `expected_line`: line after enter key fn assert_line(mode: EditMode, keys: &[KeyEvent], expected_line: &str)
// `initial`: line status before `keys` pressed: strings before and after cursor // `keys`: keys to press // `expected_line`: line after enter key fn assert_line_with_initial( mode: EditMode, initial: (&str, &str), keys: &[KeyEvent], expected_line: &str, ) { let mut editor = init_editor(mode, keys); let actual_line = editor.readline_with_initial(">>", initial).unwrap(); assert_eq!(expected_line, actual_line); } // `initial`: line status before `keys` pressed: strings before and after cursor // `keys`: keys to press // `expected`: line status before enter key: strings before and after cursor fn assert_cursor(mode: EditMode, initial: (&str, &str), keys: &[KeyEvent], expected: (&str, &str)) { let mut editor = init_editor(mode, keys); let actual_line = editor.readline_with_initial("", initial).unwrap(); assert_eq!(expected.0.to_owned() + expected.1, actual_line); assert_eq!(expected.0.len(), editor.term.cursor); } // `entries`: history entries before `keys` pressed // `keys`: keys to press // `expected`: line status before enter key: strings before and after cursor fn assert_history( mode: EditMode, entries: &[&str], keys: &[KeyEvent], prompt: &str, expected: (&str, &str), ) { let mut editor = init_editor(mode, keys); for entry in entries { editor.history.add(*entry); } let actual_line = editor.readline(prompt).unwrap(); assert_eq!(expected.0.to_owned() + expected.1, actual_line); if prompt.is_empty() { assert_eq!(expected.0.len(), editor.term.cursor); } } #[test] fn unknown_esc_key() { for mode in &[EditMode::Emacs, EditMode::Vi] { assert_line(*mode, &[E(K::UnknownEscSeq, M::NONE), E::ENTER], ""); } } #[test] fn test_send() { fn assert_send<T: Send>() {} assert_send::<Editor<()>>(); } #[test] fn test_sync() { fn assert_sync<T: Sync>() {} assert_sync::<Editor<()>>(); } #[test] fn test_apply_backspace_direct() { assert_eq!( &apply_backspace_direct("Hel\u{0008}\u{0008}el\u{0008}llo ☹\u{0008}☺"), "Hello ☺" ); } #[test] fn test_readline_direct() { use std::io::Cursor; let mut write_buf = vec![]; let output = readline_direct( Cursor::new("([)\n\u{0008}\n\n\r\n])".as_bytes()), Cursor::new(&mut write_buf), &Some(crate::validate::MatchingBracketValidator::new()), ); assert_eq!( &write_buf, b"Mismatched brackets: '[' is not properly closed" ); assert_eq!(&output.unwrap(), "([\n\n\r\n])"); }
{ let mut editor = init_editor(mode, keys); let actual_line = editor.readline(">>").unwrap(); assert_eq!(expected_line, actual_line); }
identifier_body
kindck-send-object1.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. // Test which object types are considered sendable. This test // is broken into two parts because some errors occur in distinct // phases in the compiler. See kindck-send-object2.rs as well! fn assert_send<T:Send+'static>() { } trait Dummy { } // careful with object types, who knows what they close over... fn
<'a>() { assert_send::<&'a Dummy>(); //~^ ERROR the trait `core::marker::Sync` is not implemented } fn test52<'a>() { assert_send::<&'a (Dummy+Sync)>(); //~^ ERROR does not fulfill the required lifetime } //...unless they are properly bounded fn test60() { assert_send::<&'static (Dummy+Sync)>(); } fn test61() { assert_send::<Box<Dummy+Send>>(); } // closure and object types can have lifetime bounds which make // them not ok fn test_71<'a>() { assert_send::<Box<Dummy+'a>>(); //~^ ERROR the trait `core::marker::Send` is not implemented } fn main() { }
test51
identifier_name
kindck-send-object1.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. // Test which object types are considered sendable. This test // is broken into two parts because some errors occur in distinct // phases in the compiler. See kindck-send-object2.rs as well! fn assert_send<T:Send+'static>() { } trait Dummy { } // careful with object types, who knows what they close over... fn test51<'a>() { assert_send::<&'a Dummy>(); //~^ ERROR the trait `core::marker::Sync` is not implemented } fn test52<'a>() { assert_send::<&'a (Dummy+Sync)>(); //~^ ERROR does not fulfill the required lifetime } //...unless they are properly bounded fn test60() { assert_send::<&'static (Dummy+Sync)>(); } fn test61() { assert_send::<Box<Dummy+Send>>(); } // closure and object types can have lifetime bounds which make // them not ok fn test_71<'a>() { assert_send::<Box<Dummy+'a>>(); //~^ ERROR the trait `core::marker::Send` is not implemented } fn main() { }
random_line_split
kindck-send-object1.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. // Test which object types are considered sendable. This test // is broken into two parts because some errors occur in distinct // phases in the compiler. See kindck-send-object2.rs as well! fn assert_send<T:Send+'static>() { } trait Dummy { } // careful with object types, who knows what they close over... fn test51<'a>() { assert_send::<&'a Dummy>(); //~^ ERROR the trait `core::marker::Sync` is not implemented } fn test52<'a>()
//...unless they are properly bounded fn test60() { assert_send::<&'static (Dummy+Sync)>(); } fn test61() { assert_send::<Box<Dummy+Send>>(); } // closure and object types can have lifetime bounds which make // them not ok fn test_71<'a>() { assert_send::<Box<Dummy+'a>>(); //~^ ERROR the trait `core::marker::Send` is not implemented } fn main() { }
{ assert_send::<&'a (Dummy+Sync)>(); //~^ ERROR does not fulfill the required lifetime }
identifier_body
securitybaseapi.rs
// Copyright © 2016-2017 winapi-rs developers // 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. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms. //! FFI bindings to psapi. use shared::minwindef::{BOOL, DWORD, PBOOL, PDWORD, PUCHAR, PULONG, ULONG} use um::winnt::{ HANDLE, PACL, PCLAIM_SECURITY_ATTRIBUTES_INFORMATION, PHANDLE, PSID, PTOKEN_PRIVILEGES, } extern "system" { // pub fn AccessCheck(); // pub fn AccessCheckAndAuditAlarmW(); // pub fn AccessCheckByType(); // pub fn AccessCheckByTypeResultList(); // pub fn AccessCheckByTypeAndAuditAlarmW(); // pub fn AccessCheckByTypeResultListAndAuditAlarmW(); // pub fn AccessCheckByTypeResultListAndAuditAlarmByHandleW(); // pub fn AddAccessAllowedAce(); // pub fn AddAccessAllowedAceEx(); // pub fn AddAccessAllowedObjectAce(); // pub fn AddAccessDeniedAce(); // pub fn AddAccessDeniedAceEx(); // pub fn AddAccessDeniedObjectAce(); // pub fn AddAce(); // pub fn AddAuditAccessAce(); // pub fn AddAuditAccessAceEx(); // pub fn AddAuditAccessObjectAce(); // pub fn AddMandatoryAce(); pub fn AddResourceAttributeAce( pAcl: PACL, dwAceRevision: DWORD, AceFlags: DWORD, AccessMask: DWORD, pSid: PSID, pAttributeInfo: PCLAIM_SECURITY_ATTRIBUTES_INFORMATION, pReturnLength: PDWORD, ) -> BOOL; pub fn AddScopedPolicyIDAce( pAcl: PACL, dwAceRevision: DWORD, AceFlags: DWORD, AccessMask: DWORD, pSid: PSID, ) -> BOOL; // pub fn AdjustTokenGroups(); pub fn AdjustTokenPrivileges( TokenHandle: HANDLE, DisableAllPrivileges: BOOL, NewState: PTOKEN_PRIVILEGES, BufferLength: DWORD, PreviousState: PTOKEN_PRIVILEGES, ReturnLength: PDWORD, ) -> BOOL; // pub fn AllocateAndInitializeSid(); pub fn AllocateLocallyUniqueId( Luid: PLUID, ) -> BOOL; pub fn AreAllAccessesGranted( GrantedAccess: DWORD, DesiredAccess: DWORD, ) -> BOOL; pub fn AreAnyAccessesGranted( GrantedAccess: DWORD, DesiredAccess: DWORD, ) -> BOOL; pub fn CheckTokenMembershipEx( TokenHandle: HANDLE, SidToCheck: PSID, Flags: DWORD, IsMember: PBOOL, ) -> BOOL; pub fn CheckTokenCapability( TokenHandle: HANDLE, CapabilitySidToCheck: PSID, HasCapability: PBOOL, ) -> BOOL; pub fn GetAppContainerAce( Acl: PACL, StartingAceIndex: DWORD, AppContainerAce: *mut PVOID, AppContainerAceIndex: *mut DWORD, ) -> BOOL; // pub fn CheckTokenMembershipEx(); // pub fn ConvertToAutoInheritPrivateObjectSecurity(); // pub fn CopySid(); // pub fn CreatePrivateObjectSecurity(); // pub fn CreatePrivateObjectSecurityEx(); // pub fn CreatePrivateObjectSecurityWithMultipleInheritance(); // pub fn CreateRestrictedToken(); // pub fn CreateWellKnownSid(); // pub fn EqualDomainSid(); // pub fn DeleteAce(); // pub fn DestroyPrivateObjectSecurity(); // pub fn DuplicateToken(); // pub fn DuplicateTokenEx(); // pub fn EqualPrefixSid(); // pub fn EqualSid(); // pub fn FindFirstFreeAce(); // pub fn FreeSid(); // pub fn GetAce(); // pub fn GetAclInformation();
// pub fn GetSecurityDescriptorControl(); // pub fn GetSecurityDescriptorDacl(); // pub fn GetSecurityDescriptorGroup(); // pub fn GetSecurityDescriptorLength(); // pub fn GetSecurityDescriptorOwner(); // pub fn GetSecurityDescriptorRMControl(); // pub fn GetSecurityDescriptorSacl(); // pub fn GetSidIdentifierAuthority(); // pub fn GetSidLengthRequired(); // pub fn GetSidSubAuthority(); // pub fn GetSidSubAuthorityCount(); // pub fn GetTokenInformation(); // pub fn GetWindowsAccountDomainSid(); // pub fn ImpersonateAnonymousToken(); // pub fn ImpersonateLoggedOnUser(); // pub fn ImpersonateSelf(); // pub fn InitializeAcl(); // pub fn InitializeSecurityDescriptor(); // pub fn InitializeSid(); // pub fn IsTokenRestricted(); // pub fn IsValidAcl(); // pub fn IsValidSecurityDescriptor(); // pub fn IsValidSid(); // pub fn IsWellKnownSid(); // pub fn MakeAbsoluteSD(); // pub fn MakeSelfRelativeSD(); // pub fn MapGenericMask(); // pub fn ObjectCloseAuditAlarmW(); // pub fn ObjectDeleteAuditAlarmW(); // pub fn ObjectOpenAuditAlarmW(); // pub fn ObjectPrivilegeAuditAlarmW(); // pub fn PrivilegeCheck(); // pub fn PrivilegedServiceAuditAlarmW(); // pub fn QuerySecurityAccessMask(); // pub fn RevertToSelf(); // pub fn SetAclInformation(); // pub fn SetFileSecurityW(); // pub fn SetKernelObjectSecurity(); // pub fn SetPrivateObjectSecurity(); // pub fn SetPrivateObjectSecurityEx(); // pub fn SetSecurityAccessMask(); // pub fn SetSecurityDescriptorControl(); // pub fn SetSecurityDescriptorDacl(); // pub fn SetSecurityDescriptorGroup(); // pub fn SetSecurityDescriptorOwner(); // pub fn SetSecurityDescriptorRMControl(); // pub fn SetSecurityDescriptorSacl(); // pub fn SetTokenInformation(); pub fn SetCachedSigningLevel( SourceFiles: PHANDLE, SourceFileCount: ULONG, Flags: ULONG, TargetFile: HANDLE, ) -> BOOL; pub fn GetCachedSigningLevel( File: HANDLE, Flags: PULONG, SigningLevel: PULONG, Thumbprint: PUCHAR, ThumbprintSize: PULONG, ThumbprintAlgorithm: PULONG, ) -> BOOL; // pub fn CveEventWrite(); }
// pub fn GetFileSecurityW(); // pub fn GetKernelObjectSecurity(); // pub fn GetLengthSid(); // pub fn GetPrivateObjectSecurity();
random_line_split
gradient.rs
// Copyright 2015 the simplectic-noise developers. For a full listing of the // authors, refer to the AUTHORS file at the top-level directory of this // distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and
use std::num::Float; use math; pub fn get2<T: Float>(index: usize) -> math::Point2<T> { let diag: T = math::cast(0.70710678118f32); let one: T = math::cast(1.0f32); let zero: T = math::cast(0.0f32); match index % 8 { 0 => [ diag, diag], 1 => [ diag, -diag], 2 => [-diag, diag], 3 => [-diag, -diag], 4 => [ one, zero], 5 => [-one, zero], 6 => [ zero, one], 7 => [ zero, -one], _ => panic!("Attempt to access 2D gradient {} of 8", index % 8), } } #[inline(always)] pub fn get3<T: Float>(index: usize) -> math::Point3<T> { let diag: T = math::cast(0.70710678118f32); let zero: T = math::cast(0.0f32); match index % 12 { 0 => [ diag, diag, zero], 1 => [ diag, -diag, zero], 2 => [-diag, diag, zero], 3 => [-diag, -diag, zero], 4 => [ diag, zero, diag], 5 => [ diag, zero, -diag], 6 => [-diag, zero, diag], 7 => [-diag, zero, -diag], 8 => [ zero, diag, diag], 9 => [ zero, diag, -diag], 10 => [ zero, -diag, diag], 11 => [ zero, -diag, -diag], _ => panic!("Attempt to access 3D gradient {} of 12", index % 12), } } #[inline(always)] pub fn get4<T: Float>(index: usize) -> math::Point4<T> { let diag: T = math::cast(0.57735026919f32); let zero: T = math::cast(0.0f32); match index % 32 { 0 => [ diag, diag, diag, zero], 1 => [ diag, -diag, diag, zero], 2 => [-diag, diag, diag, zero], 3 => [-diag, -diag, diag, zero], 4 => [ diag, diag, -diag, zero], 5 => [ diag, -diag, -diag, zero], 6 => [-diag, diag, -diag, zero], 7 => [-diag, -diag, -diag, zero], 8 => [ diag, diag, zero, diag], 9 => [ diag, -diag, zero, diag], 10 => [-diag, diag, zero, diag], 11 => [-diag, -diag, zero, diag], 12 => [ diag, diag, zero, -diag], 13 => [ diag, -diag, zero, -diag], 14 => [-diag, diag, zero, -diag], 15 => [-diag, -diag, zero, -diag], 16 => [ diag, zero, diag, diag], 17 => [ diag, zero, -diag, diag], 18 => [-diag, zero, diag, diag], 19 => [-diag, zero, -diag, diag], 20 => [ diag, zero, diag, -diag], 21 => [ diag, zero, -diag, -diag], 22 => [-diag, zero, diag, -diag], 23 => [-diag, zero, -diag, -diag], 24 => [ zero, diag, diag, diag], 25 => [ zero, diag, -diag, diag], 26 => [ zero, -diag, diag, diag], 27 => [ zero, -diag, -diag, diag], 28 => [ zero, diag, diag, -diag], 29 => [ zero, diag, -diag, -diag], 30 => [ zero, -diag, diag, -diag], 31 => [ zero, -diag, -diag, -diag], _ => panic!("Attempt to access 4D gradient {} of 32", index % 32), } }
// limitations under the License.
random_line_split
gradient.rs
// Copyright 2015 the simplectic-noise developers. For a full listing of the // authors, refer to the AUTHORS file at the top-level directory of this // distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::num::Float; use math; pub fn get2<T: Float>(index: usize) -> math::Point2<T>
#[inline(always)] pub fn get3<T: Float>(index: usize) -> math::Point3<T> { let diag: T = math::cast(0.70710678118f32); let zero: T = math::cast(0.0f32); match index % 12 { 0 => [ diag, diag, zero], 1 => [ diag, -diag, zero], 2 => [-diag, diag, zero], 3 => [-diag, -diag, zero], 4 => [ diag, zero, diag], 5 => [ diag, zero, -diag], 6 => [-diag, zero, diag], 7 => [-diag, zero, -diag], 8 => [ zero, diag, diag], 9 => [ zero, diag, -diag], 10 => [ zero, -diag, diag], 11 => [ zero, -diag, -diag], _ => panic!("Attempt to access 3D gradient {} of 12", index % 12), } } #[inline(always)] pub fn get4<T: Float>(index: usize) -> math::Point4<T> { let diag: T = math::cast(0.57735026919f32); let zero: T = math::cast(0.0f32); match index % 32 { 0 => [ diag, diag, diag, zero], 1 => [ diag, -diag, diag, zero], 2 => [-diag, diag, diag, zero], 3 => [-diag, -diag, diag, zero], 4 => [ diag, diag, -diag, zero], 5 => [ diag, -diag, -diag, zero], 6 => [-diag, diag, -diag, zero], 7 => [-diag, -diag, -diag, zero], 8 => [ diag, diag, zero, diag], 9 => [ diag, -diag, zero, diag], 10 => [-diag, diag, zero, diag], 11 => [-diag, -diag, zero, diag], 12 => [ diag, diag, zero, -diag], 13 => [ diag, -diag, zero, -diag], 14 => [-diag, diag, zero, -diag], 15 => [-diag, -diag, zero, -diag], 16 => [ diag, zero, diag, diag], 17 => [ diag, zero, -diag, diag], 18 => [-diag, zero, diag, diag], 19 => [-diag, zero, -diag, diag], 20 => [ diag, zero, diag, -diag], 21 => [ diag, zero, -diag, -diag], 22 => [-diag, zero, diag, -diag], 23 => [-diag, zero, -diag, -diag], 24 => [ zero, diag, diag, diag], 25 => [ zero, diag, -diag, diag], 26 => [ zero, -diag, diag, diag], 27 => [ zero, -diag, -diag, diag], 28 => [ zero, diag, diag, -diag], 29 => [ zero, diag, -diag, -diag], 30 => [ zero, -diag, diag, -diag], 31 => [ zero, -diag, -diag, -diag], _ => panic!("Attempt to access 4D gradient {} of 32", index % 32), } }
{ let diag: T = math::cast(0.70710678118f32); let one: T = math::cast(1.0f32); let zero: T = math::cast(0.0f32); match index % 8 { 0 => [ diag, diag], 1 => [ diag, -diag], 2 => [-diag, diag], 3 => [-diag, -diag], 4 => [ one, zero], 5 => [-one, zero], 6 => [ zero, one], 7 => [ zero, -one], _ => panic!("Attempt to access 2D gradient {} of 8", index % 8), } }
identifier_body
gradient.rs
// Copyright 2015 the simplectic-noise developers. For a full listing of the // authors, refer to the AUTHORS file at the top-level directory of this // distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::num::Float; use math; pub fn get2<T: Float>(index: usize) -> math::Point2<T> { let diag: T = math::cast(0.70710678118f32); let one: T = math::cast(1.0f32); let zero: T = math::cast(0.0f32); match index % 8 { 0 => [ diag, diag], 1 => [ diag, -diag], 2 => [-diag, diag], 3 => [-diag, -diag], 4 => [ one, zero], 5 => [-one, zero], 6 => [ zero, one], 7 => [ zero, -one], _ => panic!("Attempt to access 2D gradient {} of 8", index % 8), } } #[inline(always)] pub fn
<T: Float>(index: usize) -> math::Point3<T> { let diag: T = math::cast(0.70710678118f32); let zero: T = math::cast(0.0f32); match index % 12 { 0 => [ diag, diag, zero], 1 => [ diag, -diag, zero], 2 => [-diag, diag, zero], 3 => [-diag, -diag, zero], 4 => [ diag, zero, diag], 5 => [ diag, zero, -diag], 6 => [-diag, zero, diag], 7 => [-diag, zero, -diag], 8 => [ zero, diag, diag], 9 => [ zero, diag, -diag], 10 => [ zero, -diag, diag], 11 => [ zero, -diag, -diag], _ => panic!("Attempt to access 3D gradient {} of 12", index % 12), } } #[inline(always)] pub fn get4<T: Float>(index: usize) -> math::Point4<T> { let diag: T = math::cast(0.57735026919f32); let zero: T = math::cast(0.0f32); match index % 32 { 0 => [ diag, diag, diag, zero], 1 => [ diag, -diag, diag, zero], 2 => [-diag, diag, diag, zero], 3 => [-diag, -diag, diag, zero], 4 => [ diag, diag, -diag, zero], 5 => [ diag, -diag, -diag, zero], 6 => [-diag, diag, -diag, zero], 7 => [-diag, -diag, -diag, zero], 8 => [ diag, diag, zero, diag], 9 => [ diag, -diag, zero, diag], 10 => [-diag, diag, zero, diag], 11 => [-diag, -diag, zero, diag], 12 => [ diag, diag, zero, -diag], 13 => [ diag, -diag, zero, -diag], 14 => [-diag, diag, zero, -diag], 15 => [-diag, -diag, zero, -diag], 16 => [ diag, zero, diag, diag], 17 => [ diag, zero, -diag, diag], 18 => [-diag, zero, diag, diag], 19 => [-diag, zero, -diag, diag], 20 => [ diag, zero, diag, -diag], 21 => [ diag, zero, -diag, -diag], 22 => [-diag, zero, diag, -diag], 23 => [-diag, zero, -diag, -diag], 24 => [ zero, diag, diag, diag], 25 => [ zero, diag, -diag, diag], 26 => [ zero, -diag, diag, diag], 27 => [ zero, -diag, -diag, diag], 28 => [ zero, diag, diag, -diag], 29 => [ zero, diag, -diag, -diag], 30 => [ zero, -diag, diag, -diag], 31 => [ zero, -diag, -diag, -diag], _ => panic!("Attempt to access 4D gradient {} of 32", index % 32), } }
get3
identifier_name
ta.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 std::alloc::{TaPool, MemPool}; #[test] fn alloc() { let mut buf = &mut [d8::new(0); 5][..]; let addr = buf.as_ptr() as usize; unsafe { let mut pool1 = TaPool::new(&mut buf); let mut pool2 = pool1; let a1 = pool1.alloc(1, 1).unwrap(); test!(a1 as usize == addr); let a2 = pool2.alloc(2, 1).unwrap(); test!(a2 as usize == addr + 1); let a3 = pool1.alloc(2, 1).unwrap(); test!(a3 as usize == addr + 3); } test!(buf.as_ptr() as usize == addr + 5); } #[test] fn realloc() { let mut buf = &mut [d8::new(0); 5][..]; unsafe { let mut pool = TaPool::new(&mut buf);
*alloc = 1; let realloc = pool.realloc(alloc as *mut d8, 1, 2, 1).unwrap() as *mut u8; test!(*realloc == 1); } test!(buf.len() == 3); }
let alloc = pool.alloc(1, 1).unwrap() as *mut u8;
random_line_split
ta.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 std::alloc::{TaPool, MemPool}; #[test] fn alloc() { let mut buf = &mut [d8::new(0); 5][..]; let addr = buf.as_ptr() as usize; unsafe { let mut pool1 = TaPool::new(&mut buf); let mut pool2 = pool1; let a1 = pool1.alloc(1, 1).unwrap(); test!(a1 as usize == addr); let a2 = pool2.alloc(2, 1).unwrap(); test!(a2 as usize == addr + 1); let a3 = pool1.alloc(2, 1).unwrap(); test!(a3 as usize == addr + 3); } test!(buf.as_ptr() as usize == addr + 5); } #[test] fn
() { let mut buf = &mut [d8::new(0); 5][..]; unsafe { let mut pool = TaPool::new(&mut buf); let alloc = pool.alloc(1, 1).unwrap() as *mut u8; *alloc = 1; let realloc = pool.realloc(alloc as *mut d8, 1, 2, 1).unwrap() as *mut u8; test!(*realloc == 1); } test!(buf.len() == 3); }
realloc
identifier_name
ta.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 std::alloc::{TaPool, MemPool}; #[test] fn alloc()
#[test] fn realloc() { let mut buf = &mut [d8::new(0); 5][..]; unsafe { let mut pool = TaPool::new(&mut buf); let alloc = pool.alloc(1, 1).unwrap() as *mut u8; *alloc = 1; let realloc = pool.realloc(alloc as *mut d8, 1, 2, 1).unwrap() as *mut u8; test!(*realloc == 1); } test!(buf.len() == 3); }
{ let mut buf = &mut [d8::new(0); 5][..]; let addr = buf.as_ptr() as usize; unsafe { let mut pool1 = TaPool::new(&mut buf); let mut pool2 = pool1; let a1 = pool1.alloc(1, 1).unwrap(); test!(a1 as usize == addr); let a2 = pool2.alloc(2, 1).unwrap(); test!(a2 as usize == addr + 1); let a3 = pool1.alloc(2, 1).unwrap(); test!(a3 as usize == addr + 3); } test!(buf.as_ptr() as usize == addr + 5); }
identifier_body
stream.rs
> 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. /// Stream channels /// /// This is the flavor of channels which are optimized for one sender and one /// receiver. The sender will be upgraded to a shared channel if the channel is /// cloned. /// /// High level implementation details can be found in the comment of the parent /// module. pub use self::Failure::*; pub use self::UpgradeResult::*; pub use self::SelectionResult::*; use self::Message::*; use core::prelude::*; use alloc::boxed::Box; use core::cmp; use core::int; use rustrt::local::Local; use rustrt::task::{Task, BlockedTask}; use rustrt::thread::Thread; use sync::atomic; use comm::spsc_queue as spsc; use comm::Receiver; const DISCONNECTED: int = int::MIN; #[cfg(test)] const MAX_STEALS: int = 5; #[cfg(not(test))] const MAX_STEALS: int = 1 << 20; pub struct Packet<T> { queue: spsc::Queue<Message<T>>, // internal queue for all message cnt: atomic::AtomicInt, // How many items are on this channel steals: int, // How many times has a port received without blocking? to_wake: atomic::AtomicUint, // Task to wake up port_dropped: atomic::AtomicBool, // flag if the channel has been destroyed. } pub enum Failure<T> { Empty, Disconnected, Upgraded(Receiver<T>), } pub enum UpgradeResult { UpSuccess, UpDisconnected, UpWoke(BlockedTask), } pub enum SelectionResult<T> { SelSuccess, SelCanceled(BlockedTask), SelUpgraded(BlockedTask, Receiver<T>), } // Any message could contain an "upgrade request" to a new shared port, so the // internal queue it's a queue of T, but rather Message<T> enum Message<T> { Data(T), GoUp(Receiver<T>), } impl<T: Send> Packet<T> { pub fn new() -> Packet<T> { Packet { queue: unsafe { spsc::Queue::new(128) }, cnt: atomic::AtomicInt::new(0), steals: 0, to_wake: atomic::AtomicUint::new(0), port_dropped: atomic::AtomicBool::new(false), } } pub fn send(&mut self, t: T) -> Result<(), T> { // If the other port has deterministically gone away, then definitely // must return the data back up the stack. Otherwise, the data is // considered as being sent. if self.port_dropped.load(atomic::SeqCst) { return Err(t) } match self.do_send(Data(t)) { UpSuccess | UpDisconnected => {}, UpWoke(task) => { task.wake().map(|t| t.reawaken()); } } Ok(()) } pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult { // If the port has gone away, then there's no need to proceed any // further. if self.port_dropped.load(atomic::SeqCst) { return UpDisconnected } self.do_send(GoUp(up)) } fn do_send(&mut self, t: Message<T>) -> UpgradeResult { self.queue.push(t); match self.cnt.fetch_add(1, atomic::SeqCst) { // As described in the mod's doc comment, -1 == wakeup -1 => UpWoke(self.take_to_wake()), // As as described before, SPSC queues must be >= -2 -2 => UpSuccess, // Be sure to preserve the disconnected state, and the return value // in this case is going to be whether our data was received or not. // This manifests itself on whether we have an empty queue or not. // // Primarily, are required to drain the queue here because the port // will never remove this data. We can only have at most one item to // drain (the port drains the rest). DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); let first = self.queue.pop(); let second = self.queue.pop(); assert!(second.is_none()); match first { Some(..) => UpSuccess, // we failed to send the data None => UpDisconnected, // we successfully sent data } } // Otherwise we just sent some data on a non-waiting queue, so just // make sure the world is sane and carry on! n => { assert!(n >= 0); UpSuccess } } } // Consumes ownership of the 'to_wake' field. fn take_to_wake(&mut self) -> BlockedTask { let task = self.to_wake.load(atomic::SeqCst); self.to_wake.store(0, atomic::SeqCst); assert!(task!= 0); unsafe { BlockedTask::cast_from_uint(task) } } // Decrements the count on the channel for a sleeper, returning the sleeper // back if it shouldn't sleep. Note that this is the location where we take // steals into account. fn decrement(&mut self, task: BlockedTask) -> Result<(), BlockedTask> { assert_eq!(self.to_wake.load(atomic::SeqCst), 0); let n = unsafe { task.cast_to_uint() }; self.to_wake.store(n, atomic::SeqCst); let steals = self.steals; self.steals = 0; match self.cnt.fetch_sub(1 + steals, atomic::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); } // If we factor in our steals and notice that the channel has no // data, we successfully sleep n => { assert!(n >= 0); if n - steals <= 0 { return Ok(()) } } } self.to_wake.store(0, atomic::SeqCst); Err(unsafe { BlockedTask::cast_from_uint(n) }) } pub fn recv(&mut self) -> Result<T, Failure<T>> { // Optimistic preflight check (scheduling is expensive). match self.try_recv() { Err(Empty) => {} data => return data, } // Welp, our channel has no data. Deschedule the current task and // initiate the blocking protocol. let task: Box<Task> = Local::take(); task.deschedule(1, |task| { self.decrement(task) }); match self.try_recv() { // Messages which actually popped from the queue shouldn't count as // a steal, so offset the decrement here (we already have our // "steal" factored into the channel count above). data @ Ok(..) | data @ Err(Upgraded(..)) => { self.steals -= 1; data } data => data, } } pub fn try_recv(&mut self) -> Result<T, Failure<T>> { match self.queue.pop() { // If we stole some data, record to that effect (this will be // factored into cnt later on). // // Note that we don't allow steals to grow without bound in order to // prevent eventual overflow of either steals or cnt as an overflow // would have catastrophic results. Sometimes, steals > cnt, but // other times cnt > steals, so we don't know the relation between // steals and cnt. This code path is executed only rarely, so we do // a pretty slow operation, of swapping 0 into cnt, taking steals // down as much as possible (without going negative), and then // adding back in whatever we couldn't factor into steals. Some(data) => { if self.steals > MAX_STEALS { match self.cnt.swap(0, atomic::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); } n => { let m = cmp::min(n, self.steals); self.steals -= m; self.bump(n - m); } } assert!(self.steals >= 0);
Data(t) => Ok(t), GoUp(up) => Err(Upgraded(up)), } } None => { match self.cnt.load(atomic::SeqCst) { n if n!= DISCONNECTED => Err(Empty), // This is a little bit of a tricky case. We failed to pop // data above, and then we have viewed that the channel is // disconnected. In this window more data could have been // sent on the channel. It doesn't really make sense to // return that the channel is disconnected when there's // actually data on it, so be extra sure there's no data by // popping one more time. // // We can ignore steals because the other end is // disconnected and we'll never need to really factor in our // steals again. _ => { match self.queue.pop() { Some(Data(t)) => Ok(t), Some(GoUp(up)) => Err(Upgraded(up)), None => Err(Disconnected), } } } } } } pub fn drop_chan(&mut self) { // Dropping a channel is pretty simple, we just flag it as disconnected // and then wakeup a blocker if there is one. match self.cnt.swap(DISCONNECTED, atomic::SeqCst) { -1 => { self.take_to_wake().wake().map(|t| t.reawaken()); } DISCONNECTED => {} n => { assert!(n >= 0); } } } pub fn drop_port(&mut self) { // Dropping a port seems like a fairly trivial thing. In theory all we // need to do is flag that we're disconnected and then everything else // can take over (we don't have anyone to wake up). // // The catch for Ports is that we want to drop the entire contents of // the queue. There are multiple reasons for having this property, the // largest of which is that if another chan is waiting in this channel // (but not received yet), then waiting on that port will cause a // deadlock. // // So if we accept that we must now destroy the entire contents of the // queue, this code may make a bit more sense. The tricky part is that // we can't let any in-flight sends go un-dropped, we have to make sure // *everything* is dropped and nothing new will come onto the channel. // The first thing we do is set a flag saying that we're done for. All // sends are gated on this flag, so we're immediately guaranteed that // there are a bounded number of active sends that we'll have to deal // with. self.port_dropped.store(true, atomic::SeqCst); // Now that we're guaranteed to deal with a bounded number of senders, // we need to drain the queue. This draining process happens atomically // with respect to the "count" of the channel. If the count is nonzero // (with steals taken into account), then there must be data on the // channel. In this case we drain everything and then try again. We will // continue to fail while active senders send data while we're dropping // data, but eventually we're guaranteed to break out of this loop // (because there is a bounded number of senders). let mut steals = self.steals; while { let cnt = self.cnt.compare_and_swap( steals, DISCONNECTED, atomic::SeqCst); cnt!= DISCONNECTED && cnt!= steals } { loop { match self.queue.pop() { Some(..) => { steals += 1; } None => break } } } // At this point in time, we have gated all future senders from sending, // and we have flagged the channel as being disconnected. The senders // still have some responsibility, however, because some sends may not // complete until after we flag the disconnection. There are more // details in the sending methods that see DISCONNECTED } //////////////////////////////////////////////////////////////////////////// // select implementation //////////////////////////////////////////////////////////////////////////// // Tests to see whether this port can receive without blocking. If Ok is // returned, then that's the answer. If Err is returned, then the returned // port needs to be queried instead (an upgrade happened) pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> { // We peek at the queue to see if there's anything on it, and we use // this return value to determine if we should pop from the queue and // upgrade this channel immediately. If it looks like we've got an // upgrade pending, then go through the whole recv rigamarole to update // the internal state. match self.queue.peek() { Some(&GoUp(..)) => { match self.recv() { Err(Upgraded(port)) => Err(port), _ => unreachable!(), } } Some(..) => Ok(true), None => Ok(false) } } // increment the count on the channel (used for selection) fn bump(&mut self, amt: int) -> int { match self.cnt.fetch_add(amt, atomic::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); DISCONNECTED } n => n } } // Attempts to start selecting on this port. Like a oneshot, this can fail // immediately because of an upgrade. pub fn start_selection(&mut self, task: BlockedTask) -> SelectionResult<T> { match self.decrement(task) { Ok(()) => SelSuccess, Err(task) => { let ret = match self.queue.peek() { Some(&GoUp(..)) => { match self.queue.pop() { Some(GoUp(port)) => SelUpgraded(task, port), _ => unreachable!(), } } Some(..) => SelCanceled(task), None => SelCanceled(task), }; // Undo our decrement above, and we should be guaranteed that the // previous value is positive because we're not going to sleep let prev = self.bump(1); assert!(prev == DISCONNECTED || prev >= 0); return ret; } } } // Removes a previous task from being blocked in this port pub fn abort_selection(&mut self, was_upgrade: bool) -> Result<bool, Receiver<T>> { // If we're aborting selection after upgrading from a oneshot, then // we're guarantee that no one is waiting. The only way that we could // have seen the upgrade is if data was actually sent on the channel // half again. For us, this means that there is guaranteed to be data on // this channel. Furthermore, we're guaranteed that there was no // start_selection previously, so there's no need to modify `self.cnt` // at all. // // Hence, because of these invariants, we immediately return `Ok(true)`. // Note that the data may not actually be sent on the channel just yet. // The other end could have flagged the upgrade but not sent data to // this end. This is fine because we know it's a small bounded windows // of time until the data is actually sent. if was_upgrade { assert_eq!(self.steals, 0); assert_eq!(self.to_wake.load(atomic::SeqCst), 0); return Ok(true) } // We want to make sure that the count on the channel goes non-negative, // and in the stream case we can have at most one steal, so just assume // that we had one steal. let steals = 1; let prev = self.bump(steals + 1); // If we were previously disconnected, then we know for sure that there // is no task in to_wake, so just keep going let has_data = if prev == DISCONNECTED { assert_eq!(self.to_wake.load(atomic::SeqCst), 0); true // there is data, that data is that we're disconnected } else { let cur = prev + steals + 1; assert!(cur >= 0); // If the previous count was negative, then we just made things go // positive, hence we passed the -1 boundary and we're responsible // for removing the to_wake() field and trashing it. // // If the previous count was positive then we're in a tougher // situation. A possible race is that a sender just incremented // through -1 (meaning it's going to try to wake a task up), but it // hasn't yet read the to_wake. In order to prevent a future recv() // from waking up too early (this sender picking up the plastered // over to_wake), we spin loop here waiting for to_wake to be 0. // Note that this entire select() implementation needs an overhaul, // and this is *not* the worst part of it, so this is not done as a // final solution but rather out of necessity for now to get // something working. if prev < 0 { self.take_to_wake().trash(); } else { while self.to_wake.load(atomic::SeqCst)!= 0 { Thread::yield_now(); } } assert_eq!(self.steals, 0); self.steals = steals; // if we were previously positive, then there's surely data to // receive prev >= 0 }; // Now that we've determined that this queue "has data", we peek at the // queue to see if the data is an upgrade or not. If it's an upgrade, // then we need to destroy this port and abort selection on the // upgraded port. if has_data { match self.queue.peek() { Some(&GoUp(..)) => { match self.queue.pop() { Some(GoUp(port)) => Err(port), _ => unreachable!(), } } _ => Ok(true), } } else { Ok(false) } } } #[unsafe_
} self.steals += 1; match data {
random_line_split
stream.rs
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. /// Stream channels /// /// This is the flavor of channels which are optimized for one sender and one /// receiver. The sender will be upgraded to a shared channel if the channel is /// cloned. /// /// High level implementation details can be found in the comment of the parent /// module. pub use self::Failure::*; pub use self::UpgradeResult::*; pub use self::SelectionResult::*; use self::Message::*; use core::prelude::*; use alloc::boxed::Box; use core::cmp; use core::int; use rustrt::local::Local; use rustrt::task::{Task, BlockedTask}; use rustrt::thread::Thread; use sync::atomic; use comm::spsc_queue as spsc; use comm::Receiver; const DISCONNECTED: int = int::MIN; #[cfg(test)] const MAX_STEALS: int = 5; #[cfg(not(test))] const MAX_STEALS: int = 1 << 20; pub struct Packet<T> { queue: spsc::Queue<Message<T>>, // internal queue for all message cnt: atomic::AtomicInt, // How many items are on this channel steals: int, // How many times has a port received without blocking? to_wake: atomic::AtomicUint, // Task to wake up port_dropped: atomic::AtomicBool, // flag if the channel has been destroyed. } pub enum Failure<T> { Empty, Disconnected, Upgraded(Receiver<T>), } pub enum UpgradeResult { UpSuccess, UpDisconnected, UpWoke(BlockedTask), } pub enum SelectionResult<T> { SelSuccess, SelCanceled(BlockedTask), SelUpgraded(BlockedTask, Receiver<T>), } // Any message could contain an "upgrade request" to a new shared port, so the // internal queue it's a queue of T, but rather Message<T> enum Message<T> { Data(T), GoUp(Receiver<T>), } impl<T: Send> Packet<T> { pub fn new() -> Packet<T> { Packet { queue: unsafe { spsc::Queue::new(128) }, cnt: atomic::AtomicInt::new(0), steals: 0, to_wake: atomic::AtomicUint::new(0), port_dropped: atomic::AtomicBool::new(false), } } pub fn send(&mut self, t: T) -> Result<(), T> { // If the other port has deterministically gone away, then definitely // must return the data back up the stack. Otherwise, the data is // considered as being sent. if self.port_dropped.load(atomic::SeqCst) { return Err(t) } match self.do_send(Data(t)) { UpSuccess | UpDisconnected => {}, UpWoke(task) => { task.wake().map(|t| t.reawaken()); } } Ok(()) } pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult { // If the port has gone away, then there's no need to proceed any // further. if self.port_dropped.load(atomic::SeqCst) { return UpDisconnected } self.do_send(GoUp(up)) } fn do_send(&mut self, t: Message<T>) -> UpgradeResult { self.queue.push(t); match self.cnt.fetch_add(1, atomic::SeqCst) { // As described in the mod's doc comment, -1 == wakeup -1 => UpWoke(self.take_to_wake()), // As as described before, SPSC queues must be >= -2 -2 => UpSuccess, // Be sure to preserve the disconnected state, and the return value // in this case is going to be whether our data was received or not. // This manifests itself on whether we have an empty queue or not. // // Primarily, are required to drain the queue here because the port // will never remove this data. We can only have at most one item to // drain (the port drains the rest). DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); let first = self.queue.pop(); let second = self.queue.pop(); assert!(second.is_none()); match first { Some(..) => UpSuccess, // we failed to send the data None => UpDisconnected, // we successfully sent data } } // Otherwise we just sent some data on a non-waiting queue, so just // make sure the world is sane and carry on! n => { assert!(n >= 0); UpSuccess } } } // Consumes ownership of the 'to_wake' field. fn take_to_wake(&mut self) -> BlockedTask { let task = self.to_wake.load(atomic::SeqCst); self.to_wake.store(0, atomic::SeqCst); assert!(task!= 0); unsafe { BlockedTask::cast_from_uint(task) } } // Decrements the count on the channel for a sleeper, returning the sleeper // back if it shouldn't sleep. Note that this is the location where we take // steals into account. fn decrement(&mut self, task: BlockedTask) -> Result<(), BlockedTask> { assert_eq!(self.to_wake.load(atomic::SeqCst), 0); let n = unsafe { task.cast_to_uint() }; self.to_wake.store(n, atomic::SeqCst); let steals = self.steals; self.steals = 0; match self.cnt.fetch_sub(1 + steals, atomic::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); } // If we factor in our steals and notice that the channel has no // data, we successfully sleep n => { assert!(n >= 0); if n - steals <= 0 { return Ok(()) } } } self.to_wake.store(0, atomic::SeqCst); Err(unsafe { BlockedTask::cast_from_uint(n) }) } pub fn recv(&mut self) -> Result<T, Failure<T>> { // Optimistic preflight check (scheduling is expensive). match self.try_recv() { Err(Empty) => {} data => return data, } // Welp, our channel has no data. Deschedule the current task and // initiate the blocking protocol. let task: Box<Task> = Local::take(); task.deschedule(1, |task| { self.decrement(task) }); match self.try_recv() { // Messages which actually popped from the queue shouldn't count as // a steal, so offset the decrement here (we already have our // "steal" factored into the channel count above). data @ Ok(..) | data @ Err(Upgraded(..)) => { self.steals -= 1; data } data => data, } } pub fn try_recv(&mut self) -> Result<T, Failure<T>> { match self.queue.pop() { // If we stole some data, record to that effect (this will be // factored into cnt later on). // // Note that we don't allow steals to grow without bound in order to // prevent eventual overflow of either steals or cnt as an overflow // would have catastrophic results. Sometimes, steals > cnt, but // other times cnt > steals, so we don't know the relation between // steals and cnt. This code path is executed only rarely, so we do // a pretty slow operation, of swapping 0 into cnt, taking steals // down as much as possible (without going negative), and then // adding back in whatever we couldn't factor into steals. Some(data) => { if self.steals > MAX_STEALS { match self.cnt.swap(0, atomic::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); } n => { let m = cmp::min(n, self.steals); self.steals -= m; self.bump(n - m); } } assert!(self.steals >= 0); } self.steals += 1; match data { Data(t) => Ok(t), GoUp(up) => Err(Upgraded(up)), } } None => { match self.cnt.load(atomic::SeqCst) { n if n!= DISCONNECTED => Err(Empty), // This is a little bit of a tricky case. We failed to pop // data above, and then we have viewed that the channel is // disconnected. In this window more data could have been // sent on the channel. It doesn't really make sense to // return that the channel is disconnected when there's // actually data on it, so be extra sure there's no data by // popping one more time. // // We can ignore steals because the other end is // disconnected and we'll never need to really factor in our // steals again. _ => { match self.queue.pop() { Some(Data(t)) => Ok(t), Some(GoUp(up)) => Err(Upgraded(up)), None => Err(Disconnected), } } } } } } pub fn drop_chan(&mut self) { // Dropping a channel is pretty simple, we just flag it as disconnected // and then wakeup a blocker if there is one. match self.cnt.swap(DISCONNECTED, atomic::SeqCst) { -1 => { self.take_to_wake().wake().map(|t| t.reawaken()); } DISCONNECTED => {} n =>
} } pub fn drop_port(&mut self) { // Dropping a port seems like a fairly trivial thing. In theory all we // need to do is flag that we're disconnected and then everything else // can take over (we don't have anyone to wake up). // // The catch for Ports is that we want to drop the entire contents of // the queue. There are multiple reasons for having this property, the // largest of which is that if another chan is waiting in this channel // (but not received yet), then waiting on that port will cause a // deadlock. // // So if we accept that we must now destroy the entire contents of the // queue, this code may make a bit more sense. The tricky part is that // we can't let any in-flight sends go un-dropped, we have to make sure // *everything* is dropped and nothing new will come onto the channel. // The first thing we do is set a flag saying that we're done for. All // sends are gated on this flag, so we're immediately guaranteed that // there are a bounded number of active sends that we'll have to deal // with. self.port_dropped.store(true, atomic::SeqCst); // Now that we're guaranteed to deal with a bounded number of senders, // we need to drain the queue. This draining process happens atomically // with respect to the "count" of the channel. If the count is nonzero // (with steals taken into account), then there must be data on the // channel. In this case we drain everything and then try again. We will // continue to fail while active senders send data while we're dropping // data, but eventually we're guaranteed to break out of this loop // (because there is a bounded number of senders). let mut steals = self.steals; while { let cnt = self.cnt.compare_and_swap( steals, DISCONNECTED, atomic::SeqCst); cnt!= DISCONNECTED && cnt!= steals } { loop { match self.queue.pop() { Some(..) => { steals += 1; } None => break } } } // At this point in time, we have gated all future senders from sending, // and we have flagged the channel as being disconnected. The senders // still have some responsibility, however, because some sends may not // complete until after we flag the disconnection. There are more // details in the sending methods that see DISCONNECTED } //////////////////////////////////////////////////////////////////////////// // select implementation //////////////////////////////////////////////////////////////////////////// // Tests to see whether this port can receive without blocking. If Ok is // returned, then that's the answer. If Err is returned, then the returned // port needs to be queried instead (an upgrade happened) pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> { // We peek at the queue to see if there's anything on it, and we use // this return value to determine if we should pop from the queue and // upgrade this channel immediately. If it looks like we've got an // upgrade pending, then go through the whole recv rigamarole to update // the internal state. match self.queue.peek() { Some(&GoUp(..)) => { match self.recv() { Err(Upgraded(port)) => Err(port), _ => unreachable!(), } } Some(..) => Ok(true), None => Ok(false) } } // increment the count on the channel (used for selection) fn bump(&mut self, amt: int) -> int { match self.cnt.fetch_add(amt, atomic::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); DISCONNECTED } n => n } } // Attempts to start selecting on this port. Like a oneshot, this can fail // immediately because of an upgrade. pub fn start_selection(&mut self, task: BlockedTask) -> SelectionResult<T> { match self.decrement(task) { Ok(()) => SelSuccess, Err(task) => { let ret = match self.queue.peek() { Some(&GoUp(..)) => { match self.queue.pop() { Some(GoUp(port)) => SelUpgraded(task, port), _ => unreachable!(), } } Some(..) => SelCanceled(task), None => SelCanceled(task), }; // Undo our decrement above, and we should be guaranteed that the // previous value is positive because we're not going to sleep let prev = self.bump(1); assert!(prev == DISCONNECTED || prev >= 0); return ret; } } } // Removes a previous task from being blocked in this port pub fn abort_selection(&mut self, was_upgrade: bool) -> Result<bool, Receiver<T>> { // If we're aborting selection after upgrading from a oneshot, then // we're guarantee that no one is waiting. The only way that we could // have seen the upgrade is if data was actually sent on the channel // half again. For us, this means that there is guaranteed to be data on // this channel. Furthermore, we're guaranteed that there was no // start_selection previously, so there's no need to modify `self.cnt` // at all. // // Hence, because of these invariants, we immediately return `Ok(true)`. // Note that the data may not actually be sent on the channel just yet. // The other end could have flagged the upgrade but not sent data to // this end. This is fine because we know it's a small bounded windows // of time until the data is actually sent. if was_upgrade { assert_eq!(self.steals, 0); assert_eq!(self.to_wake.load(atomic::SeqCst), 0); return Ok(true) } // We want to make sure that the count on the channel goes non-negative, // and in the stream case we can have at most one steal, so just assume // that we had one steal. let steals = 1; let prev = self.bump(steals + 1); // If we were previously disconnected, then we know for sure that there // is no task in to_wake, so just keep going let has_data = if prev == DISCONNECTED { assert_eq!(self.to_wake.load(atomic::SeqCst), 0); true // there is data, that data is that we're disconnected } else { let cur = prev + steals + 1; assert!(cur >= 0); // If the previous count was negative, then we just made things go // positive, hence we passed the -1 boundary and we're responsible // for removing the to_wake() field and trashing it. // // If the previous count was positive then we're in a tougher // situation. A possible race is that a sender just incremented // through -1 (meaning it's going to try to wake a task up), but it // hasn't yet read the to_wake. In order to prevent a future recv() // from waking up too early (this sender picking up the plastered // over to_wake), we spin loop here waiting for to_wake to be 0. // Note that this entire select() implementation needs an overhaul, // and this is *not* the worst part of it, so this is not done as a // final solution but rather out of necessity for now to get // something working. if prev < 0 { self.take_to_wake().trash(); } else { while self.to_wake.load(atomic::SeqCst)!= 0 { Thread::yield_now(); } } assert_eq!(self.steals, 0); self.steals = steals; // if we were previously positive, then there's surely data to // receive prev >= 0 }; // Now that we've determined that this queue "has data", we peek at the // queue to see if the data is an upgrade or not. If it's an upgrade, // then we need to destroy this port and abort selection on the // upgraded port. if has_data { match self.queue.peek() { Some(&GoUp(..)) => { match self.queue.pop() { Some(GoUp(port)) => Err(port), _ => unreachable!(), } } _ => Ok(true), } } else { Ok(false) } } } #[
{ assert!(n >= 0); }
conditional_block
stream.rs
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. /// Stream channels /// /// This is the flavor of channels which are optimized for one sender and one /// receiver. The sender will be upgraded to a shared channel if the channel is /// cloned. /// /// High level implementation details can be found in the comment of the parent /// module. pub use self::Failure::*; pub use self::UpgradeResult::*; pub use self::SelectionResult::*; use self::Message::*; use core::prelude::*; use alloc::boxed::Box; use core::cmp; use core::int; use rustrt::local::Local; use rustrt::task::{Task, BlockedTask}; use rustrt::thread::Thread; use sync::atomic; use comm::spsc_queue as spsc; use comm::Receiver; const DISCONNECTED: int = int::MIN; #[cfg(test)] const MAX_STEALS: int = 5; #[cfg(not(test))] const MAX_STEALS: int = 1 << 20; pub struct Packet<T> { queue: spsc::Queue<Message<T>>, // internal queue for all message cnt: atomic::AtomicInt, // How many items are on this channel steals: int, // How many times has a port received without blocking? to_wake: atomic::AtomicUint, // Task to wake up port_dropped: atomic::AtomicBool, // flag if the channel has been destroyed. } pub enum Failure<T> { Empty, Disconnected, Upgraded(Receiver<T>), } pub enum UpgradeResult { UpSuccess, UpDisconnected, UpWoke(BlockedTask), } pub enum SelectionResult<T> { SelSuccess, SelCanceled(BlockedTask), SelUpgraded(BlockedTask, Receiver<T>), } // Any message could contain an "upgrade request" to a new shared port, so the // internal queue it's a queue of T, but rather Message<T> enum Message<T> { Data(T), GoUp(Receiver<T>), } impl<T: Send> Packet<T> { pub fn new() -> Packet<T> { Packet { queue: unsafe { spsc::Queue::new(128) }, cnt: atomic::AtomicInt::new(0), steals: 0, to_wake: atomic::AtomicUint::new(0), port_dropped: atomic::AtomicBool::new(false), } } pub fn send(&mut self, t: T) -> Result<(), T>
pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult { // If the port has gone away, then there's no need to proceed any // further. if self.port_dropped.load(atomic::SeqCst) { return UpDisconnected } self.do_send(GoUp(up)) } fn do_send(&mut self, t: Message<T>) -> UpgradeResult { self.queue.push(t); match self.cnt.fetch_add(1, atomic::SeqCst) { // As described in the mod's doc comment, -1 == wakeup -1 => UpWoke(self.take_to_wake()), // As as described before, SPSC queues must be >= -2 -2 => UpSuccess, // Be sure to preserve the disconnected state, and the return value // in this case is going to be whether our data was received or not. // This manifests itself on whether we have an empty queue or not. // // Primarily, are required to drain the queue here because the port // will never remove this data. We can only have at most one item to // drain (the port drains the rest). DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); let first = self.queue.pop(); let second = self.queue.pop(); assert!(second.is_none()); match first { Some(..) => UpSuccess, // we failed to send the data None => UpDisconnected, // we successfully sent data } } // Otherwise we just sent some data on a non-waiting queue, so just // make sure the world is sane and carry on! n => { assert!(n >= 0); UpSuccess } } } // Consumes ownership of the 'to_wake' field. fn take_to_wake(&mut self) -> BlockedTask { let task = self.to_wake.load(atomic::SeqCst); self.to_wake.store(0, atomic::SeqCst); assert!(task!= 0); unsafe { BlockedTask::cast_from_uint(task) } } // Decrements the count on the channel for a sleeper, returning the sleeper // back if it shouldn't sleep. Note that this is the location where we take // steals into account. fn decrement(&mut self, task: BlockedTask) -> Result<(), BlockedTask> { assert_eq!(self.to_wake.load(atomic::SeqCst), 0); let n = unsafe { task.cast_to_uint() }; self.to_wake.store(n, atomic::SeqCst); let steals = self.steals; self.steals = 0; match self.cnt.fetch_sub(1 + steals, atomic::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); } // If we factor in our steals and notice that the channel has no // data, we successfully sleep n => { assert!(n >= 0); if n - steals <= 0 { return Ok(()) } } } self.to_wake.store(0, atomic::SeqCst); Err(unsafe { BlockedTask::cast_from_uint(n) }) } pub fn recv(&mut self) -> Result<T, Failure<T>> { // Optimistic preflight check (scheduling is expensive). match self.try_recv() { Err(Empty) => {} data => return data, } // Welp, our channel has no data. Deschedule the current task and // initiate the blocking protocol. let task: Box<Task> = Local::take(); task.deschedule(1, |task| { self.decrement(task) }); match self.try_recv() { // Messages which actually popped from the queue shouldn't count as // a steal, so offset the decrement here (we already have our // "steal" factored into the channel count above). data @ Ok(..) | data @ Err(Upgraded(..)) => { self.steals -= 1; data } data => data, } } pub fn try_recv(&mut self) -> Result<T, Failure<T>> { match self.queue.pop() { // If we stole some data, record to that effect (this will be // factored into cnt later on). // // Note that we don't allow steals to grow without bound in order to // prevent eventual overflow of either steals or cnt as an overflow // would have catastrophic results. Sometimes, steals > cnt, but // other times cnt > steals, so we don't know the relation between // steals and cnt. This code path is executed only rarely, so we do // a pretty slow operation, of swapping 0 into cnt, taking steals // down as much as possible (without going negative), and then // adding back in whatever we couldn't factor into steals. Some(data) => { if self.steals > MAX_STEALS { match self.cnt.swap(0, atomic::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); } n => { let m = cmp::min(n, self.steals); self.steals -= m; self.bump(n - m); } } assert!(self.steals >= 0); } self.steals += 1; match data { Data(t) => Ok(t), GoUp(up) => Err(Upgraded(up)), } } None => { match self.cnt.load(atomic::SeqCst) { n if n!= DISCONNECTED => Err(Empty), // This is a little bit of a tricky case. We failed to pop // data above, and then we have viewed that the channel is // disconnected. In this window more data could have been // sent on the channel. It doesn't really make sense to // return that the channel is disconnected when there's // actually data on it, so be extra sure there's no data by // popping one more time. // // We can ignore steals because the other end is // disconnected and we'll never need to really factor in our // steals again. _ => { match self.queue.pop() { Some(Data(t)) => Ok(t), Some(GoUp(up)) => Err(Upgraded(up)), None => Err(Disconnected), } } } } } } pub fn drop_chan(&mut self) { // Dropping a channel is pretty simple, we just flag it as disconnected // and then wakeup a blocker if there is one. match self.cnt.swap(DISCONNECTED, atomic::SeqCst) { -1 => { self.take_to_wake().wake().map(|t| t.reawaken()); } DISCONNECTED => {} n => { assert!(n >= 0); } } } pub fn drop_port(&mut self) { // Dropping a port seems like a fairly trivial thing. In theory all we // need to do is flag that we're disconnected and then everything else // can take over (we don't have anyone to wake up). // // The catch for Ports is that we want to drop the entire contents of // the queue. There are multiple reasons for having this property, the // largest of which is that if another chan is waiting in this channel // (but not received yet), then waiting on that port will cause a // deadlock. // // So if we accept that we must now destroy the entire contents of the // queue, this code may make a bit more sense. The tricky part is that // we can't let any in-flight sends go un-dropped, we have to make sure // *everything* is dropped and nothing new will come onto the channel. // The first thing we do is set a flag saying that we're done for. All // sends are gated on this flag, so we're immediately guaranteed that // there are a bounded number of active sends that we'll have to deal // with. self.port_dropped.store(true, atomic::SeqCst); // Now that we're guaranteed to deal with a bounded number of senders, // we need to drain the queue. This draining process happens atomically // with respect to the "count" of the channel. If the count is nonzero // (with steals taken into account), then there must be data on the // channel. In this case we drain everything and then try again. We will // continue to fail while active senders send data while we're dropping // data, but eventually we're guaranteed to break out of this loop // (because there is a bounded number of senders). let mut steals = self.steals; while { let cnt = self.cnt.compare_and_swap( steals, DISCONNECTED, atomic::SeqCst); cnt!= DISCONNECTED && cnt!= steals } { loop { match self.queue.pop() { Some(..) => { steals += 1; } None => break } } } // At this point in time, we have gated all future senders from sending, // and we have flagged the channel as being disconnected. The senders // still have some responsibility, however, because some sends may not // complete until after we flag the disconnection. There are more // details in the sending methods that see DISCONNECTED } //////////////////////////////////////////////////////////////////////////// // select implementation //////////////////////////////////////////////////////////////////////////// // Tests to see whether this port can receive without blocking. If Ok is // returned, then that's the answer. If Err is returned, then the returned // port needs to be queried instead (an upgrade happened) pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> { // We peek at the queue to see if there's anything on it, and we use // this return value to determine if we should pop from the queue and // upgrade this channel immediately. If it looks like we've got an // upgrade pending, then go through the whole recv rigamarole to update // the internal state. match self.queue.peek() { Some(&GoUp(..)) => { match self.recv() { Err(Upgraded(port)) => Err(port), _ => unreachable!(), } } Some(..) => Ok(true), None => Ok(false) } } // increment the count on the channel (used for selection) fn bump(&mut self, amt: int) -> int { match self.cnt.fetch_add(amt, atomic::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); DISCONNECTED } n => n } } // Attempts to start selecting on this port. Like a oneshot, this can fail // immediately because of an upgrade. pub fn start_selection(&mut self, task: BlockedTask) -> SelectionResult<T> { match self.decrement(task) { Ok(()) => SelSuccess, Err(task) => { let ret = match self.queue.peek() { Some(&GoUp(..)) => { match self.queue.pop() { Some(GoUp(port)) => SelUpgraded(task, port), _ => unreachable!(), } } Some(..) => SelCanceled(task), None => SelCanceled(task), }; // Undo our decrement above, and we should be guaranteed that the // previous value is positive because we're not going to sleep let prev = self.bump(1); assert!(prev == DISCONNECTED || prev >= 0); return ret; } } } // Removes a previous task from being blocked in this port pub fn abort_selection(&mut self, was_upgrade: bool) -> Result<bool, Receiver<T>> { // If we're aborting selection after upgrading from a oneshot, then // we're guarantee that no one is waiting. The only way that we could // have seen the upgrade is if data was actually sent on the channel // half again. For us, this means that there is guaranteed to be data on // this channel. Furthermore, we're guaranteed that there was no // start_selection previously, so there's no need to modify `self.cnt` // at all. // // Hence, because of these invariants, we immediately return `Ok(true)`. // Note that the data may not actually be sent on the channel just yet. // The other end could have flagged the upgrade but not sent data to // this end. This is fine because we know it's a small bounded windows // of time until the data is actually sent. if was_upgrade { assert_eq!(self.steals, 0); assert_eq!(self.to_wake.load(atomic::SeqCst), 0); return Ok(true) } // We want to make sure that the count on the channel goes non-negative, // and in the stream case we can have at most one steal, so just assume // that we had one steal. let steals = 1; let prev = self.bump(steals + 1); // If we were previously disconnected, then we know for sure that there // is no task in to_wake, so just keep going let has_data = if prev == DISCONNECTED { assert_eq!(self.to_wake.load(atomic::SeqCst), 0); true // there is data, that data is that we're disconnected } else { let cur = prev + steals + 1; assert!(cur >= 0); // If the previous count was negative, then we just made things go // positive, hence we passed the -1 boundary and we're responsible // for removing the to_wake() field and trashing it. // // If the previous count was positive then we're in a tougher // situation. A possible race is that a sender just incremented // through -1 (meaning it's going to try to wake a task up), but it // hasn't yet read the to_wake. In order to prevent a future recv() // from waking up too early (this sender picking up the plastered // over to_wake), we spin loop here waiting for to_wake to be 0. // Note that this entire select() implementation needs an overhaul, // and this is *not* the worst part of it, so this is not done as a // final solution but rather out of necessity for now to get // something working. if prev < 0 { self.take_to_wake().trash(); } else { while self.to_wake.load(atomic::SeqCst)!= 0 { Thread::yield_now(); } } assert_eq!(self.steals, 0); self.steals = steals; // if we were previously positive, then there's surely data to // receive prev >= 0 }; // Now that we've determined that this queue "has data", we peek at the // queue to see if the data is an upgrade or not. If it's an upgrade, // then we need to destroy this port and abort selection on the // upgraded port. if has_data { match self.queue.peek() { Some(&GoUp(..)) => { match self.queue.pop() { Some(GoUp(port)) => Err(port), _ => unreachable!(), } } _ => Ok(true), } } else { Ok(false) } } } #[
{ // If the other port has deterministically gone away, then definitely // must return the data back up the stack. Otherwise, the data is // considered as being sent. if self.port_dropped.load(atomic::SeqCst) { return Err(t) } match self.do_send(Data(t)) { UpSuccess | UpDisconnected => {}, UpWoke(task) => { task.wake().map(|t| t.reawaken()); } } Ok(()) }
identifier_body
stream.rs
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. /// Stream channels /// /// This is the flavor of channels which are optimized for one sender and one /// receiver. The sender will be upgraded to a shared channel if the channel is /// cloned. /// /// High level implementation details can be found in the comment of the parent /// module. pub use self::Failure::*; pub use self::UpgradeResult::*; pub use self::SelectionResult::*; use self::Message::*; use core::prelude::*; use alloc::boxed::Box; use core::cmp; use core::int; use rustrt::local::Local; use rustrt::task::{Task, BlockedTask}; use rustrt::thread::Thread; use sync::atomic; use comm::spsc_queue as spsc; use comm::Receiver; const DISCONNECTED: int = int::MIN; #[cfg(test)] const MAX_STEALS: int = 5; #[cfg(not(test))] const MAX_STEALS: int = 1 << 20; pub struct Packet<T> { queue: spsc::Queue<Message<T>>, // internal queue for all message cnt: atomic::AtomicInt, // How many items are on this channel steals: int, // How many times has a port received without blocking? to_wake: atomic::AtomicUint, // Task to wake up port_dropped: atomic::AtomicBool, // flag if the channel has been destroyed. } pub enum Failure<T> { Empty, Disconnected, Upgraded(Receiver<T>), } pub enum
{ UpSuccess, UpDisconnected, UpWoke(BlockedTask), } pub enum SelectionResult<T> { SelSuccess, SelCanceled(BlockedTask), SelUpgraded(BlockedTask, Receiver<T>), } // Any message could contain an "upgrade request" to a new shared port, so the // internal queue it's a queue of T, but rather Message<T> enum Message<T> { Data(T), GoUp(Receiver<T>), } impl<T: Send> Packet<T> { pub fn new() -> Packet<T> { Packet { queue: unsafe { spsc::Queue::new(128) }, cnt: atomic::AtomicInt::new(0), steals: 0, to_wake: atomic::AtomicUint::new(0), port_dropped: atomic::AtomicBool::new(false), } } pub fn send(&mut self, t: T) -> Result<(), T> { // If the other port has deterministically gone away, then definitely // must return the data back up the stack. Otherwise, the data is // considered as being sent. if self.port_dropped.load(atomic::SeqCst) { return Err(t) } match self.do_send(Data(t)) { UpSuccess | UpDisconnected => {}, UpWoke(task) => { task.wake().map(|t| t.reawaken()); } } Ok(()) } pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult { // If the port has gone away, then there's no need to proceed any // further. if self.port_dropped.load(atomic::SeqCst) { return UpDisconnected } self.do_send(GoUp(up)) } fn do_send(&mut self, t: Message<T>) -> UpgradeResult { self.queue.push(t); match self.cnt.fetch_add(1, atomic::SeqCst) { // As described in the mod's doc comment, -1 == wakeup -1 => UpWoke(self.take_to_wake()), // As as described before, SPSC queues must be >= -2 -2 => UpSuccess, // Be sure to preserve the disconnected state, and the return value // in this case is going to be whether our data was received or not. // This manifests itself on whether we have an empty queue or not. // // Primarily, are required to drain the queue here because the port // will never remove this data. We can only have at most one item to // drain (the port drains the rest). DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); let first = self.queue.pop(); let second = self.queue.pop(); assert!(second.is_none()); match first { Some(..) => UpSuccess, // we failed to send the data None => UpDisconnected, // we successfully sent data } } // Otherwise we just sent some data on a non-waiting queue, so just // make sure the world is sane and carry on! n => { assert!(n >= 0); UpSuccess } } } // Consumes ownership of the 'to_wake' field. fn take_to_wake(&mut self) -> BlockedTask { let task = self.to_wake.load(atomic::SeqCst); self.to_wake.store(0, atomic::SeqCst); assert!(task!= 0); unsafe { BlockedTask::cast_from_uint(task) } } // Decrements the count on the channel for a sleeper, returning the sleeper // back if it shouldn't sleep. Note that this is the location where we take // steals into account. fn decrement(&mut self, task: BlockedTask) -> Result<(), BlockedTask> { assert_eq!(self.to_wake.load(atomic::SeqCst), 0); let n = unsafe { task.cast_to_uint() }; self.to_wake.store(n, atomic::SeqCst); let steals = self.steals; self.steals = 0; match self.cnt.fetch_sub(1 + steals, atomic::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); } // If we factor in our steals and notice that the channel has no // data, we successfully sleep n => { assert!(n >= 0); if n - steals <= 0 { return Ok(()) } } } self.to_wake.store(0, atomic::SeqCst); Err(unsafe { BlockedTask::cast_from_uint(n) }) } pub fn recv(&mut self) -> Result<T, Failure<T>> { // Optimistic preflight check (scheduling is expensive). match self.try_recv() { Err(Empty) => {} data => return data, } // Welp, our channel has no data. Deschedule the current task and // initiate the blocking protocol. let task: Box<Task> = Local::take(); task.deschedule(1, |task| { self.decrement(task) }); match self.try_recv() { // Messages which actually popped from the queue shouldn't count as // a steal, so offset the decrement here (we already have our // "steal" factored into the channel count above). data @ Ok(..) | data @ Err(Upgraded(..)) => { self.steals -= 1; data } data => data, } } pub fn try_recv(&mut self) -> Result<T, Failure<T>> { match self.queue.pop() { // If we stole some data, record to that effect (this will be // factored into cnt later on). // // Note that we don't allow steals to grow without bound in order to // prevent eventual overflow of either steals or cnt as an overflow // would have catastrophic results. Sometimes, steals > cnt, but // other times cnt > steals, so we don't know the relation between // steals and cnt. This code path is executed only rarely, so we do // a pretty slow operation, of swapping 0 into cnt, taking steals // down as much as possible (without going negative), and then // adding back in whatever we couldn't factor into steals. Some(data) => { if self.steals > MAX_STEALS { match self.cnt.swap(0, atomic::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); } n => { let m = cmp::min(n, self.steals); self.steals -= m; self.bump(n - m); } } assert!(self.steals >= 0); } self.steals += 1; match data { Data(t) => Ok(t), GoUp(up) => Err(Upgraded(up)), } } None => { match self.cnt.load(atomic::SeqCst) { n if n!= DISCONNECTED => Err(Empty), // This is a little bit of a tricky case. We failed to pop // data above, and then we have viewed that the channel is // disconnected. In this window more data could have been // sent on the channel. It doesn't really make sense to // return that the channel is disconnected when there's // actually data on it, so be extra sure there's no data by // popping one more time. // // We can ignore steals because the other end is // disconnected and we'll never need to really factor in our // steals again. _ => { match self.queue.pop() { Some(Data(t)) => Ok(t), Some(GoUp(up)) => Err(Upgraded(up)), None => Err(Disconnected), } } } } } } pub fn drop_chan(&mut self) { // Dropping a channel is pretty simple, we just flag it as disconnected // and then wakeup a blocker if there is one. match self.cnt.swap(DISCONNECTED, atomic::SeqCst) { -1 => { self.take_to_wake().wake().map(|t| t.reawaken()); } DISCONNECTED => {} n => { assert!(n >= 0); } } } pub fn drop_port(&mut self) { // Dropping a port seems like a fairly trivial thing. In theory all we // need to do is flag that we're disconnected and then everything else // can take over (we don't have anyone to wake up). // // The catch for Ports is that we want to drop the entire contents of // the queue. There are multiple reasons for having this property, the // largest of which is that if another chan is waiting in this channel // (but not received yet), then waiting on that port will cause a // deadlock. // // So if we accept that we must now destroy the entire contents of the // queue, this code may make a bit more sense. The tricky part is that // we can't let any in-flight sends go un-dropped, we have to make sure // *everything* is dropped and nothing new will come onto the channel. // The first thing we do is set a flag saying that we're done for. All // sends are gated on this flag, so we're immediately guaranteed that // there are a bounded number of active sends that we'll have to deal // with. self.port_dropped.store(true, atomic::SeqCst); // Now that we're guaranteed to deal with a bounded number of senders, // we need to drain the queue. This draining process happens atomically // with respect to the "count" of the channel. If the count is nonzero // (with steals taken into account), then there must be data on the // channel. In this case we drain everything and then try again. We will // continue to fail while active senders send data while we're dropping // data, but eventually we're guaranteed to break out of this loop // (because there is a bounded number of senders). let mut steals = self.steals; while { let cnt = self.cnt.compare_and_swap( steals, DISCONNECTED, atomic::SeqCst); cnt!= DISCONNECTED && cnt!= steals } { loop { match self.queue.pop() { Some(..) => { steals += 1; } None => break } } } // At this point in time, we have gated all future senders from sending, // and we have flagged the channel as being disconnected. The senders // still have some responsibility, however, because some sends may not // complete until after we flag the disconnection. There are more // details in the sending methods that see DISCONNECTED } //////////////////////////////////////////////////////////////////////////// // select implementation //////////////////////////////////////////////////////////////////////////// // Tests to see whether this port can receive without blocking. If Ok is // returned, then that's the answer. If Err is returned, then the returned // port needs to be queried instead (an upgrade happened) pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> { // We peek at the queue to see if there's anything on it, and we use // this return value to determine if we should pop from the queue and // upgrade this channel immediately. If it looks like we've got an // upgrade pending, then go through the whole recv rigamarole to update // the internal state. match self.queue.peek() { Some(&GoUp(..)) => { match self.recv() { Err(Upgraded(port)) => Err(port), _ => unreachable!(), } } Some(..) => Ok(true), None => Ok(false) } } // increment the count on the channel (used for selection) fn bump(&mut self, amt: int) -> int { match self.cnt.fetch_add(amt, atomic::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); DISCONNECTED } n => n } } // Attempts to start selecting on this port. Like a oneshot, this can fail // immediately because of an upgrade. pub fn start_selection(&mut self, task: BlockedTask) -> SelectionResult<T> { match self.decrement(task) { Ok(()) => SelSuccess, Err(task) => { let ret = match self.queue.peek() { Some(&GoUp(..)) => { match self.queue.pop() { Some(GoUp(port)) => SelUpgraded(task, port), _ => unreachable!(), } } Some(..) => SelCanceled(task), None => SelCanceled(task), }; // Undo our decrement above, and we should be guaranteed that the // previous value is positive because we're not going to sleep let prev = self.bump(1); assert!(prev == DISCONNECTED || prev >= 0); return ret; } } } // Removes a previous task from being blocked in this port pub fn abort_selection(&mut self, was_upgrade: bool) -> Result<bool, Receiver<T>> { // If we're aborting selection after upgrading from a oneshot, then // we're guarantee that no one is waiting. The only way that we could // have seen the upgrade is if data was actually sent on the channel // half again. For us, this means that there is guaranteed to be data on // this channel. Furthermore, we're guaranteed that there was no // start_selection previously, so there's no need to modify `self.cnt` // at all. // // Hence, because of these invariants, we immediately return `Ok(true)`. // Note that the data may not actually be sent on the channel just yet. // The other end could have flagged the upgrade but not sent data to // this end. This is fine because we know it's a small bounded windows // of time until the data is actually sent. if was_upgrade { assert_eq!(self.steals, 0); assert_eq!(self.to_wake.load(atomic::SeqCst), 0); return Ok(true) } // We want to make sure that the count on the channel goes non-negative, // and in the stream case we can have at most one steal, so just assume // that we had one steal. let steals = 1; let prev = self.bump(steals + 1); // If we were previously disconnected, then we know for sure that there // is no task in to_wake, so just keep going let has_data = if prev == DISCONNECTED { assert_eq!(self.to_wake.load(atomic::SeqCst), 0); true // there is data, that data is that we're disconnected } else { let cur = prev + steals + 1; assert!(cur >= 0); // If the previous count was negative, then we just made things go // positive, hence we passed the -1 boundary and we're responsible // for removing the to_wake() field and trashing it. // // If the previous count was positive then we're in a tougher // situation. A possible race is that a sender just incremented // through -1 (meaning it's going to try to wake a task up), but it // hasn't yet read the to_wake. In order to prevent a future recv() // from waking up too early (this sender picking up the plastered // over to_wake), we spin loop here waiting for to_wake to be 0. // Note that this entire select() implementation needs an overhaul, // and this is *not* the worst part of it, so this is not done as a // final solution but rather out of necessity for now to get // something working. if prev < 0 { self.take_to_wake().trash(); } else { while self.to_wake.load(atomic::SeqCst)!= 0 { Thread::yield_now(); } } assert_eq!(self.steals, 0); self.steals = steals; // if we were previously positive, then there's surely data to // receive prev >= 0 }; // Now that we've determined that this queue "has data", we peek at the // queue to see if the data is an upgrade or not. If it's an upgrade, // then we need to destroy this port and abort selection on the // upgraded port. if has_data { match self.queue.peek() { Some(&GoUp(..)) => { match self.queue.pop() { Some(GoUp(port)) => Err(port), _ => unreachable!(), } } _ => Ok(true), } } else { Ok(false) } } } #[
UpgradeResult
identifier_name
cssconditionrule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CSSConditionRuleBinding::CSSConditionRuleMethods; use dom::bindings::inheritance::Castable; use dom::bindings::str::DOMString; use dom::cssgroupingrule::CSSGroupingRule; use dom::cssmediarule::CSSMediaRule; use dom::cssstylesheet::CSSStyleSheet; use dom::csssupportsrule::CSSSupportsRule; use dom_struct::dom_struct; use style::shared_lock::{SharedRwLock, Locked}; use style::stylearc::Arc; use style::stylesheets::CssRules as StyleCssRules; #[dom_struct] pub struct CSSConditionRule { cssgroupingrule: CSSGroupingRule, } impl CSSConditionRule { pub fn
(parent_stylesheet: &CSSStyleSheet, rules: Arc<Locked<StyleCssRules>>) -> CSSConditionRule { CSSConditionRule { cssgroupingrule: CSSGroupingRule::new_inherited(parent_stylesheet, rules), } } pub fn parent_stylesheet(&self) -> &CSSStyleSheet { self.cssgroupingrule.parent_stylesheet() } pub fn shared_lock(&self) -> &SharedRwLock { self.cssgroupingrule.shared_lock() } } impl CSSConditionRuleMethods for CSSConditionRule { /// https://drafts.csswg.org/css-conditional-3/#dom-cssconditionrule-conditiontext fn ConditionText(&self) -> DOMString { if let Some(rule) = self.downcast::<CSSMediaRule>() { rule.get_condition_text() } else if let Some(rule) = self.downcast::<CSSSupportsRule>() { rule.get_condition_text() } else { unreachable!() } } /// https://drafts.csswg.org/css-conditional-3/#dom-cssconditionrule-conditiontext fn SetConditionText(&self, text: DOMString) { if let Some(rule) = self.downcast::<CSSMediaRule>() { rule.set_condition_text(text) } else if let Some(rule) = self.downcast::<CSSSupportsRule>() { rule.set_condition_text(text) } else { unreachable!() } } }
new_inherited
identifier_name
cssconditionrule.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::cssmediarule::CSSMediaRule; use dom::cssstylesheet::CSSStyleSheet; use dom::csssupportsrule::CSSSupportsRule; use dom_struct::dom_struct; use style::shared_lock::{SharedRwLock, Locked}; use style::stylearc::Arc; use style::stylesheets::CssRules as StyleCssRules; #[dom_struct] pub struct CSSConditionRule { cssgroupingrule: CSSGroupingRule, } impl CSSConditionRule { pub fn new_inherited(parent_stylesheet: &CSSStyleSheet, rules: Arc<Locked<StyleCssRules>>) -> CSSConditionRule { CSSConditionRule { cssgroupingrule: CSSGroupingRule::new_inherited(parent_stylesheet, rules), } } pub fn parent_stylesheet(&self) -> &CSSStyleSheet { self.cssgroupingrule.parent_stylesheet() } pub fn shared_lock(&self) -> &SharedRwLock { self.cssgroupingrule.shared_lock() } } impl CSSConditionRuleMethods for CSSConditionRule { /// https://drafts.csswg.org/css-conditional-3/#dom-cssconditionrule-conditiontext fn ConditionText(&self) -> DOMString { if let Some(rule) = self.downcast::<CSSMediaRule>() { rule.get_condition_text() } else if let Some(rule) = self.downcast::<CSSSupportsRule>() { rule.get_condition_text() } else { unreachable!() } } /// https://drafts.csswg.org/css-conditional-3/#dom-cssconditionrule-conditiontext fn SetConditionText(&self, text: DOMString) { if let Some(rule) = self.downcast::<CSSMediaRule>() { rule.set_condition_text(text) } else if let Some(rule) = self.downcast::<CSSSupportsRule>() { rule.set_condition_text(text) } else { unreachable!() } } }
use dom::bindings::codegen::Bindings::CSSConditionRuleBinding::CSSConditionRuleMethods; use dom::bindings::inheritance::Castable; use dom::bindings::str::DOMString; use dom::cssgroupingrule::CSSGroupingRule;
random_line_split
hs_hist.rs
extern crate cv; use cv::highgui::*; use cv::imgcodecs::ImageReadMode; use cv::imgproc::ColorConversion; use cv::*; fn main()
let hsv = mat.cvt_color(ColorConversion::BGR2HSV); //////////////////////////////// // // 2. Calculate the histogram // (demo multiple channels) // /////////////////////////////// let hbins = 30; let sbins = 32; let hist_size = [hbins, sbins]; let hranges = [0.0, 180.0]; let sranges = [0.0, 256.0]; let ranges = [hranges, sranges]; let channels = [0, 1]; let hist = hsv.calc_hist(&channels, &Mat::new(), &hist_size, &ranges); //////////////////////////////// // // 3. Display the histogram // /////////////////////////////// let min_max = hist.min_max_loc(&Mat::new()); let max_val = min_max.1 as f32; let scale = 10; let hist_image = Mat::with_size(sbins * scale, hbins * scale, CvType::Cv8UC3 as i32); for h in 0..hbins { for s in 0..sbins { let bin_val = hist.at2::<f32>(h, s); let intensity = (bin_val * 255.0 / max_val) as i32; let rect = Rect::new(h * scale + 1, s * scale + 1, scale - 1, scale - 1); hist_image.rectangle_custom(rect, Scalar::all(intensity), LineType::Filled as i32, LineType::Line8); } } highgui_named_window("Display window", WindowFlag::Normal).unwrap(); hist_image.show("Histogram", 0).unwrap(); }
{ //////////////////////////////// // // 1. Read the image // /////////////////////////////// let args: Vec<_> = std::env::args().collect(); if args.len() != 2 { println!("Usage: calchist <Path to Image>"); std::process::exit(-1); } let mat = Mat::from_path(&args[1], ImageReadMode::Color).expect("Failed to read from path"); if !mat.is_valid() { println!("Could not open or find the image"); std::process::exit(-1); }
identifier_body
hs_hist.rs
extern crate cv; use cv::highgui::*; use cv::imgcodecs::ImageReadMode; use cv::imgproc::ColorConversion; use cv::*; fn main() { //////////////////////////////// // // 1. Read the image // /////////////////////////////// let args: Vec<_> = std::env::args().collect(); if args.len()!= 2 { println!("Usage: calchist <Path to Image>"); std::process::exit(-1); } let mat = Mat::from_path(&args[1], ImageReadMode::Color).expect("Failed to read from path"); if!mat.is_valid()
let hsv = mat.cvt_color(ColorConversion::BGR2HSV); //////////////////////////////// // // 2. Calculate the histogram // (demo multiple channels) // /////////////////////////////// let hbins = 30; let sbins = 32; let hist_size = [hbins, sbins]; let hranges = [0.0, 180.0]; let sranges = [0.0, 256.0]; let ranges = [hranges, sranges]; let channels = [0, 1]; let hist = hsv.calc_hist(&channels, &Mat::new(), &hist_size, &ranges); //////////////////////////////// // // 3. Display the histogram // /////////////////////////////// let min_max = hist.min_max_loc(&Mat::new()); let max_val = min_max.1 as f32; let scale = 10; let hist_image = Mat::with_size(sbins * scale, hbins * scale, CvType::Cv8UC3 as i32); for h in 0..hbins { for s in 0..sbins { let bin_val = hist.at2::<f32>(h, s); let intensity = (bin_val * 255.0 / max_val) as i32; let rect = Rect::new(h * scale + 1, s * scale + 1, scale - 1, scale - 1); hist_image.rectangle_custom(rect, Scalar::all(intensity), LineType::Filled as i32, LineType::Line8); } } highgui_named_window("Display window", WindowFlag::Normal).unwrap(); hist_image.show("Histogram", 0).unwrap(); }
{ println!("Could not open or find the image"); std::process::exit(-1); }
conditional_block
hs_hist.rs
extern crate cv; use cv::highgui::*; use cv::imgcodecs::ImageReadMode; use cv::imgproc::ColorConversion; use cv::*; fn
() { //////////////////////////////// // // 1. Read the image // /////////////////////////////// let args: Vec<_> = std::env::args().collect(); if args.len()!= 2 { println!("Usage: calchist <Path to Image>"); std::process::exit(-1); } let mat = Mat::from_path(&args[1], ImageReadMode::Color).expect("Failed to read from path"); if!mat.is_valid() { println!("Could not open or find the image"); std::process::exit(-1); } let hsv = mat.cvt_color(ColorConversion::BGR2HSV); //////////////////////////////// // // 2. Calculate the histogram // (demo multiple channels) // /////////////////////////////// let hbins = 30; let sbins = 32; let hist_size = [hbins, sbins]; let hranges = [0.0, 180.0]; let sranges = [0.0, 256.0]; let ranges = [hranges, sranges]; let channels = [0, 1]; let hist = hsv.calc_hist(&channels, &Mat::new(), &hist_size, &ranges); //////////////////////////////// // // 3. Display the histogram // /////////////////////////////// let min_max = hist.min_max_loc(&Mat::new()); let max_val = min_max.1 as f32; let scale = 10; let hist_image = Mat::with_size(sbins * scale, hbins * scale, CvType::Cv8UC3 as i32); for h in 0..hbins { for s in 0..sbins { let bin_val = hist.at2::<f32>(h, s); let intensity = (bin_val * 255.0 / max_val) as i32; let rect = Rect::new(h * scale + 1, s * scale + 1, scale - 1, scale - 1); hist_image.rectangle_custom(rect, Scalar::all(intensity), LineType::Filled as i32, LineType::Line8); } } highgui_named_window("Display window", WindowFlag::Normal).unwrap(); hist_image.show("Histogram", 0).unwrap(); }
main
identifier_name
hs_hist.rs
extern crate cv; use cv::highgui::*; use cv::imgcodecs::ImageReadMode; use cv::imgproc::ColorConversion; use cv::*; fn main() { //////////////////////////////// // // 1. Read the image // /////////////////////////////// let args: Vec<_> = std::env::args().collect(); if args.len()!= 2 { println!("Usage: calchist <Path to Image>"); std::process::exit(-1); } let mat = Mat::from_path(&args[1], ImageReadMode::Color).expect("Failed to read from path"); if!mat.is_valid() { println!("Could not open or find the image"); std::process::exit(-1); } let hsv = mat.cvt_color(ColorConversion::BGR2HSV); //////////////////////////////// // // 2. Calculate the histogram // (demo multiple channels)
// /////////////////////////////// let hbins = 30; let sbins = 32; let hist_size = [hbins, sbins]; let hranges = [0.0, 180.0]; let sranges = [0.0, 256.0]; let ranges = [hranges, sranges]; let channels = [0, 1]; let hist = hsv.calc_hist(&channels, &Mat::new(), &hist_size, &ranges); //////////////////////////////// // // 3. Display the histogram // /////////////////////////////// let min_max = hist.min_max_loc(&Mat::new()); let max_val = min_max.1 as f32; let scale = 10; let hist_image = Mat::with_size(sbins * scale, hbins * scale, CvType::Cv8UC3 as i32); for h in 0..hbins { for s in 0..sbins { let bin_val = hist.at2::<f32>(h, s); let intensity = (bin_val * 255.0 / max_val) as i32; let rect = Rect::new(h * scale + 1, s * scale + 1, scale - 1, scale - 1); hist_image.rectangle_custom(rect, Scalar::all(intensity), LineType::Filled as i32, LineType::Line8); } } highgui_named_window("Display window", WindowFlag::Normal).unwrap(); hist_image.show("Histogram", 0).unwrap(); }
random_line_split
threads.rs
//! I/O compression/decompression threading control. //! //! This module provides functions for enabling/disabling and managing the //! global thread pool of OpenEXR. Importantly, if the thread pool is enabled, //! OpenEXR will use the same thread pool for all OpenEXR reading/writing, which //! can sometimes have unexpected performance implications for applications that //! are already multithreaded themselves. //! //! By default, the thread pool is disabled. //! //! Please see the //! [OpenEXR C++ library documentation](https://www.openexr.com/documentation/ReadingAndWritingImageFiles.pdf) //! for more details. use error::{Error, Result}; /// Sets the number of worker threads to use for compression/decompression. /// /// If set to `0`, the thread pool is disabled and all OpenEXR calls will run /// on their calling thread. pub fn set_global_thread_count(thread_count: usize) -> Result<()> { if thread_count > ::std::os::raw::c_int::max_value() as usize { return Err(Error::Generic(String::from( "The number of threads is too high", ))); } let mut error_out = ::std::ptr::null(); let error = unsafe {
if error!= 0 { Err(Error::take(error_out)) } else { Ok(()) } } #[test] fn test_set_global_thread_count() { assert!(set_global_thread_count(4).is_ok()); assert!(set_global_thread_count(::std::os::raw::c_int::max_value() as usize + 1).is_err()); }
openexr_sys::CEXR_set_global_thread_count( thread_count as ::std::os::raw::c_int, &mut error_out, ) };
random_line_split
threads.rs
//! I/O compression/decompression threading control. //! //! This module provides functions for enabling/disabling and managing the //! global thread pool of OpenEXR. Importantly, if the thread pool is enabled, //! OpenEXR will use the same thread pool for all OpenEXR reading/writing, which //! can sometimes have unexpected performance implications for applications that //! are already multithreaded themselves. //! //! By default, the thread pool is disabled. //! //! Please see the //! [OpenEXR C++ library documentation](https://www.openexr.com/documentation/ReadingAndWritingImageFiles.pdf) //! for more details. use error::{Error, Result}; /// Sets the number of worker threads to use for compression/decompression. /// /// If set to `0`, the thread pool is disabled and all OpenEXR calls will run /// on their calling thread. pub fn set_global_thread_count(thread_count: usize) -> Result<()> { if thread_count > ::std::os::raw::c_int::max_value() as usize { return Err(Error::Generic(String::from( "The number of threads is too high", ))); } let mut error_out = ::std::ptr::null(); let error = unsafe { openexr_sys::CEXR_set_global_thread_count( thread_count as ::std::os::raw::c_int, &mut error_out, ) }; if error!= 0 { Err(Error::take(error_out)) } else
} #[test] fn test_set_global_thread_count() { assert!(set_global_thread_count(4).is_ok()); assert!(set_global_thread_count(::std::os::raw::c_int::max_value() as usize + 1).is_err()); }
{ Ok(()) }
conditional_block
threads.rs
//! I/O compression/decompression threading control. //! //! This module provides functions for enabling/disabling and managing the //! global thread pool of OpenEXR. Importantly, if the thread pool is enabled, //! OpenEXR will use the same thread pool for all OpenEXR reading/writing, which //! can sometimes have unexpected performance implications for applications that //! are already multithreaded themselves. //! //! By default, the thread pool is disabled. //! //! Please see the //! [OpenEXR C++ library documentation](https://www.openexr.com/documentation/ReadingAndWritingImageFiles.pdf) //! for more details. use error::{Error, Result}; /// Sets the number of worker threads to use for compression/decompression. /// /// If set to `0`, the thread pool is disabled and all OpenEXR calls will run /// on their calling thread. pub fn set_global_thread_count(thread_count: usize) -> Result<()> { if thread_count > ::std::os::raw::c_int::max_value() as usize { return Err(Error::Generic(String::from( "The number of threads is too high", ))); } let mut error_out = ::std::ptr::null(); let error = unsafe { openexr_sys::CEXR_set_global_thread_count( thread_count as ::std::os::raw::c_int, &mut error_out, ) }; if error!= 0 { Err(Error::take(error_out)) } else { Ok(()) } } #[test] fn test_set_global_thread_count()
{ assert!(set_global_thread_count(4).is_ok()); assert!(set_global_thread_count(::std::os::raw::c_int::max_value() as usize + 1).is_err()); }
identifier_body
threads.rs
//! I/O compression/decompression threading control. //! //! This module provides functions for enabling/disabling and managing the //! global thread pool of OpenEXR. Importantly, if the thread pool is enabled, //! OpenEXR will use the same thread pool for all OpenEXR reading/writing, which //! can sometimes have unexpected performance implications for applications that //! are already multithreaded themselves. //! //! By default, the thread pool is disabled. //! //! Please see the //! [OpenEXR C++ library documentation](https://www.openexr.com/documentation/ReadingAndWritingImageFiles.pdf) //! for more details. use error::{Error, Result}; /// Sets the number of worker threads to use for compression/decompression. /// /// If set to `0`, the thread pool is disabled and all OpenEXR calls will run /// on their calling thread. pub fn
(thread_count: usize) -> Result<()> { if thread_count > ::std::os::raw::c_int::max_value() as usize { return Err(Error::Generic(String::from( "The number of threads is too high", ))); } let mut error_out = ::std::ptr::null(); let error = unsafe { openexr_sys::CEXR_set_global_thread_count( thread_count as ::std::os::raw::c_int, &mut error_out, ) }; if error!= 0 { Err(Error::take(error_out)) } else { Ok(()) } } #[test] fn test_set_global_thread_count() { assert!(set_global_thread_count(4).is_ok()); assert!(set_global_thread_count(::std::os::raw::c_int::max_value() as usize + 1).is_err()); }
set_global_thread_count
identifier_name
derive.rs
extern crate setlike; extern crate avarice; #[macro_use] extern crate avarice_derive; #[cfg(test)] mod test { use avarice::objective::*; use avarice::objective::curvature::Bounded; use avarice::errors::*; use setlike::Setlike; use std::iter; macro_rules! obj { ($tr:ident, $name:ident) => { #[derive($tr, Debug, Clone)] struct $name {} impl Objective for $name { type Element = (); type State = (); fn elements(&self) -> ElementIterator<Self> { Box::new(iter::empty()) } fn depends(&self, _u: Self::Element, _st: &Self::State) -> Result<ElementIterator<Self>> { Ok(Box::new(iter::empty())) } fn benefit<S: Setlike<Self::Element>>(&self, _s: &S, _st: &Self::State) -> Result<f64> { Ok(0.0) } fn delta<S: Setlike<Self::Element>>(&self, _el: Self::Element, _s: &S, _st: &Self::State) -> Result<f64> { Ok(0.0) } fn insert_mut(&self, _u: Self::Element, _st: &mut Self::State) -> Result<()> { Ok(()) } } } } obj!(Submodular, SubObj); #[test] fn submod_derived_bounds() { assert!(SubObj::bounds() == (None, Some(1.0))); } obj!(Supermodular, SupObj); #[test] fn supmod_derived_bounds()
obj!(Modular, ModObj); #[test] fn mod_derived_bounds() { assert!(ModObj::bounds() == (Some(1.0), Some(1.0))); } }
{ assert!(SupObj::bounds() == (Some(1.0), None)); }
identifier_body
derive.rs
extern crate setlike; extern crate avarice; #[macro_use] extern crate avarice_derive; #[cfg(test)] mod test { use avarice::objective::*; use avarice::objective::curvature::Bounded; use avarice::errors::*; use setlike::Setlike;
($tr:ident, $name:ident) => { #[derive($tr, Debug, Clone)] struct $name {} impl Objective for $name { type Element = (); type State = (); fn elements(&self) -> ElementIterator<Self> { Box::new(iter::empty()) } fn depends(&self, _u: Self::Element, _st: &Self::State) -> Result<ElementIterator<Self>> { Ok(Box::new(iter::empty())) } fn benefit<S: Setlike<Self::Element>>(&self, _s: &S, _st: &Self::State) -> Result<f64> { Ok(0.0) } fn delta<S: Setlike<Self::Element>>(&self, _el: Self::Element, _s: &S, _st: &Self::State) -> Result<f64> { Ok(0.0) } fn insert_mut(&self, _u: Self::Element, _st: &mut Self::State) -> Result<()> { Ok(()) } } } } obj!(Submodular, SubObj); #[test] fn submod_derived_bounds() { assert!(SubObj::bounds() == (None, Some(1.0))); } obj!(Supermodular, SupObj); #[test] fn supmod_derived_bounds() { assert!(SupObj::bounds() == (Some(1.0), None)); } obj!(Modular, ModObj); #[test] fn mod_derived_bounds() { assert!(ModObj::bounds() == (Some(1.0), Some(1.0))); } }
use std::iter; macro_rules! obj {
random_line_split
derive.rs
extern crate setlike; extern crate avarice; #[macro_use] extern crate avarice_derive; #[cfg(test)] mod test { use avarice::objective::*; use avarice::objective::curvature::Bounded; use avarice::errors::*; use setlike::Setlike; use std::iter; macro_rules! obj { ($tr:ident, $name:ident) => { #[derive($tr, Debug, Clone)] struct $name {} impl Objective for $name { type Element = (); type State = (); fn elements(&self) -> ElementIterator<Self> { Box::new(iter::empty()) } fn depends(&self, _u: Self::Element, _st: &Self::State) -> Result<ElementIterator<Self>> { Ok(Box::new(iter::empty())) } fn benefit<S: Setlike<Self::Element>>(&self, _s: &S, _st: &Self::State) -> Result<f64> { Ok(0.0) } fn delta<S: Setlike<Self::Element>>(&self, _el: Self::Element, _s: &S, _st: &Self::State) -> Result<f64> { Ok(0.0) } fn insert_mut(&self, _u: Self::Element, _st: &mut Self::State) -> Result<()> { Ok(()) } } } } obj!(Submodular, SubObj); #[test] fn submod_derived_bounds() { assert!(SubObj::bounds() == (None, Some(1.0))); } obj!(Supermodular, SupObj); #[test] fn
() { assert!(SupObj::bounds() == (Some(1.0), None)); } obj!(Modular, ModObj); #[test] fn mod_derived_bounds() { assert!(ModObj::bounds() == (Some(1.0), Some(1.0))); } }
supmod_derived_bounds
identifier_name
documentfragment.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DocumentFragmentBinding; use dom::bindings::codegen::Bindings::DocumentFragmentBinding::DocumentFragmentMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::InheritTypes::{DocumentFragmentDerived, NodeCast}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::Element; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlcollection::HTMLCollection; use dom::node::{DocumentFragmentNodeTypeId, Node, NodeHelpers, window_from_node}; use dom::nodelist::NodeList; use servo_util::str::DOMString; #[dom_struct] pub struct DocumentFragment { node: Node, } impl DocumentFragmentDerived for EventTarget { fn is_documentfragment(&self) -> bool { *self.type_id() == NodeTargetTypeId(DocumentFragmentNodeTypeId) } } impl DocumentFragment { /// Creates a new DocumentFragment. fn new_inherited(document: JSRef<Document>) -> DocumentFragment
pub fn new(document: JSRef<Document>) -> Temporary<DocumentFragment> { Node::reflect_node(box DocumentFragment::new_inherited(document), document, DocumentFragmentBinding::Wrap) } pub fn Constructor(global: &GlobalRef) -> Fallible<Temporary<DocumentFragment>> { let document = global.as_window().Document(); let document = document.root(); Ok(DocumentFragment::new(*document)) } } impl<'a> DocumentFragmentMethods for JSRef<'a, DocumentFragment> { // http://dom.spec.whatwg.org/#dom-parentnode-children fn Children(self) -> Temporary<HTMLCollection> { let window = window_from_node(self).root(); HTMLCollection::children(*window, NodeCast::from_ref(self)) } // http://dom.spec.whatwg.org/#dom-parentnode-queryselector fn QuerySelector(self, selectors: DOMString) -> Fallible<Option<Temporary<Element>>> { let root: JSRef<Node> = NodeCast::from_ref(self); root.query_selector(selectors) } // http://dom.spec.whatwg.org/#dom-parentnode-queryselectorall fn QuerySelectorAll(self, selectors: DOMString) -> Fallible<Temporary<NodeList>> { let root: JSRef<Node> = NodeCast::from_ref(self); root.query_selector_all(selectors) } } impl Reflectable for DocumentFragment { fn reflector<'a>(&'a self) -> &'a Reflector { self.node.reflector() } }
{ DocumentFragment { node: Node::new_inherited(DocumentFragmentNodeTypeId, document), } }
identifier_body
documentfragment.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DocumentFragmentBinding; use dom::bindings::codegen::Bindings::DocumentFragmentBinding::DocumentFragmentMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::InheritTypes::{DocumentFragmentDerived, NodeCast}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::Element; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlcollection::HTMLCollection; use dom::node::{DocumentFragmentNodeTypeId, Node, NodeHelpers, window_from_node}; use dom::nodelist::NodeList; use servo_util::str::DOMString; #[dom_struct] pub struct
{ node: Node, } impl DocumentFragmentDerived for EventTarget { fn is_documentfragment(&self) -> bool { *self.type_id() == NodeTargetTypeId(DocumentFragmentNodeTypeId) } } impl DocumentFragment { /// Creates a new DocumentFragment. fn new_inherited(document: JSRef<Document>) -> DocumentFragment { DocumentFragment { node: Node::new_inherited(DocumentFragmentNodeTypeId, document), } } pub fn new(document: JSRef<Document>) -> Temporary<DocumentFragment> { Node::reflect_node(box DocumentFragment::new_inherited(document), document, DocumentFragmentBinding::Wrap) } pub fn Constructor(global: &GlobalRef) -> Fallible<Temporary<DocumentFragment>> { let document = global.as_window().Document(); let document = document.root(); Ok(DocumentFragment::new(*document)) } } impl<'a> DocumentFragmentMethods for JSRef<'a, DocumentFragment> { // http://dom.spec.whatwg.org/#dom-parentnode-children fn Children(self) -> Temporary<HTMLCollection> { let window = window_from_node(self).root(); HTMLCollection::children(*window, NodeCast::from_ref(self)) } // http://dom.spec.whatwg.org/#dom-parentnode-queryselector fn QuerySelector(self, selectors: DOMString) -> Fallible<Option<Temporary<Element>>> { let root: JSRef<Node> = NodeCast::from_ref(self); root.query_selector(selectors) } // http://dom.spec.whatwg.org/#dom-parentnode-queryselectorall fn QuerySelectorAll(self, selectors: DOMString) -> Fallible<Temporary<NodeList>> { let root: JSRef<Node> = NodeCast::from_ref(self); root.query_selector_all(selectors) } } impl Reflectable for DocumentFragment { fn reflector<'a>(&'a self) -> &'a Reflector { self.node.reflector() } }
DocumentFragment
identifier_name
documentfragment.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DocumentFragmentBinding; use dom::bindings::codegen::Bindings::DocumentFragmentBinding::DocumentFragmentMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::InheritTypes::{DocumentFragmentDerived, NodeCast}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::Element; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlcollection::HTMLCollection; use dom::node::{DocumentFragmentNodeTypeId, Node, NodeHelpers, window_from_node}; use dom::nodelist::NodeList; use servo_util::str::DOMString; #[dom_struct] pub struct DocumentFragment { node: Node, } impl DocumentFragmentDerived for EventTarget { fn is_documentfragment(&self) -> bool { *self.type_id() == NodeTargetTypeId(DocumentFragmentNodeTypeId) } } impl DocumentFragment { /// Creates a new DocumentFragment. fn new_inherited(document: JSRef<Document>) -> DocumentFragment { DocumentFragment {
node: Node::new_inherited(DocumentFragmentNodeTypeId, document), } } pub fn new(document: JSRef<Document>) -> Temporary<DocumentFragment> { Node::reflect_node(box DocumentFragment::new_inherited(document), document, DocumentFragmentBinding::Wrap) } pub fn Constructor(global: &GlobalRef) -> Fallible<Temporary<DocumentFragment>> { let document = global.as_window().Document(); let document = document.root(); Ok(DocumentFragment::new(*document)) } } impl<'a> DocumentFragmentMethods for JSRef<'a, DocumentFragment> { // http://dom.spec.whatwg.org/#dom-parentnode-children fn Children(self) -> Temporary<HTMLCollection> { let window = window_from_node(self).root(); HTMLCollection::children(*window, NodeCast::from_ref(self)) } // http://dom.spec.whatwg.org/#dom-parentnode-queryselector fn QuerySelector(self, selectors: DOMString) -> Fallible<Option<Temporary<Element>>> { let root: JSRef<Node> = NodeCast::from_ref(self); root.query_selector(selectors) } // http://dom.spec.whatwg.org/#dom-parentnode-queryselectorall fn QuerySelectorAll(self, selectors: DOMString) -> Fallible<Temporary<NodeList>> { let root: JSRef<Node> = NodeCast::from_ref(self); root.query_selector_all(selectors) } } impl Reflectable for DocumentFragment { fn reflector<'a>(&'a self) -> &'a Reflector { self.node.reflector() } }
random_line_split
book-store.rs
//! Tests for book-store //! //! Generated by [script][script] using [canonical data][canonical-data] //! //! [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py //! [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/book-store/canonical_data.json extern crate book_store; use book_store::*; /// Process a single test case for the property `total` /// /// All cases for the `total` property are implemented /// in terms of this function. /// /// Expected input format: ('basket', 'targetgrouping') fn process_total_case(input: (Vec<usize>, Vec<Vec<usize>>), expected: f64) { assert_eq!( lowest_price(&input.0), expected ) } // Return the total basket price after applying the best discount. // Calculate lowest price for a shopping basket containing books only from
#[test] /// Only a single book fn test_only_a_single_book() { process_total_case((vec![1], vec![vec![1]]), 8.0); } #[test] #[ignore] /// Two of the same book fn test_two_of_the_same_book() { process_total_case((vec![2, 2], vec![vec![2], vec![2]]), 16.0); } #[test] #[ignore] /// Empty basket fn test_empty_basket() { process_total_case((vec![], vec![]), 0.0); } #[test] #[ignore] /// Two different books fn test_two_different_books() { process_total_case((vec![1, 2], vec![vec![1, 2]]), 15.2); } #[test] #[ignore] /// Three different books fn test_three_different_books() { process_total_case((vec![1, 2, 3], vec![vec![1, 2, 3]]), 21.6); } #[test] #[ignore] /// Four different books fn test_four_different_books() { process_total_case((vec![1, 2, 3, 4], vec![vec![1, 2, 3, 4]]), 25.6); } #[test] #[ignore] /// Five different books fn test_five_different_books() { process_total_case((vec![1, 2, 3, 4, 5], vec![vec![1, 2, 3, 4, 5]]), 30.0); } #[test] #[ignore] /// Two groups of four is cheaper than group of five plus group of three fn test_two_groups_of_four_is_cheaper_than_group_of_five_plus_group_of_three() { process_total_case((vec![1, 1, 2, 2, 3, 3, 4, 5], vec![vec![1, 2, 3, 4], vec![1, 2, 3, 5]]), 51.2); } #[test] #[ignore] /// Group of four plus group of two is cheaper than two groups of three fn test_group_of_four_plus_group_of_two_is_cheaper_than_two_groups_of_three() { process_total_case((vec![1, 1, 2, 2, 3, 4], vec![vec![1, 2, 3, 4], vec![1, 2]]), 40.8); } #[test] #[ignore] /// Two each of first 4 books and 1 copy each of rest fn test_two_each_of_first_4_books_and_1_copy_each_of_rest() { process_total_case((vec![1, 1, 2, 2, 3, 3, 4, 4, 5], vec![vec![1, 2, 3, 4, 5], vec![1, 2, 3, 4]]), 55.6); } #[test] #[ignore] /// Two copies of each book fn test_two_copies_of_each_book() { process_total_case((vec![1, 1, 2, 2, 3, 3, 4, 4, 5, 5], vec![vec![1, 2, 3, 4, 5], vec![1, 2, 3, 4, 5]]), 60.0); } #[test] #[ignore] /// Three copies of first book and 2 each of remaining fn test_three_copies_of_first_book_and_2_each_of_remaining() { process_total_case((vec![1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 1], vec![vec![1, 2, 3, 4, 5], vec![1, 2, 3, 4, 5], vec![1]]), 68.0); } #[test] #[ignore] /// Three each of first 2 books and 2 each of remaining books fn test_three_each_of_first_2_books_and_2_each_of_remaining_books() { process_total_case((vec![1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 1, 2], vec![vec![1, 2, 3, 4, 5], vec![1, 2, 3, 4, 5], vec![1, 2]]), 75.2); } #[test] #[ignore] /// Four groups of four are cheaper than two groups each of five and three fn test_four_groups_of_four_are_cheaper_than_two_groups_each_of_five_and_three() { process_total_case((vec![1,1,2,2,3,3,4,5,1,1,2,2,3,3,4,5], vec![vec![1,2,3,4],vec![1,2,3,5],vec![1,2,3,4],vec![1,2,3,5]]), 102.4); }
// a single series. There is no discount advantage for having more than // one copy of any single book in a grouping.
random_line_split
book-store.rs
//! Tests for book-store //! //! Generated by [script][script] using [canonical data][canonical-data] //! //! [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py //! [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/book-store/canonical_data.json extern crate book_store; use book_store::*; /// Process a single test case for the property `total` /// /// All cases for the `total` property are implemented /// in terms of this function. /// /// Expected input format: ('basket', 'targetgrouping') fn process_total_case(input: (Vec<usize>, Vec<Vec<usize>>), expected: f64) { assert_eq!( lowest_price(&input.0), expected ) } // Return the total basket price after applying the best discount. // Calculate lowest price for a shopping basket containing books only from // a single series. There is no discount advantage for having more than // one copy of any single book in a grouping. #[test] /// Only a single book fn test_only_a_single_book()
#[test] #[ignore] /// Two of the same book fn test_two_of_the_same_book() { process_total_case((vec![2, 2], vec![vec![2], vec![2]]), 16.0); } #[test] #[ignore] /// Empty basket fn test_empty_basket() { process_total_case((vec![], vec![]), 0.0); } #[test] #[ignore] /// Two different books fn test_two_different_books() { process_total_case((vec![1, 2], vec![vec![1, 2]]), 15.2); } #[test] #[ignore] /// Three different books fn test_three_different_books() { process_total_case((vec![1, 2, 3], vec![vec![1, 2, 3]]), 21.6); } #[test] #[ignore] /// Four different books fn test_four_different_books() { process_total_case((vec![1, 2, 3, 4], vec![vec![1, 2, 3, 4]]), 25.6); } #[test] #[ignore] /// Five different books fn test_five_different_books() { process_total_case((vec![1, 2, 3, 4, 5], vec![vec![1, 2, 3, 4, 5]]), 30.0); } #[test] #[ignore] /// Two groups of four is cheaper than group of five plus group of three fn test_two_groups_of_four_is_cheaper_than_group_of_five_plus_group_of_three() { process_total_case((vec![1, 1, 2, 2, 3, 3, 4, 5], vec![vec![1, 2, 3, 4], vec![1, 2, 3, 5]]), 51.2); } #[test] #[ignore] /// Group of four plus group of two is cheaper than two groups of three fn test_group_of_four_plus_group_of_two_is_cheaper_than_two_groups_of_three() { process_total_case((vec![1, 1, 2, 2, 3, 4], vec![vec![1, 2, 3, 4], vec![1, 2]]), 40.8); } #[test] #[ignore] /// Two each of first 4 books and 1 copy each of rest fn test_two_each_of_first_4_books_and_1_copy_each_of_rest() { process_total_case((vec![1, 1, 2, 2, 3, 3, 4, 4, 5], vec![vec![1, 2, 3, 4, 5], vec![1, 2, 3, 4]]), 55.6); } #[test] #[ignore] /// Two copies of each book fn test_two_copies_of_each_book() { process_total_case((vec![1, 1, 2, 2, 3, 3, 4, 4, 5, 5], vec![vec![1, 2, 3, 4, 5], vec![1, 2, 3, 4, 5]]), 60.0); } #[test] #[ignore] /// Three copies of first book and 2 each of remaining fn test_three_copies_of_first_book_and_2_each_of_remaining() { process_total_case((vec![1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 1], vec![vec![1, 2, 3, 4, 5], vec![1, 2, 3, 4, 5], vec![1]]), 68.0); } #[test] #[ignore] /// Three each of first 2 books and 2 each of remaining books fn test_three_each_of_first_2_books_and_2_each_of_remaining_books() { process_total_case((vec![1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 1, 2], vec![vec![1, 2, 3, 4, 5], vec![1, 2, 3, 4, 5], vec![1, 2]]), 75.2); } #[test] #[ignore] /// Four groups of four are cheaper than two groups each of five and three fn test_four_groups_of_four_are_cheaper_than_two_groups_each_of_five_and_three() { process_total_case((vec![1,1,2,2,3,3,4,5,1,1,2,2,3,3,4,5], vec![vec![1,2,3,4],vec![1,2,3,5],vec![1,2,3,4],vec![1,2,3,5]]), 102.4); }
{ process_total_case((vec![1], vec![vec![1]]), 8.0); }
identifier_body
book-store.rs
//! Tests for book-store //! //! Generated by [script][script] using [canonical data][canonical-data] //! //! [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py //! [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/book-store/canonical_data.json extern crate book_store; use book_store::*; /// Process a single test case for the property `total` /// /// All cases for the `total` property are implemented /// in terms of this function. /// /// Expected input format: ('basket', 'targetgrouping') fn process_total_case(input: (Vec<usize>, Vec<Vec<usize>>), expected: f64) { assert_eq!( lowest_price(&input.0), expected ) } // Return the total basket price after applying the best discount. // Calculate lowest price for a shopping basket containing books only from // a single series. There is no discount advantage for having more than // one copy of any single book in a grouping. #[test] /// Only a single book fn test_only_a_single_book() { process_total_case((vec![1], vec![vec![1]]), 8.0); } #[test] #[ignore] /// Two of the same book fn test_two_of_the_same_book() { process_total_case((vec![2, 2], vec![vec![2], vec![2]]), 16.0); } #[test] #[ignore] /// Empty basket fn test_empty_basket() { process_total_case((vec![], vec![]), 0.0); } #[test] #[ignore] /// Two different books fn test_two_different_books() { process_total_case((vec![1, 2], vec![vec![1, 2]]), 15.2); } #[test] #[ignore] /// Three different books fn test_three_different_books() { process_total_case((vec![1, 2, 3], vec![vec![1, 2, 3]]), 21.6); } #[test] #[ignore] /// Four different books fn test_four_different_books() { process_total_case((vec![1, 2, 3, 4], vec![vec![1, 2, 3, 4]]), 25.6); } #[test] #[ignore] /// Five different books fn test_five_different_books() { process_total_case((vec![1, 2, 3, 4, 5], vec![vec![1, 2, 3, 4, 5]]), 30.0); } #[test] #[ignore] /// Two groups of four is cheaper than group of five plus group of three fn test_two_groups_of_four_is_cheaper_than_group_of_five_plus_group_of_three() { process_total_case((vec![1, 1, 2, 2, 3, 3, 4, 5], vec![vec![1, 2, 3, 4], vec![1, 2, 3, 5]]), 51.2); } #[test] #[ignore] /// Group of four plus group of two is cheaper than two groups of three fn test_group_of_four_plus_group_of_two_is_cheaper_than_two_groups_of_three() { process_total_case((vec![1, 1, 2, 2, 3, 4], vec![vec![1, 2, 3, 4], vec![1, 2]]), 40.8); } #[test] #[ignore] /// Two each of first 4 books and 1 copy each of rest fn
() { process_total_case((vec![1, 1, 2, 2, 3, 3, 4, 4, 5], vec![vec![1, 2, 3, 4, 5], vec![1, 2, 3, 4]]), 55.6); } #[test] #[ignore] /// Two copies of each book fn test_two_copies_of_each_book() { process_total_case((vec![1, 1, 2, 2, 3, 3, 4, 4, 5, 5], vec![vec![1, 2, 3, 4, 5], vec![1, 2, 3, 4, 5]]), 60.0); } #[test] #[ignore] /// Three copies of first book and 2 each of remaining fn test_three_copies_of_first_book_and_2_each_of_remaining() { process_total_case((vec![1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 1], vec![vec![1, 2, 3, 4, 5], vec![1, 2, 3, 4, 5], vec![1]]), 68.0); } #[test] #[ignore] /// Three each of first 2 books and 2 each of remaining books fn test_three_each_of_first_2_books_and_2_each_of_remaining_books() { process_total_case((vec![1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 1, 2], vec![vec![1, 2, 3, 4, 5], vec![1, 2, 3, 4, 5], vec![1, 2]]), 75.2); } #[test] #[ignore] /// Four groups of four are cheaper than two groups each of five and three fn test_four_groups_of_four_are_cheaper_than_two_groups_each_of_five_and_three() { process_total_case((vec![1,1,2,2,3,3,4,5,1,1,2,2,3,3,4,5], vec![vec![1,2,3,4],vec![1,2,3,5],vec![1,2,3,4],vec![1,2,3,5]]), 102.4); }
test_two_each_of_first_4_books_and_1_copy_each_of_rest
identifier_name
glue.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/. */ #![allow(unsafe_code)] use app_units::Au; use bindings::{RawGeckoDocument, RawGeckoElement}; use bindings::{RawServoStyleSet, RawServoStyleSheet, ServoComputedValues, ServoNodeData}; use bindings::{nsIAtom, uint8_t, uint32_t}; use data::PerDocumentStyleData; use euclid::Size2D; use properties::GeckoComputedValues; use selector_impl::{SharedStyleContext, Stylesheet}; use std::marker::PhantomData; use std::mem::{forget, transmute}; use std::ptr; use std::slice; use std::str::from_utf8_unchecked; use std::sync::{Arc, Mutex}; use style::context::{ReflowGoal, StylistWrapper}; use style::dom::{TDocument, TElement, TNode}; use style::error_reporting::StdoutErrorReporter; use style::parallel; use style::stylesheets::Origin; use traversal::RecalcStyleOnly; use url::Url; use util::arc_ptr_eq; use wrapper::{GeckoDocument, GeckoElement, GeckoNode, NonOpaqueStyleData}; /* * For Gecko->Servo function calls, we need to redeclare the same signature that was declared in * the C header in Gecko. In order to catch accidental mismatches, we run rust-bindgen against * those signatures as well, giving us a second declaration of all the Servo_* functions in this * crate. If there's a mismatch, LLVM will assert and abort, which is a rather awful thing to * depend on but good enough for our purposes. */ #[no_mangle] pub extern "C" fn Servo_RestyleDocument(doc: *mut RawGeckoDocument, raw_data: *mut RawServoStyleSet) -> () { let document = unsafe { GeckoDocument::from_raw(doc) }; let node = match document.root_node() { Some(x) => x, None => return, }; let data = unsafe { &mut *(raw_data as *mut PerDocumentStyleData) }; let _needs_dirtying = data.stylist.update(&data.stylesheets, data.stylesheets_changed); data.stylesheets_changed = false; let shared_style_context = SharedStyleContext { viewport_size: Size2D::new(Au(0), Au(0)), screen_size_changed: false, generation: 0, goal: ReflowGoal::ForScriptQuery, stylist: StylistWrapper(&data.stylist), new_animations_sender: Mutex::new(data.new_animations_sender.clone()), running_animations: data.running_animations.clone(), expired_animations: data.expired_animations.clone(), error_reporter: Box::new(StdoutErrorReporter), }; if node.is_dirty() || node.has_dirty_descendants() { parallel::traverse_dom::<GeckoNode, RecalcStyleOnly>(node, &shared_style_context, &mut data.work_queue); } } #[no_mangle] pub extern "C" fn Servo_DropNodeData(data: *mut ServoNodeData) -> () { unsafe { let _ = Box::<NonOpaqueStyleData>::from_raw(data as *mut NonOpaqueStyleData); } } #[no_mangle] pub extern "C" fn Servo_StylesheetFromUTF8Bytes(bytes: *const uint8_t, length: uint32_t) -> *mut RawServoStyleSheet { let input = unsafe { from_utf8_unchecked(slice::from_raw_parts(bytes, length as usize)) }; // FIXME(heycam): Pass in the real base URL and sheet origin to use. let url = Url::parse("about:none").unwrap(); let sheet = Arc::new(Stylesheet::from_str(input, url, Origin::Author, Box::new(StdoutErrorReporter))); unsafe { transmute(sheet) } } struct ArcHelpers<GeckoType, ServoType> { phantom1: PhantomData<GeckoType>, phantom2: PhantomData<ServoType>, } impl<GeckoType, ServoType> ArcHelpers<GeckoType, ServoType> { fn with<F, Output>(raw: *mut GeckoType, cb: F) -> Output where F: FnOnce(&Arc<ServoType>) -> Output { let owned = unsafe { Self::into(raw) }; let result = cb(&owned); forget(owned); result } unsafe fn into(ptr: *mut GeckoType) -> Arc<ServoType> { transmute(ptr) } unsafe fn addref(ptr: *mut GeckoType) { Self::with(ptr, |arc| forget(arc.clone())); } unsafe fn release(ptr: *mut GeckoType) { let _ = Self::into(ptr); } } #[no_mangle] pub extern "C" fn Servo_AppendStyleSheet(raw_sheet: *mut RawServoStyleSheet, raw_data: *mut RawServoStyleSet) { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; let data = PerDocumentStyleData::borrow_mut_from_raw(raw_data); Helpers::with(raw_sheet, |sheet| { data.stylesheets.retain(|x|!arc_ptr_eq(x, sheet)); data.stylesheets.push(sheet.clone()); data.stylesheets_changed = true; }); } #[no_mangle] pub extern "C" fn Servo_PrependStyleSheet(raw_sheet: *mut RawServoStyleSheet, raw_data: *mut RawServoStyleSet) { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; let data = PerDocumentStyleData::borrow_mut_from_raw(raw_data); Helpers::with(raw_sheet, |sheet| { data.stylesheets.retain(|x|!arc_ptr_eq(x, sheet)); data.stylesheets.insert(0, sheet.clone()); data.stylesheets_changed = true; }) } #[no_mangle] pub extern "C" fn Servo_RemoveStyleSheet(raw_sheet: *mut RawServoStyleSheet, raw_data: *mut RawServoStyleSet) { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; let data = PerDocumentStyleData::borrow_mut_from_raw(raw_data); Helpers::with(raw_sheet, |sheet| { data.stylesheets.retain(|x|!arc_ptr_eq(x, sheet)); data.stylesheets_changed = true; }); } #[no_mangle] pub extern "C" fn Servo_StyleSheetHasRules(raw_sheet: *mut RawServoStyleSheet) -> bool { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; Helpers::with(raw_sheet, |sheet|!sheet.rules.is_empty()) } #[no_mangle] pub extern "C" fn Servo_AddRefStyleSheet(sheet: *mut RawServoStyleSheet) -> () { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; unsafe { Helpers::addref(sheet) }; } #[no_mangle] pub extern "C" fn Servo_ReleaseStyleSheet(sheet: *mut RawServoStyleSheet) -> () { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; unsafe { Helpers::release(sheet) }; } #[no_mangle] pub extern "C" fn Servo_GetComputedValues(element: *mut RawGeckoElement) -> *mut ServoComputedValues {
#[no_mangle] pub extern "C" fn Servo_GetComputedValuesForAnonymousBox(_: *mut nsIAtom) -> *mut ServoComputedValues { unimplemented!(); } #[no_mangle] pub extern "C" fn Servo_AddRefComputedValues(ptr: *mut ServoComputedValues) -> () { type Helpers = ArcHelpers<ServoComputedValues, GeckoComputedValues>; unsafe { Helpers::addref(ptr) }; } #[no_mangle] pub extern "C" fn Servo_ReleaseComputedValues(ptr: *mut ServoComputedValues) -> () { type Helpers = ArcHelpers<ServoComputedValues, GeckoComputedValues>; unsafe { Helpers::release(ptr) }; } #[no_mangle] pub extern "C" fn Servo_InitStyleSet() -> *mut RawServoStyleSet { let data = Box::new(PerDocumentStyleData::new()); Box::into_raw(data) as *mut RawServoStyleSet } #[no_mangle] pub extern "C" fn Servo_DropStyleSet(data: *mut RawServoStyleSet) -> () { unsafe { let _ = Box::<PerDocumentStyleData>::from_raw(data as *mut PerDocumentStyleData); } }
let node = unsafe { GeckoElement::from_raw(element).as_node() }; let arc_cv = node.borrow_data().map(|data| data.style.clone()); arc_cv.map_or(ptr::null_mut(), |arc| unsafe { transmute(arc) }) }
random_line_split
glue.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/. */ #![allow(unsafe_code)] use app_units::Au; use bindings::{RawGeckoDocument, RawGeckoElement}; use bindings::{RawServoStyleSet, RawServoStyleSheet, ServoComputedValues, ServoNodeData}; use bindings::{nsIAtom, uint8_t, uint32_t}; use data::PerDocumentStyleData; use euclid::Size2D; use properties::GeckoComputedValues; use selector_impl::{SharedStyleContext, Stylesheet}; use std::marker::PhantomData; use std::mem::{forget, transmute}; use std::ptr; use std::slice; use std::str::from_utf8_unchecked; use std::sync::{Arc, Mutex}; use style::context::{ReflowGoal, StylistWrapper}; use style::dom::{TDocument, TElement, TNode}; use style::error_reporting::StdoutErrorReporter; use style::parallel; use style::stylesheets::Origin; use traversal::RecalcStyleOnly; use url::Url; use util::arc_ptr_eq; use wrapper::{GeckoDocument, GeckoElement, GeckoNode, NonOpaqueStyleData}; /* * For Gecko->Servo function calls, we need to redeclare the same signature that was declared in * the C header in Gecko. In order to catch accidental mismatches, we run rust-bindgen against * those signatures as well, giving us a second declaration of all the Servo_* functions in this * crate. If there's a mismatch, LLVM will assert and abort, which is a rather awful thing to * depend on but good enough for our purposes. */ #[no_mangle] pub extern "C" fn Servo_RestyleDocument(doc: *mut RawGeckoDocument, raw_data: *mut RawServoStyleSet) -> () { let document = unsafe { GeckoDocument::from_raw(doc) }; let node = match document.root_node() { Some(x) => x, None => return, }; let data = unsafe { &mut *(raw_data as *mut PerDocumentStyleData) }; let _needs_dirtying = data.stylist.update(&data.stylesheets, data.stylesheets_changed); data.stylesheets_changed = false; let shared_style_context = SharedStyleContext { viewport_size: Size2D::new(Au(0), Au(0)), screen_size_changed: false, generation: 0, goal: ReflowGoal::ForScriptQuery, stylist: StylistWrapper(&data.stylist), new_animations_sender: Mutex::new(data.new_animations_sender.clone()), running_animations: data.running_animations.clone(), expired_animations: data.expired_animations.clone(), error_reporter: Box::new(StdoutErrorReporter), }; if node.is_dirty() || node.has_dirty_descendants() { parallel::traverse_dom::<GeckoNode, RecalcStyleOnly>(node, &shared_style_context, &mut data.work_queue); } } #[no_mangle] pub extern "C" fn Servo_DropNodeData(data: *mut ServoNodeData) -> () { unsafe { let _ = Box::<NonOpaqueStyleData>::from_raw(data as *mut NonOpaqueStyleData); } } #[no_mangle] pub extern "C" fn Servo_StylesheetFromUTF8Bytes(bytes: *const uint8_t, length: uint32_t) -> *mut RawServoStyleSheet { let input = unsafe { from_utf8_unchecked(slice::from_raw_parts(bytes, length as usize)) }; // FIXME(heycam): Pass in the real base URL and sheet origin to use. let url = Url::parse("about:none").unwrap(); let sheet = Arc::new(Stylesheet::from_str(input, url, Origin::Author, Box::new(StdoutErrorReporter))); unsafe { transmute(sheet) } } struct
<GeckoType, ServoType> { phantom1: PhantomData<GeckoType>, phantom2: PhantomData<ServoType>, } impl<GeckoType, ServoType> ArcHelpers<GeckoType, ServoType> { fn with<F, Output>(raw: *mut GeckoType, cb: F) -> Output where F: FnOnce(&Arc<ServoType>) -> Output { let owned = unsafe { Self::into(raw) }; let result = cb(&owned); forget(owned); result } unsafe fn into(ptr: *mut GeckoType) -> Arc<ServoType> { transmute(ptr) } unsafe fn addref(ptr: *mut GeckoType) { Self::with(ptr, |arc| forget(arc.clone())); } unsafe fn release(ptr: *mut GeckoType) { let _ = Self::into(ptr); } } #[no_mangle] pub extern "C" fn Servo_AppendStyleSheet(raw_sheet: *mut RawServoStyleSheet, raw_data: *mut RawServoStyleSet) { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; let data = PerDocumentStyleData::borrow_mut_from_raw(raw_data); Helpers::with(raw_sheet, |sheet| { data.stylesheets.retain(|x|!arc_ptr_eq(x, sheet)); data.stylesheets.push(sheet.clone()); data.stylesheets_changed = true; }); } #[no_mangle] pub extern "C" fn Servo_PrependStyleSheet(raw_sheet: *mut RawServoStyleSheet, raw_data: *mut RawServoStyleSet) { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; let data = PerDocumentStyleData::borrow_mut_from_raw(raw_data); Helpers::with(raw_sheet, |sheet| { data.stylesheets.retain(|x|!arc_ptr_eq(x, sheet)); data.stylesheets.insert(0, sheet.clone()); data.stylesheets_changed = true; }) } #[no_mangle] pub extern "C" fn Servo_RemoveStyleSheet(raw_sheet: *mut RawServoStyleSheet, raw_data: *mut RawServoStyleSet) { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; let data = PerDocumentStyleData::borrow_mut_from_raw(raw_data); Helpers::with(raw_sheet, |sheet| { data.stylesheets.retain(|x|!arc_ptr_eq(x, sheet)); data.stylesheets_changed = true; }); } #[no_mangle] pub extern "C" fn Servo_StyleSheetHasRules(raw_sheet: *mut RawServoStyleSheet) -> bool { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; Helpers::with(raw_sheet, |sheet|!sheet.rules.is_empty()) } #[no_mangle] pub extern "C" fn Servo_AddRefStyleSheet(sheet: *mut RawServoStyleSheet) -> () { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; unsafe { Helpers::addref(sheet) }; } #[no_mangle] pub extern "C" fn Servo_ReleaseStyleSheet(sheet: *mut RawServoStyleSheet) -> () { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; unsafe { Helpers::release(sheet) }; } #[no_mangle] pub extern "C" fn Servo_GetComputedValues(element: *mut RawGeckoElement) -> *mut ServoComputedValues { let node = unsafe { GeckoElement::from_raw(element).as_node() }; let arc_cv = node.borrow_data().map(|data| data.style.clone()); arc_cv.map_or(ptr::null_mut(), |arc| unsafe { transmute(arc) }) } #[no_mangle] pub extern "C" fn Servo_GetComputedValuesForAnonymousBox(_: *mut nsIAtom) -> *mut ServoComputedValues { unimplemented!(); } #[no_mangle] pub extern "C" fn Servo_AddRefComputedValues(ptr: *mut ServoComputedValues) -> () { type Helpers = ArcHelpers<ServoComputedValues, GeckoComputedValues>; unsafe { Helpers::addref(ptr) }; } #[no_mangle] pub extern "C" fn Servo_ReleaseComputedValues(ptr: *mut ServoComputedValues) -> () { type Helpers = ArcHelpers<ServoComputedValues, GeckoComputedValues>; unsafe { Helpers::release(ptr) }; } #[no_mangle] pub extern "C" fn Servo_InitStyleSet() -> *mut RawServoStyleSet { let data = Box::new(PerDocumentStyleData::new()); Box::into_raw(data) as *mut RawServoStyleSet } #[no_mangle] pub extern "C" fn Servo_DropStyleSet(data: *mut RawServoStyleSet) -> () { unsafe { let _ = Box::<PerDocumentStyleData>::from_raw(data as *mut PerDocumentStyleData); } }
ArcHelpers
identifier_name
glue.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/. */ #![allow(unsafe_code)] use app_units::Au; use bindings::{RawGeckoDocument, RawGeckoElement}; use bindings::{RawServoStyleSet, RawServoStyleSheet, ServoComputedValues, ServoNodeData}; use bindings::{nsIAtom, uint8_t, uint32_t}; use data::PerDocumentStyleData; use euclid::Size2D; use properties::GeckoComputedValues; use selector_impl::{SharedStyleContext, Stylesheet}; use std::marker::PhantomData; use std::mem::{forget, transmute}; use std::ptr; use std::slice; use std::str::from_utf8_unchecked; use std::sync::{Arc, Mutex}; use style::context::{ReflowGoal, StylistWrapper}; use style::dom::{TDocument, TElement, TNode}; use style::error_reporting::StdoutErrorReporter; use style::parallel; use style::stylesheets::Origin; use traversal::RecalcStyleOnly; use url::Url; use util::arc_ptr_eq; use wrapper::{GeckoDocument, GeckoElement, GeckoNode, NonOpaqueStyleData}; /* * For Gecko->Servo function calls, we need to redeclare the same signature that was declared in * the C header in Gecko. In order to catch accidental mismatches, we run rust-bindgen against * those signatures as well, giving us a second declaration of all the Servo_* functions in this * crate. If there's a mismatch, LLVM will assert and abort, which is a rather awful thing to * depend on but good enough for our purposes. */ #[no_mangle] pub extern "C" fn Servo_RestyleDocument(doc: *mut RawGeckoDocument, raw_data: *mut RawServoStyleSet) -> () { let document = unsafe { GeckoDocument::from_raw(doc) }; let node = match document.root_node() { Some(x) => x, None => return, }; let data = unsafe { &mut *(raw_data as *mut PerDocumentStyleData) }; let _needs_dirtying = data.stylist.update(&data.stylesheets, data.stylesheets_changed); data.stylesheets_changed = false; let shared_style_context = SharedStyleContext { viewport_size: Size2D::new(Au(0), Au(0)), screen_size_changed: false, generation: 0, goal: ReflowGoal::ForScriptQuery, stylist: StylistWrapper(&data.stylist), new_animations_sender: Mutex::new(data.new_animations_sender.clone()), running_animations: data.running_animations.clone(), expired_animations: data.expired_animations.clone(), error_reporter: Box::new(StdoutErrorReporter), }; if node.is_dirty() || node.has_dirty_descendants() { parallel::traverse_dom::<GeckoNode, RecalcStyleOnly>(node, &shared_style_context, &mut data.work_queue); } } #[no_mangle] pub extern "C" fn Servo_DropNodeData(data: *mut ServoNodeData) -> () { unsafe { let _ = Box::<NonOpaqueStyleData>::from_raw(data as *mut NonOpaqueStyleData); } } #[no_mangle] pub extern "C" fn Servo_StylesheetFromUTF8Bytes(bytes: *const uint8_t, length: uint32_t) -> *mut RawServoStyleSheet { let input = unsafe { from_utf8_unchecked(slice::from_raw_parts(bytes, length as usize)) }; // FIXME(heycam): Pass in the real base URL and sheet origin to use. let url = Url::parse("about:none").unwrap(); let sheet = Arc::new(Stylesheet::from_str(input, url, Origin::Author, Box::new(StdoutErrorReporter))); unsafe { transmute(sheet) } } struct ArcHelpers<GeckoType, ServoType> { phantom1: PhantomData<GeckoType>, phantom2: PhantomData<ServoType>, } impl<GeckoType, ServoType> ArcHelpers<GeckoType, ServoType> { fn with<F, Output>(raw: *mut GeckoType, cb: F) -> Output where F: FnOnce(&Arc<ServoType>) -> Output { let owned = unsafe { Self::into(raw) }; let result = cb(&owned); forget(owned); result } unsafe fn into(ptr: *mut GeckoType) -> Arc<ServoType> { transmute(ptr) } unsafe fn addref(ptr: *mut GeckoType) { Self::with(ptr, |arc| forget(arc.clone())); } unsafe fn release(ptr: *mut GeckoType) { let _ = Self::into(ptr); } } #[no_mangle] pub extern "C" fn Servo_AppendStyleSheet(raw_sheet: *mut RawServoStyleSheet, raw_data: *mut RawServoStyleSet) { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; let data = PerDocumentStyleData::borrow_mut_from_raw(raw_data); Helpers::with(raw_sheet, |sheet| { data.stylesheets.retain(|x|!arc_ptr_eq(x, sheet)); data.stylesheets.push(sheet.clone()); data.stylesheets_changed = true; }); } #[no_mangle] pub extern "C" fn Servo_PrependStyleSheet(raw_sheet: *mut RawServoStyleSheet, raw_data: *mut RawServoStyleSet) { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; let data = PerDocumentStyleData::borrow_mut_from_raw(raw_data); Helpers::with(raw_sheet, |sheet| { data.stylesheets.retain(|x|!arc_ptr_eq(x, sheet)); data.stylesheets.insert(0, sheet.clone()); data.stylesheets_changed = true; }) } #[no_mangle] pub extern "C" fn Servo_RemoveStyleSheet(raw_sheet: *mut RawServoStyleSheet, raw_data: *mut RawServoStyleSet) { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; let data = PerDocumentStyleData::borrow_mut_from_raw(raw_data); Helpers::with(raw_sheet, |sheet| { data.stylesheets.retain(|x|!arc_ptr_eq(x, sheet)); data.stylesheets_changed = true; }); } #[no_mangle] pub extern "C" fn Servo_StyleSheetHasRules(raw_sheet: *mut RawServoStyleSheet) -> bool { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; Helpers::with(raw_sheet, |sheet|!sheet.rules.is_empty()) } #[no_mangle] pub extern "C" fn Servo_AddRefStyleSheet(sheet: *mut RawServoStyleSheet) -> () { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; unsafe { Helpers::addref(sheet) }; } #[no_mangle] pub extern "C" fn Servo_ReleaseStyleSheet(sheet: *mut RawServoStyleSheet) -> () { type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>; unsafe { Helpers::release(sheet) }; } #[no_mangle] pub extern "C" fn Servo_GetComputedValues(element: *mut RawGeckoElement) -> *mut ServoComputedValues { let node = unsafe { GeckoElement::from_raw(element).as_node() }; let arc_cv = node.borrow_data().map(|data| data.style.clone()); arc_cv.map_or(ptr::null_mut(), |arc| unsafe { transmute(arc) }) } #[no_mangle] pub extern "C" fn Servo_GetComputedValuesForAnonymousBox(_: *mut nsIAtom) -> *mut ServoComputedValues { unimplemented!(); } #[no_mangle] pub extern "C" fn Servo_AddRefComputedValues(ptr: *mut ServoComputedValues) -> ()
#[no_mangle] pub extern "C" fn Servo_ReleaseComputedValues(ptr: *mut ServoComputedValues) -> () { type Helpers = ArcHelpers<ServoComputedValues, GeckoComputedValues>; unsafe { Helpers::release(ptr) }; } #[no_mangle] pub extern "C" fn Servo_InitStyleSet() -> *mut RawServoStyleSet { let data = Box::new(PerDocumentStyleData::new()); Box::into_raw(data) as *mut RawServoStyleSet } #[no_mangle] pub extern "C" fn Servo_DropStyleSet(data: *mut RawServoStyleSet) -> () { unsafe { let _ = Box::<PerDocumentStyleData>::from_raw(data as *mut PerDocumentStyleData); } }
{ type Helpers = ArcHelpers<ServoComputedValues, GeckoComputedValues>; unsafe { Helpers::addref(ptr) }; }
identifier_body
product.rs
//! The unit of processing passing through a pipeline. use std::fmt; /// Color of a grid cell on a Product. #[derive(Clone,Copy,Debug,Eq,PartialEq)] pub enum Color { Unset, Red, Green, Blue, } impl Color { fn short(&self) -> &'static str { match *self { Color::Unset => " ", Color::Red => "R", Color::Green => "G", Color::Blue => "B", } } } impl Default for Color { fn default() -> Self { Color::Unset } } /// Size of the 2D color grid on a Product. pub const GRID_SIZE: usize = 3; /// Color grid type used in Products. pub type ColorGrid = [[Color; GRID_SIZE]; GRID_SIZE]; /// Product is the unit of processing. /// /// Products are fed into the processing network, mutated, and output. #[derive(Clone,Debug,Default,Eq,PartialEq)] pub struct Product { pub color_grid: ColorGrid, } impl Product { /// Creates a `Product` with the given ColorGrid. pub fn from_grid(grid: ColorGrid) -> Self { Product { color_grid: grid } } /// Creates a `Product` filled with the given `Color`. pub fn with_color(color: Color) -> Self { let mut colors = ColorGrid::default(); for row in &mut colors { for mut cell in row { *cell = color; } } Product { color_grid: colors } } } impl fmt::Display for Product { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for row in &self.color_grid { for cell in row { try!(f.write_str(cell.short()));
Ok(()) } }
} try!(f.write_str(",")); }
random_line_split
product.rs
//! The unit of processing passing through a pipeline. use std::fmt; /// Color of a grid cell on a Product. #[derive(Clone,Copy,Debug,Eq,PartialEq)] pub enum Color { Unset, Red, Green, Blue, } impl Color { fn short(&self) -> &'static str { match *self { Color::Unset => " ", Color::Red => "R", Color::Green => "G", Color::Blue => "B", } } } impl Default for Color { fn
() -> Self { Color::Unset } } /// Size of the 2D color grid on a Product. pub const GRID_SIZE: usize = 3; /// Color grid type used in Products. pub type ColorGrid = [[Color; GRID_SIZE]; GRID_SIZE]; /// Product is the unit of processing. /// /// Products are fed into the processing network, mutated, and output. #[derive(Clone,Debug,Default,Eq,PartialEq)] pub struct Product { pub color_grid: ColorGrid, } impl Product { /// Creates a `Product` with the given ColorGrid. pub fn from_grid(grid: ColorGrid) -> Self { Product { color_grid: grid } } /// Creates a `Product` filled with the given `Color`. pub fn with_color(color: Color) -> Self { let mut colors = ColorGrid::default(); for row in &mut colors { for mut cell in row { *cell = color; } } Product { color_grid: colors } } } impl fmt::Display for Product { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for row in &self.color_grid { for cell in row { try!(f.write_str(cell.short())); } try!(f.write_str(",")); } Ok(()) } }
default
identifier_name
product.rs
//! The unit of processing passing through a pipeline. use std::fmt; /// Color of a grid cell on a Product. #[derive(Clone,Copy,Debug,Eq,PartialEq)] pub enum Color { Unset, Red, Green, Blue, } impl Color { fn short(&self) -> &'static str { match *self { Color::Unset => " ", Color::Red => "R", Color::Green => "G", Color::Blue => "B", } } } impl Default for Color { fn default() -> Self { Color::Unset } } /// Size of the 2D color grid on a Product. pub const GRID_SIZE: usize = 3; /// Color grid type used in Products. pub type ColorGrid = [[Color; GRID_SIZE]; GRID_SIZE]; /// Product is the unit of processing. /// /// Products are fed into the processing network, mutated, and output. #[derive(Clone,Debug,Default,Eq,PartialEq)] pub struct Product { pub color_grid: ColorGrid, } impl Product { /// Creates a `Product` with the given ColorGrid. pub fn from_grid(grid: ColorGrid) -> Self { Product { color_grid: grid } } /// Creates a `Product` filled with the given `Color`. pub fn with_color(color: Color) -> Self
} impl fmt::Display for Product { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for row in &self.color_grid { for cell in row { try!(f.write_str(cell.short())); } try!(f.write_str(",")); } Ok(()) } }
{ let mut colors = ColorGrid::default(); for row in &mut colors { for mut cell in row { *cell = color; } } Product { color_grid: colors } }
identifier_body
config.rs
use crate::model::*; use slog::Logger; use slog::{info, o, warn}; use yaml_rust::Yaml; pub fn parse_dot_files(log: &Logger, dot_files: &Yaml) -> Vec<DotFile> { let mut parsed_dot_files = Vec::new(); info!(log, "Processing dotfiles"); if let Yaml::Hash(entries) = dot_files.clone() { for (key, value) in entries { match (key, value) { (Yaml::String(target), Yaml::String(source)) => parsed_dot_files.push(DotFile { source: source.to_string(), target: target.to_string(), dot_file_type: DotFileType::LINK, }), (Yaml::String(target), Yaml::Hash(settings)) => { parsed_dot_files.push(dot_file_from_settings(&log.new(o!("target" => target.clone())), &target, &settings)) } _ => {} } } } else
parsed_dot_files } fn dot_file_from_settings(log: &Logger, target: &str, settings: &yaml_rust::yaml::Hash) -> DotFile { let mut dot_file = DotFile { source: "<todo>".to_string(), target: target.to_string(), dot_file_type: DotFileType::LINK, }; for (key, value) in settings.clone() { if let (Yaml::String(setting_key), Yaml::String(setting_value)) = (key, value) { match setting_key.as_ref() { "src" => dot_file.source = setting_value.to_string(), "type" => dot_file.dot_file_type = dot_file_type_from_string(log, &setting_value), _ => {} } } } dot_file } fn dot_file_type_from_string(log: &Logger, s: &str) -> DotFileType { match s.to_lowercase().as_ref() { "copy" => DotFileType::COPY, "link" => DotFileType::LINK, x => { warn!(log, "could not parse file type. fallback to link."; "file_type" => x); DotFileType::LINK } } } #[cfg(test)] mod tests { use super::*; use spectral::prelude::*; use yaml_rust::Yaml; use yaml_rust::YamlLoader; #[test] fn parse_config() { let s = " files: ~/.tmux/plugins/tpm: tpm ~/.tmux.conf: src: tmux.conf type: copy ~/.vimrc: src: vimrc type: link "; let yaml_documents = YamlLoader::load_from_str(s).unwrap(); let yaml_config = &yaml_documents[0]; let dot_files: &Yaml = &yaml_config["files"]; let logger = a_logger(); let parsed_dot_files: Vec<DotFile> = parse_dot_files(&logger, dot_files); assert_that(&parsed_dot_files).has_length(3); assert_that(&parsed_dot_files).contains(&DotFile { source: "tpm".to_string(), target: "~/.tmux/plugins/tpm".to_string(), dot_file_type: DotFileType::LINK, }); assert_that(&parsed_dot_files).contains(&DotFile { source: "tmux.conf".to_string(), target: "~/.tmux.conf".to_string(), dot_file_type: DotFileType::COPY, }); assert_that(&parsed_dot_files).contains(&DotFile { source: "vimrc".to_string(), target: "~/.vimrc".to_string(), dot_file_type: DotFileType::LINK, }); } fn a_logger() -> Logger { use slog::Drain; let plain = slog_term::PlainSyncDecorator::new(std::io::stdout()); let drain = slog_term::FullFormat::new(plain).build().fuse(); Logger::root(drain, o!()) } }
{ warn!(log, "Found no entries to process"); }
conditional_block
config.rs
use crate::model::*; use slog::Logger; use slog::{info, o, warn}; use yaml_rust::Yaml; pub fn parse_dot_files(log: &Logger, dot_files: &Yaml) -> Vec<DotFile> { let mut parsed_dot_files = Vec::new(); info!(log, "Processing dotfiles"); if let Yaml::Hash(entries) = dot_files.clone() { for (key, value) in entries { match (key, value) { (Yaml::String(target), Yaml::String(source)) => parsed_dot_files.push(DotFile { source: source.to_string(), target: target.to_string(), dot_file_type: DotFileType::LINK, }), (Yaml::String(target), Yaml::Hash(settings)) => { parsed_dot_files.push(dot_file_from_settings(&log.new(o!("target" => target.clone())), &target, &settings)) } _ => {} } } } else { warn!(log, "Found no entries to process"); } parsed_dot_files } fn dot_file_from_settings(log: &Logger, target: &str, settings: &yaml_rust::yaml::Hash) -> DotFile { let mut dot_file = DotFile { source: "<todo>".to_string(), target: target.to_string(), dot_file_type: DotFileType::LINK, }; for (key, value) in settings.clone() { if let (Yaml::String(setting_key), Yaml::String(setting_value)) = (key, value) { match setting_key.as_ref() { "src" => dot_file.source = setting_value.to_string(), "type" => dot_file.dot_file_type = dot_file_type_from_string(log, &setting_value), _ => {} } } } dot_file } fn
(log: &Logger, s: &str) -> DotFileType { match s.to_lowercase().as_ref() { "copy" => DotFileType::COPY, "link" => DotFileType::LINK, x => { warn!(log, "could not parse file type. fallback to link."; "file_type" => x); DotFileType::LINK } } } #[cfg(test)] mod tests { use super::*; use spectral::prelude::*; use yaml_rust::Yaml; use yaml_rust::YamlLoader; #[test] fn parse_config() { let s = " files: ~/.tmux/plugins/tpm: tpm ~/.tmux.conf: src: tmux.conf type: copy ~/.vimrc: src: vimrc type: link "; let yaml_documents = YamlLoader::load_from_str(s).unwrap(); let yaml_config = &yaml_documents[0]; let dot_files: &Yaml = &yaml_config["files"]; let logger = a_logger(); let parsed_dot_files: Vec<DotFile> = parse_dot_files(&logger, dot_files); assert_that(&parsed_dot_files).has_length(3); assert_that(&parsed_dot_files).contains(&DotFile { source: "tpm".to_string(), target: "~/.tmux/plugins/tpm".to_string(), dot_file_type: DotFileType::LINK, }); assert_that(&parsed_dot_files).contains(&DotFile { source: "tmux.conf".to_string(), target: "~/.tmux.conf".to_string(), dot_file_type: DotFileType::COPY, }); assert_that(&parsed_dot_files).contains(&DotFile { source: "vimrc".to_string(), target: "~/.vimrc".to_string(), dot_file_type: DotFileType::LINK, }); } fn a_logger() -> Logger { use slog::Drain; let plain = slog_term::PlainSyncDecorator::new(std::io::stdout()); let drain = slog_term::FullFormat::new(plain).build().fuse(); Logger::root(drain, o!()) } }
dot_file_type_from_string
identifier_name
config.rs
use crate::model::*; use slog::Logger; use slog::{info, o, warn};
pub fn parse_dot_files(log: &Logger, dot_files: &Yaml) -> Vec<DotFile> { let mut parsed_dot_files = Vec::new(); info!(log, "Processing dotfiles"); if let Yaml::Hash(entries) = dot_files.clone() { for (key, value) in entries { match (key, value) { (Yaml::String(target), Yaml::String(source)) => parsed_dot_files.push(DotFile { source: source.to_string(), target: target.to_string(), dot_file_type: DotFileType::LINK, }), (Yaml::String(target), Yaml::Hash(settings)) => { parsed_dot_files.push(dot_file_from_settings(&log.new(o!("target" => target.clone())), &target, &settings)) } _ => {} } } } else { warn!(log, "Found no entries to process"); } parsed_dot_files } fn dot_file_from_settings(log: &Logger, target: &str, settings: &yaml_rust::yaml::Hash) -> DotFile { let mut dot_file = DotFile { source: "<todo>".to_string(), target: target.to_string(), dot_file_type: DotFileType::LINK, }; for (key, value) in settings.clone() { if let (Yaml::String(setting_key), Yaml::String(setting_value)) = (key, value) { match setting_key.as_ref() { "src" => dot_file.source = setting_value.to_string(), "type" => dot_file.dot_file_type = dot_file_type_from_string(log, &setting_value), _ => {} } } } dot_file } fn dot_file_type_from_string(log: &Logger, s: &str) -> DotFileType { match s.to_lowercase().as_ref() { "copy" => DotFileType::COPY, "link" => DotFileType::LINK, x => { warn!(log, "could not parse file type. fallback to link."; "file_type" => x); DotFileType::LINK } } } #[cfg(test)] mod tests { use super::*; use spectral::prelude::*; use yaml_rust::Yaml; use yaml_rust::YamlLoader; #[test] fn parse_config() { let s = " files: ~/.tmux/plugins/tpm: tpm ~/.tmux.conf: src: tmux.conf type: copy ~/.vimrc: src: vimrc type: link "; let yaml_documents = YamlLoader::load_from_str(s).unwrap(); let yaml_config = &yaml_documents[0]; let dot_files: &Yaml = &yaml_config["files"]; let logger = a_logger(); let parsed_dot_files: Vec<DotFile> = parse_dot_files(&logger, dot_files); assert_that(&parsed_dot_files).has_length(3); assert_that(&parsed_dot_files).contains(&DotFile { source: "tpm".to_string(), target: "~/.tmux/plugins/tpm".to_string(), dot_file_type: DotFileType::LINK, }); assert_that(&parsed_dot_files).contains(&DotFile { source: "tmux.conf".to_string(), target: "~/.tmux.conf".to_string(), dot_file_type: DotFileType::COPY, }); assert_that(&parsed_dot_files).contains(&DotFile { source: "vimrc".to_string(), target: "~/.vimrc".to_string(), dot_file_type: DotFileType::LINK, }); } fn a_logger() -> Logger { use slog::Drain; let plain = slog_term::PlainSyncDecorator::new(std::io::stdout()); let drain = slog_term::FullFormat::new(plain).build().fuse(); Logger::root(drain, o!()) } }
use yaml_rust::Yaml;
random_line_split
config.rs
use crate::model::*; use slog::Logger; use slog::{info, o, warn}; use yaml_rust::Yaml; pub fn parse_dot_files(log: &Logger, dot_files: &Yaml) -> Vec<DotFile> { let mut parsed_dot_files = Vec::new(); info!(log, "Processing dotfiles"); if let Yaml::Hash(entries) = dot_files.clone() { for (key, value) in entries { match (key, value) { (Yaml::String(target), Yaml::String(source)) => parsed_dot_files.push(DotFile { source: source.to_string(), target: target.to_string(), dot_file_type: DotFileType::LINK, }), (Yaml::String(target), Yaml::Hash(settings)) => { parsed_dot_files.push(dot_file_from_settings(&log.new(o!("target" => target.clone())), &target, &settings)) } _ => {} } } } else { warn!(log, "Found no entries to process"); } parsed_dot_files } fn dot_file_from_settings(log: &Logger, target: &str, settings: &yaml_rust::yaml::Hash) -> DotFile { let mut dot_file = DotFile { source: "<todo>".to_string(), target: target.to_string(), dot_file_type: DotFileType::LINK, }; for (key, value) in settings.clone() { if let (Yaml::String(setting_key), Yaml::String(setting_value)) = (key, value) { match setting_key.as_ref() { "src" => dot_file.source = setting_value.to_string(), "type" => dot_file.dot_file_type = dot_file_type_from_string(log, &setting_value), _ => {} } } } dot_file } fn dot_file_type_from_string(log: &Logger, s: &str) -> DotFileType { match s.to_lowercase().as_ref() { "copy" => DotFileType::COPY, "link" => DotFileType::LINK, x => { warn!(log, "could not parse file type. fallback to link."; "file_type" => x); DotFileType::LINK } } } #[cfg(test)] mod tests { use super::*; use spectral::prelude::*; use yaml_rust::Yaml; use yaml_rust::YamlLoader; #[test] fn parse_config()
target: "~/.tmux/plugins/tpm".to_string(), dot_file_type: DotFileType::LINK, }); assert_that(&parsed_dot_files).contains(&DotFile { source: "tmux.conf".to_string(), target: "~/.tmux.conf".to_string(), dot_file_type: DotFileType::COPY, }); assert_that(&parsed_dot_files).contains(&DotFile { source: "vimrc".to_string(), target: "~/.vimrc".to_string(), dot_file_type: DotFileType::LINK, }); } fn a_logger() -> Logger { use slog::Drain; let plain = slog_term::PlainSyncDecorator::new(std::io::stdout()); let drain = slog_term::FullFormat::new(plain).build().fuse(); Logger::root(drain, o!()) } }
{ let s = " files: ~/.tmux/plugins/tpm: tpm ~/.tmux.conf: src: tmux.conf type: copy ~/.vimrc: src: vimrc type: link "; let yaml_documents = YamlLoader::load_from_str(s).unwrap(); let yaml_config = &yaml_documents[0]; let dot_files: &Yaml = &yaml_config["files"]; let logger = a_logger(); let parsed_dot_files: Vec<DotFile> = parse_dot_files(&logger, dot_files); assert_that(&parsed_dot_files).has_length(3); assert_that(&parsed_dot_files).contains(&DotFile { source: "tpm".to_string(),
identifier_body
source.rs
//! Event sources and callbacks. //! //! This is a light-weight implementation of the observer pattern. Subjects are //! modelled as the `Source` type and observers as boxed closures. use std::sync::{RwLock, Weak}; /// An error that can occur with a weakly referenced callback. #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub enum CallbackError { Disappeared, Poisoned, } /// Shorthand for common callback results. pub type CallbackResult<T = ()> = Result<T, CallbackError>; /// A boxed callback. type Callback<A> = Box<dyn FnMut(A) -> CallbackResult + Send + Sync +'static>; /// Perform some callback on a weak reference to a mutex and handle errors /// gracefully. pub fn with_weak<T, U, F: FnOnce(&mut T) -> U>(weak: &Weak<RwLock<T>>, f: F) -> CallbackResult<U> { weak.upgrade() .ok_or(CallbackError::Disappeared) .and_then(|mutex| { mutex .write() .map(|mut t| f(&mut t)) .map_err(|_| CallbackError::Poisoned) }) } /// An event source. pub struct Source<A> { callbacks: Vec<Callback<A>>, } impl<A> Source<A> { /// Create a new source. pub fn new() -> Source<A> { Source { callbacks: vec![] } } /// Register a callback. The callback will be a mutable closure that takes /// an event and must return a result. To unsubscribe from further events, /// the callback has to return an error. pub fn register<F>(&mut self, callback: F) where F: FnMut(A) -> CallbackResult + Send + Sync +'static,
impl<A: Send + Sync + Clone +'static> Source<A> { /// Make the source send an event to all its observers. pub fn send(&mut self, a: A) { use std::mem; let mut new_callbacks = vec![]; mem::swap(&mut new_callbacks, &mut self.callbacks); let n = new_callbacks.len(); let mut iter = new_callbacks.into_iter(); for _ in 1..n { let mut callback = iter.next().unwrap(); if let Ok(_) = callback(a.clone()) { self.callbacks.push(callback); } } // process the last element without cloning if let Some(mut callback) = iter.next() { if let Ok(_) = callback(a) { self.callbacks.push(callback); } } } } #[cfg(test)] mod test { use super::*; use std::sync::{Arc, RwLock}; use std::thread; #[test] fn with_weak_no_error() { let a = Arc::new(RwLock::new(3)); let weak = Arc::downgrade(&a); assert_eq!( with_weak(&weak, |a| { *a = 4; }), Ok(()) ); assert_eq!(*a.read().unwrap(), 4); } #[test] fn with_weak_disappeared() { let weak = Arc::downgrade(&Arc::new(RwLock::new(3))); assert_eq!(with_weak(&weak, |_| ()), Err(CallbackError::Disappeared)); } #[test] fn with_weak_poisoned() { let a = Arc::new(RwLock::new(3)); let a2 = a.clone(); let weak = Arc::downgrade(&a); let _ = thread::spawn(move || { let _g = a2.write().unwrap(); panic!(); }) .join(); assert_eq!(with_weak(&weak, |_| ()), Err(CallbackError::Poisoned)); } #[test] fn source_register_and_send() { let mut src = Source::new(); let a = Arc::new(RwLock::new(3)); { let a = a.clone(); src.register(move |x| { *a.write().unwrap() = x; Ok(()) }); } assert_eq!(src.callbacks.len(), 1); src.send(4); assert_eq!(*a.read().unwrap(), 4); } #[test] fn source_unregister() { let mut src = Source::new(); src.register(|_| Err(CallbackError::Disappeared)); assert_eq!(src.callbacks.len(), 1); src.send(()); assert_eq!(src.callbacks.len(), 0); } }
{ self.callbacks.push(Box::new(callback)); } }
random_line_split
source.rs
//! Event sources and callbacks. //! //! This is a light-weight implementation of the observer pattern. Subjects are //! modelled as the `Source` type and observers as boxed closures. use std::sync::{RwLock, Weak}; /// An error that can occur with a weakly referenced callback. #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub enum CallbackError { Disappeared, Poisoned, } /// Shorthand for common callback results. pub type CallbackResult<T = ()> = Result<T, CallbackError>; /// A boxed callback. type Callback<A> = Box<dyn FnMut(A) -> CallbackResult + Send + Sync +'static>; /// Perform some callback on a weak reference to a mutex and handle errors /// gracefully. pub fn with_weak<T, U, F: FnOnce(&mut T) -> U>(weak: &Weak<RwLock<T>>, f: F) -> CallbackResult<U> { weak.upgrade() .ok_or(CallbackError::Disappeared) .and_then(|mutex| { mutex .write() .map(|mut t| f(&mut t)) .map_err(|_| CallbackError::Poisoned) }) } /// An event source. pub struct Source<A> { callbacks: Vec<Callback<A>>, } impl<A> Source<A> { /// Create a new source. pub fn new() -> Source<A> { Source { callbacks: vec![] } } /// Register a callback. The callback will be a mutable closure that takes /// an event and must return a result. To unsubscribe from further events, /// the callback has to return an error. pub fn register<F>(&mut self, callback: F) where F: FnMut(A) -> CallbackResult + Send + Sync +'static, { self.callbacks.push(Box::new(callback)); } } impl<A: Send + Sync + Clone +'static> Source<A> { /// Make the source send an event to all its observers. pub fn send(&mut self, a: A) { use std::mem; let mut new_callbacks = vec![]; mem::swap(&mut new_callbacks, &mut self.callbacks); let n = new_callbacks.len(); let mut iter = new_callbacks.into_iter(); for _ in 1..n { let mut callback = iter.next().unwrap(); if let Ok(_) = callback(a.clone()) { self.callbacks.push(callback); } } // process the last element without cloning if let Some(mut callback) = iter.next() { if let Ok(_) = callback(a) { self.callbacks.push(callback); } } } } #[cfg(test)] mod test { use super::*; use std::sync::{Arc, RwLock}; use std::thread; #[test] fn with_weak_no_error() { let a = Arc::new(RwLock::new(3)); let weak = Arc::downgrade(&a); assert_eq!( with_weak(&weak, |a| { *a = 4; }), Ok(()) ); assert_eq!(*a.read().unwrap(), 4); } #[test] fn with_weak_disappeared() { let weak = Arc::downgrade(&Arc::new(RwLock::new(3))); assert_eq!(with_weak(&weak, |_| ()), Err(CallbackError::Disappeared)); } #[test] fn with_weak_poisoned()
#[test] fn source_register_and_send() { let mut src = Source::new(); let a = Arc::new(RwLock::new(3)); { let a = a.clone(); src.register(move |x| { *a.write().unwrap() = x; Ok(()) }); } assert_eq!(src.callbacks.len(), 1); src.send(4); assert_eq!(*a.read().unwrap(), 4); } #[test] fn source_unregister() { let mut src = Source::new(); src.register(|_| Err(CallbackError::Disappeared)); assert_eq!(src.callbacks.len(), 1); src.send(()); assert_eq!(src.callbacks.len(), 0); } }
{ let a = Arc::new(RwLock::new(3)); let a2 = a.clone(); let weak = Arc::downgrade(&a); let _ = thread::spawn(move || { let _g = a2.write().unwrap(); panic!(); }) .join(); assert_eq!(with_weak(&weak, |_| ()), Err(CallbackError::Poisoned)); }
identifier_body
source.rs
//! Event sources and callbacks. //! //! This is a light-weight implementation of the observer pattern. Subjects are //! modelled as the `Source` type and observers as boxed closures. use std::sync::{RwLock, Weak}; /// An error that can occur with a weakly referenced callback. #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub enum CallbackError { Disappeared, Poisoned, } /// Shorthand for common callback results. pub type CallbackResult<T = ()> = Result<T, CallbackError>; /// A boxed callback. type Callback<A> = Box<dyn FnMut(A) -> CallbackResult + Send + Sync +'static>; /// Perform some callback on a weak reference to a mutex and handle errors /// gracefully. pub fn with_weak<T, U, F: FnOnce(&mut T) -> U>(weak: &Weak<RwLock<T>>, f: F) -> CallbackResult<U> { weak.upgrade() .ok_or(CallbackError::Disappeared) .and_then(|mutex| { mutex .write() .map(|mut t| f(&mut t)) .map_err(|_| CallbackError::Poisoned) }) } /// An event source. pub struct Source<A> { callbacks: Vec<Callback<A>>, } impl<A> Source<A> { /// Create a new source. pub fn new() -> Source<A> { Source { callbacks: vec![] } } /// Register a callback. The callback will be a mutable closure that takes /// an event and must return a result. To unsubscribe from further events, /// the callback has to return an error. pub fn register<F>(&mut self, callback: F) where F: FnMut(A) -> CallbackResult + Send + Sync +'static, { self.callbacks.push(Box::new(callback)); } } impl<A: Send + Sync + Clone +'static> Source<A> { /// Make the source send an event to all its observers. pub fn send(&mut self, a: A) { use std::mem; let mut new_callbacks = vec![]; mem::swap(&mut new_callbacks, &mut self.callbacks); let n = new_callbacks.len(); let mut iter = new_callbacks.into_iter(); for _ in 1..n { let mut callback = iter.next().unwrap(); if let Ok(_) = callback(a.clone()) { self.callbacks.push(callback); } } // process the last element without cloning if let Some(mut callback) = iter.next() { if let Ok(_) = callback(a)
} } } #[cfg(test)] mod test { use super::*; use std::sync::{Arc, RwLock}; use std::thread; #[test] fn with_weak_no_error() { let a = Arc::new(RwLock::new(3)); let weak = Arc::downgrade(&a); assert_eq!( with_weak(&weak, |a| { *a = 4; }), Ok(()) ); assert_eq!(*a.read().unwrap(), 4); } #[test] fn with_weak_disappeared() { let weak = Arc::downgrade(&Arc::new(RwLock::new(3))); assert_eq!(with_weak(&weak, |_| ()), Err(CallbackError::Disappeared)); } #[test] fn with_weak_poisoned() { let a = Arc::new(RwLock::new(3)); let a2 = a.clone(); let weak = Arc::downgrade(&a); let _ = thread::spawn(move || { let _g = a2.write().unwrap(); panic!(); }) .join(); assert_eq!(with_weak(&weak, |_| ()), Err(CallbackError::Poisoned)); } #[test] fn source_register_and_send() { let mut src = Source::new(); let a = Arc::new(RwLock::new(3)); { let a = a.clone(); src.register(move |x| { *a.write().unwrap() = x; Ok(()) }); } assert_eq!(src.callbacks.len(), 1); src.send(4); assert_eq!(*a.read().unwrap(), 4); } #[test] fn source_unregister() { let mut src = Source::new(); src.register(|_| Err(CallbackError::Disappeared)); assert_eq!(src.callbacks.len(), 1); src.send(()); assert_eq!(src.callbacks.len(), 0); } }
{ self.callbacks.push(callback); }
conditional_block
source.rs
//! Event sources and callbacks. //! //! This is a light-weight implementation of the observer pattern. Subjects are //! modelled as the `Source` type and observers as boxed closures. use std::sync::{RwLock, Weak}; /// An error that can occur with a weakly referenced callback. #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub enum CallbackError { Disappeared, Poisoned, } /// Shorthand for common callback results. pub type CallbackResult<T = ()> = Result<T, CallbackError>; /// A boxed callback. type Callback<A> = Box<dyn FnMut(A) -> CallbackResult + Send + Sync +'static>; /// Perform some callback on a weak reference to a mutex and handle errors /// gracefully. pub fn with_weak<T, U, F: FnOnce(&mut T) -> U>(weak: &Weak<RwLock<T>>, f: F) -> CallbackResult<U> { weak.upgrade() .ok_or(CallbackError::Disappeared) .and_then(|mutex| { mutex .write() .map(|mut t| f(&mut t)) .map_err(|_| CallbackError::Poisoned) }) } /// An event source. pub struct Source<A> { callbacks: Vec<Callback<A>>, } impl<A> Source<A> { /// Create a new source. pub fn new() -> Source<A> { Source { callbacks: vec![] } } /// Register a callback. The callback will be a mutable closure that takes /// an event and must return a result. To unsubscribe from further events, /// the callback has to return an error. pub fn register<F>(&mut self, callback: F) where F: FnMut(A) -> CallbackResult + Send + Sync +'static, { self.callbacks.push(Box::new(callback)); } } impl<A: Send + Sync + Clone +'static> Source<A> { /// Make the source send an event to all its observers. pub fn
(&mut self, a: A) { use std::mem; let mut new_callbacks = vec![]; mem::swap(&mut new_callbacks, &mut self.callbacks); let n = new_callbacks.len(); let mut iter = new_callbacks.into_iter(); for _ in 1..n { let mut callback = iter.next().unwrap(); if let Ok(_) = callback(a.clone()) { self.callbacks.push(callback); } } // process the last element without cloning if let Some(mut callback) = iter.next() { if let Ok(_) = callback(a) { self.callbacks.push(callback); } } } } #[cfg(test)] mod test { use super::*; use std::sync::{Arc, RwLock}; use std::thread; #[test] fn with_weak_no_error() { let a = Arc::new(RwLock::new(3)); let weak = Arc::downgrade(&a); assert_eq!( with_weak(&weak, |a| { *a = 4; }), Ok(()) ); assert_eq!(*a.read().unwrap(), 4); } #[test] fn with_weak_disappeared() { let weak = Arc::downgrade(&Arc::new(RwLock::new(3))); assert_eq!(with_weak(&weak, |_| ()), Err(CallbackError::Disappeared)); } #[test] fn with_weak_poisoned() { let a = Arc::new(RwLock::new(3)); let a2 = a.clone(); let weak = Arc::downgrade(&a); let _ = thread::spawn(move || { let _g = a2.write().unwrap(); panic!(); }) .join(); assert_eq!(with_weak(&weak, |_| ()), Err(CallbackError::Poisoned)); } #[test] fn source_register_and_send() { let mut src = Source::new(); let a = Arc::new(RwLock::new(3)); { let a = a.clone(); src.register(move |x| { *a.write().unwrap() = x; Ok(()) }); } assert_eq!(src.callbacks.len(), 1); src.send(4); assert_eq!(*a.read().unwrap(), 4); } #[test] fn source_unregister() { let mut src = Source::new(); src.register(|_| Err(CallbackError::Disappeared)); assert_eq!(src.callbacks.len(), 1); src.send(()); assert_eq!(src.callbacks.len(), 0); } }
send
identifier_name
text_list.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //! List of strings containing UTF-8 encoded text. use crate::traits::{FromPointerReader, FromPointerBuilder, IndexMove, ListIter}; use crate::private::layout::{ListBuilder, ListReader, Pointer, PointerBuilder, PointerReader}; use crate::Result; #[derive(Copy, Clone)] pub struct Owned; impl <'a> crate::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } #[derive(Clone, Copy)] pub struct Reader<'a> { reader: ListReader<'a> } impl <'a> Reader<'a> { pub fn new<'b>(reader : ListReader<'b>) -> Reader<'b> { Reader::<'b> { reader : reader } } pub fn len(&self) -> u32 { self.reader.len() } pub fn
(self) -> ListIter<Reader<'a>, Result<crate::text::Reader<'a>>>{ let l = self.len(); ListIter::new(self, l) } } impl <'a> FromPointerReader<'a> for Reader<'a> { fn get_from_pointer(reader: &PointerReader<'a>, default: Option<&'a [crate::Word]>) -> Result<Reader<'a>> { Ok(Reader { reader : reader.get_list(Pointer, default)? }) } } impl <'a> IndexMove<u32, Result<crate::text::Reader<'a>>> for Reader<'a>{ fn index_move(&self, index : u32) -> Result<crate::text::Reader<'a>> { self.get(index) } } impl <'a> Reader<'a> { pub fn get(self, index : u32) -> Result<crate::text::Reader<'a>> { assert!(index < self.len()); self.reader.get_pointer_element(index).get_text(None) } } impl <'a> crate::traits::IntoInternalListReader<'a> for Reader<'a> { fn into_internal_list_reader(self) -> ListReader<'a> { self.reader } } pub struct Builder<'a> { builder: ListBuilder<'a> } impl <'a> Builder<'a> { pub fn new(builder : ListBuilder<'a>) -> Builder<'a> { Builder { builder : builder } } pub fn len(&self) -> u32 { self.builder.len() } pub fn set(&mut self, index: u32, value: crate::text::Reader) { assert!(index < self.len()); self.builder.borrow().get_pointer_element(index).set_text(value); } pub fn into_reader(self) -> Reader<'a> { Reader { reader: self.builder.into_reader() } } pub fn reborrow<'b>(&'b mut self) -> Builder<'b> { Builder::<'b> { builder: self.builder.borrow() } } } impl <'a> FromPointerBuilder<'a> for Builder<'a> { fn init_pointer(builder: PointerBuilder<'a>, size: u32) -> Builder<'a> { Builder { builder: builder.init_list(Pointer, size) } } fn get_from_pointer(builder: PointerBuilder<'a>, default: Option<&'a [crate::Word]>) -> Result<Builder<'a>> { Ok(Builder { builder: builder.get_list(Pointer, default)? }) } } impl <'a> Builder<'a> { pub fn get(self, index: u32) -> Result<crate::text::Builder<'a>> { self.builder.get_pointer_element(index).get_text(None) } } impl <'a> crate::traits::SetPointerBuilder<Builder<'a>> for Reader<'a> { fn set_pointer_builder<'b>(pointer: crate::private::layout::PointerBuilder<'b>, value: Reader<'a>, canonicalize: bool) -> Result<()> { pointer.set_list(&value.reader, canonicalize) } } impl <'a> ::std::iter::IntoIterator for Reader<'a> { type Item = Result<crate::text::Reader<'a>>; type IntoIter = ListIter<Reader<'a>, Self::Item>; fn into_iter(self) -> Self::IntoIter { self.iter() } }
iter
identifier_name
text_list.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //! List of strings containing UTF-8 encoded text. use crate::traits::{FromPointerReader, FromPointerBuilder, IndexMove, ListIter}; use crate::private::layout::{ListBuilder, ListReader, Pointer, PointerBuilder, PointerReader}; use crate::Result; #[derive(Copy, Clone)] pub struct Owned; impl <'a> crate::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } #[derive(Clone, Copy)] pub struct Reader<'a> { reader: ListReader<'a> } impl <'a> Reader<'a> { pub fn new<'b>(reader : ListReader<'b>) -> Reader<'b> { Reader::<'b> { reader : reader } } pub fn len(&self) -> u32 { self.reader.len() } pub fn iter(self) -> ListIter<Reader<'a>, Result<crate::text::Reader<'a>>>{ let l = self.len(); ListIter::new(self, l) }
} } impl <'a> IndexMove<u32, Result<crate::text::Reader<'a>>> for Reader<'a>{ fn index_move(&self, index : u32) -> Result<crate::text::Reader<'a>> { self.get(index) } } impl <'a> Reader<'a> { pub fn get(self, index : u32) -> Result<crate::text::Reader<'a>> { assert!(index < self.len()); self.reader.get_pointer_element(index).get_text(None) } } impl <'a> crate::traits::IntoInternalListReader<'a> for Reader<'a> { fn into_internal_list_reader(self) -> ListReader<'a> { self.reader } } pub struct Builder<'a> { builder: ListBuilder<'a> } impl <'a> Builder<'a> { pub fn new(builder : ListBuilder<'a>) -> Builder<'a> { Builder { builder : builder } } pub fn len(&self) -> u32 { self.builder.len() } pub fn set(&mut self, index: u32, value: crate::text::Reader) { assert!(index < self.len()); self.builder.borrow().get_pointer_element(index).set_text(value); } pub fn into_reader(self) -> Reader<'a> { Reader { reader: self.builder.into_reader() } } pub fn reborrow<'b>(&'b mut self) -> Builder<'b> { Builder::<'b> { builder: self.builder.borrow() } } } impl <'a> FromPointerBuilder<'a> for Builder<'a> { fn init_pointer(builder: PointerBuilder<'a>, size: u32) -> Builder<'a> { Builder { builder: builder.init_list(Pointer, size) } } fn get_from_pointer(builder: PointerBuilder<'a>, default: Option<&'a [crate::Word]>) -> Result<Builder<'a>> { Ok(Builder { builder: builder.get_list(Pointer, default)? }) } } impl <'a> Builder<'a> { pub fn get(self, index: u32) -> Result<crate::text::Builder<'a>> { self.builder.get_pointer_element(index).get_text(None) } } impl <'a> crate::traits::SetPointerBuilder<Builder<'a>> for Reader<'a> { fn set_pointer_builder<'b>(pointer: crate::private::layout::PointerBuilder<'b>, value: Reader<'a>, canonicalize: bool) -> Result<()> { pointer.set_list(&value.reader, canonicalize) } } impl <'a> ::std::iter::IntoIterator for Reader<'a> { type Item = Result<crate::text::Reader<'a>>; type IntoIter = ListIter<Reader<'a>, Self::Item>; fn into_iter(self) -> Self::IntoIter { self.iter() } }
} impl <'a> FromPointerReader<'a> for Reader<'a> { fn get_from_pointer(reader: &PointerReader<'a>, default: Option<&'a [crate::Word]>) -> Result<Reader<'a>> { Ok(Reader { reader : reader.get_list(Pointer, default)? })
random_line_split
idle.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 std::cast; use std::libc::{c_int, c_void}; use uvll; use super::{Loop, UvHandle}; use std::rt::rtio::{Callback, PausibleIdleCallback}; pub struct IdleWatcher { handle: *uvll::uv_idle_t, idle_flag: bool, closed: bool, callback: ~Callback, } impl IdleWatcher { pub fn new(loop_: &mut Loop, cb: ~Callback) -> ~IdleWatcher { let handle = UvHandle::alloc(None::<IdleWatcher>, uvll::UV_IDLE); assert_eq!(unsafe { uvll::uv_idle_init(loop_.handle, handle) }, 0); let me = ~IdleWatcher { handle: handle, idle_flag: false, closed: false, callback: cb, }; return me.install(); } pub fn onetime(loop_: &mut Loop, f: proc()) { let handle = UvHandle::alloc(None::<IdleWatcher>, uvll::UV_IDLE); unsafe { assert_eq!(uvll::uv_idle_init(loop_.handle, handle), 0); let data: *c_void = cast::transmute(~f); uvll::set_data_for_uv_handle(handle, data); assert_eq!(uvll::uv_idle_start(handle, onetime_cb), 0) } extern fn onetime_cb(handle: *uvll::uv_idle_t, status: c_int) { assert_eq!(status, 0); unsafe { let data = uvll::get_data_for_uv_handle(handle); let f: ~proc() = cast::transmute(data); (*f)(); uvll::uv_idle_stop(handle); uvll::uv_close(handle, close_cb); } } extern fn close_cb(handle: *uvll::uv_handle_t) { unsafe { uvll::free_handle(handle) } } } } impl PausibleIdleCallback for IdleWatcher { fn pause(&mut self) { if self.idle_flag == true { assert_eq!(unsafe {uvll::uv_idle_stop(self.handle) }, 0); self.idle_flag = false; } } fn resume(&mut self) { if self.idle_flag == false { assert_eq!(unsafe { uvll::uv_idle_start(self.handle, idle_cb) }, 0) self.idle_flag = true; } } } impl UvHandle<uvll::uv_idle_t> for IdleWatcher { fn uv_handle(&self) -> *uvll::uv_idle_t { self.handle } } extern fn idle_cb(handle: *uvll::uv_idle_t, status: c_int) { assert_eq!(status, 0); let idle: &mut IdleWatcher = unsafe { UvHandle::from_uv_handle(&handle) }; idle.callback.call(); } impl Drop for IdleWatcher { fn drop(&mut self) { self.pause(); self.close_async_(); } } #[cfg(test)] mod test { use super::*; use std::rt::tube::Tube; use std::rt::rtio::{Callback, PausibleIdleCallback}; use super::super::local_loop; struct MyCallback(Tube<int>, int); impl Callback for MyCallback { fn call(&mut self) { match *self { MyCallback(ref mut tube, val) => tube.send(val) } } } #[test] fn not_used() { let cb = ~MyCallback(Tube::new(), 1); let _idle = IdleWatcher::new(local_loop(), cb as ~Callback); } #[test] fn smoke_test() { let mut tube = Tube::new(); let cb = ~MyCallback(tube.clone(), 1); let mut idle = IdleWatcher::new(local_loop(), cb as ~Callback); idle.resume(); tube.recv(); } #[test] #[should_fail] fn
() { let tube = Tube::new(); let cb = ~MyCallback(tube.clone(), 1); let mut idle = IdleWatcher::new(local_loop(), cb as ~Callback); idle.resume(); fail!(); } #[test] fn fun_combinations_of_methods() { let mut tube = Tube::new(); let cb = ~MyCallback(tube.clone(), 1); let mut idle = IdleWatcher::new(local_loop(), cb as ~Callback); idle.resume(); tube.recv(); idle.pause(); idle.resume(); idle.resume(); tube.recv(); idle.pause(); idle.pause(); idle.resume(); tube.recv(); } #[test] fn pause_pauses() { let mut tube = Tube::new(); let cb = ~MyCallback(tube.clone(), 1); let mut idle1 = IdleWatcher::new(local_loop(), cb as ~Callback); let cb = ~MyCallback(tube.clone(), 2); let mut idle2 = IdleWatcher::new(local_loop(), cb as ~Callback); idle2.resume(); assert_eq!(tube.recv(), 2); idle2.pause(); idle1.resume(); assert_eq!(tube.recv(), 1); } }
smoke_fail
identifier_name
idle.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 std::cast; use std::libc::{c_int, c_void}; use uvll; use super::{Loop, UvHandle}; use std::rt::rtio::{Callback, PausibleIdleCallback}; pub struct IdleWatcher { handle: *uvll::uv_idle_t, idle_flag: bool, closed: bool, callback: ~Callback, } impl IdleWatcher { pub fn new(loop_: &mut Loop, cb: ~Callback) -> ~IdleWatcher { let handle = UvHandle::alloc(None::<IdleWatcher>, uvll::UV_IDLE); assert_eq!(unsafe { uvll::uv_idle_init(loop_.handle, handle) }, 0); let me = ~IdleWatcher { handle: handle, idle_flag: false, closed: false, callback: cb, }; return me.install(); } pub fn onetime(loop_: &mut Loop, f: proc()) { let handle = UvHandle::alloc(None::<IdleWatcher>, uvll::UV_IDLE); unsafe { assert_eq!(uvll::uv_idle_init(loop_.handle, handle), 0); let data: *c_void = cast::transmute(~f); uvll::set_data_for_uv_handle(handle, data); assert_eq!(uvll::uv_idle_start(handle, onetime_cb), 0) } extern fn onetime_cb(handle: *uvll::uv_idle_t, status: c_int) { assert_eq!(status, 0); unsafe { let data = uvll::get_data_for_uv_handle(handle); let f: ~proc() = cast::transmute(data); (*f)(); uvll::uv_idle_stop(handle); uvll::uv_close(handle, close_cb); } } extern fn close_cb(handle: *uvll::uv_handle_t) { unsafe { uvll::free_handle(handle) } } } } impl PausibleIdleCallback for IdleWatcher { fn pause(&mut self) { if self.idle_flag == true { assert_eq!(unsafe {uvll::uv_idle_stop(self.handle) }, 0); self.idle_flag = false; } } fn resume(&mut self) { if self.idle_flag == false { assert_eq!(unsafe { uvll::uv_idle_start(self.handle, idle_cb) }, 0) self.idle_flag = true; } } } impl UvHandle<uvll::uv_idle_t> for IdleWatcher { fn uv_handle(&self) -> *uvll::uv_idle_t { self.handle } } extern fn idle_cb(handle: *uvll::uv_idle_t, status: c_int) { assert_eq!(status, 0); let idle: &mut IdleWatcher = unsafe { UvHandle::from_uv_handle(&handle) }; idle.callback.call(); } impl Drop for IdleWatcher { fn drop(&mut self) { self.pause(); self.close_async_(); } } #[cfg(test)] mod test { use super::*; use std::rt::tube::Tube; use std::rt::rtio::{Callback, PausibleIdleCallback}; use super::super::local_loop; struct MyCallback(Tube<int>, int); impl Callback for MyCallback { fn call(&mut self)
} #[test] fn not_used() { let cb = ~MyCallback(Tube::new(), 1); let _idle = IdleWatcher::new(local_loop(), cb as ~Callback); } #[test] fn smoke_test() { let mut tube = Tube::new(); let cb = ~MyCallback(tube.clone(), 1); let mut idle = IdleWatcher::new(local_loop(), cb as ~Callback); idle.resume(); tube.recv(); } #[test] #[should_fail] fn smoke_fail() { let tube = Tube::new(); let cb = ~MyCallback(tube.clone(), 1); let mut idle = IdleWatcher::new(local_loop(), cb as ~Callback); idle.resume(); fail!(); } #[test] fn fun_combinations_of_methods() { let mut tube = Tube::new(); let cb = ~MyCallback(tube.clone(), 1); let mut idle = IdleWatcher::new(local_loop(), cb as ~Callback); idle.resume(); tube.recv(); idle.pause(); idle.resume(); idle.resume(); tube.recv(); idle.pause(); idle.pause(); idle.resume(); tube.recv(); } #[test] fn pause_pauses() { let mut tube = Tube::new(); let cb = ~MyCallback(tube.clone(), 1); let mut idle1 = IdleWatcher::new(local_loop(), cb as ~Callback); let cb = ~MyCallback(tube.clone(), 2); let mut idle2 = IdleWatcher::new(local_loop(), cb as ~Callback); idle2.resume(); assert_eq!(tube.recv(), 2); idle2.pause(); idle1.resume(); assert_eq!(tube.recv(), 1); } }
{ match *self { MyCallback(ref mut tube, val) => tube.send(val) } }
identifier_body
idle.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 std::cast; use std::libc::{c_int, c_void}; use uvll; use super::{Loop, UvHandle}; use std::rt::rtio::{Callback, PausibleIdleCallback}; pub struct IdleWatcher { handle: *uvll::uv_idle_t, idle_flag: bool, closed: bool, callback: ~Callback, } impl IdleWatcher { pub fn new(loop_: &mut Loop, cb: ~Callback) -> ~IdleWatcher { let handle = UvHandle::alloc(None::<IdleWatcher>, uvll::UV_IDLE); assert_eq!(unsafe { uvll::uv_idle_init(loop_.handle, handle) }, 0); let me = ~IdleWatcher { handle: handle, idle_flag: false, closed: false, callback: cb, }; return me.install(); } pub fn onetime(loop_: &mut Loop, f: proc()) { let handle = UvHandle::alloc(None::<IdleWatcher>, uvll::UV_IDLE); unsafe { assert_eq!(uvll::uv_idle_init(loop_.handle, handle), 0); let data: *c_void = cast::transmute(~f); uvll::set_data_for_uv_handle(handle, data); assert_eq!(uvll::uv_idle_start(handle, onetime_cb), 0) } extern fn onetime_cb(handle: *uvll::uv_idle_t, status: c_int) { assert_eq!(status, 0); unsafe { let data = uvll::get_data_for_uv_handle(handle); let f: ~proc() = cast::transmute(data); (*f)(); uvll::uv_idle_stop(handle); uvll::uv_close(handle, close_cb); } } extern fn close_cb(handle: *uvll::uv_handle_t) { unsafe { uvll::free_handle(handle) } } } } impl PausibleIdleCallback for IdleWatcher { fn pause(&mut self) { if self.idle_flag == true { assert_eq!(unsafe {uvll::uv_idle_stop(self.handle) }, 0); self.idle_flag = false; } } fn resume(&mut self) { if self.idle_flag == false { assert_eq!(unsafe { uvll::uv_idle_start(self.handle, idle_cb) }, 0) self.idle_flag = true; } } } impl UvHandle<uvll::uv_idle_t> for IdleWatcher { fn uv_handle(&self) -> *uvll::uv_idle_t { self.handle } } extern fn idle_cb(handle: *uvll::uv_idle_t, status: c_int) { assert_eq!(status, 0); let idle: &mut IdleWatcher = unsafe { UvHandle::from_uv_handle(&handle) }; idle.callback.call(); } impl Drop for IdleWatcher { fn drop(&mut self) { self.pause(); self.close_async_(); } } #[cfg(test)] mod test { use super::*; use std::rt::tube::Tube; use std::rt::rtio::{Callback, PausibleIdleCallback}; use super::super::local_loop; struct MyCallback(Tube<int>, int); impl Callback for MyCallback { fn call(&mut self) { match *self { MyCallback(ref mut tube, val) => tube.send(val) } } } #[test] fn not_used() { let cb = ~MyCallback(Tube::new(), 1); let _idle = IdleWatcher::new(local_loop(), cb as ~Callback); } #[test] fn smoke_test() { let mut tube = Tube::new(); let cb = ~MyCallback(tube.clone(), 1); let mut idle = IdleWatcher::new(local_loop(), cb as ~Callback); idle.resume(); tube.recv(); } #[test] #[should_fail] fn smoke_fail() { let tube = Tube::new(); let cb = ~MyCallback(tube.clone(), 1); let mut idle = IdleWatcher::new(local_loop(), cb as ~Callback); idle.resume(); fail!(); } #[test] fn fun_combinations_of_methods() { let mut tube = Tube::new(); let cb = ~MyCallback(tube.clone(), 1); let mut idle = IdleWatcher::new(local_loop(), cb as ~Callback); idle.resume();
idle.pause(); idle.resume(); idle.resume(); tube.recv(); idle.pause(); idle.pause(); idle.resume(); tube.recv(); } #[test] fn pause_pauses() { let mut tube = Tube::new(); let cb = ~MyCallback(tube.clone(), 1); let mut idle1 = IdleWatcher::new(local_loop(), cb as ~Callback); let cb = ~MyCallback(tube.clone(), 2); let mut idle2 = IdleWatcher::new(local_loop(), cb as ~Callback); idle2.resume(); assert_eq!(tube.recv(), 2); idle2.pause(); idle1.resume(); assert_eq!(tube.recv(), 1); } }
tube.recv();
random_line_split
idle.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 std::cast; use std::libc::{c_int, c_void}; use uvll; use super::{Loop, UvHandle}; use std::rt::rtio::{Callback, PausibleIdleCallback}; pub struct IdleWatcher { handle: *uvll::uv_idle_t, idle_flag: bool, closed: bool, callback: ~Callback, } impl IdleWatcher { pub fn new(loop_: &mut Loop, cb: ~Callback) -> ~IdleWatcher { let handle = UvHandle::alloc(None::<IdleWatcher>, uvll::UV_IDLE); assert_eq!(unsafe { uvll::uv_idle_init(loop_.handle, handle) }, 0); let me = ~IdleWatcher { handle: handle, idle_flag: false, closed: false, callback: cb, }; return me.install(); } pub fn onetime(loop_: &mut Loop, f: proc()) { let handle = UvHandle::alloc(None::<IdleWatcher>, uvll::UV_IDLE); unsafe { assert_eq!(uvll::uv_idle_init(loop_.handle, handle), 0); let data: *c_void = cast::transmute(~f); uvll::set_data_for_uv_handle(handle, data); assert_eq!(uvll::uv_idle_start(handle, onetime_cb), 0) } extern fn onetime_cb(handle: *uvll::uv_idle_t, status: c_int) { assert_eq!(status, 0); unsafe { let data = uvll::get_data_for_uv_handle(handle); let f: ~proc() = cast::transmute(data); (*f)(); uvll::uv_idle_stop(handle); uvll::uv_close(handle, close_cb); } } extern fn close_cb(handle: *uvll::uv_handle_t) { unsafe { uvll::free_handle(handle) } } } } impl PausibleIdleCallback for IdleWatcher { fn pause(&mut self) { if self.idle_flag == true { assert_eq!(unsafe {uvll::uv_idle_stop(self.handle) }, 0); self.idle_flag = false; } } fn resume(&mut self) { if self.idle_flag == false
} } impl UvHandle<uvll::uv_idle_t> for IdleWatcher { fn uv_handle(&self) -> *uvll::uv_idle_t { self.handle } } extern fn idle_cb(handle: *uvll::uv_idle_t, status: c_int) { assert_eq!(status, 0); let idle: &mut IdleWatcher = unsafe { UvHandle::from_uv_handle(&handle) }; idle.callback.call(); } impl Drop for IdleWatcher { fn drop(&mut self) { self.pause(); self.close_async_(); } } #[cfg(test)] mod test { use super::*; use std::rt::tube::Tube; use std::rt::rtio::{Callback, PausibleIdleCallback}; use super::super::local_loop; struct MyCallback(Tube<int>, int); impl Callback for MyCallback { fn call(&mut self) { match *self { MyCallback(ref mut tube, val) => tube.send(val) } } } #[test] fn not_used() { let cb = ~MyCallback(Tube::new(), 1); let _idle = IdleWatcher::new(local_loop(), cb as ~Callback); } #[test] fn smoke_test() { let mut tube = Tube::new(); let cb = ~MyCallback(tube.clone(), 1); let mut idle = IdleWatcher::new(local_loop(), cb as ~Callback); idle.resume(); tube.recv(); } #[test] #[should_fail] fn smoke_fail() { let tube = Tube::new(); let cb = ~MyCallback(tube.clone(), 1); let mut idle = IdleWatcher::new(local_loop(), cb as ~Callback); idle.resume(); fail!(); } #[test] fn fun_combinations_of_methods() { let mut tube = Tube::new(); let cb = ~MyCallback(tube.clone(), 1); let mut idle = IdleWatcher::new(local_loop(), cb as ~Callback); idle.resume(); tube.recv(); idle.pause(); idle.resume(); idle.resume(); tube.recv(); idle.pause(); idle.pause(); idle.resume(); tube.recv(); } #[test] fn pause_pauses() { let mut tube = Tube::new(); let cb = ~MyCallback(tube.clone(), 1); let mut idle1 = IdleWatcher::new(local_loop(), cb as ~Callback); let cb = ~MyCallback(tube.clone(), 2); let mut idle2 = IdleWatcher::new(local_loop(), cb as ~Callback); idle2.resume(); assert_eq!(tube.recv(), 2); idle2.pause(); idle1.resume(); assert_eq!(tube.recv(), 1); } }
{ assert_eq!(unsafe { uvll::uv_idle_start(self.handle, idle_cb) }, 0) self.idle_flag = true; }
conditional_block
lib.rs
#![doc(html_logo_url = "https://raw.githubusercontent.com/Kliemann-Service-GmbH/xMZ-Mod-Touch-Server/master/share/xmz-logo.png", html_favicon_url = "https://raw.githubusercontent.com/Kliemann-Service-GmbH/xMZ-Mod-Touch-Server/master/share/favicon.ico", html_root_url = "https://gaswarnanlagen.com/")] //! `xMZ-Mod-Touch Server` //! //! Server Teil der `xMZ-Mod-Touch`-Platform //! //! Git Repository: [https://github.com/Kliemann-Service-GmbH/xMZ-Mod-Touch-Server.git](https://github.com/Kliemann-Service-GmbH/xMZ-Mod-Touch-Server.git) // `error_chain!` can recurse deeply(3) #![recursion_limit = "1024"] #[macro_use] extern crate error_chain;
extern crate iron; extern crate libmodbus_rs; extern crate rand; extern crate router; extern crate serde_json; extern crate sysfs_gpio; pub mod errors; pub mod exception; pub mod json_api; pub mod server; pub mod shift_register; pub use self::exception::{Action, Check, Exception, ExceptionType}; pub use self::server::{Server, ServerType}; pub use self::server::zone::{Zone, ZoneStatus}; pub use self::server::zone::kombisensor::{Kombisensor, KombisensorType}; pub use self::server::zone::kombisensor::sensor::{Sensor, SensorType, SI}; pub use self::shift_register::{ShiftRegister, ShiftRegisterType};
#[macro_use] extern crate log; #[macro_use] extern crate serde_derive; extern crate chrono; extern crate env_logger;
random_line_split
tag-align-dyn-u64.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-linux #7340 fails on 32-bit Linux // ignore-macos #7340 fails on 32-bit macos use std::mem; enum Tag<A> { Tag2(A) } struct Rec { c8: u8, t: Tag<u64> } fn mk_rec() -> Rec { return Rec { c8:0u8, t:Tag::Tag2(0u64) }; } fn is_8_byte_aligned(u: &Tag<u64>) -> bool { let p: uint = unsafe { mem::transmute(u) }; return (p & 7_usize) == 0_usize; } pub fn main() { let x = mk_rec(); assert!(is_8_byte_aligned(&x.t));
}
random_line_split
tag-align-dyn-u64.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-linux #7340 fails on 32-bit Linux // ignore-macos #7340 fails on 32-bit macos use std::mem; enum Tag<A> { Tag2(A) } struct Rec { c8: u8, t: Tag<u64> } fn mk_rec() -> Rec
fn is_8_byte_aligned(u: &Tag<u64>) -> bool { let p: uint = unsafe { mem::transmute(u) }; return (p & 7_usize) == 0_usize; } pub fn main() { let x = mk_rec(); assert!(is_8_byte_aligned(&x.t)); }
{ return Rec { c8:0u8, t:Tag::Tag2(0u64) }; }
identifier_body
tag-align-dyn-u64.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-linux #7340 fails on 32-bit Linux // ignore-macos #7340 fails on 32-bit macos use std::mem; enum Tag<A> { Tag2(A) } struct
{ c8: u8, t: Tag<u64> } fn mk_rec() -> Rec { return Rec { c8:0u8, t:Tag::Tag2(0u64) }; } fn is_8_byte_aligned(u: &Tag<u64>) -> bool { let p: uint = unsafe { mem::transmute(u) }; return (p & 7_usize) == 0_usize; } pub fn main() { let x = mk_rec(); assert!(is_8_byte_aligned(&x.t)); }
Rec
identifier_name
git.rs
use std::collections::HashMap; use std::env; use std::fs::{self, File}; use std::io::prelude::*; use std::path::{Path, PathBuf}; use semver; use git2; use rustc_serialize::json; use app::App; use dependency::Kind; use util::{CargoResult, internal}; #[derive(RustcEncodable, RustcDecodable)] pub struct Crate { pub name: String, pub vers: String, pub deps: Vec<Dependency>, pub cksum: String, pub features: HashMap<String, Vec<String>>, pub yanked: Option<bool>, } #[derive(RustcEncodable, RustcDecodable)] pub struct Dependency { pub name: String, pub req: String, pub features: Vec<String>, pub optional: bool, pub default_features: bool, pub target: Option<String>, pub kind: Option<Kind>, } fn index_file(base: &Path, name: &str) -> PathBuf { let name = name.chars().flat_map(|c| c.to_lowercase()).collect::<String>(); match name.len() { 1 => base.join("1").join(&name), 2 => base.join("2").join(&name), 3 => base.join("3").join(&name[..1]).join(&name), _ => base.join(&name[0..2]) .join(&name[2..4]) .join(&name), } } pub fn add_crate(app: &App, krate: &Crate) -> CargoResult<()> { let repo = app.git_repo.lock().unwrap(); let repo = &*repo; let repo_path = repo.workdir().unwrap(); let dst = index_file(&repo_path, &krate.name); commit_and_push(repo, || { // Add the crate to its relevant file try!(fs::create_dir_all(dst.parent().unwrap())); let mut prev = String::new(); if fs::metadata(&dst).is_ok() { try!(File::open(&dst).and_then(|mut f| f.read_to_string(&mut prev))); } let s = json::encode(krate).unwrap(); let new = prev + &s; let mut f = try!(File::create(&dst)); try!(f.write_all(new.as_bytes())); try!(f.write_all(b"\n")); Ok((format!("Updating crate `{}#{}`", krate.name, krate.vers), dst.clone())) }) } pub fn yank(app: &App, krate: &str, version: &semver::Version, yanked: bool) -> CargoResult<()> { let repo = app.git_repo.lock().unwrap(); let repo = &*repo; let repo_path = repo.workdir().unwrap(); let dst = index_file(&repo_path, krate); commit_and_push(repo, || { let mut prev = String::new(); try!(File::open(&dst).and_then(|mut f| f.read_to_string(&mut prev))); let new = prev.lines().map(|line| { let mut git_crate = try!(json::decode::<Crate>(line).map_err(|_| { internal(format!("couldn't decode: `{}`", line)) })); if git_crate.name!= krate || git_crate.vers.to_string()!= version.to_string() { return Ok(line.to_string()) } git_crate.yanked = Some(yanked); Ok(json::encode(&git_crate).unwrap()) }).collect::<CargoResult<Vec<String>>>(); let new = try!(new).join("\n"); let mut f = try!(File::create(&dst)); try!(f.write_all(new.as_bytes())); try!(f.write_all(b"\n")); Ok((format!("{} crate `{}#{}`", if yanked {"Yanking"} else {"Unyanking"}, krate, version), dst.clone())) }) } fn
<F>(repo: &git2::Repository, mut f: F) -> CargoResult<()> where F: FnMut() -> CargoResult<(String, PathBuf)> { let repo_path = repo.workdir().unwrap(); // Attempt to commit in a loop. It's possible that we're going to need to // rebase our repository, and after that it's possible that we're going to // race to commit the changes. For now we just cap out the maximum number of // retries at a fixed number. for _ in 0..20 { let (msg, dst) = try!(f()); // git add $file let mut index = try!(repo.index()); let mut repo_path = repo_path.iter(); let dst = dst.iter().skip_while(|s| Some(*s) == repo_path.next()) .collect::<PathBuf>(); try!(index.add_path(&dst)); try!(index.write()); let tree_id = try!(index.write_tree()); let tree = try!(repo.find_tree(tree_id)); // git commit -m "..." let head = try!(repo.head()); let parent = try!(repo.find_commit(head.target().unwrap())); let sig = try!(repo.signature()); try!(repo.commit(Some("HEAD"), &sig, &sig, &msg, &tree, &[&parent])); // git push let mut callbacks = git2::RemoteCallbacks::new(); callbacks.credentials(credentials); let mut origin = try!(repo.find_remote("origin")); origin.set_callbacks(callbacks); { let mut push = try!(origin.push()); try!(push.add_refspec("refs/heads/master")); match push.finish() { Ok(()) => { try!(push.update_tips(None, None)); return Ok(()) } Err(..) => {} } } // Ok, we need to update, so fetch and reset --hard try!(origin.add_fetch("refs/heads/*:refs/heads/*")); try!(origin.fetch(&[], None)); let head = try!(repo.head()).target().unwrap(); let obj = try!(repo.find_object(head, None)); try!(repo.reset(&obj, git2::ResetType::Hard, None)); } Err(internal("Too many rebase failures")) } pub fn credentials(_user: &str, _user_from_url: Option<&str>, _cred: git2::CredentialType) -> Result<git2::Cred, git2::Error> { match (env::var("GIT_HTTP_USER"), env::var("GIT_HTTP_PWD")) { (Ok(u), Ok(p)) => { git2::Cred::userpass_plaintext(&u, &p) } _ => Err(git2::Error::from_str("no authentication set")) } }
commit_and_push
identifier_name
git.rs
use std::collections::HashMap; use std::env; use std::fs::{self, File}; use std::io::prelude::*; use std::path::{Path, PathBuf}; use semver; use git2; use rustc_serialize::json; use app::App; use dependency::Kind; use util::{CargoResult, internal}; #[derive(RustcEncodable, RustcDecodable)] pub struct Crate { pub name: String, pub vers: String, pub deps: Vec<Dependency>, pub cksum: String, pub features: HashMap<String, Vec<String>>, pub yanked: Option<bool>, } #[derive(RustcEncodable, RustcDecodable)] pub struct Dependency { pub name: String, pub req: String, pub features: Vec<String>, pub optional: bool, pub default_features: bool, pub target: Option<String>, pub kind: Option<Kind>, } fn index_file(base: &Path, name: &str) -> PathBuf { let name = name.chars().flat_map(|c| c.to_lowercase()).collect::<String>(); match name.len() { 1 => base.join("1").join(&name), 2 => base.join("2").join(&name), 3 => base.join("3").join(&name[..1]).join(&name), _ => base.join(&name[0..2]) .join(&name[2..4]) .join(&name), } } pub fn add_crate(app: &App, krate: &Crate) -> CargoResult<()> { let repo = app.git_repo.lock().unwrap(); let repo = &*repo; let repo_path = repo.workdir().unwrap(); let dst = index_file(&repo_path, &krate.name); commit_and_push(repo, || { // Add the crate to its relevant file try!(fs::create_dir_all(dst.parent().unwrap())); let mut prev = String::new(); if fs::metadata(&dst).is_ok() { try!(File::open(&dst).and_then(|mut f| f.read_to_string(&mut prev))); } let s = json::encode(krate).unwrap(); let new = prev + &s; let mut f = try!(File::create(&dst)); try!(f.write_all(new.as_bytes())); try!(f.write_all(b"\n")); Ok((format!("Updating crate `{}#{}`", krate.name, krate.vers), dst.clone())) }) } pub fn yank(app: &App, krate: &str, version: &semver::Version, yanked: bool) -> CargoResult<()> { let repo = app.git_repo.lock().unwrap(); let repo = &*repo; let repo_path = repo.workdir().unwrap(); let dst = index_file(&repo_path, krate); commit_and_push(repo, || { let mut prev = String::new(); try!(File::open(&dst).and_then(|mut f| f.read_to_string(&mut prev)));
if git_crate.name!= krate || git_crate.vers.to_string()!= version.to_string() { return Ok(line.to_string()) } git_crate.yanked = Some(yanked); Ok(json::encode(&git_crate).unwrap()) }).collect::<CargoResult<Vec<String>>>(); let new = try!(new).join("\n"); let mut f = try!(File::create(&dst)); try!(f.write_all(new.as_bytes())); try!(f.write_all(b"\n")); Ok((format!("{} crate `{}#{}`", if yanked {"Yanking"} else {"Unyanking"}, krate, version), dst.clone())) }) } fn commit_and_push<F>(repo: &git2::Repository, mut f: F) -> CargoResult<()> where F: FnMut() -> CargoResult<(String, PathBuf)> { let repo_path = repo.workdir().unwrap(); // Attempt to commit in a loop. It's possible that we're going to need to // rebase our repository, and after that it's possible that we're going to // race to commit the changes. For now we just cap out the maximum number of // retries at a fixed number. for _ in 0..20 { let (msg, dst) = try!(f()); // git add $file let mut index = try!(repo.index()); let mut repo_path = repo_path.iter(); let dst = dst.iter().skip_while(|s| Some(*s) == repo_path.next()) .collect::<PathBuf>(); try!(index.add_path(&dst)); try!(index.write()); let tree_id = try!(index.write_tree()); let tree = try!(repo.find_tree(tree_id)); // git commit -m "..." let head = try!(repo.head()); let parent = try!(repo.find_commit(head.target().unwrap())); let sig = try!(repo.signature()); try!(repo.commit(Some("HEAD"), &sig, &sig, &msg, &tree, &[&parent])); // git push let mut callbacks = git2::RemoteCallbacks::new(); callbacks.credentials(credentials); let mut origin = try!(repo.find_remote("origin")); origin.set_callbacks(callbacks); { let mut push = try!(origin.push()); try!(push.add_refspec("refs/heads/master")); match push.finish() { Ok(()) => { try!(push.update_tips(None, None)); return Ok(()) } Err(..) => {} } } // Ok, we need to update, so fetch and reset --hard try!(origin.add_fetch("refs/heads/*:refs/heads/*")); try!(origin.fetch(&[], None)); let head = try!(repo.head()).target().unwrap(); let obj = try!(repo.find_object(head, None)); try!(repo.reset(&obj, git2::ResetType::Hard, None)); } Err(internal("Too many rebase failures")) } pub fn credentials(_user: &str, _user_from_url: Option<&str>, _cred: git2::CredentialType) -> Result<git2::Cred, git2::Error> { match (env::var("GIT_HTTP_USER"), env::var("GIT_HTTP_PWD")) { (Ok(u), Ok(p)) => { git2::Cred::userpass_plaintext(&u, &p) } _ => Err(git2::Error::from_str("no authentication set")) } }
let new = prev.lines().map(|line| { let mut git_crate = try!(json::decode::<Crate>(line).map_err(|_| { internal(format!("couldn't decode: `{}`", line)) }));
random_line_split
git.rs
use std::collections::HashMap; use std::env; use std::fs::{self, File}; use std::io::prelude::*; use std::path::{Path, PathBuf}; use semver; use git2; use rustc_serialize::json; use app::App; use dependency::Kind; use util::{CargoResult, internal}; #[derive(RustcEncodable, RustcDecodable)] pub struct Crate { pub name: String, pub vers: String, pub deps: Vec<Dependency>, pub cksum: String, pub features: HashMap<String, Vec<String>>, pub yanked: Option<bool>, } #[derive(RustcEncodable, RustcDecodable)] pub struct Dependency { pub name: String, pub req: String, pub features: Vec<String>, pub optional: bool, pub default_features: bool, pub target: Option<String>, pub kind: Option<Kind>, } fn index_file(base: &Path, name: &str) -> PathBuf { let name = name.chars().flat_map(|c| c.to_lowercase()).collect::<String>(); match name.len() { 1 => base.join("1").join(&name), 2 => base.join("2").join(&name), 3 => base.join("3").join(&name[..1]).join(&name), _ => base.join(&name[0..2]) .join(&name[2..4]) .join(&name), } } pub fn add_crate(app: &App, krate: &Crate) -> CargoResult<()>
dst.clone())) }) } pub fn yank(app: &App, krate: &str, version: &semver::Version, yanked: bool) -> CargoResult<()> { let repo = app.git_repo.lock().unwrap(); let repo = &*repo; let repo_path = repo.workdir().unwrap(); let dst = index_file(&repo_path, krate); commit_and_push(repo, || { let mut prev = String::new(); try!(File::open(&dst).and_then(|mut f| f.read_to_string(&mut prev))); let new = prev.lines().map(|line| { let mut git_crate = try!(json::decode::<Crate>(line).map_err(|_| { internal(format!("couldn't decode: `{}`", line)) })); if git_crate.name!= krate || git_crate.vers.to_string()!= version.to_string() { return Ok(line.to_string()) } git_crate.yanked = Some(yanked); Ok(json::encode(&git_crate).unwrap()) }).collect::<CargoResult<Vec<String>>>(); let new = try!(new).join("\n"); let mut f = try!(File::create(&dst)); try!(f.write_all(new.as_bytes())); try!(f.write_all(b"\n")); Ok((format!("{} crate `{}#{}`", if yanked {"Yanking"} else {"Unyanking"}, krate, version), dst.clone())) }) } fn commit_and_push<F>(repo: &git2::Repository, mut f: F) -> CargoResult<()> where F: FnMut() -> CargoResult<(String, PathBuf)> { let repo_path = repo.workdir().unwrap(); // Attempt to commit in a loop. It's possible that we're going to need to // rebase our repository, and after that it's possible that we're going to // race to commit the changes. For now we just cap out the maximum number of // retries at a fixed number. for _ in 0..20 { let (msg, dst) = try!(f()); // git add $file let mut index = try!(repo.index()); let mut repo_path = repo_path.iter(); let dst = dst.iter().skip_while(|s| Some(*s) == repo_path.next()) .collect::<PathBuf>(); try!(index.add_path(&dst)); try!(index.write()); let tree_id = try!(index.write_tree()); let tree = try!(repo.find_tree(tree_id)); // git commit -m "..." let head = try!(repo.head()); let parent = try!(repo.find_commit(head.target().unwrap())); let sig = try!(repo.signature()); try!(repo.commit(Some("HEAD"), &sig, &sig, &msg, &tree, &[&parent])); // git push let mut callbacks = git2::RemoteCallbacks::new(); callbacks.credentials(credentials); let mut origin = try!(repo.find_remote("origin")); origin.set_callbacks(callbacks); { let mut push = try!(origin.push()); try!(push.add_refspec("refs/heads/master")); match push.finish() { Ok(()) => { try!(push.update_tips(None, None)); return Ok(()) } Err(..) => {} } } // Ok, we need to update, so fetch and reset --hard try!(origin.add_fetch("refs/heads/*:refs/heads/*")); try!(origin.fetch(&[], None)); let head = try!(repo.head()).target().unwrap(); let obj = try!(repo.find_object(head, None)); try!(repo.reset(&obj, git2::ResetType::Hard, None)); } Err(internal("Too many rebase failures")) } pub fn credentials(_user: &str, _user_from_url: Option<&str>, _cred: git2::CredentialType) -> Result<git2::Cred, git2::Error> { match (env::var("GIT_HTTP_USER"), env::var("GIT_HTTP_PWD")) { (Ok(u), Ok(p)) => { git2::Cred::userpass_plaintext(&u, &p) } _ => Err(git2::Error::from_str("no authentication set")) } }
{ let repo = app.git_repo.lock().unwrap(); let repo = &*repo; let repo_path = repo.workdir().unwrap(); let dst = index_file(&repo_path, &krate.name); commit_and_push(repo, || { // Add the crate to its relevant file try!(fs::create_dir_all(dst.parent().unwrap())); let mut prev = String::new(); if fs::metadata(&dst).is_ok() { try!(File::open(&dst).and_then(|mut f| f.read_to_string(&mut prev))); } let s = json::encode(krate).unwrap(); let new = prev + &s; let mut f = try!(File::create(&dst)); try!(f.write_all(new.as_bytes())); try!(f.write_all(b"\n")); Ok((format!("Updating crate `{}#{}`", krate.name, krate.vers),
identifier_body
oestexturefloatlinear.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use super::{constants as webgl, WebGLExtension, WebGLExtensionSpec, WebGLExtensions}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::webglrenderingcontext::WebGLRenderingContext; use dom_struct::dom_struct; #[dom_struct] pub struct OESTextureFloatLinear { reflector_: Reflector, } impl OESTextureFloatLinear { fn new_inherited() -> OESTextureFloatLinear { Self { reflector_: Reflector::new(), } } } impl WebGLExtension for OESTextureFloatLinear { type Extension = OESTextureFloatLinear; fn new(ctx: &WebGLRenderingContext) -> DomRoot<OESTextureFloatLinear> { reflect_dom_object( Box::new(OESTextureFloatLinear::new_inherited()), &*ctx.global(), ) } fn
() -> WebGLExtensionSpec { WebGLExtensionSpec::All } fn is_supported(ext: &WebGLExtensions) -> bool { ext.supports_any_gl_extension(&["GL_OES_texture_float_linear", "GL_ARB_texture_float"]) } fn enable(ext: &WebGLExtensions) { ext.enable_filterable_tex_type(webgl::FLOAT); } fn name() -> &'static str { "OES_texture_float_linear" } }
spec
identifier_name
oestexturefloatlinear.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use super::{constants as webgl, WebGLExtension, WebGLExtensionSpec, WebGLExtensions}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::webglrenderingcontext::WebGLRenderingContext; use dom_struct::dom_struct; #[dom_struct] pub struct OESTextureFloatLinear { reflector_: Reflector, } impl OESTextureFloatLinear { fn new_inherited() -> OESTextureFloatLinear { Self { reflector_: Reflector::new(), } } } impl WebGLExtension for OESTextureFloatLinear { type Extension = OESTextureFloatLinear; fn new(ctx: &WebGLRenderingContext) -> DomRoot<OESTextureFloatLinear> { reflect_dom_object( Box::new(OESTextureFloatLinear::new_inherited()), &*ctx.global(), ) } fn spec() -> WebGLExtensionSpec { WebGLExtensionSpec::All } fn is_supported(ext: &WebGLExtensions) -> bool { ext.supports_any_gl_extension(&["GL_OES_texture_float_linear", "GL_ARB_texture_float"]) } fn enable(ext: &WebGLExtensions)
fn name() -> &'static str { "OES_texture_float_linear" } }
{ ext.enable_filterable_tex_type(webgl::FLOAT); }
identifier_body
oestexturefloatlinear.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use super::{constants as webgl, WebGLExtension, WebGLExtensionSpec, WebGLExtensions}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::webglrenderingcontext::WebGLRenderingContext; use dom_struct::dom_struct; #[dom_struct] pub struct OESTextureFloatLinear { reflector_: Reflector, } impl OESTextureFloatLinear { fn new_inherited() -> OESTextureFloatLinear { Self { reflector_: Reflector::new(), } } } impl WebGLExtension for OESTextureFloatLinear { type Extension = OESTextureFloatLinear; fn new(ctx: &WebGLRenderingContext) -> DomRoot<OESTextureFloatLinear> { reflect_dom_object( Box::new(OESTextureFloatLinear::new_inherited()), &*ctx.global(), ) } fn spec() -> WebGLExtensionSpec { WebGLExtensionSpec::All } fn is_supported(ext: &WebGLExtensions) -> bool {
ext.enable_filterable_tex_type(webgl::FLOAT); } fn name() -> &'static str { "OES_texture_float_linear" } }
ext.supports_any_gl_extension(&["GL_OES_texture_float_linear", "GL_ARB_texture_float"]) } fn enable(ext: &WebGLExtensions) {
random_line_split