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
read-scale.rs
// Copyright 2016 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. extern crate xsettings; extern crate x11_dl; use std::ptr; use std::str; use x11_dl::xlib::Xlib; use xsettings::Client; pub fn
() { let display; let client; let xlib = Xlib::open().unwrap(); unsafe { display = (xlib.XOpenDisplay)(ptr::null_mut()); // Enumerate all properties. client = Client::new(display, (xlib.XDefaultScreen)(display), Box::new(|name, _, setting| { println!("{:?}={:?}", str::from_utf8(name), setting) }), Box::new(|_, _, _| {})); } // Print out a few well-known properties that describe the window scale. let gdk_unscaled_dpi: &[u8] = b"Gdk/UnscaledDPI"; let gdk_xft_dpi: &[u8] = b"Xft/DPI"; let gdk_window_scaling_factor: &[u8] = b"Gdk/WindowScalingFactor"; for key in &[gdk_unscaled_dpi, gdk_xft_dpi, gdk_window_scaling_factor] { let key_str = str::from_utf8(key).unwrap(); match client.get_setting(*key) { Err(err) => println!("{}: {:?}", key_str, err), Ok(setting) => println!("{}={:?}", key_str, setting), } } }
main
identifier_name
read-scale.rs
// Copyright 2016 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. extern crate xsettings; extern crate x11_dl; use std::ptr; use std::str; use x11_dl::xlib::Xlib; use xsettings::Client; pub fn main() { let display; let client; let xlib = Xlib::open().unwrap(); unsafe { display = (xlib.XOpenDisplay)(ptr::null_mut()); // Enumerate all properties. client = Client::new(display, (xlib.XDefaultScreen)(display), Box::new(|name, _, setting| { println!("{:?}={:?}", str::from_utf8(name), setting) }),
let gdk_xft_dpi: &[u8] = b"Xft/DPI"; let gdk_window_scaling_factor: &[u8] = b"Gdk/WindowScalingFactor"; for key in &[gdk_unscaled_dpi, gdk_xft_dpi, gdk_window_scaling_factor] { let key_str = str::from_utf8(key).unwrap(); match client.get_setting(*key) { Err(err) => println!("{}: {:?}", key_str, err), Ok(setting) => println!("{}={:?}", key_str, setting), } } }
Box::new(|_, _, _| {})); } // Print out a few well-known properties that describe the window scale. let gdk_unscaled_dpi: &[u8] = b"Gdk/UnscaledDPI";
random_line_split
heapview.rs
use l2::ast::*; use std::vec::Vec; #[derive(Clone, Copy)] pub enum HeapCellView<'a> { Str(usize, &'a Atom), Var(usize) } pub struct
<'a> { heap: &'a Heap, state_stack: Vec<(usize, &'a HeapCellValue)> } impl<'a> HeapCellViewer<'a> { pub fn new(heap: &'a Heap, focus: usize) -> Self { HeapCellViewer { heap: heap, state_stack: vec![(focus, &heap[focus])] } } fn follow(&self, value: &'a HeapCellValue) -> &'a HeapCellValue { match value { &HeapCellValue::NamedStr(_, _) => value, &HeapCellValue::Ref(cell_num) | &HeapCellValue::Str(cell_num) => &self.heap[cell_num], } } } impl<'a> Iterator for HeapCellViewer<'a> { type Item = HeapCellView<'a>; fn next(&mut self) -> Option<Self::Item> { while let Some(hcv) = self.state_stack.pop() { match hcv { (focus, &HeapCellValue::NamedStr(arity, ref name)) => { for i in (1.. arity + 1).rev() { self.state_stack.push((focus + i, &self.heap[focus + i])); } return Some(HeapCellView::Str(arity, name)); }, (_, &HeapCellValue::Ref(cell_num)) => { let new_hcv = self.follow(hcv.1); if hcv.1 == new_hcv { return Some(HeapCellView::Var(cell_num)); } else { self.state_stack.push((cell_num, new_hcv)); } }, (_, &HeapCellValue::Str(cell_num)) => { let new_hcv = self.follow(hcv.1); self.state_stack.push((cell_num, new_hcv)); } } } None } }
HeapCellViewer
identifier_name
heapview.rs
use l2::ast::*; use std::vec::Vec; #[derive(Clone, Copy)] pub enum HeapCellView<'a> { Str(usize, &'a Atom), Var(usize) } pub struct HeapCellViewer<'a> { heap: &'a Heap, state_stack: Vec<(usize, &'a HeapCellValue)> } impl<'a> HeapCellViewer<'a> { pub fn new(heap: &'a Heap, focus: usize) -> Self { HeapCellViewer { heap: heap, state_stack: vec![(focus, &heap[focus])] } } fn follow(&self, value: &'a HeapCellValue) -> &'a HeapCellValue { match value { &HeapCellValue::NamedStr(_, _) => value, &HeapCellValue::Ref(cell_num) | &HeapCellValue::Str(cell_num) => &self.heap[cell_num], } } } impl<'a> Iterator for HeapCellViewer<'a> { type Item = HeapCellView<'a>; fn next(&mut self) -> Option<Self::Item> { while let Some(hcv) = self.state_stack.pop() { match hcv { (focus, &HeapCellValue::NamedStr(arity, ref name)) => {
return Some(HeapCellView::Str(arity, name)); }, (_, &HeapCellValue::Ref(cell_num)) => { let new_hcv = self.follow(hcv.1); if hcv.1 == new_hcv { return Some(HeapCellView::Var(cell_num)); } else { self.state_stack.push((cell_num, new_hcv)); } }, (_, &HeapCellValue::Str(cell_num)) => { let new_hcv = self.follow(hcv.1); self.state_stack.push((cell_num, new_hcv)); } } } None } }
for i in (1 .. arity + 1).rev() { self.state_stack.push((focus + i, &self.heap[focus + i])); }
random_line_split
macros.rs
// Rust JSON-RPC Library // Written in 2015 by // Andrew Poelstra <[email protected]> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. // // You should have received a copy of the CC0 Public Domain Dedication // along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // //! # Macros //! //! Macros to replace serde's codegen while that is not stable //! #[macro_export] macro_rules! serde_struct_serialize { ($name:ident, $mapvisitor:ident, $($fe:ident => $n:expr),*) => ( impl ::serde::Serialize for $name { fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: ::serde::Serializer { struct $mapvisitor<'a> { value: &'a $name, state: u8, } impl<'a> ::serde::ser::MapVisitor for $mapvisitor<'a> { fn visit<S>(&mut self, serializer: &mut S) -> Result<Option<()>, S::Error> where S: ::serde::Serializer { match self.state { $($n => { self.state += 1; Ok(Some(try!(serializer.visit_struct_elt(stringify!($fe), &self.value.$fe)))) })* _ => { Ok(None) } } } } serializer.visit_struct(stringify!($name), $mapvisitor { value: self, state: 0, }) } } ) } #[macro_export] macro_rules! serde_struct_deserialize { ($name:ident, $visitor:ident, $enum_ty:ident, $enum_visitor:ident, $($fe:ident => $en:ident),*) => ( enum $enum_ty { $($en),* }
struct $enum_visitor; impl ::serde::de::Visitor for $enum_visitor { type Value = $enum_ty; fn visit_str<E>(&mut self, value: &str) -> Result<$enum_ty, E> where E: ::serde::de::Error { match value { $(stringify!($fe) => Ok($enum_ty::$en)),*, _ => Err(::serde::de::Error::syntax("unexpected field")), } } } deserializer.visit($enum_visitor) } } impl ::serde::Deserialize for $name { fn deserialize<D>(deserializer: &mut D) -> Result<$name, D::Error> where D: serde::de::Deserializer { static FIELDS: &'static [&'static str] = &[$(stringify!($fe)),*]; struct $visitor; impl ::serde::de::Visitor for $visitor { type Value = $name; fn visit_map<V>(&mut self, mut v: V) -> Result<$name, V::Error> where V: ::serde::de::MapVisitor { $(let mut $fe = None;)* loop { match try!(v.visit_key()) { $(Some($enum_ty::$en) => { $fe = Some(try!(v.visit_value())); })* None => { break; } } } $(let $fe = match $fe { Some(x) => x, None => try!(v.missing_field(stringify!($fe))), };)* try!(v.end()); Ok($name{ $($fe: $fe),* }) } } deserializer.visit_struct(stringify!($name), FIELDS, $visitor) } } ) }
impl ::serde::Deserialize for $enum_ty { fn deserialize<D>(deserializer: &mut D) -> Result<$enum_ty, D::Error> where D: ::serde::de::Deserializer {
random_line_split
lib.rs
extern crate libc; use std::os::raw; use std::ffi::CString; use std::mem::{transmute, size_of}; use std::default::Default; #[link(name = "kleeRuntest")] extern { fn klee_make_symbolic(data: *mut raw::c_void, length: libc::size_t, name: *const raw::c_char); fn klee_set_forking(state: bool); } pub unsafe fn any(data: *mut raw::c_void, length: usize, name: &str) { klee_make_symbolic(data, length as libc::size_t, CString::new(name).unwrap().as_ptr()); } pub fn set_forking(state: bool) { unsafe { klee_set_forking(state); } } pub fn some<T: Default>(name: &str) -> T { let mut new_symbol = T::default(); symbol(&mut new_symbol, name); return new_symbol; } pub fn
<T>(data: *mut T, name: &str) { unsafe{ any(transmute(data), size_of::<T>(), name); } }
symbol
identifier_name
lib.rs
extern crate libc; use std::os::raw; use std::ffi::CString; use std::mem::{transmute, size_of}; use std::default::Default; #[link(name = "kleeRuntest")] extern { fn klee_make_symbolic(data: *mut raw::c_void, length: libc::size_t, name: *const raw::c_char); fn klee_set_forking(state: bool); } pub unsafe fn any(data: *mut raw::c_void, length: usize, name: &str) { klee_make_symbolic(data, length as libc::size_t, CString::new(name).unwrap().as_ptr()); } pub fn set_forking(state: bool) { unsafe { klee_set_forking(state); } } pub fn some<T: Default>(name: &str) -> T { let mut new_symbol = T::default();
return new_symbol; } pub fn symbol<T>(data: *mut T, name: &str) { unsafe{ any(transmute(data), size_of::<T>(), name); } }
symbol(&mut new_symbol, name);
random_line_split
lib.rs
extern crate libc; use std::os::raw; use std::ffi::CString; use std::mem::{transmute, size_of}; use std::default::Default; #[link(name = "kleeRuntest")] extern { fn klee_make_symbolic(data: *mut raw::c_void, length: libc::size_t, name: *const raw::c_char); fn klee_set_forking(state: bool); } pub unsafe fn any(data: *mut raw::c_void, length: usize, name: &str) { klee_make_symbolic(data, length as libc::size_t, CString::new(name).unwrap().as_ptr()); } pub fn set_forking(state: bool)
pub fn some<T: Default>(name: &str) -> T { let mut new_symbol = T::default(); symbol(&mut new_symbol, name); return new_symbol; } pub fn symbol<T>(data: *mut T, name: &str) { unsafe{ any(transmute(data), size_of::<T>(), name); } }
{ unsafe { klee_set_forking(state); } }
identifier_body
canvaspattern.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 canvas_traits::canvas::{FillOrStrokeStyle, RepetitionStyle, SurfaceStyle}; use dom::bindings::codegen::Bindings::CanvasPatternBinding; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::canvasgradient::ToFillOrStrokeStyle; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use euclid::Size2D; // https://html.spec.whatwg.org/multipage/#canvaspattern #[dom_struct] pub struct CanvasPattern { reflector_: Reflector, surface_data: Vec<u8>, surface_size: Size2D<i32>, repeat_x: bool, repeat_y: bool, origin_clean: bool, } impl CanvasPattern { fn new_inherited( surface_data: Vec<u8>, surface_size: Size2D<i32>, repeat: RepetitionStyle, origin_clean: bool, ) -> CanvasPattern { let (x, y) = match repeat { RepetitionStyle::Repeat => (true, true), RepetitionStyle::RepeatX => (true, false), RepetitionStyle::RepeatY => (false, true), RepetitionStyle::NoRepeat => (false, false), }; CanvasPattern { reflector_: Reflector::new(), surface_data: surface_data, surface_size: surface_size, repeat_x: x, repeat_y: y, origin_clean: origin_clean, } } pub fn new(
origin_clean: bool, ) -> DomRoot<CanvasPattern> { reflect_dom_object( Box::new(CanvasPattern::new_inherited( surface_data, surface_size, repeat, origin_clean, )), global, CanvasPatternBinding::Wrap, ) } pub fn origin_is_clean(&self) -> bool { self.origin_clean } } impl<'a> ToFillOrStrokeStyle for &'a CanvasPattern { fn to_fill_or_stroke_style(self) -> FillOrStrokeStyle { FillOrStrokeStyle::Surface(SurfaceStyle::new( self.surface_data.clone(), self.surface_size, self.repeat_x, self.repeat_y, )) } }
global: &GlobalScope, surface_data: Vec<u8>, surface_size: Size2D<i32>, repeat: RepetitionStyle,
random_line_split
canvaspattern.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 canvas_traits::canvas::{FillOrStrokeStyle, RepetitionStyle, SurfaceStyle}; use dom::bindings::codegen::Bindings::CanvasPatternBinding; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::canvasgradient::ToFillOrStrokeStyle; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use euclid::Size2D; // https://html.spec.whatwg.org/multipage/#canvaspattern #[dom_struct] pub struct
{ reflector_: Reflector, surface_data: Vec<u8>, surface_size: Size2D<i32>, repeat_x: bool, repeat_y: bool, origin_clean: bool, } impl CanvasPattern { fn new_inherited( surface_data: Vec<u8>, surface_size: Size2D<i32>, repeat: RepetitionStyle, origin_clean: bool, ) -> CanvasPattern { let (x, y) = match repeat { RepetitionStyle::Repeat => (true, true), RepetitionStyle::RepeatX => (true, false), RepetitionStyle::RepeatY => (false, true), RepetitionStyle::NoRepeat => (false, false), }; CanvasPattern { reflector_: Reflector::new(), surface_data: surface_data, surface_size: surface_size, repeat_x: x, repeat_y: y, origin_clean: origin_clean, } } pub fn new( global: &GlobalScope, surface_data: Vec<u8>, surface_size: Size2D<i32>, repeat: RepetitionStyle, origin_clean: bool, ) -> DomRoot<CanvasPattern> { reflect_dom_object( Box::new(CanvasPattern::new_inherited( surface_data, surface_size, repeat, origin_clean, )), global, CanvasPatternBinding::Wrap, ) } pub fn origin_is_clean(&self) -> bool { self.origin_clean } } impl<'a> ToFillOrStrokeStyle for &'a CanvasPattern { fn to_fill_or_stroke_style(self) -> FillOrStrokeStyle { FillOrStrokeStyle::Surface(SurfaceStyle::new( self.surface_data.clone(), self.surface_size, self.repeat_x, self.repeat_y, )) } }
CanvasPattern
identifier_name
canvaspattern.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 canvas_traits::canvas::{FillOrStrokeStyle, RepetitionStyle, SurfaceStyle}; use dom::bindings::codegen::Bindings::CanvasPatternBinding; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::canvasgradient::ToFillOrStrokeStyle; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use euclid::Size2D; // https://html.spec.whatwg.org/multipage/#canvaspattern #[dom_struct] pub struct CanvasPattern { reflector_: Reflector, surface_data: Vec<u8>, surface_size: Size2D<i32>, repeat_x: bool, repeat_y: bool, origin_clean: bool, } impl CanvasPattern { fn new_inherited( surface_data: Vec<u8>, surface_size: Size2D<i32>, repeat: RepetitionStyle, origin_clean: bool, ) -> CanvasPattern { let (x, y) = match repeat { RepetitionStyle::Repeat => (true, true), RepetitionStyle::RepeatX => (true, false), RepetitionStyle::RepeatY => (false, true), RepetitionStyle::NoRepeat => (false, false), }; CanvasPattern { reflector_: Reflector::new(), surface_data: surface_data, surface_size: surface_size, repeat_x: x, repeat_y: y, origin_clean: origin_clean, } } pub fn new( global: &GlobalScope, surface_data: Vec<u8>, surface_size: Size2D<i32>, repeat: RepetitionStyle, origin_clean: bool, ) -> DomRoot<CanvasPattern> { reflect_dom_object( Box::new(CanvasPattern::new_inherited( surface_data, surface_size, repeat, origin_clean, )), global, CanvasPatternBinding::Wrap, ) } pub fn origin_is_clean(&self) -> bool { self.origin_clean } } impl<'a> ToFillOrStrokeStyle for &'a CanvasPattern { fn to_fill_or_stroke_style(self) -> FillOrStrokeStyle
}
{ FillOrStrokeStyle::Surface(SurfaceStyle::new( self.surface_data.clone(), self.surface_size, self.repeat_x, self.repeat_y, )) }
identifier_body
send-type-inference.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::sync::mpsc::{channel, Sender}; // tests that ctrl's type gets inferred properly struct Command<K, V> { key: K, val: V } fn
<K:Send+'static,V:Send+'static>(mut tx: Sender<Sender<Command<K, V>>>) { let (tx1, _rx) = channel(); tx.send(tx1); } pub fn main() { }
cache_server
identifier_name
send-type-inference.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::sync::mpsc::{channel, Sender}; // tests that ctrl's type gets inferred properly struct Command<K, V> { key: K, val: V } fn cache_server<K:Send+'static,V:Send+'static>(mut tx: Sender<Sender<Command<K, V>>>) { let (tx1, _rx) = channel();
} pub fn main() { }
tx.send(tx1);
random_line_split
send-type-inference.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::sync::mpsc::{channel, Sender}; // tests that ctrl's type gets inferred properly struct Command<K, V> { key: K, val: V } fn cache_server<K:Send+'static,V:Send+'static>(mut tx: Sender<Sender<Command<K, V>>>)
pub fn main() { }
{ let (tx1, _rx) = channel(); tx.send(tx1); }
identifier_body
box_shadow.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 api::{BorderRadius, BoxShadowClipMode, ClipMode, ColorF, DeviceIntSize, LayoutPrimitiveInfo}; use api::{LayoutRect, LayoutSize, LayoutVector2D}; use clip::ClipSource; use display_list_flattener::DisplayListFlattener; use gpu_cache::GpuCacheHandle; use gpu_types::BoxShadowStretchMode; use prim_store::{BrushKind, BrushPrimitive, PrimitiveContainer}; use prim_store::ScrollNodeAndClipChain; use render_task::RenderTaskCacheEntryHandle; use util::RectHelpers; #[derive(Debug)] pub struct BoxShadowClipSource { // Parameters that define the shadow and are constant. pub shadow_radius: BorderRadius, pub blur_radius: f32, pub clip_mode: BoxShadowClipMode, pub stretch_mode_x: BoxShadowStretchMode, pub stretch_mode_y: BoxShadowStretchMode, // The current cache key (in device-pixels), and handles // to the cached clip region and blurred texture. pub cache_key: Option<(DeviceIntSize, BoxShadowCacheKey)>, pub cache_handle: Option<RenderTaskCacheEntryHandle>, pub clip_data_handle: GpuCacheHandle, // Local-space size of the required render task size. pub shadow_rect_alloc_size: LayoutSize, // The minimal shadow rect for the parameters above, // used when drawing the shadow rect to be blurred. pub minimal_shadow_rect: LayoutRect, // Local space rect for the shadow to be drawn or // stretched in the shadow primitive. pub prim_shadow_rect: LayoutRect, } // The blur shader samples BLUR_SAMPLE_SCALE * blur_radius surrounding texels. pub const BLUR_SAMPLE_SCALE: f32 = 3.0; // Maximum blur radius. // Taken from https://searchfox.org/mozilla-central/rev/c633ffa4c4611f202ca11270dcddb7b29edddff8/layout/painting/nsCSSRendering.cpp#4412 pub const MAX_BLUR_RADIUS : f32 = 300.; // A cache key that uniquely identifies a minimally sized // and blurred box-shadow rect that can be stored in the // texture cache and applied to clip-masks. #[derive(Debug, Clone, Eq, Hash, PartialEq)] #[cfg_attr(feature = "capture", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] pub struct BoxShadowCacheKey { pub blur_radius_dp: i32, pub clip_mode: BoxShadowClipMode, pub rect_size: DeviceIntSize, pub br_top_left: DeviceIntSize, pub br_top_right: DeviceIntSize, pub br_bottom_right: DeviceIntSize, pub br_bottom_left: DeviceIntSize, } impl<'a> DisplayListFlattener<'a> { pub fn add_box_shadow( &mut self, clip_and_scroll: ScrollNodeAndClipChain, prim_info: &LayoutPrimitiveInfo, box_offset: &LayoutVector2D, color: &ColorF, mut blur_radius: f32, spread_radius: f32, border_radius: BorderRadius, clip_mode: BoxShadowClipMode, ) { if color.a == 0.0 { return; } // Inset shadows get smaller as spread radius increases. let (spread_amount, prim_clip_mode) = match clip_mode { BoxShadowClipMode::Outset => { (spread_radius, ClipMode::ClipOut) } BoxShadowClipMode::Inset => { (-spread_radius, ClipMode::Clip) } }; // Ensure the blur radius is somewhat sensible. blur_radius = f32::min(blur_radius, MAX_BLUR_RADIUS); // Adjust the border radius of the box shadow per CSS-spec. let shadow_radius = adjust_border_radius_for_box_shadow( border_radius, spread_amount, ); // Apply parameters that affect where the shadow rect // exists in the local space of the primitive. let shadow_rect = prim_info.rect .translate(box_offset) .inflate(spread_amount, spread_amount); // If blur radius is zero, we can use a fast path with // no blur applied. if blur_radius == 0.0 { // Trivial reject of box-shadows that are not visible. if box_offset.x == 0.0 && box_offset.y == 0.0 && spread_amount == 0.0 { return; } let mut clips = Vec::with_capacity(2); let (final_prim_rect, clip_radius) = match clip_mode { BoxShadowClipMode::Outset => { if!shadow_rect.is_well_formed_and_nonempty() { return; } // TODO(gw): Add a fast path for ClipOut + zero border radius! clips.push(ClipSource::new_rounded_rect( prim_info.rect, border_radius, ClipMode::ClipOut )); (shadow_rect, shadow_radius) } BoxShadowClipMode::Inset => { if shadow_rect.is_well_formed_and_nonempty() { clips.push(ClipSource::new_rounded_rect( shadow_rect, shadow_radius, ClipMode::ClipOut )); } (prim_info.rect, border_radius) } }; clips.push(ClipSource::new_rounded_rect(final_prim_rect, clip_radius, ClipMode::Clip)); self.add_primitive( clip_and_scroll, &LayoutPrimitiveInfo::with_clip_rect(final_prim_rect, prim_info.clip_rect), clips, PrimitiveContainer::Brush( BrushPrimitive::new( BrushKind::new_solid(*color), None, ) ), ); } else { // Normal path for box-shadows with a valid blur radius. let blur_offset = BLUR_SAMPLE_SCALE * blur_radius; let mut extra_clips = vec![]; // Add a normal clip mask to clip out the contents // of the surrounding primitive. extra_clips.push(ClipSource::new_rounded_rect( prim_info.rect, border_radius, prim_clip_mode, )); // Get the local rect of where the shadow will be drawn, // expanded to include room for the blurred region. let dest_rect = shadow_rect.inflate(blur_offset, blur_offset); // Draw the box-shadow as a solid rect, using a box-shadow // clip mask source. let prim = BrushPrimitive::new( BrushKind::new_solid(*color), None, ); // Create the box-shadow clip source. let shadow_clip_source = ClipSource::new_box_shadow( shadow_rect, shadow_radius, dest_rect, blur_radius, clip_mode, ); let prim_info = match clip_mode { BoxShadowClipMode::Outset =>
BoxShadowClipMode::Inset => { // If the inner shadow rect contains the prim // rect, no pixels will be shadowed. if border_radius.is_zero() && shadow_rect.inflate(-blur_radius, -blur_radius).contains_rect(&prim_info.rect) { return; } // Inset shadows are still visible, even if the // inset shadow rect becomes invalid (they will // just look like a solid rectangle). if shadow_rect.is_well_formed_and_nonempty() { extra_clips.push(shadow_clip_source); } // Inset shadows draw inside the original primitive. prim_info.clone() } }; self.add_primitive( clip_and_scroll, &prim_info, extra_clips, PrimitiveContainer::Brush(prim), ); } } } fn adjust_border_radius_for_box_shadow( radius: BorderRadius, spread_amount: f32, ) -> BorderRadius { BorderRadius { top_left: adjust_corner_for_box_shadow( radius.top_left, spread_amount, ), top_right: adjust_corner_for_box_shadow( radius.top_right, spread_amount, ), bottom_right: adjust_corner_for_box_shadow( radius.bottom_right, spread_amount, ), bottom_left: adjust_corner_for_box_shadow( radius.bottom_left, spread_amount, ), } } fn adjust_corner_for_box_shadow( corner: LayoutSize, spread_amount: f32, ) -> LayoutSize { LayoutSize::new( adjust_radius_for_box_shadow( corner.width, spread_amount ), adjust_radius_for_box_shadow( corner.height, spread_amount ), ) } fn adjust_radius_for_box_shadow( border_radius: f32, spread_amount: f32, ) -> f32 { if border_radius > 0.0 { (border_radius + spread_amount).max(0.0) } else { 0.0 } }
{ // Certain spread-radii make the shadow invalid. if !shadow_rect.is_well_formed_and_nonempty() { return; } // Add the box-shadow clip source. extra_clips.push(shadow_clip_source); // Outset shadows are expanded by the shadow // region from the original primitive. LayoutPrimitiveInfo::with_clip_rect(dest_rect, prim_info.clip_rect) }
conditional_block
box_shadow.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 api::{BorderRadius, BoxShadowClipMode, ClipMode, ColorF, DeviceIntSize, LayoutPrimitiveInfo}; use api::{LayoutRect, LayoutSize, LayoutVector2D}; use clip::ClipSource; use display_list_flattener::DisplayListFlattener; use gpu_cache::GpuCacheHandle; use gpu_types::BoxShadowStretchMode; use prim_store::{BrushKind, BrushPrimitive, PrimitiveContainer}; use prim_store::ScrollNodeAndClipChain; use render_task::RenderTaskCacheEntryHandle; use util::RectHelpers; #[derive(Debug)] pub struct BoxShadowClipSource { // Parameters that define the shadow and are constant. pub shadow_radius: BorderRadius, pub blur_radius: f32, pub clip_mode: BoxShadowClipMode, pub stretch_mode_x: BoxShadowStretchMode, pub stretch_mode_y: BoxShadowStretchMode, // The current cache key (in device-pixels), and handles // to the cached clip region and blurred texture. pub cache_key: Option<(DeviceIntSize, BoxShadowCacheKey)>, pub cache_handle: Option<RenderTaskCacheEntryHandle>, pub clip_data_handle: GpuCacheHandle, // Local-space size of the required render task size. pub shadow_rect_alloc_size: LayoutSize, // The minimal shadow rect for the parameters above, // used when drawing the shadow rect to be blurred. pub minimal_shadow_rect: LayoutRect, // Local space rect for the shadow to be drawn or // stretched in the shadow primitive. pub prim_shadow_rect: LayoutRect, } // The blur shader samples BLUR_SAMPLE_SCALE * blur_radius surrounding texels. pub const BLUR_SAMPLE_SCALE: f32 = 3.0; // Maximum blur radius. // Taken from https://searchfox.org/mozilla-central/rev/c633ffa4c4611f202ca11270dcddb7b29edddff8/layout/painting/nsCSSRendering.cpp#4412 pub const MAX_BLUR_RADIUS : f32 = 300.; // A cache key that uniquely identifies a minimally sized // and blurred box-shadow rect that can be stored in the // texture cache and applied to clip-masks. #[derive(Debug, Clone, Eq, Hash, PartialEq)] #[cfg_attr(feature = "capture", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] pub struct BoxShadowCacheKey { pub blur_radius_dp: i32, pub clip_mode: BoxShadowClipMode, pub rect_size: DeviceIntSize, pub br_top_left: DeviceIntSize, pub br_top_right: DeviceIntSize, pub br_bottom_right: DeviceIntSize, pub br_bottom_left: DeviceIntSize, } impl<'a> DisplayListFlattener<'a> { pub fn add_box_shadow( &mut self, clip_and_scroll: ScrollNodeAndClipChain, prim_info: &LayoutPrimitiveInfo, box_offset: &LayoutVector2D, color: &ColorF, mut blur_radius: f32, spread_radius: f32, border_radius: BorderRadius, clip_mode: BoxShadowClipMode, ) { if color.a == 0.0 { return; } // Inset shadows get smaller as spread radius increases. let (spread_amount, prim_clip_mode) = match clip_mode { BoxShadowClipMode::Outset => { (spread_radius, ClipMode::ClipOut) } BoxShadowClipMode::Inset => { (-spread_radius, ClipMode::Clip) } }; // Ensure the blur radius is somewhat sensible. blur_radius = f32::min(blur_radius, MAX_BLUR_RADIUS); // Adjust the border radius of the box shadow per CSS-spec. let shadow_radius = adjust_border_radius_for_box_shadow( border_radius, spread_amount, ); // Apply parameters that affect where the shadow rect // exists in the local space of the primitive. let shadow_rect = prim_info.rect .translate(box_offset) .inflate(spread_amount, spread_amount); // If blur radius is zero, we can use a fast path with // no blur applied. if blur_radius == 0.0 { // Trivial reject of box-shadows that are not visible. if box_offset.x == 0.0 && box_offset.y == 0.0 && spread_amount == 0.0 { return; } let mut clips = Vec::with_capacity(2); let (final_prim_rect, clip_radius) = match clip_mode { BoxShadowClipMode::Outset => { if!shadow_rect.is_well_formed_and_nonempty() { return; } // TODO(gw): Add a fast path for ClipOut + zero border radius! clips.push(ClipSource::new_rounded_rect( prim_info.rect, border_radius, ClipMode::ClipOut )); (shadow_rect, shadow_radius) } BoxShadowClipMode::Inset => { if shadow_rect.is_well_formed_and_nonempty() { clips.push(ClipSource::new_rounded_rect( shadow_rect, shadow_radius, ClipMode::ClipOut )); } (prim_info.rect, border_radius) } }; clips.push(ClipSource::new_rounded_rect(final_prim_rect, clip_radius, ClipMode::Clip)); self.add_primitive( clip_and_scroll, &LayoutPrimitiveInfo::with_clip_rect(final_prim_rect, prim_info.clip_rect), clips, PrimitiveContainer::Brush( BrushPrimitive::new( BrushKind::new_solid(*color), None, ) ), ); } else { // Normal path for box-shadows with a valid blur radius. let blur_offset = BLUR_SAMPLE_SCALE * blur_radius; let mut extra_clips = vec![]; // Add a normal clip mask to clip out the contents // of the surrounding primitive. extra_clips.push(ClipSource::new_rounded_rect( prim_info.rect, border_radius, prim_clip_mode, )); // Get the local rect of where the shadow will be drawn, // expanded to include room for the blurred region. let dest_rect = shadow_rect.inflate(blur_offset, blur_offset); // Draw the box-shadow as a solid rect, using a box-shadow // clip mask source. let prim = BrushPrimitive::new( BrushKind::new_solid(*color), None, ); // Create the box-shadow clip source. let shadow_clip_source = ClipSource::new_box_shadow( shadow_rect, shadow_radius, dest_rect, blur_radius, clip_mode, ); let prim_info = match clip_mode { BoxShadowClipMode::Outset => { // Certain spread-radii make the shadow invalid. if!shadow_rect.is_well_formed_and_nonempty() { return; } // Add the box-shadow clip source. extra_clips.push(shadow_clip_source); // Outset shadows are expanded by the shadow // region from the original primitive. LayoutPrimitiveInfo::with_clip_rect(dest_rect, prim_info.clip_rect) } BoxShadowClipMode::Inset => { // If the inner shadow rect contains the prim // rect, no pixels will be shadowed. if border_radius.is_zero() && shadow_rect.inflate(-blur_radius, -blur_radius).contains_rect(&prim_info.rect) { return; } // Inset shadows are still visible, even if the // inset shadow rect becomes invalid (they will // just look like a solid rectangle). if shadow_rect.is_well_formed_and_nonempty() { extra_clips.push(shadow_clip_source); } // Inset shadows draw inside the original primitive. prim_info.clone() } }; self.add_primitive( clip_and_scroll, &prim_info, extra_clips, PrimitiveContainer::Brush(prim), ); } } } fn adjust_border_radius_for_box_shadow( radius: BorderRadius, spread_amount: f32, ) -> BorderRadius { BorderRadius { top_left: adjust_corner_for_box_shadow( radius.top_left, spread_amount, ), top_right: adjust_corner_for_box_shadow( radius.top_right, spread_amount, ), bottom_right: adjust_corner_for_box_shadow( radius.bottom_right, spread_amount, ), bottom_left: adjust_corner_for_box_shadow( radius.bottom_left, spread_amount, ), } } fn
( corner: LayoutSize, spread_amount: f32, ) -> LayoutSize { LayoutSize::new( adjust_radius_for_box_shadow( corner.width, spread_amount ), adjust_radius_for_box_shadow( corner.height, spread_amount ), ) } fn adjust_radius_for_box_shadow( border_radius: f32, spread_amount: f32, ) -> f32 { if border_radius > 0.0 { (border_radius + spread_amount).max(0.0) } else { 0.0 } }
adjust_corner_for_box_shadow
identifier_name
box_shadow.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 api::{BorderRadius, BoxShadowClipMode, ClipMode, ColorF, DeviceIntSize, LayoutPrimitiveInfo}; use api::{LayoutRect, LayoutSize, LayoutVector2D}; use clip::ClipSource; use display_list_flattener::DisplayListFlattener; use gpu_cache::GpuCacheHandle; use gpu_types::BoxShadowStretchMode; use prim_store::{BrushKind, BrushPrimitive, PrimitiveContainer}; use prim_store::ScrollNodeAndClipChain; use render_task::RenderTaskCacheEntryHandle; use util::RectHelpers; #[derive(Debug)] pub struct BoxShadowClipSource { // Parameters that define the shadow and are constant. pub shadow_radius: BorderRadius, pub blur_radius: f32, pub clip_mode: BoxShadowClipMode, pub stretch_mode_x: BoxShadowStretchMode, pub stretch_mode_y: BoxShadowStretchMode, // The current cache key (in device-pixels), and handles // to the cached clip region and blurred texture. pub cache_key: Option<(DeviceIntSize, BoxShadowCacheKey)>, pub cache_handle: Option<RenderTaskCacheEntryHandle>, pub clip_data_handle: GpuCacheHandle, // Local-space size of the required render task size. pub shadow_rect_alloc_size: LayoutSize, // The minimal shadow rect for the parameters above, // used when drawing the shadow rect to be blurred. pub minimal_shadow_rect: LayoutRect, // Local space rect for the shadow to be drawn or // stretched in the shadow primitive. pub prim_shadow_rect: LayoutRect, } // The blur shader samples BLUR_SAMPLE_SCALE * blur_radius surrounding texels. pub const BLUR_SAMPLE_SCALE: f32 = 3.0; // Maximum blur radius. // Taken from https://searchfox.org/mozilla-central/rev/c633ffa4c4611f202ca11270dcddb7b29edddff8/layout/painting/nsCSSRendering.cpp#4412 pub const MAX_BLUR_RADIUS : f32 = 300.; // A cache key that uniquely identifies a minimally sized // and blurred box-shadow rect that can be stored in the // texture cache and applied to clip-masks. #[derive(Debug, Clone, Eq, Hash, PartialEq)] #[cfg_attr(feature = "capture", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] pub struct BoxShadowCacheKey { pub blur_radius_dp: i32, pub clip_mode: BoxShadowClipMode, pub rect_size: DeviceIntSize, pub br_top_left: DeviceIntSize, pub br_top_right: DeviceIntSize, pub br_bottom_right: DeviceIntSize, pub br_bottom_left: DeviceIntSize, } impl<'a> DisplayListFlattener<'a> { pub fn add_box_shadow( &mut self, clip_and_scroll: ScrollNodeAndClipChain, prim_info: &LayoutPrimitiveInfo, box_offset: &LayoutVector2D, color: &ColorF, mut blur_radius: f32, spread_radius: f32, border_radius: BorderRadius, clip_mode: BoxShadowClipMode, ) { if color.a == 0.0 { return; } // Inset shadows get smaller as spread radius increases. let (spread_amount, prim_clip_mode) = match clip_mode { BoxShadowClipMode::Outset => { (spread_radius, ClipMode::ClipOut) } BoxShadowClipMode::Inset => { (-spread_radius, ClipMode::Clip) } }; // Ensure the blur radius is somewhat sensible. blur_radius = f32::min(blur_radius, MAX_BLUR_RADIUS); // Adjust the border radius of the box shadow per CSS-spec. let shadow_radius = adjust_border_radius_for_box_shadow( border_radius, spread_amount, ); // Apply parameters that affect where the shadow rect // exists in the local space of the primitive. let shadow_rect = prim_info.rect .translate(box_offset) .inflate(spread_amount, spread_amount); // If blur radius is zero, we can use a fast path with // no blur applied. if blur_radius == 0.0 { // Trivial reject of box-shadows that are not visible. if box_offset.x == 0.0 && box_offset.y == 0.0 && spread_amount == 0.0 { return; } let mut clips = Vec::with_capacity(2); let (final_prim_rect, clip_radius) = match clip_mode { BoxShadowClipMode::Outset => { if!shadow_rect.is_well_formed_and_nonempty() { return; } // TODO(gw): Add a fast path for ClipOut + zero border radius! clips.push(ClipSource::new_rounded_rect( prim_info.rect, border_radius, ClipMode::ClipOut )); (shadow_rect, shadow_radius) } BoxShadowClipMode::Inset => { if shadow_rect.is_well_formed_and_nonempty() { clips.push(ClipSource::new_rounded_rect( shadow_rect, shadow_radius, ClipMode::ClipOut )); } (prim_info.rect, border_radius) } }; clips.push(ClipSource::new_rounded_rect(final_prim_rect, clip_radius, ClipMode::Clip)); self.add_primitive( clip_and_scroll, &LayoutPrimitiveInfo::with_clip_rect(final_prim_rect, prim_info.clip_rect), clips, PrimitiveContainer::Brush( BrushPrimitive::new( BrushKind::new_solid(*color), None, ) ), ); } else { // Normal path for box-shadows with a valid blur radius. let blur_offset = BLUR_SAMPLE_SCALE * blur_radius; let mut extra_clips = vec![]; // Add a normal clip mask to clip out the contents // of the surrounding primitive. extra_clips.push(ClipSource::new_rounded_rect( prim_info.rect, border_radius, prim_clip_mode, )); // Get the local rect of where the shadow will be drawn, // expanded to include room for the blurred region. let dest_rect = shadow_rect.inflate(blur_offset, blur_offset); // Draw the box-shadow as a solid rect, using a box-shadow // clip mask source. let prim = BrushPrimitive::new( BrushKind::new_solid(*color), None, ); // Create the box-shadow clip source. let shadow_clip_source = ClipSource::new_box_shadow( shadow_rect, shadow_radius, dest_rect, blur_radius, clip_mode, ); let prim_info = match clip_mode { BoxShadowClipMode::Outset => { // Certain spread-radii make the shadow invalid. if!shadow_rect.is_well_formed_and_nonempty() { return; } // Add the box-shadow clip source. extra_clips.push(shadow_clip_source); // Outset shadows are expanded by the shadow // region from the original primitive. LayoutPrimitiveInfo::with_clip_rect(dest_rect, prim_info.clip_rect) } BoxShadowClipMode::Inset => { // If the inner shadow rect contains the prim // rect, no pixels will be shadowed. if border_radius.is_zero() && shadow_rect.inflate(-blur_radius, -blur_radius).contains_rect(&prim_info.rect) { return; } // Inset shadows are still visible, even if the // inset shadow rect becomes invalid (they will // just look like a solid rectangle). if shadow_rect.is_well_formed_and_nonempty() { extra_clips.push(shadow_clip_source); } // Inset shadows draw inside the original primitive. prim_info.clone() } }; self.add_primitive( clip_and_scroll, &prim_info, extra_clips, PrimitiveContainer::Brush(prim), ); } } } fn adjust_border_radius_for_box_shadow( radius: BorderRadius, spread_amount: f32, ) -> BorderRadius { BorderRadius { top_left: adjust_corner_for_box_shadow( radius.top_left, spread_amount, ), top_right: adjust_corner_for_box_shadow( radius.top_right, spread_amount, ), bottom_right: adjust_corner_for_box_shadow( radius.bottom_right, spread_amount, ),
} } fn adjust_corner_for_box_shadow( corner: LayoutSize, spread_amount: f32, ) -> LayoutSize { LayoutSize::new( adjust_radius_for_box_shadow( corner.width, spread_amount ), adjust_radius_for_box_shadow( corner.height, spread_amount ), ) } fn adjust_radius_for_box_shadow( border_radius: f32, spread_amount: f32, ) -> f32 { if border_radius > 0.0 { (border_radius + spread_amount).max(0.0) } else { 0.0 } }
bottom_left: adjust_corner_for_box_shadow( radius.bottom_left, spread_amount, ),
random_line_split
char.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. //! Character manipulation (`char` type, Unicode Scalar Value) //! //! This module provides the `CharExt` trait, as well as its //! implementation for the primitive `char` type, in order to allow //! basic character manipulation. //! //! A `char` actually represents a //! *[Unicode Scalar //! Value](http://www.unicode.org/glossary/#unicode_scalar_value)*, as it can //! contain any Unicode code point except high-surrogate and low-surrogate code //! points. //! //! As such, only values in the ranges \[0x0,0xD7FF\] and \[0xE000,0x10FFFF\] //! (inclusive) are allowed. A `char` can always be safely cast to a `u32`; //! however the converse is not always true due to the above range limits //! and, as such, should be performed via the `from_u32` function. #![stable(feature = "rust1", since = "1.0.0")] #![doc(primitive = "char")] use core::char::CharExt as C; use core::option::Option::{self, Some}; use core::iter::Iterator; use tables::{derived_property, property, general_category, conversions, charwidth}; // stable reexports pub use core::char::{MAX, from_u32, from_digit, EscapeUnicode, EscapeDefault}; // unstable reexports #[allow(deprecated)] pub use normalize::{decompose_canonical, decompose_compatible, compose}; #[allow(deprecated)] pub use tables::normalization::canonical_combining_class; pub use tables::UNICODE_VERSION; /// An iterator over the lowercase mapping of a given character, returned from /// the [`to_lowercase` method](../primitive.char.html#method.to_lowercase) on /// characters. #[stable(feature = "rust1", since = "1.0.0")] pub struct ToLowercase(Option<char>); #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for ToLowercase { type Item = char; fn next(&mut self) -> Option<char> { self.0.take() } } /// An iterator over the uppercase mapping of a given character, returned from /// the [`to_uppercase` method](../primitive.char.html#method.to_uppercase) on /// characters. #[stable(feature = "rust1", since = "1.0.0")] pub struct ToUppercase(Option<char>); #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for ToUppercase { type Item = char; fn next(&mut self) -> Option<char> { self.0.take() } } #[stable(feature = "rust1", since = "1.0.0")] #[lang = "char"] impl char { /// Checks if a `char` parses as a numeric digit in the given radix. /// /// Compared to `is_numeric()`, this function only recognizes the characters /// `0-9`, `a-z` and `A-Z`. /// /// # Return value /// /// Returns `true` if `c` is a valid digit under `radix`, and `false` /// otherwise. /// /// # Panics /// /// Panics if given a radix > 36. /// /// # Examples /// /// ``` /// let c = '1'; /// /// assert!(c.is_digit(10)); /// /// assert!('f'.is_digit(16)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_digit(self, radix: u32) -> bool { C::is_digit(self, radix) } /// Converts a character to the corresponding digit. /// /// # Return value /// /// If `c` is between '0' and '9', the corresponding value between 0 and /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns /// none if the character does not refer to a digit in the given radix. /// /// # Panics /// /// Panics if given a radix outside the range [0..36]. /// /// # Examples /// /// ``` /// let c = '1'; /// /// assert_eq!(c.to_digit(10), Some(1)); /// /// assert_eq!('f'.to_digit(16), Some(15)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn to_digit(self, radix: u32) -> Option<u32> { C::to_digit(self, radix) } /// Returns an iterator that yields the hexadecimal Unicode escape of a /// character, as `char`s. /// /// All characters are escaped with Rust syntax of the form `\\u{NNNN}` /// where `NNNN` is the shortest hexadecimal representation of the code /// point. /// /// # Examples /// /// ``` /// for i in '❀'.escape_unicode() { /// println!("{}", i); /// } /// ``` /// /// This prints: /// /// ```text /// \ /// u /// { /// 2 /// 7 /// 6 /// 4 /// } /// ``` /// /// Collecting into a `String`: /// /// ``` /// let heart: String = '❀'.escape_unicode().collect(); /// /// assert_eq!(heart, r"\u{2764}"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn escape_unicode(self) -> EscapeUnicode { C::escape_unicode(self) } /// Returns an iterator that yields the 'default' ASCII and /// C++11-like literal escape of a character, as `char`s. /// /// The default is chosen with a bias toward producing literals that are /// legal in a variety of languages, including C++11 and similar C-family /// languages. The exact rules are: /// /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively. /// * Single-quote, double-quote and backslash chars are backslash- /// escaped. /// * Any other chars in the range [0x20,0x7e] are not escaped. /// * Any other chars are given hex Unicode escapes; see `escape_unicode`. /// /// # Examples /// /// ``` /// for i in '"'.escape_default() { /// println!("{}", i); /// } /// ``` /// /// This prints: /// /// ```text /// \ /// " /// ``` /// /// Collecting into a `String`: /// /// ``` /// let quote: String = '"'.escape_default().collect(); /// /// assert_eq!(quote, "\\\""); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn escape_default(self) -> EscapeDefault { C::escape_default(self) } /// Returns the number of bytes this character would need if encoded in /// UTF-8. /// /// # Examples /// /// ``` /// let n = 'ß'.len_utf8(); /// /// assert_eq!(n, 2); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn len_utf8(self) -> usize { C::len_utf8(self) } /// Returns the number of 16-bit code units this character would need if /// encoded in UTF-16. /// /// # Examples /// /// ``` /// let n = 'ß'.len_utf16(); /// /// assert_eq!(n, 1); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn len_utf16(self) -> usize { C::len_utf16(self) } /// Encodes this character as UTF-8 into the provided byte buffer, and then /// returns the number of bytes written. /// /// If the buffer is not large enough, nothing will be written into it and a /// `None` will be returned. A buffer of length four is large enough to /// encode any `char`. /// /// # Examples /// /// In both of these examples, 'ß' takes two bytes to encode. /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 2]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, Some(2)); /// ``` /// /// A buffer that's too small: /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 1]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, None); /// ``` #[unstable(feature = "unicode", reason = "pending decision about Iterator/Writer/Reader")] pub fn encode_utf8(self, dst: &mut [u8]) -> Option<usize> { C::encode_utf8(self, dst) } /// Encodes this character as UTF-16 into the provided `u16` buffer, and /// then returns the number of `u16`s written. /// /// If the buffer is not large enough, nothing will be written into it and a /// `None` will be returned. A buffer of length 2 is large enough to encode /// any `char`. /// /// # Examples /// /// In both of these examples, 'ß' takes one `u16` to encode. /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 1]; /// /// let result = 'ß'.encode_utf16(&mut b); /// /// assert_eq!(result, Some(1)); /// ``` /// /// A buffer that's too small: /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 0]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, None); /// ``` #[unstable(feature = "unicode", reason = "pending decision about Iterator/Writer/Reader")] pub fn encode_utf16(self, dst: &mut [u16]) -> Option<usize> { C::encode_utf16(self, dst) } /// Returns whether the specified character is considered a Unicode /// alphabetic code point. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_alphabetic(self) -> bool { match self { 'a'... 'z' | 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Alphabetic(c), _ => false } } /// Returns whether the specified character satisfies the 'XID_Start' /// Unicode property. /// /// 'XID_Start' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to ID_Start but modified for closure under NFKx. #[unstable(feature = "unicode", reason = "mainly needed for compiler internals")] #[inline] pub fn is_xid_start(self) -> bool { derived_pr
turns whether the specified `char` satisfies the 'XID_Continue' /// Unicode property. /// /// 'XID_Continue' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to 'ID_Continue' but modified for closure under NFKx. #[unstable(feature = "unicode", reason = "mainly needed for compiler internals")] #[inline] pub fn is_xid_continue(self) -> bool { derived_property::XID_Continue(self) } /// Indicates whether a character is in lowercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Lowercase`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_lowercase(self) -> bool { match self { 'a'... 'z' => true, c if c > '\x7f' => derived_property::Lowercase(c), _ => false } } /// Indicates whether a character is in uppercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Uppercase`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_uppercase(self) -> bool { match self { 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Uppercase(c), _ => false } } /// Indicates whether a character is whitespace. /// /// Whitespace is defined in terms of the Unicode Property `White_Space`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_whitespace(self) -> bool { match self { '' | '\x09'... '\x0d' => true, c if c > '\x7f' => property::White_Space(c), _ => false } } /// Indicates whether a character is alphanumeric. /// /// Alphanumericness is defined in terms of the Unicode General Categories /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_alphanumeric(self) -> bool { self.is_alphabetic() || self.is_numeric() } /// Indicates whether a character is a control code point. /// /// Control code points are defined in terms of the Unicode General /// Category `Cc`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_control(self) -> bool { general_category::Cc(self) } /// Indicates whether the character is numeric (Nd, Nl, or No). #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_numeric(self) -> bool { match self { '0'... '9' => true, c if c > '\x7f' => general_category::N(c), _ => false } } /// Converts a character to its lowercase equivalent. /// /// The case-folding performed is the common or simple mapping. See /// `to_uppercase()` for references and more information. /// /// # Return value /// /// Returns an iterator which yields the characters corresponding to the /// lowercase equivalent of the character. If no conversion is possible then /// the input character is returned. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn to_lowercase(self) -> ToLowercase { ToLowercase(Some(conversions::to_lower(self))) } /// Converts a character to its uppercase equivalent. /// /// The case-folding performed is the common or simple mapping: it maps /// one Unicode codepoint to its uppercase equivalent according to the /// Unicode database [1]. The additional [`SpecialCasing.txt`] is not yet /// considered here, but the iterator returned will soon support this form /// of case folding. /// /// A full reference can be found here [2]. /// /// # Return value /// /// Returns an iterator which yields the characters corresponding to the /// uppercase equivalent of the character. If no conversion is possible then /// the input character is returned. /// /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt /// /// [`SpecialCasing.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt /// /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992 #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn to_uppercase(self) -> ToUppercase { ToUppercase(Some(conversions::to_upper(self))) } /// Returns this character's displayed width in columns, or `None` if it is a /// control character other than `'\x00'`. /// /// `is_cjk` determines behavior for characters in the Ambiguous category: /// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1. /// In CJK contexts, `is_cjk` should be `true`, else it should be `false`. /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) /// recommends that these characters be treated as 1 column (i.e., /// `is_cjk` = `false`) if the context cannot be reliably determined. #[deprecated(reason = "use the crates.io `unicode-width` library instead", since = "1.0.0")] #[unstable(feature = "unicode", reason = "needs expert opinion. is_cjk flag stands out as ugly")] pub fn width(self, is_cjk: bool) -> Option<usize> { charwidth::width(self, is_cjk) } }
operty::XID_Start(self) } /// Re
identifier_body
char.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. //! Character manipulation (`char` type, Unicode Scalar Value) //! //! This module provides the `CharExt` trait, as well as its //! implementation for the primitive `char` type, in order to allow //! basic character manipulation. //! //! A `char` actually represents a //! *[Unicode Scalar //! Value](http://www.unicode.org/glossary/#unicode_scalar_value)*, as it can //! contain any Unicode code point except high-surrogate and low-surrogate code //! points. //! //! As such, only values in the ranges \[0x0,0xD7FF\] and \[0xE000,0x10FFFF\] //! (inclusive) are allowed. A `char` can always be safely cast to a `u32`; //! however the converse is not always true due to the above range limits //! and, as such, should be performed via the `from_u32` function. #![stable(feature = "rust1", since = "1.0.0")] #![doc(primitive = "char")] use core::char::CharExt as C; use core::option::Option::{self, Some}; use core::iter::Iterator; use tables::{derived_property, property, general_category, conversions, charwidth}; // stable reexports pub use core::char::{MAX, from_u32, from_digit, EscapeUnicode, EscapeDefault}; // unstable reexports #[allow(deprecated)] pub use normalize::{decompose_canonical, decompose_compatible, compose}; #[allow(deprecated)] pub use tables::normalization::canonical_combining_class; pub use tables::UNICODE_VERSION; /// An iterator over the lowercase mapping of a given character, returned from /// the [`to_lowercase` method](../primitive.char.html#method.to_lowercase) on /// characters. #[stable(feature = "rust1", since = "1.0.0")] pub struct ToLowercase(Option<char>); #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for ToLowercase { type Item = char; fn next(&mut self) -> Option<char> { self.0.take() } } /// An iterator over the uppercase mapping of a given character, returned from /// the [`to_uppercase` method](../primitive.char.html#method.to_uppercase) on /// characters. #[stable(feature = "rust1", since = "1.0.0")] pub struct ToUppercase(Option<char>); #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for ToUppercase { type Item = char; fn next(&mut self) -> Option<char> { self.0.take() } } #[stable(feature = "rust1", since = "1.0.0")] #[lang = "char"] impl char { /// Checks if a `char` parses as a numeric digit in the given radix. /// /// Compared to `is_numeric()`, this function only recognizes the characters /// `0-9`, `a-z` and `A-Z`. /// /// # Return value /// /// Returns `true` if `c` is a valid digit under `radix`, and `false` /// otherwise. /// /// # Panics /// /// Panics if given a radix > 36. /// /// # Examples /// /// ``` /// let c = '1'; /// /// assert!(c.is_digit(10)); /// /// assert!('f'.is_digit(16)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_digit(self, radix: u32) -> bool { C::is_digit(self, radix) } /// Converts a character to the corresponding digit. /// /// # Return value /// /// If `c` is between '0' and '9', the corresponding value between 0 and /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns /// none if the character does not refer to a digit in the given radix. /// /// # Panics /// /// Panics if given a radix outside the range [0..36]. /// /// # Examples /// /// ``` /// let c = '1'; /// /// assert_eq!(c.to_digit(10), Some(1)); /// /// assert_eq!('f'.to_digit(16), Some(15)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn to_digit(self, radix: u32) -> Option<u32> { C::to_digit(self, radix) } /// Returns an iterator that yields the hexadecimal Unicode escape of a /// character, as `char`s. /// /// All characters are escaped with Rust syntax of the form `\\u{NNNN}` /// where `NNNN` is the shortest hexadecimal representation of the code /// point. /// /// # Examples /// /// ``` /// for i in '❀'.escape_unicode() { /// println!("{}", i); /// } /// ``` /// /// This prints: /// /// ```text /// \ /// u /// { /// 2 /// 7 /// 6 /// 4 /// } /// ``` /// /// Collecting into a `String`: /// /// ``` /// let heart: String = '❀'.escape_unicode().collect(); /// /// assert_eq!(heart, r"\u{2764}"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn escape_unicode(self) -> EscapeUnicode { C::escape_unicode(self) } /// Returns an iterator that yields the 'default' ASCII and /// C++11-like literal escape of a character, as `char`s. /// /// The default is chosen with a bias toward producing literals that are /// legal in a variety of languages, including C++11 and similar C-family /// languages. The exact rules are: /// /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively. /// * Single-quote, double-quote and backslash chars are backslash- /// escaped. /// * Any other chars in the range [0x20,0x7e] are not escaped. /// * Any other chars are given hex Unicode escapes; see `escape_unicode`. /// /// # Examples /// /// ``` /// for i in '"'.escape_default() { /// println!("{}", i); /// } /// ``` /// /// This prints: /// /// ```text /// \ /// " /// ``` /// /// Collecting into a `String`: /// /// ``` /// let quote: String = '"'.escape_default().collect(); /// /// assert_eq!(quote, "\\\""); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn escape_default(self) -> EscapeDefault { C::escape_default(self) } /// Returns the number of bytes this character would need if encoded in /// UTF-8. /// /// # Examples /// /// ``` /// let n = 'ß'.len_utf8(); /// /// assert_eq!(n, 2); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn len_utf8(self) -> usize { C::len_utf8(self) } /// Returns the number of 16-bit code units this character would need if /// encoded in UTF-16. /// /// # Examples /// /// ``` /// let n = 'ß'.len_utf16(); /// /// assert_eq!(n, 1); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn len_utf16(self) -> usize { C::len_utf16(self) } /// Encodes this character as UTF-8 into the provided byte buffer, and then /// returns the number of bytes written. /// /// If the buffer is not large enough, nothing will be written into it and a /// `None` will be returned. A buffer of length four is large enough to /// encode any `char`. /// /// # Examples /// /// In both of these examples, 'ß' takes two bytes to encode. /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 2]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, Some(2)); /// ``` /// /// A buffer that's too small: /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 1]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, None); /// ``` #[unstable(feature = "unicode", reason = "pending decision about Iterator/Writer/Reader")] pub fn encode_utf8(self, dst: &mut [u8]) -> Option<usize> { C::encode_utf8(self, dst) } /// Encodes this character as UTF-16 into the provided `u16` buffer, and /// then returns the number of `u16`s written. /// /// If the buffer is not large enough, nothing will be written into it and a /// `None` will be returned. A buffer of length 2 is large enough to encode /// any `char`. /// /// # Examples /// /// In both of these examples, 'ß' takes one `u16` to encode. /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 1]; /// /// let result = 'ß'.encode_utf16(&mut b); /// /// assert_eq!(result, Some(1)); /// ``` /// /// A buffer that's too small: /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 0]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, None); /// ``` #[unstable(feature = "unicode", reason = "pending decision about Iterator/Writer/Reader")] pub fn encode_utf16(self, dst: &mut [u16]) -> Option<usize> { C::encode_utf16(self, dst) } /// Returns whether the specified character is considered a Unicode /// alphabetic code point. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_alphabetic(self) -> bool { match self { 'a'... 'z' | 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Alphabetic(c), _ => false } } /// Returns whether the specified character satisfies the 'XID_Start' /// Unicode property. /// /// 'XID_Start' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to ID_Start but modified for closure under NFKx. #[unstable(feature = "unicode", reason = "mainly needed for compiler internals")] #[inline] pub fn is_xid_start(self) -> bool { derived_property::XID_Start(self) } /// Returns whether the specified `char` satisfies the 'XID_Continue' /// Unicode property. /// /// 'XID_Continue' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to 'ID_Continue' but modified for closure under NFKx. #[unstable(feature = "unicode", reason = "mainly needed for compiler internals")] #[inline] pub fn is_xid_continue(self) -> bool { derived_property::XID_Continue(self) } /// Indicates whether a character is in lowercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Lowercase`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_lowercase(self) -> bool { match self { 'a'... 'z' => true, c if c > '\x7f' => derived_property::Lowercase(c), _ => false } } /// Indicates whether a character is in uppercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Uppercase`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_uppercase(self) -> bool { match self { 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Uppercase(c), _ => false } } /// Indicates whether a character is whitespace. /// /// Whitespace is defined in terms of the Unicode Property `White_Space`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_whitespace(self) -> bool { match self { '' | '\x09'... '\x0d' => true, c if c > '\x7f' => property::White_Space(c), _ => false } } /// Indicates whether a character is alphanumeric. /// /// Alphanumericness is defined in terms of the Unicode General Categories
#[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_alphanumeric(self) -> bool { self.is_alphabetic() || self.is_numeric() } /// Indicates whether a character is a control code point. /// /// Control code points are defined in terms of the Unicode General /// Category `Cc`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_control(self) -> bool { general_category::Cc(self) } /// Indicates whether the character is numeric (Nd, Nl, or No). #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_numeric(self) -> bool { match self { '0'... '9' => true, c if c > '\x7f' => general_category::N(c), _ => false } } /// Converts a character to its lowercase equivalent. /// /// The case-folding performed is the common or simple mapping. See /// `to_uppercase()` for references and more information. /// /// # Return value /// /// Returns an iterator which yields the characters corresponding to the /// lowercase equivalent of the character. If no conversion is possible then /// the input character is returned. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn to_lowercase(self) -> ToLowercase { ToLowercase(Some(conversions::to_lower(self))) } /// Converts a character to its uppercase equivalent. /// /// The case-folding performed is the common or simple mapping: it maps /// one Unicode codepoint to its uppercase equivalent according to the /// Unicode database [1]. The additional [`SpecialCasing.txt`] is not yet /// considered here, but the iterator returned will soon support this form /// of case folding. /// /// A full reference can be found here [2]. /// /// # Return value /// /// Returns an iterator which yields the characters corresponding to the /// uppercase equivalent of the character. If no conversion is possible then /// the input character is returned. /// /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt /// /// [`SpecialCasing.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt /// /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992 #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn to_uppercase(self) -> ToUppercase { ToUppercase(Some(conversions::to_upper(self))) } /// Returns this character's displayed width in columns, or `None` if it is a /// control character other than `'\x00'`. /// /// `is_cjk` determines behavior for characters in the Ambiguous category: /// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1. /// In CJK contexts, `is_cjk` should be `true`, else it should be `false`. /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) /// recommends that these characters be treated as 1 column (i.e., /// `is_cjk` = `false`) if the context cannot be reliably determined. #[deprecated(reason = "use the crates.io `unicode-width` library instead", since = "1.0.0")] #[unstable(feature = "unicode", reason = "needs expert opinion. is_cjk flag stands out as ugly")] pub fn width(self, is_cjk: bool) -> Option<usize> { charwidth::width(self, is_cjk) } }
/// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'.
random_line_split
char.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. //! Character manipulation (`char` type, Unicode Scalar Value) //! //! This module provides the `CharExt` trait, as well as its //! implementation for the primitive `char` type, in order to allow //! basic character manipulation. //! //! A `char` actually represents a //! *[Unicode Scalar //! Value](http://www.unicode.org/glossary/#unicode_scalar_value)*, as it can //! contain any Unicode code point except high-surrogate and low-surrogate code //! points. //! //! As such, only values in the ranges \[0x0,0xD7FF\] and \[0xE000,0x10FFFF\] //! (inclusive) are allowed. A `char` can always be safely cast to a `u32`; //! however the converse is not always true due to the above range limits //! and, as such, should be performed via the `from_u32` function. #![stable(feature = "rust1", since = "1.0.0")] #![doc(primitive = "char")] use core::char::CharExt as C; use core::option::Option::{self, Some}; use core::iter::Iterator; use tables::{derived_property, property, general_category, conversions, charwidth}; // stable reexports pub use core::char::{MAX, from_u32, from_digit, EscapeUnicode, EscapeDefault}; // unstable reexports #[allow(deprecated)] pub use normalize::{decompose_canonical, decompose_compatible, compose}; #[allow(deprecated)] pub use tables::normalization::canonical_combining_class; pub use tables::UNICODE_VERSION; /// An iterator over the lowercase mapping of a given character, returned from /// the [`to_lowercase` method](../primitive.char.html#method.to_lowercase) on /// characters. #[stable(feature = "rust1", since = "1.0.0")] pub struct ToLowercase(Option<char>); #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for ToLowercase { type Item = char; fn next(&mut self) -> Option<char> { self.0.take() } } /// An iterator over the uppercase mapping of a given character, returned from /// the [`to_uppercase` method](../primitive.char.html#method.to_uppercase) on /// characters. #[stable(feature = "rust1", since = "1.0.0")] pub struct ToUppercase(Option<char>); #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for ToUppercase { type Item = char; fn next(&mut self) -> Option<char> { self.0.take() } } #[stable(feature = "rust1", since = "1.0.0")] #[lang = "char"] impl char { /// Checks if a `char` parses as a numeric digit in the given radix. /// /// Compared to `is_numeric()`, this function only recognizes the characters /// `0-9`, `a-z` and `A-Z`. /// /// # Return value /// /// Returns `true` if `c` is a valid digit under `radix`, and `false` /// otherwise. /// /// # Panics /// /// Panics if given a radix > 36. /// /// # Examples /// /// ``` /// let c = '1'; /// /// assert!(c.is_digit(10)); /// /// assert!('f'.is_digit(16)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_digit(self, radix: u32) -> bool { C::is_digit(self, radix) } /// Converts a character to the corresponding digit. /// /// # Return value /// /// If `c` is between '0' and '9', the corresponding value between 0 and /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns /// none if the character does not refer to a digit in the given radix. /// /// # Panics /// /// Panics if given a radix outside the range [0..36]. /// /// # Examples /// /// ``` /// let c = '1'; /// /// assert_eq!(c.to_digit(10), Some(1)); /// /// assert_eq!('f'.to_digit(16), Some(15)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn to_digit(self, radix: u32) -> Option<u32> { C::to_digit(self, radix) } /// Returns an iterator that yields the hexadecimal Unicode escape of a /// character, as `char`s. /// /// All characters are escaped with Rust syntax of the form `\\u{NNNN}` /// where `NNNN` is the shortest hexadecimal representation of the code /// point. /// /// # Examples /// /// ``` /// for i in '❀'.escape_unicode() { /// println!("{}", i); /// } /// ``` /// /// This prints: /// /// ```text /// \ /// u /// { /// 2 /// 7 /// 6 /// 4 /// } /// ``` /// /// Collecting into a `String`: /// /// ``` /// let heart: String = '❀'.escape_unicode().collect(); /// /// assert_eq!(heart, r"\u{2764}"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn esca
f) -> EscapeUnicode { C::escape_unicode(self) } /// Returns an iterator that yields the 'default' ASCII and /// C++11-like literal escape of a character, as `char`s. /// /// The default is chosen with a bias toward producing literals that are /// legal in a variety of languages, including C++11 and similar C-family /// languages. The exact rules are: /// /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively. /// * Single-quote, double-quote and backslash chars are backslash- /// escaped. /// * Any other chars in the range [0x20,0x7e] are not escaped. /// * Any other chars are given hex Unicode escapes; see `escape_unicode`. /// /// # Examples /// /// ``` /// for i in '"'.escape_default() { /// println!("{}", i); /// } /// ``` /// /// This prints: /// /// ```text /// \ /// " /// ``` /// /// Collecting into a `String`: /// /// ``` /// let quote: String = '"'.escape_default().collect(); /// /// assert_eq!(quote, "\\\""); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn escape_default(self) -> EscapeDefault { C::escape_default(self) } /// Returns the number of bytes this character would need if encoded in /// UTF-8. /// /// # Examples /// /// ``` /// let n = 'ß'.len_utf8(); /// /// assert_eq!(n, 2); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn len_utf8(self) -> usize { C::len_utf8(self) } /// Returns the number of 16-bit code units this character would need if /// encoded in UTF-16. /// /// # Examples /// /// ``` /// let n = 'ß'.len_utf16(); /// /// assert_eq!(n, 1); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn len_utf16(self) -> usize { C::len_utf16(self) } /// Encodes this character as UTF-8 into the provided byte buffer, and then /// returns the number of bytes written. /// /// If the buffer is not large enough, nothing will be written into it and a /// `None` will be returned. A buffer of length four is large enough to /// encode any `char`. /// /// # Examples /// /// In both of these examples, 'ß' takes two bytes to encode. /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 2]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, Some(2)); /// ``` /// /// A buffer that's too small: /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 1]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, None); /// ``` #[unstable(feature = "unicode", reason = "pending decision about Iterator/Writer/Reader")] pub fn encode_utf8(self, dst: &mut [u8]) -> Option<usize> { C::encode_utf8(self, dst) } /// Encodes this character as UTF-16 into the provided `u16` buffer, and /// then returns the number of `u16`s written. /// /// If the buffer is not large enough, nothing will be written into it and a /// `None` will be returned. A buffer of length 2 is large enough to encode /// any `char`. /// /// # Examples /// /// In both of these examples, 'ß' takes one `u16` to encode. /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 1]; /// /// let result = 'ß'.encode_utf16(&mut b); /// /// assert_eq!(result, Some(1)); /// ``` /// /// A buffer that's too small: /// /// ``` /// # #![feature(unicode)] /// let mut b = [0; 0]; /// /// let result = 'ß'.encode_utf8(&mut b); /// /// assert_eq!(result, None); /// ``` #[unstable(feature = "unicode", reason = "pending decision about Iterator/Writer/Reader")] pub fn encode_utf16(self, dst: &mut [u16]) -> Option<usize> { C::encode_utf16(self, dst) } /// Returns whether the specified character is considered a Unicode /// alphabetic code point. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_alphabetic(self) -> bool { match self { 'a'... 'z' | 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Alphabetic(c), _ => false } } /// Returns whether the specified character satisfies the 'XID_Start' /// Unicode property. /// /// 'XID_Start' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to ID_Start but modified for closure under NFKx. #[unstable(feature = "unicode", reason = "mainly needed for compiler internals")] #[inline] pub fn is_xid_start(self) -> bool { derived_property::XID_Start(self) } /// Returns whether the specified `char` satisfies the 'XID_Continue' /// Unicode property. /// /// 'XID_Continue' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to 'ID_Continue' but modified for closure under NFKx. #[unstable(feature = "unicode", reason = "mainly needed for compiler internals")] #[inline] pub fn is_xid_continue(self) -> bool { derived_property::XID_Continue(self) } /// Indicates whether a character is in lowercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Lowercase`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_lowercase(self) -> bool { match self { 'a'... 'z' => true, c if c > '\x7f' => derived_property::Lowercase(c), _ => false } } /// Indicates whether a character is in uppercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Uppercase`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_uppercase(self) -> bool { match self { 'A'... 'Z' => true, c if c > '\x7f' => derived_property::Uppercase(c), _ => false } } /// Indicates whether a character is whitespace. /// /// Whitespace is defined in terms of the Unicode Property `White_Space`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_whitespace(self) -> bool { match self { '' | '\x09'... '\x0d' => true, c if c > '\x7f' => property::White_Space(c), _ => false } } /// Indicates whether a character is alphanumeric. /// /// Alphanumericness is defined in terms of the Unicode General Categories /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_alphanumeric(self) -> bool { self.is_alphabetic() || self.is_numeric() } /// Indicates whether a character is a control code point. /// /// Control code points are defined in terms of the Unicode General /// Category `Cc`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_control(self) -> bool { general_category::Cc(self) } /// Indicates whether the character is numeric (Nd, Nl, or No). #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_numeric(self) -> bool { match self { '0'... '9' => true, c if c > '\x7f' => general_category::N(c), _ => false } } /// Converts a character to its lowercase equivalent. /// /// The case-folding performed is the common or simple mapping. See /// `to_uppercase()` for references and more information. /// /// # Return value /// /// Returns an iterator which yields the characters corresponding to the /// lowercase equivalent of the character. If no conversion is possible then /// the input character is returned. #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn to_lowercase(self) -> ToLowercase { ToLowercase(Some(conversions::to_lower(self))) } /// Converts a character to its uppercase equivalent. /// /// The case-folding performed is the common or simple mapping: it maps /// one Unicode codepoint to its uppercase equivalent according to the /// Unicode database [1]. The additional [`SpecialCasing.txt`] is not yet /// considered here, but the iterator returned will soon support this form /// of case folding. /// /// A full reference can be found here [2]. /// /// # Return value /// /// Returns an iterator which yields the characters corresponding to the /// uppercase equivalent of the character. If no conversion is possible then /// the input character is returned. /// /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt /// /// [`SpecialCasing.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt /// /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992 #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn to_uppercase(self) -> ToUppercase { ToUppercase(Some(conversions::to_upper(self))) } /// Returns this character's displayed width in columns, or `None` if it is a /// control character other than `'\x00'`. /// /// `is_cjk` determines behavior for characters in the Ambiguous category: /// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1. /// In CJK contexts, `is_cjk` should be `true`, else it should be `false`. /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) /// recommends that these characters be treated as 1 column (i.e., /// `is_cjk` = `false`) if the context cannot be reliably determined. #[deprecated(reason = "use the crates.io `unicode-width` library instead", since = "1.0.0")] #[unstable(feature = "unicode", reason = "needs expert opinion. is_cjk flag stands out as ugly")] pub fn width(self, is_cjk: bool) -> Option<usize> { charwidth::width(self, is_cjk) } }
pe_unicode(sel
identifier_name
errors.rs
/* Copyright 2017 Takashi Ogura 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,
See the License for the specific language governing permissions and limitations under the License. */ use std::io; use thiserror::Error; #[derive(Debug, Error)] pub enum Error { #[error("Error: {:?}", error)] Other { error: String }, #[error("IOError: {:?}", source)] IoError { #[from] source: io::Error, }, } pub type Result<T> = ::std::result::Result<T, Error>; impl<'a> From<&'a str> for Error { fn from(error: &'a str) -> Error { Error::Other { error: error.to_owned(), } } } impl From<String> for Error { fn from(error: String) -> Error { Error::Other { error } } }
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
random_line_split
errors.rs
/* Copyright 2017 Takashi Ogura 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::io; use thiserror::Error; #[derive(Debug, Error)] pub enum Error { #[error("Error: {:?}", error)] Other { error: String }, #[error("IOError: {:?}", source)] IoError { #[from] source: io::Error, }, } pub type Result<T> = ::std::result::Result<T, Error>; impl<'a> From<&'a str> for Error { fn from(error: &'a str) -> Error { Error::Other { error: error.to_owned(), } } } impl From<String> for Error { fn
(error: String) -> Error { Error::Other { error } } }
from
identifier_name
037.rs
use std::str::FromStr; fn read_line() -> String { let mut input = String::new(); std::io::stdin().read_line(&mut input).expect("Could not read stdin!"); input } fn read_one<F>() -> F where F: FromStr { read_line().trim().parse().ok().unwrap() } fn main() {
let mut prime = vec![true; limit]; prime[0] = false; prime[1] = false; // Sieve of Eratosthenes to find primes for p in 2.. limit { if prime[p] { let mut multiple = 2 * p; while multiple < limit { prime[multiple] = false; multiple += p; } } } let mut right_truncatable = prime.clone(); let mut left_truncatable = prime.clone(); // For the algorithm we'll assume one digit primes to be truncatable for p in 10.. limit { right_truncatable[p] &= right_truncatable[p / 10]; left_truncatable[p] &= left_truncatable[p % 10usize.pow((p as f64).log10() as u32)]; } // Now we'll simply skip the one digit numbers let sum = (10.. limit).filter(|&p| right_truncatable[p] && left_truncatable[p]).fold(0, |sum, p| sum + p); println!("{}", sum); }
let limit = read_one::<usize>();
random_line_split
037.rs
use std::str::FromStr; fn read_line() -> String { let mut input = String::new(); std::io::stdin().read_line(&mut input).expect("Could not read stdin!"); input } fn read_one<F>() -> F where F: FromStr { read_line().trim().parse().ok().unwrap() } fn main() { let limit = read_one::<usize>(); let mut prime = vec![true; limit]; prime[0] = false; prime[1] = false; // Sieve of Eratosthenes to find primes for p in 2.. limit { if prime[p]
} let mut right_truncatable = prime.clone(); let mut left_truncatable = prime.clone(); // For the algorithm we'll assume one digit primes to be truncatable for p in 10.. limit { right_truncatable[p] &= right_truncatable[p / 10]; left_truncatable[p] &= left_truncatable[p % 10usize.pow((p as f64).log10() as u32)]; } // Now we'll simply skip the one digit numbers let sum = (10.. limit).filter(|&p| right_truncatable[p] && left_truncatable[p]).fold(0, |sum, p| sum + p); println!("{}", sum); }
{ let mut multiple = 2 * p; while multiple < limit { prime[multiple] = false; multiple += p; } }
conditional_block
037.rs
use std::str::FromStr; fn read_line() -> String { let mut input = String::new(); std::io::stdin().read_line(&mut input).expect("Could not read stdin!"); input } fn read_one<F>() -> F where F: FromStr { read_line().trim().parse().ok().unwrap() } fn
() { let limit = read_one::<usize>(); let mut prime = vec![true; limit]; prime[0] = false; prime[1] = false; // Sieve of Eratosthenes to find primes for p in 2.. limit { if prime[p] { let mut multiple = 2 * p; while multiple < limit { prime[multiple] = false; multiple += p; } } } let mut right_truncatable = prime.clone(); let mut left_truncatable = prime.clone(); // For the algorithm we'll assume one digit primes to be truncatable for p in 10.. limit { right_truncatable[p] &= right_truncatable[p / 10]; left_truncatable[p] &= left_truncatable[p % 10usize.pow((p as f64).log10() as u32)]; } // Now we'll simply skip the one digit numbers let sum = (10.. limit).filter(|&p| right_truncatable[p] && left_truncatable[p]).fold(0, |sum, p| sum + p); println!("{}", sum); }
main
identifier_name
037.rs
use std::str::FromStr; fn read_line() -> String
fn read_one<F>() -> F where F: FromStr { read_line().trim().parse().ok().unwrap() } fn main() { let limit = read_one::<usize>(); let mut prime = vec![true; limit]; prime[0] = false; prime[1] = false; // Sieve of Eratosthenes to find primes for p in 2.. limit { if prime[p] { let mut multiple = 2 * p; while multiple < limit { prime[multiple] = false; multiple += p; } } } let mut right_truncatable = prime.clone(); let mut left_truncatable = prime.clone(); // For the algorithm we'll assume one digit primes to be truncatable for p in 10.. limit { right_truncatable[p] &= right_truncatable[p / 10]; left_truncatable[p] &= left_truncatable[p % 10usize.pow((p as f64).log10() as u32)]; } // Now we'll simply skip the one digit numbers let sum = (10.. limit).filter(|&p| right_truncatable[p] && left_truncatable[p]).fold(0, |sum, p| sum + p); println!("{}", sum); }
{ let mut input = String::new(); std::io::stdin().read_line(&mut input).expect("Could not read stdin!"); input }
identifier_body
locate_project.rs
use cargo::core::MultiShell; use cargo::util::{CliResult, CliError, human, ChainError}; use cargo::util::important_paths::{find_root_manifest_for_cwd}; #[derive(RustcDecodable)] struct LocateProjectFlags { flag_manifest_path: Option<String>, } pub const USAGE: &'static str = " Usage: cargo locate-project [options] Options: --manifest-path PATH Path to the manifest to build benchmarks for -h, --help Print this message "; #[derive(RustcEncodable)] struct
{ root: String } pub fn execute(flags: LocateProjectFlags, _: &mut MultiShell) -> CliResult<Option<ProjectLocation>> { let root = try!(find_root_manifest_for_cwd(flags.flag_manifest_path)); let string = try!(root.as_str() .chain_error(|| human("Your project path contains \ characters not representable in \ Unicode")) .map_err(|e| CliError::from_boxed(e, 1))); Ok(Some(ProjectLocation { root: string.to_string() })) }
ProjectLocation
identifier_name
locate_project.rs
use cargo::core::MultiShell; use cargo::util::{CliResult, CliError, human, ChainError}; use cargo::util::important_paths::{find_root_manifest_for_cwd}; #[derive(RustcDecodable)] struct LocateProjectFlags { flag_manifest_path: Option<String>, } pub const USAGE: &'static str = " Usage: cargo locate-project [options] Options: --manifest-path PATH Path to the manifest to build benchmarks for -h, --help Print this message "; #[derive(RustcEncodable)] struct ProjectLocation { root: String } pub fn execute(flags: LocateProjectFlags, _: &mut MultiShell) -> CliResult<Option<ProjectLocation>> { let root = try!(find_root_manifest_for_cwd(flags.flag_manifest_path)); let string = try!(root.as_str() .chain_error(|| human("Your project path contains \ characters not representable in \ Unicode")) .map_err(|e| CliError::from_boxed(e, 1)));
Ok(Some(ProjectLocation { root: string.to_string() })) }
random_line_split
render_context.rs
use std::collections::{HashMap}; use std::path::{Path}; use std::sync::{Arc}; use crossbeam::sync::{MsQueue}; use glium::backend::{Facade}; use debug::{gnomon, indicator}; use inverse_kinematics::{Chain}; use model::{Model}; use unlit_model::{UnlitModel}; use render::render_frame::{RenderFrame}; pub const DEPTH_DIMENSION: u32 = 2048; #[derive(Eq, PartialEq, Hash, Copy, Clone)] pub enum ModelId { Player, Scene, IKModel, // TODO: we are going to need more of these / a dynamic way to generate ids and load at a later time Tree, // DEBUG Gnomon, Indicator, } pub struct RenderContext { pub q: Arc<MsQueue<RenderFrame>>, // TODO: make private and provide minimal decent api window_size: (u32, u32), // TODO: maybe this should be a per RenderFrame parameter pub models: HashMap<ModelId, Arc<Model>>, // DEBUG pub unlit_models: HashMap<ModelId, Arc<UnlitModel>>, } impl RenderContext { pub fn new<F: Facade>(facade: &F, q: Arc<MsQueue<RenderFrame>>, window_size: (u32, u32), ik_chains: &[Chain]) -> RenderContext { let model_map = load_initial_models(facade, ik_chains); // DEBUG let mut unlit_models = HashMap::new(); unlit_models.insert(ModelId::Gnomon, Arc::new(gnomon::model(facade))); unlit_models.insert(ModelId::Indicator, Arc::new(indicator::model(facade))); RenderContext { q: q, window_size: window_size, models: model_map, // DEBUG unlit_models: unlit_models, } } pub fn aspect_ratio(&self) -> f32
} // TODO: don't pass in chains but make something like IntoModel // fn load_initial_models<F: Facade>(facade: &F, ik_chains: &[Chain]) -> HashMap<ModelId, Arc<Model>> { let mut map = HashMap::new(); const MODEL_PATH_STRINGS: [(ModelId, &'static str); 3] = [ (ModelId::Player, "./data/player.obj"), (ModelId::Scene, "./data/level.obj"), (ModelId::Tree, "./data/tree.obj") ]; for &(model_id, path) in &MODEL_PATH_STRINGS { let model = Arc::new(Model::new(facade, &Path::new(path))); map.insert(model_id, model); } for chain in ik_chains { map.insert(ModelId::IKModel, Arc::new(chain.model(facade))); } map } unsafe impl Send for RenderContext {} unsafe impl Sync for RenderContext {}
{ (self.window_size.0 as f32) / (self.window_size.1 as f32) }
identifier_body
render_context.rs
use std::collections::{HashMap}; use std::path::{Path}; use std::sync::{Arc}; use crossbeam::sync::{MsQueue}; use glium::backend::{Facade}; use debug::{gnomon, indicator}; use inverse_kinematics::{Chain}; use model::{Model}; use unlit_model::{UnlitModel}; use render::render_frame::{RenderFrame}; pub const DEPTH_DIMENSION: u32 = 2048; #[derive(Eq, PartialEq, Hash, Copy, Clone)] pub enum ModelId { Player, Scene, IKModel, // TODO: we are going to need more of these / a dynamic way to generate ids and load at a later time Tree, // DEBUG Gnomon, Indicator, } pub struct RenderContext { pub q: Arc<MsQueue<RenderFrame>>, // TODO: make private and provide minimal decent api window_size: (u32, u32), // TODO: maybe this should be a per RenderFrame parameter pub models: HashMap<ModelId, Arc<Model>>, // DEBUG pub unlit_models: HashMap<ModelId, Arc<UnlitModel>>, } impl RenderContext { pub fn
<F: Facade>(facade: &F, q: Arc<MsQueue<RenderFrame>>, window_size: (u32, u32), ik_chains: &[Chain]) -> RenderContext { let model_map = load_initial_models(facade, ik_chains); // DEBUG let mut unlit_models = HashMap::new(); unlit_models.insert(ModelId::Gnomon, Arc::new(gnomon::model(facade))); unlit_models.insert(ModelId::Indicator, Arc::new(indicator::model(facade))); RenderContext { q: q, window_size: window_size, models: model_map, // DEBUG unlit_models: unlit_models, } } pub fn aspect_ratio(&self) -> f32 { (self.window_size.0 as f32) / (self.window_size.1 as f32) } } // TODO: don't pass in chains but make something like IntoModel // fn load_initial_models<F: Facade>(facade: &F, ik_chains: &[Chain]) -> HashMap<ModelId, Arc<Model>> { let mut map = HashMap::new(); const MODEL_PATH_STRINGS: [(ModelId, &'static str); 3] = [ (ModelId::Player, "./data/player.obj"), (ModelId::Scene, "./data/level.obj"), (ModelId::Tree, "./data/tree.obj") ]; for &(model_id, path) in &MODEL_PATH_STRINGS { let model = Arc::new(Model::new(facade, &Path::new(path))); map.insert(model_id, model); } for chain in ik_chains { map.insert(ModelId::IKModel, Arc::new(chain.model(facade))); } map } unsafe impl Send for RenderContext {} unsafe impl Sync for RenderContext {}
new
identifier_name
render_context.rs
use std::collections::{HashMap}; use std::path::{Path}; use std::sync::{Arc}; use crossbeam::sync::{MsQueue}; use glium::backend::{Facade}; use debug::{gnomon, indicator}; use inverse_kinematics::{Chain}; use model::{Model}; use unlit_model::{UnlitModel}; use render::render_frame::{RenderFrame}; pub const DEPTH_DIMENSION: u32 = 2048; #[derive(Eq, PartialEq, Hash, Copy, Clone)] pub enum ModelId { Player, Scene, IKModel, // TODO: we are going to need more of these / a dynamic way to generate ids and load at a later time Tree, // DEBUG Gnomon, Indicator, } pub struct RenderContext { pub q: Arc<MsQueue<RenderFrame>>, // TODO: make private and provide minimal decent api window_size: (u32, u32), // TODO: maybe this should be a per RenderFrame parameter pub models: HashMap<ModelId, Arc<Model>>, // DEBUG pub unlit_models: HashMap<ModelId, Arc<UnlitModel>>, } impl RenderContext { pub fn new<F: Facade>(facade: &F, q: Arc<MsQueue<RenderFrame>>, window_size: (u32, u32), ik_chains: &[Chain]) -> RenderContext { let model_map = load_initial_models(facade, ik_chains); // DEBUG let mut unlit_models = HashMap::new(); unlit_models.insert(ModelId::Gnomon, Arc::new(gnomon::model(facade)));
unlit_models.insert(ModelId::Indicator, Arc::new(indicator::model(facade))); RenderContext { q: q, window_size: window_size, models: model_map, // DEBUG unlit_models: unlit_models, } } pub fn aspect_ratio(&self) -> f32 { (self.window_size.0 as f32) / (self.window_size.1 as f32) } } // TODO: don't pass in chains but make something like IntoModel // fn load_initial_models<F: Facade>(facade: &F, ik_chains: &[Chain]) -> HashMap<ModelId, Arc<Model>> { let mut map = HashMap::new(); const MODEL_PATH_STRINGS: [(ModelId, &'static str); 3] = [ (ModelId::Player, "./data/player.obj"), (ModelId::Scene, "./data/level.obj"), (ModelId::Tree, "./data/tree.obj") ]; for &(model_id, path) in &MODEL_PATH_STRINGS { let model = Arc::new(Model::new(facade, &Path::new(path))); map.insert(model_id, model); } for chain in ik_chains { map.insert(ModelId::IKModel, Arc::new(chain.model(facade))); } map } unsafe impl Send for RenderContext {} unsafe impl Sync for RenderContext {}
random_line_split
build.rs
// // Copyright 2022 The Project Oak Authors // // 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 oak_utils::{generate_grpc_code, CodegenOptions}; fn main() -> Result<(), Box<dyn std::error::Error>>
{ generate_grpc_code( "../", &["oak_functions/proto/streaming_server.proto"], CodegenOptions { build_client: true, build_server: true, ..Default::default() }, )?; Ok(()) }
identifier_body
build.rs
// // Copyright 2022 The Project Oak Authors // // 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 oak_utils::{generate_grpc_code, CodegenOptions}; fn main() -> Result<(), Box<dyn std::error::Error>> { generate_grpc_code( "../",
..Default::default() }, )?; Ok(()) }
&["oak_functions/proto/streaming_server.proto"], CodegenOptions { build_client: true, build_server: true,
random_line_split
build.rs
// // Copyright 2022 The Project Oak Authors // // 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 oak_utils::{generate_grpc_code, CodegenOptions}; fn
() -> Result<(), Box<dyn std::error::Error>> { generate_grpc_code( "../", &["oak_functions/proto/streaming_server.proto"], CodegenOptions { build_client: true, build_server: true, ..Default::default() }, )?; Ok(()) }
main
identifier_name
uds_split.rs
#![warn(rust_2018_idioms)] #![cfg(feature = "full")] #![cfg(unix)] use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use tokio::net::UnixStream; /// Checks that `UnixStream` can be split into a read half and a write half using /// `UnixStream::split` and `UnixStream::split_mut`. /// /// Verifies that the implementation of `AsyncWrite::poll_shutdown` shutdowns the stream for /// writing by reading to the end of stream on the other side of the connection. #[tokio::test] async fn split() -> std::io::Result<()> { let (mut a, mut b) = UnixStream::pair()?; let (mut a_read, mut a_write) = a.split(); let (mut b_read, mut b_write) = b.split(); let (a_response, b_response) = futures::future::try_join( send_recv_all(&mut a_read, &mut a_write, b"A"), send_recv_all(&mut b_read, &mut b_write, b"B"), ) .await?; assert_eq!(a_response, b"B"); assert_eq!(b_response, b"A"); Ok(()) } async fn
( read: &mut (dyn AsyncRead + Unpin), write: &mut (dyn AsyncWrite + Unpin), input: &[u8], ) -> std::io::Result<Vec<u8>> { write.write_all(input).await?; write.shutdown().await?; let mut output = Vec::new(); read.read_to_end(&mut output).await?; Ok(output) }
send_recv_all
identifier_name
uds_split.rs
#![warn(rust_2018_idioms)] #![cfg(feature = "full")] #![cfg(unix)] use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use tokio::net::UnixStream; /// Checks that `UnixStream` can be split into a read half and a write half using /// `UnixStream::split` and `UnixStream::split_mut`. /// /// Verifies that the implementation of `AsyncWrite::poll_shutdown` shutdowns the stream for /// writing by reading to the end of stream on the other side of the connection. #[tokio::test] async fn split() -> std::io::Result<()> { let (mut a, mut b) = UnixStream::pair()?; let (mut a_read, mut a_write) = a.split();
send_recv_all(&mut a_read, &mut a_write, b"A"), send_recv_all(&mut b_read, &mut b_write, b"B"), ) .await?; assert_eq!(a_response, b"B"); assert_eq!(b_response, b"A"); Ok(()) } async fn send_recv_all( read: &mut (dyn AsyncRead + Unpin), write: &mut (dyn AsyncWrite + Unpin), input: &[u8], ) -> std::io::Result<Vec<u8>> { write.write_all(input).await?; write.shutdown().await?; let mut output = Vec::new(); read.read_to_end(&mut output).await?; Ok(output) }
let (mut b_read, mut b_write) = b.split(); let (a_response, b_response) = futures::future::try_join(
random_line_split
uds_split.rs
#![warn(rust_2018_idioms)] #![cfg(feature = "full")] #![cfg(unix)] use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use tokio::net::UnixStream; /// Checks that `UnixStream` can be split into a read half and a write half using /// `UnixStream::split` and `UnixStream::split_mut`. /// /// Verifies that the implementation of `AsyncWrite::poll_shutdown` shutdowns the stream for /// writing by reading to the end of stream on the other side of the connection. #[tokio::test] async fn split() -> std::io::Result<()>
async fn send_recv_all( read: &mut (dyn AsyncRead + Unpin), write: &mut (dyn AsyncWrite + Unpin), input: &[u8], ) -> std::io::Result<Vec<u8>> { write.write_all(input).await?; write.shutdown().await?; let mut output = Vec::new(); read.read_to_end(&mut output).await?; Ok(output) }
{ let (mut a, mut b) = UnixStream::pair()?; let (mut a_read, mut a_write) = a.split(); let (mut b_read, mut b_write) = b.split(); let (a_response, b_response) = futures::future::try_join( send_recv_all(&mut a_read, &mut a_write, b"A"), send_recv_all(&mut b_read, &mut b_write, b"B"), ) .await?; assert_eq!(a_response, b"B"); assert_eq!(b_response, b"A"); Ok(()) }
identifier_body
ofrefsofrects.rs
use rect::Rect; pub fn run() { println!("********* Option<&Rect> examples *********"); demo_basic_matching(); demo_as_ref(); demo_as_mut(); demo_unwrap(); demo_take(); demo_logical_or_and_combinators(); demo_chaining(); demo_map(); // demo_collection_of_options(); } fn demo_basic_matching() { println!(">>> demo_basic_matching"); // We need to keep r around for the lifetime checker. let r = Rect::demo(); let a = Some(&r); assert!(a.is_some()); assert!(!a.is_none()); // Match is the most basic way of getting at an option. // Note that x is now &Rect automatically, so we do not need'ref x'. match a { Some(x) => println!("MATCH: x (from a) = {}. x is of type &Rect.", x), None => panic!("a should not be None") } // If let is equivalent to a match where we do nothing in the None. // Because x is automatically a borrow, both of these compile fine. if let Some(x) = a { println!("IF LET: x (from a) = {}. x is of type &Rect.", x); } if let Some(x) = a { println!("IF LET: x (from a) = {}. x is of type &Rect.", x); } } fn demo_as_ref() { println!(">>> demo_as_ref"); let r = Rect::demo(); let a = Some(&r); // b is of type Option<&&Rect>. // Now when we pattern match, we get an &&Rect by default. let b = a.as_ref(); if let Some(x) = b { println!("IF LET: x (from b) = {}. x is of type &&Rect.", x); } // Trying to use & in this case works, we get rid of one of the references. let b = a.as_ref(); if let Some(&x) = b { } } fn demo_as_mut() { println!(">>> demo_as_mut (not sure what is going on here, to be honest)"); let r = Rect::demo(); let mut a = Some(&r); { // Again, but using as_mut(); // c is of type Option<&mut &Rect>. // Now when we pattern match, we get an &mut &Rect by default. let c = a.as_mut(); if let Some(x) = c { println!("IF LET: x (from c) = {}. x is of type &mut i32 and can be changed.", x); // x.w = 200; // Cannot assign to immutable field x.w } } { // We can now pattern match using &mut x. let c = a.as_mut(); if let Some(&mut x) = c { } } } fn demo_unwrap() { println!(">>> demo_unwrap"); let r = Rect::demo(); let r2 = Rect::demo2(); let a = Some(&r); let x = a.unwrap(); println!("x = {}", x); // These are all no-ops because is a Some. let a = Some(&r); let x = a.unwrap_or(&r2); assert!(x.title == "first demo"); // Won't compile, T is &Rect, not Rect. // let a = Some(&r); // let x = a.unwrap_or_default(); // assert!(x == "hello".to_string()); let a = Some(&r); let x = a.unwrap_or_else(|| &r2); assert!(x.title == "first demo"); // Let's make a None. let a : Option<&Rect> = None; let x = a.unwrap_or(&r2); assert!(x.title == "second demo"); // let a : Option<&Rect> = None; // let x = a.unwrap_or_default(); // Type needs to implement the Default trait, &Rect doesn't. // assert!(x == String::new()); let a : Option<&Rect> = None; let x = a.unwrap_or_else(|| &r2); // Result of a closure. assert!(x.title == "second demo"); } fn demo_take() { println!(">>> demo_take"); // Take can be used to move a value from one option to another. let r = Rect::demo(); let mut a = Some(&r); let b = a.take(); assert!(a.is_none()); match b { Some(x) => assert!(x.title == "first demo"), None => panic!("a should not be None") } } fn
() { // This is quite simple, but there is a wrinkle. let r = Rect::demo(); let a = Some(&r); let b : Option<&Rect> = None; // For 'or', both options must be of the same type. let c = a.or(b).unwrap(); assert_eq!(c.title, "first demo"); // Reset. let a = Some(&r); let b : Option<&Rect> = None; let d = a.and(b); assert!(d.is_none()); // But for 'and', they can be different: you get back the second. let a = Some(&r); let b = Some("b".to_string()); let d = a.and(b); assert_eq!(d, Some("b".to_string())); } fn demo_chaining() { println!(">>> demo_chaining"); // The closure (or function) passed to and_then() only gets called if 'a' is Some. // Since it isn't, we never call the closure. x is of type i32 in this example. // The closure must return an Option<T>. let a : Option<&Rect> = None; let result = a.and_then(|x| Some(x)); assert!(result.is_none()); // This can be chained. None of these closures will get called. let a : Option<&Rect> = None; let result = a.and_then(|x| Some(x)).and_then(|x| Some(x)).and_then(|x| Some(x)); assert!(result.is_none()); // This will flow the whole way down. Notice that we have to specify mut x for the closure // parameter in order to be able to call app(), and note also that we create the Some // with a '&mut r'!! It won't compile without it. let mut r = Rect::demo(); let a = Some(&mut r); let result = a.and_then(|mut x| { x.app(" world"); Some(x) }) .and_then(|mut x| { x.app(" world"); Some(x) }) .and_then(|mut x| { x.app(" world"); Some(x) }); assert_eq!(result.unwrap().title, "first demo world world world"); // We can terminate in the middle, but the chain remains safe from panics. // Notice that we can even bugger up the types in the last closure. This is probably because // rustc deduces the type of the None as being of Option<i32>, hence the last closure compiles. let mut r = Rect::demo(); let a = Some(&mut r); let result = a.and_then(|mut x| { x.app(" world"); Some(x) }) .and_then(|x| None) .and_then(|x : i32| Some(x * x)); assert_eq!(result, None); // or_else is the other half of the pair. let mut r = Rect::demo(); let a = Some(&mut r); let result = a.and_then(|mut x| { x.app(" world"); Some(x) }) .and_then(|x| None) .or_else(|| Some(22)); assert_eq!(result, Some(22)); // and_then - call the closure if the value is Some // or_else - call the closure if the value is None let mut r = Rect::demo(); let mut r2 = Rect::demo2(); let a = Some(&mut r); let result = a.or_else(|| Some(&mut r2)).unwrap(); assert_eq!(result.title, "first demo"); // We can also use take() in chains to move the value from one place to another. let mut r = Rect::demo(); let mut a = Some(&mut r); let result = a.take().and_then(|mut x| { x.app(" world"); Some(x) }).unwrap(); assert!(a.is_none()); assert_eq!(result.title, "first demo world"); // and_then can change the type of the Option. let mut r = Rect::demo(); let mut a = Some(&mut r); let result = a.and_then(|x| Some(x.title.len())); assert_eq!(result, Some(10)); } fn demo_map() { println!(">>> demo_map"); let mut r = Rect::demo(); let mut a = Some(&mut r); // Maps an Option<T> to Option<U> by applying a function to a contained value. // * Consumes the original value (see as_ref for a way around this) // * and always applies a new wrapping. let result = a.map(|x| x); // TODO 'Consumes' is NOT misleading in the case of references to things. // This won't compile because a has been moved. //assert!(a.is_none()); // Here is demonstrated the property of automatically wrapping in a Some. // Note that the closure does not have Some. let t = result.unwrap(); assert_eq!(t.title, "first demo"); // Like and_then(), map can change the type of the Option. let mut r = Rect::demo(); let mut a = Some(&mut r); let result = a.map(|x| x.title.len()); // assert_eq!(a,...); Again, won't compile because a is moved. assert_eq!(result, Some(10)); // You can call map() on a None. Nothing happens, the None is propagated and the closure is not called. // TODO: The documentation is really bad here. let a : Option<&Rect> = None; let result = a.map(|x| x.title.len()); assert!(result.is_none()); // The other two map variants basically allow us to deal with the None by // supplying a default or a closure to compute a value. // n.b. These do not return Options, they return values! let a : Option<&Rect> = None; let result = a.map_or("hello".len(), |x| x.title.len()); assert_eq!(result, 5); // Note that the default-calculating closure for map_or_else() takes no arguments. let a : Option<&Rect> = None; let x = "hello".to_string(); let result = a.map_or_else(|| x.len(), |y| y.title.len()); assert_eq!(result, 5); }
demo_logical_or_and_combinators
identifier_name
ofrefsofrects.rs
use rect::Rect; pub fn run() { println!("********* Option<&Rect> examples *********"); demo_basic_matching(); demo_as_ref(); demo_as_mut(); demo_unwrap(); demo_take(); demo_logical_or_and_combinators(); demo_chaining(); demo_map(); // demo_collection_of_options(); } fn demo_basic_matching() { println!(">>> demo_basic_matching"); // We need to keep r around for the lifetime checker. let r = Rect::demo(); let a = Some(&r); assert!(a.is_some()); assert!(!a.is_none()); // Match is the most basic way of getting at an option. // Note that x is now &Rect automatically, so we do not need'ref x'. match a { Some(x) => println!("MATCH: x (from a) = {}. x is of type &Rect.", x), None => panic!("a should not be None") } // If let is equivalent to a match where we do nothing in the None. // Because x is automatically a borrow, both of these compile fine. if let Some(x) = a { println!("IF LET: x (from a) = {}. x is of type &Rect.", x); } if let Some(x) = a { println!("IF LET: x (from a) = {}. x is of type &Rect.", x); } } fn demo_as_ref() { println!(">>> demo_as_ref"); let r = Rect::demo(); let a = Some(&r); // b is of type Option<&&Rect>. // Now when we pattern match, we get an &&Rect by default. let b = a.as_ref(); if let Some(x) = b { println!("IF LET: x (from b) = {}. x is of type &&Rect.", x); } // Trying to use & in this case works, we get rid of one of the references. let b = a.as_ref(); if let Some(&x) = b { } } fn demo_as_mut() { println!(">>> demo_as_mut (not sure what is going on here, to be honest)"); let r = Rect::demo(); let mut a = Some(&r); { // Again, but using as_mut(); // c is of type Option<&mut &Rect>. // Now when we pattern match, we get an &mut &Rect by default. let c = a.as_mut(); if let Some(x) = c { println!("IF LET: x (from c) = {}. x is of type &mut i32 and can be changed.", x); // x.w = 200; // Cannot assign to immutable field x.w } } { // We can now pattern match using &mut x. let c = a.as_mut(); if let Some(&mut x) = c { } } } fn demo_unwrap()
let x = a.unwrap_or_else(|| &r2); assert!(x.title == "first demo"); // Let's make a None. let a : Option<&Rect> = None; let x = a.unwrap_or(&r2); assert!(x.title == "second demo"); // let a : Option<&Rect> = None; // let x = a.unwrap_or_default(); // Type needs to implement the Default trait, &Rect doesn't. // assert!(x == String::new()); let a : Option<&Rect> = None; let x = a.unwrap_or_else(|| &r2); // Result of a closure. assert!(x.title == "second demo"); } fn demo_take() { println!(">>> demo_take"); // Take can be used to move a value from one option to another. let r = Rect::demo(); let mut a = Some(&r); let b = a.take(); assert!(a.is_none()); match b { Some(x) => assert!(x.title == "first demo"), None => panic!("a should not be None") } } fn demo_logical_or_and_combinators() { // This is quite simple, but there is a wrinkle. let r = Rect::demo(); let a = Some(&r); let b : Option<&Rect> = None; // For 'or', both options must be of the same type. let c = a.or(b).unwrap(); assert_eq!(c.title, "first demo"); // Reset. let a = Some(&r); let b : Option<&Rect> = None; let d = a.and(b); assert!(d.is_none()); // But for 'and', they can be different: you get back the second. let a = Some(&r); let b = Some("b".to_string()); let d = a.and(b); assert_eq!(d, Some("b".to_string())); } fn demo_chaining() { println!(">>> demo_chaining"); // The closure (or function) passed to and_then() only gets called if 'a' is Some. // Since it isn't, we never call the closure. x is of type i32 in this example. // The closure must return an Option<T>. let a : Option<&Rect> = None; let result = a.and_then(|x| Some(x)); assert!(result.is_none()); // This can be chained. None of these closures will get called. let a : Option<&Rect> = None; let result = a.and_then(|x| Some(x)).and_then(|x| Some(x)).and_then(|x| Some(x)); assert!(result.is_none()); // This will flow the whole way down. Notice that we have to specify mut x for the closure // parameter in order to be able to call app(), and note also that we create the Some // with a '&mut r'!! It won't compile without it. let mut r = Rect::demo(); let a = Some(&mut r); let result = a.and_then(|mut x| { x.app(" world"); Some(x) }) .and_then(|mut x| { x.app(" world"); Some(x) }) .and_then(|mut x| { x.app(" world"); Some(x) }); assert_eq!(result.unwrap().title, "first demo world world world"); // We can terminate in the middle, but the chain remains safe from panics. // Notice that we can even bugger up the types in the last closure. This is probably because // rustc deduces the type of the None as being of Option<i32>, hence the last closure compiles. let mut r = Rect::demo(); let a = Some(&mut r); let result = a.and_then(|mut x| { x.app(" world"); Some(x) }) .and_then(|x| None) .and_then(|x : i32| Some(x * x)); assert_eq!(result, None); // or_else is the other half of the pair. let mut r = Rect::demo(); let a = Some(&mut r); let result = a.and_then(|mut x| { x.app(" world"); Some(x) }) .and_then(|x| None) .or_else(|| Some(22)); assert_eq!(result, Some(22)); // and_then - call the closure if the value is Some // or_else - call the closure if the value is None let mut r = Rect::demo(); let mut r2 = Rect::demo2(); let a = Some(&mut r); let result = a.or_else(|| Some(&mut r2)).unwrap(); assert_eq!(result.title, "first demo"); // We can also use take() in chains to move the value from one place to another. let mut r = Rect::demo(); let mut a = Some(&mut r); let result = a.take().and_then(|mut x| { x.app(" world"); Some(x) }).unwrap(); assert!(a.is_none()); assert_eq!(result.title, "first demo world"); // and_then can change the type of the Option. let mut r = Rect::demo(); let mut a = Some(&mut r); let result = a.and_then(|x| Some(x.title.len())); assert_eq!(result, Some(10)); } fn demo_map() { println!(">>> demo_map"); let mut r = Rect::demo(); let mut a = Some(&mut r); // Maps an Option<T> to Option<U> by applying a function to a contained value. // * Consumes the original value (see as_ref for a way around this) // * and always applies a new wrapping. let result = a.map(|x| x); // TODO 'Consumes' is NOT misleading in the case of references to things. // This won't compile because a has been moved. //assert!(a.is_none()); // Here is demonstrated the property of automatically wrapping in a Some. // Note that the closure does not have Some. let t = result.unwrap(); assert_eq!(t.title, "first demo"); // Like and_then(), map can change the type of the Option. let mut r = Rect::demo(); let mut a = Some(&mut r); let result = a.map(|x| x.title.len()); // assert_eq!(a,...); Again, won't compile because a is moved. assert_eq!(result, Some(10)); // You can call map() on a None. Nothing happens, the None is propagated and the closure is not called. // TODO: The documentation is really bad here. let a : Option<&Rect> = None; let result = a.map(|x| x.title.len()); assert!(result.is_none()); // The other two map variants basically allow us to deal with the None by // supplying a default or a closure to compute a value. // n.b. These do not return Options, they return values! let a : Option<&Rect> = None; let result = a.map_or("hello".len(), |x| x.title.len()); assert_eq!(result, 5); // Note that the default-calculating closure for map_or_else() takes no arguments. let a : Option<&Rect> = None; let x = "hello".to_string(); let result = a.map_or_else(|| x.len(), |y| y.title.len()); assert_eq!(result, 5); }
{ println!(">>> demo_unwrap"); let r = Rect::demo(); let r2 = Rect::demo2(); let a = Some(&r); let x = a.unwrap(); println!("x = {}", x); // These are all no-ops because is a Some. let a = Some(&r); let x = a.unwrap_or(&r2); assert!(x.title == "first demo"); // Won't compile, T is &Rect, not Rect. // let a = Some(&r); // let x = a.unwrap_or_default(); // assert!(x == "hello".to_string()); let a = Some(&r);
identifier_body
ofrefsofrects.rs
use rect::Rect; pub fn run() { println!("********* Option<&Rect> examples *********"); demo_basic_matching(); demo_as_ref(); demo_as_mut(); demo_unwrap(); demo_take(); demo_logical_or_and_combinators(); demo_chaining(); demo_map(); // demo_collection_of_options(); } fn demo_basic_matching() { println!(">>> demo_basic_matching"); // We need to keep r around for the lifetime checker. let r = Rect::demo(); let a = Some(&r); assert!(a.is_some());
match a { Some(x) => println!("MATCH: x (from a) = {}. x is of type &Rect.", x), None => panic!("a should not be None") } // If let is equivalent to a match where we do nothing in the None. // Because x is automatically a borrow, both of these compile fine. if let Some(x) = a { println!("IF LET: x (from a) = {}. x is of type &Rect.", x); } if let Some(x) = a { println!("IF LET: x (from a) = {}. x is of type &Rect.", x); } } fn demo_as_ref() { println!(">>> demo_as_ref"); let r = Rect::demo(); let a = Some(&r); // b is of type Option<&&Rect>. // Now when we pattern match, we get an &&Rect by default. let b = a.as_ref(); if let Some(x) = b { println!("IF LET: x (from b) = {}. x is of type &&Rect.", x); } // Trying to use & in this case works, we get rid of one of the references. let b = a.as_ref(); if let Some(&x) = b { } } fn demo_as_mut() { println!(">>> demo_as_mut (not sure what is going on here, to be honest)"); let r = Rect::demo(); let mut a = Some(&r); { // Again, but using as_mut(); // c is of type Option<&mut &Rect>. // Now when we pattern match, we get an &mut &Rect by default. let c = a.as_mut(); if let Some(x) = c { println!("IF LET: x (from c) = {}. x is of type &mut i32 and can be changed.", x); // x.w = 200; // Cannot assign to immutable field x.w } } { // We can now pattern match using &mut x. let c = a.as_mut(); if let Some(&mut x) = c { } } } fn demo_unwrap() { println!(">>> demo_unwrap"); let r = Rect::demo(); let r2 = Rect::demo2(); let a = Some(&r); let x = a.unwrap(); println!("x = {}", x); // These are all no-ops because is a Some. let a = Some(&r); let x = a.unwrap_or(&r2); assert!(x.title == "first demo"); // Won't compile, T is &Rect, not Rect. // let a = Some(&r); // let x = a.unwrap_or_default(); // assert!(x == "hello".to_string()); let a = Some(&r); let x = a.unwrap_or_else(|| &r2); assert!(x.title == "first demo"); // Let's make a None. let a : Option<&Rect> = None; let x = a.unwrap_or(&r2); assert!(x.title == "second demo"); // let a : Option<&Rect> = None; // let x = a.unwrap_or_default(); // Type needs to implement the Default trait, &Rect doesn't. // assert!(x == String::new()); let a : Option<&Rect> = None; let x = a.unwrap_or_else(|| &r2); // Result of a closure. assert!(x.title == "second demo"); } fn demo_take() { println!(">>> demo_take"); // Take can be used to move a value from one option to another. let r = Rect::demo(); let mut a = Some(&r); let b = a.take(); assert!(a.is_none()); match b { Some(x) => assert!(x.title == "first demo"), None => panic!("a should not be None") } } fn demo_logical_or_and_combinators() { // This is quite simple, but there is a wrinkle. let r = Rect::demo(); let a = Some(&r); let b : Option<&Rect> = None; // For 'or', both options must be of the same type. let c = a.or(b).unwrap(); assert_eq!(c.title, "first demo"); // Reset. let a = Some(&r); let b : Option<&Rect> = None; let d = a.and(b); assert!(d.is_none()); // But for 'and', they can be different: you get back the second. let a = Some(&r); let b = Some("b".to_string()); let d = a.and(b); assert_eq!(d, Some("b".to_string())); } fn demo_chaining() { println!(">>> demo_chaining"); // The closure (or function) passed to and_then() only gets called if 'a' is Some. // Since it isn't, we never call the closure. x is of type i32 in this example. // The closure must return an Option<T>. let a : Option<&Rect> = None; let result = a.and_then(|x| Some(x)); assert!(result.is_none()); // This can be chained. None of these closures will get called. let a : Option<&Rect> = None; let result = a.and_then(|x| Some(x)).and_then(|x| Some(x)).and_then(|x| Some(x)); assert!(result.is_none()); // This will flow the whole way down. Notice that we have to specify mut x for the closure // parameter in order to be able to call app(), and note also that we create the Some // with a '&mut r'!! It won't compile without it. let mut r = Rect::demo(); let a = Some(&mut r); let result = a.and_then(|mut x| { x.app(" world"); Some(x) }) .and_then(|mut x| { x.app(" world"); Some(x) }) .and_then(|mut x| { x.app(" world"); Some(x) }); assert_eq!(result.unwrap().title, "first demo world world world"); // We can terminate in the middle, but the chain remains safe from panics. // Notice that we can even bugger up the types in the last closure. This is probably because // rustc deduces the type of the None as being of Option<i32>, hence the last closure compiles. let mut r = Rect::demo(); let a = Some(&mut r); let result = a.and_then(|mut x| { x.app(" world"); Some(x) }) .and_then(|x| None) .and_then(|x : i32| Some(x * x)); assert_eq!(result, None); // or_else is the other half of the pair. let mut r = Rect::demo(); let a = Some(&mut r); let result = a.and_then(|mut x| { x.app(" world"); Some(x) }) .and_then(|x| None) .or_else(|| Some(22)); assert_eq!(result, Some(22)); // and_then - call the closure if the value is Some // or_else - call the closure if the value is None let mut r = Rect::demo(); let mut r2 = Rect::demo2(); let a = Some(&mut r); let result = a.or_else(|| Some(&mut r2)).unwrap(); assert_eq!(result.title, "first demo"); // We can also use take() in chains to move the value from one place to another. let mut r = Rect::demo(); let mut a = Some(&mut r); let result = a.take().and_then(|mut x| { x.app(" world"); Some(x) }).unwrap(); assert!(a.is_none()); assert_eq!(result.title, "first demo world"); // and_then can change the type of the Option. let mut r = Rect::demo(); let mut a = Some(&mut r); let result = a.and_then(|x| Some(x.title.len())); assert_eq!(result, Some(10)); } fn demo_map() { println!(">>> demo_map"); let mut r = Rect::demo(); let mut a = Some(&mut r); // Maps an Option<T> to Option<U> by applying a function to a contained value. // * Consumes the original value (see as_ref for a way around this) // * and always applies a new wrapping. let result = a.map(|x| x); // TODO 'Consumes' is NOT misleading in the case of references to things. // This won't compile because a has been moved. //assert!(a.is_none()); // Here is demonstrated the property of automatically wrapping in a Some. // Note that the closure does not have Some. let t = result.unwrap(); assert_eq!(t.title, "first demo"); // Like and_then(), map can change the type of the Option. let mut r = Rect::demo(); let mut a = Some(&mut r); let result = a.map(|x| x.title.len()); // assert_eq!(a,...); Again, won't compile because a is moved. assert_eq!(result, Some(10)); // You can call map() on a None. Nothing happens, the None is propagated and the closure is not called. // TODO: The documentation is really bad here. let a : Option<&Rect> = None; let result = a.map(|x| x.title.len()); assert!(result.is_none()); // The other two map variants basically allow us to deal with the None by // supplying a default or a closure to compute a value. // n.b. These do not return Options, they return values! let a : Option<&Rect> = None; let result = a.map_or("hello".len(), |x| x.title.len()); assert_eq!(result, 5); // Note that the default-calculating closure for map_or_else() takes no arguments. let a : Option<&Rect> = None; let x = "hello".to_string(); let result = a.map_or_else(|| x.len(), |y| y.title.len()); assert_eq!(result, 5); }
assert!(!a.is_none()); // Match is the most basic way of getting at an option. // Note that x is now &Rect automatically, so we do not need 'ref x'.
random_line_split
mod.rs
// Copyright 2016 Alexander Reece // // 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. mod inner; use xml::reader::XmlEvent; use {Class, Constant, Domain}; use parser::Error; pub use self::inner::Parser as InnerParser; #[derive(Debug)] pub enum Child<'a> { Constant(Constant<'a>), Domain(Domain<'a>), Class(Class<'a>), } #[derive(Debug)] pub enum Parser<'a> { Parsing(InnerParser<'a>), Finished(Option<Child<'a>>), } impl<'a> Parser<'a> { pub fn new(parser: InnerParser<'a>) -> Self { Parser::Parsing(parser.into()) } pub fn parse(self, event: &XmlEvent) -> Result<Self, Error> { match self { Parser::Parsing(parser) =>
, _ => Err(Error::ExpectedEnd), } } } impl<'a> From<Constant<'a>> for Child<'a> { fn from(child: Constant<'a>) -> Self { Child::Constant(child) } } impl<'a> From<Domain<'a>> for Child<'a> { fn from(child: Domain<'a>) -> Self { Child::Domain(child) } } impl<'a> From<Class<'a>> for Child<'a> { fn from(child: Class<'a>) -> Self { Child::Class(child) } }
{ let parser = try!(parser.parse(event)); Ok(match parser.child() { Ok(child) => Parser::Finished(child.into()), Err(parser) => Parser::Parsing(parser), }) }
conditional_block
mod.rs
// Copyright 2016 Alexander Reece // // 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. mod inner;
use xml::reader::XmlEvent; use {Class, Constant, Domain}; use parser::Error; pub use self::inner::Parser as InnerParser; #[derive(Debug)] pub enum Child<'a> { Constant(Constant<'a>), Domain(Domain<'a>), Class(Class<'a>), } #[derive(Debug)] pub enum Parser<'a> { Parsing(InnerParser<'a>), Finished(Option<Child<'a>>), } impl<'a> Parser<'a> { pub fn new(parser: InnerParser<'a>) -> Self { Parser::Parsing(parser.into()) } pub fn parse(self, event: &XmlEvent) -> Result<Self, Error> { match self { Parser::Parsing(parser) => { let parser = try!(parser.parse(event)); Ok(match parser.child() { Ok(child) => Parser::Finished(child.into()), Err(parser) => Parser::Parsing(parser), }) }, _ => Err(Error::ExpectedEnd), } } } impl<'a> From<Constant<'a>> for Child<'a> { fn from(child: Constant<'a>) -> Self { Child::Constant(child) } } impl<'a> From<Domain<'a>> for Child<'a> { fn from(child: Domain<'a>) -> Self { Child::Domain(child) } } impl<'a> From<Class<'a>> for Child<'a> { fn from(child: Class<'a>) -> Self { Child::Class(child) } }
random_line_split
mod.rs
// Copyright 2016 Alexander Reece // // 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. mod inner; use xml::reader::XmlEvent; use {Class, Constant, Domain}; use parser::Error; pub use self::inner::Parser as InnerParser; #[derive(Debug)] pub enum Child<'a> { Constant(Constant<'a>), Domain(Domain<'a>), Class(Class<'a>), } #[derive(Debug)] pub enum Parser<'a> { Parsing(InnerParser<'a>), Finished(Option<Child<'a>>), } impl<'a> Parser<'a> { pub fn new(parser: InnerParser<'a>) -> Self { Parser::Parsing(parser.into()) } pub fn parse(self, event: &XmlEvent) -> Result<Self, Error> { match self { Parser::Parsing(parser) => { let parser = try!(parser.parse(event)); Ok(match parser.child() { Ok(child) => Parser::Finished(child.into()), Err(parser) => Parser::Parsing(parser), }) }, _ => Err(Error::ExpectedEnd), } } } impl<'a> From<Constant<'a>> for Child<'a> { fn from(child: Constant<'a>) -> Self { Child::Constant(child) } } impl<'a> From<Domain<'a>> for Child<'a> { fn from(child: Domain<'a>) -> Self { Child::Domain(child) } } impl<'a> From<Class<'a>> for Child<'a> { fn from(child: Class<'a>) -> Self
}
{ Child::Class(child) }
identifier_body
mod.rs
// Copyright 2016 Alexander Reece // // 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. mod inner; use xml::reader::XmlEvent; use {Class, Constant, Domain}; use parser::Error; pub use self::inner::Parser as InnerParser; #[derive(Debug)] pub enum Child<'a> { Constant(Constant<'a>), Domain(Domain<'a>), Class(Class<'a>), } #[derive(Debug)] pub enum Parser<'a> { Parsing(InnerParser<'a>), Finished(Option<Child<'a>>), } impl<'a> Parser<'a> { pub fn new(parser: InnerParser<'a>) -> Self { Parser::Parsing(parser.into()) } pub fn parse(self, event: &XmlEvent) -> Result<Self, Error> { match self { Parser::Parsing(parser) => { let parser = try!(parser.parse(event)); Ok(match parser.child() { Ok(child) => Parser::Finished(child.into()), Err(parser) => Parser::Parsing(parser), }) }, _ => Err(Error::ExpectedEnd), } } } impl<'a> From<Constant<'a>> for Child<'a> { fn from(child: Constant<'a>) -> Self { Child::Constant(child) } } impl<'a> From<Domain<'a>> for Child<'a> { fn
(child: Domain<'a>) -> Self { Child::Domain(child) } } impl<'a> From<Class<'a>> for Child<'a> { fn from(child: Class<'a>) -> Self { Child::Class(child) } }
from
identifier_name
call_chain.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any // later version. // This program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use common_types::receipt::LocalizedReceipt; use core::libchain::Genesis; use core::libchain::chain::*; use std::sync::Arc; use std::sync::mpsc::Sender; use util::{H256, H160}; use util::KeyValueDB; #[allow(unused_variables, dead_code)] #[derive(Clone)] pub struct Callchain { chain: Arc<Chain>, } #[allow(unused_variables, dead_code)] impl Callchain { pub fn new(db: Arc<KeyValueDB>, genesis: Genesis, sync_sender: Sender<u64>) -> Self { let (chain, st) = Chain::init_chain(db, genesis, sync_sender); Callchain { chain: chain } }
} pub fn get_height(&self) -> u64 { self.chain.get_current_height() } pub fn get_pre_hash(&self) -> H256 { *self.chain.current_hash.read() } pub fn get_contract_address(&self, hash: H256) -> H160 { let receipt = self.chain.localized_receipt(hash).unwrap(); match receipt.contract_address { Some(contract_address) => contract_address, None => panic!("contract_address error"), } } pub fn get_receipt(&self, hash: H256) -> LocalizedReceipt { self.chain.localized_receipt(hash).unwrap() } }
pub fn add_block(&self, block: Block) { self.chain.set_block(block);
random_line_split
call_chain.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any // later version. // This program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use common_types::receipt::LocalizedReceipt; use core::libchain::Genesis; use core::libchain::chain::*; use std::sync::Arc; use std::sync::mpsc::Sender; use util::{H256, H160}; use util::KeyValueDB; #[allow(unused_variables, dead_code)] #[derive(Clone)] pub struct Callchain { chain: Arc<Chain>, } #[allow(unused_variables, dead_code)] impl Callchain { pub fn new(db: Arc<KeyValueDB>, genesis: Genesis, sync_sender: Sender<u64>) -> Self
pub fn add_block(&self, block: Block) { self.chain.set_block(block); } pub fn get_height(&self) -> u64 { self.chain.get_current_height() } pub fn get_pre_hash(&self) -> H256 { *self.chain.current_hash.read() } pub fn get_contract_address(&self, hash: H256) -> H160 { let receipt = self.chain.localized_receipt(hash).unwrap(); match receipt.contract_address { Some(contract_address) => contract_address, None => panic!("contract_address error"), } } pub fn get_receipt(&self, hash: H256) -> LocalizedReceipt { self.chain.localized_receipt(hash).unwrap() } }
{ let (chain, st) = Chain::init_chain(db, genesis, sync_sender); Callchain { chain: chain } }
identifier_body
call_chain.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any // later version. // This program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use common_types::receipt::LocalizedReceipt; use core::libchain::Genesis; use core::libchain::chain::*; use std::sync::Arc; use std::sync::mpsc::Sender; use util::{H256, H160}; use util::KeyValueDB; #[allow(unused_variables, dead_code)] #[derive(Clone)] pub struct Callchain { chain: Arc<Chain>, } #[allow(unused_variables, dead_code)] impl Callchain { pub fn new(db: Arc<KeyValueDB>, genesis: Genesis, sync_sender: Sender<u64>) -> Self { let (chain, st) = Chain::init_chain(db, genesis, sync_sender); Callchain { chain: chain } } pub fn add_block(&self, block: Block) { self.chain.set_block(block); } pub fn
(&self) -> u64 { self.chain.get_current_height() } pub fn get_pre_hash(&self) -> H256 { *self.chain.current_hash.read() } pub fn get_contract_address(&self, hash: H256) -> H160 { let receipt = self.chain.localized_receipt(hash).unwrap(); match receipt.contract_address { Some(contract_address) => contract_address, None => panic!("contract_address error"), } } pub fn get_receipt(&self, hash: H256) -> LocalizedReceipt { self.chain.localized_receipt(hash).unwrap() } }
get_height
identifier_name
cache.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 simple LRU cache. use arrayvec::{Array, ArrayVec}; /// A LRU cache using a statically-sized array for storage. /// /// The most-recently-used entry is at index `head`. The entries form a linked list, linked to each /// other by indices within the `entries` array. After an entry is added to the array, its index /// never changes, so these links are never invalidated. pub struct LRUCache<T, A: Array<Item=Entry<T>>> { entries: ArrayVec<A>, /// Index of the first entry. If the cache is empty, ignore this field. head: u16, /// Index of the last entry. If the cache is empty, ignore this field. tail: u16, } /// An opaque token used as an index into an LRUCache. pub struct CacheIndex(u16); /// An entry in an LRUCache. pub struct Entry<T> { val: T, /// Index of the previous entry. If this entry is the head, ignore this field. prev: u16, /// Index of the next entry. If this entry is the tail, ignore this field. next: u16, } impl<T, A: Array<Item=Entry<T>>> LRUCache<T, A> { /// Create an empty LRU cache. pub fn new() -> Self { let cache = LRUCache { entries: ArrayVec::new(), head: 0, tail: 0, }; assert!(cache.entries.capacity() < u16::max_value() as usize, "Capacity overflow"); cache } /// Returns the number of elements in the cache. pub fn num_entries(&self) -> usize { self.entries.len() } #[inline] /// Touch a given entry, putting it first in the list. pub fn touch(&mut self, idx: CacheIndex) { if idx.0!= self.head { self.remove(idx.0); self.push_front(idx.0); } } /// Returns the front entry in the list (most recently used). pub fn front(&self) -> Option<&T> { self.entries.get(self.head as usize).map(|e| &e.val) } /// Returns a mutable reference to the front entry in the list (most recently used). pub fn front_mut(&mut self) -> Option<&mut T> { self.entries.get_mut(self.head as usize).map(|e| &mut e.val) } /// Iterate over the contents of this cache, from more to less recently /// used. pub fn iter(&self) -> LRUCacheIterator<T, A> { LRUCacheIterator { pos: self.head, done: self.entries.len() == 0, cache: self, } } /// Iterate mutably over the contents of this cache. pub fn iter_mut(&mut self) -> LRUCacheMutIterator<T, A> { LRUCacheMutIterator { pos: self.head, done: self.entries.len() == 0, cache: self, } } /// Insert a given key in the cache. pub fn insert(&mut self, val: T)
/// Remove an from the linked list. /// /// Note: This only unlinks the entry from the list; it does not remove it from the array. fn remove(&mut self, i: u16) { let prev = self.entries[i as usize].prev; let next = self.entries[i as usize].next; if i == self.head { self.head = next; } else { self.entries[prev as usize].next = next; } if i == self.tail { self.tail = prev; } else { self.entries[next as usize].prev = prev; } } /// Insert a new entry at the head of the list. fn push_front(&mut self, i: u16) { if self.entries.len() == 1 { self.tail = i; } else { self.entries[i as usize].next = self.head; self.entries[self.head as usize].prev = i; } self.head = i; } /// Remove the last entry from the linked list. Returns the index of the removed entry. /// /// Note: This only unlinks the entry from the list; it does not remove it from the array. fn pop_back(&mut self) -> u16 { let old_tail = self.tail; let new_tail = self.entries[old_tail as usize].prev; self.tail = new_tail; old_tail } /// Evict all elements from the cache. pub fn evict_all(&mut self) { self.entries.clear(); } } /// Immutable iterator over values in an LRUCache, from most-recently-used to least-recently-used. pub struct LRUCacheIterator<'a, T: 'a, A: 'a + Array<Item=Entry<T>>> { cache: &'a LRUCache<T, A>, pos: u16, done: bool, } impl<'a, T, A> Iterator for LRUCacheIterator<'a, T, A> where T: 'a, A: 'a + Array<Item=Entry<T>> { type Item = (CacheIndex, &'a T); fn next(&mut self) -> Option<Self::Item> { if self.done { return None } let entry = &self.cache.entries[self.pos as usize]; let index = CacheIndex(self.pos); if self.pos == self.cache.tail { self.done = true; } self.pos = entry.next; Some((index, &entry.val)) } } /// Mutable iterator over values in an LRUCache, from most-recently-used to least-recently-used. pub struct LRUCacheMutIterator<'a, T: 'a, A: 'a + Array<Item=Entry<T>>> { cache: &'a mut LRUCache<T, A>, pos: u16, done: bool, } impl<'a, T, A> Iterator for LRUCacheMutIterator<'a, T, A> where T: 'a, A: 'a + Array<Item=Entry<T>> { type Item = (CacheIndex, &'a mut T); fn next(&mut self) -> Option<Self::Item> { if self.done { return None } // Use a raw pointer because the compiler doesn't know that subsequent calls can't alias. let entry = unsafe { &mut *(&mut self.cache.entries[self.pos as usize] as *mut Entry<T>) }; let index = CacheIndex(self.pos); if self.pos == self.cache.tail { self.done = true; } self.pos = entry.next; Some((index, &mut entry.val)) } }
{ let entry = Entry { val, prev: 0, next: 0 }; // If the cache is full, replace the oldest entry. Otherwise, add an entry. let new_head = if self.entries.len() == self.entries.capacity() { let i = self.pop_back(); self.entries[i as usize] = entry; i } else { self.entries.push(entry); self.entries.len() as u16 - 1 }; self.push_front(new_head); }
identifier_body
cache.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 simple LRU cache. use arrayvec::{Array, ArrayVec}; /// A LRU cache using a statically-sized array for storage. /// /// The most-recently-used entry is at index `head`. The entries form a linked list, linked to each /// other by indices within the `entries` array. After an entry is added to the array, its index /// never changes, so these links are never invalidated. pub struct LRUCache<T, A: Array<Item=Entry<T>>> { entries: ArrayVec<A>, /// Index of the first entry. If the cache is empty, ignore this field. head: u16, /// Index of the last entry. If the cache is empty, ignore this field. tail: u16, } /// An opaque token used as an index into an LRUCache. pub struct CacheIndex(u16); /// An entry in an LRUCache. pub struct Entry<T> { val: T, /// Index of the previous entry. If this entry is the head, ignore this field. prev: u16, /// Index of the next entry. If this entry is the tail, ignore this field. next: u16, } impl<T, A: Array<Item=Entry<T>>> LRUCache<T, A> { /// Create an empty LRU cache. pub fn new() -> Self { let cache = LRUCache { entries: ArrayVec::new(), head: 0, tail: 0, }; assert!(cache.entries.capacity() < u16::max_value() as usize, "Capacity overflow"); cache } /// Returns the number of elements in the cache. pub fn num_entries(&self) -> usize { self.entries.len() } #[inline] /// Touch a given entry, putting it first in the list. pub fn touch(&mut self, idx: CacheIndex) { if idx.0!= self.head { self.remove(idx.0); self.push_front(idx.0); } } /// Returns the front entry in the list (most recently used). pub fn front(&self) -> Option<&T> { self.entries.get(self.head as usize).map(|e| &e.val) } /// Returns a mutable reference to the front entry in the list (most recently used). pub fn front_mut(&mut self) -> Option<&mut T> { self.entries.get_mut(self.head as usize).map(|e| &mut e.val) } /// Iterate over the contents of this cache, from more to less recently /// used. pub fn iter(&self) -> LRUCacheIterator<T, A> { LRUCacheIterator { pos: self.head, done: self.entries.len() == 0, cache: self, } } /// Iterate mutably over the contents of this cache. pub fn iter_mut(&mut self) -> LRUCacheMutIterator<T, A> { LRUCacheMutIterator { pos: self.head, done: self.entries.len() == 0, cache: self, } } /// Insert a given key in the cache. pub fn insert(&mut self, val: T) { let entry = Entry { val, prev: 0, next: 0 }; // If the cache is full, replace the oldest entry. Otherwise, add an entry. let new_head = if self.entries.len() == self.entries.capacity() { let i = self.pop_back(); self.entries[i as usize] = entry; i } else { self.entries.push(entry); self.entries.len() as u16 - 1 }; self.push_front(new_head); } /// Remove an from the linked list. /// /// Note: This only unlinks the entry from the list; it does not remove it from the array. fn remove(&mut self, i: u16) { let prev = self.entries[i as usize].prev; let next = self.entries[i as usize].next; if i == self.head { self.head = next; } else { self.entries[prev as usize].next = next; } if i == self.tail { self.tail = prev; } else { self.entries[next as usize].prev = prev;
} } /// Insert a new entry at the head of the list. fn push_front(&mut self, i: u16) { if self.entries.len() == 1 { self.tail = i; } else { self.entries[i as usize].next = self.head; self.entries[self.head as usize].prev = i; } self.head = i; } /// Remove the last entry from the linked list. Returns the index of the removed entry. /// /// Note: This only unlinks the entry from the list; it does not remove it from the array. fn pop_back(&mut self) -> u16 { let old_tail = self.tail; let new_tail = self.entries[old_tail as usize].prev; self.tail = new_tail; old_tail } /// Evict all elements from the cache. pub fn evict_all(&mut self) { self.entries.clear(); } } /// Immutable iterator over values in an LRUCache, from most-recently-used to least-recently-used. pub struct LRUCacheIterator<'a, T: 'a, A: 'a + Array<Item=Entry<T>>> { cache: &'a LRUCache<T, A>, pos: u16, done: bool, } impl<'a, T, A> Iterator for LRUCacheIterator<'a, T, A> where T: 'a, A: 'a + Array<Item=Entry<T>> { type Item = (CacheIndex, &'a T); fn next(&mut self) -> Option<Self::Item> { if self.done { return None } let entry = &self.cache.entries[self.pos as usize]; let index = CacheIndex(self.pos); if self.pos == self.cache.tail { self.done = true; } self.pos = entry.next; Some((index, &entry.val)) } } /// Mutable iterator over values in an LRUCache, from most-recently-used to least-recently-used. pub struct LRUCacheMutIterator<'a, T: 'a, A: 'a + Array<Item=Entry<T>>> { cache: &'a mut LRUCache<T, A>, pos: u16, done: bool, } impl<'a, T, A> Iterator for LRUCacheMutIterator<'a, T, A> where T: 'a, A: 'a + Array<Item=Entry<T>> { type Item = (CacheIndex, &'a mut T); fn next(&mut self) -> Option<Self::Item> { if self.done { return None } // Use a raw pointer because the compiler doesn't know that subsequent calls can't alias. let entry = unsafe { &mut *(&mut self.cache.entries[self.pos as usize] as *mut Entry<T>) }; let index = CacheIndex(self.pos); if self.pos == self.cache.tail { self.done = true; } self.pos = entry.next; Some((index, &mut entry.val)) } }
random_line_split
cache.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 simple LRU cache. use arrayvec::{Array, ArrayVec}; /// A LRU cache using a statically-sized array for storage. /// /// The most-recently-used entry is at index `head`. The entries form a linked list, linked to each /// other by indices within the `entries` array. After an entry is added to the array, its index /// never changes, so these links are never invalidated. pub struct LRUCache<T, A: Array<Item=Entry<T>>> { entries: ArrayVec<A>, /// Index of the first entry. If the cache is empty, ignore this field. head: u16, /// Index of the last entry. If the cache is empty, ignore this field. tail: u16, } /// An opaque token used as an index into an LRUCache. pub struct CacheIndex(u16); /// An entry in an LRUCache. pub struct Entry<T> { val: T, /// Index of the previous entry. If this entry is the head, ignore this field. prev: u16, /// Index of the next entry. If this entry is the tail, ignore this field. next: u16, } impl<T, A: Array<Item=Entry<T>>> LRUCache<T, A> { /// Create an empty LRU cache. pub fn new() -> Self { let cache = LRUCache { entries: ArrayVec::new(), head: 0, tail: 0, }; assert!(cache.entries.capacity() < u16::max_value() as usize, "Capacity overflow"); cache } /// Returns the number of elements in the cache. pub fn num_entries(&self) -> usize { self.entries.len() } #[inline] /// Touch a given entry, putting it first in the list. pub fn touch(&mut self, idx: CacheIndex) { if idx.0!= self.head { self.remove(idx.0); self.push_front(idx.0); } } /// Returns the front entry in the list (most recently used). pub fn front(&self) -> Option<&T> { self.entries.get(self.head as usize).map(|e| &e.val) } /// Returns a mutable reference to the front entry in the list (most recently used). pub fn front_mut(&mut self) -> Option<&mut T> { self.entries.get_mut(self.head as usize).map(|e| &mut e.val) } /// Iterate over the contents of this cache, from more to less recently /// used. pub fn iter(&self) -> LRUCacheIterator<T, A> { LRUCacheIterator { pos: self.head, done: self.entries.len() == 0, cache: self, } } /// Iterate mutably over the contents of this cache. pub fn
(&mut self) -> LRUCacheMutIterator<T, A> { LRUCacheMutIterator { pos: self.head, done: self.entries.len() == 0, cache: self, } } /// Insert a given key in the cache. pub fn insert(&mut self, val: T) { let entry = Entry { val, prev: 0, next: 0 }; // If the cache is full, replace the oldest entry. Otherwise, add an entry. let new_head = if self.entries.len() == self.entries.capacity() { let i = self.pop_back(); self.entries[i as usize] = entry; i } else { self.entries.push(entry); self.entries.len() as u16 - 1 }; self.push_front(new_head); } /// Remove an from the linked list. /// /// Note: This only unlinks the entry from the list; it does not remove it from the array. fn remove(&mut self, i: u16) { let prev = self.entries[i as usize].prev; let next = self.entries[i as usize].next; if i == self.head { self.head = next; } else { self.entries[prev as usize].next = next; } if i == self.tail { self.tail = prev; } else { self.entries[next as usize].prev = prev; } } /// Insert a new entry at the head of the list. fn push_front(&mut self, i: u16) { if self.entries.len() == 1 { self.tail = i; } else { self.entries[i as usize].next = self.head; self.entries[self.head as usize].prev = i; } self.head = i; } /// Remove the last entry from the linked list. Returns the index of the removed entry. /// /// Note: This only unlinks the entry from the list; it does not remove it from the array. fn pop_back(&mut self) -> u16 { let old_tail = self.tail; let new_tail = self.entries[old_tail as usize].prev; self.tail = new_tail; old_tail } /// Evict all elements from the cache. pub fn evict_all(&mut self) { self.entries.clear(); } } /// Immutable iterator over values in an LRUCache, from most-recently-used to least-recently-used. pub struct LRUCacheIterator<'a, T: 'a, A: 'a + Array<Item=Entry<T>>> { cache: &'a LRUCache<T, A>, pos: u16, done: bool, } impl<'a, T, A> Iterator for LRUCacheIterator<'a, T, A> where T: 'a, A: 'a + Array<Item=Entry<T>> { type Item = (CacheIndex, &'a T); fn next(&mut self) -> Option<Self::Item> { if self.done { return None } let entry = &self.cache.entries[self.pos as usize]; let index = CacheIndex(self.pos); if self.pos == self.cache.tail { self.done = true; } self.pos = entry.next; Some((index, &entry.val)) } } /// Mutable iterator over values in an LRUCache, from most-recently-used to least-recently-used. pub struct LRUCacheMutIterator<'a, T: 'a, A: 'a + Array<Item=Entry<T>>> { cache: &'a mut LRUCache<T, A>, pos: u16, done: bool, } impl<'a, T, A> Iterator for LRUCacheMutIterator<'a, T, A> where T: 'a, A: 'a + Array<Item=Entry<T>> { type Item = (CacheIndex, &'a mut T); fn next(&mut self) -> Option<Self::Item> { if self.done { return None } // Use a raw pointer because the compiler doesn't know that subsequent calls can't alias. let entry = unsafe { &mut *(&mut self.cache.entries[self.pos as usize] as *mut Entry<T>) }; let index = CacheIndex(self.pos); if self.pos == self.cache.tail { self.done = true; } self.pos = entry.next; Some((index, &mut entry.val)) } }
iter_mut
identifier_name
cache.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 simple LRU cache. use arrayvec::{Array, ArrayVec}; /// A LRU cache using a statically-sized array for storage. /// /// The most-recently-used entry is at index `head`. The entries form a linked list, linked to each /// other by indices within the `entries` array. After an entry is added to the array, its index /// never changes, so these links are never invalidated. pub struct LRUCache<T, A: Array<Item=Entry<T>>> { entries: ArrayVec<A>, /// Index of the first entry. If the cache is empty, ignore this field. head: u16, /// Index of the last entry. If the cache is empty, ignore this field. tail: u16, } /// An opaque token used as an index into an LRUCache. pub struct CacheIndex(u16); /// An entry in an LRUCache. pub struct Entry<T> { val: T, /// Index of the previous entry. If this entry is the head, ignore this field. prev: u16, /// Index of the next entry. If this entry is the tail, ignore this field. next: u16, } impl<T, A: Array<Item=Entry<T>>> LRUCache<T, A> { /// Create an empty LRU cache. pub fn new() -> Self { let cache = LRUCache { entries: ArrayVec::new(), head: 0, tail: 0, }; assert!(cache.entries.capacity() < u16::max_value() as usize, "Capacity overflow"); cache } /// Returns the number of elements in the cache. pub fn num_entries(&self) -> usize { self.entries.len() } #[inline] /// Touch a given entry, putting it first in the list. pub fn touch(&mut self, idx: CacheIndex) { if idx.0!= self.head { self.remove(idx.0); self.push_front(idx.0); } } /// Returns the front entry in the list (most recently used). pub fn front(&self) -> Option<&T> { self.entries.get(self.head as usize).map(|e| &e.val) } /// Returns a mutable reference to the front entry in the list (most recently used). pub fn front_mut(&mut self) -> Option<&mut T> { self.entries.get_mut(self.head as usize).map(|e| &mut e.val) } /// Iterate over the contents of this cache, from more to less recently /// used. pub fn iter(&self) -> LRUCacheIterator<T, A> { LRUCacheIterator { pos: self.head, done: self.entries.len() == 0, cache: self, } } /// Iterate mutably over the contents of this cache. pub fn iter_mut(&mut self) -> LRUCacheMutIterator<T, A> { LRUCacheMutIterator { pos: self.head, done: self.entries.len() == 0, cache: self, } } /// Insert a given key in the cache. pub fn insert(&mut self, val: T) { let entry = Entry { val, prev: 0, next: 0 }; // If the cache is full, replace the oldest entry. Otherwise, add an entry. let new_head = if self.entries.len() == self.entries.capacity() { let i = self.pop_back(); self.entries[i as usize] = entry; i } else { self.entries.push(entry); self.entries.len() as u16 - 1 }; self.push_front(new_head); } /// Remove an from the linked list. /// /// Note: This only unlinks the entry from the list; it does not remove it from the array. fn remove(&mut self, i: u16) { let prev = self.entries[i as usize].prev; let next = self.entries[i as usize].next; if i == self.head { self.head = next; } else
if i == self.tail { self.tail = prev; } else { self.entries[next as usize].prev = prev; } } /// Insert a new entry at the head of the list. fn push_front(&mut self, i: u16) { if self.entries.len() == 1 { self.tail = i; } else { self.entries[i as usize].next = self.head; self.entries[self.head as usize].prev = i; } self.head = i; } /// Remove the last entry from the linked list. Returns the index of the removed entry. /// /// Note: This only unlinks the entry from the list; it does not remove it from the array. fn pop_back(&mut self) -> u16 { let old_tail = self.tail; let new_tail = self.entries[old_tail as usize].prev; self.tail = new_tail; old_tail } /// Evict all elements from the cache. pub fn evict_all(&mut self) { self.entries.clear(); } } /// Immutable iterator over values in an LRUCache, from most-recently-used to least-recently-used. pub struct LRUCacheIterator<'a, T: 'a, A: 'a + Array<Item=Entry<T>>> { cache: &'a LRUCache<T, A>, pos: u16, done: bool, } impl<'a, T, A> Iterator for LRUCacheIterator<'a, T, A> where T: 'a, A: 'a + Array<Item=Entry<T>> { type Item = (CacheIndex, &'a T); fn next(&mut self) -> Option<Self::Item> { if self.done { return None } let entry = &self.cache.entries[self.pos as usize]; let index = CacheIndex(self.pos); if self.pos == self.cache.tail { self.done = true; } self.pos = entry.next; Some((index, &entry.val)) } } /// Mutable iterator over values in an LRUCache, from most-recently-used to least-recently-used. pub struct LRUCacheMutIterator<'a, T: 'a, A: 'a + Array<Item=Entry<T>>> { cache: &'a mut LRUCache<T, A>, pos: u16, done: bool, } impl<'a, T, A> Iterator for LRUCacheMutIterator<'a, T, A> where T: 'a, A: 'a + Array<Item=Entry<T>> { type Item = (CacheIndex, &'a mut T); fn next(&mut self) -> Option<Self::Item> { if self.done { return None } // Use a raw pointer because the compiler doesn't know that subsequent calls can't alias. let entry = unsafe { &mut *(&mut self.cache.entries[self.pos as usize] as *mut Entry<T>) }; let index = CacheIndex(self.pos); if self.pos == self.cache.tail { self.done = true; } self.pos = entry.next; Some((index, &mut entry.val)) } }
{ self.entries[prev as usize].next = next; }
conditional_block
validation.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use tests::helpers::{serve_hosts, request}; #[test] fn should_reject_invalid_host() { // given let server = serve_hosts(Some(vec!["localhost:8080".into()])); // when let response = request(server, "\ GET / HTTP/1.1\r\n\ Host: 127.0.0.1:8080\r\n\ Connection: close\r\n\ \r\n\ {} " ); // then assert_eq!(response.status, "HTTP/1.1 403 Forbidden".to_owned()); assert!(response.body.contains("Current Host Is Disallowed"), response.body); } #[test] fn
() { // given let server = serve_hosts(Some(vec!["localhost:8080".into()])); // when let response = request(server, "\ GET /ui/ HTTP/1.1\r\n\ Host: localhost:8080\r\n\ Connection: close\r\n\ \r\n\ {} " ); // then assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); } #[test] fn should_serve_dapps_domains() { // given let server = serve_hosts(Some(vec!["localhost:8080".into()])); // when let response = request(server, "\ GET / HTTP/1.1\r\n\ Host: ui.parity\r\n\ Connection: close\r\n\ \r\n\ {} " ); // then assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); } #[test] // NOTE [todr] This is required for error pages to be styled properly. fn should_allow_parity_utils_even_on_invalid_domain() { // given let server = serve_hosts(Some(vec!["localhost:8080".into()])); // when let response = request(server, "\ GET /parity-utils/styles.css HTTP/1.1\r\n\ Host: 127.0.0.1:8080\r\n\ Connection: close\r\n\ \r\n\ {} " ); // then assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); } #[test] fn should_not_return_cors_headers_for_rpc() { // given let server = serve_hosts(Some(vec!["localhost:8080".into()])); // when let response = request(server, "\ POST /rpc HTTP/1.1\r\n\ Host: localhost:8080\r\n\ Origin: null\r\n\ Content-Type: application/json\r\n\ Connection: close\r\n\ \r\n\ {} " ); // then assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); assert!( !response.headers_raw.contains("Access-Control-Allow-Origin"), "CORS headers were not expected: {:?}", response.headers ); }
should_allow_valid_host
identifier_name
validation.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use tests::helpers::{serve_hosts, request}; #[test] fn should_reject_invalid_host() { // given let server = serve_hosts(Some(vec!["localhost:8080".into()])); // when let response = request(server, "\ GET / HTTP/1.1\r\n\ Host: 127.0.0.1:8080\r\n\ Connection: close\r\n\ \r\n\ {} " ); // then assert_eq!(response.status, "HTTP/1.1 403 Forbidden".to_owned()); assert!(response.body.contains("Current Host Is Disallowed"), response.body); } #[test] fn should_allow_valid_host() { // given let server = serve_hosts(Some(vec!["localhost:8080".into()])); // when let response = request(server, "\ GET /ui/ HTTP/1.1\r\n\ Host: localhost:8080\r\n\ Connection: close\r\n\ \r\n\ {} " ); // then assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); } #[test] fn should_serve_dapps_domains() { // given let server = serve_hosts(Some(vec!["localhost:8080".into()])); // when let response = request(server, "\ GET / HTTP/1.1\r\n\ Host: ui.parity\r\n\ Connection: close\r\n\ \r\n\ {} " ); // then assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); } #[test] // NOTE [todr] This is required for error pages to be styled properly. fn should_allow_parity_utils_even_on_invalid_domain() { // given let server = serve_hosts(Some(vec!["localhost:8080".into()])); // when let response = request(server, "\ GET /parity-utils/styles.css HTTP/1.1\r\n\ Host: 127.0.0.1:8080\r\n\ Connection: close\r\n\ \r\n\ {} " ); // then assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); } #[test] fn should_not_return_cors_headers_for_rpc() {
// given let server = serve_hosts(Some(vec!["localhost:8080".into()])); // when let response = request(server, "\ POST /rpc HTTP/1.1\r\n\ Host: localhost:8080\r\n\ Origin: null\r\n\ Content-Type: application/json\r\n\ Connection: close\r\n\ \r\n\ {} " ); // then assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); assert!( !response.headers_raw.contains("Access-Control-Allow-Origin"), "CORS headers were not expected: {:?}", response.headers ); }
random_line_split
validation.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use tests::helpers::{serve_hosts, request}; #[test] fn should_reject_invalid_host() { // given let server = serve_hosts(Some(vec!["localhost:8080".into()])); // when let response = request(server, "\ GET / HTTP/1.1\r\n\ Host: 127.0.0.1:8080\r\n\ Connection: close\r\n\ \r\n\ {} " ); // then assert_eq!(response.status, "HTTP/1.1 403 Forbidden".to_owned()); assert!(response.body.contains("Current Host Is Disallowed"), response.body); } #[test] fn should_allow_valid_host()
#[test] fn should_serve_dapps_domains() { // given let server = serve_hosts(Some(vec!["localhost:8080".into()])); // when let response = request(server, "\ GET / HTTP/1.1\r\n\ Host: ui.parity\r\n\ Connection: close\r\n\ \r\n\ {} " ); // then assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); } #[test] // NOTE [todr] This is required for error pages to be styled properly. fn should_allow_parity_utils_even_on_invalid_domain() { // given let server = serve_hosts(Some(vec!["localhost:8080".into()])); // when let response = request(server, "\ GET /parity-utils/styles.css HTTP/1.1\r\n\ Host: 127.0.0.1:8080\r\n\ Connection: close\r\n\ \r\n\ {} " ); // then assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); } #[test] fn should_not_return_cors_headers_for_rpc() { // given let server = serve_hosts(Some(vec!["localhost:8080".into()])); // when let response = request(server, "\ POST /rpc HTTP/1.1\r\n\ Host: localhost:8080\r\n\ Origin: null\r\n\ Content-Type: application/json\r\n\ Connection: close\r\n\ \r\n\ {} " ); // then assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); assert!( !response.headers_raw.contains("Access-Control-Allow-Origin"), "CORS headers were not expected: {:?}", response.headers ); }
{ // given let server = serve_hosts(Some(vec!["localhost:8080".into()])); // when let response = request(server, "\ GET /ui/ HTTP/1.1\r\n\ Host: localhost:8080\r\n\ Connection: close\r\n\ \r\n\ {} " ); // then assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); }
identifier_body
main.rs
#![feature(plugin)] #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; mod primary_index; mod secondary_index; mod table; mod find; use std::fs::File; use std::io::Read; use serde_json::{Value, Error}; fn
() { let db_path = "/data/testdb"; let mut t = table::Table::new("test_table", db_path); t.create_secondary_index("Type", secondary_index::key_types::Str(20)); t.create_secondary_index("Name", secondary_index::key_types::Str(128)); t.create_secondary_index("X", secondary_index::key_types::F32); t.create_secondary_index("Y", secondary_index::key_types::F32); // load_dummy_data(&mut t); println!("Get by id 3 {:?}", t.get(3)); println!("Get by id 4 {:?}", t.get(4)); println!("Get by id 33 {:?}", t.get(33)); println!("Get by id 333 {:?}, has an index of {:?}", t.get(333), t.get(333).get_id()); println!("Search index {:?}", t.secondary_indexes[0].get("TEST", "TEST2")); println!("{}", t.table_name); } fn load_dummy_data(t:&mut table::Table) { // load json from thing let mut s = String::new(); File::open("data.json").unwrap().read_to_string(&mut s).unwrap(); let n:Vec<serde_json::Value> = serde_json::from_str(&s).unwrap(); for item in n.into_iter() { t.insert(&item.to_string()); //println!("{:?}", item.to_string()); } }
main
identifier_name
main.rs
#![feature(plugin)] #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; mod primary_index; mod secondary_index; mod table; mod find; use std::fs::File; use std::io::Read; use serde_json::{Value, Error}; fn main() { let db_path = "/data/testdb"; let mut t = table::Table::new("test_table", db_path); t.create_secondary_index("Type", secondary_index::key_types::Str(20)); t.create_secondary_index("Name", secondary_index::key_types::Str(128));
// load_dummy_data(&mut t); println!("Get by id 3 {:?}", t.get(3)); println!("Get by id 4 {:?}", t.get(4)); println!("Get by id 33 {:?}", t.get(33)); println!("Get by id 333 {:?}, has an index of {:?}", t.get(333), t.get(333).get_id()); println!("Search index {:?}", t.secondary_indexes[0].get("TEST", "TEST2")); println!("{}", t.table_name); } fn load_dummy_data(t:&mut table::Table) { // load json from thing let mut s = String::new(); File::open("data.json").unwrap().read_to_string(&mut s).unwrap(); let n:Vec<serde_json::Value> = serde_json::from_str(&s).unwrap(); for item in n.into_iter() { t.insert(&item.to_string()); //println!("{:?}", item.to_string()); } }
t.create_secondary_index("X", secondary_index::key_types::F32); t.create_secondary_index("Y", secondary_index::key_types::F32);
random_line_split
main.rs
#![feature(plugin)] #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; mod primary_index; mod secondary_index; mod table; mod find; use std::fs::File; use std::io::Read; use serde_json::{Value, Error}; fn main()
println!("Get by id 333 {:?}, has an index of {:?}", t.get(333), t.get(333).get_id()); println!("Search index {:?}", t.secondary_indexes[0].get("TEST", "TEST2")); println!("{}", t.table_name); } fn load_dummy_data(t:&mut table::Table) { // load json from thing let mut s = String::new(); File::open("data.json").unwrap().read_to_string(&mut s).unwrap(); let n:Vec<serde_json::Value> = serde_json::from_str(&s).unwrap(); for item in n.into_iter() { t.insert(&item.to_string()); //println!("{:?}", item.to_string()); } }
{ let db_path = "/data/testdb"; let mut t = table::Table::new("test_table", db_path); t.create_secondary_index("Type", secondary_index::key_types::Str(20)); t.create_secondary_index("Name", secondary_index::key_types::Str(128)); t.create_secondary_index("X", secondary_index::key_types::F32); t.create_secondary_index("Y", secondary_index::key_types::F32); // load_dummy_data(&mut t); println!("Get by id 3 {:?}", t.get(3)); println!("Get by id 4 {:?}", t.get(4)); println!("Get by id 33 {:?}", t.get(33));
identifier_body
browsingcontext.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::conversions::{ToJSValConvertible, root_from_handleobject}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference}; use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor}; use dom::bindings::reflector::{Reflectable, MutReflectable, Reflector}; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::WindowProxyHandler; use dom::bindings::utils::get_array_index_from_id; use dom::document::Document; use dom::element::Element; use dom::globalscope::GlobalScope; use dom::window::Window; use js::JSCLASS_IS_GLOBAL; use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy}; use js::glue::{GetProxyPrivate, SetProxyExtra, GetProxyExtra}; use js::jsapi::{Handle, HandleId, HandleObject, HandleValue}; use js::jsapi::{JSAutoCompartment, JSContext, JSErrNum, JSFreeOp, JSObject}; use js::jsapi::{JSPROP_READONLY, JSTracer, JS_DefinePropertyById}; use js::jsapi::{JS_ForwardGetPropertyTo, JS_ForwardSetPropertyTo}; use js::jsapi::{JS_GetOwnPropertyDescriptorById, JS_HasPropertyById}; use js::jsapi::{MutableHandle, MutableHandleObject, MutableHandleValue}; use js::jsapi::{ObjectOpResult, PropertyDescriptor}; use js::jsval::{UndefinedValue, PrivateValue}; use js::rust::get_object_class; use msg::constellation_msg::PipelineId; use std::cell::Cell; #[dom_struct] // NOTE: the browsing context for a window is managed in two places: // here, in script, but also in the constellation. The constellation // manages the session history, which in script is accessed through // History objects, messaging the constellation. pub struct BrowsingContext { reflector: Reflector, /// Indicates if reflow is required when reloading. needs_reflow: Cell<bool>, /// The current active document. /// Note that the session history is stored in the constellation, /// in the script thread we just track the current active document. active_document: MutNullableHeap<JS<Document>>, /// The containing iframe element, if this is a same-origin iframe frame_element: Option<JS<Element>>, } impl BrowsingContext { pub fn new_inherited(frame_element: Option<&Element>) -> BrowsingContext { BrowsingContext { reflector: Reflector::new(), needs_reflow: Cell::new(true), active_document: Default::default(), frame_element: frame_element.map(JS::from_ref), } } #[allow(unsafe_code)] pub fn new(window: &Window, frame_element: Option<&Element>) -> Root<BrowsingContext> { unsafe { let WindowProxyHandler(handler) = window.windowproxy_handler(); assert!(!handler.is_null()); let cx = window.get_cx(); let parent = window.reflector().get_jsobject(); assert!(!parent.get().is_null()); assert!(((*get_object_class(parent.get())).flags & JSCLASS_IS_GLOBAL)!= 0); let _ac = JSAutoCompartment::new(cx, parent.get()); rooted!(in(cx) let window_proxy = NewWindowProxy(cx, parent, handler)); assert!(!window_proxy.is_null()); let object = box BrowsingContext::new_inherited(frame_element); let raw = Box::into_raw(object); SetProxyExtra(window_proxy.get(), 0, &PrivateValue(raw as *const _)); (*raw).init_reflector(window_proxy.get()); Root::from_ref(&*raw) } } pub fn set_active_document(&self, document: &Document) { self.active_document.set(Some(document)) } pub fn active_document(&self) -> Root<Document> { self.active_document.get().expect("No active document.") } pub fn maybe_active_document(&self) -> Option<Root<Document>> { self.active_document.get() } pub fn active_window(&self) -> Root<Window> { Root::from_ref(self.active_document().window()) } pub fn frame_element(&self) -> Option<&Element> { self.frame_element.r() } pub fn window_proxy(&self) -> *mut JSObject { let window_proxy = self.reflector.get_jsobject(); assert!(!window_proxy.get().is_null()); window_proxy.get() } pub fn set_reflow_status(&self, status: bool) -> bool { let old = self.needs_reflow.get(); self.needs_reflow.set(status); old } pub fn active_pipeline_id(&self) -> Option<PipelineId> { self.active_document.get() .map(|doc| doc.window().upcast::<GlobalScope>().pipeline_id()) } pub fn
(&self) { self.active_document.set(None) } } #[allow(unsafe_code)] unsafe fn GetSubframeWindow(cx: *mut JSContext, proxy: HandleObject, id: HandleId) -> Option<Root<Window>> { let index = get_array_index_from_id(cx, id); if let Some(index) = index { rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); let win = root_from_handleobject::<Window>(target.handle()).unwrap(); let mut found = false; return win.IndexedGetter(index, &mut found); } None } #[allow(unsafe_code)] unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut JSContext, proxy: HandleObject, id: HandleId, mut desc: MutableHandle<PropertyDescriptor>) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { rooted!(in(cx) let mut val = UndefinedValue()); window.to_jsval(cx, val.handle_mut()); desc.value = val.get(); fill_property_descriptor(desc, proxy.get(), JSPROP_READONLY); return true; } rooted!(in(cx) let target = GetProxyPrivate(proxy.get()).to_object()); if!JS_GetOwnPropertyDescriptorById(cx, target.handle(), id, desc) { return false; } assert!(desc.obj.is_null() || desc.obj == target.get()); if desc.obj == target.get() { // FIXME(#11868) Should assign to desc.obj, desc.get() is a copy. desc.get().obj = proxy.get(); } true } #[allow(unsafe_code)] unsafe extern "C" fn defineProperty(cx: *mut JSContext, proxy: HandleObject, id: HandleId, desc: Handle<PropertyDescriptor>, res: *mut ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Spec says to Reject whether this is a supported index or not, // since we have no indexed setter or indexed creator. That means // throwing in strict mode (FIXME: Bug 828137), doing nothing in // non-strict mode. (*res).code_ = JSErrNum::JSMSG_CANT_DEFINE_WINDOW_ELEMENT as ::libc::uintptr_t; return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); JS_DefinePropertyById(cx, target.handle(), id, desc, res) } #[allow(unsafe_code)] unsafe extern "C" fn has(cx: *mut JSContext, proxy: HandleObject, id: HandleId, bp: *mut bool) -> bool { let window = GetSubframeWindow(cx, proxy, id); if window.is_some() { *bp = true; return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); let mut found = false; if!JS_HasPropertyById(cx, target.handle(), id, &mut found) { return false; } *bp = found; true } #[allow(unsafe_code)] unsafe extern "C" fn get(cx: *mut JSContext, proxy: HandleObject, receiver: HandleValue, id: HandleId, vp: MutableHandleValue) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { window.to_jsval(cx, vp); return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); JS_ForwardGetPropertyTo(cx, target.handle(), id, receiver, vp) } #[allow(unsafe_code)] unsafe extern "C" fn set(cx: *mut JSContext, proxy: HandleObject, id: HandleId, v: HandleValue, receiver: HandleValue, res: *mut ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Reject (which means throw if and only if strict) the set. (*res).code_ = JSErrNum::JSMSG_READ_ONLY as ::libc::uintptr_t; return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); JS_ForwardSetPropertyTo(cx, target.handle(), id, v, receiver, res) } #[allow(unsafe_code)] unsafe extern "C" fn get_prototype_if_ordinary(_: *mut JSContext, _: HandleObject, is_ordinary: *mut bool, _: MutableHandleObject) -> bool { // Window's [[GetPrototypeOf]] trap isn't the ordinary definition: // // https://html.spec.whatwg.org/multipage/#windowproxy-getprototypeof // // We nonetheless can implement it with a static [[Prototype]], because // wrapper-class handlers (particularly, XOW in FilteringWrapper.cpp) supply // all non-ordinary behavior. // // But from a spec point of view, it's the exact same object in both cases -- // only the observer's changed. So this getPrototypeIfOrdinary trap on the // non-wrapper object *must* report non-ordinary, even if static [[Prototype]] // usually means ordinary. *is_ordinary = false; return true; } static PROXY_HANDLER: ProxyTraps = ProxyTraps { enter: None, getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor), defineProperty: Some(defineProperty), ownPropertyKeys: None, delete_: None, enumerate: None, getPrototypeIfOrdinary: Some(get_prototype_if_ordinary), preventExtensions: None, isExtensible: None, has: Some(has), get: Some(get), set: Some(set), call: None, construct: None, getPropertyDescriptor: Some(get_property_descriptor), hasOwn: None, getOwnEnumerablePropertyKeys: None, nativeCall: None, hasInstance: None, objectClassIs: None, className: None, fun_toString: None, boxedValue_unbox: None, defaultValue: None, trace: Some(trace), finalize: Some(finalize), objectMoved: None, isCallable: None, isConstructor: None, }; #[allow(unsafe_code)] unsafe extern fn finalize(_fop: *mut JSFreeOp, obj: *mut JSObject) { let this = GetProxyExtra(obj, 0).to_private() as *mut BrowsingContext; assert!(!this.is_null()); let _ = Box::from_raw(this); debug!("BrowsingContext finalize: {:p}", this); } #[allow(unsafe_code)] unsafe extern fn trace(trc: *mut JSTracer, obj: *mut JSObject) { let this = GetProxyExtra(obj, 0).to_private() as *const BrowsingContext; if this.is_null() { // GC during obj creation return; } (*this).trace(trc); } #[allow(unsafe_code)] pub fn new_window_proxy_handler() -> WindowProxyHandler { unsafe { WindowProxyHandler(CreateWrapperProxyHandler(&PROXY_HANDLER)) } }
unset_active_document
identifier_name
browsingcontext.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::conversions::{ToJSValConvertible, root_from_handleobject}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference}; use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor}; use dom::bindings::reflector::{Reflectable, MutReflectable, Reflector}; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::WindowProxyHandler; use dom::bindings::utils::get_array_index_from_id; use dom::document::Document; use dom::element::Element; use dom::globalscope::GlobalScope; use dom::window::Window; use js::JSCLASS_IS_GLOBAL; use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy}; use js::glue::{GetProxyPrivate, SetProxyExtra, GetProxyExtra}; use js::jsapi::{Handle, HandleId, HandleObject, HandleValue}; use js::jsapi::{JSAutoCompartment, JSContext, JSErrNum, JSFreeOp, JSObject}; use js::jsapi::{JSPROP_READONLY, JSTracer, JS_DefinePropertyById}; use js::jsapi::{JS_ForwardGetPropertyTo, JS_ForwardSetPropertyTo}; use js::jsapi::{JS_GetOwnPropertyDescriptorById, JS_HasPropertyById}; use js::jsapi::{MutableHandle, MutableHandleObject, MutableHandleValue}; use js::jsapi::{ObjectOpResult, PropertyDescriptor}; use js::jsval::{UndefinedValue, PrivateValue}; use js::rust::get_object_class; use msg::constellation_msg::PipelineId; use std::cell::Cell; #[dom_struct] // NOTE: the browsing context for a window is managed in two places: // here, in script, but also in the constellation. The constellation // manages the session history, which in script is accessed through // History objects, messaging the constellation. pub struct BrowsingContext { reflector: Reflector, /// Indicates if reflow is required when reloading. needs_reflow: Cell<bool>, /// The current active document. /// Note that the session history is stored in the constellation, /// in the script thread we just track the current active document. active_document: MutNullableHeap<JS<Document>>, /// The containing iframe element, if this is a same-origin iframe frame_element: Option<JS<Element>>, } impl BrowsingContext { pub fn new_inherited(frame_element: Option<&Element>) -> BrowsingContext { BrowsingContext { reflector: Reflector::new(), needs_reflow: Cell::new(true), active_document: Default::default(), frame_element: frame_element.map(JS::from_ref), } } #[allow(unsafe_code)] pub fn new(window: &Window, frame_element: Option<&Element>) -> Root<BrowsingContext> { unsafe { let WindowProxyHandler(handler) = window.windowproxy_handler(); assert!(!handler.is_null()); let cx = window.get_cx(); let parent = window.reflector().get_jsobject(); assert!(!parent.get().is_null()); assert!(((*get_object_class(parent.get())).flags & JSCLASS_IS_GLOBAL)!= 0); let _ac = JSAutoCompartment::new(cx, parent.get()); rooted!(in(cx) let window_proxy = NewWindowProxy(cx, parent, handler)); assert!(!window_proxy.is_null()); let object = box BrowsingContext::new_inherited(frame_element); let raw = Box::into_raw(object); SetProxyExtra(window_proxy.get(), 0, &PrivateValue(raw as *const _)); (*raw).init_reflector(window_proxy.get()); Root::from_ref(&*raw) } } pub fn set_active_document(&self, document: &Document) { self.active_document.set(Some(document)) } pub fn active_document(&self) -> Root<Document> { self.active_document.get().expect("No active document.") } pub fn maybe_active_document(&self) -> Option<Root<Document>> { self.active_document.get() } pub fn active_window(&self) -> Root<Window> { Root::from_ref(self.active_document().window()) } pub fn frame_element(&self) -> Option<&Element> { self.frame_element.r() } pub fn window_proxy(&self) -> *mut JSObject { let window_proxy = self.reflector.get_jsobject(); assert!(!window_proxy.get().is_null()); window_proxy.get() } pub fn set_reflow_status(&self, status: bool) -> bool { let old = self.needs_reflow.get(); self.needs_reflow.set(status); old } pub fn active_pipeline_id(&self) -> Option<PipelineId> { self.active_document.get() .map(|doc| doc.window().upcast::<GlobalScope>().pipeline_id()) } pub fn unset_active_document(&self) { self.active_document.set(None) } } #[allow(unsafe_code)] unsafe fn GetSubframeWindow(cx: *mut JSContext, proxy: HandleObject, id: HandleId) -> Option<Root<Window>> { let index = get_array_index_from_id(cx, id); if let Some(index) = index { rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); let win = root_from_handleobject::<Window>(target.handle()).unwrap(); let mut found = false; return win.IndexedGetter(index, &mut found); } None } #[allow(unsafe_code)] unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut JSContext, proxy: HandleObject, id: HandleId, mut desc: MutableHandle<PropertyDescriptor>) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { rooted!(in(cx) let mut val = UndefinedValue()); window.to_jsval(cx, val.handle_mut()); desc.value = val.get(); fill_property_descriptor(desc, proxy.get(), JSPROP_READONLY); return true; } rooted!(in(cx) let target = GetProxyPrivate(proxy.get()).to_object()); if!JS_GetOwnPropertyDescriptorById(cx, target.handle(), id, desc) { return false; } assert!(desc.obj.is_null() || desc.obj == target.get()); if desc.obj == target.get() { // FIXME(#11868) Should assign to desc.obj, desc.get() is a copy. desc.get().obj = proxy.get(); } true } #[allow(unsafe_code)] unsafe extern "C" fn defineProperty(cx: *mut JSContext, proxy: HandleObject, id: HandleId, desc: Handle<PropertyDescriptor>, res: *mut ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Spec says to Reject whether this is a supported index or not, // since we have no indexed setter or indexed creator. That means // throwing in strict mode (FIXME: Bug 828137), doing nothing in // non-strict mode. (*res).code_ = JSErrNum::JSMSG_CANT_DEFINE_WINDOW_ELEMENT as ::libc::uintptr_t; return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); JS_DefinePropertyById(cx, target.handle(), id, desc, res) } #[allow(unsafe_code)] unsafe extern "C" fn has(cx: *mut JSContext, proxy: HandleObject, id: HandleId, bp: *mut bool) -> bool { let window = GetSubframeWindow(cx, proxy, id); if window.is_some() { *bp = true; return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); let mut found = false; if!JS_HasPropertyById(cx, target.handle(), id, &mut found) { return false; } *bp = found; true } #[allow(unsafe_code)] unsafe extern "C" fn get(cx: *mut JSContext, proxy: HandleObject, receiver: HandleValue, id: HandleId, vp: MutableHandleValue) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { window.to_jsval(cx, vp); return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); JS_ForwardGetPropertyTo(cx, target.handle(), id, receiver, vp) }
#[allow(unsafe_code)] unsafe extern "C" fn set(cx: *mut JSContext, proxy: HandleObject, id: HandleId, v: HandleValue, receiver: HandleValue, res: *mut ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Reject (which means throw if and only if strict) the set. (*res).code_ = JSErrNum::JSMSG_READ_ONLY as ::libc::uintptr_t; return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); JS_ForwardSetPropertyTo(cx, target.handle(), id, v, receiver, res) } #[allow(unsafe_code)] unsafe extern "C" fn get_prototype_if_ordinary(_: *mut JSContext, _: HandleObject, is_ordinary: *mut bool, _: MutableHandleObject) -> bool { // Window's [[GetPrototypeOf]] trap isn't the ordinary definition: // // https://html.spec.whatwg.org/multipage/#windowproxy-getprototypeof // // We nonetheless can implement it with a static [[Prototype]], because // wrapper-class handlers (particularly, XOW in FilteringWrapper.cpp) supply // all non-ordinary behavior. // // But from a spec point of view, it's the exact same object in both cases -- // only the observer's changed. So this getPrototypeIfOrdinary trap on the // non-wrapper object *must* report non-ordinary, even if static [[Prototype]] // usually means ordinary. *is_ordinary = false; return true; } static PROXY_HANDLER: ProxyTraps = ProxyTraps { enter: None, getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor), defineProperty: Some(defineProperty), ownPropertyKeys: None, delete_: None, enumerate: None, getPrototypeIfOrdinary: Some(get_prototype_if_ordinary), preventExtensions: None, isExtensible: None, has: Some(has), get: Some(get), set: Some(set), call: None, construct: None, getPropertyDescriptor: Some(get_property_descriptor), hasOwn: None, getOwnEnumerablePropertyKeys: None, nativeCall: None, hasInstance: None, objectClassIs: None, className: None, fun_toString: None, boxedValue_unbox: None, defaultValue: None, trace: Some(trace), finalize: Some(finalize), objectMoved: None, isCallable: None, isConstructor: None, }; #[allow(unsafe_code)] unsafe extern fn finalize(_fop: *mut JSFreeOp, obj: *mut JSObject) { let this = GetProxyExtra(obj, 0).to_private() as *mut BrowsingContext; assert!(!this.is_null()); let _ = Box::from_raw(this); debug!("BrowsingContext finalize: {:p}", this); } #[allow(unsafe_code)] unsafe extern fn trace(trc: *mut JSTracer, obj: *mut JSObject) { let this = GetProxyExtra(obj, 0).to_private() as *const BrowsingContext; if this.is_null() { // GC during obj creation return; } (*this).trace(trc); } #[allow(unsafe_code)] pub fn new_window_proxy_handler() -> WindowProxyHandler { unsafe { WindowProxyHandler(CreateWrapperProxyHandler(&PROXY_HANDLER)) } }
random_line_split
browsingcontext.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::conversions::{ToJSValConvertible, root_from_handleobject}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference}; use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor}; use dom::bindings::reflector::{Reflectable, MutReflectable, Reflector}; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::WindowProxyHandler; use dom::bindings::utils::get_array_index_from_id; use dom::document::Document; use dom::element::Element; use dom::globalscope::GlobalScope; use dom::window::Window; use js::JSCLASS_IS_GLOBAL; use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy}; use js::glue::{GetProxyPrivate, SetProxyExtra, GetProxyExtra}; use js::jsapi::{Handle, HandleId, HandleObject, HandleValue}; use js::jsapi::{JSAutoCompartment, JSContext, JSErrNum, JSFreeOp, JSObject}; use js::jsapi::{JSPROP_READONLY, JSTracer, JS_DefinePropertyById}; use js::jsapi::{JS_ForwardGetPropertyTo, JS_ForwardSetPropertyTo}; use js::jsapi::{JS_GetOwnPropertyDescriptorById, JS_HasPropertyById}; use js::jsapi::{MutableHandle, MutableHandleObject, MutableHandleValue}; use js::jsapi::{ObjectOpResult, PropertyDescriptor}; use js::jsval::{UndefinedValue, PrivateValue}; use js::rust::get_object_class; use msg::constellation_msg::PipelineId; use std::cell::Cell; #[dom_struct] // NOTE: the browsing context for a window is managed in two places: // here, in script, but also in the constellation. The constellation // manages the session history, which in script is accessed through // History objects, messaging the constellation. pub struct BrowsingContext { reflector: Reflector, /// Indicates if reflow is required when reloading. needs_reflow: Cell<bool>, /// The current active document. /// Note that the session history is stored in the constellation, /// in the script thread we just track the current active document. active_document: MutNullableHeap<JS<Document>>, /// The containing iframe element, if this is a same-origin iframe frame_element: Option<JS<Element>>, } impl BrowsingContext { pub fn new_inherited(frame_element: Option<&Element>) -> BrowsingContext { BrowsingContext { reflector: Reflector::new(), needs_reflow: Cell::new(true), active_document: Default::default(), frame_element: frame_element.map(JS::from_ref), } } #[allow(unsafe_code)] pub fn new(window: &Window, frame_element: Option<&Element>) -> Root<BrowsingContext> { unsafe { let WindowProxyHandler(handler) = window.windowproxy_handler(); assert!(!handler.is_null()); let cx = window.get_cx(); let parent = window.reflector().get_jsobject(); assert!(!parent.get().is_null()); assert!(((*get_object_class(parent.get())).flags & JSCLASS_IS_GLOBAL)!= 0); let _ac = JSAutoCompartment::new(cx, parent.get()); rooted!(in(cx) let window_proxy = NewWindowProxy(cx, parent, handler)); assert!(!window_proxy.is_null()); let object = box BrowsingContext::new_inherited(frame_element); let raw = Box::into_raw(object); SetProxyExtra(window_proxy.get(), 0, &PrivateValue(raw as *const _)); (*raw).init_reflector(window_proxy.get()); Root::from_ref(&*raw) } } pub fn set_active_document(&self, document: &Document) { self.active_document.set(Some(document)) } pub fn active_document(&self) -> Root<Document> { self.active_document.get().expect("No active document.") } pub fn maybe_active_document(&self) -> Option<Root<Document>> { self.active_document.get() } pub fn active_window(&self) -> Root<Window> { Root::from_ref(self.active_document().window()) } pub fn frame_element(&self) -> Option<&Element> { self.frame_element.r() } pub fn window_proxy(&self) -> *mut JSObject { let window_proxy = self.reflector.get_jsobject(); assert!(!window_proxy.get().is_null()); window_proxy.get() } pub fn set_reflow_status(&self, status: bool) -> bool { let old = self.needs_reflow.get(); self.needs_reflow.set(status); old } pub fn active_pipeline_id(&self) -> Option<PipelineId> { self.active_document.get() .map(|doc| doc.window().upcast::<GlobalScope>().pipeline_id()) } pub fn unset_active_document(&self) { self.active_document.set(None) } } #[allow(unsafe_code)] unsafe fn GetSubframeWindow(cx: *mut JSContext, proxy: HandleObject, id: HandleId) -> Option<Root<Window>> { let index = get_array_index_from_id(cx, id); if let Some(index) = index
None } #[allow(unsafe_code)] unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut JSContext, proxy: HandleObject, id: HandleId, mut desc: MutableHandle<PropertyDescriptor>) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { rooted!(in(cx) let mut val = UndefinedValue()); window.to_jsval(cx, val.handle_mut()); desc.value = val.get(); fill_property_descriptor(desc, proxy.get(), JSPROP_READONLY); return true; } rooted!(in(cx) let target = GetProxyPrivate(proxy.get()).to_object()); if!JS_GetOwnPropertyDescriptorById(cx, target.handle(), id, desc) { return false; } assert!(desc.obj.is_null() || desc.obj == target.get()); if desc.obj == target.get() { // FIXME(#11868) Should assign to desc.obj, desc.get() is a copy. desc.get().obj = proxy.get(); } true } #[allow(unsafe_code)] unsafe extern "C" fn defineProperty(cx: *mut JSContext, proxy: HandleObject, id: HandleId, desc: Handle<PropertyDescriptor>, res: *mut ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Spec says to Reject whether this is a supported index or not, // since we have no indexed setter or indexed creator. That means // throwing in strict mode (FIXME: Bug 828137), doing nothing in // non-strict mode. (*res).code_ = JSErrNum::JSMSG_CANT_DEFINE_WINDOW_ELEMENT as ::libc::uintptr_t; return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); JS_DefinePropertyById(cx, target.handle(), id, desc, res) } #[allow(unsafe_code)] unsafe extern "C" fn has(cx: *mut JSContext, proxy: HandleObject, id: HandleId, bp: *mut bool) -> bool { let window = GetSubframeWindow(cx, proxy, id); if window.is_some() { *bp = true; return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); let mut found = false; if!JS_HasPropertyById(cx, target.handle(), id, &mut found) { return false; } *bp = found; true } #[allow(unsafe_code)] unsafe extern "C" fn get(cx: *mut JSContext, proxy: HandleObject, receiver: HandleValue, id: HandleId, vp: MutableHandleValue) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { window.to_jsval(cx, vp); return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); JS_ForwardGetPropertyTo(cx, target.handle(), id, receiver, vp) } #[allow(unsafe_code)] unsafe extern "C" fn set(cx: *mut JSContext, proxy: HandleObject, id: HandleId, v: HandleValue, receiver: HandleValue, res: *mut ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Reject (which means throw if and only if strict) the set. (*res).code_ = JSErrNum::JSMSG_READ_ONLY as ::libc::uintptr_t; return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); JS_ForwardSetPropertyTo(cx, target.handle(), id, v, receiver, res) } #[allow(unsafe_code)] unsafe extern "C" fn get_prototype_if_ordinary(_: *mut JSContext, _: HandleObject, is_ordinary: *mut bool, _: MutableHandleObject) -> bool { // Window's [[GetPrototypeOf]] trap isn't the ordinary definition: // // https://html.spec.whatwg.org/multipage/#windowproxy-getprototypeof // // We nonetheless can implement it with a static [[Prototype]], because // wrapper-class handlers (particularly, XOW in FilteringWrapper.cpp) supply // all non-ordinary behavior. // // But from a spec point of view, it's the exact same object in both cases -- // only the observer's changed. So this getPrototypeIfOrdinary trap on the // non-wrapper object *must* report non-ordinary, even if static [[Prototype]] // usually means ordinary. *is_ordinary = false; return true; } static PROXY_HANDLER: ProxyTraps = ProxyTraps { enter: None, getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor), defineProperty: Some(defineProperty), ownPropertyKeys: None, delete_: None, enumerate: None, getPrototypeIfOrdinary: Some(get_prototype_if_ordinary), preventExtensions: None, isExtensible: None, has: Some(has), get: Some(get), set: Some(set), call: None, construct: None, getPropertyDescriptor: Some(get_property_descriptor), hasOwn: None, getOwnEnumerablePropertyKeys: None, nativeCall: None, hasInstance: None, objectClassIs: None, className: None, fun_toString: None, boxedValue_unbox: None, defaultValue: None, trace: Some(trace), finalize: Some(finalize), objectMoved: None, isCallable: None, isConstructor: None, }; #[allow(unsafe_code)] unsafe extern fn finalize(_fop: *mut JSFreeOp, obj: *mut JSObject) { let this = GetProxyExtra(obj, 0).to_private() as *mut BrowsingContext; assert!(!this.is_null()); let _ = Box::from_raw(this); debug!("BrowsingContext finalize: {:p}", this); } #[allow(unsafe_code)] unsafe extern fn trace(trc: *mut JSTracer, obj: *mut JSObject) { let this = GetProxyExtra(obj, 0).to_private() as *const BrowsingContext; if this.is_null() { // GC during obj creation return; } (*this).trace(trc); } #[allow(unsafe_code)] pub fn new_window_proxy_handler() -> WindowProxyHandler { unsafe { WindowProxyHandler(CreateWrapperProxyHandler(&PROXY_HANDLER)) } }
{ rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); let win = root_from_handleobject::<Window>(target.handle()).unwrap(); let mut found = false; return win.IndexedGetter(index, &mut found); }
conditional_block
browsingcontext.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::conversions::{ToJSValConvertible, root_from_handleobject}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference}; use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor}; use dom::bindings::reflector::{Reflectable, MutReflectable, Reflector}; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::WindowProxyHandler; use dom::bindings::utils::get_array_index_from_id; use dom::document::Document; use dom::element::Element; use dom::globalscope::GlobalScope; use dom::window::Window; use js::JSCLASS_IS_GLOBAL; use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy}; use js::glue::{GetProxyPrivate, SetProxyExtra, GetProxyExtra}; use js::jsapi::{Handle, HandleId, HandleObject, HandleValue}; use js::jsapi::{JSAutoCompartment, JSContext, JSErrNum, JSFreeOp, JSObject}; use js::jsapi::{JSPROP_READONLY, JSTracer, JS_DefinePropertyById}; use js::jsapi::{JS_ForwardGetPropertyTo, JS_ForwardSetPropertyTo}; use js::jsapi::{JS_GetOwnPropertyDescriptorById, JS_HasPropertyById}; use js::jsapi::{MutableHandle, MutableHandleObject, MutableHandleValue}; use js::jsapi::{ObjectOpResult, PropertyDescriptor}; use js::jsval::{UndefinedValue, PrivateValue}; use js::rust::get_object_class; use msg::constellation_msg::PipelineId; use std::cell::Cell; #[dom_struct] // NOTE: the browsing context for a window is managed in two places: // here, in script, but also in the constellation. The constellation // manages the session history, which in script is accessed through // History objects, messaging the constellation. pub struct BrowsingContext { reflector: Reflector, /// Indicates if reflow is required when reloading. needs_reflow: Cell<bool>, /// The current active document. /// Note that the session history is stored in the constellation, /// in the script thread we just track the current active document. active_document: MutNullableHeap<JS<Document>>, /// The containing iframe element, if this is a same-origin iframe frame_element: Option<JS<Element>>, } impl BrowsingContext { pub fn new_inherited(frame_element: Option<&Element>) -> BrowsingContext { BrowsingContext { reflector: Reflector::new(), needs_reflow: Cell::new(true), active_document: Default::default(), frame_element: frame_element.map(JS::from_ref), } } #[allow(unsafe_code)] pub fn new(window: &Window, frame_element: Option<&Element>) -> Root<BrowsingContext> { unsafe { let WindowProxyHandler(handler) = window.windowproxy_handler(); assert!(!handler.is_null()); let cx = window.get_cx(); let parent = window.reflector().get_jsobject(); assert!(!parent.get().is_null()); assert!(((*get_object_class(parent.get())).flags & JSCLASS_IS_GLOBAL)!= 0); let _ac = JSAutoCompartment::new(cx, parent.get()); rooted!(in(cx) let window_proxy = NewWindowProxy(cx, parent, handler)); assert!(!window_proxy.is_null()); let object = box BrowsingContext::new_inherited(frame_element); let raw = Box::into_raw(object); SetProxyExtra(window_proxy.get(), 0, &PrivateValue(raw as *const _)); (*raw).init_reflector(window_proxy.get()); Root::from_ref(&*raw) } } pub fn set_active_document(&self, document: &Document) { self.active_document.set(Some(document)) } pub fn active_document(&self) -> Root<Document> { self.active_document.get().expect("No active document.") } pub fn maybe_active_document(&self) -> Option<Root<Document>>
pub fn active_window(&self) -> Root<Window> { Root::from_ref(self.active_document().window()) } pub fn frame_element(&self) -> Option<&Element> { self.frame_element.r() } pub fn window_proxy(&self) -> *mut JSObject { let window_proxy = self.reflector.get_jsobject(); assert!(!window_proxy.get().is_null()); window_proxy.get() } pub fn set_reflow_status(&self, status: bool) -> bool { let old = self.needs_reflow.get(); self.needs_reflow.set(status); old } pub fn active_pipeline_id(&self) -> Option<PipelineId> { self.active_document.get() .map(|doc| doc.window().upcast::<GlobalScope>().pipeline_id()) } pub fn unset_active_document(&self) { self.active_document.set(None) } } #[allow(unsafe_code)] unsafe fn GetSubframeWindow(cx: *mut JSContext, proxy: HandleObject, id: HandleId) -> Option<Root<Window>> { let index = get_array_index_from_id(cx, id); if let Some(index) = index { rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); let win = root_from_handleobject::<Window>(target.handle()).unwrap(); let mut found = false; return win.IndexedGetter(index, &mut found); } None } #[allow(unsafe_code)] unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut JSContext, proxy: HandleObject, id: HandleId, mut desc: MutableHandle<PropertyDescriptor>) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { rooted!(in(cx) let mut val = UndefinedValue()); window.to_jsval(cx, val.handle_mut()); desc.value = val.get(); fill_property_descriptor(desc, proxy.get(), JSPROP_READONLY); return true; } rooted!(in(cx) let target = GetProxyPrivate(proxy.get()).to_object()); if!JS_GetOwnPropertyDescriptorById(cx, target.handle(), id, desc) { return false; } assert!(desc.obj.is_null() || desc.obj == target.get()); if desc.obj == target.get() { // FIXME(#11868) Should assign to desc.obj, desc.get() is a copy. desc.get().obj = proxy.get(); } true } #[allow(unsafe_code)] unsafe extern "C" fn defineProperty(cx: *mut JSContext, proxy: HandleObject, id: HandleId, desc: Handle<PropertyDescriptor>, res: *mut ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Spec says to Reject whether this is a supported index or not, // since we have no indexed setter or indexed creator. That means // throwing in strict mode (FIXME: Bug 828137), doing nothing in // non-strict mode. (*res).code_ = JSErrNum::JSMSG_CANT_DEFINE_WINDOW_ELEMENT as ::libc::uintptr_t; return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); JS_DefinePropertyById(cx, target.handle(), id, desc, res) } #[allow(unsafe_code)] unsafe extern "C" fn has(cx: *mut JSContext, proxy: HandleObject, id: HandleId, bp: *mut bool) -> bool { let window = GetSubframeWindow(cx, proxy, id); if window.is_some() { *bp = true; return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); let mut found = false; if!JS_HasPropertyById(cx, target.handle(), id, &mut found) { return false; } *bp = found; true } #[allow(unsafe_code)] unsafe extern "C" fn get(cx: *mut JSContext, proxy: HandleObject, receiver: HandleValue, id: HandleId, vp: MutableHandleValue) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { window.to_jsval(cx, vp); return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); JS_ForwardGetPropertyTo(cx, target.handle(), id, receiver, vp) } #[allow(unsafe_code)] unsafe extern "C" fn set(cx: *mut JSContext, proxy: HandleObject, id: HandleId, v: HandleValue, receiver: HandleValue, res: *mut ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Reject (which means throw if and only if strict) the set. (*res).code_ = JSErrNum::JSMSG_READ_ONLY as ::libc::uintptr_t; return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); JS_ForwardSetPropertyTo(cx, target.handle(), id, v, receiver, res) } #[allow(unsafe_code)] unsafe extern "C" fn get_prototype_if_ordinary(_: *mut JSContext, _: HandleObject, is_ordinary: *mut bool, _: MutableHandleObject) -> bool { // Window's [[GetPrototypeOf]] trap isn't the ordinary definition: // // https://html.spec.whatwg.org/multipage/#windowproxy-getprototypeof // // We nonetheless can implement it with a static [[Prototype]], because // wrapper-class handlers (particularly, XOW in FilteringWrapper.cpp) supply // all non-ordinary behavior. // // But from a spec point of view, it's the exact same object in both cases -- // only the observer's changed. So this getPrototypeIfOrdinary trap on the // non-wrapper object *must* report non-ordinary, even if static [[Prototype]] // usually means ordinary. *is_ordinary = false; return true; } static PROXY_HANDLER: ProxyTraps = ProxyTraps { enter: None, getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor), defineProperty: Some(defineProperty), ownPropertyKeys: None, delete_: None, enumerate: None, getPrototypeIfOrdinary: Some(get_prototype_if_ordinary), preventExtensions: None, isExtensible: None, has: Some(has), get: Some(get), set: Some(set), call: None, construct: None, getPropertyDescriptor: Some(get_property_descriptor), hasOwn: None, getOwnEnumerablePropertyKeys: None, nativeCall: None, hasInstance: None, objectClassIs: None, className: None, fun_toString: None, boxedValue_unbox: None, defaultValue: None, trace: Some(trace), finalize: Some(finalize), objectMoved: None, isCallable: None, isConstructor: None, }; #[allow(unsafe_code)] unsafe extern fn finalize(_fop: *mut JSFreeOp, obj: *mut JSObject) { let this = GetProxyExtra(obj, 0).to_private() as *mut BrowsingContext; assert!(!this.is_null()); let _ = Box::from_raw(this); debug!("BrowsingContext finalize: {:p}", this); } #[allow(unsafe_code)] unsafe extern fn trace(trc: *mut JSTracer, obj: *mut JSObject) { let this = GetProxyExtra(obj, 0).to_private() as *const BrowsingContext; if this.is_null() { // GC during obj creation return; } (*this).trace(trc); } #[allow(unsafe_code)] pub fn new_window_proxy_handler() -> WindowProxyHandler { unsafe { WindowProxyHandler(CreateWrapperProxyHandler(&PROXY_HANDLER)) } }
{ self.active_document.get() }
identifier_body
cow.rs
#![allow(unused_imports)] use geometry::prim::{Prim}; use geometry::prims::{Plane, Sphere, Triangle}; use light::light::{Light}; use light::lights::{PointLight, SphereLight}; use material::materials::{CookTorranceMaterial, FlatMaterial, PhongMaterial}; use material::Texture; use material::textures::{CheckerTexture, CubeMap, UVTexture, ImageTexture}; use raytracer::animator::CameraKeyframe; use scene::{Camera, Scene}; use vec3::Vec3; // 5000 polys, cow. Octree helps. pub fn get_camera(image_width: u32, image_height: u32, fov: f64) -> Camera { Camera::new( Vec3 { x: -2.0, y: 4.0, z: 10.0 }, Vec3 { x: 0.0, y: 0.0, z: 0.0 }, Vec3 { x: 0.0, y: 1.0, z: 0.0 }, fov, image_width, image_height ) } pub fn get_scene() -> Scene
skybox: None } }
{ let mut lights: Vec<Box<Light+Send+Sync>> = Vec::new(); lights.push(Box::new(SphereLight { position: Vec3 {x: 3.0, y: 10.0, z: 6.0}, color: Vec3::one(), radius: 5.0 })); let red = CookTorranceMaterial { k_a: 0.0, k_d: 0.6, k_s: 1.0, k_sg: 0.2, k_tg: 0.0, gauss_constant: 30.0, roughness: 0.1, glossiness: 0.0, ior: 0.8, ambient: Vec3::one(), diffuse: Vec3 { x: 1.0, y: 0.25, z: 0.1 }, specular: Vec3::one(), transmission: Vec3::zero(), diffuse_texture: None }; let green = CookTorranceMaterial { k_a: 0.0, k_d: 0.5, k_s: 0.4, k_sg: 0.1, k_tg: 0.0, gauss_constant: 25.0, roughness: 0.4, glossiness: 0.0, ior: 0.95, ambient: Vec3::one(), diffuse: Vec3 { x: 0.2, y: 0.7, z: 0.2 }, specular: Vec3::one(), transmission: Vec3::zero(), diffuse_texture: None }; let mut prims: Vec<Box<Prim+Send+Sync>> = Vec::new(); prims.push(Box::new(Plane { a: 0.0, b: 1.0, c: 0.0, d: 3.6, material: Box::new(green) })); let cow = ::util::import::from_obj(red, true, "./docs/assets/models/cow.obj").ok().expect("failed to load obj model");; for triangle in cow.triangles.into_iter() { prims.push(triangle); } println!("Generating octree..."); let octree = prims.into_iter().collect(); println!("Octree generated..."); Scene { lights: lights, octree: octree, background: Vec3 { x: 0.3, y: 0.5, z: 0.8 },
identifier_body
cow.rs
#![allow(unused_imports)] use geometry::prim::{Prim}; use geometry::prims::{Plane, Sphere, Triangle}; use light::light::{Light}; use light::lights::{PointLight, SphereLight}; use material::materials::{CookTorranceMaterial, FlatMaterial, PhongMaterial}; use material::Texture; use material::textures::{CheckerTexture, CubeMap, UVTexture, ImageTexture}; use raytracer::animator::CameraKeyframe; use scene::{Camera, Scene}; use vec3::Vec3; // 5000 polys, cow. Octree helps. pub fn get_camera(image_width: u32, image_height: u32, fov: f64) -> Camera { Camera::new( Vec3 { x: -2.0, y: 4.0, z: 10.0 }, Vec3 { x: 0.0, y: 0.0, z: 0.0 }, Vec3 { x: 0.0, y: 1.0, z: 0.0 }, fov, image_width, image_height ) } pub fn
() -> Scene { let mut lights: Vec<Box<Light+Send+Sync>> = Vec::new(); lights.push(Box::new(SphereLight { position: Vec3 {x: 3.0, y: 10.0, z: 6.0}, color: Vec3::one(), radius: 5.0 })); let red = CookTorranceMaterial { k_a: 0.0, k_d: 0.6, k_s: 1.0, k_sg: 0.2, k_tg: 0.0, gauss_constant: 30.0, roughness: 0.1, glossiness: 0.0, ior: 0.8, ambient: Vec3::one(), diffuse: Vec3 { x: 1.0, y: 0.25, z: 0.1 }, specular: Vec3::one(), transmission: Vec3::zero(), diffuse_texture: None }; let green = CookTorranceMaterial { k_a: 0.0, k_d: 0.5, k_s: 0.4, k_sg: 0.1, k_tg: 0.0, gauss_constant: 25.0, roughness: 0.4, glossiness: 0.0, ior: 0.95, ambient: Vec3::one(), diffuse: Vec3 { x: 0.2, y: 0.7, z: 0.2 }, specular: Vec3::one(), transmission: Vec3::zero(), diffuse_texture: None }; let mut prims: Vec<Box<Prim+Send+Sync>> = Vec::new(); prims.push(Box::new(Plane { a: 0.0, b: 1.0, c: 0.0, d: 3.6, material: Box::new(green) })); let cow = ::util::import::from_obj(red, true, "./docs/assets/models/cow.obj").ok().expect("failed to load obj model");; for triangle in cow.triangles.into_iter() { prims.push(triangle); } println!("Generating octree..."); let octree = prims.into_iter().collect(); println!("Octree generated..."); Scene { lights: lights, octree: octree, background: Vec3 { x: 0.3, y: 0.5, z: 0.8 }, skybox: None } }
get_scene
identifier_name
cow.rs
#![allow(unused_imports)] use geometry::prim::{Prim}; use geometry::prims::{Plane, Sphere, Triangle}; use light::light::{Light}; use light::lights::{PointLight, SphereLight}; use material::materials::{CookTorranceMaterial, FlatMaterial, PhongMaterial}; use material::Texture; use material::textures::{CheckerTexture, CubeMap, UVTexture, ImageTexture}; use raytracer::animator::CameraKeyframe; use scene::{Camera, Scene}; use vec3::Vec3; // 5000 polys, cow. Octree helps. pub fn get_camera(image_width: u32, image_height: u32, fov: f64) -> Camera { Camera::new( Vec3 { x: -2.0, y: 4.0, z: 10.0 }, Vec3 { x: 0.0, y: 0.0, z: 0.0 }, Vec3 { x: 0.0, y: 1.0, z: 0.0 }, fov, image_width, image_height ) } pub fn get_scene() -> Scene { let mut lights: Vec<Box<Light+Send+Sync>> = Vec::new(); lights.push(Box::new(SphereLight { position: Vec3 {x: 3.0, y: 10.0, z: 6.0}, color: Vec3::one(), radius: 5.0 })); let red = CookTorranceMaterial { k_a: 0.0, k_d: 0.6, k_s: 1.0, k_sg: 0.2, k_tg: 0.0, gauss_constant: 30.0, roughness: 0.1, glossiness: 0.0, ior: 0.8, ambient: Vec3::one(), diffuse: Vec3 { x: 1.0, y: 0.25, z: 0.1 }, specular: Vec3::one(), transmission: Vec3::zero(), diffuse_texture: None }; let green = CookTorranceMaterial { k_a: 0.0, k_d: 0.5, k_s: 0.4, k_sg: 0.1, k_tg: 0.0, gauss_constant: 25.0, roughness: 0.4, glossiness: 0.0, ior: 0.95, ambient: Vec3::one(), diffuse: Vec3 { x: 0.2, y: 0.7, z: 0.2 }, specular: Vec3::one(), transmission: Vec3::zero(), diffuse_texture: None }; let mut prims: Vec<Box<Prim+Send+Sync>> = Vec::new(); prims.push(Box::new(Plane { a: 0.0, b: 1.0, c: 0.0, d: 3.6, material: Box::new(green) })); let cow = ::util::import::from_obj(red, true, "./docs/assets/models/cow.obj").ok().expect("failed to load obj model");; for triangle in cow.triangles.into_iter() { prims.push(triangle); }
Scene { lights: lights, octree: octree, background: Vec3 { x: 0.3, y: 0.5, z: 0.8 }, skybox: None } }
println!("Generating octree..."); let octree = prims.into_iter().collect(); println!("Octree generated...");
random_line_split
fields.rs
//! # fields //! All necessery functions for appliying fields to json results. use serde_json::Value; use serde_json; use service::query_api::Queries; /// let only named fields array according to the query api pub fn apply(obj: &mut Value, queries: &Queries) { let ref fields = queries.fields; if fields.len() == 0 { return; } match obj { &mut Value::Array(ref mut arr) => { let mut i = 0usize; let size = (&arr.len()).clone(); let remove_keys = match arr.get(0) { Some(item) => { if let &Value::Object(ref map) = item { diff_left(map.keys(), fields) } else { Vec::<String>::new() } } None => Vec::<String>::new(), }; while i < size { let map_val = arr.get_mut(i).unwrap(); if let &mut Value::Object(ref mut obj) = map_val { for key in &remove_keys { obj.remove(key); } } i += 1; } } &mut Value::Object(ref mut map) => { let remove_keys = diff_left(map.keys(), fields); for key in &remove_keys { map.remove(key); } } _ => { //No need to handle other types } } } fn diff_left(a: serde_json::map::Keys, b: &Vec<String>) -> Vec<String>
#[cfg(test)] mod tests { use super::*; fn get_json() -> Value { let json_string = r#"[ { "name":"seray", "age":31, "active":true, "password":"123" }, { "name":"kamil", "age":900, "active":false, "password":"333" }, { "name":"hasan", "age":25, "active":true, "password":"321" } ]"#; serde_json::from_str(&json_string).unwrap() } #[test] fn apply_test() { let mut queries = Queries::new(); { let fields = &mut queries.fields; fields.push("name".to_string()); fields.push("active".to_string()); } let expected: Value = serde_json::from_str(&r#"[ { "name":"seray", "active":true }, { "name":"kamil", "active":false }, { "name":"hasan", "active":true } ]"#) .unwrap(); let json = &mut get_json(); apply(json, &queries); assert_eq!(json.clone(), expected); } #[test] fn diff_left_test() { let mut a = serde_json::Map::<String, Value>::new(); a.insert("a".to_string(), Value::Null); a.insert("b".to_string(), Value::Null); a.insert("c".to_string(), Value::Null); let b = vec!["b".to_string(), "c".to_string()]; let r = diff_left(a.keys(), &b); assert_eq!(r, vec!["a".to_string()]); } }
{ let mut diff = Vec::<String>::new(); 'outer: for a_item in a { for b_item in b { if a_item == b_item { continue 'outer; } } diff.push(a_item.clone()); } diff }
identifier_body
fields.rs
//! # fields //! All necessery functions for appliying fields to json results. use serde_json::Value; use serde_json; use service::query_api::Queries; /// let only named fields array according to the query api pub fn apply(obj: &mut Value, queries: &Queries) { let ref fields = queries.fields; if fields.len() == 0 { return; } match obj { &mut Value::Array(ref mut arr) => { let mut i = 0usize; let size = (&arr.len()).clone(); let remove_keys = match arr.get(0) { Some(item) => { if let &Value::Object(ref map) = item { diff_left(map.keys(), fields) } else { Vec::<String>::new() } } None => Vec::<String>::new(), }; while i < size { let map_val = arr.get_mut(i).unwrap(); if let &mut Value::Object(ref mut obj) = map_val
i += 1; } } &mut Value::Object(ref mut map) => { let remove_keys = diff_left(map.keys(), fields); for key in &remove_keys { map.remove(key); } } _ => { //No need to handle other types } } } fn diff_left(a: serde_json::map::Keys, b: &Vec<String>) -> Vec<String> { let mut diff = Vec::<String>::new(); 'outer: for a_item in a { for b_item in b { if a_item == b_item { continue 'outer; } } diff.push(a_item.clone()); } diff } #[cfg(test)] mod tests { use super::*; fn get_json() -> Value { let json_string = r#"[ { "name":"seray", "age":31, "active":true, "password":"123" }, { "name":"kamil", "age":900, "active":false, "password":"333" }, { "name":"hasan", "age":25, "active":true, "password":"321" } ]"#; serde_json::from_str(&json_string).unwrap() } #[test] fn apply_test() { let mut queries = Queries::new(); { let fields = &mut queries.fields; fields.push("name".to_string()); fields.push("active".to_string()); } let expected: Value = serde_json::from_str(&r#"[ { "name":"seray", "active":true }, { "name":"kamil", "active":false }, { "name":"hasan", "active":true } ]"#) .unwrap(); let json = &mut get_json(); apply(json, &queries); assert_eq!(json.clone(), expected); } #[test] fn diff_left_test() { let mut a = serde_json::Map::<String, Value>::new(); a.insert("a".to_string(), Value::Null); a.insert("b".to_string(), Value::Null); a.insert("c".to_string(), Value::Null); let b = vec!["b".to_string(), "c".to_string()]; let r = diff_left(a.keys(), &b); assert_eq!(r, vec!["a".to_string()]); } }
{ for key in &remove_keys { obj.remove(key); } }
conditional_block
fields.rs
//! # fields //! All necessery functions for appliying fields to json results. use serde_json::Value; use serde_json; use service::query_api::Queries; /// let only named fields array according to the query api pub fn apply(obj: &mut Value, queries: &Queries) { let ref fields = queries.fields; if fields.len() == 0 { return; } match obj { &mut Value::Array(ref mut arr) => { let mut i = 0usize; let size = (&arr.len()).clone(); let remove_keys = match arr.get(0) { Some(item) => { if let &Value::Object(ref map) = item { diff_left(map.keys(), fields) } else { Vec::<String>::new() } } None => Vec::<String>::new(), }; while i < size { let map_val = arr.get_mut(i).unwrap(); if let &mut Value::Object(ref mut obj) = map_val { for key in &remove_keys { obj.remove(key); } } i += 1; } } &mut Value::Object(ref mut map) => { let remove_keys = diff_left(map.keys(), fields); for key in &remove_keys { map.remove(key); } } _ => { //No need to handle other types } } } fn diff_left(a: serde_json::map::Keys, b: &Vec<String>) -> Vec<String> { let mut diff = Vec::<String>::new(); 'outer: for a_item in a { for b_item in b { if a_item == b_item { continue 'outer; } } diff.push(a_item.clone()); } diff } #[cfg(test)] mod tests { use super::*; fn get_json() -> Value { let json_string = r#"[
}, { "name":"kamil", "age":900, "active":false, "password":"333" }, { "name":"hasan", "age":25, "active":true, "password":"321" } ]"#; serde_json::from_str(&json_string).unwrap() } #[test] fn apply_test() { let mut queries = Queries::new(); { let fields = &mut queries.fields; fields.push("name".to_string()); fields.push("active".to_string()); } let expected: Value = serde_json::from_str(&r#"[ { "name":"seray", "active":true }, { "name":"kamil", "active":false }, { "name":"hasan", "active":true } ]"#) .unwrap(); let json = &mut get_json(); apply(json, &queries); assert_eq!(json.clone(), expected); } #[test] fn diff_left_test() { let mut a = serde_json::Map::<String, Value>::new(); a.insert("a".to_string(), Value::Null); a.insert("b".to_string(), Value::Null); a.insert("c".to_string(), Value::Null); let b = vec!["b".to_string(), "c".to_string()]; let r = diff_left(a.keys(), &b); assert_eq!(r, vec!["a".to_string()]); } }
{ "name":"seray", "age":31, "active":true, "password":"123"
random_line_split
fields.rs
//! # fields //! All necessery functions for appliying fields to json results. use serde_json::Value; use serde_json; use service::query_api::Queries; /// let only named fields array according to the query api pub fn apply(obj: &mut Value, queries: &Queries) { let ref fields = queries.fields; if fields.len() == 0 { return; } match obj { &mut Value::Array(ref mut arr) => { let mut i = 0usize; let size = (&arr.len()).clone(); let remove_keys = match arr.get(0) { Some(item) => { if let &Value::Object(ref map) = item { diff_left(map.keys(), fields) } else { Vec::<String>::new() } } None => Vec::<String>::new(), }; while i < size { let map_val = arr.get_mut(i).unwrap(); if let &mut Value::Object(ref mut obj) = map_val { for key in &remove_keys { obj.remove(key); } } i += 1; } } &mut Value::Object(ref mut map) => { let remove_keys = diff_left(map.keys(), fields); for key in &remove_keys { map.remove(key); } } _ => { //No need to handle other types } } } fn diff_left(a: serde_json::map::Keys, b: &Vec<String>) -> Vec<String> { let mut diff = Vec::<String>::new(); 'outer: for a_item in a { for b_item in b { if a_item == b_item { continue 'outer; } } diff.push(a_item.clone()); } diff } #[cfg(test)] mod tests { use super::*; fn
() -> Value { let json_string = r#"[ { "name":"seray", "age":31, "active":true, "password":"123" }, { "name":"kamil", "age":900, "active":false, "password":"333" }, { "name":"hasan", "age":25, "active":true, "password":"321" } ]"#; serde_json::from_str(&json_string).unwrap() } #[test] fn apply_test() { let mut queries = Queries::new(); { let fields = &mut queries.fields; fields.push("name".to_string()); fields.push("active".to_string()); } let expected: Value = serde_json::from_str(&r#"[ { "name":"seray", "active":true }, { "name":"kamil", "active":false }, { "name":"hasan", "active":true } ]"#) .unwrap(); let json = &mut get_json(); apply(json, &queries); assert_eq!(json.clone(), expected); } #[test] fn diff_left_test() { let mut a = serde_json::Map::<String, Value>::new(); a.insert("a".to_string(), Value::Null); a.insert("b".to_string(), Value::Null); a.insert("c".to_string(), Value::Null); let b = vec!["b".to_string(), "c".to_string()]; let r = diff_left(a.keys(), &b); assert_eq!(r, vec!["a".to_string()]); } }
get_json
identifier_name
bloom.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! The style bloom filter is used as an optimization when matching deep //! descendant selectors. #![deny(missing_docs)] use crate::dom::{SendElement, TElement}; use atomic_refcell::{AtomicRefCell, AtomicRefMut}; use owning_ref::OwningHandle; use selectors::bloom::BloomFilter; use servo_arc::Arc; use smallvec::SmallVec; thread_local! { /// Bloom filters are large allocations, so we store them in thread-local storage /// such that they can be reused across style traversals. StyleBloom is responsible /// for ensuring that the bloom filter is zeroed when it is dropped. static BLOOM_KEY: Arc<AtomicRefCell<BloomFilter>> = Arc::new_leaked(AtomicRefCell::new(BloomFilter::new())); } /// A struct that allows us to fast-reject deep descendant selectors avoiding /// selector-matching. /// /// This is implemented using a counting bloom filter, and it's a standard /// optimization. See Gecko's `AncestorFilter`, and Blink's and WebKit's /// `SelectorFilter`. /// /// The constraints for Servo's style system are a bit different compared to /// traditional style systems given Servo does a parallel breadth-first /// traversal instead of a sequential depth-first traversal. /// /// This implies that we need to track a bit more state than other browsers to /// ensure we're doing the correct thing during the traversal, and being able to /// apply this optimization effectively. /// /// Concretely, we have a bloom filter instance per worker thread, and we track /// the current DOM depth in order to find a common ancestor when it doesn't /// match the previous element we've styled. /// /// This is usually a pretty fast operation (we use to be one level deeper than /// the previous one), but in the case of work-stealing, we may needed to push /// and pop multiple elements. /// /// See the `insert_parents_recovering`, where most of the magic happens. /// /// Regarding thread-safety, this struct is safe because: /// /// * We clear this after a restyle. /// * The DOM shape and attributes (and every other thing we access here) are /// immutable during a restyle. /// pub struct StyleBloom<E: TElement> { /// A handle to the bloom filter from the thread upon which this StyleBloom /// was created. We use AtomicRefCell so that this is all |Send|, which allows /// StyleBloom to live in ThreadLocalStyleContext, which is dropped from the /// parent thread. filter: OwningHandle<Arc<AtomicRefCell<BloomFilter>>, AtomicRefMut<'static, BloomFilter>>, /// The stack of elements that this bloom filter contains, along with the /// number of hashes pushed for each element. elements: SmallVec<[PushedElement<E>; 16]>, /// Stack of hashes that have been pushed onto this filter. pushed_hashes: SmallVec<[u32; 64]>, } /// The very rough benchmarks in the selectors crate show clear() /// costing about 25 times more than remove_hash(). We use this to implement /// clear() more efficiently when only a small number of hashes have been /// pushed. /// /// One subtly to note is that remove_hash() will not touch the value /// if the filter overflowed. However, overflow can only occur if we /// get 255 collisions on the same hash value, and 25 < 255. const MEMSET_CLEAR_THRESHOLD: usize = 25; struct PushedElement<E: TElement> { /// The element that was pushed. element: SendElement<E>, /// The number of hashes pushed for the element. num_hashes: usize, } impl<E: TElement> PushedElement<E> { fn new(el: E, num_hashes: usize) -> Self { PushedElement { element: unsafe { SendElement::new(el) }, num_hashes, } } } fn each_relevant_element_hash<E, F>(element: E, mut f: F) where E: TElement, F: FnMut(u32), { f(element.local_name().get_hash()); f(element.namespace().get_hash()); if let Some(id) = element.id() { f(id.get_hash()); } element.each_class(|class| f(class.get_hash())); } impl<E: TElement> Drop for StyleBloom<E> { fn drop(&mut self) { // Leave the reusable bloom filter in a zeroed state. self.clear(); } } impl<E: TElement> StyleBloom<E> { /// Create an empty `StyleBloom`. Because StyleBloom acquires the thread- /// local filter buffer, creating multiple live StyleBloom instances at /// the same time on the same thread will panic. // Forced out of line to limit stack frame sizes after extra inlining from // https://github.com/rust-lang/rust/pull/43931 // // See https://github.com/servo/servo/pull/18420#issuecomment-328769322 #[inline(never)] pub fn new() -> Self { let bloom_arc = BLOOM_KEY.with(|b| b.clone()); let filter = OwningHandle::new_with_fn(bloom_arc, |x| unsafe { x.as_ref() }.unwrap().borrow_mut()); debug_assert!( filter.is_zeroed(), "Forgot to zero the bloom filter last time" ); StyleBloom { filter: filter, elements: Default::default(), pushed_hashes: Default::default(),
} } /// Return the bloom filter used properly by the `selectors` crate. pub fn filter(&self) -> &BloomFilter { &*self.filter } /// Push an element to the bloom filter, knowing that it's a child of the /// last element parent. pub fn push(&mut self, element: E) { if cfg!(debug_assertions) { if self.elements.is_empty() { assert!(element.traversal_parent().is_none()); } } self.push_internal(element); } /// Same as `push`, but without asserting, in order to use it from /// `rebuild`. fn push_internal(&mut self, element: E) { let mut count = 0; each_relevant_element_hash(element, |hash| { count += 1; self.filter.insert_hash(hash); self.pushed_hashes.push(hash); }); self.elements.push(PushedElement::new(element, count)); } /// Pop the last element in the bloom filter and return it. #[inline] fn pop(&mut self) -> Option<E> { let PushedElement { element, num_hashes, } = self.elements.pop()?; let popped_element = *element; // Verify that the pushed hashes match the ones we'd get from the element. let mut expected_hashes = vec![]; if cfg!(debug_assertions) { each_relevant_element_hash(popped_element, |hash| expected_hashes.push(hash)); } for _ in 0..num_hashes { let hash = self.pushed_hashes.pop().unwrap(); debug_assert_eq!(expected_hashes.pop().unwrap(), hash); self.filter.remove_hash(hash); } Some(popped_element) } /// Returns the DOM depth of elements that can be correctly /// matched against the bloom filter (that is, the number of /// elements in our list). pub fn matching_depth(&self) -> usize { self.elements.len() } /// Clears the bloom filter. pub fn clear(&mut self) { self.elements.clear(); if self.pushed_hashes.len() > MEMSET_CLEAR_THRESHOLD { self.filter.clear(); self.pushed_hashes.clear(); } else { for hash in self.pushed_hashes.drain() { self.filter.remove_hash(hash); } debug_assert!(self.filter.is_zeroed()); } } /// Rebuilds the bloom filter up to the parent of the given element. pub fn rebuild(&mut self, mut element: E) { self.clear(); let mut parents_to_insert = SmallVec::<[E; 16]>::new(); while let Some(parent) = element.traversal_parent() { parents_to_insert.push(parent); element = parent; } for parent in parents_to_insert.drain().rev() { self.push(parent); } } /// In debug builds, asserts that all the parents of `element` are in the /// bloom filter. /// /// Goes away in release builds. pub fn assert_complete(&self, mut element: E) { if cfg!(debug_assertions) { let mut checked = 0; while let Some(parent) = element.traversal_parent() { assert_eq!( parent, *(self.elements[self.elements.len() - 1 - checked].element) ); element = parent; checked += 1; } assert_eq!(checked, self.elements.len()); } } /// Get the element that represents the chain of things inserted /// into the filter right now. That chain is the given element /// (if any) and its ancestors. #[inline] pub fn current_parent(&self) -> Option<E> { self.elements.last().map(|ref el| *el.element) } /// Insert the parents of an element in the bloom filter, trying to recover /// the filter if the last element inserted doesn't match. /// /// Gets the element depth in the dom, to make it efficient, or if not /// provided always rebuilds the filter from scratch. /// /// Returns the new bloom filter depth, that the traversal code is /// responsible to keep around if it wants to get an effective filter. pub fn insert_parents_recovering(&mut self, element: E, element_depth: usize) { // Easy case, we're in a different restyle, or we're empty. if self.elements.is_empty() { self.rebuild(element); return; } let traversal_parent = match element.traversal_parent() { Some(parent) => parent, None => { // Yay, another easy case. self.clear(); return; }, }; if self.current_parent() == Some(traversal_parent) { // Ta da, cache hit, we're all done. return; } if element_depth == 0 { self.clear(); return; } // We should've early exited above. debug_assert!( element_depth!= 0, "We should have already cleared the bloom filter" ); debug_assert!(!self.elements.is_empty(), "How! We should've just rebuilt!"); // Now the fun begins: We have the depth of the dom and the depth of the // last element inserted in the filter, let's try to find a common // parent. // // The current depth, that is, the depth of the last element inserted in // the bloom filter, is the number of elements _minus one_, that is: if // there's one element, it must be the root -> depth zero. let mut current_depth = self.elements.len() - 1; // If the filter represents an element too deep in the dom, we need to // pop ancestors. while current_depth > element_depth - 1 { self.pop().expect("Emilio is bad at math"); current_depth -= 1; } // Now let's try to find a common parent in the bloom filter chain, // starting with traversal_parent. let mut common_parent = traversal_parent; let mut common_parent_depth = element_depth - 1; // Let's collect the parents we are going to need to insert once we've // found the common one. let mut parents_to_insert = SmallVec::<[E; 16]>::new(); // If the bloom filter still doesn't have enough elements, the common // parent is up in the dom. while common_parent_depth > current_depth { // TODO(emilio): Seems like we could insert parents here, then // reverse the slice. parents_to_insert.push(common_parent); common_parent = common_parent.traversal_parent().expect("We were lied to"); common_parent_depth -= 1; } // Now the two depths are the same. debug_assert_eq!(common_parent_depth, current_depth); // Happy case: The parents match, we only need to push the ancestors // we've collected and we'll never enter in this loop. // // Not-so-happy case: Parent's don't match, so we need to keep going up // until we find a common ancestor. // // Gecko currently models native anonymous content that conceptually // hangs off the document (such as scrollbars) as a separate subtree // from the document root. // // Thus it's possible with Gecko that we do not find any common // ancestor. while *(self.elements.last().unwrap().element)!= common_parent { parents_to_insert.push(common_parent); self.pop().unwrap(); common_parent = match common_parent.traversal_parent() { Some(parent) => parent, None => { debug_assert!(self.elements.is_empty()); if cfg!(feature = "gecko") { break; } else { panic!("should have found a common ancestor"); } }, } } // Now the parents match, so insert the stack of elements we have been // collecting so far. for parent in parents_to_insert.drain().rev() { self.push(parent); } debug_assert_eq!(self.elements.len(), element_depth); // We're done! Easy. } }
random_line_split
bloom.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! The style bloom filter is used as an optimization when matching deep //! descendant selectors. #![deny(missing_docs)] use crate::dom::{SendElement, TElement}; use atomic_refcell::{AtomicRefCell, AtomicRefMut}; use owning_ref::OwningHandle; use selectors::bloom::BloomFilter; use servo_arc::Arc; use smallvec::SmallVec; thread_local! { /// Bloom filters are large allocations, so we store them in thread-local storage /// such that they can be reused across style traversals. StyleBloom is responsible /// for ensuring that the bloom filter is zeroed when it is dropped. static BLOOM_KEY: Arc<AtomicRefCell<BloomFilter>> = Arc::new_leaked(AtomicRefCell::new(BloomFilter::new())); } /// A struct that allows us to fast-reject deep descendant selectors avoiding /// selector-matching. /// /// This is implemented using a counting bloom filter, and it's a standard /// optimization. See Gecko's `AncestorFilter`, and Blink's and WebKit's /// `SelectorFilter`. /// /// The constraints for Servo's style system are a bit different compared to /// traditional style systems given Servo does a parallel breadth-first /// traversal instead of a sequential depth-first traversal. /// /// This implies that we need to track a bit more state than other browsers to /// ensure we're doing the correct thing during the traversal, and being able to /// apply this optimization effectively. /// /// Concretely, we have a bloom filter instance per worker thread, and we track /// the current DOM depth in order to find a common ancestor when it doesn't /// match the previous element we've styled. /// /// This is usually a pretty fast operation (we use to be one level deeper than /// the previous one), but in the case of work-stealing, we may needed to push /// and pop multiple elements. /// /// See the `insert_parents_recovering`, where most of the magic happens. /// /// Regarding thread-safety, this struct is safe because: /// /// * We clear this after a restyle. /// * The DOM shape and attributes (and every other thing we access here) are /// immutable during a restyle. /// pub struct StyleBloom<E: TElement> { /// A handle to the bloom filter from the thread upon which this StyleBloom /// was created. We use AtomicRefCell so that this is all |Send|, which allows /// StyleBloom to live in ThreadLocalStyleContext, which is dropped from the /// parent thread. filter: OwningHandle<Arc<AtomicRefCell<BloomFilter>>, AtomicRefMut<'static, BloomFilter>>, /// The stack of elements that this bloom filter contains, along with the /// number of hashes pushed for each element. elements: SmallVec<[PushedElement<E>; 16]>, /// Stack of hashes that have been pushed onto this filter. pushed_hashes: SmallVec<[u32; 64]>, } /// The very rough benchmarks in the selectors crate show clear() /// costing about 25 times more than remove_hash(). We use this to implement /// clear() more efficiently when only a small number of hashes have been /// pushed. /// /// One subtly to note is that remove_hash() will not touch the value /// if the filter overflowed. However, overflow can only occur if we /// get 255 collisions on the same hash value, and 25 < 255. const MEMSET_CLEAR_THRESHOLD: usize = 25; struct PushedElement<E: TElement> { /// The element that was pushed. element: SendElement<E>, /// The number of hashes pushed for the element. num_hashes: usize, } impl<E: TElement> PushedElement<E> { fn new(el: E, num_hashes: usize) -> Self { PushedElement { element: unsafe { SendElement::new(el) }, num_hashes, } } } fn each_relevant_element_hash<E, F>(element: E, mut f: F) where E: TElement, F: FnMut(u32), { f(element.local_name().get_hash()); f(element.namespace().get_hash()); if let Some(id) = element.id() { f(id.get_hash()); } element.each_class(|class| f(class.get_hash())); } impl<E: TElement> Drop for StyleBloom<E> { fn drop(&mut self) { // Leave the reusable bloom filter in a zeroed state. self.clear(); } } impl<E: TElement> StyleBloom<E> { /// Create an empty `StyleBloom`. Because StyleBloom acquires the thread- /// local filter buffer, creating multiple live StyleBloom instances at /// the same time on the same thread will panic. // Forced out of line to limit stack frame sizes after extra inlining from // https://github.com/rust-lang/rust/pull/43931 // // See https://github.com/servo/servo/pull/18420#issuecomment-328769322 #[inline(never)] pub fn new() -> Self { let bloom_arc = BLOOM_KEY.with(|b| b.clone()); let filter = OwningHandle::new_with_fn(bloom_arc, |x| unsafe { x.as_ref() }.unwrap().borrow_mut()); debug_assert!( filter.is_zeroed(), "Forgot to zero the bloom filter last time" ); StyleBloom { filter: filter, elements: Default::default(), pushed_hashes: Default::default(), } } /// Return the bloom filter used properly by the `selectors` crate. pub fn filter(&self) -> &BloomFilter { &*self.filter } /// Push an element to the bloom filter, knowing that it's a child of the /// last element parent. pub fn push(&mut self, element: E) { if cfg!(debug_assertions) { if self.elements.is_empty() { assert!(element.traversal_parent().is_none()); } } self.push_internal(element); } /// Same as `push`, but without asserting, in order to use it from /// `rebuild`. fn
(&mut self, element: E) { let mut count = 0; each_relevant_element_hash(element, |hash| { count += 1; self.filter.insert_hash(hash); self.pushed_hashes.push(hash); }); self.elements.push(PushedElement::new(element, count)); } /// Pop the last element in the bloom filter and return it. #[inline] fn pop(&mut self) -> Option<E> { let PushedElement { element, num_hashes, } = self.elements.pop()?; let popped_element = *element; // Verify that the pushed hashes match the ones we'd get from the element. let mut expected_hashes = vec![]; if cfg!(debug_assertions) { each_relevant_element_hash(popped_element, |hash| expected_hashes.push(hash)); } for _ in 0..num_hashes { let hash = self.pushed_hashes.pop().unwrap(); debug_assert_eq!(expected_hashes.pop().unwrap(), hash); self.filter.remove_hash(hash); } Some(popped_element) } /// Returns the DOM depth of elements that can be correctly /// matched against the bloom filter (that is, the number of /// elements in our list). pub fn matching_depth(&self) -> usize { self.elements.len() } /// Clears the bloom filter. pub fn clear(&mut self) { self.elements.clear(); if self.pushed_hashes.len() > MEMSET_CLEAR_THRESHOLD { self.filter.clear(); self.pushed_hashes.clear(); } else { for hash in self.pushed_hashes.drain() { self.filter.remove_hash(hash); } debug_assert!(self.filter.is_zeroed()); } } /// Rebuilds the bloom filter up to the parent of the given element. pub fn rebuild(&mut self, mut element: E) { self.clear(); let mut parents_to_insert = SmallVec::<[E; 16]>::new(); while let Some(parent) = element.traversal_parent() { parents_to_insert.push(parent); element = parent; } for parent in parents_to_insert.drain().rev() { self.push(parent); } } /// In debug builds, asserts that all the parents of `element` are in the /// bloom filter. /// /// Goes away in release builds. pub fn assert_complete(&self, mut element: E) { if cfg!(debug_assertions) { let mut checked = 0; while let Some(parent) = element.traversal_parent() { assert_eq!( parent, *(self.elements[self.elements.len() - 1 - checked].element) ); element = parent; checked += 1; } assert_eq!(checked, self.elements.len()); } } /// Get the element that represents the chain of things inserted /// into the filter right now. That chain is the given element /// (if any) and its ancestors. #[inline] pub fn current_parent(&self) -> Option<E> { self.elements.last().map(|ref el| *el.element) } /// Insert the parents of an element in the bloom filter, trying to recover /// the filter if the last element inserted doesn't match. /// /// Gets the element depth in the dom, to make it efficient, or if not /// provided always rebuilds the filter from scratch. /// /// Returns the new bloom filter depth, that the traversal code is /// responsible to keep around if it wants to get an effective filter. pub fn insert_parents_recovering(&mut self, element: E, element_depth: usize) { // Easy case, we're in a different restyle, or we're empty. if self.elements.is_empty() { self.rebuild(element); return; } let traversal_parent = match element.traversal_parent() { Some(parent) => parent, None => { // Yay, another easy case. self.clear(); return; }, }; if self.current_parent() == Some(traversal_parent) { // Ta da, cache hit, we're all done. return; } if element_depth == 0 { self.clear(); return; } // We should've early exited above. debug_assert!( element_depth!= 0, "We should have already cleared the bloom filter" ); debug_assert!(!self.elements.is_empty(), "How! We should've just rebuilt!"); // Now the fun begins: We have the depth of the dom and the depth of the // last element inserted in the filter, let's try to find a common // parent. // // The current depth, that is, the depth of the last element inserted in // the bloom filter, is the number of elements _minus one_, that is: if // there's one element, it must be the root -> depth zero. let mut current_depth = self.elements.len() - 1; // If the filter represents an element too deep in the dom, we need to // pop ancestors. while current_depth > element_depth - 1 { self.pop().expect("Emilio is bad at math"); current_depth -= 1; } // Now let's try to find a common parent in the bloom filter chain, // starting with traversal_parent. let mut common_parent = traversal_parent; let mut common_parent_depth = element_depth - 1; // Let's collect the parents we are going to need to insert once we've // found the common one. let mut parents_to_insert = SmallVec::<[E; 16]>::new(); // If the bloom filter still doesn't have enough elements, the common // parent is up in the dom. while common_parent_depth > current_depth { // TODO(emilio): Seems like we could insert parents here, then // reverse the slice. parents_to_insert.push(common_parent); common_parent = common_parent.traversal_parent().expect("We were lied to"); common_parent_depth -= 1; } // Now the two depths are the same. debug_assert_eq!(common_parent_depth, current_depth); // Happy case: The parents match, we only need to push the ancestors // we've collected and we'll never enter in this loop. // // Not-so-happy case: Parent's don't match, so we need to keep going up // until we find a common ancestor. // // Gecko currently models native anonymous content that conceptually // hangs off the document (such as scrollbars) as a separate subtree // from the document root. // // Thus it's possible with Gecko that we do not find any common // ancestor. while *(self.elements.last().unwrap().element)!= common_parent { parents_to_insert.push(common_parent); self.pop().unwrap(); common_parent = match common_parent.traversal_parent() { Some(parent) => parent, None => { debug_assert!(self.elements.is_empty()); if cfg!(feature = "gecko") { break; } else { panic!("should have found a common ancestor"); } }, } } // Now the parents match, so insert the stack of elements we have been // collecting so far. for parent in parents_to_insert.drain().rev() { self.push(parent); } debug_assert_eq!(self.elements.len(), element_depth); // We're done! Easy. } }
push_internal
identifier_name
bloom.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! The style bloom filter is used as an optimization when matching deep //! descendant selectors. #![deny(missing_docs)] use crate::dom::{SendElement, TElement}; use atomic_refcell::{AtomicRefCell, AtomicRefMut}; use owning_ref::OwningHandle; use selectors::bloom::BloomFilter; use servo_arc::Arc; use smallvec::SmallVec; thread_local! { /// Bloom filters are large allocations, so we store them in thread-local storage /// such that they can be reused across style traversals. StyleBloom is responsible /// for ensuring that the bloom filter is zeroed when it is dropped. static BLOOM_KEY: Arc<AtomicRefCell<BloomFilter>> = Arc::new_leaked(AtomicRefCell::new(BloomFilter::new())); } /// A struct that allows us to fast-reject deep descendant selectors avoiding /// selector-matching. /// /// This is implemented using a counting bloom filter, and it's a standard /// optimization. See Gecko's `AncestorFilter`, and Blink's and WebKit's /// `SelectorFilter`. /// /// The constraints for Servo's style system are a bit different compared to /// traditional style systems given Servo does a parallel breadth-first /// traversal instead of a sequential depth-first traversal. /// /// This implies that we need to track a bit more state than other browsers to /// ensure we're doing the correct thing during the traversal, and being able to /// apply this optimization effectively. /// /// Concretely, we have a bloom filter instance per worker thread, and we track /// the current DOM depth in order to find a common ancestor when it doesn't /// match the previous element we've styled. /// /// This is usually a pretty fast operation (we use to be one level deeper than /// the previous one), but in the case of work-stealing, we may needed to push /// and pop multiple elements. /// /// See the `insert_parents_recovering`, where most of the magic happens. /// /// Regarding thread-safety, this struct is safe because: /// /// * We clear this after a restyle. /// * The DOM shape and attributes (and every other thing we access here) are /// immutable during a restyle. /// pub struct StyleBloom<E: TElement> { /// A handle to the bloom filter from the thread upon which this StyleBloom /// was created. We use AtomicRefCell so that this is all |Send|, which allows /// StyleBloom to live in ThreadLocalStyleContext, which is dropped from the /// parent thread. filter: OwningHandle<Arc<AtomicRefCell<BloomFilter>>, AtomicRefMut<'static, BloomFilter>>, /// The stack of elements that this bloom filter contains, along with the /// number of hashes pushed for each element. elements: SmallVec<[PushedElement<E>; 16]>, /// Stack of hashes that have been pushed onto this filter. pushed_hashes: SmallVec<[u32; 64]>, } /// The very rough benchmarks in the selectors crate show clear() /// costing about 25 times more than remove_hash(). We use this to implement /// clear() more efficiently when only a small number of hashes have been /// pushed. /// /// One subtly to note is that remove_hash() will not touch the value /// if the filter overflowed. However, overflow can only occur if we /// get 255 collisions on the same hash value, and 25 < 255. const MEMSET_CLEAR_THRESHOLD: usize = 25; struct PushedElement<E: TElement> { /// The element that was pushed. element: SendElement<E>, /// The number of hashes pushed for the element. num_hashes: usize, } impl<E: TElement> PushedElement<E> { fn new(el: E, num_hashes: usize) -> Self { PushedElement { element: unsafe { SendElement::new(el) }, num_hashes, } } } fn each_relevant_element_hash<E, F>(element: E, mut f: F) where E: TElement, F: FnMut(u32), { f(element.local_name().get_hash()); f(element.namespace().get_hash()); if let Some(id) = element.id() { f(id.get_hash()); } element.each_class(|class| f(class.get_hash())); } impl<E: TElement> Drop for StyleBloom<E> { fn drop(&mut self)
} impl<E: TElement> StyleBloom<E> { /// Create an empty `StyleBloom`. Because StyleBloom acquires the thread- /// local filter buffer, creating multiple live StyleBloom instances at /// the same time on the same thread will panic. // Forced out of line to limit stack frame sizes after extra inlining from // https://github.com/rust-lang/rust/pull/43931 // // See https://github.com/servo/servo/pull/18420#issuecomment-328769322 #[inline(never)] pub fn new() -> Self { let bloom_arc = BLOOM_KEY.with(|b| b.clone()); let filter = OwningHandle::new_with_fn(bloom_arc, |x| unsafe { x.as_ref() }.unwrap().borrow_mut()); debug_assert!( filter.is_zeroed(), "Forgot to zero the bloom filter last time" ); StyleBloom { filter: filter, elements: Default::default(), pushed_hashes: Default::default(), } } /// Return the bloom filter used properly by the `selectors` crate. pub fn filter(&self) -> &BloomFilter { &*self.filter } /// Push an element to the bloom filter, knowing that it's a child of the /// last element parent. pub fn push(&mut self, element: E) { if cfg!(debug_assertions) { if self.elements.is_empty() { assert!(element.traversal_parent().is_none()); } } self.push_internal(element); } /// Same as `push`, but without asserting, in order to use it from /// `rebuild`. fn push_internal(&mut self, element: E) { let mut count = 0; each_relevant_element_hash(element, |hash| { count += 1; self.filter.insert_hash(hash); self.pushed_hashes.push(hash); }); self.elements.push(PushedElement::new(element, count)); } /// Pop the last element in the bloom filter and return it. #[inline] fn pop(&mut self) -> Option<E> { let PushedElement { element, num_hashes, } = self.elements.pop()?; let popped_element = *element; // Verify that the pushed hashes match the ones we'd get from the element. let mut expected_hashes = vec![]; if cfg!(debug_assertions) { each_relevant_element_hash(popped_element, |hash| expected_hashes.push(hash)); } for _ in 0..num_hashes { let hash = self.pushed_hashes.pop().unwrap(); debug_assert_eq!(expected_hashes.pop().unwrap(), hash); self.filter.remove_hash(hash); } Some(popped_element) } /// Returns the DOM depth of elements that can be correctly /// matched against the bloom filter (that is, the number of /// elements in our list). pub fn matching_depth(&self) -> usize { self.elements.len() } /// Clears the bloom filter. pub fn clear(&mut self) { self.elements.clear(); if self.pushed_hashes.len() > MEMSET_CLEAR_THRESHOLD { self.filter.clear(); self.pushed_hashes.clear(); } else { for hash in self.pushed_hashes.drain() { self.filter.remove_hash(hash); } debug_assert!(self.filter.is_zeroed()); } } /// Rebuilds the bloom filter up to the parent of the given element. pub fn rebuild(&mut self, mut element: E) { self.clear(); let mut parents_to_insert = SmallVec::<[E; 16]>::new(); while let Some(parent) = element.traversal_parent() { parents_to_insert.push(parent); element = parent; } for parent in parents_to_insert.drain().rev() { self.push(parent); } } /// In debug builds, asserts that all the parents of `element` are in the /// bloom filter. /// /// Goes away in release builds. pub fn assert_complete(&self, mut element: E) { if cfg!(debug_assertions) { let mut checked = 0; while let Some(parent) = element.traversal_parent() { assert_eq!( parent, *(self.elements[self.elements.len() - 1 - checked].element) ); element = parent; checked += 1; } assert_eq!(checked, self.elements.len()); } } /// Get the element that represents the chain of things inserted /// into the filter right now. That chain is the given element /// (if any) and its ancestors. #[inline] pub fn current_parent(&self) -> Option<E> { self.elements.last().map(|ref el| *el.element) } /// Insert the parents of an element in the bloom filter, trying to recover /// the filter if the last element inserted doesn't match. /// /// Gets the element depth in the dom, to make it efficient, or if not /// provided always rebuilds the filter from scratch. /// /// Returns the new bloom filter depth, that the traversal code is /// responsible to keep around if it wants to get an effective filter. pub fn insert_parents_recovering(&mut self, element: E, element_depth: usize) { // Easy case, we're in a different restyle, or we're empty. if self.elements.is_empty() { self.rebuild(element); return; } let traversal_parent = match element.traversal_parent() { Some(parent) => parent, None => { // Yay, another easy case. self.clear(); return; }, }; if self.current_parent() == Some(traversal_parent) { // Ta da, cache hit, we're all done. return; } if element_depth == 0 { self.clear(); return; } // We should've early exited above. debug_assert!( element_depth!= 0, "We should have already cleared the bloom filter" ); debug_assert!(!self.elements.is_empty(), "How! We should've just rebuilt!"); // Now the fun begins: We have the depth of the dom and the depth of the // last element inserted in the filter, let's try to find a common // parent. // // The current depth, that is, the depth of the last element inserted in // the bloom filter, is the number of elements _minus one_, that is: if // there's one element, it must be the root -> depth zero. let mut current_depth = self.elements.len() - 1; // If the filter represents an element too deep in the dom, we need to // pop ancestors. while current_depth > element_depth - 1 { self.pop().expect("Emilio is bad at math"); current_depth -= 1; } // Now let's try to find a common parent in the bloom filter chain, // starting with traversal_parent. let mut common_parent = traversal_parent; let mut common_parent_depth = element_depth - 1; // Let's collect the parents we are going to need to insert once we've // found the common one. let mut parents_to_insert = SmallVec::<[E; 16]>::new(); // If the bloom filter still doesn't have enough elements, the common // parent is up in the dom. while common_parent_depth > current_depth { // TODO(emilio): Seems like we could insert parents here, then // reverse the slice. parents_to_insert.push(common_parent); common_parent = common_parent.traversal_parent().expect("We were lied to"); common_parent_depth -= 1; } // Now the two depths are the same. debug_assert_eq!(common_parent_depth, current_depth); // Happy case: The parents match, we only need to push the ancestors // we've collected and we'll never enter in this loop. // // Not-so-happy case: Parent's don't match, so we need to keep going up // until we find a common ancestor. // // Gecko currently models native anonymous content that conceptually // hangs off the document (such as scrollbars) as a separate subtree // from the document root. // // Thus it's possible with Gecko that we do not find any common // ancestor. while *(self.elements.last().unwrap().element)!= common_parent { parents_to_insert.push(common_parent); self.pop().unwrap(); common_parent = match common_parent.traversal_parent() { Some(parent) => parent, None => { debug_assert!(self.elements.is_empty()); if cfg!(feature = "gecko") { break; } else { panic!("should have found a common ancestor"); } }, } } // Now the parents match, so insert the stack of elements we have been // collecting so far. for parent in parents_to_insert.drain().rev() { self.push(parent); } debug_assert_eq!(self.elements.len(), element_depth); // We're done! Easy. } }
{ // Leave the reusable bloom filter in a zeroed state. self.clear(); }
identifier_body
bloom.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! The style bloom filter is used as an optimization when matching deep //! descendant selectors. #![deny(missing_docs)] use crate::dom::{SendElement, TElement}; use atomic_refcell::{AtomicRefCell, AtomicRefMut}; use owning_ref::OwningHandle; use selectors::bloom::BloomFilter; use servo_arc::Arc; use smallvec::SmallVec; thread_local! { /// Bloom filters are large allocations, so we store them in thread-local storage /// such that they can be reused across style traversals. StyleBloom is responsible /// for ensuring that the bloom filter is zeroed when it is dropped. static BLOOM_KEY: Arc<AtomicRefCell<BloomFilter>> = Arc::new_leaked(AtomicRefCell::new(BloomFilter::new())); } /// A struct that allows us to fast-reject deep descendant selectors avoiding /// selector-matching. /// /// This is implemented using a counting bloom filter, and it's a standard /// optimization. See Gecko's `AncestorFilter`, and Blink's and WebKit's /// `SelectorFilter`. /// /// The constraints for Servo's style system are a bit different compared to /// traditional style systems given Servo does a parallel breadth-first /// traversal instead of a sequential depth-first traversal. /// /// This implies that we need to track a bit more state than other browsers to /// ensure we're doing the correct thing during the traversal, and being able to /// apply this optimization effectively. /// /// Concretely, we have a bloom filter instance per worker thread, and we track /// the current DOM depth in order to find a common ancestor when it doesn't /// match the previous element we've styled. /// /// This is usually a pretty fast operation (we use to be one level deeper than /// the previous one), but in the case of work-stealing, we may needed to push /// and pop multiple elements. /// /// See the `insert_parents_recovering`, where most of the magic happens. /// /// Regarding thread-safety, this struct is safe because: /// /// * We clear this after a restyle. /// * The DOM shape and attributes (and every other thing we access here) are /// immutable during a restyle. /// pub struct StyleBloom<E: TElement> { /// A handle to the bloom filter from the thread upon which this StyleBloom /// was created. We use AtomicRefCell so that this is all |Send|, which allows /// StyleBloom to live in ThreadLocalStyleContext, which is dropped from the /// parent thread. filter: OwningHandle<Arc<AtomicRefCell<BloomFilter>>, AtomicRefMut<'static, BloomFilter>>, /// The stack of elements that this bloom filter contains, along with the /// number of hashes pushed for each element. elements: SmallVec<[PushedElement<E>; 16]>, /// Stack of hashes that have been pushed onto this filter. pushed_hashes: SmallVec<[u32; 64]>, } /// The very rough benchmarks in the selectors crate show clear() /// costing about 25 times more than remove_hash(). We use this to implement /// clear() more efficiently when only a small number of hashes have been /// pushed. /// /// One subtly to note is that remove_hash() will not touch the value /// if the filter overflowed. However, overflow can only occur if we /// get 255 collisions on the same hash value, and 25 < 255. const MEMSET_CLEAR_THRESHOLD: usize = 25; struct PushedElement<E: TElement> { /// The element that was pushed. element: SendElement<E>, /// The number of hashes pushed for the element. num_hashes: usize, } impl<E: TElement> PushedElement<E> { fn new(el: E, num_hashes: usize) -> Self { PushedElement { element: unsafe { SendElement::new(el) }, num_hashes, } } } fn each_relevant_element_hash<E, F>(element: E, mut f: F) where E: TElement, F: FnMut(u32), { f(element.local_name().get_hash()); f(element.namespace().get_hash()); if let Some(id) = element.id() { f(id.get_hash()); } element.each_class(|class| f(class.get_hash())); } impl<E: TElement> Drop for StyleBloom<E> { fn drop(&mut self) { // Leave the reusable bloom filter in a zeroed state. self.clear(); } } impl<E: TElement> StyleBloom<E> { /// Create an empty `StyleBloom`. Because StyleBloom acquires the thread- /// local filter buffer, creating multiple live StyleBloom instances at /// the same time on the same thread will panic. // Forced out of line to limit stack frame sizes after extra inlining from // https://github.com/rust-lang/rust/pull/43931 // // See https://github.com/servo/servo/pull/18420#issuecomment-328769322 #[inline(never)] pub fn new() -> Self { let bloom_arc = BLOOM_KEY.with(|b| b.clone()); let filter = OwningHandle::new_with_fn(bloom_arc, |x| unsafe { x.as_ref() }.unwrap().borrow_mut()); debug_assert!( filter.is_zeroed(), "Forgot to zero the bloom filter last time" ); StyleBloom { filter: filter, elements: Default::default(), pushed_hashes: Default::default(), } } /// Return the bloom filter used properly by the `selectors` crate. pub fn filter(&self) -> &BloomFilter { &*self.filter } /// Push an element to the bloom filter, knowing that it's a child of the /// last element parent. pub fn push(&mut self, element: E) { if cfg!(debug_assertions) { if self.elements.is_empty() { assert!(element.traversal_parent().is_none()); } } self.push_internal(element); } /// Same as `push`, but without asserting, in order to use it from /// `rebuild`. fn push_internal(&mut self, element: E) { let mut count = 0; each_relevant_element_hash(element, |hash| { count += 1; self.filter.insert_hash(hash); self.pushed_hashes.push(hash); }); self.elements.push(PushedElement::new(element, count)); } /// Pop the last element in the bloom filter and return it. #[inline] fn pop(&mut self) -> Option<E> { let PushedElement { element, num_hashes, } = self.elements.pop()?; let popped_element = *element; // Verify that the pushed hashes match the ones we'd get from the element. let mut expected_hashes = vec![]; if cfg!(debug_assertions) { each_relevant_element_hash(popped_element, |hash| expected_hashes.push(hash)); } for _ in 0..num_hashes { let hash = self.pushed_hashes.pop().unwrap(); debug_assert_eq!(expected_hashes.pop().unwrap(), hash); self.filter.remove_hash(hash); } Some(popped_element) } /// Returns the DOM depth of elements that can be correctly /// matched against the bloom filter (that is, the number of /// elements in our list). pub fn matching_depth(&self) -> usize { self.elements.len() } /// Clears the bloom filter. pub fn clear(&mut self) { self.elements.clear(); if self.pushed_hashes.len() > MEMSET_CLEAR_THRESHOLD { self.filter.clear(); self.pushed_hashes.clear(); } else
} /// Rebuilds the bloom filter up to the parent of the given element. pub fn rebuild(&mut self, mut element: E) { self.clear(); let mut parents_to_insert = SmallVec::<[E; 16]>::new(); while let Some(parent) = element.traversal_parent() { parents_to_insert.push(parent); element = parent; } for parent in parents_to_insert.drain().rev() { self.push(parent); } } /// In debug builds, asserts that all the parents of `element` are in the /// bloom filter. /// /// Goes away in release builds. pub fn assert_complete(&self, mut element: E) { if cfg!(debug_assertions) { let mut checked = 0; while let Some(parent) = element.traversal_parent() { assert_eq!( parent, *(self.elements[self.elements.len() - 1 - checked].element) ); element = parent; checked += 1; } assert_eq!(checked, self.elements.len()); } } /// Get the element that represents the chain of things inserted /// into the filter right now. That chain is the given element /// (if any) and its ancestors. #[inline] pub fn current_parent(&self) -> Option<E> { self.elements.last().map(|ref el| *el.element) } /// Insert the parents of an element in the bloom filter, trying to recover /// the filter if the last element inserted doesn't match. /// /// Gets the element depth in the dom, to make it efficient, or if not /// provided always rebuilds the filter from scratch. /// /// Returns the new bloom filter depth, that the traversal code is /// responsible to keep around if it wants to get an effective filter. pub fn insert_parents_recovering(&mut self, element: E, element_depth: usize) { // Easy case, we're in a different restyle, or we're empty. if self.elements.is_empty() { self.rebuild(element); return; } let traversal_parent = match element.traversal_parent() { Some(parent) => parent, None => { // Yay, another easy case. self.clear(); return; }, }; if self.current_parent() == Some(traversal_parent) { // Ta da, cache hit, we're all done. return; } if element_depth == 0 { self.clear(); return; } // We should've early exited above. debug_assert!( element_depth!= 0, "We should have already cleared the bloom filter" ); debug_assert!(!self.elements.is_empty(), "How! We should've just rebuilt!"); // Now the fun begins: We have the depth of the dom and the depth of the // last element inserted in the filter, let's try to find a common // parent. // // The current depth, that is, the depth of the last element inserted in // the bloom filter, is the number of elements _minus one_, that is: if // there's one element, it must be the root -> depth zero. let mut current_depth = self.elements.len() - 1; // If the filter represents an element too deep in the dom, we need to // pop ancestors. while current_depth > element_depth - 1 { self.pop().expect("Emilio is bad at math"); current_depth -= 1; } // Now let's try to find a common parent in the bloom filter chain, // starting with traversal_parent. let mut common_parent = traversal_parent; let mut common_parent_depth = element_depth - 1; // Let's collect the parents we are going to need to insert once we've // found the common one. let mut parents_to_insert = SmallVec::<[E; 16]>::new(); // If the bloom filter still doesn't have enough elements, the common // parent is up in the dom. while common_parent_depth > current_depth { // TODO(emilio): Seems like we could insert parents here, then // reverse the slice. parents_to_insert.push(common_parent); common_parent = common_parent.traversal_parent().expect("We were lied to"); common_parent_depth -= 1; } // Now the two depths are the same. debug_assert_eq!(common_parent_depth, current_depth); // Happy case: The parents match, we only need to push the ancestors // we've collected and we'll never enter in this loop. // // Not-so-happy case: Parent's don't match, so we need to keep going up // until we find a common ancestor. // // Gecko currently models native anonymous content that conceptually // hangs off the document (such as scrollbars) as a separate subtree // from the document root. // // Thus it's possible with Gecko that we do not find any common // ancestor. while *(self.elements.last().unwrap().element)!= common_parent { parents_to_insert.push(common_parent); self.pop().unwrap(); common_parent = match common_parent.traversal_parent() { Some(parent) => parent, None => { debug_assert!(self.elements.is_empty()); if cfg!(feature = "gecko") { break; } else { panic!("should have found a common ancestor"); } }, } } // Now the parents match, so insert the stack of elements we have been // collecting so far. for parent in parents_to_insert.drain().rev() { self.push(parent); } debug_assert_eq!(self.elements.len(), element_depth); // We're done! Easy. } }
{ for hash in self.pushed_hashes.drain() { self.filter.remove_hash(hash); } debug_assert!(self.filter.is_zeroed()); }
conditional_block
filter.rs
use expression::{Expression, SelectableExpression, NonAggregate}; use expression::expression_methods::*; use expression::predicates::And; use helper_types::Filter; use query_builder::*; use query_dsl::FilterDsl; use query_source::QuerySource; use types::Bool; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct FilteredQuerySource<Source, Predicate> { source: Source, predicate: Predicate, } impl<Source, Predicate> FilteredQuerySource<Source, Predicate> { pub fn new(source: Source, predicate: Predicate) -> Self { FilteredQuerySource { source: source, predicate: predicate, } } } impl<Source, Predicate> AsQuery for FilteredQuerySource<Source, Predicate> where Predicate: SelectableExpression<Source, SqlType=Bool> + NonAggregate, Source: QuerySource + AsQuery, Source::Query: FilterDsl<Predicate>, { type SqlType = <Filter<Source::Query, Predicate> as AsQuery>::SqlType; type Query = <Filter<Source::Query, Predicate> as AsQuery>::Query; fn as_query(self) -> Self::Query { self.source.as_query().filter(self.predicate) .as_query() } } impl<Source, Predicate, NewPredicate> FilterDsl<NewPredicate> for FilteredQuerySource<Source, Predicate> where FilteredQuerySource<Source, And<Predicate, NewPredicate>>: AsQuery, Predicate: SelectableExpression<Source, SqlType=Bool>, NewPredicate: SelectableExpression<Source, SqlType=Bool> + NonAggregate, { type Output = FilteredQuerySource<Source, And<Predicate, NewPredicate>>; fn filter(self, predicate: NewPredicate) -> Self::Output { FilteredQuerySource::new(self.source, self.predicate.and(predicate))
} } impl<Source, Predicate> QuerySource for FilteredQuerySource<Source, Predicate> where Source: QuerySource, { fn from_clause(&self, out: &mut QueryBuilder) -> BuildQueryResult { self.source.from_clause(out) } } impl<Source, Predicate> UpdateTarget for FilteredQuerySource<Source, Predicate> where Source: UpdateTarget, Predicate: SelectableExpression<Source, SqlType=Bool>, { type Table = Source::Table; fn where_clause(&self, out: &mut QueryBuilder) -> BuildQueryResult { out.push_sql(" WHERE "); self.predicate.to_sql(out) } fn table(&self) -> &Self::Table { self.source.table() } }
random_line_split
filter.rs
use expression::{Expression, SelectableExpression, NonAggregate}; use expression::expression_methods::*; use expression::predicates::And; use helper_types::Filter; use query_builder::*; use query_dsl::FilterDsl; use query_source::QuerySource; use types::Bool; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct FilteredQuerySource<Source, Predicate> { source: Source, predicate: Predicate, } impl<Source, Predicate> FilteredQuerySource<Source, Predicate> { pub fn new(source: Source, predicate: Predicate) -> Self { FilteredQuerySource { source: source, predicate: predicate, } } } impl<Source, Predicate> AsQuery for FilteredQuerySource<Source, Predicate> where Predicate: SelectableExpression<Source, SqlType=Bool> + NonAggregate, Source: QuerySource + AsQuery, Source::Query: FilterDsl<Predicate>, { type SqlType = <Filter<Source::Query, Predicate> as AsQuery>::SqlType; type Query = <Filter<Source::Query, Predicate> as AsQuery>::Query; fn as_query(self) -> Self::Query { self.source.as_query().filter(self.predicate) .as_query() } } impl<Source, Predicate, NewPredicate> FilterDsl<NewPredicate> for FilteredQuerySource<Source, Predicate> where FilteredQuerySource<Source, And<Predicate, NewPredicate>>: AsQuery, Predicate: SelectableExpression<Source, SqlType=Bool>, NewPredicate: SelectableExpression<Source, SqlType=Bool> + NonAggregate, { type Output = FilteredQuerySource<Source, And<Predicate, NewPredicate>>; fn filter(self, predicate: NewPredicate) -> Self::Output { FilteredQuerySource::new(self.source, self.predicate.and(predicate)) } } impl<Source, Predicate> QuerySource for FilteredQuerySource<Source, Predicate> where Source: QuerySource, { fn from_clause(&self, out: &mut QueryBuilder) -> BuildQueryResult { self.source.from_clause(out) } } impl<Source, Predicate> UpdateTarget for FilteredQuerySource<Source, Predicate> where Source: UpdateTarget, Predicate: SelectableExpression<Source, SqlType=Bool>, { type Table = Source::Table; fn where_clause(&self, out: &mut QueryBuilder) -> BuildQueryResult
fn table(&self) -> &Self::Table { self.source.table() } }
{ out.push_sql(" WHERE "); self.predicate.to_sql(out) }
identifier_body
filter.rs
use expression::{Expression, SelectableExpression, NonAggregate}; use expression::expression_methods::*; use expression::predicates::And; use helper_types::Filter; use query_builder::*; use query_dsl::FilterDsl; use query_source::QuerySource; use types::Bool; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct
<Source, Predicate> { source: Source, predicate: Predicate, } impl<Source, Predicate> FilteredQuerySource<Source, Predicate> { pub fn new(source: Source, predicate: Predicate) -> Self { FilteredQuerySource { source: source, predicate: predicate, } } } impl<Source, Predicate> AsQuery for FilteredQuerySource<Source, Predicate> where Predicate: SelectableExpression<Source, SqlType=Bool> + NonAggregate, Source: QuerySource + AsQuery, Source::Query: FilterDsl<Predicate>, { type SqlType = <Filter<Source::Query, Predicate> as AsQuery>::SqlType; type Query = <Filter<Source::Query, Predicate> as AsQuery>::Query; fn as_query(self) -> Self::Query { self.source.as_query().filter(self.predicate) .as_query() } } impl<Source, Predicate, NewPredicate> FilterDsl<NewPredicate> for FilteredQuerySource<Source, Predicate> where FilteredQuerySource<Source, And<Predicate, NewPredicate>>: AsQuery, Predicate: SelectableExpression<Source, SqlType=Bool>, NewPredicate: SelectableExpression<Source, SqlType=Bool> + NonAggregate, { type Output = FilteredQuerySource<Source, And<Predicate, NewPredicate>>; fn filter(self, predicate: NewPredicate) -> Self::Output { FilteredQuerySource::new(self.source, self.predicate.and(predicate)) } } impl<Source, Predicate> QuerySource for FilteredQuerySource<Source, Predicate> where Source: QuerySource, { fn from_clause(&self, out: &mut QueryBuilder) -> BuildQueryResult { self.source.from_clause(out) } } impl<Source, Predicate> UpdateTarget for FilteredQuerySource<Source, Predicate> where Source: UpdateTarget, Predicate: SelectableExpression<Source, SqlType=Bool>, { type Table = Source::Table; fn where_clause(&self, out: &mut QueryBuilder) -> BuildQueryResult { out.push_sql(" WHERE "); self.predicate.to_sql(out) } fn table(&self) -> &Self::Table { self.source.table() } }
FilteredQuerySource
identifier_name
invalid-crate-type.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.
// regression test for issue 11256 #![crate_type="foo"] //~ ERROR invalid `crate_type` value // Tests for suggestions (#53958) #![crate_type="statoclib"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION staticlib #![crate_type="procmacro"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION proc-macro #![crate_type="static-lib"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION staticlib #![crate_type="drylib"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION dylib #![crate_type="dlib"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION rlib #![crate_type="lob"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION lib #![crate_type="bon"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION bin #![crate_type="cdalib"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION cdylib fn main() { return }
random_line_split
invalid-crate-type.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. // regression test for issue 11256 #![crate_type="foo"] //~ ERROR invalid `crate_type` value // Tests for suggestions (#53958) #![crate_type="statoclib"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION staticlib #![crate_type="procmacro"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION proc-macro #![crate_type="static-lib"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION staticlib #![crate_type="drylib"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION dylib #![crate_type="dlib"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION rlib #![crate_type="lob"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION lib #![crate_type="bon"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION bin #![crate_type="cdalib"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION cdylib fn main()
{ return }
identifier_body
invalid-crate-type.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. // regression test for issue 11256 #![crate_type="foo"] //~ ERROR invalid `crate_type` value // Tests for suggestions (#53958) #![crate_type="statoclib"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION staticlib #![crate_type="procmacro"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION proc-macro #![crate_type="static-lib"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION staticlib #![crate_type="drylib"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION dylib #![crate_type="dlib"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION rlib #![crate_type="lob"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION lib #![crate_type="bon"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION bin #![crate_type="cdalib"] //~^ ERROR invalid `crate_type` value //~| HELP did you mean //~| SUGGESTION cdylib fn
() { return }
main
identifier_name
issue-2631-a.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[link(name = "req")]; #[crate_type = "lib"]; extern mod extra; use std::hashmap::HashMap;
pub fn request<T:Copy>(req: &header_map) { let _x = copy *(copy **req.get(&~"METHOD"))[0u]; }
pub type header_map = HashMap<~str, @mut ~[@~str]>; // the unused ty param is necessary so this gets monomorphized
random_line_split
issue-2631-a.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[link(name = "req")]; #[crate_type = "lib"]; extern mod extra; use std::hashmap::HashMap; pub type header_map = HashMap<~str, @mut ~[@~str]>; // the unused ty param is necessary so this gets monomorphized pub fn
<T:Copy>(req: &header_map) { let _x = copy *(copy **req.get(&~"METHOD"))[0u]; }
request
identifier_name
issue-2631-a.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[link(name = "req")]; #[crate_type = "lib"]; extern mod extra; use std::hashmap::HashMap; pub type header_map = HashMap<~str, @mut ~[@~str]>; // the unused ty param is necessary so this gets monomorphized pub fn request<T:Copy>(req: &header_map)
{ let _x = copy *(copy **req.get(&~"METHOD"))[0u]; }
identifier_body
handle.rs
use std::{ffi::CString, sync::Arc}; use crate::{ core_interfaces::{WL_DISPLAY_INTERFACE, WL_REGISTRY_INTERFACE}, protocol::{same_interface, Argument, Interface, Message, ObjectInfo, ANONYMOUS_INTERFACE}, types::server::{DisconnectReason, GlobalInfo, InvalidId}, }; use smallvec::SmallVec; use super::{ client::ClientStore, registry::Registry, ClientData, ClientId, Credentials, Data, GlobalHandler, GlobalId, ObjectData, ObjectId, }; use crate::rs::map::Object; pub(crate) type PendingDestructor<D> = (Arc<dyn ObjectData<D>>, ClientId, ObjectId); /// Main handle of a backend to the Wayland protocol /// /// This type hosts most of the protocol-related functionality of the backend, and is the /// main entry point for manipulating Wayland objects. It can be retrieved both from /// the backend via [`Backend::handle()`](super::Backend::handle), and is given to you as argument /// in most event callbacks. #[derive(Debug)] pub struct Handle<D> { pub(crate) clients: ClientStore<D>, pub(crate) registry: Registry<D>, pub(crate) pending_destructors: Vec<PendingDestructor<D>>,
object_id: ObjectId, opcode: u16, arguments: SmallVec<[Argument<ObjectId>; 4]>, is_destructor: bool, created_id: Option<ObjectId>, }, Bind { object: ObjectId, client: ClientId, global: GlobalId, handler: Arc<dyn GlobalHandler<D>>, }, } impl<D> Handle<D> { pub(crate) fn new() -> Self { let debug = matches!(std::env::var_os("WAYLAND_DEBUG"), Some(str) if str == "1" || str == "server"); Handle { clients: ClientStore::new(debug), registry: Registry::new(), pending_destructors: Vec::new(), } } pub(crate) fn cleanup(&mut self, data: &mut D) { let dead_clients = self.clients.cleanup(data); self.registry.cleanup(&dead_clients); // invoke all pending destructors if relevant for (object_data, client_id, object_id) in self.pending_destructors.drain(..) { object_data.destroyed(data, client_id, object_id); } } pub(crate) fn dispatch_events_for( &mut self, data: &mut D, client_id: ClientId, ) -> std::io::Result<usize> { let mut dispatched = 0; loop { let action = if let Ok(client) = self.clients.get_client_mut(client_id.clone()) { let (message, object) = match client.next_request() { Ok(v) => v, Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { if dispatched > 0 { break; } else { return Err(e); } } Err(e) => return Err(e), }; dispatched += 1; if same_interface(object.interface, &WL_DISPLAY_INTERFACE) { client.handle_display_request(message, &mut self.registry); continue; } else if same_interface(object.interface, &WL_REGISTRY_INTERFACE) { if let Some((client, global, object, handler)) = client.handle_registry_request(message, &mut self.registry) { DispatchAction::Bind { client, global, object, handler } } else { continue; } } else { let object_id = ObjectId { id: message.sender_id, serial: object.data.serial, interface: object.interface, client_id: client.id.clone(), }; let opcode = message.opcode; let (arguments, is_destructor, created_id) = match client.process_request(&object, message) { Some(args) => args, None => continue, }; // Return the whole set to invoke the callback while handle is not borrower via client DispatchAction::Request { object, object_id, opcode, arguments, is_destructor, created_id, } } } else { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, "Invalid client ID", )); }; match action { DispatchAction::Request { object, object_id, opcode, arguments, is_destructor, created_id, } => { let ret = object.data.user_data.clone().request( self, data, client_id.clone(), Message { sender_id: object_id.clone(), opcode, args: arguments }, ); if is_destructor { object.data.user_data.destroyed(data, client_id.clone(), object_id.clone()); if let Ok(client) = self.clients.get_client_mut(client_id.clone()) { client.send_delete_id(object_id); } } match (created_id, ret) { (Some(child_id), Some(child_data)) => { if let Ok(client) = self.clients.get_client_mut(client_id.clone()) { client .map .with(child_id.id, |obj| obj.data.user_data = child_data) .unwrap(); } } (None, None) => {} (Some(child_id), None) => { // Allow the callback to not return any data if the client is already dead (typically // if the callback provoked a protocol error) if let Ok(client) = self.clients.get_client(client_id.clone()) { if!client.killed { panic!( "Callback creating object {} did not provide any object data.", child_id ); } } } (None, Some(_)) => { panic!("An object data was returned from a callback not creating any object"); } } } DispatchAction::Bind { object, client, global, handler } => { let child_data = handler.bind(self, data, client.clone(), global, object.clone()); if let Ok(client) = self.clients.get_client_mut(client.clone()) { client.map.with(object.id, |obj| obj.data.user_data = child_data).unwrap(); } } } } Ok(dispatched) } pub(crate) fn flush(&mut self, client: Option<ClientId>) -> std::io::Result<()> { if let Some(client) = client { match self.clients.get_client_mut(client) { Ok(client) => client.flush(), Err(InvalidId) => Ok(()), } } else { for client in self.clients.clients_mut() { let _ = client.flush(); } Ok(()) } } } impl<D> Handle<D> { /// Returns information about some object. pub fn object_info(&self, id: ObjectId) -> Result<ObjectInfo, InvalidId> { self.clients.get_client(id.client_id.clone())?.object_info(id) } /// Returns the id of the client which owns the object. pub fn get_client(&self, id: ObjectId) -> Result<ClientId, InvalidId> { if self.clients.get_client(id.client_id.clone()).is_ok() { Ok(id.client_id) } else { Err(InvalidId) } } /// Returns the data associated with a client. pub fn get_client_data(&self, id: ClientId) -> Result<Arc<dyn ClientData<D>>, InvalidId> { let client = self.clients.get_client(id)?; Ok(client.data.clone()) } /// Retrive the [`Credentials`] of a client pub fn get_client_credentials(&self, id: ClientId) -> Result<Credentials, InvalidId> { let client = self.clients.get_client(id)?; Ok(client.get_credentials()) } /// Returns an iterator over all clients connected to the server. pub fn all_clients<'a>(&'a self) -> Box<dyn Iterator<Item = ClientId> + 'a> { Box::new(self.clients.all_clients_id()) } /// Returns an iterator over all objects owned by a client. pub fn all_objects_for<'a>( &'a self, client_id: ClientId, ) -> Result<Box<dyn Iterator<Item = ObjectId> + 'a>, InvalidId> { let client = self.clients.get_client(client_id)?; Ok(Box::new(client.all_objects())) } /// Retrieve the `ObjectId` for a wayland object given its protocol numerical ID pub fn object_for_protocol_id( &self, client_id: ClientId, interface: &'static Interface, protocol_id: u32, ) -> Result<ObjectId, InvalidId> { let client = self.clients.get_client(client_id)?; let object = client.object_for_protocol_id(protocol_id)?; if same_interface(interface, object.interface) { Ok(object) } else { Err(InvalidId) } } /// Create a new object for given client /// /// To ensure state coherence of the protocol, the created object should be immediately /// sent as a "New ID" argument in an event to the client. pub fn create_object( &mut self, client_id: ClientId, interface: &'static Interface, version: u32, data: Arc<dyn ObjectData<D>>, ) -> Result<ObjectId, InvalidId> { let client = self.clients.get_client_mut(client_id)?; Ok(client.create_object(interface, version, data)) } /// Returns an object id that represents a null object. pub fn null_id(&mut self) -> ObjectId { ObjectId { id: 0, serial: 0, client_id: ClientId { id: 0, serial: 0 }, interface: &ANONYMOUS_INTERFACE, } } /// Send an event to the client /// /// Returns an error if the sender ID of the provided message is no longer valid. /// /// **Panic:** /// /// Checks against the protocol specification are done, and this method will panic if they do /// not pass: /// /// - the message opcode must be valid for the sender interface /// - the argument list must match the prototype for the message associated with this opcode pub fn send_event(&mut self, msg: Message<ObjectId>) -> Result<(), InvalidId> { self.clients .get_client_mut(msg.sender_id.client_id.clone())? .send_event(msg, Some(&mut self.pending_destructors)) } /// Returns the data associated with an object. pub fn get_object_data(&self, id: ObjectId) -> Result<Arc<dyn ObjectData<D>>, InvalidId> { self.clients.get_client(id.client_id.clone())?.get_object_data(id) } /// Sets the data associated with some object. pub fn set_object_data( &mut self, id: ObjectId, data: Arc<dyn ObjectData<D>>, ) -> Result<(), InvalidId> { self.clients.get_client_mut(id.client_id.clone())?.set_object_data(id, data) } /// Posts an error on an object. This will also disconnect the client which created the object. pub fn post_error(&mut self, object_id: ObjectId, error_code: u32, message: CString) { if let Ok(client) = self.clients.get_client_mut(object_id.client_id.clone()) { client.post_error(object_id, error_code, message) } } /// Kills the connection to a client. /// /// The disconnection reason determines the error message that is sent to the client (if any). pub fn kill_client(&mut self, client_id: ClientId, reason: DisconnectReason) { if let Ok(client) = self.clients.get_client_mut(client_id) { client.kill(reason) } } /// Creates a global of the specified interface and version and then advertises it to clients. /// /// The clients which the global is advertised to is determined by the implementation of the [`GlobalHandler`]. pub fn create_global( &mut self, interface: &'static Interface, version: u32, handler: Arc<dyn GlobalHandler<D>>, ) -> GlobalId { self.registry.create_global(interface, version, handler, &mut self.clients) } /// Disables a global object that is currently active. /// /// The global removal will be signaled to all currently connected clients. New clients will not know of the global, /// but the associated state and callbacks will not be freed. As such, clients that still try to bind the global /// afterwards (because they have not yet realized it was removed) will succeed. pub fn disable_global(&mut self, id: GlobalId) { self.registry.disable_global(id, &mut self.clients) } /// Removes a global object and free its ressources. /// /// The global object will no longer be considered valid by the server, clients trying to bind it will be killed, /// and the global ID is freed for re-use. /// /// It is advised to first disable a global and wait some amount of time before removing it, to ensure all clients /// are correctly aware of its removal. Note that clients will generally not expect globals that represent a capability /// of the server to be removed, as opposed to globals representing peripherals (like `wl_output` or `wl_seat`). pub fn remove_global(&mut self, id: GlobalId) { self.registry.remove_global(id, &mut self.clients) } /// Returns information about a global. pub fn global_info(&self, id: GlobalId) -> Result<GlobalInfo, InvalidId> { self.registry.get_info(id) } /// Returns the handler which manages the visibility and notifies when a client has bound the global. pub fn get_global_handler(&self, id: GlobalId) -> Result<Arc<dyn GlobalHandler<D>>, InvalidId> { self.registry.get_handler(id) } }
} enum DispatchAction<D> { Request { object: Object<Data<D>>,
random_line_split
handle.rs
use std::{ffi::CString, sync::Arc}; use crate::{ core_interfaces::{WL_DISPLAY_INTERFACE, WL_REGISTRY_INTERFACE}, protocol::{same_interface, Argument, Interface, Message, ObjectInfo, ANONYMOUS_INTERFACE}, types::server::{DisconnectReason, GlobalInfo, InvalidId}, }; use smallvec::SmallVec; use super::{ client::ClientStore, registry::Registry, ClientData, ClientId, Credentials, Data, GlobalHandler, GlobalId, ObjectData, ObjectId, }; use crate::rs::map::Object; pub(crate) type PendingDestructor<D> = (Arc<dyn ObjectData<D>>, ClientId, ObjectId); /// Main handle of a backend to the Wayland protocol /// /// This type hosts most of the protocol-related functionality of the backend, and is the /// main entry point for manipulating Wayland objects. It can be retrieved both from /// the backend via [`Backend::handle()`](super::Backend::handle), and is given to you as argument /// in most event callbacks. #[derive(Debug)] pub struct Handle<D> { pub(crate) clients: ClientStore<D>, pub(crate) registry: Registry<D>, pub(crate) pending_destructors: Vec<PendingDestructor<D>>, } enum DispatchAction<D> { Request { object: Object<Data<D>>, object_id: ObjectId, opcode: u16, arguments: SmallVec<[Argument<ObjectId>; 4]>, is_destructor: bool, created_id: Option<ObjectId>, }, Bind { object: ObjectId, client: ClientId, global: GlobalId, handler: Arc<dyn GlobalHandler<D>>, }, } impl<D> Handle<D> { pub(crate) fn new() -> Self { let debug = matches!(std::env::var_os("WAYLAND_DEBUG"), Some(str) if str == "1" || str == "server"); Handle { clients: ClientStore::new(debug), registry: Registry::new(), pending_destructors: Vec::new(), } } pub(crate) fn cleanup(&mut self, data: &mut D) { let dead_clients = self.clients.cleanup(data); self.registry.cleanup(&dead_clients); // invoke all pending destructors if relevant for (object_data, client_id, object_id) in self.pending_destructors.drain(..) { object_data.destroyed(data, client_id, object_id); } } pub(crate) fn dispatch_events_for( &mut self, data: &mut D, client_id: ClientId, ) -> std::io::Result<usize> { let mut dispatched = 0; loop { let action = if let Ok(client) = self.clients.get_client_mut(client_id.clone()) { let (message, object) = match client.next_request() { Ok(v) => v, Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { if dispatched > 0 { break; } else { return Err(e); } } Err(e) => return Err(e), }; dispatched += 1; if same_interface(object.interface, &WL_DISPLAY_INTERFACE) { client.handle_display_request(message, &mut self.registry); continue; } else if same_interface(object.interface, &WL_REGISTRY_INTERFACE) { if let Some((client, global, object, handler)) = client.handle_registry_request(message, &mut self.registry) { DispatchAction::Bind { client, global, object, handler } } else { continue; } } else { let object_id = ObjectId { id: message.sender_id, serial: object.data.serial, interface: object.interface, client_id: client.id.clone(), }; let opcode = message.opcode; let (arguments, is_destructor, created_id) = match client.process_request(&object, message) { Some(args) => args, None => continue, }; // Return the whole set to invoke the callback while handle is not borrower via client DispatchAction::Request { object, object_id, opcode, arguments, is_destructor, created_id, } } } else { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, "Invalid client ID", )); }; match action { DispatchAction::Request { object, object_id, opcode, arguments, is_destructor, created_id, } => { let ret = object.data.user_data.clone().request( self, data, client_id.clone(), Message { sender_id: object_id.clone(), opcode, args: arguments }, ); if is_destructor { object.data.user_data.destroyed(data, client_id.clone(), object_id.clone()); if let Ok(client) = self.clients.get_client_mut(client_id.clone()) { client.send_delete_id(object_id); } } match (created_id, ret) { (Some(child_id), Some(child_data)) => { if let Ok(client) = self.clients.get_client_mut(client_id.clone()) { client .map .with(child_id.id, |obj| obj.data.user_data = child_data) .unwrap(); } } (None, None) => {} (Some(child_id), None) => { // Allow the callback to not return any data if the client is already dead (typically // if the callback provoked a protocol error) if let Ok(client) = self.clients.get_client(client_id.clone()) { if!client.killed { panic!( "Callback creating object {} did not provide any object data.", child_id ); } } } (None, Some(_)) => { panic!("An object data was returned from a callback not creating any object"); } } } DispatchAction::Bind { object, client, global, handler } => { let child_data = handler.bind(self, data, client.clone(), global, object.clone()); if let Ok(client) = self.clients.get_client_mut(client.clone()) { client.map.with(object.id, |obj| obj.data.user_data = child_data).unwrap(); } } } } Ok(dispatched) } pub(crate) fn flush(&mut self, client: Option<ClientId>) -> std::io::Result<()> { if let Some(client) = client { match self.clients.get_client_mut(client) { Ok(client) => client.flush(), Err(InvalidId) => Ok(()), } } else { for client in self.clients.clients_mut() { let _ = client.flush(); } Ok(()) } } } impl<D> Handle<D> { /// Returns information about some object. pub fn object_info(&self, id: ObjectId) -> Result<ObjectInfo, InvalidId> { self.clients.get_client(id.client_id.clone())?.object_info(id) } /// Returns the id of the client which owns the object. pub fn get_client(&self, id: ObjectId) -> Result<ClientId, InvalidId> { if self.clients.get_client(id.client_id.clone()).is_ok() { Ok(id.client_id) } else { Err(InvalidId) } } /// Returns the data associated with a client. pub fn get_client_data(&self, id: ClientId) -> Result<Arc<dyn ClientData<D>>, InvalidId> { let client = self.clients.get_client(id)?; Ok(client.data.clone()) } /// Retrive the [`Credentials`] of a client pub fn
(&self, id: ClientId) -> Result<Credentials, InvalidId> { let client = self.clients.get_client(id)?; Ok(client.get_credentials()) } /// Returns an iterator over all clients connected to the server. pub fn all_clients<'a>(&'a self) -> Box<dyn Iterator<Item = ClientId> + 'a> { Box::new(self.clients.all_clients_id()) } /// Returns an iterator over all objects owned by a client. pub fn all_objects_for<'a>( &'a self, client_id: ClientId, ) -> Result<Box<dyn Iterator<Item = ObjectId> + 'a>, InvalidId> { let client = self.clients.get_client(client_id)?; Ok(Box::new(client.all_objects())) } /// Retrieve the `ObjectId` for a wayland object given its protocol numerical ID pub fn object_for_protocol_id( &self, client_id: ClientId, interface: &'static Interface, protocol_id: u32, ) -> Result<ObjectId, InvalidId> { let client = self.clients.get_client(client_id)?; let object = client.object_for_protocol_id(protocol_id)?; if same_interface(interface, object.interface) { Ok(object) } else { Err(InvalidId) } } /// Create a new object for given client /// /// To ensure state coherence of the protocol, the created object should be immediately /// sent as a "New ID" argument in an event to the client. pub fn create_object( &mut self, client_id: ClientId, interface: &'static Interface, version: u32, data: Arc<dyn ObjectData<D>>, ) -> Result<ObjectId, InvalidId> { let client = self.clients.get_client_mut(client_id)?; Ok(client.create_object(interface, version, data)) } /// Returns an object id that represents a null object. pub fn null_id(&mut self) -> ObjectId { ObjectId { id: 0, serial: 0, client_id: ClientId { id: 0, serial: 0 }, interface: &ANONYMOUS_INTERFACE, } } /// Send an event to the client /// /// Returns an error if the sender ID of the provided message is no longer valid. /// /// **Panic:** /// /// Checks against the protocol specification are done, and this method will panic if they do /// not pass: /// /// - the message opcode must be valid for the sender interface /// - the argument list must match the prototype for the message associated with this opcode pub fn send_event(&mut self, msg: Message<ObjectId>) -> Result<(), InvalidId> { self.clients .get_client_mut(msg.sender_id.client_id.clone())? .send_event(msg, Some(&mut self.pending_destructors)) } /// Returns the data associated with an object. pub fn get_object_data(&self, id: ObjectId) -> Result<Arc<dyn ObjectData<D>>, InvalidId> { self.clients.get_client(id.client_id.clone())?.get_object_data(id) } /// Sets the data associated with some object. pub fn set_object_data( &mut self, id: ObjectId, data: Arc<dyn ObjectData<D>>, ) -> Result<(), InvalidId> { self.clients.get_client_mut(id.client_id.clone())?.set_object_data(id, data) } /// Posts an error on an object. This will also disconnect the client which created the object. pub fn post_error(&mut self, object_id: ObjectId, error_code: u32, message: CString) { if let Ok(client) = self.clients.get_client_mut(object_id.client_id.clone()) { client.post_error(object_id, error_code, message) } } /// Kills the connection to a client. /// /// The disconnection reason determines the error message that is sent to the client (if any). pub fn kill_client(&mut self, client_id: ClientId, reason: DisconnectReason) { if let Ok(client) = self.clients.get_client_mut(client_id) { client.kill(reason) } } /// Creates a global of the specified interface and version and then advertises it to clients. /// /// The clients which the global is advertised to is determined by the implementation of the [`GlobalHandler`]. pub fn create_global( &mut self, interface: &'static Interface, version: u32, handler: Arc<dyn GlobalHandler<D>>, ) -> GlobalId { self.registry.create_global(interface, version, handler, &mut self.clients) } /// Disables a global object that is currently active. /// /// The global removal will be signaled to all currently connected clients. New clients will not know of the global, /// but the associated state and callbacks will not be freed. As such, clients that still try to bind the global /// afterwards (because they have not yet realized it was removed) will succeed. pub fn disable_global(&mut self, id: GlobalId) { self.registry.disable_global(id, &mut self.clients) } /// Removes a global object and free its ressources. /// /// The global object will no longer be considered valid by the server, clients trying to bind it will be killed, /// and the global ID is freed for re-use. /// /// It is advised to first disable a global and wait some amount of time before removing it, to ensure all clients /// are correctly aware of its removal. Note that clients will generally not expect globals that represent a capability /// of the server to be removed, as opposed to globals representing peripherals (like `wl_output` or `wl_seat`). pub fn remove_global(&mut self, id: GlobalId) { self.registry.remove_global(id, &mut self.clients) } /// Returns information about a global. pub fn global_info(&self, id: GlobalId) -> Result<GlobalInfo, InvalidId> { self.registry.get_info(id) } /// Returns the handler which manages the visibility and notifies when a client has bound the global. pub fn get_global_handler(&self, id: GlobalId) -> Result<Arc<dyn GlobalHandler<D>>, InvalidId> { self.registry.get_handler(id) } }
get_client_credentials
identifier_name
handle.rs
use std::{ffi::CString, sync::Arc}; use crate::{ core_interfaces::{WL_DISPLAY_INTERFACE, WL_REGISTRY_INTERFACE}, protocol::{same_interface, Argument, Interface, Message, ObjectInfo, ANONYMOUS_INTERFACE}, types::server::{DisconnectReason, GlobalInfo, InvalidId}, }; use smallvec::SmallVec; use super::{ client::ClientStore, registry::Registry, ClientData, ClientId, Credentials, Data, GlobalHandler, GlobalId, ObjectData, ObjectId, }; use crate::rs::map::Object; pub(crate) type PendingDestructor<D> = (Arc<dyn ObjectData<D>>, ClientId, ObjectId); /// Main handle of a backend to the Wayland protocol /// /// This type hosts most of the protocol-related functionality of the backend, and is the /// main entry point for manipulating Wayland objects. It can be retrieved both from /// the backend via [`Backend::handle()`](super::Backend::handle), and is given to you as argument /// in most event callbacks. #[derive(Debug)] pub struct Handle<D> { pub(crate) clients: ClientStore<D>, pub(crate) registry: Registry<D>, pub(crate) pending_destructors: Vec<PendingDestructor<D>>, } enum DispatchAction<D> { Request { object: Object<Data<D>>, object_id: ObjectId, opcode: u16, arguments: SmallVec<[Argument<ObjectId>; 4]>, is_destructor: bool, created_id: Option<ObjectId>, }, Bind { object: ObjectId, client: ClientId, global: GlobalId, handler: Arc<dyn GlobalHandler<D>>, }, } impl<D> Handle<D> { pub(crate) fn new() -> Self { let debug = matches!(std::env::var_os("WAYLAND_DEBUG"), Some(str) if str == "1" || str == "server"); Handle { clients: ClientStore::new(debug), registry: Registry::new(), pending_destructors: Vec::new(), } } pub(crate) fn cleanup(&mut self, data: &mut D) { let dead_clients = self.clients.cleanup(data); self.registry.cleanup(&dead_clients); // invoke all pending destructors if relevant for (object_data, client_id, object_id) in self.pending_destructors.drain(..) { object_data.destroyed(data, client_id, object_id); } } pub(crate) fn dispatch_events_for( &mut self, data: &mut D, client_id: ClientId, ) -> std::io::Result<usize> { let mut dispatched = 0; loop { let action = if let Ok(client) = self.clients.get_client_mut(client_id.clone()) { let (message, object) = match client.next_request() { Ok(v) => v, Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { if dispatched > 0 { break; } else { return Err(e); } } Err(e) => return Err(e), }; dispatched += 1; if same_interface(object.interface, &WL_DISPLAY_INTERFACE) { client.handle_display_request(message, &mut self.registry); continue; } else if same_interface(object.interface, &WL_REGISTRY_INTERFACE) { if let Some((client, global, object, handler)) = client.handle_registry_request(message, &mut self.registry) { DispatchAction::Bind { client, global, object, handler } } else { continue; } } else { let object_id = ObjectId { id: message.sender_id, serial: object.data.serial, interface: object.interface, client_id: client.id.clone(), }; let opcode = message.opcode; let (arguments, is_destructor, created_id) = match client.process_request(&object, message) { Some(args) => args, None => continue, }; // Return the whole set to invoke the callback while handle is not borrower via client DispatchAction::Request { object, object_id, opcode, arguments, is_destructor, created_id, } } } else { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, "Invalid client ID", )); }; match action { DispatchAction::Request { object, object_id, opcode, arguments, is_destructor, created_id, } => { let ret = object.data.user_data.clone().request( self, data, client_id.clone(), Message { sender_id: object_id.clone(), opcode, args: arguments }, ); if is_destructor { object.data.user_data.destroyed(data, client_id.clone(), object_id.clone()); if let Ok(client) = self.clients.get_client_mut(client_id.clone()) { client.send_delete_id(object_id); } } match (created_id, ret) { (Some(child_id), Some(child_data)) => { if let Ok(client) = self.clients.get_client_mut(client_id.clone()) { client .map .with(child_id.id, |obj| obj.data.user_data = child_data) .unwrap(); } } (None, None) => {} (Some(child_id), None) => { // Allow the callback to not return any data if the client is already dead (typically // if the callback provoked a protocol error) if let Ok(client) = self.clients.get_client(client_id.clone()) { if!client.killed { panic!( "Callback creating object {} did not provide any object data.", child_id ); } } } (None, Some(_)) => { panic!("An object data was returned from a callback not creating any object"); } } } DispatchAction::Bind { object, client, global, handler } => { let child_data = handler.bind(self, data, client.clone(), global, object.clone()); if let Ok(client) = self.clients.get_client_mut(client.clone()) { client.map.with(object.id, |obj| obj.data.user_data = child_data).unwrap(); } } } } Ok(dispatched) } pub(crate) fn flush(&mut self, client: Option<ClientId>) -> std::io::Result<()> { if let Some(client) = client { match self.clients.get_client_mut(client) { Ok(client) => client.flush(), Err(InvalidId) => Ok(()), } } else { for client in self.clients.clients_mut() { let _ = client.flush(); } Ok(()) } } } impl<D> Handle<D> { /// Returns information about some object. pub fn object_info(&self, id: ObjectId) -> Result<ObjectInfo, InvalidId> { self.clients.get_client(id.client_id.clone())?.object_info(id) } /// Returns the id of the client which owns the object. pub fn get_client(&self, id: ObjectId) -> Result<ClientId, InvalidId> { if self.clients.get_client(id.client_id.clone()).is_ok() { Ok(id.client_id) } else { Err(InvalidId) } } /// Returns the data associated with a client. pub fn get_client_data(&self, id: ClientId) -> Result<Arc<dyn ClientData<D>>, InvalidId> { let client = self.clients.get_client(id)?; Ok(client.data.clone()) } /// Retrive the [`Credentials`] of a client pub fn get_client_credentials(&self, id: ClientId) -> Result<Credentials, InvalidId> { let client = self.clients.get_client(id)?; Ok(client.get_credentials()) } /// Returns an iterator over all clients connected to the server. pub fn all_clients<'a>(&'a self) -> Box<dyn Iterator<Item = ClientId> + 'a> { Box::new(self.clients.all_clients_id()) } /// Returns an iterator over all objects owned by a client. pub fn all_objects_for<'a>( &'a self, client_id: ClientId, ) -> Result<Box<dyn Iterator<Item = ObjectId> + 'a>, InvalidId>
/// Retrieve the `ObjectId` for a wayland object given its protocol numerical ID pub fn object_for_protocol_id( &self, client_id: ClientId, interface: &'static Interface, protocol_id: u32, ) -> Result<ObjectId, InvalidId> { let client = self.clients.get_client(client_id)?; let object = client.object_for_protocol_id(protocol_id)?; if same_interface(interface, object.interface) { Ok(object) } else { Err(InvalidId) } } /// Create a new object for given client /// /// To ensure state coherence of the protocol, the created object should be immediately /// sent as a "New ID" argument in an event to the client. pub fn create_object( &mut self, client_id: ClientId, interface: &'static Interface, version: u32, data: Arc<dyn ObjectData<D>>, ) -> Result<ObjectId, InvalidId> { let client = self.clients.get_client_mut(client_id)?; Ok(client.create_object(interface, version, data)) } /// Returns an object id that represents a null object. pub fn null_id(&mut self) -> ObjectId { ObjectId { id: 0, serial: 0, client_id: ClientId { id: 0, serial: 0 }, interface: &ANONYMOUS_INTERFACE, } } /// Send an event to the client /// /// Returns an error if the sender ID of the provided message is no longer valid. /// /// **Panic:** /// /// Checks against the protocol specification are done, and this method will panic if they do /// not pass: /// /// - the message opcode must be valid for the sender interface /// - the argument list must match the prototype for the message associated with this opcode pub fn send_event(&mut self, msg: Message<ObjectId>) -> Result<(), InvalidId> { self.clients .get_client_mut(msg.sender_id.client_id.clone())? .send_event(msg, Some(&mut self.pending_destructors)) } /// Returns the data associated with an object. pub fn get_object_data(&self, id: ObjectId) -> Result<Arc<dyn ObjectData<D>>, InvalidId> { self.clients.get_client(id.client_id.clone())?.get_object_data(id) } /// Sets the data associated with some object. pub fn set_object_data( &mut self, id: ObjectId, data: Arc<dyn ObjectData<D>>, ) -> Result<(), InvalidId> { self.clients.get_client_mut(id.client_id.clone())?.set_object_data(id, data) } /// Posts an error on an object. This will also disconnect the client which created the object. pub fn post_error(&mut self, object_id: ObjectId, error_code: u32, message: CString) { if let Ok(client) = self.clients.get_client_mut(object_id.client_id.clone()) { client.post_error(object_id, error_code, message) } } /// Kills the connection to a client. /// /// The disconnection reason determines the error message that is sent to the client (if any). pub fn kill_client(&mut self, client_id: ClientId, reason: DisconnectReason) { if let Ok(client) = self.clients.get_client_mut(client_id) { client.kill(reason) } } /// Creates a global of the specified interface and version and then advertises it to clients. /// /// The clients which the global is advertised to is determined by the implementation of the [`GlobalHandler`]. pub fn create_global( &mut self, interface: &'static Interface, version: u32, handler: Arc<dyn GlobalHandler<D>>, ) -> GlobalId { self.registry.create_global(interface, version, handler, &mut self.clients) } /// Disables a global object that is currently active. /// /// The global removal will be signaled to all currently connected clients. New clients will not know of the global, /// but the associated state and callbacks will not be freed. As such, clients that still try to bind the global /// afterwards (because they have not yet realized it was removed) will succeed. pub fn disable_global(&mut self, id: GlobalId) { self.registry.disable_global(id, &mut self.clients) } /// Removes a global object and free its ressources. /// /// The global object will no longer be considered valid by the server, clients trying to bind it will be killed, /// and the global ID is freed for re-use. /// /// It is advised to first disable a global and wait some amount of time before removing it, to ensure all clients /// are correctly aware of its removal. Note that clients will generally not expect globals that represent a capability /// of the server to be removed, as opposed to globals representing peripherals (like `wl_output` or `wl_seat`). pub fn remove_global(&mut self, id: GlobalId) { self.registry.remove_global(id, &mut self.clients) } /// Returns information about a global. pub fn global_info(&self, id: GlobalId) -> Result<GlobalInfo, InvalidId> { self.registry.get_info(id) } /// Returns the handler which manages the visibility and notifies when a client has bound the global. pub fn get_global_handler(&self, id: GlobalId) -> Result<Arc<dyn GlobalHandler<D>>, InvalidId> { self.registry.get_handler(id) } }
{ let client = self.clients.get_client(client_id)?; Ok(Box::new(client.all_objects())) }
identifier_body
handle.rs
use std::{ffi::CString, sync::Arc}; use crate::{ core_interfaces::{WL_DISPLAY_INTERFACE, WL_REGISTRY_INTERFACE}, protocol::{same_interface, Argument, Interface, Message, ObjectInfo, ANONYMOUS_INTERFACE}, types::server::{DisconnectReason, GlobalInfo, InvalidId}, }; use smallvec::SmallVec; use super::{ client::ClientStore, registry::Registry, ClientData, ClientId, Credentials, Data, GlobalHandler, GlobalId, ObjectData, ObjectId, }; use crate::rs::map::Object; pub(crate) type PendingDestructor<D> = (Arc<dyn ObjectData<D>>, ClientId, ObjectId); /// Main handle of a backend to the Wayland protocol /// /// This type hosts most of the protocol-related functionality of the backend, and is the /// main entry point for manipulating Wayland objects. It can be retrieved both from /// the backend via [`Backend::handle()`](super::Backend::handle), and is given to you as argument /// in most event callbacks. #[derive(Debug)] pub struct Handle<D> { pub(crate) clients: ClientStore<D>, pub(crate) registry: Registry<D>, pub(crate) pending_destructors: Vec<PendingDestructor<D>>, } enum DispatchAction<D> { Request { object: Object<Data<D>>, object_id: ObjectId, opcode: u16, arguments: SmallVec<[Argument<ObjectId>; 4]>, is_destructor: bool, created_id: Option<ObjectId>, }, Bind { object: ObjectId, client: ClientId, global: GlobalId, handler: Arc<dyn GlobalHandler<D>>, }, } impl<D> Handle<D> { pub(crate) fn new() -> Self { let debug = matches!(std::env::var_os("WAYLAND_DEBUG"), Some(str) if str == "1" || str == "server"); Handle { clients: ClientStore::new(debug), registry: Registry::new(), pending_destructors: Vec::new(), } } pub(crate) fn cleanup(&mut self, data: &mut D) { let dead_clients = self.clients.cleanup(data); self.registry.cleanup(&dead_clients); // invoke all pending destructors if relevant for (object_data, client_id, object_id) in self.pending_destructors.drain(..) { object_data.destroyed(data, client_id, object_id); } } pub(crate) fn dispatch_events_for( &mut self, data: &mut D, client_id: ClientId, ) -> std::io::Result<usize> { let mut dispatched = 0; loop { let action = if let Ok(client) = self.clients.get_client_mut(client_id.clone()) { let (message, object) = match client.next_request() { Ok(v) => v, Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { if dispatched > 0 { break; } else { return Err(e); } } Err(e) => return Err(e), }; dispatched += 1; if same_interface(object.interface, &WL_DISPLAY_INTERFACE) { client.handle_display_request(message, &mut self.registry); continue; } else if same_interface(object.interface, &WL_REGISTRY_INTERFACE)
else { let object_id = ObjectId { id: message.sender_id, serial: object.data.serial, interface: object.interface, client_id: client.id.clone(), }; let opcode = message.opcode; let (arguments, is_destructor, created_id) = match client.process_request(&object, message) { Some(args) => args, None => continue, }; // Return the whole set to invoke the callback while handle is not borrower via client DispatchAction::Request { object, object_id, opcode, arguments, is_destructor, created_id, } } } else { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, "Invalid client ID", )); }; match action { DispatchAction::Request { object, object_id, opcode, arguments, is_destructor, created_id, } => { let ret = object.data.user_data.clone().request( self, data, client_id.clone(), Message { sender_id: object_id.clone(), opcode, args: arguments }, ); if is_destructor { object.data.user_data.destroyed(data, client_id.clone(), object_id.clone()); if let Ok(client) = self.clients.get_client_mut(client_id.clone()) { client.send_delete_id(object_id); } } match (created_id, ret) { (Some(child_id), Some(child_data)) => { if let Ok(client) = self.clients.get_client_mut(client_id.clone()) { client .map .with(child_id.id, |obj| obj.data.user_data = child_data) .unwrap(); } } (None, None) => {} (Some(child_id), None) => { // Allow the callback to not return any data if the client is already dead (typically // if the callback provoked a protocol error) if let Ok(client) = self.clients.get_client(client_id.clone()) { if!client.killed { panic!( "Callback creating object {} did not provide any object data.", child_id ); } } } (None, Some(_)) => { panic!("An object data was returned from a callback not creating any object"); } } } DispatchAction::Bind { object, client, global, handler } => { let child_data = handler.bind(self, data, client.clone(), global, object.clone()); if let Ok(client) = self.clients.get_client_mut(client.clone()) { client.map.with(object.id, |obj| obj.data.user_data = child_data).unwrap(); } } } } Ok(dispatched) } pub(crate) fn flush(&mut self, client: Option<ClientId>) -> std::io::Result<()> { if let Some(client) = client { match self.clients.get_client_mut(client) { Ok(client) => client.flush(), Err(InvalidId) => Ok(()), } } else { for client in self.clients.clients_mut() { let _ = client.flush(); } Ok(()) } } } impl<D> Handle<D> { /// Returns information about some object. pub fn object_info(&self, id: ObjectId) -> Result<ObjectInfo, InvalidId> { self.clients.get_client(id.client_id.clone())?.object_info(id) } /// Returns the id of the client which owns the object. pub fn get_client(&self, id: ObjectId) -> Result<ClientId, InvalidId> { if self.clients.get_client(id.client_id.clone()).is_ok() { Ok(id.client_id) } else { Err(InvalidId) } } /// Returns the data associated with a client. pub fn get_client_data(&self, id: ClientId) -> Result<Arc<dyn ClientData<D>>, InvalidId> { let client = self.clients.get_client(id)?; Ok(client.data.clone()) } /// Retrive the [`Credentials`] of a client pub fn get_client_credentials(&self, id: ClientId) -> Result<Credentials, InvalidId> { let client = self.clients.get_client(id)?; Ok(client.get_credentials()) } /// Returns an iterator over all clients connected to the server. pub fn all_clients<'a>(&'a self) -> Box<dyn Iterator<Item = ClientId> + 'a> { Box::new(self.clients.all_clients_id()) } /// Returns an iterator over all objects owned by a client. pub fn all_objects_for<'a>( &'a self, client_id: ClientId, ) -> Result<Box<dyn Iterator<Item = ObjectId> + 'a>, InvalidId> { let client = self.clients.get_client(client_id)?; Ok(Box::new(client.all_objects())) } /// Retrieve the `ObjectId` for a wayland object given its protocol numerical ID pub fn object_for_protocol_id( &self, client_id: ClientId, interface: &'static Interface, protocol_id: u32, ) -> Result<ObjectId, InvalidId> { let client = self.clients.get_client(client_id)?; let object = client.object_for_protocol_id(protocol_id)?; if same_interface(interface, object.interface) { Ok(object) } else { Err(InvalidId) } } /// Create a new object for given client /// /// To ensure state coherence of the protocol, the created object should be immediately /// sent as a "New ID" argument in an event to the client. pub fn create_object( &mut self, client_id: ClientId, interface: &'static Interface, version: u32, data: Arc<dyn ObjectData<D>>, ) -> Result<ObjectId, InvalidId> { let client = self.clients.get_client_mut(client_id)?; Ok(client.create_object(interface, version, data)) } /// Returns an object id that represents a null object. pub fn null_id(&mut self) -> ObjectId { ObjectId { id: 0, serial: 0, client_id: ClientId { id: 0, serial: 0 }, interface: &ANONYMOUS_INTERFACE, } } /// Send an event to the client /// /// Returns an error if the sender ID of the provided message is no longer valid. /// /// **Panic:** /// /// Checks against the protocol specification are done, and this method will panic if they do /// not pass: /// /// - the message opcode must be valid for the sender interface /// - the argument list must match the prototype for the message associated with this opcode pub fn send_event(&mut self, msg: Message<ObjectId>) -> Result<(), InvalidId> { self.clients .get_client_mut(msg.sender_id.client_id.clone())? .send_event(msg, Some(&mut self.pending_destructors)) } /// Returns the data associated with an object. pub fn get_object_data(&self, id: ObjectId) -> Result<Arc<dyn ObjectData<D>>, InvalidId> { self.clients.get_client(id.client_id.clone())?.get_object_data(id) } /// Sets the data associated with some object. pub fn set_object_data( &mut self, id: ObjectId, data: Arc<dyn ObjectData<D>>, ) -> Result<(), InvalidId> { self.clients.get_client_mut(id.client_id.clone())?.set_object_data(id, data) } /// Posts an error on an object. This will also disconnect the client which created the object. pub fn post_error(&mut self, object_id: ObjectId, error_code: u32, message: CString) { if let Ok(client) = self.clients.get_client_mut(object_id.client_id.clone()) { client.post_error(object_id, error_code, message) } } /// Kills the connection to a client. /// /// The disconnection reason determines the error message that is sent to the client (if any). pub fn kill_client(&mut self, client_id: ClientId, reason: DisconnectReason) { if let Ok(client) = self.clients.get_client_mut(client_id) { client.kill(reason) } } /// Creates a global of the specified interface and version and then advertises it to clients. /// /// The clients which the global is advertised to is determined by the implementation of the [`GlobalHandler`]. pub fn create_global( &mut self, interface: &'static Interface, version: u32, handler: Arc<dyn GlobalHandler<D>>, ) -> GlobalId { self.registry.create_global(interface, version, handler, &mut self.clients) } /// Disables a global object that is currently active. /// /// The global removal will be signaled to all currently connected clients. New clients will not know of the global, /// but the associated state and callbacks will not be freed. As such, clients that still try to bind the global /// afterwards (because they have not yet realized it was removed) will succeed. pub fn disable_global(&mut self, id: GlobalId) { self.registry.disable_global(id, &mut self.clients) } /// Removes a global object and free its ressources. /// /// The global object will no longer be considered valid by the server, clients trying to bind it will be killed, /// and the global ID is freed for re-use. /// /// It is advised to first disable a global and wait some amount of time before removing it, to ensure all clients /// are correctly aware of its removal. Note that clients will generally not expect globals that represent a capability /// of the server to be removed, as opposed to globals representing peripherals (like `wl_output` or `wl_seat`). pub fn remove_global(&mut self, id: GlobalId) { self.registry.remove_global(id, &mut self.clients) } /// Returns information about a global. pub fn global_info(&self, id: GlobalId) -> Result<GlobalInfo, InvalidId> { self.registry.get_info(id) } /// Returns the handler which manages the visibility and notifies when a client has bound the global. pub fn get_global_handler(&self, id: GlobalId) -> Result<Arc<dyn GlobalHandler<D>>, InvalidId> { self.registry.get_handler(id) } }
{ if let Some((client, global, object, handler)) = client.handle_registry_request(message, &mut self.registry) { DispatchAction::Bind { client, global, object, handler } } else { continue; } }
conditional_block
registry.rs
use std::collections::HashSet; use std::collections::hash_map::HashMap; use core::{Source, SourceId, SourceMap, Summary, Dependency, PackageId, Package}; use util::{CargoResult, ChainError, Config, human, profile}; /// Source of information about a group of packages. /// /// See also `core::Source`. pub trait Registry { /// Attempt to find the packages that match a dependency request. fn query(&mut self, name: &Dependency) -> CargoResult<Vec<Summary>>; } impl Registry for Vec<Summary> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { Ok(self.iter().filter(|summary| dep.matches(*summary)) .map(|summary| summary.clone()).collect()) } } impl Registry for Vec<Package> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { Ok(self.iter().filter(|pkg| dep.matches(pkg.summary())) .map(|pkg| pkg.summary().clone()).collect()) } } /// This structure represents a registry of known packages. It internally /// contains a number of `Box<Source>` instances which are used to load a /// `Package` from. /// /// The resolution phase of Cargo uses this to drive knowledge about new /// packages as well as querying for lists of new packages. It is here that /// sources are updated (e.g. network operations) and overrides are /// handled. /// /// The general idea behind this registry is that it is centered around the /// `SourceMap` structure, contained within which is a mapping of a `SourceId` to /// a `Source`. Each `Source` in the map has been updated (using network /// operations if necessary) and is ready to be queried for packages. pub struct PackageRegistry<'cfg> { sources: SourceMap<'cfg>, config: &'cfg Config, // A list of sources which are considered "overrides" which take precedent // when querying for packages. overrides: Vec<SourceId>, // Note that each SourceId does not take into account its `precise` field // when hashing or testing for equality. When adding a new `SourceId`, we // want to avoid duplicates in the `SourceMap` (to prevent re-updating the // same git repo twice for example), but we also want to ensure that the // loaded source is always updated. // // Sources with a `precise` field normally don't need to be updated because // their contents are already on disk, but sources without a `precise` field // almost always need to be updated. If we have a cached `Source` for a // precise `SourceId`, then when we add a new `SourceId` that is not precise // we want to ensure that the underlying source is updated. // // This is basically a long-winded way of saying that we want to know // precisely what the keys of `sources` are, so this is a mapping of key to // what exactly the key is. source_ids: HashMap<SourceId, (SourceId, Kind)>, locked: HashMap<SourceId, HashMap<String, Vec<(PackageId, Vec<PackageId>)>>>, } #[derive(PartialEq, Eq, Clone, Copy)] enum Kind { Override, Locked, Normal, } impl<'cfg> PackageRegistry<'cfg> { pub fn new(config: &'cfg Config) -> PackageRegistry<'cfg> { PackageRegistry { sources: SourceMap::new(), source_ids: HashMap::new(), overrides: vec!(), config: config, locked: HashMap::new(), } } pub fn get(&mut self, package_ids: &[PackageId]) -> CargoResult<Vec<Package>> { trace!("getting packages; sources={}", self.sources.len()); // TODO: Only call source with package ID if the package came from the // source let mut ret = Vec::new(); for (_, source) in self.sources.sources_mut() { try!(source.download(package_ids)); let packages = try!(source.get(package_ids)); ret.extend(packages.into_iter()); } // TODO: Return earlier if fail assert!(package_ids.len() == ret.len(), "could not get packages from registry; ids={:?}; ret={:?}", package_ids, ret); Ok(ret) } pub fn move_sources(self) -> SourceMap<'cfg> { self.sources } fn ensure_loaded(&mut self, namespace: &SourceId) -> CargoResult<()> { match self.source_ids.get(namespace) { // We've previously loaded this source, and we've already locked it, // so we're not allowed to change it even if `namespace` has a // slightly different precise version listed. Some(&(_, Kind::Locked)) => { debug!("load/locked {}", namespace); return Ok(()) } // If the previous source was not a precise source, then we can be // sure that it's already been updated if we've already loaded it. Some(&(ref previous, _)) if previous.precise().is_none() => { debug!("load/precise {}", namespace); return Ok(()) } // If the previous source has the same precise version as we do, // then we're done, otherwise we need to need to move forward // updating this source. Some(&(ref previous, _)) => { if previous.precise() == namespace.precise() { debug!("load/match {}", namespace); return Ok(()) } debug!("load/mismatch {}", namespace); } None => { debug!("load/missing {}", namespace); } } try!(self.load(namespace, Kind::Normal)); Ok(()) } pub fn preload(&mut self, id: &SourceId, source: Box<Source + 'cfg>) { self.sources.insert(id, source); self.source_ids.insert(id.clone(), (id.clone(), Kind::Locked)); } pub fn add_sources(&mut self, ids: &[SourceId]) -> CargoResult<()> { for id in ids.iter() { try!(self.load(id, Kind::Locked)); } Ok(()) } pub fn add_overrides(&mut self, ids: Vec<SourceId>) -> CargoResult<()> { for id in ids.iter() { try!(self.load(id, Kind::Override)); } Ok(()) } pub fn register_lock(&mut self, id: PackageId, deps: Vec<PackageId>) { let sub_map = self.locked.entry(id.source_id().clone()) .or_insert(HashMap::new()); let sub_vec = sub_map.entry(id.name().to_string()) .or_insert(Vec::new()); sub_vec.push((id, deps)); } fn load(&mut self, source_id: &SourceId, kind: Kind) -> CargoResult<()> { (|| { let mut source = source_id.load(self.config); // Ensure the source has fetched all necessary remote data. let p = profile::start(format!("updating: {}", source_id)); try!(source.update()); drop(p); if kind == Kind::Override { self.overrides.push(source_id.clone()); } // Save off the source self.sources.insert(source_id, source); self.source_ids.insert(source_id.clone(), (source_id.clone(), kind)); Ok(()) }).chain_error(|| human(format!("Unable to update {}", source_id))) } fn query_overrides(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { let mut seen = HashSet::new(); let mut ret = Vec::new(); for s in self.overrides.iter() { let src = self.sources.get_mut(s).unwrap(); let dep = Dependency::new_override(dep.name(), s); ret.extend(try!(src.query(&dep)).into_iter().filter(|s| { seen.insert(s.name().to_string()) })); } Ok(ret) } // This function is used to transform a summary to another locked summary if // possible. This is where the concept of a lockfile comes into play. // // If a summary points at a package id which was previously locked, then we // override the summary's id itself, as well as all dependencies, to be // rewritten to the locked versions. This will transform the summary's // source to a precise source (listed in the locked version) as well as // transforming all of the dependencies from range requirements on imprecise // sources to exact requirements on precise sources. // // If a summary does not point at a package id which was previously locked, // we still want to avoid updating as many dependencies as possible to keep // the graph stable. In this case we map all of the summary's dependencies // to be rewritten to a locked version wherever possible. If we're unable to // map a dependency though, we just pass it on through. fn lock(&self, summary: Summary) -> Summary { let pair = self.locked.get(summary.source_id()).and_then(|map| { map.get(summary.name()) }).and_then(|vec| { vec.iter().find(|&&(ref id, _)| id == summary.package_id()) }); // Lock the summary's id if possible let summary = match pair { Some(&(ref precise, _)) => summary.override_id(precise.clone()), None => summary, }; summary.map_dependencies(|dep| { match pair { // If we've got a known set of overrides for this summary, then // one of a few cases can arise: // // 1. We have a lock entry for this dependency from the same // source as it's listed as coming from. In this case we make // sure to lock to precisely the given package id. // // 2. We have a lock entry for this dependency, but it's from a // different source than what's listed, or the version // requirement has changed. In this case we must discard the // locked version because the dependency needs to be // re-resolved. // // 3. We don't have a lock entry for this dependency, in which // case it was likely an optional dependency which wasn't // included previously so we just pass it through anyway. Some(&(_, ref deps)) => { match deps.iter().find(|d| d.name() == dep.name()) { Some(lock) => { if dep.matches_id(lock) { dep.lock_to(lock) } else { dep } } None => dep, } } // If this summary did not have a locked version, then we query // all known locked packages to see if they match this // dependency. If anything does then we lock it to that and move // on. None => { let v = self.locked.get(dep.source_id()).and_then(|map| { map.get(dep.name()) }).and_then(|vec| { vec.iter().find(|&&(ref id, _)| dep.matches_id(id)) }); match v { Some(&(ref id, _)) => dep.lock_to(id), None => dep } } } }) } } impl<'cfg> Registry for PackageRegistry<'cfg> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { let overrides = try!(self.query_overrides(dep)); let ret = if overrides.len() == 0 { // Ensure the requested source_id is loaded try!(self.ensure_loaded(dep.source_id())); let mut ret = Vec::new(); for (id, src) in self.sources.sources_mut() { if id == dep.source_id() { ret.extend(try!(src.query(dep)).into_iter()); } } ret } else { overrides }; // post-process all returned summaries to ensure that we lock all // relevant summaries to the right versions and sources Ok(ret.into_iter().map(|summary| self.lock(summary)).collect()) } } #[cfg(test)] pub mod test { use core::{Summary, Registry, Dependency}; use util::{CargoResult}; pub struct RegistryBuilder { summaries: Vec<Summary>, overrides: Vec<Summary> } impl RegistryBuilder { pub fn new() -> RegistryBuilder { RegistryBuilder { summaries: vec!(), overrides: vec!() } } pub fn summary(mut self, summary: Summary) -> RegistryBuilder { self.summaries.push(summary); self } pub fn summaries(mut self, summaries: Vec<Summary>) -> RegistryBuilder { self.summaries.extend(summaries.into_iter()); self } pub fn add_override(mut self, summary: Summary) -> RegistryBuilder
pub fn overrides(mut self, summaries: Vec<Summary>) -> RegistryBuilder { self.overrides.extend(summaries.into_iter()); self } fn query_overrides(&self, dep: &Dependency) -> Vec<Summary> { self.overrides.iter() .filter(|s| s.name() == dep.name()) .map(|s| s.clone()) .collect() } } impl Registry for RegistryBuilder { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { debug!("querying; dep={:?}", dep); let overrides = self.query_overrides(dep); if overrides.is_empty() { self.summaries.query(dep) } else { Ok(overrides) } } } }
{ self.overrides.push(summary); self }
identifier_body
registry.rs
use std::collections::HashSet; use std::collections::hash_map::HashMap; use core::{Source, SourceId, SourceMap, Summary, Dependency, PackageId, Package}; use util::{CargoResult, ChainError, Config, human, profile}; /// Source of information about a group of packages. /// /// See also `core::Source`. pub trait Registry { /// Attempt to find the packages that match a dependency request. fn query(&mut self, name: &Dependency) -> CargoResult<Vec<Summary>>; } impl Registry for Vec<Summary> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { Ok(self.iter().filter(|summary| dep.matches(*summary)) .map(|summary| summary.clone()).collect()) } } impl Registry for Vec<Package> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { Ok(self.iter().filter(|pkg| dep.matches(pkg.summary())) .map(|pkg| pkg.summary().clone()).collect()) } } /// This structure represents a registry of known packages. It internally /// contains a number of `Box<Source>` instances which are used to load a /// `Package` from. /// /// The resolution phase of Cargo uses this to drive knowledge about new /// packages as well as querying for lists of new packages. It is here that /// sources are updated (e.g. network operations) and overrides are /// handled. /// /// The general idea behind this registry is that it is centered around the /// `SourceMap` structure, contained within which is a mapping of a `SourceId` to /// a `Source`. Each `Source` in the map has been updated (using network /// operations if necessary) and is ready to be queried for packages. pub struct PackageRegistry<'cfg> { sources: SourceMap<'cfg>, config: &'cfg Config, // A list of sources which are considered "overrides" which take precedent // when querying for packages. overrides: Vec<SourceId>, // Note that each SourceId does not take into account its `precise` field // when hashing or testing for equality. When adding a new `SourceId`, we // want to avoid duplicates in the `SourceMap` (to prevent re-updating the // same git repo twice for example), but we also want to ensure that the // loaded source is always updated. // // Sources with a `precise` field normally don't need to be updated because // their contents are already on disk, but sources without a `precise` field // almost always need to be updated. If we have a cached `Source` for a // precise `SourceId`, then when we add a new `SourceId` that is not precise // we want to ensure that the underlying source is updated. // // This is basically a long-winded way of saying that we want to know // precisely what the keys of `sources` are, so this is a mapping of key to // what exactly the key is. source_ids: HashMap<SourceId, (SourceId, Kind)>, locked: HashMap<SourceId, HashMap<String, Vec<(PackageId, Vec<PackageId>)>>>, } #[derive(PartialEq, Eq, Clone, Copy)] enum Kind { Override, Locked, Normal, } impl<'cfg> PackageRegistry<'cfg> { pub fn new(config: &'cfg Config) -> PackageRegistry<'cfg> { PackageRegistry { sources: SourceMap::new(), source_ids: HashMap::new(), overrides: vec!(), config: config, locked: HashMap::new(), } } pub fn get(&mut self, package_ids: &[PackageId]) -> CargoResult<Vec<Package>> { trace!("getting packages; sources={}", self.sources.len()); // TODO: Only call source with package ID if the package came from the // source let mut ret = Vec::new(); for (_, source) in self.sources.sources_mut() { try!(source.download(package_ids)); let packages = try!(source.get(package_ids)); ret.extend(packages.into_iter()); } // TODO: Return earlier if fail assert!(package_ids.len() == ret.len(), "could not get packages from registry; ids={:?}; ret={:?}", package_ids, ret); Ok(ret) } pub fn move_sources(self) -> SourceMap<'cfg> { self.sources } fn ensure_loaded(&mut self, namespace: &SourceId) -> CargoResult<()> { match self.source_ids.get(namespace) { // We've previously loaded this source, and we've already locked it, // so we're not allowed to change it even if `namespace` has a // slightly different precise version listed. Some(&(_, Kind::Locked)) => { debug!("load/locked {}", namespace); return Ok(()) } // If the previous source was not a precise source, then we can be // sure that it's already been updated if we've already loaded it. Some(&(ref previous, _)) if previous.precise().is_none() => { debug!("load/precise {}", namespace); return Ok(()) } // If the previous source has the same precise version as we do, // then we're done, otherwise we need to need to move forward // updating this source. Some(&(ref previous, _)) => { if previous.precise() == namespace.precise() { debug!("load/match {}", namespace); return Ok(()) } debug!("load/mismatch {}", namespace); } None => { debug!("load/missing {}", namespace); } } try!(self.load(namespace, Kind::Normal)); Ok(()) } pub fn preload(&mut self, id: &SourceId, source: Box<Source + 'cfg>) { self.sources.insert(id, source); self.source_ids.insert(id.clone(), (id.clone(), Kind::Locked)); } pub fn add_sources(&mut self, ids: &[SourceId]) -> CargoResult<()> { for id in ids.iter() { try!(self.load(id, Kind::Locked)); } Ok(()) } pub fn add_overrides(&mut self, ids: Vec<SourceId>) -> CargoResult<()> { for id in ids.iter() { try!(self.load(id, Kind::Override)); } Ok(()) } pub fn register_lock(&mut self, id: PackageId, deps: Vec<PackageId>) { let sub_map = self.locked.entry(id.source_id().clone()) .or_insert(HashMap::new()); let sub_vec = sub_map.entry(id.name().to_string()) .or_insert(Vec::new()); sub_vec.push((id, deps)); } fn load(&mut self, source_id: &SourceId, kind: Kind) -> CargoResult<()> { (|| { let mut source = source_id.load(self.config); // Ensure the source has fetched all necessary remote data. let p = profile::start(format!("updating: {}", source_id)); try!(source.update()); drop(p); if kind == Kind::Override { self.overrides.push(source_id.clone()); } // Save off the source self.sources.insert(source_id, source); self.source_ids.insert(source_id.clone(), (source_id.clone(), kind)); Ok(()) }).chain_error(|| human(format!("Unable to update {}", source_id))) } fn query_overrides(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { let mut seen = HashSet::new(); let mut ret = Vec::new(); for s in self.overrides.iter() { let src = self.sources.get_mut(s).unwrap(); let dep = Dependency::new_override(dep.name(), s); ret.extend(try!(src.query(&dep)).into_iter().filter(|s| { seen.insert(s.name().to_string()) })); } Ok(ret) } // This function is used to transform a summary to another locked summary if // possible. This is where the concept of a lockfile comes into play. // // If a summary points at a package id which was previously locked, then we // override the summary's id itself, as well as all dependencies, to be // rewritten to the locked versions. This will transform the summary's // source to a precise source (listed in the locked version) as well as // transforming all of the dependencies from range requirements on imprecise // sources to exact requirements on precise sources. // // If a summary does not point at a package id which was previously locked, // we still want to avoid updating as many dependencies as possible to keep // the graph stable. In this case we map all of the summary's dependencies // to be rewritten to a locked version wherever possible. If we're unable to // map a dependency though, we just pass it on through. fn
(&self, summary: Summary) -> Summary { let pair = self.locked.get(summary.source_id()).and_then(|map| { map.get(summary.name()) }).and_then(|vec| { vec.iter().find(|&&(ref id, _)| id == summary.package_id()) }); // Lock the summary's id if possible let summary = match pair { Some(&(ref precise, _)) => summary.override_id(precise.clone()), None => summary, }; summary.map_dependencies(|dep| { match pair { // If we've got a known set of overrides for this summary, then // one of a few cases can arise: // // 1. We have a lock entry for this dependency from the same // source as it's listed as coming from. In this case we make // sure to lock to precisely the given package id. // // 2. We have a lock entry for this dependency, but it's from a // different source than what's listed, or the version // requirement has changed. In this case we must discard the // locked version because the dependency needs to be // re-resolved. // // 3. We don't have a lock entry for this dependency, in which // case it was likely an optional dependency which wasn't // included previously so we just pass it through anyway. Some(&(_, ref deps)) => { match deps.iter().find(|d| d.name() == dep.name()) { Some(lock) => { if dep.matches_id(lock) { dep.lock_to(lock) } else { dep } } None => dep, } } // If this summary did not have a locked version, then we query // all known locked packages to see if they match this // dependency. If anything does then we lock it to that and move // on. None => { let v = self.locked.get(dep.source_id()).and_then(|map| { map.get(dep.name()) }).and_then(|vec| { vec.iter().find(|&&(ref id, _)| dep.matches_id(id)) }); match v { Some(&(ref id, _)) => dep.lock_to(id), None => dep } } } }) } } impl<'cfg> Registry for PackageRegistry<'cfg> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { let overrides = try!(self.query_overrides(dep)); let ret = if overrides.len() == 0 { // Ensure the requested source_id is loaded try!(self.ensure_loaded(dep.source_id())); let mut ret = Vec::new(); for (id, src) in self.sources.sources_mut() { if id == dep.source_id() { ret.extend(try!(src.query(dep)).into_iter()); } } ret } else { overrides }; // post-process all returned summaries to ensure that we lock all // relevant summaries to the right versions and sources Ok(ret.into_iter().map(|summary| self.lock(summary)).collect()) } } #[cfg(test)] pub mod test { use core::{Summary, Registry, Dependency}; use util::{CargoResult}; pub struct RegistryBuilder { summaries: Vec<Summary>, overrides: Vec<Summary> } impl RegistryBuilder { pub fn new() -> RegistryBuilder { RegistryBuilder { summaries: vec!(), overrides: vec!() } } pub fn summary(mut self, summary: Summary) -> RegistryBuilder { self.summaries.push(summary); self } pub fn summaries(mut self, summaries: Vec<Summary>) -> RegistryBuilder { self.summaries.extend(summaries.into_iter()); self } pub fn add_override(mut self, summary: Summary) -> RegistryBuilder { self.overrides.push(summary); self } pub fn overrides(mut self, summaries: Vec<Summary>) -> RegistryBuilder { self.overrides.extend(summaries.into_iter()); self } fn query_overrides(&self, dep: &Dependency) -> Vec<Summary> { self.overrides.iter() .filter(|s| s.name() == dep.name()) .map(|s| s.clone()) .collect() } } impl Registry for RegistryBuilder { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { debug!("querying; dep={:?}", dep); let overrides = self.query_overrides(dep); if overrides.is_empty() { self.summaries.query(dep) } else { Ok(overrides) } } } }
lock
identifier_name
registry.rs
use std::collections::HashSet; use std::collections::hash_map::HashMap; use core::{Source, SourceId, SourceMap, Summary, Dependency, PackageId, Package}; use util::{CargoResult, ChainError, Config, human, profile}; /// Source of information about a group of packages. /// /// See also `core::Source`. pub trait Registry { /// Attempt to find the packages that match a dependency request. fn query(&mut self, name: &Dependency) -> CargoResult<Vec<Summary>>; } impl Registry for Vec<Summary> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { Ok(self.iter().filter(|summary| dep.matches(*summary)) .map(|summary| summary.clone()).collect()) } } impl Registry for Vec<Package> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { Ok(self.iter().filter(|pkg| dep.matches(pkg.summary())) .map(|pkg| pkg.summary().clone()).collect()) } } /// This structure represents a registry of known packages. It internally /// contains a number of `Box<Source>` instances which are used to load a /// `Package` from. /// /// The resolution phase of Cargo uses this to drive knowledge about new /// packages as well as querying for lists of new packages. It is here that /// sources are updated (e.g. network operations) and overrides are /// handled. /// /// The general idea behind this registry is that it is centered around the /// `SourceMap` structure, contained within which is a mapping of a `SourceId` to /// a `Source`. Each `Source` in the map has been updated (using network /// operations if necessary) and is ready to be queried for packages. pub struct PackageRegistry<'cfg> { sources: SourceMap<'cfg>, config: &'cfg Config, // A list of sources which are considered "overrides" which take precedent // when querying for packages. overrides: Vec<SourceId>, // Note that each SourceId does not take into account its `precise` field // when hashing or testing for equality. When adding a new `SourceId`, we // want to avoid duplicates in the `SourceMap` (to prevent re-updating the // same git repo twice for example), but we also want to ensure that the // loaded source is always updated. // // Sources with a `precise` field normally don't need to be updated because // their contents are already on disk, but sources without a `precise` field // almost always need to be updated. If we have a cached `Source` for a // precise `SourceId`, then when we add a new `SourceId` that is not precise // we want to ensure that the underlying source is updated. // // This is basically a long-winded way of saying that we want to know // precisely what the keys of `sources` are, so this is a mapping of key to // what exactly the key is. source_ids: HashMap<SourceId, (SourceId, Kind)>, locked: HashMap<SourceId, HashMap<String, Vec<(PackageId, Vec<PackageId>)>>>, } #[derive(PartialEq, Eq, Clone, Copy)] enum Kind { Override, Locked, Normal, } impl<'cfg> PackageRegistry<'cfg> { pub fn new(config: &'cfg Config) -> PackageRegistry<'cfg> { PackageRegistry { sources: SourceMap::new(), source_ids: HashMap::new(), overrides: vec!(), config: config, locked: HashMap::new(), } } pub fn get(&mut self, package_ids: &[PackageId]) -> CargoResult<Vec<Package>> { trace!("getting packages; sources={}", self.sources.len()); // TODO: Only call source with package ID if the package came from the // source let mut ret = Vec::new(); for (_, source) in self.sources.sources_mut() { try!(source.download(package_ids)); let packages = try!(source.get(package_ids)); ret.extend(packages.into_iter()); } // TODO: Return earlier if fail assert!(package_ids.len() == ret.len(), "could not get packages from registry; ids={:?}; ret={:?}", package_ids, ret); Ok(ret) } pub fn move_sources(self) -> SourceMap<'cfg> { self.sources } fn ensure_loaded(&mut self, namespace: &SourceId) -> CargoResult<()> { match self.source_ids.get(namespace) { // We've previously loaded this source, and we've already locked it, // so we're not allowed to change it even if `namespace` has a // slightly different precise version listed. Some(&(_, Kind::Locked)) => { debug!("load/locked {}", namespace); return Ok(()) } // If the previous source was not a precise source, then we can be // sure that it's already been updated if we've already loaded it. Some(&(ref previous, _)) if previous.precise().is_none() => { debug!("load/precise {}", namespace); return Ok(()) } // If the previous source has the same precise version as we do, // then we're done, otherwise we need to need to move forward // updating this source. Some(&(ref previous, _)) => { if previous.precise() == namespace.precise() { debug!("load/match {}", namespace); return Ok(()) } debug!("load/mismatch {}", namespace); } None => { debug!("load/missing {}", namespace); } } try!(self.load(namespace, Kind::Normal)); Ok(()) } pub fn preload(&mut self, id: &SourceId, source: Box<Source + 'cfg>) { self.sources.insert(id, source); self.source_ids.insert(id.clone(), (id.clone(), Kind::Locked)); } pub fn add_sources(&mut self, ids: &[SourceId]) -> CargoResult<()> { for id in ids.iter() { try!(self.load(id, Kind::Locked)); } Ok(()) } pub fn add_overrides(&mut self, ids: Vec<SourceId>) -> CargoResult<()> { for id in ids.iter() { try!(self.load(id, Kind::Override)); } Ok(()) } pub fn register_lock(&mut self, id: PackageId, deps: Vec<PackageId>) { let sub_map = self.locked.entry(id.source_id().clone()) .or_insert(HashMap::new()); let sub_vec = sub_map.entry(id.name().to_string()) .or_insert(Vec::new()); sub_vec.push((id, deps)); } fn load(&mut self, source_id: &SourceId, kind: Kind) -> CargoResult<()> { (|| { let mut source = source_id.load(self.config); // Ensure the source has fetched all necessary remote data. let p = profile::start(format!("updating: {}", source_id)); try!(source.update()); drop(p); if kind == Kind::Override { self.overrides.push(source_id.clone()); } // Save off the source self.sources.insert(source_id, source); self.source_ids.insert(source_id.clone(), (source_id.clone(), kind)); Ok(()) }).chain_error(|| human(format!("Unable to update {}", source_id))) } fn query_overrides(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { let mut seen = HashSet::new(); let mut ret = Vec::new(); for s in self.overrides.iter() { let src = self.sources.get_mut(s).unwrap(); let dep = Dependency::new_override(dep.name(), s); ret.extend(try!(src.query(&dep)).into_iter().filter(|s| { seen.insert(s.name().to_string()) })); } Ok(ret) } // This function is used to transform a summary to another locked summary if // possible. This is where the concept of a lockfile comes into play. // // If a summary points at a package id which was previously locked, then we // override the summary's id itself, as well as all dependencies, to be // rewritten to the locked versions. This will transform the summary's // source to a precise source (listed in the locked version) as well as // transforming all of the dependencies from range requirements on imprecise // sources to exact requirements on precise sources. // // If a summary does not point at a package id which was previously locked, // we still want to avoid updating as many dependencies as possible to keep // the graph stable. In this case we map all of the summary's dependencies // to be rewritten to a locked version wherever possible. If we're unable to // map a dependency though, we just pass it on through. fn lock(&self, summary: Summary) -> Summary { let pair = self.locked.get(summary.source_id()).and_then(|map| { map.get(summary.name()) }).and_then(|vec| { vec.iter().find(|&&(ref id, _)| id == summary.package_id()) }); // Lock the summary's id if possible let summary = match pair { Some(&(ref precise, _)) => summary.override_id(precise.clone()), None => summary, }; summary.map_dependencies(|dep| { match pair { // If we've got a known set of overrides for this summary, then // one of a few cases can arise: // // 1. We have a lock entry for this dependency from the same // source as it's listed as coming from. In this case we make // sure to lock to precisely the given package id. // // 2. We have a lock entry for this dependency, but it's from a // different source than what's listed, or the version // requirement has changed. In this case we must discard the // locked version because the dependency needs to be // re-resolved. // // 3. We don't have a lock entry for this dependency, in which // case it was likely an optional dependency which wasn't // included previously so we just pass it through anyway. Some(&(_, ref deps)) => { match deps.iter().find(|d| d.name() == dep.name()) { Some(lock) => { if dep.matches_id(lock) { dep.lock_to(lock) } else { dep } } None => dep, } } // If this summary did not have a locked version, then we query // all known locked packages to see if they match this // dependency. If anything does then we lock it to that and move // on. None => { let v = self.locked.get(dep.source_id()).and_then(|map| { map.get(dep.name()) }).and_then(|vec| { vec.iter().find(|&&(ref id, _)| dep.matches_id(id)) }); match v { Some(&(ref id, _)) => dep.lock_to(id), None => dep } } } }) } } impl<'cfg> Registry for PackageRegistry<'cfg> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { let overrides = try!(self.query_overrides(dep)); let ret = if overrides.len() == 0 { // Ensure the requested source_id is loaded try!(self.ensure_loaded(dep.source_id())); let mut ret = Vec::new(); for (id, src) in self.sources.sources_mut() { if id == dep.source_id() { ret.extend(try!(src.query(dep)).into_iter()); } } ret } else { overrides }; // post-process all returned summaries to ensure that we lock all // relevant summaries to the right versions and sources Ok(ret.into_iter().map(|summary| self.lock(summary)).collect()) } }
#[cfg(test)] pub mod test { use core::{Summary, Registry, Dependency}; use util::{CargoResult}; pub struct RegistryBuilder { summaries: Vec<Summary>, overrides: Vec<Summary> } impl RegistryBuilder { pub fn new() -> RegistryBuilder { RegistryBuilder { summaries: vec!(), overrides: vec!() } } pub fn summary(mut self, summary: Summary) -> RegistryBuilder { self.summaries.push(summary); self } pub fn summaries(mut self, summaries: Vec<Summary>) -> RegistryBuilder { self.summaries.extend(summaries.into_iter()); self } pub fn add_override(mut self, summary: Summary) -> RegistryBuilder { self.overrides.push(summary); self } pub fn overrides(mut self, summaries: Vec<Summary>) -> RegistryBuilder { self.overrides.extend(summaries.into_iter()); self } fn query_overrides(&self, dep: &Dependency) -> Vec<Summary> { self.overrides.iter() .filter(|s| s.name() == dep.name()) .map(|s| s.clone()) .collect() } } impl Registry for RegistryBuilder { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { debug!("querying; dep={:?}", dep); let overrides = self.query_overrides(dep); if overrides.is_empty() { self.summaries.query(dep) } else { Ok(overrides) } } } }
random_line_split
lib.rs
//! # Half-precision conversion for Rust //! This crate uses the fast table-based f32 <-> f16 conversions given in //! "Fast Half Float Conversions" by Jeroen van der Zijp; see //! `ftp://ftp.fox-toolkit.org/pub/fasthalffloatconversion.pdf`. use std::mem::transmute; #[allow(non_camel_case_types)] #[derive(Copy, Clone, Debug)] pub struct f16 { pub bytes: u16, } impl PartialEq for f16 { fn eq(self: &f16, other: &f16) -> bool { return self.bytes == other.bytes; } } impl From<f32> for f16 { fn from(f: f32) -> f16 { unsafe { let base_table: *const u16 = transmute(include_bytes!("base_table.bin")); let shift_table: *const u8 = transmute(include_bytes!("shift_table.bin")); let ff: u32 = transmute(f); let bytes = *base_table.offset(((ff >> 23) & 0x1FF) as isize) + ((ff & 0x007FFFFF) >> *shift_table.offset(((ff >> 23) & 0x1FF) as isize)) as u16; f16 { bytes: bytes } } } } impl Into<f32> for f16 { fn into(self: f16) -> f32 { unsafe { let mantissa_table: *const u32 = transmute(include_bytes!("mantissa_table.bin")); let offset_table: *const u32 = transmute(include_bytes!("offset_table.bin")); let exponent_table: *const u32 = transmute(include_bytes!("exponent_table.bin")); let h0 = (self.bytes >> 10) as isize; let h1 = (self.bytes & 0x3FF) as u16 as isize; let mt_offset = *offset_table.offset(h0) as isize + h1; let mut tr = *mantissa_table.offset(mt_offset) + *exponent_table.offset(h0); tr |= ((self.bytes & 0x8000) as u32) << 16; transmute(tr) } } } pub fn slice_to_f16(v: &[f32]) -> Vec<f16> { let mut tr = Vec::with_capacity(v.len()); for it in v.iter() { tr.push(f16::from(*it)); } tr } pub fn slice_to_f32(v: &[f16]) -> Vec<f32> { let mut tr = Vec::with_capacity(v.len()); for it in v.iter() { tr.push((*it).into()); } tr } #[test] fn test()
{ for bytes in 0..65535 as u16 { let h0 = f16 { bytes: bytes }; let f: f32 = h0.into(); let h1 = f16::from(f); assert_eq!(h0, h1); } }
identifier_body
lib.rs
//! # Half-precision conversion for Rust //! This crate uses the fast table-based f32 <-> f16 conversions given in //! "Fast Half Float Conversions" by Jeroen van der Zijp; see //! `ftp://ftp.fox-toolkit.org/pub/fasthalffloatconversion.pdf`. use std::mem::transmute;
} impl PartialEq for f16 { fn eq(self: &f16, other: &f16) -> bool { return self.bytes == other.bytes; } } impl From<f32> for f16 { fn from(f: f32) -> f16 { unsafe { let base_table: *const u16 = transmute(include_bytes!("base_table.bin")); let shift_table: *const u8 = transmute(include_bytes!("shift_table.bin")); let ff: u32 = transmute(f); let bytes = *base_table.offset(((ff >> 23) & 0x1FF) as isize) + ((ff & 0x007FFFFF) >> *shift_table.offset(((ff >> 23) & 0x1FF) as isize)) as u16; f16 { bytes: bytes } } } } impl Into<f32> for f16 { fn into(self: f16) -> f32 { unsafe { let mantissa_table: *const u32 = transmute(include_bytes!("mantissa_table.bin")); let offset_table: *const u32 = transmute(include_bytes!("offset_table.bin")); let exponent_table: *const u32 = transmute(include_bytes!("exponent_table.bin")); let h0 = (self.bytes >> 10) as isize; let h1 = (self.bytes & 0x3FF) as u16 as isize; let mt_offset = *offset_table.offset(h0) as isize + h1; let mut tr = *mantissa_table.offset(mt_offset) + *exponent_table.offset(h0); tr |= ((self.bytes & 0x8000) as u32) << 16; transmute(tr) } } } pub fn slice_to_f16(v: &[f32]) -> Vec<f16> { let mut tr = Vec::with_capacity(v.len()); for it in v.iter() { tr.push(f16::from(*it)); } tr } pub fn slice_to_f32(v: &[f16]) -> Vec<f32> { let mut tr = Vec::with_capacity(v.len()); for it in v.iter() { tr.push((*it).into()); } tr } #[test] fn test() { for bytes in 0..65535 as u16 { let h0 = f16 { bytes: bytes }; let f: f32 = h0.into(); let h1 = f16::from(f); assert_eq!(h0, h1); } }
#[allow(non_camel_case_types)] #[derive(Copy, Clone, Debug)] pub struct f16 { pub bytes: u16,
random_line_split
lib.rs
//! # Half-precision conversion for Rust //! This crate uses the fast table-based f32 <-> f16 conversions given in //! "Fast Half Float Conversions" by Jeroen van der Zijp; see //! `ftp://ftp.fox-toolkit.org/pub/fasthalffloatconversion.pdf`. use std::mem::transmute; #[allow(non_camel_case_types)] #[derive(Copy, Clone, Debug)] pub struct f16 { pub bytes: u16, } impl PartialEq for f16 { fn eq(self: &f16, other: &f16) -> bool { return self.bytes == other.bytes; } } impl From<f32> for f16 { fn from(f: f32) -> f16 { unsafe { let base_table: *const u16 = transmute(include_bytes!("base_table.bin")); let shift_table: *const u8 = transmute(include_bytes!("shift_table.bin")); let ff: u32 = transmute(f); let bytes = *base_table.offset(((ff >> 23) & 0x1FF) as isize) + ((ff & 0x007FFFFF) >> *shift_table.offset(((ff >> 23) & 0x1FF) as isize)) as u16; f16 { bytes: bytes } } } } impl Into<f32> for f16 { fn into(self: f16) -> f32 { unsafe { let mantissa_table: *const u32 = transmute(include_bytes!("mantissa_table.bin")); let offset_table: *const u32 = transmute(include_bytes!("offset_table.bin")); let exponent_table: *const u32 = transmute(include_bytes!("exponent_table.bin")); let h0 = (self.bytes >> 10) as isize; let h1 = (self.bytes & 0x3FF) as u16 as isize; let mt_offset = *offset_table.offset(h0) as isize + h1; let mut tr = *mantissa_table.offset(mt_offset) + *exponent_table.offset(h0); tr |= ((self.bytes & 0x8000) as u32) << 16; transmute(tr) } } } pub fn slice_to_f16(v: &[f32]) -> Vec<f16> { let mut tr = Vec::with_capacity(v.len()); for it in v.iter() { tr.push(f16::from(*it)); } tr } pub fn slice_to_f32(v: &[f16]) -> Vec<f32> { let mut tr = Vec::with_capacity(v.len()); for it in v.iter() { tr.push((*it).into()); } tr } #[test] fn
() { for bytes in 0..65535 as u16 { let h0 = f16 { bytes: bytes }; let f: f32 = h0.into(); let h1 = f16::from(f); assert_eq!(h0, h1); } }
test
identifier_name
conf.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ use std::os::raw::c_char; use std::os::raw::c_void; use std::os::raw::c_int; use std::ffi::{CString, CStr}; use std::ptr; use std::str; use nom::{ character::complete::{multispace0, not_line_ending}, sequence::{preceded, tuple}, number::complete::double, combinator::verify, }; extern { fn ConfGet(key: *const c_char, res: *mut *const c_char) -> i8; fn ConfGetChildValue(conf: *const c_void, key: *const c_char, vptr: *mut *const c_char) -> i8; fn ConfGetChildValueBool(conf: *const c_void, key: *const c_char, vptr: *mut c_int) -> i8; } // Return the string value of a configuration value. pub fn conf_get(key: &str) -> Option<&str> { let mut vptr: *const c_char = ptr::null_mut(); unsafe { let s = CString::new(key).unwrap(); if ConfGet(s.as_ptr(), &mut vptr)!= 1 { SCLogDebug!("Failed to find value for key {}", key); return None; } } if vptr.is_null() { return None; } let value = str::from_utf8(unsafe{ CStr::from_ptr(vptr).to_bytes() }).unwrap(); return Some(value); } // Return the value of key as a boolean. A value that is not set is // the same as having it set to false. pub fn conf_get_bool(key: &str) -> bool { match conf_get(key) { Some(val) => { match val { "1" | "yes" | "true" | "on" => { return true; }, _ => {}, } }, None => {}, } return false; } /// Wrap a Suricata ConfNode and expose some of its methods with a /// Rust friendly interface. pub struct ConfNode { pub conf: *const c_void, } impl ConfNode { pub fn wrap(conf: *const c_void) -> Self { return Self { conf: conf, } } pub fn get_child_value(&self, key: &str) -> Option<&str> { let mut vptr: *const c_char = ptr::null_mut(); unsafe { let s = CString::new(key).unwrap(); if ConfGetChildValue(self.conf, s.as_ptr(), &mut vptr)!= 1 { return None; } } if vptr.is_null() { return None; } let value = str::from_utf8(unsafe{ CStr::from_ptr(vptr).to_bytes() }).unwrap(); return Some(value); } pub fn get_child_bool(&self, key: &str) -> bool { let mut vptr: c_int = 0; unsafe { let s = CString::new(key).unwrap(); if ConfGetChildValueBool(self.conf, s.as_ptr(), &mut vptr)!= 1 { return false; } } if vptr == 1 { return true; } return false; } } const BYTE: u64 = 1; const KILOBYTE: u64 = 1024; const MEGABYTE: u64 = 1_048_576; const GIGABYTE: u64 = 1_073_741_824; /// Helper function to retrieve memory unit from a string slice /// /// Return value: u64 /// /// # Arguments /// /// * `unit` - A string slice possibly containing memory unit fn get_memunit(unit: &str) -> u64 { let unit = &unit.to_lowercase()[..]; match unit { "b" => { BYTE } "kb" => { KILOBYTE } "mb" => { MEGABYTE } "gb" => { GIGABYTE } _ => { 0 } } } /// Parses memory units from human readable form to machine readable /// /// Return value: /// Result => Ok(u64) /// => Err(error string) /// /// # Arguments /// /// * `arg` - A string slice that holds the value parsed from the config pub fn get_memval(arg: &str) -> Result<u64, &'static str> { let arg = arg.trim(); let val: f64; let mut unit: &str; let parser = tuple((preceded(multispace0, double), preceded(multispace0, verify(not_line_ending, |c: &str| c.len() < 3)))); let r: nom::IResult<&str, (f64, &str)> = parser(arg); if let Ok(r) = r { val = (r.1).0; unit = (r.1).1; } else { return Err("Error parsing the memory value"); } if unit.is_empty() { unit = "B"; } let unit = get_memunit(unit) as u64; if unit == 0
let res = val * unit as f64; Ok(res as u64) } #[cfg(test)] mod tests { use super::*; #[test] fn test_memval_nospace() { let s = "10"; let res = 10 ; assert_eq!(Ok(10), get_memval(s)); let s = "10kb"; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = "10Kb"; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = "10KB"; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = "10mb"; assert_eq!(Ok(res * MEGABYTE), get_memval(s)); let s = "10gb"; assert_eq!(Ok(res * GIGABYTE), get_memval(s)); } #[test] fn test_memval_space_start() { let s = " 10"; let res = 10 ; assert_eq!(Ok(res), get_memval(s)); let s = " 10Kb"; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = " 10mb"; assert_eq!(Ok(res * MEGABYTE), get_memval(s)); let s = " 10Gb"; assert_eq!(Ok(res * GIGABYTE), get_memval(s)); let s = " 30b"; assert_eq!(Ok(30), get_memval(s)); } #[test] fn test_memval_space_end() { let s = " 10 "; let res = 10 ; assert_eq!(Ok(res), get_memval(s)); let s = "10Kb "; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = "10mb "; assert_eq!(Ok(res * MEGABYTE), get_memval(s)); let s = " 10Gb "; assert_eq!(Ok(res * GIGABYTE), get_memval(s)); let s = " 30b "; assert_eq!(Ok(30), get_memval(s)); } #[test] fn test_memval_space_in_bw() { let s = " 10 "; let res = 10 ; assert_eq!(Ok(res), get_memval(s)); let s = "10 Kb "; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = "10 mb"; assert_eq!(Ok(res * MEGABYTE), get_memval(s)); let s = " 10 Gb "; assert_eq!(Ok(res * GIGABYTE), get_memval(s)); let s = "30 b"; assert_eq!(Ok(30), get_memval(s)); } #[test] fn test_memval_float_val() { let s = " 10.5 "; assert_eq!(Ok(10), get_memval(s)); let s = "10.8Kb "; assert_eq!(Ok((10.8 * KILOBYTE as f64) as u64), get_memval(s)); let s = "10.4 mb "; assert_eq!(Ok((10.4 * MEGABYTE as f64) as u64), get_memval(s)); let s = " 10.5Gb "; assert_eq!(Ok((10.5 * GIGABYTE as f64) as u64), get_memval(s)); let s = " 30.0 b "; assert_eq!(Ok(30), get_memval(s)); } #[test] fn test_memval_erroneous_val() { let s = "5eb"; assert_eq!(true, get_memval(s).is_err()); let s = "5 1kb"; assert_eq!(true, get_memval(s).is_err()); let s = "61k b"; assert_eq!(true, get_memval(s).is_err()); let s = "8 8 k b"; assert_eq!(true, get_memval(s).is_err()); } }
{ return Err("Invalid memory unit"); }
conditional_block
conf.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ use std::os::raw::c_char; use std::os::raw::c_void; use std::os::raw::c_int; use std::ffi::{CString, CStr}; use std::ptr; use std::str; use nom::{ character::complete::{multispace0, not_line_ending}, sequence::{preceded, tuple}, number::complete::double, combinator::verify, }; extern { fn ConfGet(key: *const c_char, res: *mut *const c_char) -> i8; fn ConfGetChildValue(conf: *const c_void, key: *const c_char, vptr: *mut *const c_char) -> i8; fn ConfGetChildValueBool(conf: *const c_void, key: *const c_char, vptr: *mut c_int) -> i8; } // Return the string value of a configuration value. pub fn conf_get(key: &str) -> Option<&str> { let mut vptr: *const c_char = ptr::null_mut(); unsafe { let s = CString::new(key).unwrap(); if ConfGet(s.as_ptr(), &mut vptr)!= 1 { SCLogDebug!("Failed to find value for key {}", key); return None; } } if vptr.is_null() { return None; } let value = str::from_utf8(unsafe{ CStr::from_ptr(vptr).to_bytes() }).unwrap(); return Some(value); } // Return the value of key as a boolean. A value that is not set is // the same as having it set to false. pub fn conf_get_bool(key: &str) -> bool { match conf_get(key) { Some(val) => { match val { "1" | "yes" | "true" | "on" => { return true; }, _ => {}, } }, None => {}, } return false; } /// Wrap a Suricata ConfNode and expose some of its methods with a /// Rust friendly interface. pub struct ConfNode { pub conf: *const c_void, } impl ConfNode { pub fn wrap(conf: *const c_void) -> Self { return Self { conf: conf, } } pub fn get_child_value(&self, key: &str) -> Option<&str> { let mut vptr: *const c_char = ptr::null_mut(); unsafe { let s = CString::new(key).unwrap(); if ConfGetChildValue(self.conf, s.as_ptr(), &mut vptr)!= 1 { return None; } } if vptr.is_null() { return None; } let value = str::from_utf8(unsafe{ CStr::from_ptr(vptr).to_bytes() }).unwrap(); return Some(value); } pub fn get_child_bool(&self, key: &str) -> bool { let mut vptr: c_int = 0; unsafe { let s = CString::new(key).unwrap(); if ConfGetChildValueBool(self.conf, s.as_ptr(), &mut vptr)!= 1 { return false; } } if vptr == 1 { return true; } return false; } } const BYTE: u64 = 1; const KILOBYTE: u64 = 1024; const MEGABYTE: u64 = 1_048_576; const GIGABYTE: u64 = 1_073_741_824; /// Helper function to retrieve memory unit from a string slice /// /// Return value: u64 /// /// # Arguments /// /// * `unit` - A string slice possibly containing memory unit fn get_memunit(unit: &str) -> u64 { let unit = &unit.to_lowercase()[..]; match unit { "b" => { BYTE } "kb" => { KILOBYTE } "mb" => { MEGABYTE } "gb" => { GIGABYTE } _ => { 0 } } } /// Parses memory units from human readable form to machine readable /// /// Return value: /// Result => Ok(u64) /// => Err(error string) /// /// # Arguments /// /// * `arg` - A string slice that holds the value parsed from the config pub fn get_memval(arg: &str) -> Result<u64, &'static str> { let arg = arg.trim(); let val: f64; let mut unit: &str; let parser = tuple((preceded(multispace0, double), preceded(multispace0, verify(not_line_ending, |c: &str| c.len() < 3)))); let r: nom::IResult<&str, (f64, &str)> = parser(arg); if let Ok(r) = r { val = (r.1).0; unit = (r.1).1; } else { return Err("Error parsing the memory value"); } if unit.is_empty() { unit = "B"; } let unit = get_memunit(unit) as u64; if unit == 0 { return Err("Invalid memory unit"); } let res = val * unit as f64; Ok(res as u64) } #[cfg(test)] mod tests { use super::*; #[test] fn test_memval_nospace() { let s = "10"; let res = 10 ; assert_eq!(Ok(10), get_memval(s)); let s = "10kb"; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = "10Kb"; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = "10KB"; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = "10mb"; assert_eq!(Ok(res * MEGABYTE), get_memval(s)); let s = "10gb"; assert_eq!(Ok(res * GIGABYTE), get_memval(s)); } #[test] fn test_memval_space_start() { let s = " 10"; let res = 10 ; assert_eq!(Ok(res), get_memval(s)); let s = " 10Kb"; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = " 10mb"; assert_eq!(Ok(res * MEGABYTE), get_memval(s)); let s = " 10Gb"; assert_eq!(Ok(res * GIGABYTE), get_memval(s)); let s = " 30b"; assert_eq!(Ok(30), get_memval(s)); } #[test] fn
() { let s = " 10 "; let res = 10 ; assert_eq!(Ok(res), get_memval(s)); let s = "10Kb "; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = "10mb "; assert_eq!(Ok(res * MEGABYTE), get_memval(s)); let s = " 10Gb "; assert_eq!(Ok(res * GIGABYTE), get_memval(s)); let s = " 30b "; assert_eq!(Ok(30), get_memval(s)); } #[test] fn test_memval_space_in_bw() { let s = " 10 "; let res = 10 ; assert_eq!(Ok(res), get_memval(s)); let s = "10 Kb "; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = "10 mb"; assert_eq!(Ok(res * MEGABYTE), get_memval(s)); let s = " 10 Gb "; assert_eq!(Ok(res * GIGABYTE), get_memval(s)); let s = "30 b"; assert_eq!(Ok(30), get_memval(s)); } #[test] fn test_memval_float_val() { let s = " 10.5 "; assert_eq!(Ok(10), get_memval(s)); let s = "10.8Kb "; assert_eq!(Ok((10.8 * KILOBYTE as f64) as u64), get_memval(s)); let s = "10.4 mb "; assert_eq!(Ok((10.4 * MEGABYTE as f64) as u64), get_memval(s)); let s = " 10.5Gb "; assert_eq!(Ok((10.5 * GIGABYTE as f64) as u64), get_memval(s)); let s = " 30.0 b "; assert_eq!(Ok(30), get_memval(s)); } #[test] fn test_memval_erroneous_val() { let s = "5eb"; assert_eq!(true, get_memval(s).is_err()); let s = "5 1kb"; assert_eq!(true, get_memval(s).is_err()); let s = "61k b"; assert_eq!(true, get_memval(s).is_err()); let s = "8 8 k b"; assert_eq!(true, get_memval(s).is_err()); } }
test_memval_space_end
identifier_name
conf.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ use std::os::raw::c_char; use std::os::raw::c_void; use std::os::raw::c_int; use std::ffi::{CString, CStr}; use std::ptr; use std::str; use nom::{ character::complete::{multispace0, not_line_ending}, sequence::{preceded, tuple}, number::complete::double, combinator::verify, }; extern { fn ConfGet(key: *const c_char, res: *mut *const c_char) -> i8; fn ConfGetChildValue(conf: *const c_void, key: *const c_char, vptr: *mut *const c_char) -> i8; fn ConfGetChildValueBool(conf: *const c_void, key: *const c_char, vptr: *mut c_int) -> i8; } // Return the string value of a configuration value. pub fn conf_get(key: &str) -> Option<&str> { let mut vptr: *const c_char = ptr::null_mut();
let s = CString::new(key).unwrap(); if ConfGet(s.as_ptr(), &mut vptr)!= 1 { SCLogDebug!("Failed to find value for key {}", key); return None; } } if vptr.is_null() { return None; } let value = str::from_utf8(unsafe{ CStr::from_ptr(vptr).to_bytes() }).unwrap(); return Some(value); } // Return the value of key as a boolean. A value that is not set is // the same as having it set to false. pub fn conf_get_bool(key: &str) -> bool { match conf_get(key) { Some(val) => { match val { "1" | "yes" | "true" | "on" => { return true; }, _ => {}, } }, None => {}, } return false; } /// Wrap a Suricata ConfNode and expose some of its methods with a /// Rust friendly interface. pub struct ConfNode { pub conf: *const c_void, } impl ConfNode { pub fn wrap(conf: *const c_void) -> Self { return Self { conf: conf, } } pub fn get_child_value(&self, key: &str) -> Option<&str> { let mut vptr: *const c_char = ptr::null_mut(); unsafe { let s = CString::new(key).unwrap(); if ConfGetChildValue(self.conf, s.as_ptr(), &mut vptr)!= 1 { return None; } } if vptr.is_null() { return None; } let value = str::from_utf8(unsafe{ CStr::from_ptr(vptr).to_bytes() }).unwrap(); return Some(value); } pub fn get_child_bool(&self, key: &str) -> bool { let mut vptr: c_int = 0; unsafe { let s = CString::new(key).unwrap(); if ConfGetChildValueBool(self.conf, s.as_ptr(), &mut vptr)!= 1 { return false; } } if vptr == 1 { return true; } return false; } } const BYTE: u64 = 1; const KILOBYTE: u64 = 1024; const MEGABYTE: u64 = 1_048_576; const GIGABYTE: u64 = 1_073_741_824; /// Helper function to retrieve memory unit from a string slice /// /// Return value: u64 /// /// # Arguments /// /// * `unit` - A string slice possibly containing memory unit fn get_memunit(unit: &str) -> u64 { let unit = &unit.to_lowercase()[..]; match unit { "b" => { BYTE } "kb" => { KILOBYTE } "mb" => { MEGABYTE } "gb" => { GIGABYTE } _ => { 0 } } } /// Parses memory units from human readable form to machine readable /// /// Return value: /// Result => Ok(u64) /// => Err(error string) /// /// # Arguments /// /// * `arg` - A string slice that holds the value parsed from the config pub fn get_memval(arg: &str) -> Result<u64, &'static str> { let arg = arg.trim(); let val: f64; let mut unit: &str; let parser = tuple((preceded(multispace0, double), preceded(multispace0, verify(not_line_ending, |c: &str| c.len() < 3)))); let r: nom::IResult<&str, (f64, &str)> = parser(arg); if let Ok(r) = r { val = (r.1).0; unit = (r.1).1; } else { return Err("Error parsing the memory value"); } if unit.is_empty() { unit = "B"; } let unit = get_memunit(unit) as u64; if unit == 0 { return Err("Invalid memory unit"); } let res = val * unit as f64; Ok(res as u64) } #[cfg(test)] mod tests { use super::*; #[test] fn test_memval_nospace() { let s = "10"; let res = 10 ; assert_eq!(Ok(10), get_memval(s)); let s = "10kb"; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = "10Kb"; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = "10KB"; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = "10mb"; assert_eq!(Ok(res * MEGABYTE), get_memval(s)); let s = "10gb"; assert_eq!(Ok(res * GIGABYTE), get_memval(s)); } #[test] fn test_memval_space_start() { let s = " 10"; let res = 10 ; assert_eq!(Ok(res), get_memval(s)); let s = " 10Kb"; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = " 10mb"; assert_eq!(Ok(res * MEGABYTE), get_memval(s)); let s = " 10Gb"; assert_eq!(Ok(res * GIGABYTE), get_memval(s)); let s = " 30b"; assert_eq!(Ok(30), get_memval(s)); } #[test] fn test_memval_space_end() { let s = " 10 "; let res = 10 ; assert_eq!(Ok(res), get_memval(s)); let s = "10Kb "; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = "10mb "; assert_eq!(Ok(res * MEGABYTE), get_memval(s)); let s = " 10Gb "; assert_eq!(Ok(res * GIGABYTE), get_memval(s)); let s = " 30b "; assert_eq!(Ok(30), get_memval(s)); } #[test] fn test_memval_space_in_bw() { let s = " 10 "; let res = 10 ; assert_eq!(Ok(res), get_memval(s)); let s = "10 Kb "; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = "10 mb"; assert_eq!(Ok(res * MEGABYTE), get_memval(s)); let s = " 10 Gb "; assert_eq!(Ok(res * GIGABYTE), get_memval(s)); let s = "30 b"; assert_eq!(Ok(30), get_memval(s)); } #[test] fn test_memval_float_val() { let s = " 10.5 "; assert_eq!(Ok(10), get_memval(s)); let s = "10.8Kb "; assert_eq!(Ok((10.8 * KILOBYTE as f64) as u64), get_memval(s)); let s = "10.4 mb "; assert_eq!(Ok((10.4 * MEGABYTE as f64) as u64), get_memval(s)); let s = " 10.5Gb "; assert_eq!(Ok((10.5 * GIGABYTE as f64) as u64), get_memval(s)); let s = " 30.0 b "; assert_eq!(Ok(30), get_memval(s)); } #[test] fn test_memval_erroneous_val() { let s = "5eb"; assert_eq!(true, get_memval(s).is_err()); let s = "5 1kb"; assert_eq!(true, get_memval(s).is_err()); let s = "61k b"; assert_eq!(true, get_memval(s).is_err()); let s = "8 8 k b"; assert_eq!(true, get_memval(s).is_err()); } }
unsafe {
random_line_split
details.rs
decimal_prefix, Prefixed, Standalone, PrefixNames}; use users::{OSUsers, Users}; use users::mock::MockUsers; use super::filename; /// With the **Details** view, the output gets formatted into columns, with /// each `Column` object showing some piece of information about the file, /// such as its size, or its permissions. /// /// To do this, the results have to be written to a table, instead of /// displaying each file immediately. Then, the width of each column can be /// calculated based on the individual results, and the fields are padded /// during output. /// /// Almost all the heavy lifting is done in a Table object, which handles the /// columns for each row. #[derive(PartialEq, Debug, Copy, Clone, Default)] pub struct Details { /// A Columns object that says which columns should be included in the /// output in the general case. Directories themselves can pick which /// columns are *added* to this list, such as the Git column. pub columns: Option<Columns>, /// Whether to recurse through directories with a tree view, and if so, /// which options to use. This field is only relevant here if the `tree` /// field of the RecurseOptions is `true`. pub recurse: Option<RecurseOptions>, /// How to sort and filter the files after getting their details. pub filter: FileFilter, /// Whether to show a header line or not. pub header: bool, /// Whether to show each file's extended attributes. pub xattr: bool, /// The colours to use to display information in the table, including the /// colour of the tree view symbols. pub colours: Colours, } impl Details { /// Print the details of the given vector of files -- all of which will /// have been read from the given directory, if present -- to stdout. pub fn view(&self, dir: Option<&Dir>, files: Vec<File>) { // First, transform the Columns object into a vector of columns for // the current directory. let columns_for_dir = match self.columns { Some(cols) => cols.for_dir(dir), None => Vec::new(), }; // Next, add a header if the user requests it. let mut table = Table::with_options(self.colours, columns_for_dir); if self.header { table.add_header() } // Then add files to the table and print it out. self.add_files_to_table(&mut table, files, 0); for cell in table.print_table() { println!("{}", cell.text); } } /// Adds files to the table, possibly recursively. This is easily /// parallelisable, and uses a pool of threads. fn add_files_to_table<'dir, U: Users+Send>(&self, mut table: &mut Table<U>, src: Vec<File<'dir>>, depth: usize) { use num_cpus; use scoped_threadpool::Pool; use std::sync::{Arc, Mutex}; let mut pool = Pool::new(num_cpus::get() as u32); let mut file_eggs = Vec::new(); struct Egg<'_> { cells: Vec<Cell>, name: Cell, xattrs: Vec<Attribute>, errors: Vec<(io::Error, Option<PathBuf>)>, dir: Option<Dir>, file: Arc<File<'_>>, } pool.scoped(|scoped| { let file_eggs = Arc::new(Mutex::new(&mut file_eggs)); let table = Arc::new(Mutex::new(&mut table)); for file in src.into_iter() { let file: Arc<File> = Arc::new(file); let file_eggs = file_eggs.clone(); let table = table.clone(); scoped.execute(move || { let mut errors = Vec::new(); let mut xattrs = Vec::new(); match file.path.attributes() { Ok(xs) => { if self.xattr { for xattr in xs { xattrs.push(xattr); } } }, Err(e) => { if self.xattr { errors.push((e, None)); } }, }; let cells = table.lock().unwrap().cells_for_file(&file,!xattrs.is_empty());
let name = Cell { text: filename(&file, &self.colours, true), length: file.file_name_width() }; let mut dir = None; if let Some(r) = self.recurse { if file.is_directory() && r.tree &&!r.is_too_deep(depth) { if let Ok(d) = file.to_dir(false) { dir = Some(d); } } }; let egg = Egg { cells: cells, name: name, xattrs: xattrs, errors: errors, dir: dir, file: file, }; file_eggs.lock().unwrap().push(egg); }); } }); file_eggs.sort_by(|a, b| self.filter.compare_files(&*a.file, &*b.file)); let num_eggs = file_eggs.len(); for (index, egg) in file_eggs.into_iter().enumerate() { let mut files = Vec::new(); let mut errors = egg.errors; let row = Row { depth: depth, cells: Some(egg.cells), name: egg.name, last: index == num_eggs - 1, }; table.rows.push(row); if let Some(ref dir) = egg.dir { for file_to_add in dir.files() { match file_to_add { Ok(f) => files.push(f), Err((path, e)) => errors.push((e, Some(path))) } } self.filter.filter_files(&mut files); if!files.is_empty() { for xattr in egg.xattrs { table.add_xattr(xattr, depth + 1, false); } for (error, path) in errors { table.add_error(&error, depth + 1, false, path); } self.add_files_to_table(table, files, depth + 1); continue; } } let count = egg.xattrs.len(); for (index, xattr) in egg.xattrs.into_iter().enumerate() { table.add_xattr(xattr, depth + 1, errors.is_empty() && index == count - 1); } let count = errors.len(); for (index, (error, path)) in errors.into_iter().enumerate() { table.add_error(&error, depth + 1, index == count - 1, path); } } } } struct Row { /// Vector of cells to display. /// /// Most of the rows will be used to display files' metadata, so this will /// almost always be `Some`, containing a vector of cells. It will only be /// `None` for a row displaying an attribute or error, neither of which /// have cells. cells: Option<Vec<Cell>>, // Did You Know? // A Vec<Cell> and an Option<Vec<Cell>> actually have the same byte size! /// This file's name, in coloured output. The name is treated separately /// from the other cells, as it never requires padding. name: Cell, /// How many directories deep into the tree structure this is. Directories /// on top have depth 0. depth: usize, /// Whether this is the last entry in the directory. This flag is used /// when calculating the tree view. last: bool, } impl Row { /// Gets the Unicode display width of the indexed column, if present. If /// not, returns 0. fn column_width(&self, index: usize) -> usize { match self.cells { Some(ref cells) => cells[index].length, None => 0, } } } /// A **Table** object gets built up by the view as it lists files and /// directories. pub struct Table<U> { columns: Vec<Column>, rows: Vec<Row>, time: locale::Time, numeric: locale::Numeric, tz: TimeZone, users: U, colours: Colours, current_year: i64, } impl Default for Table<MockUsers> { fn default() -> Table<MockUsers> { Table { columns: Columns::default().for_dir(None), rows: Vec::new(), time: locale::Time::english(), numeric: locale::Numeric::english(), tz: TimeZone::localtime().unwrap(), users: MockUsers::with_current_uid(0), colours: Colours::default(), current_year: 1234, } } } impl Table<OSUsers> { /// Create a new, empty Table object, setting the caching fields to their /// empty states. pub fn with_options(colours: Colours, columns: Vec<Column>) -> Table<OSUsers> { Table { columns: columns, rows: Vec::new(), time: locale::Time::load_user_locale().unwrap_or_else(|_| locale::Time::english()), numeric: locale::Numeric::load_user_locale().unwrap_or_else(|_| locale::Numeric::english()), tz: TimeZone::localtime().unwrap(), users: OSUsers::empty_cache(), colours: colours, current_year: LocalDateTime::now().year(), } } } impl<U> Table<U> where U: Users { /// Add a dummy "header" row to the table, which contains the names of all /// the columns, underlined. This has dummy data for the cases that aren't /// actually used, such as the depth or list of attributes. pub fn add_header(&mut self) { let row = Row { depth: 0, cells: Some(self.columns.iter().map(|c| Cell::paint(self.colours.header, c.header())).collect()), name: Cell::paint(self.colours.header, "Name"), last: false, }; self.rows.push(row); } fn add_error(&mut self, error: &io::Error, depth: usize, last: bool, path: Option<PathBuf>) { let error_message = match path { Some(path) => format!("<{}: {}>", path.display(), error), None => format!("<{}>", error), }; let row = Row { depth: depth, cells: None, name: Cell::paint(self.colours.broken_arrow, &error_message), last: last, }; self.rows.push(row); } fn add_xattr(&mut self, xattr: Attribute, depth: usize, last: bool) { let row = Row { depth: depth, cells: None, name: Cell::paint(self.colours.perms.attribute, &format!("{} (len {})", xattr.name, xattr.size)), last: last, }; self.rows.push(row); } pub fn add_file_with_cells(&mut self, cells: Vec<Cell>, file: &File, depth: usize, last: bool, links: bool) { let row = Row { depth: depth, cells: Some(cells), name: Cell { text: filename(file, &self.colours, links), length: file.file_name_width() }, last: last, }; self.rows.push(row); } /// Use the list of columns to find which cells should be produced for /// this file, per-column. pub fn cells_for_file(&mut self, file: &File, xattrs: bool) -> Vec<Cell> { self.columns.clone().iter() .map(|c| self.display(file, c, xattrs)) .collect() } fn display(&mut self, file: &File, column: &Column, xattrs: bool) -> Cell { match *column { Column::Permissions => self.render_permissions(file.permissions(), xattrs), Column::FileSize(fmt) => self.render_size(file.size(), fmt), Column::Timestamp(t) => self.render_time(file.timestamp(t)), Column::HardLinks => self.render_links(file.links()), Column::Inode => self.render_inode(file.inode()), Column::Blocks => self.render_blocks(file.blocks()), Column::User => self.render_user(file.user()), Column::Group => self.render_group(file.group()), Column::GitStatus => self.render_git_status(file.git_status()), } } fn render_permissions(&self, permissions: f::Permissions, xattrs: bool) -> Cell { let c = self.colours.perms; let bit = |bit, chr: &'static str, style: Style| { if bit { style.paint(chr) } else { self.colours.punctuation.paint("-") } }; let file_type = match permissions.file_type { f::Type::File => self.colours.filetypes.normal.paint("."), f::Type::Directory => self.colours.filetypes.directory.paint("d"), f::Type::Pipe => self.colours.filetypes.special.paint("|"), f::Type::Link => self.colours.filetypes.symlink.paint("l"), f::Type::Special => self.colours.filetypes.special.paint("?"), }; let x_colour = if let f::Type::File = permissions.file_type { c.user_execute_file } else { c.user_execute_other }; let mut columns = vec![ file_type, bit(permissions.user_read, "r", c.user_read), bit(permissions.user_write, "w", c.user_write), bit(permissions.user_execute, "x", x_colour), bit(permissions.group_read, "r", c.group_read), bit(permissions.group_write, "w", c.group_write), bit(permissions.group_execute, "x", c.group_execute), bit(permissions.other_read, "r", c.other_read), bit(permissions.other_write, "w", c.other_write), bit(permissions.other_execute, "x", c.other_execute), ]; if xattrs { columns.push(c.attribute.paint("@")); } Cell { text: ANSIStrings(&columns).to_string(), length: columns.len(), } } fn render_links(&self, links: f::Links) -> Cell { let style = if links.multiple { self.colours.links.multi_link_file } else { self.colours.links.normal }; Cell::paint(style, &self.numeric.format_int(links.count)) } fn render_blocks(&self, blocks: f::Blocks) -> Cell { match blocks { f::Blocks::Some(blocks) => Cell::paint(self.colours.blocks, &blocks.to_string()), f::Blocks::None => Cell::paint(self.colours.punctuation, "-"), } } fn render_inode(&self, inode: f::Inode) -> Cell { Cell::paint(self.colours.inode, &inode.0.to_string()) } fn render_size(&self, size: f::Size, size_format: SizeFormat) -> Cell { if let f::Size::Some(offset) = size { let result = match size_format { SizeFormat::DecimalBytes => decimal_prefix(offset as f64), SizeFormat::BinaryBytes => binary_prefix(offset as f64), SizeFormat::JustBytes => return Cell::paint(self.colours.size.numbers, &self.numeric.format_int(offset)), }; match result { Standalone(bytes) => Cell::paint(self.colours.size.numbers, &*bytes.to_string()), Prefixed(prefix, n) => { let number = if n < 10f64 { self.numeric.format_float(n, 1) } else { self.numeric.format_int(n as isize) }; let symbol = prefix.symbol(); Cell { text: ANSIStrings( &[ self.colours.size.numbers.paint(&number[..]), self.colours.size.unit.paint(symbol) ]).to_string(), length: number.len() + symbol.len(), } } } } else { Cell::paint(self.colours.punctuation, "-") } } fn render_time(&self, timestamp: f::Time) -> Cell { let date = self.tz.at(LocalDateTime::at(timestamp.0)); let format = if date.year() == self.current_year { DateFormat::parse("{2>:D} {:M} {2>:h}:{02>:m}").unwrap() } else { DateFormat::parse("{2>:D} {:M} {5>:Y}").unwrap() }; Cell::paint(self.colours.date, &format.format(&date, &self.time)) } fn render_git_status(&self, git: f::Git) -> Cell { Cell { text: ANSIStrings(&[ self.render_git_char(git.staged), self.render_git_char(git.unstaged) ]).to_string(), length: 2, } } fn render_git_char(&self, status: f::GitStatus) -> ANSIString { match status { f::GitStatus::NotModified =>
random_line_split
details.rs
_prefix, Prefixed, Standalone, PrefixNames}; use users::{OSUsers, Users}; use users::mock::MockUsers; use super::filename; /// With the **Details** view, the output gets formatted into columns, with /// each `Column` object showing some piece of information about the file, /// such as its size, or its permissions. /// /// To do this, the results have to be written to a table, instead of /// displaying each file immediately. Then, the width of each column can be /// calculated based on the individual results, and the fields are padded /// during output. /// /// Almost all the heavy lifting is done in a Table object, which handles the /// columns for each row. #[derive(PartialEq, Debug, Copy, Clone, Default)] pub struct Details { /// A Columns object that says which columns should be included in the /// output in the general case. Directories themselves can pick which /// columns are *added* to this list, such as the Git column. pub columns: Option<Columns>, /// Whether to recurse through directories with a tree view, and if so, /// which options to use. This field is only relevant here if the `tree` /// field of the RecurseOptions is `true`. pub recurse: Option<RecurseOptions>, /// How to sort and filter the files after getting their details. pub filter: FileFilter, /// Whether to show a header line or not. pub header: bool, /// Whether to show each file's extended attributes. pub xattr: bool, /// The colours to use to display information in the table, including the /// colour of the tree view symbols. pub colours: Colours, } impl Details { /// Print the details of the given vector of files -- all of which will /// have been read from the given directory, if present -- to stdout. pub fn view(&self, dir: Option<&Dir>, files: Vec<File>) { // First, transform the Columns object into a vector of columns for // the current directory. let columns_for_dir = match self.columns { Some(cols) => cols.for_dir(dir), None => Vec::new(), }; // Next, add a header if the user requests it. let mut table = Table::with_options(self.colours, columns_for_dir); if self.header { table.add_header() } // Then add files to the table and print it out. self.add_files_to_table(&mut table, files, 0); for cell in table.print_table() { println!("{}", cell.text); } } /// Adds files to the table, possibly recursively. This is easily /// parallelisable, and uses a pool of threads. fn add_files_to_table<'dir, U: Users+Send>(&self, mut table: &mut Table<U>, src: Vec<File<'dir>>, depth: usize) { use num_cpus; use scoped_threadpool::Pool; use std::sync::{Arc, Mutex}; let mut pool = Pool::new(num_cpus::get() as u32); let mut file_eggs = Vec::new(); struct Egg<'_> { cells: Vec<Cell>, name: Cell, xattrs: Vec<Attribute>, errors: Vec<(io::Error, Option<PathBuf>)>, dir: Option<Dir>, file: Arc<File<'_>>, } pool.scoped(|scoped| { let file_eggs = Arc::new(Mutex::new(&mut file_eggs)); let table = Arc::new(Mutex::new(&mut table)); for file in src.into_iter() { let file: Arc<File> = Arc::new(file); let file_eggs = file_eggs.clone(); let table = table.clone(); scoped.execute(move || { let mut errors = Vec::new(); let mut xattrs = Vec::new(); match file.path.attributes() { Ok(xs) => { if self.xattr { for xattr in xs { xattrs.push(xattr); } } }, Err(e) => { if self.xattr { errors.push((e, None)); } }, }; let cells = table.lock().unwrap().cells_for_file(&file,!xattrs.is_empty()); let name = Cell { text: filename(&file, &self.colours, true), length: file.file_name_width() }; let mut dir = None; if let Some(r) = self.recurse { if file.is_directory() && r.tree &&!r.is_too_deep(depth) { if let Ok(d) = file.to_dir(false) { dir = Some(d); } } }; let egg = Egg { cells: cells, name: name, xattrs: xattrs, errors: errors, dir: dir, file: file, }; file_eggs.lock().unwrap().push(egg); }); } }); file_eggs.sort_by(|a, b| self.filter.compare_files(&*a.file, &*b.file)); let num_eggs = file_eggs.len(); for (index, egg) in file_eggs.into_iter().enumerate() { let mut files = Vec::new(); let mut errors = egg.errors; let row = Row { depth: depth, cells: Some(egg.cells), name: egg.name, last: index == num_eggs - 1, }; table.rows.push(row); if let Some(ref dir) = egg.dir { for file_to_add in dir.files() { match file_to_add { Ok(f) => files.push(f), Err((path, e)) => errors.push((e, Some(path))) } } self.filter.filter_files(&mut files); if!files.is_empty() { for xattr in egg.xattrs { table.add_xattr(xattr, depth + 1, false); } for (error, path) in errors { table.add_error(&error, depth + 1, false, path); } self.add_files_to_table(table, files, depth + 1); continue; } } let count = egg.xattrs.len(); for (index, xattr) in egg.xattrs.into_iter().enumerate() { table.add_xattr(xattr, depth + 1, errors.is_empty() && index == count - 1); } let count = errors.len(); for (index, (error, path)) in errors.into_iter().enumerate() { table.add_error(&error, depth + 1, index == count - 1, path); } } } } struct Row { /// Vector of cells to display. /// /// Most of the rows will be used to display files' metadata, so this will /// almost always be `Some`, containing a vector of cells. It will only be /// `None` for a row displaying an attribute or error, neither of which /// have cells. cells: Option<Vec<Cell>>, // Did You Know? // A Vec<Cell> and an Option<Vec<Cell>> actually have the same byte size! /// This file's name, in coloured output. The name is treated separately /// from the other cells, as it never requires padding. name: Cell, /// How many directories deep into the tree structure this is. Directories /// on top have depth 0. depth: usize, /// Whether this is the last entry in the directory. This flag is used /// when calculating the tree view. last: bool, } impl Row { /// Gets the Unicode display width of the indexed column, if present. If /// not, returns 0. fn column_width(&self, index: usize) -> usize { match self.cells { Some(ref cells) => cells[index].length, None => 0, } } } /// A **Table** object gets built up by the view as it lists files and /// directories. pub struct Table<U> { columns: Vec<Column>, rows: Vec<Row>, time: locale::Time, numeric: locale::Numeric, tz: TimeZone, users: U, colours: Colours, current_year: i64, } impl Default for Table<MockUsers> { fn default() -> Table<MockUsers> { Table { columns: Columns::default().for_dir(None), rows: Vec::new(), time: locale::Time::english(), numeric: locale::Numeric::english(), tz: TimeZone::localtime().unwrap(), users: MockUsers::with_current_uid(0), colours: Colours::default(), current_year: 1234, } } } impl Table<OSUsers> { /// Create a new, empty Table object, setting the caching fields to their /// empty states. pub fn with_options(colours: Colours, columns: Vec<Column>) -> Table<OSUsers> { Table { columns: columns, rows: Vec::new(), time: locale::Time::load_user_locale().unwrap_or_else(|_| locale::Time::english()), numeric: locale::Numeric::load_user_locale().unwrap_or_else(|_| locale::Numeric::english()), tz: TimeZone::localtime().unwrap(), users: OSUsers::empty_cache(), colours: colours, current_year: LocalDateTime::now().year(), } } } impl<U> Table<U> where U: Users { /// Add a dummy "header" row to the table, which contains the names of all /// the columns, underlined. This has dummy data for the cases that aren't /// actually used, such as the depth or list of attributes. pub fn add_header(&mut self) { let row = Row { depth: 0, cells: Some(self.columns.iter().map(|c| Cell::paint(self.colours.header, c.header())).collect()), name: Cell::paint(self.colours.header, "Name"), last: false, }; self.rows.push(row); } fn add_error(&mut self, error: &io::Error, depth: usize, last: bool, path: Option<PathBuf>) { let error_message = match path { Some(path) => format!("<{}: {}>", path.display(), error), None => format!("<{}>", error), }; let row = Row { depth: depth, cells: None, name: Cell::paint(self.colours.broken_arrow, &error_message), last: last, }; self.rows.push(row); } fn add_xattr(&mut self, xattr: Attribute, depth: usize, last: bool) { let row = Row { depth: depth, cells: None, name: Cell::paint(self.colours.perms.attribute, &format!("{} (len {})", xattr.name, xattr.size)), last: last, }; self.rows.push(row); } pub fn add_file_with_cells(&mut self, cells: Vec<Cell>, file: &File, depth: usize, last: bool, links: bool) { let row = Row { depth: depth, cells: Some(cells), name: Cell { text: filename(file, &self.colours, links), length: file.file_name_width() }, last: last, }; self.rows.push(row); } /// Use the list of columns to find which cells should be produced for /// this file, per-column. pub fn cells_for_file(&mut self, file: &File, xattrs: bool) -> Vec<Cell> { self.columns.clone().iter() .map(|c| self.display(file, c, xattrs)) .collect() } fn display(&mut self, file: &File, column: &Column, xattrs: bool) -> Cell { match *column { Column::Permissions => self.render_permissions(file.permissions(), xattrs), Column::FileSize(fmt) => self.render_size(file.size(), fmt), Column::Timestamp(t) => self.render_time(file.timestamp(t)), Column::HardLinks => self.render_links(file.links()), Column::Inode => self.render_inode(file.inode()), Column::Blocks => self.render_blocks(file.blocks()), Column::User => self.render_user(file.user()), Column::Group => self.render_group(file.group()), Column::GitStatus => self.render_git_status(file.git_status()), } } fn render_permissions(&self, permissions: f::Permissions, xattrs: bool) -> Cell { let c = self.colours.perms; let bit = |bit, chr: &'static str, style: Style| { if bit { style.paint(chr) } else { self.colours.punctuation.paint("-") } }; let file_type = match permissions.file_type { f::Type::File => self.colours.filetypes.normal.paint("."), f::Type::Directory => self.colours.filetypes.directory.paint("d"), f::Type::Pipe => self.colours.filetypes.special.paint("|"), f::Type::Link => self.colours.filetypes.symlink.paint("l"), f::Type::Special => self.colours.filetypes.special.paint("?"), }; let x_colour = if let f::Type::File = permissions.file_type { c.user_execute_file } else { c.user_execute_other }; let mut columns = vec![ file_type, bit(permissions.user_read, "r", c.user_read), bit(permissions.user_write, "w", c.user_write), bit(permissions.user_execute, "x", x_colour), bit(permissions.group_read, "r", c.group_read), bit(permissions.group_write, "w", c.group_write), bit(permissions.group_execute, "x", c.group_execute), bit(permissions.other_read, "r", c.other_read), bit(permissions.other_write, "w", c.other_write), bit(permissions.other_execute, "x", c.other_execute), ]; if xattrs { columns.push(c.attribute.paint("@")); } Cell { text: ANSIStrings(&columns).to_string(), length: columns.len(), } } fn render_links(&self, links: f::Links) -> Cell { let style = if links.multiple { self.colours.links.multi_link_file } else { self.colours.links.normal }; Cell::paint(style, &self.numeric.format_int(links.count)) } fn render_blocks(&self, blocks: f::Blocks) -> Cell { match blocks { f::Blocks::Some(blocks) => Cell::paint(self.colours.blocks, &blocks.to_string()), f::Blocks::None => Cell::paint(self.colours.punctuation, "-"), } } fn render_inode(&self, inode: f::Inode) -> Cell { Cell::paint(self.colours.inode, &inode.0.to_string()) } fn render_size(&self, size: f::Size, size_format: SizeFormat) -> Cell { if let f::Size::Some(offset) = size { let result = match size_format { SizeFormat::DecimalBytes => decimal_prefix(offset as f64), SizeFormat::BinaryBytes => binary_prefix(offset as f64), SizeFormat::JustBytes => return Cell::paint(self.colours.size.numbers, &self.numeric.format_int(offset)), }; match result { Standalone(bytes) => Cell::paint(self.colours.size.numbers, &*bytes.to_string()), Prefixed(prefix, n) => { let number = if n < 10f64 { self.numeric.format_float(n, 1) } else { self.numeric.format_int(n as isize) }; let symbol = prefix.symbol(); Cell { text: ANSIStrings( &[ self.colours.size.numbers.paint(&number[..]), self.colours.size.unit.paint(symbol) ]).to_string(), length: number.len() + symbol
Cell::paint(self.colours.date, &format.format(&date, &self.time)) } fn render_git_status(&self, git: f::Git) -> Cell { Cell { text: ANSIStrings(&[ self.render_git_char(git.staged), self.render_git_char(git.unstaged) ]).to_string(), length: 2, } } fn render_git_char(&self, status: f::GitStatus) -> ANSIString { match status { f::GitStatus::N otModified
.len(), } } } } else { Cell::paint(self.colours.punctuation, "-") } } fn render_time(&self, timestamp: f::Time) -> Cell { let date = self.tz.at(LocalDateTime::at(timestamp.0)); let format = if date.year() == self.current_year { DateFormat::parse("{2>:D} {:M} {2>:h}:{02>:m}").unwrap() } else { DateFormat::parse("{2>:D} {:M} {5>:Y}").unwrap() };
conditional_block
details.rs
_prefix, Prefixed, Standalone, PrefixNames}; use users::{OSUsers, Users}; use users::mock::MockUsers; use super::filename; /// With the **Details** view, the output gets formatted into columns, with /// each `Column` object showing some piece of information about the file, /// such as its size, or its permissions. /// /// To do this, the results have to be written to a table, instead of /// displaying each file immediately. Then, the width of each column can be /// calculated based on the individual results, and the fields are padded /// during output. /// /// Almost all the heavy lifting is done in a Table object, which handles the /// columns for each row. #[derive(PartialEq, Debug, Copy, Clone, Default)] pub struct Details { /// A Columns object that says which columns should be included in the /// output in the general case. Directories themselves can pick which /// columns are *added* to this list, such as the Git column. pub columns: Option<Columns>, /// Whether to recurse through directories with a tree view, and if so, /// which options to use. This field is only relevant here if the `tree` /// field of the RecurseOptions is `true`. pub recurse: Option<RecurseOptions>, /// How to sort and filter the files after getting their details. pub filter: FileFilter, /// Whether to show a header line or not. pub header: bool, /// Whether to show each file's extended attributes. pub xattr: bool, /// The colours to use to display information in the table, including the /// colour of the tree view symbols. pub colours: Colours, } impl Details { /// Print the details of the given vector of files -- all of which will /// have been read from the given directory, if present -- to stdout. pub fn view(&self, dir: Option<&Dir>, files: Vec<File>) { // First, transform the Columns object into a vector of columns for // the current directory. let columns_for_dir = match self.columns { Some(cols) => cols.for_dir(dir), None => Vec::new(), }; // Next, add a header if the user requests it. let mut table = Table::with_options(self.colours, columns_for_dir); if self.header { table.add_header() } // Then add files to the table and print it out. self.add_files_to_table(&mut table, files, 0); for cell in table.print_table() { println!("{}", cell.text); } } /// Adds files to the table, possibly recursively. This is easily /// parallelisable, and uses a pool of threads. fn add_files_to_table<'dir, U: Users+Send>(&self, mut table: &mut Table<U>, src: Vec<File<'dir>>, depth: usize) { use num_cpus; use scoped_threadpool::Pool; use std::sync::{Arc, Mutex}; let mut pool = Pool::new(num_cpus::get() as u32); let mut file_eggs = Vec::new(); struct Egg<'_> { cells: Vec<Cell>, name: Cell, xattrs: Vec<Attribute>, errors: Vec<(io::Error, Option<PathBuf>)>, dir: Option<Dir>, file: Arc<File<'_>>, } pool.scoped(|scoped| { let file_eggs = Arc::new(Mutex::new(&mut file_eggs)); let table = Arc::new(Mutex::new(&mut table)); for file in src.into_iter() { let file: Arc<File> = Arc::new(file); let file_eggs = file_eggs.clone(); let table = table.clone(); scoped.execute(move || { let mut errors = Vec::new(); let mut xattrs = Vec::new(); match file.path.attributes() { Ok(xs) => { if self.xattr { for xattr in xs { xattrs.push(xattr); } } }, Err(e) => { if self.xattr { errors.push((e, None)); } }, }; let cells = table.lock().unwrap().cells_for_file(&file,!xattrs.is_empty()); let name = Cell { text: filename(&file, &self.colours, true), length: file.file_name_width() }; let mut dir = None; if let Some(r) = self.recurse { if file.is_directory() && r.tree &&!r.is_too_deep(depth) { if let Ok(d) = file.to_dir(false) { dir = Some(d); } } }; let egg = Egg { cells: cells, name: name, xattrs: xattrs, errors: errors, dir: dir, file: file, }; file_eggs.lock().unwrap().push(egg); }); } }); file_eggs.sort_by(|a, b| self.filter.compare_files(&*a.file, &*b.file)); let num_eggs = file_eggs.len(); for (index, egg) in file_eggs.into_iter().enumerate() { let mut files = Vec::new(); let mut errors = egg.errors; let row = Row { depth: depth, cells: Some(egg.cells), name: egg.name, last: index == num_eggs - 1, }; table.rows.push(row); if let Some(ref dir) = egg.dir { for file_to_add in dir.files() { match file_to_add { Ok(f) => files.push(f), Err((path, e)) => errors.push((e, Some(path))) } } self.filter.filter_files(&mut files); if!files.is_empty() { for xattr in egg.xattrs { table.add_xattr(xattr, depth + 1, false); } for (error, path) in errors { table.add_error(&error, depth + 1, false, path); } self.add_files_to_table(table, files, depth + 1); continue; } } let count = egg.xattrs.len(); for (index, xattr) in egg.xattrs.into_iter().enumerate() { table.add_xattr(xattr, depth + 1, errors.is_empty() && index == count - 1); } let count = errors.len(); for (index, (error, path)) in errors.into_iter().enumerate() { table.add_error(&error, depth + 1, index == count - 1, path); } } } } struct Row { /// Vector of cells to display. /// /// Most of the rows will be used to display files' metadata, so this will /// almost always be `Some`, containing a vector of cells. It will only be /// `None` for a row displaying an attribute or error, neither of which /// have cells. cells: Option<Vec<Cell>>, // Did You Know? // A Vec<Cell> and an Option<Vec<Cell>> actually have the same byte size! /// This file's name, in coloured output. The name is treated separately /// from the other cells, as it never requires padding. name: Cell, /// How many directories deep into the tree structure this is. Directories /// on top have depth 0. depth: usize, /// Whether this is the last entry in the directory. This flag is used /// when calculating the tree view. last: bool, } impl Row { /// Gets the Unicode display width of the indexed column, if present. If /// not, returns 0. fn column_width(&self, index: usize) -> usize { match self.cells { Some(ref cells) => cells[index].length, None => 0, } } } /// A **Table** object gets built up by the view as it lists files and /// directories. pub struct Table<U> { columns: Vec<Column>, rows: Vec<Row>, time: locale::Time, numeric: locale::Numeric, tz: TimeZone, users: U, colours: Colours, current_year: i64, } impl Default for Table<MockUsers> { fn default() -> Table<MockUsers> { Table { columns: Columns::default().for_dir(None), rows: Vec::new(), time: locale::Time::english(), numeric: locale::Numeric::english(), tz: TimeZone::localtime().unwrap(), users: MockUsers::with_current_uid(0), colours: Colours::default(), current_year: 1234, } } } impl Table<OSUsers> { /// Create a new, empty Table object, setting the caching fields to their /// empty states. pub fn with_options(colours: Colours, columns: Vec<Column>) -> Table<OSUsers> { Table { columns: columns, rows: Vec::new(), time: locale::Time::load_user_locale().unwrap_or_else(|_| locale::Time::english()), numeric: locale::Numeric::load_user_locale().unwrap_or_else(|_| locale::Numer
lish()), tz: TimeZone::localtime().unwrap(), users: OSUsers::empty_cache(), colours: colours, current_year: LocalDateTime::now().year(), } } } impl<U> Table<U> where U: Users { /// Add a dummy "header" row to the table, which contains the names of all /// the columns, underlined. This has dummy data for the cases that aren't /// actually used, such as the depth or list of attributes. pub fn add_header(&mut self) { let row = Row { depth: 0, cells: Some(self.columns.iter().map(|c| Cell::paint(self.colours.header, c.header())).collect()), name: Cell::paint(self.colours.header, "Name"), last: false, }; self.rows.push(row); } fn add_error(&mut self, error: &io::Error, depth: usize, last: bool, path: Option<PathBuf>) { let error_message = match path { Some(path) => format!("<{}: {}>", path.display(), error), None => format!("<{}>", error), }; let row = Row { depth: depth, cells: None, name: Cell::paint(self.colours.broken_arrow, &error_message), last: last, }; self.rows.push(row); } fn add_xattr(&mut self, xattr: Attribute, depth: usize, last: bool) { let row = Row { depth: depth, cells: None, name: Cell::paint(self.colours.perms.attribute, &format!("{} (len {})", xattr.name, xattr.size)), last: last, }; self.rows.push(row); } pub fn add_file_with_cells(&mut self, cells: Vec<Cell>, file: &File, depth: usize, last: bool, links: bool) { let row = Row { depth: depth, cells: Some(cells), name: Cell { text: filename(file, &self.colours, links), length: file.file_name_width() }, last: last, }; self.rows.push(row); } /// Use the list of columns to find which cells should be produced for /// this file, per-column. pub fn cells_for_file(&mut self, file: &File, xattrs: bool) -> Vec<Cell> { self.columns.clone().iter() .map(|c| self.display(file, c, xattrs)) .collect() } fn display(&mut self, file: &File, column: &Column, xattrs: bool) -> Cell { match *column { Column::Permissions => self.render_permissions(file.permissions(), xattrs), Column::FileSize(fmt) => self.render_size(file.size(), fmt), Column::Timestamp(t) => self.render_time(file.timestamp(t)), Column::HardLinks => self.render_links(file.links()), Column::Inode => self.render_inode(file.inode()), Column::Blocks => self.render_blocks(file.blocks()), Column::User => self.render_user(file.user()), Column::Group => self.render_group(file.group()), Column::GitStatus => self.render_git_status(file.git_status()), } } fn render_permissions(&self, permissions: f::Permissions, xattrs: bool) -> Cell { let c = self.colours.perms; let bit = |bit, chr: &'static str, style: Style| { if bit { style.paint(chr) } else { self.colours.punctuation.paint("-") } }; let file_type = match permissions.file_type { f::Type::File => self.colours.filetypes.normal.paint("."), f::Type::Directory => self.colours.filetypes.directory.paint("d"), f::Type::Pipe => self.colours.filetypes.special.paint("|"), f::Type::Link => self.colours.filetypes.symlink.paint("l"), f::Type::Special => self.colours.filetypes.special.paint("?"), }; let x_colour = if let f::Type::File = permissions.file_type { c.user_execute_file } else { c.user_execute_other }; let mut columns = vec![ file_type, bit(permissions.user_read, "r", c.user_read), bit(permissions.user_write, "w", c.user_write), bit(permissions.user_execute, "x", x_colour), bit(permissions.group_read, "r", c.group_read), bit(permissions.group_write, "w", c.group_write), bit(permissions.group_execute, "x", c.group_execute), bit(permissions.other_read, "r", c.other_read), bit(permissions.other_write, "w", c.other_write), bit(permissions.other_execute, "x", c.other_execute), ]; if xattrs { columns.push(c.attribute.paint("@")); } Cell { text: ANSIStrings(&columns).to_string(), length: columns.len(), } } fn render_links(&self, links: f::Links) -> Cell { let style = if links.multiple { self.colours.links.multi_link_file } else { self.colours.links.normal }; Cell::paint(style, &self.numeric.format_int(links.count)) } fn render_blocks(&self, blocks: f::Blocks) -> Cell { match blocks { f::Blocks::Some(blocks) => Cell::paint(self.colours.blocks, &blocks.to_string()), f::Blocks::None => Cell::paint(self.colours.punctuation, "-"), } } fn render_inode(&self, inode: f::Inode) -> Cell { Cell::paint(self.colours.inode, &inode.0.to_string()) } fn render_size(&self, size: f::Size, size_format: SizeFormat) -> Cell { if let f::Size::Some(offset) = size { let result = match size_format { SizeFormat::DecimalBytes => decimal_prefix(offset as f64), SizeFormat::BinaryBytes => binary_prefix(offset as f64), SizeFormat::JustBytes => return Cell::paint(self.colours.size.numbers, &self.numeric.format_int(offset)), }; match result { Standalone(bytes) => Cell::paint(self.colours.size.numbers, &*bytes.to_string()), Prefixed(prefix, n) => { let number = if n < 10f64 { self.numeric.format_float(n, 1) } else { self.numeric.format_int(n as isize) }; let symbol = prefix.symbol(); Cell { text: ANSIStrings( &[ self.colours.size.numbers.paint(&number[..]), self.colours.size.unit.paint(symbol) ]).to_string(), length: number.len() + symbol.len(), } } } } else { Cell::paint(self.colours.punctuation, "-") } } fn render_time(&self, timestamp: f::Time) -> Cell { let date = self.tz.at(LocalDateTime::at(timestamp.0)); let format = if date.year() == self.current_year { DateFormat::parse("{2>:D} {:M} {2>:h}:{02>:m}").unwrap() } else { DateFormat::parse("{2>:D} {:M} {5>:Y}").unwrap() }; Cell::paint(self.colours.date, &format.format(&date, &self.time)) } fn render_git_status(&self, git: f::Git) -> Cell { Cell { text: ANSIStrings(&[ self.render_git_char(git.staged), self.render_git_char(git.unstaged) ]).to_string(), length: 2, } } fn render_git_char(&self, status: f::GitStatus) -> ANSIString { match status { f::GitStatus::Not
ic::eng
identifier_name
details.rs
::Error, depth: usize, last: bool, path: Option<PathBuf>) { let error_message = match path { Some(path) => format!("<{}: {}>", path.display(), error), None => format!("<{}>", error), }; let row = Row { depth: depth, cells: None, name: Cell::paint(self.colours.broken_arrow, &error_message), last: last, }; self.rows.push(row); } fn add_xattr(&mut self, xattr: Attribute, depth: usize, last: bool) { let row = Row { depth: depth, cells: None, name: Cell::paint(self.colours.perms.attribute, &format!("{} (len {})", xattr.name, xattr.size)), last: last, }; self.rows.push(row); } pub fn add_file_with_cells(&mut self, cells: Vec<Cell>, file: &File, depth: usize, last: bool, links: bool) { let row = Row { depth: depth, cells: Some(cells), name: Cell { text: filename(file, &self.colours, links), length: file.file_name_width() }, last: last, }; self.rows.push(row); } /// Use the list of columns to find which cells should be produced for /// this file, per-column. pub fn cells_for_file(&mut self, file: &File, xattrs: bool) -> Vec<Cell> { self.columns.clone().iter() .map(|c| self.display(file, c, xattrs)) .collect() } fn display(&mut self, file: &File, column: &Column, xattrs: bool) -> Cell { match *column { Column::Permissions => self.render_permissions(file.permissions(), xattrs), Column::FileSize(fmt) => self.render_size(file.size(), fmt), Column::Timestamp(t) => self.render_time(file.timestamp(t)), Column::HardLinks => self.render_links(file.links()), Column::Inode => self.render_inode(file.inode()), Column::Blocks => self.render_blocks(file.blocks()), Column::User => self.render_user(file.user()), Column::Group => self.render_group(file.group()), Column::GitStatus => self.render_git_status(file.git_status()), } } fn render_permissions(&self, permissions: f::Permissions, xattrs: bool) -> Cell { let c = self.colours.perms; let bit = |bit, chr: &'static str, style: Style| { if bit { style.paint(chr) } else { self.colours.punctuation.paint("-") } }; let file_type = match permissions.file_type { f::Type::File => self.colours.filetypes.normal.paint("."), f::Type::Directory => self.colours.filetypes.directory.paint("d"), f::Type::Pipe => self.colours.filetypes.special.paint("|"), f::Type::Link => self.colours.filetypes.symlink.paint("l"), f::Type::Special => self.colours.filetypes.special.paint("?"), }; let x_colour = if let f::Type::File = permissions.file_type { c.user_execute_file } else { c.user_execute_other }; let mut columns = vec![ file_type, bit(permissions.user_read, "r", c.user_read), bit(permissions.user_write, "w", c.user_write), bit(permissions.user_execute, "x", x_colour), bit(permissions.group_read, "r", c.group_read), bit(permissions.group_write, "w", c.group_write), bit(permissions.group_execute, "x", c.group_execute), bit(permissions.other_read, "r", c.other_read), bit(permissions.other_write, "w", c.other_write), bit(permissions.other_execute, "x", c.other_execute), ]; if xattrs { columns.push(c.attribute.paint("@")); } Cell { text: ANSIStrings(&columns).to_string(), length: columns.len(), } } fn render_links(&self, links: f::Links) -> Cell { let style = if links.multiple { self.colours.links.multi_link_file } else { self.colours.links.normal }; Cell::paint(style, &self.numeric.format_int(links.count)) } fn render_blocks(&self, blocks: f::Blocks) -> Cell { match blocks { f::Blocks::Some(blocks) => Cell::paint(self.colours.blocks, &blocks.to_string()), f::Blocks::None => Cell::paint(self.colours.punctuation, "-"), } } fn render_inode(&self, inode: f::Inode) -> Cell { Cell::paint(self.colours.inode, &inode.0.to_string()) } fn render_size(&self, size: f::Size, size_format: SizeFormat) -> Cell { if let f::Size::Some(offset) = size { let result = match size_format { SizeFormat::DecimalBytes => decimal_prefix(offset as f64), SizeFormat::BinaryBytes => binary_prefix(offset as f64), SizeFormat::JustBytes => return Cell::paint(self.colours.size.numbers, &self.numeric.format_int(offset)), }; match result { Standalone(bytes) => Cell::paint(self.colours.size.numbers, &*bytes.to_string()), Prefixed(prefix, n) => { let number = if n < 10f64 { self.numeric.format_float(n, 1) } else { self.numeric.format_int(n as isize) }; let symbol = prefix.symbol(); Cell { text: ANSIStrings( &[ self.colours.size.numbers.paint(&number[..]), self.colours.size.unit.paint(symbol) ]).to_string(), length: number.len() + symbol.len(), } } } } else { Cell::paint(self.colours.punctuation, "-") } } fn render_time(&self, timestamp: f::Time) -> Cell { let date = self.tz.at(LocalDateTime::at(timestamp.0)); let format = if date.year() == self.current_year { DateFormat::parse("{2>:D} {:M} {2>:h}:{02>:m}").unwrap() } else { DateFormat::parse("{2>:D} {:M} {5>:Y}").unwrap() }; Cell::paint(self.colours.date, &format.format(&date, &self.time)) } fn render_git_status(&self, git: f::Git) -> Cell { Cell { text: ANSIStrings(&[ self.render_git_char(git.staged), self.render_git_char(git.unstaged) ]).to_string(), length: 2, } } fn render_git_char(&self, status: f::GitStatus) -> ANSIString { match status { f::GitStatus::NotModified => self.colours.punctuation.paint("-"), f::GitStatus::New => self.colours.git.new.paint("N"), f::GitStatus::Modified => self.colours.git.modified.paint("M"), f::GitStatus::Deleted => self.colours.git.deleted.paint("D"), f::GitStatus::Renamed => self.colours.git.renamed.paint("R"), f::GitStatus::TypeChange => self.colours.git.typechange.paint("T"), } } fn render_user(&mut self, user: f::User) -> Cell { let user_name = match self.users.get_user_by_uid(user.0) { Some(user) => user.name, None => user.0.to_string(), }; let style = if self.users.get_current_uid() == user.0 { self.colours.users.user_you } else { self.colours.users.user_someone_else }; Cell::paint(style, &*user_name) } fn render_group(&mut self, group: f::Group) -> Cell { let mut style = self.colours.users.group_not_yours; let group_name = match self.users.get_group_by_gid(group.0) { Some(group) => { let current_uid = self.users.get_current_uid(); if let Some(current_user) = self.users.get_user_by_uid(current_uid) { if current_user.primary_group == group.gid || group.members.contains(&current_user.name) { style = self.colours.users.group_yours; } } group.name }, None => group.0.to_string(), }; Cell::paint(style, &*group_name) } /// Render the table as a vector of Cells, to be displayed on standard output. pub fn print_table(&self) -> Vec<Cell> { let mut stack = Vec::new(); let mut cells = Vec::new(); // Work out the list of column widths by finding the longest cell for // each column, then formatting each cell in that column to be the // width of that one. let column_widths: Vec<usize> = (0.. self.columns.len()) .map(|n| self.rows.iter().map(|row| row.column_width(n)).max().unwrap_or(0)) .collect(); let total_width: usize = self.columns.len() + column_widths.iter().sum::<usize>(); for row in self.rows.iter() { let mut cell = Cell::empty(); if let Some(ref cells) = row.cells { for (n, width) in column_widths.iter().enumerate() { match self.columns[n].alignment() { Alignment::Left => { cell.append(&cells[n]); cell.add_spaces(width - cells[n].length); } Alignment::Right => { cell.add_spaces(width - cells[n].length); cell.append(&cells[n]); } } cell.add_spaces(1); } } else { cell.add_spaces(total_width) } let mut filename = String::new(); let mut filename_length = 0; // A stack tracks which tree characters should be printed. It's // necessary to maintain information about the previously-printed // lines, as the output will change based on whether the // *previous* entry was the last in its directory. stack.resize(row.depth + 1, TreePart::Edge); stack[row.depth] = if row.last { TreePart::Corner } else { TreePart::Edge }; for i in 1.. row.depth + 1 { filename.push_str(&*self.colours.punctuation.paint(stack[i].ascii_art()).to_string()); filename_length += 4; } stack[row.depth] = if row.last { TreePart::Blank } else { TreePart::Line }; // If any tree characters have been printed, then add an extra // space, which makes the output look much better. if row.depth!= 0 { filename.push(' '); filename_length += 1; } // Print the name without worrying about padding. filename.push_str(&*row.name.text); filename_length += row.name.length; cell.append(&Cell { text: filename, length: filename_length }); cells.push(cell); } cells } } #[derive(PartialEq, Debug, Clone)] enum TreePart { /// Rightmost column, *not* the last in the directory. Edge, /// Not the rightmost column, and the directory has not finished yet. Line, /// Rightmost column, and the last in the directory. Corner, /// Not the rightmost column, and the directory *has* finished. Blank, } impl TreePart { fn ascii_art(&self) -> &'static str { match *self { TreePart::Edge => "β”œβ”€β”€", TreePart::Line => "β”‚ ", TreePart::Corner => "└──", TreePart::Blank => " ", } } } #[cfg(test)] pub mod test { pub use super::Table; pub use file::File; pub use file::fields as f; pub use column::{Cell, Column}; pub use users::{User, Group, uid_t, gid_t}; pub use users::mock::MockUsers; pub use ansi_term::Style; pub use ansi_term::Colour::*; pub fn newser(uid: uid_t, name: &str, group: gid_t) -> User { User { uid: uid, name: name.to_string(), primary_group: group, home_dir: String::new(), shell: String::new(), } } // These tests create a new, default Table object, then fill in the // expected style in a certain way. This means we can check that the // right style is being used, as otherwise, it would just be plain. // // Doing things with fields is way easier than having to fake the entire // Metadata struct, which is what I was doing before! mod users { #![allow(unused_results)] use super::*; #[test] fn named() { let mut table = Table::default(); table.colours.users.user_you = Red.bold(); let mut users = MockUsers::with_current_uid(1000); users.add_user(newser(1000, "enoch", 100)); table.users = users; let user = f::User(1000); let expected = Cell::paint(Red.bold(), "enoch"); assert_eq!(expected, table.render_user(user)) } #[test] fn unnamed() { let mut table = Table::default(); table.colours.users.user_you = Cyan.bold(); let users = MockUsers::with_current_uid(1000); table.users = users; let user = f::User(1000); let expected = Cell::paint(Cyan.bold(), "1000"); assert_eq!(expected, table.render_user(user)); } #[test] fn different_named() { let mut table = Table::default(); table.colours.users.user_someone_else = Green.bold(); table.users.add_user(newser(1000, "enoch", 100)); let user = f::User(1000); let expected = Cell::paint(Green.bold(), "enoch"); assert_eq!(expected, table.render_user(user)); } #[test] fn different_unnamed() { let mut table = Table::default(); table.colours.users.user_someone_else = Red.normal(); let user = f::User(1000); let expected = Cell::paint(Red.normal(), "1000"); assert_eq!(expected, table.render_user(user)); } #[test] fn overflow() { let mut table = Table::default(); table.colours.users.user_someone_else = Blue.underline(); let user = f::User(2_147_483_648); let expected = Cell::paint(Blue.underline(), "2147483648"); assert_eq!(expected, table.render_user(user)); } } mod groups { #![allow(unused_results)] use super::*; #[test] fn named() { let mut table = Table::default(); table.colours.users.group_not_yours = Fixed(101).normal(); let mut users = MockUsers::with_current_uid(1000); users.add_group(Group { gid: 100, name: "folk".to_string(), members: vec![] }); table.users = users; let group = f::Group(100); let expected = Cell::paint(Fixed(101).normal(), "folk"); assert_eq!(expected, table.render_group(group)) } #[test] fn unnamed() { let mut table = Table::default(); table.colours.users.group_not_yours = Fixed(87).normal(); let users = MockUsers::with_current_uid(1000); table.users = users; let group = f::Group(100); let expected = Cell::paint(Fixed(87).normal(), "100"); assert_eq!(expected, table.render_group(group)); } #[test] fn primary() { let mut table = Table::default(); table.colours.users.group_yours = Fixed(64).normal(); let mut users = MockUsers::with_current_uid(2); users.add_user(newser(2, "eve", 100)); users.add_group(Group { gid: 100, name: "folk".to_string(), members: vec![] }); table.users = users; let group = f::Group(100); let expected = Cell::paint(Fixed(64).normal(), "folk"); assert_eq!(expected, table.render_group(group)) } #[test] fn secondary() { let mut table = Table::default(); table.colours.users.group_yours = Fixed(31).normal(); let mut users = MockUsers::with_current_uid(2); users.add_user(newser(2, "eve", 666)); users.add_group(Group { gid: 100, name: "folk".to_string(), members: vec![ "eve".to_string() ] }); table.users = users; let group = f::Group(100); let expected = Cell::paint(Fixed(31).normal(), "folk"); assert_eq!(expected, table.render_group(group)) } #[test] fn overflow() { let mut table = Table::default(); table.colours.users.group_not_yours = Blue.underline(); let group = f::Group(2_147_483_648); let expected = Cell::paint(Blue.underline(), "2147483648"); assert_eq!(expected, table.render_group(group)); } } }
identifier_body
cabi_powerpc.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use libc::c_uint; use llvm; use llvm::{Integer, Pointer, Float, Double, Struct, Array}; use llvm::{StructRetAttribute, ZExtAttribute}; use trans::cabi::{FnType, ArgType}; use trans::context::CrateContext; use trans::type_::Type; use std::cmp; fn align_up_to(off: uint, a: uint) -> uint { return (off + a - 1u) / a * a; } fn align(off: uint, ty: Type) -> uint { let a = ty_align(ty); return align_up_to(off, a); } fn ty_align(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { 1 } else { let str_tys = ty.field_types(); str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t))) } } Array => { let elt = ty.element_type(); ty_align(elt) } _ => panic!("ty_size: unhandled type") } } fn ty_size(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { let str_tys = ty.field_types(); str_tys.iter().fold(0, |s, t| s + ty_size(*t)) } else { let str_tys = ty.field_types(); let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t)); align(size, ty) } } Array => { let len = ty.array_length(); let elt = ty.element_type(); let eltsz = ty_size(elt); len * eltsz } _ => panic!("ty_size: unhandled type") } } fn classify_ret_ty(ccx: &CrateContext, ty: Type) -> ArgType { if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else { ArgType::indirect(ty, Some(StructRetAttribute)) } } fn classify_arg_ty(ccx: &CrateContext, ty: Type, offset: &mut uint) -> ArgType { let orig_offset = *offset; let size = ty_size(ty) * 8; let mut align = ty_align(ty); align = cmp::min(cmp::max(align, 4), 8); *offset = align_up_to(*offset, align); *offset += align_up_to(size, align * 8) / 8; if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else { ArgType::direct( ty, Some(struct_ty(ccx, ty)), padding_ty(ccx, align, orig_offset), None ) } } fn is_reg_ty(ty: Type) -> bool { return match ty.kind() { Integer | Pointer | Float | Double => true, _ => false }; } fn padding_ty(ccx: &CrateContext, align: uint, offset: uint) -> Option<Type> { if ((align - 1 ) & offset) > 0 { Some(Type::i32(ccx)) } else { None } } fn coerce_to_int(ccx: &CrateContext, size: uint) -> Vec<Type> { let int_ty = Type::i32(ccx); let mut args = Vec::new(); let mut n = size / 32; while n > 0 { args.push(int_ty); n -= 1; } let r = size % 32; if r > 0 { unsafe { args.push(Type::from_ref(llvm::LLVMIntTypeInContext(ccx.llcx(), r as c_uint))); } } args } fn
(ccx: &CrateContext, ty: Type) -> Type { let size = ty_size(ty) * 8; Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false) } pub fn compute_abi_info(ccx: &CrateContext, atys: &[Type], rty: Type, ret_def: bool) -> FnType { let ret_ty = if ret_def { classify_ret_ty(ccx, rty) } else { ArgType::direct(Type::void(ccx), None, None, None) }; let sret = ret_ty.is_indirect(); let mut arg_tys = Vec::new(); let mut offset = if sret { 4 } else { 0 }; for aty in atys.iter() { let ty = classify_arg_ty(ccx, *aty, &mut offset); arg_tys.push(ty); }; return FnType { arg_tys: arg_tys, ret_ty: ret_ty, }; }
struct_ty
identifier_name
cabi_powerpc.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use libc::c_uint; use llvm; use llvm::{Integer, Pointer, Float, Double, Struct, Array}; use llvm::{StructRetAttribute, ZExtAttribute}; use trans::cabi::{FnType, ArgType}; use trans::context::CrateContext; use trans::type_::Type; use std::cmp; fn align_up_to(off: uint, a: uint) -> uint { return (off + a - 1u) / a * a; } fn align(off: uint, ty: Type) -> uint { let a = ty_align(ty); return align_up_to(off, a); } fn ty_align(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { 1 } else { let str_tys = ty.field_types(); str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t))) } } Array => { let elt = ty.element_type(); ty_align(elt) } _ => panic!("ty_size: unhandled type") } } fn ty_size(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { let str_tys = ty.field_types(); str_tys.iter().fold(0, |s, t| s + ty_size(*t)) } else { let str_tys = ty.field_types(); let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t)); align(size, ty) } } Array => { let len = ty.array_length(); let elt = ty.element_type(); let eltsz = ty_size(elt); len * eltsz } _ => panic!("ty_size: unhandled type") } } fn classify_ret_ty(ccx: &CrateContext, ty: Type) -> ArgType { if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else { ArgType::indirect(ty, Some(StructRetAttribute)) } } fn classify_arg_ty(ccx: &CrateContext, ty: Type, offset: &mut uint) -> ArgType { let orig_offset = *offset; let size = ty_size(ty) * 8; let mut align = ty_align(ty); align = cmp::min(cmp::max(align, 4), 8); *offset = align_up_to(*offset, align); *offset += align_up_to(size, align * 8) / 8; if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else { ArgType::direct( ty, Some(struct_ty(ccx, ty)), padding_ty(ccx, align, orig_offset), None ) } } fn is_reg_ty(ty: Type) -> bool { return match ty.kind() { Integer | Pointer | Float | Double => true, _ => false }; } fn padding_ty(ccx: &CrateContext, align: uint, offset: uint) -> Option<Type> { if ((align - 1 ) & offset) > 0 { Some(Type::i32(ccx)) } else { None } } fn coerce_to_int(ccx: &CrateContext, size: uint) -> Vec<Type> { let int_ty = Type::i32(ccx); let mut args = Vec::new(); let mut n = size / 32; while n > 0 { args.push(int_ty); n -= 1; } let r = size % 32; if r > 0 { unsafe { args.push(Type::from_ref(llvm::LLVMIntTypeInContext(ccx.llcx(), r as c_uint))); } } args } fn struct_ty(ccx: &CrateContext, ty: Type) -> Type { let size = ty_size(ty) * 8; Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false) } pub fn compute_abi_info(ccx: &CrateContext, atys: &[Type], rty: Type, ret_def: bool) -> FnType
}
{ let ret_ty = if ret_def { classify_ret_ty(ccx, rty) } else { ArgType::direct(Type::void(ccx), None, None, None) }; let sret = ret_ty.is_indirect(); let mut arg_tys = Vec::new(); let mut offset = if sret { 4 } else { 0 }; for aty in atys.iter() { let ty = classify_arg_ty(ccx, *aty, &mut offset); arg_tys.push(ty); }; return FnType { arg_tys: arg_tys, ret_ty: ret_ty, };
identifier_body