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
var-captured-in-nested-closure.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#10381) // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:rbreak zzz // gdb-command:run // gdb-command:finish // gdb-command:print variable // gdb-check:$1 = 1 // gdb-command:print constant // gdb-check:$2 = 2 // gdb-command:print a_struct // gdb-check:$3 = {a = -3, b = 4.5, c = 5} // gdb-command:print *struct_ref // gdb-check:$4 = {a = -3, b = 4.5, c = 5} // gdb-command:print *owned // gdb-check:$5 = 6 // gdb-command:print managed->val // gdb-check:$6 = 7 // gdb-command:print closure_local // gdb-check:$7 = 8 // gdb-command:continue // gdb-command:finish // gdb-command:print variable // gdb-check:$8 = 1 // gdb-command:print constant // gdb-check:$9 = 2 // gdb-command:print a_struct // gdb-check:$10 = {a = -3, b = 4.5, c = 5} // gdb-command:print *struct_ref // gdb-check:$11 = {a = -3, b = 4.5, c = 5} // gdb-command:print *owned // gdb-check:$12 = 6 // gdb-command:print managed->val // gdb-check:$13 = 7 // gdb-command:print closure_local // gdb-check:$14 = 8 // gdb-command:continue // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print variable // lldb-check:[...]$0 = 1 // lldb-command:print constant // lldb-check:[...]$1 = 2 // lldb-command:print a_struct // lldb-check:[...]$2 = Struct { a: -3, b: 4.5, c: 5 } // lldb-command:print *struct_ref // lldb-check:[...]$3 = Struct { a: -3, b: 4.5, c: 5 } // lldb-command:print *owned // lldb-check:[...]$4 = 6 // lldb-command:print managed->val // lldb-check:[...]$5 = 7 // lldb-command:print closure_local // lldb-check:[...]$6 = 8 // lldb-command:continue // lldb-command:print variable // lldb-check:[...]$7 = 1 // lldb-command:print constant // lldb-check:[...]$8 = 2 // lldb-command:print a_struct // lldb-check:[...]$9 = Struct { a: -3, b: 4.5, c: 5 } // lldb-command:print *struct_ref // lldb-check:[...]$10 = Struct { a: -3, b: 4.5, c: 5 } // lldb-command:print *owned // lldb-check:[...]$11 = 6 // lldb-command:print managed->val // lldb-check:[...]$12 = 7 // lldb-command:print closure_local // lldb-check:[...]$13 = 8 // lldb-command:continue #![allow(unused_variable)] use std::gc::GC; struct
{ a: int, b: f64, c: uint } fn main() { let mut variable = 1; let constant = 2; let a_struct = Struct { a: -3, b: 4.5, c: 5 }; let struct_ref = &a_struct; let owned = box 6; let managed = box(GC) 7; let closure = || { let closure_local = 8; let nested_closure = || { zzz(); // #break variable = constant + a_struct.a + struct_ref.a + *owned + *managed + closure_local; }; zzz(); // #break nested_closure(); }; closure(); } fn zzz() {()}
Struct
identifier_name
config.rs
use toml; pub struct Config { value: Option<toml::Value>, } impl Config { pub fn new(str: &str) -> Config { Config { value: str.parse::<toml::Value>().ok() } } /// # Get the value of the preference pub fn get(&self, str: &str) -> Option<&toml::Value>
break; }, } } } config_value } /// # Checks if the value of the preference is boolean true pub fn is(&self, str: &str) -> Option<bool> { let value: Option<&toml::Value> = self.get(str); if value.is_some() { return value.unwrap().as_bool() } else { return None } } }
{ let strings: Vec<&str> = str.split(".").collect::<Vec<&str>>(); let mut config_value: Option<&toml::Value> = self.value.as_ref(); for item in &strings { if config_value.is_some() { match config_value.unwrap().get(item) { Some(value) => { config_value = Some(value); match *value { toml::Value::Array(_) | toml::Value::Table(_) => { config_value = Some(value); }, _ => { break; }, } }, None => { config_value = None;
identifier_body
config.rs
use toml; pub struct Config { value: Option<toml::Value>, } impl Config { pub fn new(str: &str) -> Config { Config { value: str.parse::<toml::Value>().ok() } } /// # Get the value of the preference pub fn get(&self, str: &str) -> Option<&toml::Value> { let strings: Vec<&str> = str.split(".").collect::<Vec<&str>>(); let mut config_value: Option<&toml::Value> = self.value.as_ref(); for item in &strings { if config_value.is_some() { match config_value.unwrap().get(item) { Some(value) =>
, None => { config_value = None; break; }, } } } config_value } /// # Checks if the value of the preference is boolean true pub fn is(&self, str: &str) -> Option<bool> { let value: Option<&toml::Value> = self.get(str); if value.is_some() { return value.unwrap().as_bool() } else { return None } } }
{ config_value = Some(value); match *value { toml::Value::Array(_) | toml::Value::Table(_) => { config_value = Some(value); }, _ => { break; }, } }
conditional_block
config.rs
use toml; pub struct Config { value: Option<toml::Value>, } impl Config { pub fn new(str: &str) -> Config { Config { value: str.parse::<toml::Value>().ok() } } /// # Get the value of the preference pub fn get(&self, str: &str) -> Option<&toml::Value> { let strings: Vec<&str> = str.split(".").collect::<Vec<&str>>(); let mut config_value: Option<&toml::Value> = self.value.as_ref(); for item in &strings { if config_value.is_some() { match config_value.unwrap().get(item) { Some(value) => { config_value = Some(value); match *value { toml::Value::Array(_) | toml::Value::Table(_) => { config_value = Some(value); }, _ => { break; }, } }, None => { config_value = None; break; }, } } } config_value } /// # Checks if the value of the preference is boolean true pub fn
(&self, str: &str) -> Option<bool> { let value: Option<&toml::Value> = self.get(str); if value.is_some() { return value.unwrap().as_bool() } else { return None } } }
is
identifier_name
config.rs
use toml; pub struct Config { value: Option<toml::Value>, } impl Config { pub fn new(str: &str) -> Config { Config { value: str.parse::<toml::Value>().ok() } } /// # Get the value of the preference pub fn get(&self, str: &str) -> Option<&toml::Value> { let strings: Vec<&str> = str.split(".").collect::<Vec<&str>>(); let mut config_value: Option<&toml::Value> = self.value.as_ref(); for item in &strings { if config_value.is_some() { match config_value.unwrap().get(item) { Some(value) => { config_value = Some(value);
_ => { break; }, } }, None => { config_value = None; break; }, } } } config_value } /// # Checks if the value of the preference is boolean true pub fn is(&self, str: &str) -> Option<bool> { let value: Option<&toml::Value> = self.get(str); if value.is_some() { return value.unwrap().as_bool() } else { return None } } }
match *value { toml::Value::Array(_) | toml::Value::Table(_) => { config_value = Some(value); },
random_line_split
issue-62307-match-ref-ref-forbidden-without-eq.rs
// RFC 1445 introduced `#[structural_match]`; this attribute must // appear on the `struct`/`enum` definition for any `const` used in a // pattern. // // This is our (forever-unstable) way to mark a datatype as having a // `PartialEq` implementation that is equivalent to recursion over its // substructure. This avoids (at least in the short term) any need to // resolve the question of what semantics is used for such matching. // (See RFC 1445 for more details and discussion.) // Issue 62307 pointed out a case where the structural-match checking // was too shallow. #![warn(indirect_structural_match, nontrivial_structural_match)] // run-pass #[derive(Debug)] struct
(i32); // Overriding `PartialEq` to use this strange notion of "equality" exposes // whether `match` is using structural-equality or method-dispatch // under the hood, which is the antithesis of rust-lang/rfcs#1445 impl PartialEq for B { fn eq(&self, other: &B) -> bool { std::cmp::min(self.0, other.0) == 0 } } fn main() { const RR_B0: & & B = & & B(0); const RR_B1: & & B = & & B(1); match RR_B0 { RR_B1 => { println!("CLAIM RR0: {:?} matches {:?}", RR_B1, RR_B0); } //~^ WARN must be annotated with `#[derive(PartialEq, Eq)]` //~| WARN this was previously accepted _ => { } } match RR_B1 { RR_B1 => { println!("CLAIM RR1: {:?} matches {:?}", RR_B1, RR_B1); } //~^ WARN must be annotated with `#[derive(PartialEq, Eq)]` //~| WARN this was previously accepted _ => { } } }
B
identifier_name
issue-62307-match-ref-ref-forbidden-without-eq.rs
// RFC 1445 introduced `#[structural_match]`; this attribute must // appear on the `struct`/`enum` definition for any `const` used in a // pattern. // // This is our (forever-unstable) way to mark a datatype as having a // `PartialEq` implementation that is equivalent to recursion over its // substructure. This avoids (at least in the short term) any need to // resolve the question of what semantics is used for such matching. // (See RFC 1445 for more details and discussion.) // Issue 62307 pointed out a case where the structural-match checking // was too shallow. #![warn(indirect_structural_match, nontrivial_structural_match)] // run-pass #[derive(Debug)] struct B(i32); // Overriding `PartialEq` to use this strange notion of "equality" exposes // whether `match` is using structural-equality or method-dispatch // under the hood, which is the antithesis of rust-lang/rfcs#1445 impl PartialEq for B { fn eq(&self, other: &B) -> bool { std::cmp::min(self.0, other.0) == 0 } } fn main()
{ const RR_B0: & & B = & & B(0); const RR_B1: & & B = & & B(1); match RR_B0 { RR_B1 => { println!("CLAIM RR0: {:?} matches {:?}", RR_B1, RR_B0); } //~^ WARN must be annotated with `#[derive(PartialEq, Eq)]` //~| WARN this was previously accepted _ => { } } match RR_B1 { RR_B1 => { println!("CLAIM RR1: {:?} matches {:?}", RR_B1, RR_B1); } //~^ WARN must be annotated with `#[derive(PartialEq, Eq)]` //~| WARN this was previously accepted _ => { } } }
identifier_body
issue-62307-match-ref-ref-forbidden-without-eq.rs
// RFC 1445 introduced `#[structural_match]`; this attribute must // appear on the `struct`/`enum` definition for any `const` used in a // pattern. // // This is our (forever-unstable) way to mark a datatype as having a
// Issue 62307 pointed out a case where the structural-match checking // was too shallow. #![warn(indirect_structural_match, nontrivial_structural_match)] // run-pass #[derive(Debug)] struct B(i32); // Overriding `PartialEq` to use this strange notion of "equality" exposes // whether `match` is using structural-equality or method-dispatch // under the hood, which is the antithesis of rust-lang/rfcs#1445 impl PartialEq for B { fn eq(&self, other: &B) -> bool { std::cmp::min(self.0, other.0) == 0 } } fn main() { const RR_B0: & & B = & & B(0); const RR_B1: & & B = & & B(1); match RR_B0 { RR_B1 => { println!("CLAIM RR0: {:?} matches {:?}", RR_B1, RR_B0); } //~^ WARN must be annotated with `#[derive(PartialEq, Eq)]` //~| WARN this was previously accepted _ => { } } match RR_B1 { RR_B1 => { println!("CLAIM RR1: {:?} matches {:?}", RR_B1, RR_B1); } //~^ WARN must be annotated with `#[derive(PartialEq, Eq)]` //~| WARN this was previously accepted _ => { } } }
// `PartialEq` implementation that is equivalent to recursion over its // substructure. This avoids (at least in the short term) any need to // resolve the question of what semantics is used for such matching. // (See RFC 1445 for more details and discussion.)
random_line_split
arc-rw-write-mode-shouldnt-escape.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. // error-pattern: reference is not valid outside of its lifetime extern mod std; use std::arc; fn main()
{ let x = ~arc::RWARC(1); let mut y = None; do x.write_downgrade |write_mode| { y = Some(write_mode); } y.get(); // Adding this line causes a method unification failure instead // do (&option::unwrap(y)).write |state| { assert!(*state == 1); } }
identifier_body
arc-rw-write-mode-shouldnt-escape.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. // error-pattern: reference is not valid outside of its lifetime extern mod std; use std::arc; fn
() { let x = ~arc::RWARC(1); let mut y = None; do x.write_downgrade |write_mode| { y = Some(write_mode); } y.get(); // Adding this line causes a method unification failure instead // do (&option::unwrap(y)).write |state| { assert!(*state == 1); } }
main
identifier_name
arc-rw-write-mode-shouldnt-escape.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. // error-pattern: reference is not valid outside of its lifetime extern mod std; use std::arc; fn main() { let x = ~arc::RWARC(1); let mut y = None; do x.write_downgrade |write_mode| { y = Some(write_mode); } y.get(); // Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).write |state| { assert!(*state == 1); } }
random_line_split
motion.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/. */ //! Computed types for CSS values that are related to motion path. use crate::values::computed::Angle; use crate::values::generics::motion::GenericOffsetPath; use crate::Zero; /// The computed value of `offset-path`. pub type OffsetPath = GenericOffsetPath<Angle>; #[inline] fn
(auto: &bool, angle: &Angle) -> bool { *auto && angle.is_zero() } /// A computed offset-rotate. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedZero, ToCss, ToResolvedValue, )] #[repr(C)] pub struct OffsetRotate { /// If auto is false, this is a fixed angle which indicates a /// constant clockwise rotation transformation applied to it by this /// specified rotation angle. Otherwise, the angle will be added to /// the angle of the direction in layout. #[animation(constant)] #[css(represents_keyword)] pub auto: bool, /// The angle value. #[css(contextual_skip_if = "is_auto_zero_angle")] pub angle: Angle, } impl OffsetRotate { /// Returns "auto 0deg". #[inline] pub fn auto() -> Self { OffsetRotate { auto: true, angle: Zero::zero(), } } }
is_auto_zero_angle
identifier_name
motion.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/. */ //! Computed types for CSS values that are related to motion path. use crate::values::computed::Angle; use crate::values::generics::motion::GenericOffsetPath; use crate::Zero; /// The computed value of `offset-path`. pub type OffsetPath = GenericOffsetPath<Angle>; #[inline] fn is_auto_zero_angle(auto: &bool, angle: &Angle) -> bool { *auto && angle.is_zero() } /// A computed offset-rotate. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq,
ToResolvedValue, )] #[repr(C)] pub struct OffsetRotate { /// If auto is false, this is a fixed angle which indicates a /// constant clockwise rotation transformation applied to it by this /// specified rotation angle. Otherwise, the angle will be added to /// the angle of the direction in layout. #[animation(constant)] #[css(represents_keyword)] pub auto: bool, /// The angle value. #[css(contextual_skip_if = "is_auto_zero_angle")] pub angle: Angle, } impl OffsetRotate { /// Returns "auto 0deg". #[inline] pub fn auto() -> Self { OffsetRotate { auto: true, angle: Zero::zero(), } } }
ToAnimatedZero, ToCss,
random_line_split
motion.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/. */ //! Computed types for CSS values that are related to motion path. use crate::values::computed::Angle; use crate::values::generics::motion::GenericOffsetPath; use crate::Zero; /// The computed value of `offset-path`. pub type OffsetPath = GenericOffsetPath<Angle>; #[inline] fn is_auto_zero_angle(auto: &bool, angle: &Angle) -> bool { *auto && angle.is_zero() } /// A computed offset-rotate. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedZero, ToCss, ToResolvedValue, )] #[repr(C)] pub struct OffsetRotate { /// If auto is false, this is a fixed angle which indicates a /// constant clockwise rotation transformation applied to it by this /// specified rotation angle. Otherwise, the angle will be added to /// the angle of the direction in layout. #[animation(constant)] #[css(represents_keyword)] pub auto: bool, /// The angle value. #[css(contextual_skip_if = "is_auto_zero_angle")] pub angle: Angle, } impl OffsetRotate { /// Returns "auto 0deg". #[inline] pub fn auto() -> Self
}
{ OffsetRotate { auto: true, angle: Zero::zero(), } }
identifier_body
lib.rs
//! //! # Conrod //! //! An easy-to-use, immediate-mode, 2D GUI library featuring a range of useful widgets. //! #![deny(missing_copy_implementations)] #![warn(missing_docs)] #[macro_use] extern crate bitflags; extern crate clock_ticks; extern crate elmesque; extern crate graphics; extern crate json_io; extern crate num; extern crate petgraph; extern crate input; extern crate rand; extern crate rustc_serialize; extern crate vecmath; pub use widget::button::Button; pub use widget::canvas::Canvas; pub use widget::drop_down_list::DropDownList; pub use widget::envelope_editor::EnvelopeEditor; pub use widget::envelope_editor::EnvelopePoint; pub use widget::label::Label; pub use widget::matrix::Matrix as WidgetMatrix; pub use widget::number_dialer::NumberDialer; pub use widget::slider::Slider; pub use widget::split::Split; pub use widget::tabs::Tabs; pub use widget::text_box::TextBox; pub use widget::toggle::Toggle; pub use widget::xy_pad::XYPad; pub use widget::button::Style as ButtonStyle; pub use widget::canvas::Style as CanvasStyle; pub use widget::drop_down_list::Style as DropDownListStyle; pub use widget::envelope_editor::Style as EnvelopeEditorStyle; pub use widget::label::Style as LabelStyle; pub use widget::number_dialer::Style as NumberDialerStyle; pub use widget::slider::Style as SliderStyle; pub use widget::tabs::Style as TabsStyle; pub use widget::text_box::Style as TextBoxStyle; pub use widget::toggle::Style as ToggleStyle; pub use widget::xy_pad::Style as XYPadStyle; pub use background::Background; pub use elmesque::{color, Element}; pub use elmesque::color::{Color, Colorable}; pub use frame::{Framing, Frameable}; pub use graphics::character::CharacterCache; pub use graphics::math::Scalar; pub use label::{FontSize, Labelable}; pub use mouse::Mouse; pub use mouse::ButtonState as MouseButtonState; pub use mouse::Scroll as MouseScroll; pub use position::{align_left_of, align_right_of, align_bottom_of, align_top_of}; pub use position::{middle_of, top_left_of, top_right_of, bottom_left_of, bottom_right_of, mid_top_of, mid_bottom_of, mid_left_of, mid_right_of}; pub use position::{Corner, Depth, Direction, Dimensions, Horizontal, HorizontalAlign, Margin, Padding, Place, Point, Position, Positionable, Sizeable, Vertical, VerticalAlign}; pub use theme::{Align, Theme}; pub use ui::{GlyphCache, Ui, UserInput}; pub use widget::{CommonBuilder, DrawArgs, UpdateArgs, Widget, WidgetId}; pub use widget::State as WidgetState; pub use json_io::Error as JsonIoError; mod background; mod frame; mod graph; mod label; mod mouse; mod position; pub mod theme; mod ui; pub mod utils; mod widget; /// Generate a list of unique IDs given a list of identifiers. /// /// This is the recommended way of generating `WidgetId`s as it greatly lessens the chances of /// making errors when adding or removing widget ids. /// /// Each Widget must have its own unique identifier so that the `Ui` can keep track of its state /// between updates. /// /// To make this easier, we provide the `widget_ids` macro, which generates a unique `WidgetId` for /// each identifier given in the list. /// /// The `with n` syntax reserves `n` number of `WidgetId`s for that identifier rather than just one. /// /// This is often useful in the case that you need to set multiple Widgets in a loop or when using /// the `widget::Matrix`. /// /// Note: Make sure when that you remember to `#[macro_use]` if you want to use this macro - i.e. /// /// `#[macro_use] extern crate conrod;` /// /// Also, if your list has a large number of identifiers (~64 or more) you may find this macro /// hitting rustc's recursion limit (this will show as a compile error). To fix this you can try /// adding the following to your crate root. /// /// `#![recursion_limit="512"]` /// /// This will raise the recursion limit from the default (~64) to 512. You should be able to set it /// to a higher number if you find it necessary. /// #[macro_export] macro_rules! widget_ids { // Handle the first ID. ( $widget_id:ident, $($rest:tt)* ) => ( const $widget_id: $crate::WidgetId = 0; widget_ids!($widget_id => $($rest)*); ); // Handle the first ID with some given step between it and the next ID. ( $widget_id:ident with $step:expr, $($rest:tt)* ) => ( const $widget_id: $crate::WidgetId = 0; widget_ids!($widget_id + $step => $($rest)*); ); // Handle some consecutive ID. ( $prev_id:expr => $widget_id:ident, $($rest:tt)* ) => ( const $widget_id: $crate::WidgetId = $prev_id + 1; widget_ids!($widget_id => $($rest)*); ); // Handle some consecutive ID with some given step between it and the next ID. ( $prev_id:expr => $widget_id:ident with $step:expr, $($rest:tt)* ) => ( const $widget_id: $crate::WidgetId = $prev_id + 1; widget_ids!($widget_id + $step => $($rest)*); ); ///// End cases. ///// // Handle the final ID.
// Handle the final ID. ( $prev_id:expr => ) => (); ///// Handle end cases that don't have a trailing comma. ///// // Handle a single ID without a trailing comma. ( $widget_id:ident ) => ( const $widget_id: $crate::WidgetId = 0; ); // Handle a single ID with some given step without a trailing comma. ( $widget_id:ident with $step:expr ) => ( const $widget_id: $crate::WidgetId = 0; ); // Handle the last ID without a trailing comma. ( $prev_id:expr => $widget_id:ident ) => ( const $widget_id: $crate::WidgetId = $prev_id + 1; ); // Handle the last ID with some given step without a trailing comma. ( $prev_id:expr => $widget_id:ident with $step:expr ) => ( const $widget_id: $crate::WidgetId = $prev_id + 1; ); } #[test] fn test() { widget_ids! { A, B with 64, C with 32, D, E with 8, } assert_eq!(A, 0); assert_eq!(B, 1); assert_eq!(C, 66); assert_eq!(D, 99); assert_eq!(E, 100); }
() => ();
random_line_split
lib.rs
//! //! # Conrod //! //! An easy-to-use, immediate-mode, 2D GUI library featuring a range of useful widgets. //! #![deny(missing_copy_implementations)] #![warn(missing_docs)] #[macro_use] extern crate bitflags; extern crate clock_ticks; extern crate elmesque; extern crate graphics; extern crate json_io; extern crate num; extern crate petgraph; extern crate input; extern crate rand; extern crate rustc_serialize; extern crate vecmath; pub use widget::button::Button; pub use widget::canvas::Canvas; pub use widget::drop_down_list::DropDownList; pub use widget::envelope_editor::EnvelopeEditor; pub use widget::envelope_editor::EnvelopePoint; pub use widget::label::Label; pub use widget::matrix::Matrix as WidgetMatrix; pub use widget::number_dialer::NumberDialer; pub use widget::slider::Slider; pub use widget::split::Split; pub use widget::tabs::Tabs; pub use widget::text_box::TextBox; pub use widget::toggle::Toggle; pub use widget::xy_pad::XYPad; pub use widget::button::Style as ButtonStyle; pub use widget::canvas::Style as CanvasStyle; pub use widget::drop_down_list::Style as DropDownListStyle; pub use widget::envelope_editor::Style as EnvelopeEditorStyle; pub use widget::label::Style as LabelStyle; pub use widget::number_dialer::Style as NumberDialerStyle; pub use widget::slider::Style as SliderStyle; pub use widget::tabs::Style as TabsStyle; pub use widget::text_box::Style as TextBoxStyle; pub use widget::toggle::Style as ToggleStyle; pub use widget::xy_pad::Style as XYPadStyle; pub use background::Background; pub use elmesque::{color, Element}; pub use elmesque::color::{Color, Colorable}; pub use frame::{Framing, Frameable}; pub use graphics::character::CharacterCache; pub use graphics::math::Scalar; pub use label::{FontSize, Labelable}; pub use mouse::Mouse; pub use mouse::ButtonState as MouseButtonState; pub use mouse::Scroll as MouseScroll; pub use position::{align_left_of, align_right_of, align_bottom_of, align_top_of}; pub use position::{middle_of, top_left_of, top_right_of, bottom_left_of, bottom_right_of, mid_top_of, mid_bottom_of, mid_left_of, mid_right_of}; pub use position::{Corner, Depth, Direction, Dimensions, Horizontal, HorizontalAlign, Margin, Padding, Place, Point, Position, Positionable, Sizeable, Vertical, VerticalAlign}; pub use theme::{Align, Theme}; pub use ui::{GlyphCache, Ui, UserInput}; pub use widget::{CommonBuilder, DrawArgs, UpdateArgs, Widget, WidgetId}; pub use widget::State as WidgetState; pub use json_io::Error as JsonIoError; mod background; mod frame; mod graph; mod label; mod mouse; mod position; pub mod theme; mod ui; pub mod utils; mod widget; /// Generate a list of unique IDs given a list of identifiers. /// /// This is the recommended way of generating `WidgetId`s as it greatly lessens the chances of /// making errors when adding or removing widget ids. /// /// Each Widget must have its own unique identifier so that the `Ui` can keep track of its state /// between updates. /// /// To make this easier, we provide the `widget_ids` macro, which generates a unique `WidgetId` for /// each identifier given in the list. /// /// The `with n` syntax reserves `n` number of `WidgetId`s for that identifier rather than just one. /// /// This is often useful in the case that you need to set multiple Widgets in a loop or when using /// the `widget::Matrix`. /// /// Note: Make sure when that you remember to `#[macro_use]` if you want to use this macro - i.e. /// /// `#[macro_use] extern crate conrod;` /// /// Also, if your list has a large number of identifiers (~64 or more) you may find this macro /// hitting rustc's recursion limit (this will show as a compile error). To fix this you can try /// adding the following to your crate root. /// /// `#![recursion_limit="512"]` /// /// This will raise the recursion limit from the default (~64) to 512. You should be able to set it /// to a higher number if you find it necessary. /// #[macro_export] macro_rules! widget_ids { // Handle the first ID. ( $widget_id:ident, $($rest:tt)* ) => ( const $widget_id: $crate::WidgetId = 0; widget_ids!($widget_id => $($rest)*); ); // Handle the first ID with some given step between it and the next ID. ( $widget_id:ident with $step:expr, $($rest:tt)* ) => ( const $widget_id: $crate::WidgetId = 0; widget_ids!($widget_id + $step => $($rest)*); ); // Handle some consecutive ID. ( $prev_id:expr => $widget_id:ident, $($rest:tt)* ) => ( const $widget_id: $crate::WidgetId = $prev_id + 1; widget_ids!($widget_id => $($rest)*); ); // Handle some consecutive ID with some given step between it and the next ID. ( $prev_id:expr => $widget_id:ident with $step:expr, $($rest:tt)* ) => ( const $widget_id: $crate::WidgetId = $prev_id + 1; widget_ids!($widget_id + $step => $($rest)*); ); ///// End cases. ///// // Handle the final ID. () => (); // Handle the final ID. ( $prev_id:expr => ) => (); ///// Handle end cases that don't have a trailing comma. ///// // Handle a single ID without a trailing comma. ( $widget_id:ident ) => ( const $widget_id: $crate::WidgetId = 0; ); // Handle a single ID with some given step without a trailing comma. ( $widget_id:ident with $step:expr ) => ( const $widget_id: $crate::WidgetId = 0; ); // Handle the last ID without a trailing comma. ( $prev_id:expr => $widget_id:ident ) => ( const $widget_id: $crate::WidgetId = $prev_id + 1; ); // Handle the last ID with some given step without a trailing comma. ( $prev_id:expr => $widget_id:ident with $step:expr ) => ( const $widget_id: $crate::WidgetId = $prev_id + 1; ); } #[test] fn
() { widget_ids! { A, B with 64, C with 32, D, E with 8, } assert_eq!(A, 0); assert_eq!(B, 1); assert_eq!(C, 66); assert_eq!(D, 99); assert_eq!(E, 100); }
test
identifier_name
lib.rs
//! //! # Conrod //! //! An easy-to-use, immediate-mode, 2D GUI library featuring a range of useful widgets. //! #![deny(missing_copy_implementations)] #![warn(missing_docs)] #[macro_use] extern crate bitflags; extern crate clock_ticks; extern crate elmesque; extern crate graphics; extern crate json_io; extern crate num; extern crate petgraph; extern crate input; extern crate rand; extern crate rustc_serialize; extern crate vecmath; pub use widget::button::Button; pub use widget::canvas::Canvas; pub use widget::drop_down_list::DropDownList; pub use widget::envelope_editor::EnvelopeEditor; pub use widget::envelope_editor::EnvelopePoint; pub use widget::label::Label; pub use widget::matrix::Matrix as WidgetMatrix; pub use widget::number_dialer::NumberDialer; pub use widget::slider::Slider; pub use widget::split::Split; pub use widget::tabs::Tabs; pub use widget::text_box::TextBox; pub use widget::toggle::Toggle; pub use widget::xy_pad::XYPad; pub use widget::button::Style as ButtonStyle; pub use widget::canvas::Style as CanvasStyle; pub use widget::drop_down_list::Style as DropDownListStyle; pub use widget::envelope_editor::Style as EnvelopeEditorStyle; pub use widget::label::Style as LabelStyle; pub use widget::number_dialer::Style as NumberDialerStyle; pub use widget::slider::Style as SliderStyle; pub use widget::tabs::Style as TabsStyle; pub use widget::text_box::Style as TextBoxStyle; pub use widget::toggle::Style as ToggleStyle; pub use widget::xy_pad::Style as XYPadStyle; pub use background::Background; pub use elmesque::{color, Element}; pub use elmesque::color::{Color, Colorable}; pub use frame::{Framing, Frameable}; pub use graphics::character::CharacterCache; pub use graphics::math::Scalar; pub use label::{FontSize, Labelable}; pub use mouse::Mouse; pub use mouse::ButtonState as MouseButtonState; pub use mouse::Scroll as MouseScroll; pub use position::{align_left_of, align_right_of, align_bottom_of, align_top_of}; pub use position::{middle_of, top_left_of, top_right_of, bottom_left_of, bottom_right_of, mid_top_of, mid_bottom_of, mid_left_of, mid_right_of}; pub use position::{Corner, Depth, Direction, Dimensions, Horizontal, HorizontalAlign, Margin, Padding, Place, Point, Position, Positionable, Sizeable, Vertical, VerticalAlign}; pub use theme::{Align, Theme}; pub use ui::{GlyphCache, Ui, UserInput}; pub use widget::{CommonBuilder, DrawArgs, UpdateArgs, Widget, WidgetId}; pub use widget::State as WidgetState; pub use json_io::Error as JsonIoError; mod background; mod frame; mod graph; mod label; mod mouse; mod position; pub mod theme; mod ui; pub mod utils; mod widget; /// Generate a list of unique IDs given a list of identifiers. /// /// This is the recommended way of generating `WidgetId`s as it greatly lessens the chances of /// making errors when adding or removing widget ids. /// /// Each Widget must have its own unique identifier so that the `Ui` can keep track of its state /// between updates. /// /// To make this easier, we provide the `widget_ids` macro, which generates a unique `WidgetId` for /// each identifier given in the list. /// /// The `with n` syntax reserves `n` number of `WidgetId`s for that identifier rather than just one. /// /// This is often useful in the case that you need to set multiple Widgets in a loop or when using /// the `widget::Matrix`. /// /// Note: Make sure when that you remember to `#[macro_use]` if you want to use this macro - i.e. /// /// `#[macro_use] extern crate conrod;` /// /// Also, if your list has a large number of identifiers (~64 or more) you may find this macro /// hitting rustc's recursion limit (this will show as a compile error). To fix this you can try /// adding the following to your crate root. /// /// `#![recursion_limit="512"]` /// /// This will raise the recursion limit from the default (~64) to 512. You should be able to set it /// to a higher number if you find it necessary. /// #[macro_export] macro_rules! widget_ids { // Handle the first ID. ( $widget_id:ident, $($rest:tt)* ) => ( const $widget_id: $crate::WidgetId = 0; widget_ids!($widget_id => $($rest)*); ); // Handle the first ID with some given step between it and the next ID. ( $widget_id:ident with $step:expr, $($rest:tt)* ) => ( const $widget_id: $crate::WidgetId = 0; widget_ids!($widget_id + $step => $($rest)*); ); // Handle some consecutive ID. ( $prev_id:expr => $widget_id:ident, $($rest:tt)* ) => ( const $widget_id: $crate::WidgetId = $prev_id + 1; widget_ids!($widget_id => $($rest)*); ); // Handle some consecutive ID with some given step between it and the next ID. ( $prev_id:expr => $widget_id:ident with $step:expr, $($rest:tt)* ) => ( const $widget_id: $crate::WidgetId = $prev_id + 1; widget_ids!($widget_id + $step => $($rest)*); ); ///// End cases. ///// // Handle the final ID. () => (); // Handle the final ID. ( $prev_id:expr => ) => (); ///// Handle end cases that don't have a trailing comma. ///// // Handle a single ID without a trailing comma. ( $widget_id:ident ) => ( const $widget_id: $crate::WidgetId = 0; ); // Handle a single ID with some given step without a trailing comma. ( $widget_id:ident with $step:expr ) => ( const $widget_id: $crate::WidgetId = 0; ); // Handle the last ID without a trailing comma. ( $prev_id:expr => $widget_id:ident ) => ( const $widget_id: $crate::WidgetId = $prev_id + 1; ); // Handle the last ID with some given step without a trailing comma. ( $prev_id:expr => $widget_id:ident with $step:expr ) => ( const $widget_id: $crate::WidgetId = $prev_id + 1; ); } #[test] fn test()
{ widget_ids! { A, B with 64, C with 32, D, E with 8, } assert_eq!(A, 0); assert_eq!(B, 1); assert_eq!(C, 66); assert_eq!(D, 99); assert_eq!(E, 100); }
identifier_body
touch.rs
// Copyright 2014 The sdl2-rs Developers. // // 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 ffi::stdinc::{Uint32, Sint64}; use libc::{c_float, c_int}; // SDL_touch.h pub type SDL_TouchID = Sint64; pub type SDL_FingerID = Sint64; pub struct SDL_Finger { pub id: SDL_FingerID, pub x: c_float, pub y: c_float, pub pressure: c_float, } pub static SDL_TOUCH_MOUSEID: Uint32 = -1; extern "C" { pub fn SDL_GetNumTouchDevices() -> c_int;
pub fn SDL_GetNumTouchFingers(touchID: SDL_TouchID) -> c_int; pub fn SDL_GetTouchFinger(touchID: SDL_TouchID, index: c_int) -> *SDL_Finger; }
pub fn SDL_GetTouchDevice(index: c_int) -> SDL_TouchID;
random_line_split
touch.rs
// Copyright 2014 The sdl2-rs Developers. // // 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 ffi::stdinc::{Uint32, Sint64}; use libc::{c_float, c_int}; // SDL_touch.h pub type SDL_TouchID = Sint64; pub type SDL_FingerID = Sint64; pub struct
{ pub id: SDL_FingerID, pub x: c_float, pub y: c_float, pub pressure: c_float, } pub static SDL_TOUCH_MOUSEID: Uint32 = -1; extern "C" { pub fn SDL_GetNumTouchDevices() -> c_int; pub fn SDL_GetTouchDevice(index: c_int) -> SDL_TouchID; pub fn SDL_GetNumTouchFingers(touchID: SDL_TouchID) -> c_int; pub fn SDL_GetTouchFinger(touchID: SDL_TouchID, index: c_int) -> *SDL_Finger; }
SDL_Finger
identifier_name
deriving-meta-multiple.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::hash::{Hash, SipHasher}; // testing multiple separate deriving attributes #[derive(PartialEq)] #[derive(Clone)] #[derive(Hash)] struct
{ bar: uint, baz: int } fn hash<T: Hash>(_t: &T) {} pub fn main() { let a = Foo {bar: 4, baz: -3}; a == a; // check for PartialEq impl w/o testing its correctness a.clone(); // check for Clone impl w/o testing its correctness hash(&a); // check for Hash impl w/o testing its correctness }
Foo
identifier_name
deriving-meta-multiple.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::hash::{Hash, SipHasher}; // testing multiple separate deriving attributes #[derive(PartialEq)] #[derive(Clone)] #[derive(Hash)] struct Foo { bar: uint, baz: int } fn hash<T: Hash>(_t: &T)
pub fn main() { let a = Foo {bar: 4, baz: -3}; a == a; // check for PartialEq impl w/o testing its correctness a.clone(); // check for Clone impl w/o testing its correctness hash(&a); // check for Hash impl w/o testing its correctness }
{}
identifier_body
deriving-meta-multiple.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// <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::hash::{Hash, SipHasher}; // testing multiple separate deriving attributes #[derive(PartialEq)] #[derive(Clone)] #[derive(Hash)] struct Foo { bar: uint, baz: int } fn hash<T: Hash>(_t: &T) {} pub fn main() { let a = Foo {bar: 4, baz: -3}; a == a; // check for PartialEq impl w/o testing its correctness a.clone(); // check for Clone impl w/o testing its correctness hash(&a); // check for Hash impl w/o testing its correctness }
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
random_line_split
htmlformelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::HTMLFormElementBinding; use dom::bindings::utils::{DOMString, ErrorResult}; use dom::document::AbstractDocument; use dom::element::HTMLFormElementTypeId; use dom::htmlcollection::HTMLCollection; use dom::htmlelement::HTMLElement; use dom::node::{AbstractNode, Node}; pub struct HTMLFormElement { htmlelement: HTMLElement } impl HTMLFormElement { pub fn new_inherited(localName: ~str, document: AbstractDocument) -> HTMLFormElement { HTMLFormElement { htmlelement: HTMLElement::new_inherited(HTMLFormElementTypeId, localName, document) } } pub fn new(localName: ~str, document: AbstractDocument) -> AbstractNode { let element = HTMLFormElement::new_inherited(localName, document); Node::reflect_node(@mut element, document, HTMLFormElementBinding::Wrap) } } impl HTMLFormElement { pub fn AcceptCharset(&self) -> DOMString { ~"" } pub fn SetAcceptCharset(&mut self, _accept_charset: DOMString) -> ErrorResult { Ok(()) } pub fn Action(&self) -> DOMString { ~"" } pub fn SetAction(&mut self, _action: DOMString) -> ErrorResult { Ok(()) } pub fn Autocomplete(&self) -> DOMString { ~"" } pub fn SetAutocomplete(&mut self, _autocomplete: DOMString) -> ErrorResult { Ok(()) } pub fn Enctype(&self) -> DOMString { ~"" } pub fn SetEnctype(&mut self, _enctype: DOMString) -> ErrorResult { Ok(()) } pub fn Encoding(&self) -> DOMString { ~"" } pub fn SetEncoding(&mut self, _encoding: DOMString) -> ErrorResult { Ok(()) } pub fn Method(&self) -> DOMString { ~"" } pub fn SetMethod(&mut self, _method: DOMString) -> ErrorResult { Ok(()) } pub fn Name(&self) -> DOMString { ~"" } pub fn SetName(&mut self, _name: DOMString) -> ErrorResult { Ok(()) } pub fn NoValidate(&self) -> bool { false } pub fn SetNoValidate(&mut self, _no_validate: bool) -> ErrorResult { Ok(()) } pub fn
(&self) -> DOMString { ~"" } pub fn SetTarget(&mut self, _target: DOMString) -> ErrorResult { Ok(()) } pub fn Elements(&self) -> @mut HTMLCollection { let window = self.htmlelement.element.node.owner_doc().document().window; HTMLCollection::new(window, ~[]) } pub fn Length(&self) -> i32 { 0 } pub fn Submit(&self) -> ErrorResult { Ok(()) } pub fn Reset(&self) { } pub fn CheckValidity(&self) -> bool { false } pub fn IndexedGetter(&self, _index: u32, _found: &mut bool) -> AbstractNode { fail!("Not implemented.") } }
Target
identifier_name
htmlformelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::HTMLFormElementBinding; use dom::bindings::utils::{DOMString, ErrorResult}; use dom::document::AbstractDocument; use dom::element::HTMLFormElementTypeId; use dom::htmlcollection::HTMLCollection; use dom::htmlelement::HTMLElement; use dom::node::{AbstractNode, Node}; pub struct HTMLFormElement { htmlelement: HTMLElement } impl HTMLFormElement { pub fn new_inherited(localName: ~str, document: AbstractDocument) -> HTMLFormElement { HTMLFormElement { htmlelement: HTMLElement::new_inherited(HTMLFormElementTypeId, localName, document) } } pub fn new(localName: ~str, document: AbstractDocument) -> AbstractNode { let element = HTMLFormElement::new_inherited(localName, document); Node::reflect_node(@mut element, document, HTMLFormElementBinding::Wrap) } } impl HTMLFormElement { pub fn AcceptCharset(&self) -> DOMString { ~"" } pub fn SetAcceptCharset(&mut self, _accept_charset: DOMString) -> ErrorResult { Ok(()) } pub fn Action(&self) -> DOMString { ~"" } pub fn SetAction(&mut self, _action: DOMString) -> ErrorResult { Ok(()) } pub fn Autocomplete(&self) -> DOMString { ~"" } pub fn SetAutocomplete(&mut self, _autocomplete: DOMString) -> ErrorResult { Ok(()) } pub fn Enctype(&self) -> DOMString { ~"" } pub fn SetEnctype(&mut self, _enctype: DOMString) -> ErrorResult { Ok(()) } pub fn Encoding(&self) -> DOMString { ~"" } pub fn SetEncoding(&mut self, _encoding: DOMString) -> ErrorResult { Ok(()) } pub fn Method(&self) -> DOMString { ~""
pub fn SetMethod(&mut self, _method: DOMString) -> ErrorResult { Ok(()) } pub fn Name(&self) -> DOMString { ~"" } pub fn SetName(&mut self, _name: DOMString) -> ErrorResult { Ok(()) } pub fn NoValidate(&self) -> bool { false } pub fn SetNoValidate(&mut self, _no_validate: bool) -> ErrorResult { Ok(()) } pub fn Target(&self) -> DOMString { ~"" } pub fn SetTarget(&mut self, _target: DOMString) -> ErrorResult { Ok(()) } pub fn Elements(&self) -> @mut HTMLCollection { let window = self.htmlelement.element.node.owner_doc().document().window; HTMLCollection::new(window, ~[]) } pub fn Length(&self) -> i32 { 0 } pub fn Submit(&self) -> ErrorResult { Ok(()) } pub fn Reset(&self) { } pub fn CheckValidity(&self) -> bool { false } pub fn IndexedGetter(&self, _index: u32, _found: &mut bool) -> AbstractNode { fail!("Not implemented.") } }
}
random_line_split
htmlformelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::HTMLFormElementBinding; use dom::bindings::utils::{DOMString, ErrorResult}; use dom::document::AbstractDocument; use dom::element::HTMLFormElementTypeId; use dom::htmlcollection::HTMLCollection; use dom::htmlelement::HTMLElement; use dom::node::{AbstractNode, Node}; pub struct HTMLFormElement { htmlelement: HTMLElement } impl HTMLFormElement { pub fn new_inherited(localName: ~str, document: AbstractDocument) -> HTMLFormElement { HTMLFormElement { htmlelement: HTMLElement::new_inherited(HTMLFormElementTypeId, localName, document) } } pub fn new(localName: ~str, document: AbstractDocument) -> AbstractNode { let element = HTMLFormElement::new_inherited(localName, document); Node::reflect_node(@mut element, document, HTMLFormElementBinding::Wrap) } } impl HTMLFormElement { pub fn AcceptCharset(&self) -> DOMString { ~"" } pub fn SetAcceptCharset(&mut self, _accept_charset: DOMString) -> ErrorResult { Ok(()) } pub fn Action(&self) -> DOMString { ~"" } pub fn SetAction(&mut self, _action: DOMString) -> ErrorResult { Ok(()) } pub fn Autocomplete(&self) -> DOMString { ~"" } pub fn SetAutocomplete(&mut self, _autocomplete: DOMString) -> ErrorResult { Ok(()) } pub fn Enctype(&self) -> DOMString { ~"" } pub fn SetEnctype(&mut self, _enctype: DOMString) -> ErrorResult { Ok(()) } pub fn Encoding(&self) -> DOMString { ~"" } pub fn SetEncoding(&mut self, _encoding: DOMString) -> ErrorResult { Ok(()) } pub fn Method(&self) -> DOMString { ~"" } pub fn SetMethod(&mut self, _method: DOMString) -> ErrorResult { Ok(()) } pub fn Name(&self) -> DOMString { ~"" } pub fn SetName(&mut self, _name: DOMString) -> ErrorResult { Ok(()) } pub fn NoValidate(&self) -> bool { false } pub fn SetNoValidate(&mut self, _no_validate: bool) -> ErrorResult { Ok(()) } pub fn Target(&self) -> DOMString
pub fn SetTarget(&mut self, _target: DOMString) -> ErrorResult { Ok(()) } pub fn Elements(&self) -> @mut HTMLCollection { let window = self.htmlelement.element.node.owner_doc().document().window; HTMLCollection::new(window, ~[]) } pub fn Length(&self) -> i32 { 0 } pub fn Submit(&self) -> ErrorResult { Ok(()) } pub fn Reset(&self) { } pub fn CheckValidity(&self) -> bool { false } pub fn IndexedGetter(&self, _index: u32, _found: &mut bool) -> AbstractNode { fail!("Not implemented.") } }
{ ~"" }
identifier_body
mod.rs
use num::{BigUint, Integer, Zero, One}; use rand::{Rng,Rand}; use std::io; use std::ops::{Mul, Rem, Shr}; use std::fs; use std::path::Path; use time; mod int128; mod spotify_id; mod arcvec; mod subfile; mod zerofile; pub use util::int128::u128; pub use util::spotify_id::{SpotifyId, FileId}; pub use util::arcvec::ArcVec; pub use util::subfile::Subfile; pub use util::zerofile::ZeroFile; #[macro_export] macro_rules! eprintln( ($($arg:tt)*) => ( { use std::io::Write; writeln!(&mut ::std::io::stderr(), $($arg)* ).unwrap() } ) ); #[macro_export] macro_rules! eprint( ($($arg:tt)*) => ( { use std::io::Write; write!(&mut ::std::io::stderr(), $($arg)* ).unwrap() } ) ); pub fn rand_vec<G: Rng, R: Rand>(rng: &mut G, size: usize) -> Vec<R> { let mut vec = Vec::with_capacity(size); for _ in 0..size { vec.push(R::rand(rng)); } return vec } pub mod version { include!(concat!(env!("OUT_DIR"), "/version.rs")); pub fn version_string() -> String { format!("librespot-{}", short_sha()) } } pub fn hexdump(data: &[u8]) { for b in data.iter() { eprint!("{:02X} ", b); } eprintln!(""); } pub trait IgnoreExt { fn ignore(self); } impl <T, E> IgnoreExt for Result<T, E> { fn ignore(self)
} pub fn now_ms() -> i64 { let ts = time::now_utc().to_timespec(); ts.sec * 1000 + ts.nsec as i64 / 1000000 } pub fn mkdir_existing(path: &Path) -> io::Result<()> { fs::create_dir(path) .or_else(|err| if err.kind() == io::ErrorKind::AlreadyExists { Ok(()) } else { Err(err) }) } pub fn powm(base: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint { let mut base = base.clone(); let mut exp = exp.clone(); let mut result : BigUint = One::one(); while!exp.is_zero() { if exp.is_odd() { result = result.mul(&base).rem(modulus); } exp = exp.shr(1); base = (&base).mul(&base).rem(modulus); } return result; } pub struct StrChunks<'s>(&'s str, usize); pub trait StrChunksExt { fn chunks<'s>(&'s self, size: usize) -> StrChunks<'s>; } impl StrChunksExt for str { fn chunks<'a>(&'a self, size: usize) -> StrChunks<'a> { StrChunks(self, size) } } impl <'s> Iterator for StrChunks<'s> { type Item = &'s str; fn next(&mut self) -> Option<&'s str> { let &mut StrChunks(data, size) = self; if data.is_empty() { None } else { let ret = Some(&data[..size]); self.0 = &data[size..]; ret } } }
{ match self { Ok(_) => (), Err(_) => (), } }
identifier_body
mod.rs
use num::{BigUint, Integer, Zero, One}; use rand::{Rng,Rand}; use std::io; use std::ops::{Mul, Rem, Shr}; use std::fs; use std::path::Path; use time; mod int128; mod spotify_id; mod arcvec; mod subfile; mod zerofile; pub use util::int128::u128; pub use util::spotify_id::{SpotifyId, FileId}; pub use util::arcvec::ArcVec; pub use util::subfile::Subfile; pub use util::zerofile::ZeroFile; #[macro_export] macro_rules! eprintln( ($($arg:tt)*) => ( { use std::io::Write; writeln!(&mut ::std::io::stderr(), $($arg)* ).unwrap() } ) ); #[macro_export] macro_rules! eprint( ($($arg:tt)*) => ( { use std::io::Write; write!(&mut ::std::io::stderr(), $($arg)* ).unwrap() } ) ); pub fn rand_vec<G: Rng, R: Rand>(rng: &mut G, size: usize) -> Vec<R> { let mut vec = Vec::with_capacity(size); for _ in 0..size { vec.push(R::rand(rng)); }
} pub mod version { include!(concat!(env!("OUT_DIR"), "/version.rs")); pub fn version_string() -> String { format!("librespot-{}", short_sha()) } } pub fn hexdump(data: &[u8]) { for b in data.iter() { eprint!("{:02X} ", b); } eprintln!(""); } pub trait IgnoreExt { fn ignore(self); } impl <T, E> IgnoreExt for Result<T, E> { fn ignore(self) { match self { Ok(_) => (), Err(_) => (), } } } pub fn now_ms() -> i64 { let ts = time::now_utc().to_timespec(); ts.sec * 1000 + ts.nsec as i64 / 1000000 } pub fn mkdir_existing(path: &Path) -> io::Result<()> { fs::create_dir(path) .or_else(|err| if err.kind() == io::ErrorKind::AlreadyExists { Ok(()) } else { Err(err) }) } pub fn powm(base: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint { let mut base = base.clone(); let mut exp = exp.clone(); let mut result : BigUint = One::one(); while!exp.is_zero() { if exp.is_odd() { result = result.mul(&base).rem(modulus); } exp = exp.shr(1); base = (&base).mul(&base).rem(modulus); } return result; } pub struct StrChunks<'s>(&'s str, usize); pub trait StrChunksExt { fn chunks<'s>(&'s self, size: usize) -> StrChunks<'s>; } impl StrChunksExt for str { fn chunks<'a>(&'a self, size: usize) -> StrChunks<'a> { StrChunks(self, size) } } impl <'s> Iterator for StrChunks<'s> { type Item = &'s str; fn next(&mut self) -> Option<&'s str> { let &mut StrChunks(data, size) = self; if data.is_empty() { None } else { let ret = Some(&data[..size]); self.0 = &data[size..]; ret } } }
return vec
random_line_split
mod.rs
use num::{BigUint, Integer, Zero, One}; use rand::{Rng,Rand}; use std::io; use std::ops::{Mul, Rem, Shr}; use std::fs; use std::path::Path; use time; mod int128; mod spotify_id; mod arcvec; mod subfile; mod zerofile; pub use util::int128::u128; pub use util::spotify_id::{SpotifyId, FileId}; pub use util::arcvec::ArcVec; pub use util::subfile::Subfile; pub use util::zerofile::ZeroFile; #[macro_export] macro_rules! eprintln( ($($arg:tt)*) => ( { use std::io::Write; writeln!(&mut ::std::io::stderr(), $($arg)* ).unwrap() } ) ); #[macro_export] macro_rules! eprint( ($($arg:tt)*) => ( { use std::io::Write; write!(&mut ::std::io::stderr(), $($arg)* ).unwrap() } ) ); pub fn rand_vec<G: Rng, R: Rand>(rng: &mut G, size: usize) -> Vec<R> { let mut vec = Vec::with_capacity(size); for _ in 0..size { vec.push(R::rand(rng)); } return vec } pub mod version { include!(concat!(env!("OUT_DIR"), "/version.rs")); pub fn version_string() -> String { format!("librespot-{}", short_sha()) } } pub fn hexdump(data: &[u8]) { for b in data.iter() { eprint!("{:02X} ", b); } eprintln!(""); } pub trait IgnoreExt { fn ignore(self); } impl <T, E> IgnoreExt for Result<T, E> { fn ignore(self) { match self { Ok(_) => (), Err(_) => (), } } } pub fn now_ms() -> i64 { let ts = time::now_utc().to_timespec(); ts.sec * 1000 + ts.nsec as i64 / 1000000 } pub fn mkdir_existing(path: &Path) -> io::Result<()> { fs::create_dir(path) .or_else(|err| if err.kind() == io::ErrorKind::AlreadyExists { Ok(()) } else { Err(err) }) } pub fn powm(base: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint { let mut base = base.clone(); let mut exp = exp.clone(); let mut result : BigUint = One::one(); while!exp.is_zero() { if exp.is_odd() { result = result.mul(&base).rem(modulus); } exp = exp.shr(1); base = (&base).mul(&base).rem(modulus); } return result; } pub struct StrChunks<'s>(&'s str, usize); pub trait StrChunksExt { fn chunks<'s>(&'s self, size: usize) -> StrChunks<'s>; } impl StrChunksExt for str { fn
<'a>(&'a self, size: usize) -> StrChunks<'a> { StrChunks(self, size) } } impl <'s> Iterator for StrChunks<'s> { type Item = &'s str; fn next(&mut self) -> Option<&'s str> { let &mut StrChunks(data, size) = self; if data.is_empty() { None } else { let ret = Some(&data[..size]); self.0 = &data[size..]; ret } } }
chunks
identifier_name
f12-race-condition.rs
/// Figure 8.12 Program with a race condition /// /// Takeaway: on OSX it needed at least usleep(20) in order /// to experience the race condition /// /// $ f12-race-condition | awk 'END{print NR}' /// 2 extern crate libc; extern crate apue; use libc::{c_char, FILE, STDOUT_FILENO, fork, setbuf, fdopen, usleep}; use apue::LibcResult; use apue::my_libc::putc; unsafe fn
(out: *mut FILE, s: &str) { for c in s.chars() { putc(c as i32, out); usleep(20); } } fn main() { unsafe { // set unbuffered let stdout = fdopen(STDOUT_FILENO, &('w' as c_char)); setbuf(stdout, std::ptr::null_mut()); let pid = fork().check_not_negative().expect("fork error"); match pid { 0 => charatatime(stdout, "output from child \n"), _ => charatatime(stdout, "output from parent \n"), } } }
charatatime
identifier_name
f12-race-condition.rs
/// Figure 8.12 Program with a race condition /// /// Takeaway: on OSX it needed at least usleep(20) in order /// to experience the race condition /// /// $ f12-race-condition | awk 'END{print NR}' /// 2 extern crate libc; extern crate apue; use libc::{c_char, FILE, STDOUT_FILENO, fork, setbuf, fdopen, usleep}; use apue::LibcResult; use apue::my_libc::putc; unsafe fn charatatime(out: *mut FILE, s: &str) { for c in s.chars() {
putc(c as i32, out); usleep(20); } } fn main() { unsafe { // set unbuffered let stdout = fdopen(STDOUT_FILENO, &('w' as c_char)); setbuf(stdout, std::ptr::null_mut()); let pid = fork().check_not_negative().expect("fork error"); match pid { 0 => charatatime(stdout, "output from child \n"), _ => charatatime(stdout, "output from parent \n"), } } }
random_line_split
f12-race-condition.rs
/// Figure 8.12 Program with a race condition /// /// Takeaway: on OSX it needed at least usleep(20) in order /// to experience the race condition /// /// $ f12-race-condition | awk 'END{print NR}' /// 2 extern crate libc; extern crate apue; use libc::{c_char, FILE, STDOUT_FILENO, fork, setbuf, fdopen, usleep}; use apue::LibcResult; use apue::my_libc::putc; unsafe fn charatatime(out: *mut FILE, s: &str)
fn main() { unsafe { // set unbuffered let stdout = fdopen(STDOUT_FILENO, &('w' as c_char)); setbuf(stdout, std::ptr::null_mut()); let pid = fork().check_not_negative().expect("fork error"); match pid { 0 => charatatime(stdout, "output from child \n"), _ => charatatime(stdout, "output from parent \n"), } } }
{ for c in s.chars() { putc(c as i32, out); usleep(20); } }
identifier_body
arena.rs
use std::ptr; use crate::gc::Address; use crate::mem; use crate::os::page_size; pub fn reserve(size: usize) -> Address { debug_assert!(mem::is_page_aligned(size)); let ptr = unsafe { libc::mmap( ptr::null_mut(), size, libc::PROT_NONE, libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_NORESERVE, -1, 0, ) as *mut libc::c_void }; if ptr == libc::MAP_FAILED { panic!("reserving memory with mmap() failed"); } Address::from_ptr(ptr) } pub fn reserve_align(size: usize, align: usize) -> Address { debug_assert!(mem::is_page_aligned(size)); debug_assert!(mem::is_page_aligned(align)); let align_minus_page = align - page_size() as usize; let unaligned = reserve(size + align_minus_page); let aligned: Address = mem::align_usize(unaligned.to_usize(), align).into(); let gap_start = aligned.offset_from(unaligned); let gap_end = align_minus_page - gap_start; if gap_start > 0 { uncommit(unaligned, gap_start); } if gap_end > 0 { uncommit(aligned.offset(size), gap_end); } aligned } pub fn commit(ptr: Address, size: usize, executable: bool) { debug_assert!(ptr.is_page_aligned()); debug_assert!(mem::is_page_aligned(size)); let mut prot = libc::PROT_READ | libc::PROT_WRITE; if executable { prot |= libc::PROT_EXEC; } let val = unsafe { libc::mmap( ptr.to_mut_ptr(), size, prot, libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_FIXED, -1, 0, ) }; if val == libc::MAP_FAILED { panic!("committing memory with mmap() failed"); } } pub fn uncommit(ptr: Address, size: usize) { debug_assert!(ptr.is_page_aligned()); debug_assert!(mem::is_page_aligned(size)); let val = unsafe { libc::mmap( ptr.to_mut_ptr(), size, libc::PROT_NONE, libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_NORESERVE, -1, 0, ) }; if val == libc::MAP_FAILED { panic!("uncommitting memory with mmap() failed"); } } pub fn discard(ptr: Address, size: usize) { debug_assert!(ptr.is_page_aligned()); debug_assert!(mem::is_page_aligned(size)); let res = unsafe { libc::madvise(ptr.to_mut_ptr(), size, libc::MADV_DONTNEED) }; if res!= 0 { panic!("discarding memory with madvise() failed"); } let res = unsafe { libc::mprotect(ptr.to_mut_ptr(), size, libc::PROT_NONE) }; if res!= 0
}
{ panic!("discarding memory with mprotect() failed"); }
conditional_block
arena.rs
use std::ptr;
pub fn reserve(size: usize) -> Address { debug_assert!(mem::is_page_aligned(size)); let ptr = unsafe { libc::mmap( ptr::null_mut(), size, libc::PROT_NONE, libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_NORESERVE, -1, 0, ) as *mut libc::c_void }; if ptr == libc::MAP_FAILED { panic!("reserving memory with mmap() failed"); } Address::from_ptr(ptr) } pub fn reserve_align(size: usize, align: usize) -> Address { debug_assert!(mem::is_page_aligned(size)); debug_assert!(mem::is_page_aligned(align)); let align_minus_page = align - page_size() as usize; let unaligned = reserve(size + align_minus_page); let aligned: Address = mem::align_usize(unaligned.to_usize(), align).into(); let gap_start = aligned.offset_from(unaligned); let gap_end = align_minus_page - gap_start; if gap_start > 0 { uncommit(unaligned, gap_start); } if gap_end > 0 { uncommit(aligned.offset(size), gap_end); } aligned } pub fn commit(ptr: Address, size: usize, executable: bool) { debug_assert!(ptr.is_page_aligned()); debug_assert!(mem::is_page_aligned(size)); let mut prot = libc::PROT_READ | libc::PROT_WRITE; if executable { prot |= libc::PROT_EXEC; } let val = unsafe { libc::mmap( ptr.to_mut_ptr(), size, prot, libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_FIXED, -1, 0, ) }; if val == libc::MAP_FAILED { panic!("committing memory with mmap() failed"); } } pub fn uncommit(ptr: Address, size: usize) { debug_assert!(ptr.is_page_aligned()); debug_assert!(mem::is_page_aligned(size)); let val = unsafe { libc::mmap( ptr.to_mut_ptr(), size, libc::PROT_NONE, libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_NORESERVE, -1, 0, ) }; if val == libc::MAP_FAILED { panic!("uncommitting memory with mmap() failed"); } } pub fn discard(ptr: Address, size: usize) { debug_assert!(ptr.is_page_aligned()); debug_assert!(mem::is_page_aligned(size)); let res = unsafe { libc::madvise(ptr.to_mut_ptr(), size, libc::MADV_DONTNEED) }; if res!= 0 { panic!("discarding memory with madvise() failed"); } let res = unsafe { libc::mprotect(ptr.to_mut_ptr(), size, libc::PROT_NONE) }; if res!= 0 { panic!("discarding memory with mprotect() failed"); } }
use crate::gc::Address; use crate::mem; use crate::os::page_size;
random_line_split
arena.rs
use std::ptr; use crate::gc::Address; use crate::mem; use crate::os::page_size; pub fn reserve(size: usize) -> Address { debug_assert!(mem::is_page_aligned(size)); let ptr = unsafe { libc::mmap( ptr::null_mut(), size, libc::PROT_NONE, libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_NORESERVE, -1, 0, ) as *mut libc::c_void }; if ptr == libc::MAP_FAILED { panic!("reserving memory with mmap() failed"); } Address::from_ptr(ptr) } pub fn reserve_align(size: usize, align: usize) -> Address { debug_assert!(mem::is_page_aligned(size)); debug_assert!(mem::is_page_aligned(align)); let align_minus_page = align - page_size() as usize; let unaligned = reserve(size + align_minus_page); let aligned: Address = mem::align_usize(unaligned.to_usize(), align).into(); let gap_start = aligned.offset_from(unaligned); let gap_end = align_minus_page - gap_start; if gap_start > 0 { uncommit(unaligned, gap_start); } if gap_end > 0 { uncommit(aligned.offset(size), gap_end); } aligned } pub fn commit(ptr: Address, size: usize, executable: bool) { debug_assert!(ptr.is_page_aligned()); debug_assert!(mem::is_page_aligned(size)); let mut prot = libc::PROT_READ | libc::PROT_WRITE; if executable { prot |= libc::PROT_EXEC; } let val = unsafe { libc::mmap( ptr.to_mut_ptr(), size, prot, libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_FIXED, -1, 0, ) }; if val == libc::MAP_FAILED { panic!("committing memory with mmap() failed"); } } pub fn uncommit(ptr: Address, size: usize) { debug_assert!(ptr.is_page_aligned()); debug_assert!(mem::is_page_aligned(size)); let val = unsafe { libc::mmap( ptr.to_mut_ptr(), size, libc::PROT_NONE, libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_NORESERVE, -1, 0, ) }; if val == libc::MAP_FAILED { panic!("uncommitting memory with mmap() failed"); } } pub fn
(ptr: Address, size: usize) { debug_assert!(ptr.is_page_aligned()); debug_assert!(mem::is_page_aligned(size)); let res = unsafe { libc::madvise(ptr.to_mut_ptr(), size, libc::MADV_DONTNEED) }; if res!= 0 { panic!("discarding memory with madvise() failed"); } let res = unsafe { libc::mprotect(ptr.to_mut_ptr(), size, libc::PROT_NONE) }; if res!= 0 { panic!("discarding memory with mprotect() failed"); } }
discard
identifier_name
arena.rs
use std::ptr; use crate::gc::Address; use crate::mem; use crate::os::page_size; pub fn reserve(size: usize) -> Address { debug_assert!(mem::is_page_aligned(size)); let ptr = unsafe { libc::mmap( ptr::null_mut(), size, libc::PROT_NONE, libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_NORESERVE, -1, 0, ) as *mut libc::c_void }; if ptr == libc::MAP_FAILED { panic!("reserving memory with mmap() failed"); } Address::from_ptr(ptr) } pub fn reserve_align(size: usize, align: usize) -> Address { debug_assert!(mem::is_page_aligned(size)); debug_assert!(mem::is_page_aligned(align)); let align_minus_page = align - page_size() as usize; let unaligned = reserve(size + align_minus_page); let aligned: Address = mem::align_usize(unaligned.to_usize(), align).into(); let gap_start = aligned.offset_from(unaligned); let gap_end = align_minus_page - gap_start; if gap_start > 0 { uncommit(unaligned, gap_start); } if gap_end > 0 { uncommit(aligned.offset(size), gap_end); } aligned } pub fn commit(ptr: Address, size: usize, executable: bool) { debug_assert!(ptr.is_page_aligned()); debug_assert!(mem::is_page_aligned(size)); let mut prot = libc::PROT_READ | libc::PROT_WRITE; if executable { prot |= libc::PROT_EXEC; } let val = unsafe { libc::mmap( ptr.to_mut_ptr(), size, prot, libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_FIXED, -1, 0, ) }; if val == libc::MAP_FAILED { panic!("committing memory with mmap() failed"); } } pub fn uncommit(ptr: Address, size: usize)
pub fn discard(ptr: Address, size: usize) { debug_assert!(ptr.is_page_aligned()); debug_assert!(mem::is_page_aligned(size)); let res = unsafe { libc::madvise(ptr.to_mut_ptr(), size, libc::MADV_DONTNEED) }; if res!= 0 { panic!("discarding memory with madvise() failed"); } let res = unsafe { libc::mprotect(ptr.to_mut_ptr(), size, libc::PROT_NONE) }; if res!= 0 { panic!("discarding memory with mprotect() failed"); } }
{ debug_assert!(ptr.is_page_aligned()); debug_assert!(mem::is_page_aligned(size)); let val = unsafe { libc::mmap( ptr.to_mut_ptr(), size, libc::PROT_NONE, libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_NORESERVE, -1, 0, ) }; if val == libc::MAP_FAILED { panic!("uncommitting memory with mmap() failed"); } }
identifier_body
mod.rs
// Copyright 2017 Kai Strempel
// // 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. pub mod schema; use super::common::*; use super::Client; use super::error::DockerError; use self::schema::Volumes; endpoint!(VolumesClient); impl<'a> VolumesClient<'a> { pub fn get(&self) -> Result<Volumes, DockerError> { get(self.client, "volumes") } } #[cfg(test)] mod tests { #[test] fn it_works() { use Client; use volumes::VolumesClient; let client = Client::from_env(); let volumes_client = VolumesClient::new(&client); let volumes = volumes_client.get(); assert!(volumes.is_ok()); } }
random_line_split
mod.rs
// Copyright 2017 Kai Strempel // // 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. pub mod schema; use super::common::*; use super::Client; use super::error::DockerError; use self::schema::Volumes; endpoint!(VolumesClient); impl<'a> VolumesClient<'a> { pub fn get(&self) -> Result<Volumes, DockerError> { get(self.client, "volumes") } } #[cfg(test)] mod tests { #[test] fn
() { use Client; use volumes::VolumesClient; let client = Client::from_env(); let volumes_client = VolumesClient::new(&client); let volumes = volumes_client.get(); assert!(volumes.is_ok()); } }
it_works
identifier_name
mod.rs
// Copyright 2017 Kai Strempel // // 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. pub mod schema; use super::common::*; use super::Client; use super::error::DockerError; use self::schema::Volumes; endpoint!(VolumesClient); impl<'a> VolumesClient<'a> { pub fn get(&self) -> Result<Volumes, DockerError>
} #[cfg(test)] mod tests { #[test] fn it_works() { use Client; use volumes::VolumesClient; let client = Client::from_env(); let volumes_client = VolumesClient::new(&client); let volumes = volumes_client.get(); assert!(volumes.is_ok()); } }
{ get(self.client, "volumes") }
identifier_body
lib.rs
//! Atomic counting semaphore that can help you control access to a common resource //! by multiple processes in a concurrent system. //! //! ## Features //! //! - Effectively lock-free* semantics //! - Provides RAII-style acquire/release API //! - Implements `Send`, `Sync` and `Clone` //! //! _* lock-free when not using the `shutdown` API_ extern crate parking_lot; use std::sync::Arc; use parking_lot::RwLock; mod raw; use raw::RawSemaphore; mod guard; pub use guard::SemaphoreGuard; mod shutdown; pub use shutdown::ShutdownHandle; #[cfg(test)] mod tests; /// Result returned from `Semaphore::try_access`. pub type TryAccessResult<T> = Result<SemaphoreGuard<T>, TryAccessError>; #[derive(Copy, Clone, Debug, PartialEq)] /// Error indicating a failure to acquire access to the resource /// behind the semaphore. /// /// Returned from `Semaphore::try_access`. pub enum TryAccessError { /// This semaphore has shut down and will no longer grant access to the underlying resource. Shutdown, /// This semaphore has no more capacity to grant further access. /// Other access needs to be released before this semaphore can grant more. NoCapacity } /// Counting semaphore to control concurrent access to a common resource. pub struct Semaphore<T> { raw: Arc<RawSemaphore>, resource: Arc<RwLock<Option<Arc<T>>>> } impl<T> Clone for Semaphore<T> { fn clone(&self) -> Semaphore<T> { Semaphore { raw: self.raw.clone(), resource: self.resource.clone() } } } impl<T> Semaphore<T> { /// Create a new semaphore around a resource. /// /// The semaphore will limit the number of processes that can access /// the underlying resource at every point in time to the specified capacity. pub fn new(capacity: usize, resource: T) -> Self { Semaphore { raw: Arc::new(RawSemaphore::new(capacity)), resource: Arc::new(RwLock::new(Some(Arc::new(resource)))) } } #[inline] /// Attempt to access the underlying resource of this semaphore. /// /// This function will try to acquire access, and then return an RAII /// guard structure which will release the access when it falls out of scope. /// If the semaphore is out of capacity or shut down, a `TryAccessError` will be returned. pub fn try_access(&self) -> TryAccessResult<T> { if let Some(ref resource) = *self.resource.read() { if self.raw.try_acquire() { Ok(guard::new(&self.raw, resource)) } else
} else { Err(TryAccessError::Shutdown) } } /// Shut down the semaphore. /// /// This prevents any further access from being granted to the underlying resource. /// As soon as the last access is released and the returned handle goes out of scope, /// the resource will be dropped. /// /// Does _not_ block until the resource is no longer in use. If you would like to do that, /// you can call `wait` on the returned handle. pub fn shutdown(&self) -> ShutdownHandle<T> { shutdown::new(&self.raw, self.resource.write().take()) } }
{ Err(TryAccessError::NoCapacity) }
conditional_block
lib.rs
//! Atomic counting semaphore that can help you control access to a common resource //! by multiple processes in a concurrent system. //! //! ## Features //! //! - Effectively lock-free* semantics //! - Provides RAII-style acquire/release API //! - Implements `Send`, `Sync` and `Clone` //! //! _* lock-free when not using the `shutdown` API_ extern crate parking_lot; use std::sync::Arc;
use parking_lot::RwLock; mod raw; use raw::RawSemaphore; mod guard; pub use guard::SemaphoreGuard; mod shutdown; pub use shutdown::ShutdownHandle; #[cfg(test)] mod tests; /// Result returned from `Semaphore::try_access`. pub type TryAccessResult<T> = Result<SemaphoreGuard<T>, TryAccessError>; #[derive(Copy, Clone, Debug, PartialEq)] /// Error indicating a failure to acquire access to the resource /// behind the semaphore. /// /// Returned from `Semaphore::try_access`. pub enum TryAccessError { /// This semaphore has shut down and will no longer grant access to the underlying resource. Shutdown, /// This semaphore has no more capacity to grant further access. /// Other access needs to be released before this semaphore can grant more. NoCapacity } /// Counting semaphore to control concurrent access to a common resource. pub struct Semaphore<T> { raw: Arc<RawSemaphore>, resource: Arc<RwLock<Option<Arc<T>>>> } impl<T> Clone for Semaphore<T> { fn clone(&self) -> Semaphore<T> { Semaphore { raw: self.raw.clone(), resource: self.resource.clone() } } } impl<T> Semaphore<T> { /// Create a new semaphore around a resource. /// /// The semaphore will limit the number of processes that can access /// the underlying resource at every point in time to the specified capacity. pub fn new(capacity: usize, resource: T) -> Self { Semaphore { raw: Arc::new(RawSemaphore::new(capacity)), resource: Arc::new(RwLock::new(Some(Arc::new(resource)))) } } #[inline] /// Attempt to access the underlying resource of this semaphore. /// /// This function will try to acquire access, and then return an RAII /// guard structure which will release the access when it falls out of scope. /// If the semaphore is out of capacity or shut down, a `TryAccessError` will be returned. pub fn try_access(&self) -> TryAccessResult<T> { if let Some(ref resource) = *self.resource.read() { if self.raw.try_acquire() { Ok(guard::new(&self.raw, resource)) } else { Err(TryAccessError::NoCapacity) } } else { Err(TryAccessError::Shutdown) } } /// Shut down the semaphore. /// /// This prevents any further access from being granted to the underlying resource. /// As soon as the last access is released and the returned handle goes out of scope, /// the resource will be dropped. /// /// Does _not_ block until the resource is no longer in use. If you would like to do that, /// you can call `wait` on the returned handle. pub fn shutdown(&self) -> ShutdownHandle<T> { shutdown::new(&self.raw, self.resource.write().take()) } }
random_line_split
lib.rs
//! Atomic counting semaphore that can help you control access to a common resource //! by multiple processes in a concurrent system. //! //! ## Features //! //! - Effectively lock-free* semantics //! - Provides RAII-style acquire/release API //! - Implements `Send`, `Sync` and `Clone` //! //! _* lock-free when not using the `shutdown` API_ extern crate parking_lot; use std::sync::Arc; use parking_lot::RwLock; mod raw; use raw::RawSemaphore; mod guard; pub use guard::SemaphoreGuard; mod shutdown; pub use shutdown::ShutdownHandle; #[cfg(test)] mod tests; /// Result returned from `Semaphore::try_access`. pub type TryAccessResult<T> = Result<SemaphoreGuard<T>, TryAccessError>; #[derive(Copy, Clone, Debug, PartialEq)] /// Error indicating a failure to acquire access to the resource /// behind the semaphore. /// /// Returned from `Semaphore::try_access`. pub enum TryAccessError { /// This semaphore has shut down and will no longer grant access to the underlying resource. Shutdown, /// This semaphore has no more capacity to grant further access. /// Other access needs to be released before this semaphore can grant more. NoCapacity } /// Counting semaphore to control concurrent access to a common resource. pub struct Semaphore<T> { raw: Arc<RawSemaphore>, resource: Arc<RwLock<Option<Arc<T>>>> } impl<T> Clone for Semaphore<T> { fn clone(&self) -> Semaphore<T> { Semaphore { raw: self.raw.clone(), resource: self.resource.clone() } } } impl<T> Semaphore<T> { /// Create a new semaphore around a resource. /// /// The semaphore will limit the number of processes that can access /// the underlying resource at every point in time to the specified capacity. pub fn new(capacity: usize, resource: T) -> Self
#[inline] /// Attempt to access the underlying resource of this semaphore. /// /// This function will try to acquire access, and then return an RAII /// guard structure which will release the access when it falls out of scope. /// If the semaphore is out of capacity or shut down, a `TryAccessError` will be returned. pub fn try_access(&self) -> TryAccessResult<T> { if let Some(ref resource) = *self.resource.read() { if self.raw.try_acquire() { Ok(guard::new(&self.raw, resource)) } else { Err(TryAccessError::NoCapacity) } } else { Err(TryAccessError::Shutdown) } } /// Shut down the semaphore. /// /// This prevents any further access from being granted to the underlying resource. /// As soon as the last access is released and the returned handle goes out of scope, /// the resource will be dropped. /// /// Does _not_ block until the resource is no longer in use. If you would like to do that, /// you can call `wait` on the returned handle. pub fn shutdown(&self) -> ShutdownHandle<T> { shutdown::new(&self.raw, self.resource.write().take()) } }
{ Semaphore { raw: Arc::new(RawSemaphore::new(capacity)), resource: Arc::new(RwLock::new(Some(Arc::new(resource)))) } }
identifier_body
lib.rs
//! Atomic counting semaphore that can help you control access to a common resource //! by multiple processes in a concurrent system. //! //! ## Features //! //! - Effectively lock-free* semantics //! - Provides RAII-style acquire/release API //! - Implements `Send`, `Sync` and `Clone` //! //! _* lock-free when not using the `shutdown` API_ extern crate parking_lot; use std::sync::Arc; use parking_lot::RwLock; mod raw; use raw::RawSemaphore; mod guard; pub use guard::SemaphoreGuard; mod shutdown; pub use shutdown::ShutdownHandle; #[cfg(test)] mod tests; /// Result returned from `Semaphore::try_access`. pub type TryAccessResult<T> = Result<SemaphoreGuard<T>, TryAccessError>; #[derive(Copy, Clone, Debug, PartialEq)] /// Error indicating a failure to acquire access to the resource /// behind the semaphore. /// /// Returned from `Semaphore::try_access`. pub enum TryAccessError { /// This semaphore has shut down and will no longer grant access to the underlying resource. Shutdown, /// This semaphore has no more capacity to grant further access. /// Other access needs to be released before this semaphore can grant more. NoCapacity } /// Counting semaphore to control concurrent access to a common resource. pub struct Semaphore<T> { raw: Arc<RawSemaphore>, resource: Arc<RwLock<Option<Arc<T>>>> } impl<T> Clone for Semaphore<T> { fn clone(&self) -> Semaphore<T> { Semaphore { raw: self.raw.clone(), resource: self.resource.clone() } } } impl<T> Semaphore<T> { /// Create a new semaphore around a resource. /// /// The semaphore will limit the number of processes that can access /// the underlying resource at every point in time to the specified capacity. pub fn new(capacity: usize, resource: T) -> Self { Semaphore { raw: Arc::new(RawSemaphore::new(capacity)), resource: Arc::new(RwLock::new(Some(Arc::new(resource)))) } } #[inline] /// Attempt to access the underlying resource of this semaphore. /// /// This function will try to acquire access, and then return an RAII /// guard structure which will release the access when it falls out of scope. /// If the semaphore is out of capacity or shut down, a `TryAccessError` will be returned. pub fn try_access(&self) -> TryAccessResult<T> { if let Some(ref resource) = *self.resource.read() { if self.raw.try_acquire() { Ok(guard::new(&self.raw, resource)) } else { Err(TryAccessError::NoCapacity) } } else { Err(TryAccessError::Shutdown) } } /// Shut down the semaphore. /// /// This prevents any further access from being granted to the underlying resource. /// As soon as the last access is released and the returned handle goes out of scope, /// the resource will be dropped. /// /// Does _not_ block until the resource is no longer in use. If you would like to do that, /// you can call `wait` on the returned handle. pub fn
(&self) -> ShutdownHandle<T> { shutdown::new(&self.raw, self.resource.write().take()) } }
shutdown
identifier_name
animation.rs
// Copyright 2018 Google LLC // // 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 map_model::Pt2D; use std::time::Instant; #[derive(PartialEq)] pub enum
{ Animation, InputOnly, } impl EventLoopMode { pub fn merge(self, other: EventLoopMode) -> EventLoopMode { match self { EventLoopMode::Animation => EventLoopMode::Animation, _ => other, } } } #[derive(Clone)] pub struct TimeLerp { started_at: Instant, dur_s: f64, } impl TimeLerp { pub fn with_dur_s(dur_s: f64) -> TimeLerp { TimeLerp { dur_s, started_at: Instant::now(), } } fn elapsed(&self) -> f64 { let dt = self.started_at.elapsed(); dt.as_secs() as f64 + f64::from(dt.subsec_nanos()) * 1e-9 } // Returns [0.0, 1.0] pub fn interpolate(&self) -> f64 { (self.elapsed() / self.dur_s).min(1.0) } pub fn is_done(&self) -> bool { self.interpolate() == 1.0 } } pub struct LineLerp { pub from: Pt2D, pub to: Pt2D, pub lerp: TimeLerp, // could have other types of interpolation later } impl LineLerp { pub fn get_pt(&self) -> Pt2D { let x1 = self.from.x(); let y1 = self.from.y(); let x2 = self.to.x(); let y2 = self.to.y(); let i = self.lerp.interpolate(); Pt2D::new(x1 + i * (x2 - x1), y1 + i * (y2 - y1)) } }
EventLoopMode
identifier_name
animation.rs
// Copyright 2018 Google LLC // // 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 map_model::Pt2D; use std::time::Instant; #[derive(PartialEq)] pub enum EventLoopMode { Animation, InputOnly, } impl EventLoopMode { pub fn merge(self, other: EventLoopMode) -> EventLoopMode { match self { EventLoopMode::Animation => EventLoopMode::Animation, _ => other, } } } #[derive(Clone)] pub struct TimeLerp { started_at: Instant, dur_s: f64, } impl TimeLerp { pub fn with_dur_s(dur_s: f64) -> TimeLerp { TimeLerp { dur_s, started_at: Instant::now(), } } fn elapsed(&self) -> f64 { let dt = self.started_at.elapsed(); dt.as_secs() as f64 + f64::from(dt.subsec_nanos()) * 1e-9 } // Returns [0.0, 1.0] pub fn interpolate(&self) -> f64 { (self.elapsed() / self.dur_s).min(1.0) } pub fn is_done(&self) -> bool { self.interpolate() == 1.0 } } pub struct LineLerp { pub from: Pt2D, pub to: Pt2D, pub lerp: TimeLerp, // could have other types of interpolation later } impl LineLerp { pub fn get_pt(&self) -> Pt2D { let x1 = self.from.x(); let y1 = self.from.y(); let x2 = self.to.x(); let y2 = self.to.y(); let i = self.lerp.interpolate(); Pt2D::new(x1 + i * (x2 - x1), y1 + i * (y2 - y1)) } }
random_line_split
animation.rs
// Copyright 2018 Google LLC // // 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 map_model::Pt2D; use std::time::Instant; #[derive(PartialEq)] pub enum EventLoopMode { Animation, InputOnly, } impl EventLoopMode { pub fn merge(self, other: EventLoopMode) -> EventLoopMode
} #[derive(Clone)] pub struct TimeLerp { started_at: Instant, dur_s: f64, } impl TimeLerp { pub fn with_dur_s(dur_s: f64) -> TimeLerp { TimeLerp { dur_s, started_at: Instant::now(), } } fn elapsed(&self) -> f64 { let dt = self.started_at.elapsed(); dt.as_secs() as f64 + f64::from(dt.subsec_nanos()) * 1e-9 } // Returns [0.0, 1.0] pub fn interpolate(&self) -> f64 { (self.elapsed() / self.dur_s).min(1.0) } pub fn is_done(&self) -> bool { self.interpolate() == 1.0 } } pub struct LineLerp { pub from: Pt2D, pub to: Pt2D, pub lerp: TimeLerp, // could have other types of interpolation later } impl LineLerp { pub fn get_pt(&self) -> Pt2D { let x1 = self.from.x(); let y1 = self.from.y(); let x2 = self.to.x(); let y2 = self.to.y(); let i = self.lerp.interpolate(); Pt2D::new(x1 + i * (x2 - x1), y1 + i * (y2 - y1)) } }
{ match self { EventLoopMode::Animation => EventLoopMode::Animation, _ => other, } }
identifier_body
comment.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CommentBinding; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::characterdata::CharacterData; use crate::dom::document::Document; use crate::dom::node::Node; use crate::dom::window::Window; use dom_struct::dom_struct; /// An HTML comment. #[dom_struct] pub struct Comment { characterdata: CharacterData, } impl Comment { fn new_inherited(text: DOMString, document: &Document) -> Comment { Comment { characterdata: CharacterData::new_inherited(text, document), } } pub fn new(text: DOMString, document: &Document) -> DomRoot<Comment> { Node::reflect_node( Box::new(Comment::new_inherited(text, document)), document, CommentBinding::Wrap, ) } #[allow(non_snake_case)] pub fn
(window: &Window, data: DOMString) -> Fallible<DomRoot<Comment>> { let document = window.Document(); Ok(Comment::new(data, &document)) } }
Constructor
identifier_name
comment.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CommentBinding;
use crate::dom::characterdata::CharacterData; use crate::dom::document::Document; use crate::dom::node::Node; use crate::dom::window::Window; use dom_struct::dom_struct; /// An HTML comment. #[dom_struct] pub struct Comment { characterdata: CharacterData, } impl Comment { fn new_inherited(text: DOMString, document: &Document) -> Comment { Comment { characterdata: CharacterData::new_inherited(text, document), } } pub fn new(text: DOMString, document: &Document) -> DomRoot<Comment> { Node::reflect_node( Box::new(Comment::new_inherited(text, document)), document, CommentBinding::Wrap, ) } #[allow(non_snake_case)] pub fn Constructor(window: &Window, data: DOMString) -> Fallible<DomRoot<Comment>> { let document = window.Document(); Ok(Comment::new(data, &document)) } }
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString;
random_line_split
compress.rs
extern crate byteorder; extern crate crc; use std::io; use std::io::{BufWriter, ErrorKind, Write, Seek, SeekFrom, Result, Error}; use self::byteorder::{ByteOrder, WriteBytesExt, LittleEndian}; use self::crc::{crc32, Hasher32}; use definitions::*; // We limit how far copy back-references can go, the same as the C++ code. const MAX_OFFSET: usize = 1 << 15; // The Max Encoded Length of the Max Chunk of 65536 bytes const MAX_BUFFER_SIZE: usize = 76_490; pub struct Compressor<W: Write> { inner: BufWriter<W>, pos: u64, buf_body: [u8; MAX_BUFFER_SIZE], buf_header: [u8; (CHECK_SUM_SIZE + CHUNK_HEADER_SIZE) as usize], wrote_header: bool, } impl <W: Write> Compressor<W> { pub fn new(inner: W) -> Compressor<W> { Compressor { inner: BufWriter::new(inner), pos: 0, buf_body: [0; MAX_BUFFER_SIZE], buf_header: [0; (CHECK_SUM_SIZE + CHUNK_HEADER_SIZE) as usize], wrote_header: false, } } } impl <W: Write> Write for Compressor<W> { // Implement Write // Source Buffer -> Destination (Inner) Buffer fn write(&mut self, src: &[u8]) -> Result<usize> { let mut written: usize = 0; if!self.wrote_header { // Write Stream Literal try!(self.inner.write(&MAGIC_CHUNK)); self.wrote_header = true; } // Split source into chunks of 65536 bytes each. for src_chunk in src.chunks(MAX_UNCOMPRESSED_CHUNK_LEN as usize) { // TODO // Handle Written Slice Length (Ignore Previous Garbage) let chunk_body: &[u8]; let chunk_type: u8; // Create Checksum let checksum: u32 = crc32::checksum_ieee(src_chunk); // Compress the buffer, discarding the result if the improvement // isn't at least 12.5%. let n = try!(compress(&mut self.buf_body, src_chunk)); if n >= src_chunk.len() * (7 / 8) { chunk_type = CHUNK_TYPE_UNCOMPRESSED_DATA; chunk_body = src_chunk; } else { chunk_type = CHUNK_TYPE_COMPRESSED_DATA; chunk_body = self.buf_body.split_at(n).0; } let chunk_len = chunk_body.len() + 4; // Write Chunk Type self.buf_header[0] = chunk_type; // Write Chunk Length self.buf_header[1] = (chunk_len >> 0) as u8; self.buf_header[2] = (chunk_len >> 8) as u8; self.buf_header[3] = (chunk_len >> 16) as u8; // Write Chunk Checksum self.buf_header[4] = (checksum >> 0) as u8; self.buf_header[5] = (checksum >> 8) as u8; self.buf_header[6] = (checksum >> 16) as u8; self.buf_header[7] = (checksum >> 24) as u8; // Write Chunk Header and Handle Error try!(self.inner.write_all(&self.buf_header)); // Write Chunk Body and Handle Error try!(self.inner.write_all(chunk_body)); // If all goes well, count written length as uncompressed length written += src_chunk.len(); } Ok(written) } // Flushes Inner buffer and resets Compressor fn flush(&mut self) -> Result<()> { self.inner.flush() } } // If Compressor is Given a Cursor or Seekable Writer // This Gives the BufWriter the seek method impl <W: Write + Seek> Seek for Compressor<W> { fn seek(&mut self, pos: SeekFrom) -> Result<u64> { self.inner.seek(pos).and_then(|res: u64| { self.pos = res; Ok(res) }) } } // Compress writes the encoded form of src into dst and return the length // written. // Returns an error if dst was not large enough to hold the entire encoded // block. // (Future) Include a Legacy Compress?? pub fn compress(dst: &mut [u8], src: &[u8]) -> io::Result<usize> { if dst.len() < max_compressed_len(src.len()) { return Err(Error::new(ErrorKind::InvalidInput, "snappy: destination buffer is too short")); } // Start Block with varint-encoded length of decompressed bytes LittleEndian::write_u64(dst, src.len() as u64); let mut d: usize = 4; // Return early if src is short if src.len() <= 4 { if src.len()!= 0 { // TODO Handle Error d += emit_literal(dst.split_at_mut(d).1, src).unwrap(); } return Ok(d); } // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive. const MAX_TABLE_SIZE: usize = 1 << 14; let mut shift: u32 = 24; let mut table_size: usize = 1 << 8; while table_size < MAX_TABLE_SIZE && table_size < src.len() { shift -= 1; table_size *= 2; } // Create table let mut table: Vec<i32> = vec![0; MAX_TABLE_SIZE]; // Iterate over the source bytes let mut s: usize = 0; let mut t: i32; let mut lit: usize = 0; // (Future) Iterate in chunks of 4? while s + 3 < src.len() { // Grab 4 bytes let b: (u8, u8, u8, u8) = (src[s], src[s + 1], src[s + 2], src[s + 3]); // Create u32 for Hashing let h: u32 = (b.0 as u32) | ((b.1 as u32) << 8) | ((b.2 as u32) << 16) | ((b.3 as u32) << 24); // Update the hash table let ref mut p: i32 = table[(h.wrapping_mul(0x1e35a7bd) >> shift) as usize]; // We need to to store values in [-1, inf) in table. To save // some initialization time, (re)use the table's zero value // and shift the values against this zero: add 1 on writes, // subtract 1 on reads. // If Hash Exists t = 0; if not t = -1; t = *p - 1; // Set Position of new Hash -> i32 *p = (s + 1) as i32; // If t is invalid or src[s:s+4] differs from src[t:t+4], accumulate a literal // byte. if t < 0 || s.wrapping_sub(t as usize) >= MAX_OFFSET || b.0!= src[t as usize] || b.1!= src[(t + 1) as usize] || b.2!= src[(t + 2) as usize] || b.3!= src[(t + 3) as usize] { s += 1; continue; } // Otherwise, we have a match. First, emit any pending literal bytes. // Panics on d > dst.len(); if lit!= s { d += try!(emit_literal(dst.split_at_mut(d).1, // Handle Split_at mid < src check { if src.len() > s { src.split_at(s).0.split_at(lit).1 } else { src.split_at(lit).1 } })); } // Extend the match to be as long as possible let s0 = s; s += 4; t += 4; while s < src.len() && src[s] == src[t as usize] { s += 1; t += 1; } // Emit the copied bytes. d += emit_copy(dst.split_at_mut(d).1, s.wrapping_sub(t as usize), s - s0); lit = s; } // Emit any final pending literal bytes and return. if lit!= src.len() { d += emit_literal(dst.split_at_mut(d).1, src.split_at(lit).1).unwrap(); } Ok(d) } // emitLiteral writes a literal chunk and returns the number of bytes written. fn emit_literal(dst: &mut [u8], lit: &[u8]) -> io::Result<usize> { let i: usize; let n: u64 = (lit.len() - 1) as u64; if n < 60 { dst[0] = (n as u8) << 2 | TAG_LITERAL; i = 1; } else if n < 1 << 8 { dst[0] = 60 << 2 | TAG_LITERAL; dst[1] = n as u8; i = 2; } else if n < 1 << 16 { dst[0] = 61 << 2 | TAG_LITERAL; dst[1] = n as u8; dst[2] = (n >> 8) as u8; i = 3; } else if n < 1 << 24 { dst[0] = 62 << 2 | TAG_LITERAL; dst[1] = n as u8; dst[2] = (n >> 8) as u8; dst[3] = (n >> 16) as u8; i = 4; } else if n < 1 << 32 { dst[0] = 63 << 2 | TAG_LITERAL; dst[1] = n as u8; dst[2] = (n >> 8) as u8; dst[3] = (n >> 16) as u8; dst[4] = (n >> 24) as u8; i = 5; } else { return Err(Error::new(ErrorKind::InvalidInput, "snappy: source buffer is too long")); } let mut s = 0; for (d, l) in dst.split_at_mut(i).1.iter_mut().zip(lit.iter()) { *d = *l; s += 1; } if s == lit.len() { Ok(i + lit.len()) } else { return Err(Error::new(ErrorKind::InvalidInput, "snappy: destination buffer is too short")); } } // emitCopy writes a copy chunk and returns the number of bytes written. fn emit_copy(dst: &mut [u8], offset: usize, mut length: usize) -> usize { let mut i: usize = 0; while length > 0 { // TODO: Handle Overflow let mut x = length - 4; if 0 <= x && x < 1 << 3 && offset < 1 << 11
x = length; if x > 1 << 6 { x = 1 << 6; } dst[i] = ((x as u8) - 1) << 2 | TAG_COPY_2; dst[i + 1] = offset as u8; dst[i + 2] = (offset >> 8) as u8; i += 3; length -= x; } // (Future) Return a `Result<usize>` Instead?? i } // max_compressed_len returns the maximum length of a snappy block, given its // uncompressed length. pub fn max_compressed_len(src_len: usize) -> usize { 32 + src_len + src_len / 6 }
{ dst[i] = ((offset >> 8) as u8) & 0x07 << 5 | (x as u8) << 2 | TAG_COPY_1; dst[i + 1] = offset as u8; i += 2; break; }
conditional_block
compress.rs
extern crate byteorder; extern crate crc; use std::io; use std::io::{BufWriter, ErrorKind, Write, Seek, SeekFrom, Result, Error}; use self::byteorder::{ByteOrder, WriteBytesExt, LittleEndian}; use self::crc::{crc32, Hasher32}; use definitions::*; // We limit how far copy back-references can go, the same as the C++ code. const MAX_OFFSET: usize = 1 << 15; // The Max Encoded Length of the Max Chunk of 65536 bytes const MAX_BUFFER_SIZE: usize = 76_490; pub struct Compressor<W: Write> { inner: BufWriter<W>, pos: u64, buf_body: [u8; MAX_BUFFER_SIZE], buf_header: [u8; (CHECK_SUM_SIZE + CHUNK_HEADER_SIZE) as usize], wrote_header: bool, } impl <W: Write> Compressor<W> { pub fn new(inner: W) -> Compressor<W> { Compressor { inner: BufWriter::new(inner), pos: 0, buf_body: [0; MAX_BUFFER_SIZE], buf_header: [0; (CHECK_SUM_SIZE + CHUNK_HEADER_SIZE) as usize], wrote_header: false, } } } impl <W: Write> Write for Compressor<W> { // Implement Write // Source Buffer -> Destination (Inner) Buffer fn write(&mut self, src: &[u8]) -> Result<usize> { let mut written: usize = 0; if!self.wrote_header { // Write Stream Literal try!(self.inner.write(&MAGIC_CHUNK)); self.wrote_header = true; } // Split source into chunks of 65536 bytes each. for src_chunk in src.chunks(MAX_UNCOMPRESSED_CHUNK_LEN as usize) { // TODO // Handle Written Slice Length (Ignore Previous Garbage) let chunk_body: &[u8]; let chunk_type: u8; // Create Checksum let checksum: u32 = crc32::checksum_ieee(src_chunk); // Compress the buffer, discarding the result if the improvement // isn't at least 12.5%. let n = try!(compress(&mut self.buf_body, src_chunk)); if n >= src_chunk.len() * (7 / 8) { chunk_type = CHUNK_TYPE_UNCOMPRESSED_DATA; chunk_body = src_chunk; } else { chunk_type = CHUNK_TYPE_COMPRESSED_DATA; chunk_body = self.buf_body.split_at(n).0; } let chunk_len = chunk_body.len() + 4; // Write Chunk Type self.buf_header[0] = chunk_type; // Write Chunk Length self.buf_header[1] = (chunk_len >> 0) as u8; self.buf_header[2] = (chunk_len >> 8) as u8; self.buf_header[3] = (chunk_len >> 16) as u8; // Write Chunk Checksum self.buf_header[4] = (checksum >> 0) as u8; self.buf_header[5] = (checksum >> 8) as u8; self.buf_header[6] = (checksum >> 16) as u8; self.buf_header[7] = (checksum >> 24) as u8; // Write Chunk Header and Handle Error try!(self.inner.write_all(&self.buf_header)); // Write Chunk Body and Handle Error try!(self.inner.write_all(chunk_body)); // If all goes well, count written length as uncompressed length written += src_chunk.len(); } Ok(written) } // Flushes Inner buffer and resets Compressor fn flush(&mut self) -> Result<()> { self.inner.flush() } } // If Compressor is Given a Cursor or Seekable Writer // This Gives the BufWriter the seek method impl <W: Write + Seek> Seek for Compressor<W> { fn seek(&mut self, pos: SeekFrom) -> Result<u64> { self.inner.seek(pos).and_then(|res: u64| { self.pos = res; Ok(res) }) } } // Compress writes the encoded form of src into dst and return the length // written. // Returns an error if dst was not large enough to hold the entire encoded // block. // (Future) Include a Legacy Compress?? pub fn compress(dst: &mut [u8], src: &[u8]) -> io::Result<usize> { if dst.len() < max_compressed_len(src.len()) { return Err(Error::new(ErrorKind::InvalidInput, "snappy: destination buffer is too short")); } // Start Block with varint-encoded length of decompressed bytes LittleEndian::write_u64(dst, src.len() as u64); let mut d: usize = 4; // Return early if src is short if src.len() <= 4 { if src.len()!= 0 { // TODO Handle Error d += emit_literal(dst.split_at_mut(d).1, src).unwrap(); } return Ok(d); } // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive. const MAX_TABLE_SIZE: usize = 1 << 14; let mut shift: u32 = 24; let mut table_size: usize = 1 << 8; while table_size < MAX_TABLE_SIZE && table_size < src.len() { shift -= 1; table_size *= 2; } // Create table let mut table: Vec<i32> = vec![0; MAX_TABLE_SIZE]; // Iterate over the source bytes let mut s: usize = 0; let mut t: i32; let mut lit: usize = 0; // (Future) Iterate in chunks of 4? while s + 3 < src.len() { // Grab 4 bytes let b: (u8, u8, u8, u8) = (src[s], src[s + 1], src[s + 2], src[s + 3]); // Create u32 for Hashing let h: u32 = (b.0 as u32) | ((b.1 as u32) << 8) | ((b.2 as u32) << 16) | ((b.3 as u32) << 24); // Update the hash table let ref mut p: i32 = table[(h.wrapping_mul(0x1e35a7bd) >> shift) as usize]; // We need to to store values in [-1, inf) in table. To save // some initialization time, (re)use the table's zero value // and shift the values against this zero: add 1 on writes, // subtract 1 on reads. // If Hash Exists t = 0; if not t = -1; t = *p - 1; // Set Position of new Hash -> i32 *p = (s + 1) as i32; // If t is invalid or src[s:s+4] differs from src[t:t+4], accumulate a literal // byte. if t < 0 || s.wrapping_sub(t as usize) >= MAX_OFFSET || b.0!= src[t as usize] || b.1!= src[(t + 1) as usize] || b.2!= src[(t + 2) as usize] || b.3!= src[(t + 3) as usize] { s += 1; continue; } // Otherwise, we have a match. First, emit any pending literal bytes. // Panics on d > dst.len(); if lit!= s { d += try!(emit_literal(dst.split_at_mut(d).1, // Handle Split_at mid < src check { if src.len() > s { src.split_at(s).0.split_at(lit).1 } else { src.split_at(lit).1 } })); } // Extend the match to be as long as possible let s0 = s; s += 4; t += 4; while s < src.len() && src[s] == src[t as usize] { s += 1; t += 1; } // Emit the copied bytes. d += emit_copy(dst.split_at_mut(d).1, s.wrapping_sub(t as usize), s - s0); lit = s; } // Emit any final pending literal bytes and return. if lit!= src.len() { d += emit_literal(dst.split_at_mut(d).1, src.split_at(lit).1).unwrap(); } Ok(d) } // emitLiteral writes a literal chunk and returns the number of bytes written. fn emit_literal(dst: &mut [u8], lit: &[u8]) -> io::Result<usize> { let i: usize; let n: u64 = (lit.len() - 1) as u64; if n < 60 { dst[0] = (n as u8) << 2 | TAG_LITERAL; i = 1; } else if n < 1 << 8 { dst[0] = 60 << 2 | TAG_LITERAL; dst[1] = n as u8; i = 2; } else if n < 1 << 16 { dst[0] = 61 << 2 | TAG_LITERAL; dst[1] = n as u8; dst[2] = (n >> 8) as u8; i = 3; } else if n < 1 << 24 { dst[0] = 62 << 2 | TAG_LITERAL; dst[1] = n as u8; dst[2] = (n >> 8) as u8; dst[3] = (n >> 16) as u8; i = 4; } else if n < 1 << 32 { dst[0] = 63 << 2 | TAG_LITERAL; dst[1] = n as u8; dst[2] = (n >> 8) as u8; dst[3] = (n >> 16) as u8; dst[4] = (n >> 24) as u8; i = 5; } else { return Err(Error::new(ErrorKind::InvalidInput, "snappy: source buffer is too long")); } let mut s = 0; for (d, l) in dst.split_at_mut(i).1.iter_mut().zip(lit.iter()) { *d = *l; s += 1; } if s == lit.len() { Ok(i + lit.len()) } else { return Err(Error::new(ErrorKind::InvalidInput, "snappy: destination buffer is too short")); } } // emitCopy writes a copy chunk and returns the number of bytes written. fn emit_copy(dst: &mut [u8], offset: usize, mut length: usize) -> usize { let mut i: usize = 0;
while length > 0 { // TODO: Handle Overflow let mut x = length - 4; if 0 <= x && x < 1 << 3 && offset < 1 << 11 { dst[i] = ((offset >> 8) as u8) & 0x07 << 5 | (x as u8) << 2 | TAG_COPY_1; dst[i + 1] = offset as u8; i += 2; break; } x = length; if x > 1 << 6 { x = 1 << 6; } dst[i] = ((x as u8) - 1) << 2 | TAG_COPY_2; dst[i + 1] = offset as u8; dst[i + 2] = (offset >> 8) as u8; i += 3; length -= x; } // (Future) Return a `Result<usize>` Instead?? i } // max_compressed_len returns the maximum length of a snappy block, given its // uncompressed length. pub fn max_compressed_len(src_len: usize) -> usize { 32 + src_len + src_len / 6 }
random_line_split
compress.rs
extern crate byteorder; extern crate crc; use std::io; use std::io::{BufWriter, ErrorKind, Write, Seek, SeekFrom, Result, Error}; use self::byteorder::{ByteOrder, WriteBytesExt, LittleEndian}; use self::crc::{crc32, Hasher32}; use definitions::*; // We limit how far copy back-references can go, the same as the C++ code. const MAX_OFFSET: usize = 1 << 15; // The Max Encoded Length of the Max Chunk of 65536 bytes const MAX_BUFFER_SIZE: usize = 76_490; pub struct Compressor<W: Write> { inner: BufWriter<W>, pos: u64, buf_body: [u8; MAX_BUFFER_SIZE], buf_header: [u8; (CHECK_SUM_SIZE + CHUNK_HEADER_SIZE) as usize], wrote_header: bool, } impl <W: Write> Compressor<W> { pub fn new(inner: W) -> Compressor<W> { Compressor { inner: BufWriter::new(inner), pos: 0, buf_body: [0; MAX_BUFFER_SIZE], buf_header: [0; (CHECK_SUM_SIZE + CHUNK_HEADER_SIZE) as usize], wrote_header: false, } } } impl <W: Write> Write for Compressor<W> { // Implement Write // Source Buffer -> Destination (Inner) Buffer fn
(&mut self, src: &[u8]) -> Result<usize> { let mut written: usize = 0; if!self.wrote_header { // Write Stream Literal try!(self.inner.write(&MAGIC_CHUNK)); self.wrote_header = true; } // Split source into chunks of 65536 bytes each. for src_chunk in src.chunks(MAX_UNCOMPRESSED_CHUNK_LEN as usize) { // TODO // Handle Written Slice Length (Ignore Previous Garbage) let chunk_body: &[u8]; let chunk_type: u8; // Create Checksum let checksum: u32 = crc32::checksum_ieee(src_chunk); // Compress the buffer, discarding the result if the improvement // isn't at least 12.5%. let n = try!(compress(&mut self.buf_body, src_chunk)); if n >= src_chunk.len() * (7 / 8) { chunk_type = CHUNK_TYPE_UNCOMPRESSED_DATA; chunk_body = src_chunk; } else { chunk_type = CHUNK_TYPE_COMPRESSED_DATA; chunk_body = self.buf_body.split_at(n).0; } let chunk_len = chunk_body.len() + 4; // Write Chunk Type self.buf_header[0] = chunk_type; // Write Chunk Length self.buf_header[1] = (chunk_len >> 0) as u8; self.buf_header[2] = (chunk_len >> 8) as u8; self.buf_header[3] = (chunk_len >> 16) as u8; // Write Chunk Checksum self.buf_header[4] = (checksum >> 0) as u8; self.buf_header[5] = (checksum >> 8) as u8; self.buf_header[6] = (checksum >> 16) as u8; self.buf_header[7] = (checksum >> 24) as u8; // Write Chunk Header and Handle Error try!(self.inner.write_all(&self.buf_header)); // Write Chunk Body and Handle Error try!(self.inner.write_all(chunk_body)); // If all goes well, count written length as uncompressed length written += src_chunk.len(); } Ok(written) } // Flushes Inner buffer and resets Compressor fn flush(&mut self) -> Result<()> { self.inner.flush() } } // If Compressor is Given a Cursor or Seekable Writer // This Gives the BufWriter the seek method impl <W: Write + Seek> Seek for Compressor<W> { fn seek(&mut self, pos: SeekFrom) -> Result<u64> { self.inner.seek(pos).and_then(|res: u64| { self.pos = res; Ok(res) }) } } // Compress writes the encoded form of src into dst and return the length // written. // Returns an error if dst was not large enough to hold the entire encoded // block. // (Future) Include a Legacy Compress?? pub fn compress(dst: &mut [u8], src: &[u8]) -> io::Result<usize> { if dst.len() < max_compressed_len(src.len()) { return Err(Error::new(ErrorKind::InvalidInput, "snappy: destination buffer is too short")); } // Start Block with varint-encoded length of decompressed bytes LittleEndian::write_u64(dst, src.len() as u64); let mut d: usize = 4; // Return early if src is short if src.len() <= 4 { if src.len()!= 0 { // TODO Handle Error d += emit_literal(dst.split_at_mut(d).1, src).unwrap(); } return Ok(d); } // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive. const MAX_TABLE_SIZE: usize = 1 << 14; let mut shift: u32 = 24; let mut table_size: usize = 1 << 8; while table_size < MAX_TABLE_SIZE && table_size < src.len() { shift -= 1; table_size *= 2; } // Create table let mut table: Vec<i32> = vec![0; MAX_TABLE_SIZE]; // Iterate over the source bytes let mut s: usize = 0; let mut t: i32; let mut lit: usize = 0; // (Future) Iterate in chunks of 4? while s + 3 < src.len() { // Grab 4 bytes let b: (u8, u8, u8, u8) = (src[s], src[s + 1], src[s + 2], src[s + 3]); // Create u32 for Hashing let h: u32 = (b.0 as u32) | ((b.1 as u32) << 8) | ((b.2 as u32) << 16) | ((b.3 as u32) << 24); // Update the hash table let ref mut p: i32 = table[(h.wrapping_mul(0x1e35a7bd) >> shift) as usize]; // We need to to store values in [-1, inf) in table. To save // some initialization time, (re)use the table's zero value // and shift the values against this zero: add 1 on writes, // subtract 1 on reads. // If Hash Exists t = 0; if not t = -1; t = *p - 1; // Set Position of new Hash -> i32 *p = (s + 1) as i32; // If t is invalid or src[s:s+4] differs from src[t:t+4], accumulate a literal // byte. if t < 0 || s.wrapping_sub(t as usize) >= MAX_OFFSET || b.0!= src[t as usize] || b.1!= src[(t + 1) as usize] || b.2!= src[(t + 2) as usize] || b.3!= src[(t + 3) as usize] { s += 1; continue; } // Otherwise, we have a match. First, emit any pending literal bytes. // Panics on d > dst.len(); if lit!= s { d += try!(emit_literal(dst.split_at_mut(d).1, // Handle Split_at mid < src check { if src.len() > s { src.split_at(s).0.split_at(lit).1 } else { src.split_at(lit).1 } })); } // Extend the match to be as long as possible let s0 = s; s += 4; t += 4; while s < src.len() && src[s] == src[t as usize] { s += 1; t += 1; } // Emit the copied bytes. d += emit_copy(dst.split_at_mut(d).1, s.wrapping_sub(t as usize), s - s0); lit = s; } // Emit any final pending literal bytes and return. if lit!= src.len() { d += emit_literal(dst.split_at_mut(d).1, src.split_at(lit).1).unwrap(); } Ok(d) } // emitLiteral writes a literal chunk and returns the number of bytes written. fn emit_literal(dst: &mut [u8], lit: &[u8]) -> io::Result<usize> { let i: usize; let n: u64 = (lit.len() - 1) as u64; if n < 60 { dst[0] = (n as u8) << 2 | TAG_LITERAL; i = 1; } else if n < 1 << 8 { dst[0] = 60 << 2 | TAG_LITERAL; dst[1] = n as u8; i = 2; } else if n < 1 << 16 { dst[0] = 61 << 2 | TAG_LITERAL; dst[1] = n as u8; dst[2] = (n >> 8) as u8; i = 3; } else if n < 1 << 24 { dst[0] = 62 << 2 | TAG_LITERAL; dst[1] = n as u8; dst[2] = (n >> 8) as u8; dst[3] = (n >> 16) as u8; i = 4; } else if n < 1 << 32 { dst[0] = 63 << 2 | TAG_LITERAL; dst[1] = n as u8; dst[2] = (n >> 8) as u8; dst[3] = (n >> 16) as u8; dst[4] = (n >> 24) as u8; i = 5; } else { return Err(Error::new(ErrorKind::InvalidInput, "snappy: source buffer is too long")); } let mut s = 0; for (d, l) in dst.split_at_mut(i).1.iter_mut().zip(lit.iter()) { *d = *l; s += 1; } if s == lit.len() { Ok(i + lit.len()) } else { return Err(Error::new(ErrorKind::InvalidInput, "snappy: destination buffer is too short")); } } // emitCopy writes a copy chunk and returns the number of bytes written. fn emit_copy(dst: &mut [u8], offset: usize, mut length: usize) -> usize { let mut i: usize = 0; while length > 0 { // TODO: Handle Overflow let mut x = length - 4; if 0 <= x && x < 1 << 3 && offset < 1 << 11 { dst[i] = ((offset >> 8) as u8) & 0x07 << 5 | (x as u8) << 2 | TAG_COPY_1; dst[i + 1] = offset as u8; i += 2; break; } x = length; if x > 1 << 6 { x = 1 << 6; } dst[i] = ((x as u8) - 1) << 2 | TAG_COPY_2; dst[i + 1] = offset as u8; dst[i + 2] = (offset >> 8) as u8; i += 3; length -= x; } // (Future) Return a `Result<usize>` Instead?? i } // max_compressed_len returns the maximum length of a snappy block, given its // uncompressed length. pub fn max_compressed_len(src_len: usize) -> usize { 32 + src_len + src_len / 6 }
write
identifier_name
compress.rs
extern crate byteorder; extern crate crc; use std::io; use std::io::{BufWriter, ErrorKind, Write, Seek, SeekFrom, Result, Error}; use self::byteorder::{ByteOrder, WriteBytesExt, LittleEndian}; use self::crc::{crc32, Hasher32}; use definitions::*; // We limit how far copy back-references can go, the same as the C++ code. const MAX_OFFSET: usize = 1 << 15; // The Max Encoded Length of the Max Chunk of 65536 bytes const MAX_BUFFER_SIZE: usize = 76_490; pub struct Compressor<W: Write> { inner: BufWriter<W>, pos: u64, buf_body: [u8; MAX_BUFFER_SIZE], buf_header: [u8; (CHECK_SUM_SIZE + CHUNK_HEADER_SIZE) as usize], wrote_header: bool, } impl <W: Write> Compressor<W> { pub fn new(inner: W) -> Compressor<W> { Compressor { inner: BufWriter::new(inner), pos: 0, buf_body: [0; MAX_BUFFER_SIZE], buf_header: [0; (CHECK_SUM_SIZE + CHUNK_HEADER_SIZE) as usize], wrote_header: false, } } } impl <W: Write> Write for Compressor<W> { // Implement Write // Source Buffer -> Destination (Inner) Buffer fn write(&mut self, src: &[u8]) -> Result<usize> { let mut written: usize = 0; if!self.wrote_header { // Write Stream Literal try!(self.inner.write(&MAGIC_CHUNK)); self.wrote_header = true; } // Split source into chunks of 65536 bytes each. for src_chunk in src.chunks(MAX_UNCOMPRESSED_CHUNK_LEN as usize) { // TODO // Handle Written Slice Length (Ignore Previous Garbage) let chunk_body: &[u8]; let chunk_type: u8; // Create Checksum let checksum: u32 = crc32::checksum_ieee(src_chunk); // Compress the buffer, discarding the result if the improvement // isn't at least 12.5%. let n = try!(compress(&mut self.buf_body, src_chunk)); if n >= src_chunk.len() * (7 / 8) { chunk_type = CHUNK_TYPE_UNCOMPRESSED_DATA; chunk_body = src_chunk; } else { chunk_type = CHUNK_TYPE_COMPRESSED_DATA; chunk_body = self.buf_body.split_at(n).0; } let chunk_len = chunk_body.len() + 4; // Write Chunk Type self.buf_header[0] = chunk_type; // Write Chunk Length self.buf_header[1] = (chunk_len >> 0) as u8; self.buf_header[2] = (chunk_len >> 8) as u8; self.buf_header[3] = (chunk_len >> 16) as u8; // Write Chunk Checksum self.buf_header[4] = (checksum >> 0) as u8; self.buf_header[5] = (checksum >> 8) as u8; self.buf_header[6] = (checksum >> 16) as u8; self.buf_header[7] = (checksum >> 24) as u8; // Write Chunk Header and Handle Error try!(self.inner.write_all(&self.buf_header)); // Write Chunk Body and Handle Error try!(self.inner.write_all(chunk_body)); // If all goes well, count written length as uncompressed length written += src_chunk.len(); } Ok(written) } // Flushes Inner buffer and resets Compressor fn flush(&mut self) -> Result<()> { self.inner.flush() } } // If Compressor is Given a Cursor or Seekable Writer // This Gives the BufWriter the seek method impl <W: Write + Seek> Seek for Compressor<W> { fn seek(&mut self, pos: SeekFrom) -> Result<u64>
} // Compress writes the encoded form of src into dst and return the length // written. // Returns an error if dst was not large enough to hold the entire encoded // block. // (Future) Include a Legacy Compress?? pub fn compress(dst: &mut [u8], src: &[u8]) -> io::Result<usize> { if dst.len() < max_compressed_len(src.len()) { return Err(Error::new(ErrorKind::InvalidInput, "snappy: destination buffer is too short")); } // Start Block with varint-encoded length of decompressed bytes LittleEndian::write_u64(dst, src.len() as u64); let mut d: usize = 4; // Return early if src is short if src.len() <= 4 { if src.len()!= 0 { // TODO Handle Error d += emit_literal(dst.split_at_mut(d).1, src).unwrap(); } return Ok(d); } // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive. const MAX_TABLE_SIZE: usize = 1 << 14; let mut shift: u32 = 24; let mut table_size: usize = 1 << 8; while table_size < MAX_TABLE_SIZE && table_size < src.len() { shift -= 1; table_size *= 2; } // Create table let mut table: Vec<i32> = vec![0; MAX_TABLE_SIZE]; // Iterate over the source bytes let mut s: usize = 0; let mut t: i32; let mut lit: usize = 0; // (Future) Iterate in chunks of 4? while s + 3 < src.len() { // Grab 4 bytes let b: (u8, u8, u8, u8) = (src[s], src[s + 1], src[s + 2], src[s + 3]); // Create u32 for Hashing let h: u32 = (b.0 as u32) | ((b.1 as u32) << 8) | ((b.2 as u32) << 16) | ((b.3 as u32) << 24); // Update the hash table let ref mut p: i32 = table[(h.wrapping_mul(0x1e35a7bd) >> shift) as usize]; // We need to to store values in [-1, inf) in table. To save // some initialization time, (re)use the table's zero value // and shift the values against this zero: add 1 on writes, // subtract 1 on reads. // If Hash Exists t = 0; if not t = -1; t = *p - 1; // Set Position of new Hash -> i32 *p = (s + 1) as i32; // If t is invalid or src[s:s+4] differs from src[t:t+4], accumulate a literal // byte. if t < 0 || s.wrapping_sub(t as usize) >= MAX_OFFSET || b.0!= src[t as usize] || b.1!= src[(t + 1) as usize] || b.2!= src[(t + 2) as usize] || b.3!= src[(t + 3) as usize] { s += 1; continue; } // Otherwise, we have a match. First, emit any pending literal bytes. // Panics on d > dst.len(); if lit!= s { d += try!(emit_literal(dst.split_at_mut(d).1, // Handle Split_at mid < src check { if src.len() > s { src.split_at(s).0.split_at(lit).1 } else { src.split_at(lit).1 } })); } // Extend the match to be as long as possible let s0 = s; s += 4; t += 4; while s < src.len() && src[s] == src[t as usize] { s += 1; t += 1; } // Emit the copied bytes. d += emit_copy(dst.split_at_mut(d).1, s.wrapping_sub(t as usize), s - s0); lit = s; } // Emit any final pending literal bytes and return. if lit!= src.len() { d += emit_literal(dst.split_at_mut(d).1, src.split_at(lit).1).unwrap(); } Ok(d) } // emitLiteral writes a literal chunk and returns the number of bytes written. fn emit_literal(dst: &mut [u8], lit: &[u8]) -> io::Result<usize> { let i: usize; let n: u64 = (lit.len() - 1) as u64; if n < 60 { dst[0] = (n as u8) << 2 | TAG_LITERAL; i = 1; } else if n < 1 << 8 { dst[0] = 60 << 2 | TAG_LITERAL; dst[1] = n as u8; i = 2; } else if n < 1 << 16 { dst[0] = 61 << 2 | TAG_LITERAL; dst[1] = n as u8; dst[2] = (n >> 8) as u8; i = 3; } else if n < 1 << 24 { dst[0] = 62 << 2 | TAG_LITERAL; dst[1] = n as u8; dst[2] = (n >> 8) as u8; dst[3] = (n >> 16) as u8; i = 4; } else if n < 1 << 32 { dst[0] = 63 << 2 | TAG_LITERAL; dst[1] = n as u8; dst[2] = (n >> 8) as u8; dst[3] = (n >> 16) as u8; dst[4] = (n >> 24) as u8; i = 5; } else { return Err(Error::new(ErrorKind::InvalidInput, "snappy: source buffer is too long")); } let mut s = 0; for (d, l) in dst.split_at_mut(i).1.iter_mut().zip(lit.iter()) { *d = *l; s += 1; } if s == lit.len() { Ok(i + lit.len()) } else { return Err(Error::new(ErrorKind::InvalidInput, "snappy: destination buffer is too short")); } } // emitCopy writes a copy chunk and returns the number of bytes written. fn emit_copy(dst: &mut [u8], offset: usize, mut length: usize) -> usize { let mut i: usize = 0; while length > 0 { // TODO: Handle Overflow let mut x = length - 4; if 0 <= x && x < 1 << 3 && offset < 1 << 11 { dst[i] = ((offset >> 8) as u8) & 0x07 << 5 | (x as u8) << 2 | TAG_COPY_1; dst[i + 1] = offset as u8; i += 2; break; } x = length; if x > 1 << 6 { x = 1 << 6; } dst[i] = ((x as u8) - 1) << 2 | TAG_COPY_2; dst[i + 1] = offset as u8; dst[i + 2] = (offset >> 8) as u8; i += 3; length -= x; } // (Future) Return a `Result<usize>` Instead?? i } // max_compressed_len returns the maximum length of a snappy block, given its // uncompressed length. pub fn max_compressed_len(src_len: usize) -> usize { 32 + src_len + src_len / 6 }
{ self.inner.seek(pos).and_then(|res: u64| { self.pos = res; Ok(res) }) }
identifier_body
mod.rs
extern crate fdt; extern crate byteorder; use alloc::vec::Vec; use core::slice; use crate::memory::MemoryArea; use self::byteorder::{ByteOrder, BE}; pub static mut MEMORY_MAP: [MemoryArea; 512] = [MemoryArea { base_addr: 0, length: 0, _type: 0, acpi: 0, }; 512]; fn root_cell_sz(dt: &fdt::DeviceTree) -> Option<(u32, u32)> { let root_node = dt.nodes().nth(0).unwrap(); let address_cells = root_node.properties().find(|p| p.name.contains("#address-cells")).unwrap(); let size_cells = root_node.properties().find(|p| p.name.contains("#size-cells")).unwrap(); Some((BE::read_u32(&size_cells.data), BE::read_u32(&size_cells.data))) } fn memory_ranges(dt: &fdt::DeviceTree, address_cells: usize, size_cells: usize, ranges: &mut [(usize, usize); 10]) -> usize { let memory_node = dt.find_node("/memory").unwrap(); let reg = memory_node.properties().find(|p| p.name.contains("reg")).unwrap(); let chunk_sz = (address_cells + size_cells) * 4; let chunk_count = (reg.data.len() / chunk_sz); let mut index = 0; for chunk in reg.data.chunks(chunk_sz as usize) { if index == chunk_count { return index; } let (base, size) = chunk.split_at((address_cells * 4) as usize);
} let mut s = 0; for sz_chunk in size.rchunks(4) { s += BE::read_u32(sz_chunk); } ranges[index] = (b as usize, s as usize); index += 1; } index } pub fn diag_uart_range(dtb_base: usize, dtb_size: usize) -> Option<(usize, usize)> { let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) }; let dt = fdt::DeviceTree::new(data).unwrap(); let chosen_node = dt.find_node("/chosen").unwrap(); let stdout_path = chosen_node.properties().find(|p| p.name.contains("stdout-path")).unwrap(); let uart_node_name = core::str::from_utf8(stdout_path.data).unwrap() .split('/') .nth(1)? .trim_end(); let len = uart_node_name.len(); let uart_node_name = &uart_node_name[0..len-1]; let uart_node = dt.nodes().find(|n| n.name.contains(uart_node_name)).unwrap(); let reg = uart_node.properties().find(|p| p.name.contains("reg")).unwrap(); let (address_cells, size_cells) = root_cell_sz(&dt).unwrap(); let chunk_sz = (address_cells + size_cells) * 4; let (base, size) = reg.data.split_at((address_cells * 4) as usize); let mut b = 0; for base_chunk in base.rchunks(4) { b += BE::read_u32(base_chunk); } let mut s = 0; for sz_chunk in size.rchunks(4) { s += BE::read_u32(sz_chunk); } Some((b as usize, s as usize)) } fn compatible_node_present<'a>(dt: &fdt::DeviceTree<'a>, compat_string: &str) -> bool { for node in dt.nodes() { if let Some(compatible) = node.properties().find(|p| p.name.contains("compatible")) { let s = core::str::from_utf8(compatible.data).unwrap(); if s.contains(compat_string) { return true; } } } false } pub fn fill_env_data(dtb_base: usize, dtb_size: usize, env_base: usize) -> usize { let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) }; let dt = fdt::DeviceTree::new(data).unwrap(); let chosen_node = dt.find_node("/chosen").unwrap(); if let Some(bootargs) = chosen_node.properties().find(|p| p.name.contains("bootargs")) { let bootargs_len = bootargs.data.len(); let env_base_slice = unsafe { slice::from_raw_parts_mut(env_base as *mut u8, bootargs_len) }; env_base_slice[..bootargs_len].clone_from_slice(bootargs.data); bootargs_len } else { 0 } } pub fn fill_memory_map(dtb_base: usize, dtb_size: usize) { let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) }; let dt = fdt::DeviceTree::new(data).unwrap(); let (address_cells, size_cells) = root_cell_sz(&dt).unwrap(); let mut ranges: [(usize, usize); 10] = [(0,0); 10]; let nranges = memory_ranges(&dt, address_cells as usize, size_cells as usize, &mut ranges); for index in (0..nranges) { let (base, size) = ranges[index]; unsafe { MEMORY_MAP[index] = MemoryArea { base_addr: base as u64, length: size as u64, _type: 1, acpi: 0, }; } } }
let mut b = 0; for base_chunk in base.rchunks(4) { b += BE::read_u32(base_chunk);
random_line_split
mod.rs
extern crate fdt; extern crate byteorder; use alloc::vec::Vec; use core::slice; use crate::memory::MemoryArea; use self::byteorder::{ByteOrder, BE}; pub static mut MEMORY_MAP: [MemoryArea; 512] = [MemoryArea { base_addr: 0, length: 0, _type: 0, acpi: 0, }; 512]; fn root_cell_sz(dt: &fdt::DeviceTree) -> Option<(u32, u32)> { let root_node = dt.nodes().nth(0).unwrap(); let address_cells = root_node.properties().find(|p| p.name.contains("#address-cells")).unwrap(); let size_cells = root_node.properties().find(|p| p.name.contains("#size-cells")).unwrap(); Some((BE::read_u32(&size_cells.data), BE::read_u32(&size_cells.data))) } fn memory_ranges(dt: &fdt::DeviceTree, address_cells: usize, size_cells: usize, ranges: &mut [(usize, usize); 10]) -> usize { let memory_node = dt.find_node("/memory").unwrap(); let reg = memory_node.properties().find(|p| p.name.contains("reg")).unwrap(); let chunk_sz = (address_cells + size_cells) * 4; let chunk_count = (reg.data.len() / chunk_sz); let mut index = 0; for chunk in reg.data.chunks(chunk_sz as usize) { if index == chunk_count { return index; } let (base, size) = chunk.split_at((address_cells * 4) as usize); let mut b = 0; for base_chunk in base.rchunks(4) { b += BE::read_u32(base_chunk); } let mut s = 0; for sz_chunk in size.rchunks(4) { s += BE::read_u32(sz_chunk); } ranges[index] = (b as usize, s as usize); index += 1; } index } pub fn
(dtb_base: usize, dtb_size: usize) -> Option<(usize, usize)> { let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) }; let dt = fdt::DeviceTree::new(data).unwrap(); let chosen_node = dt.find_node("/chosen").unwrap(); let stdout_path = chosen_node.properties().find(|p| p.name.contains("stdout-path")).unwrap(); let uart_node_name = core::str::from_utf8(stdout_path.data).unwrap() .split('/') .nth(1)? .trim_end(); let len = uart_node_name.len(); let uart_node_name = &uart_node_name[0..len-1]; let uart_node = dt.nodes().find(|n| n.name.contains(uart_node_name)).unwrap(); let reg = uart_node.properties().find(|p| p.name.contains("reg")).unwrap(); let (address_cells, size_cells) = root_cell_sz(&dt).unwrap(); let chunk_sz = (address_cells + size_cells) * 4; let (base, size) = reg.data.split_at((address_cells * 4) as usize); let mut b = 0; for base_chunk in base.rchunks(4) { b += BE::read_u32(base_chunk); } let mut s = 0; for sz_chunk in size.rchunks(4) { s += BE::read_u32(sz_chunk); } Some((b as usize, s as usize)) } fn compatible_node_present<'a>(dt: &fdt::DeviceTree<'a>, compat_string: &str) -> bool { for node in dt.nodes() { if let Some(compatible) = node.properties().find(|p| p.name.contains("compatible")) { let s = core::str::from_utf8(compatible.data).unwrap(); if s.contains(compat_string) { return true; } } } false } pub fn fill_env_data(dtb_base: usize, dtb_size: usize, env_base: usize) -> usize { let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) }; let dt = fdt::DeviceTree::new(data).unwrap(); let chosen_node = dt.find_node("/chosen").unwrap(); if let Some(bootargs) = chosen_node.properties().find(|p| p.name.contains("bootargs")) { let bootargs_len = bootargs.data.len(); let env_base_slice = unsafe { slice::from_raw_parts_mut(env_base as *mut u8, bootargs_len) }; env_base_slice[..bootargs_len].clone_from_slice(bootargs.data); bootargs_len } else { 0 } } pub fn fill_memory_map(dtb_base: usize, dtb_size: usize) { let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) }; let dt = fdt::DeviceTree::new(data).unwrap(); let (address_cells, size_cells) = root_cell_sz(&dt).unwrap(); let mut ranges: [(usize, usize); 10] = [(0,0); 10]; let nranges = memory_ranges(&dt, address_cells as usize, size_cells as usize, &mut ranges); for index in (0..nranges) { let (base, size) = ranges[index]; unsafe { MEMORY_MAP[index] = MemoryArea { base_addr: base as u64, length: size as u64, _type: 1, acpi: 0, }; } } }
diag_uart_range
identifier_name
mod.rs
extern crate fdt; extern crate byteorder; use alloc::vec::Vec; use core::slice; use crate::memory::MemoryArea; use self::byteorder::{ByteOrder, BE}; pub static mut MEMORY_MAP: [MemoryArea; 512] = [MemoryArea { base_addr: 0, length: 0, _type: 0, acpi: 0, }; 512]; fn root_cell_sz(dt: &fdt::DeviceTree) -> Option<(u32, u32)> { let root_node = dt.nodes().nth(0).unwrap(); let address_cells = root_node.properties().find(|p| p.name.contains("#address-cells")).unwrap(); let size_cells = root_node.properties().find(|p| p.name.contains("#size-cells")).unwrap(); Some((BE::read_u32(&size_cells.data), BE::read_u32(&size_cells.data))) } fn memory_ranges(dt: &fdt::DeviceTree, address_cells: usize, size_cells: usize, ranges: &mut [(usize, usize); 10]) -> usize { let memory_node = dt.find_node("/memory").unwrap(); let reg = memory_node.properties().find(|p| p.name.contains("reg")).unwrap(); let chunk_sz = (address_cells + size_cells) * 4; let chunk_count = (reg.data.len() / chunk_sz); let mut index = 0; for chunk in reg.data.chunks(chunk_sz as usize) { if index == chunk_count { return index; } let (base, size) = chunk.split_at((address_cells * 4) as usize); let mut b = 0; for base_chunk in base.rchunks(4) { b += BE::read_u32(base_chunk); } let mut s = 0; for sz_chunk in size.rchunks(4) { s += BE::read_u32(sz_chunk); } ranges[index] = (b as usize, s as usize); index += 1; } index } pub fn diag_uart_range(dtb_base: usize, dtb_size: usize) -> Option<(usize, usize)> { let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) }; let dt = fdt::DeviceTree::new(data).unwrap(); let chosen_node = dt.find_node("/chosen").unwrap(); let stdout_path = chosen_node.properties().find(|p| p.name.contains("stdout-path")).unwrap(); let uart_node_name = core::str::from_utf8(stdout_path.data).unwrap() .split('/') .nth(1)? .trim_end(); let len = uart_node_name.len(); let uart_node_name = &uart_node_name[0..len-1]; let uart_node = dt.nodes().find(|n| n.name.contains(uart_node_name)).unwrap(); let reg = uart_node.properties().find(|p| p.name.contains("reg")).unwrap(); let (address_cells, size_cells) = root_cell_sz(&dt).unwrap(); let chunk_sz = (address_cells + size_cells) * 4; let (base, size) = reg.data.split_at((address_cells * 4) as usize); let mut b = 0; for base_chunk in base.rchunks(4) { b += BE::read_u32(base_chunk); } let mut s = 0; for sz_chunk in size.rchunks(4) { s += BE::read_u32(sz_chunk); } Some((b as usize, s as usize)) } fn compatible_node_present<'a>(dt: &fdt::DeviceTree<'a>, compat_string: &str) -> bool { for node in dt.nodes() { if let Some(compatible) = node.properties().find(|p| p.name.contains("compatible")) { let s = core::str::from_utf8(compatible.data).unwrap(); if s.contains(compat_string) { return true; } } } false } pub fn fill_env_data(dtb_base: usize, dtb_size: usize, env_base: usize) -> usize { let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) }; let dt = fdt::DeviceTree::new(data).unwrap(); let chosen_node = dt.find_node("/chosen").unwrap(); if let Some(bootargs) = chosen_node.properties().find(|p| p.name.contains("bootargs")) { let bootargs_len = bootargs.data.len(); let env_base_slice = unsafe { slice::from_raw_parts_mut(env_base as *mut u8, bootargs_len) }; env_base_slice[..bootargs_len].clone_from_slice(bootargs.data); bootargs_len } else
} pub fn fill_memory_map(dtb_base: usize, dtb_size: usize) { let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) }; let dt = fdt::DeviceTree::new(data).unwrap(); let (address_cells, size_cells) = root_cell_sz(&dt).unwrap(); let mut ranges: [(usize, usize); 10] = [(0,0); 10]; let nranges = memory_ranges(&dt, address_cells as usize, size_cells as usize, &mut ranges); for index in (0..nranges) { let (base, size) = ranges[index]; unsafe { MEMORY_MAP[index] = MemoryArea { base_addr: base as u64, length: size as u64, _type: 1, acpi: 0, }; } } }
{ 0 }
conditional_block
mod.rs
extern crate fdt; extern crate byteorder; use alloc::vec::Vec; use core::slice; use crate::memory::MemoryArea; use self::byteorder::{ByteOrder, BE}; pub static mut MEMORY_MAP: [MemoryArea; 512] = [MemoryArea { base_addr: 0, length: 0, _type: 0, acpi: 0, }; 512]; fn root_cell_sz(dt: &fdt::DeviceTree) -> Option<(u32, u32)> { let root_node = dt.nodes().nth(0).unwrap(); let address_cells = root_node.properties().find(|p| p.name.contains("#address-cells")).unwrap(); let size_cells = root_node.properties().find(|p| p.name.contains("#size-cells")).unwrap(); Some((BE::read_u32(&size_cells.data), BE::read_u32(&size_cells.data))) } fn memory_ranges(dt: &fdt::DeviceTree, address_cells: usize, size_cells: usize, ranges: &mut [(usize, usize); 10]) -> usize
ranges[index] = (b as usize, s as usize); index += 1; } index } pub fn diag_uart_range(dtb_base: usize, dtb_size: usize) -> Option<(usize, usize)> { let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) }; let dt = fdt::DeviceTree::new(data).unwrap(); let chosen_node = dt.find_node("/chosen").unwrap(); let stdout_path = chosen_node.properties().find(|p| p.name.contains("stdout-path")).unwrap(); let uart_node_name = core::str::from_utf8(stdout_path.data).unwrap() .split('/') .nth(1)? .trim_end(); let len = uart_node_name.len(); let uart_node_name = &uart_node_name[0..len-1]; let uart_node = dt.nodes().find(|n| n.name.contains(uart_node_name)).unwrap(); let reg = uart_node.properties().find(|p| p.name.contains("reg")).unwrap(); let (address_cells, size_cells) = root_cell_sz(&dt).unwrap(); let chunk_sz = (address_cells + size_cells) * 4; let (base, size) = reg.data.split_at((address_cells * 4) as usize); let mut b = 0; for base_chunk in base.rchunks(4) { b += BE::read_u32(base_chunk); } let mut s = 0; for sz_chunk in size.rchunks(4) { s += BE::read_u32(sz_chunk); } Some((b as usize, s as usize)) } fn compatible_node_present<'a>(dt: &fdt::DeviceTree<'a>, compat_string: &str) -> bool { for node in dt.nodes() { if let Some(compatible) = node.properties().find(|p| p.name.contains("compatible")) { let s = core::str::from_utf8(compatible.data).unwrap(); if s.contains(compat_string) { return true; } } } false } pub fn fill_env_data(dtb_base: usize, dtb_size: usize, env_base: usize) -> usize { let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) }; let dt = fdt::DeviceTree::new(data).unwrap(); let chosen_node = dt.find_node("/chosen").unwrap(); if let Some(bootargs) = chosen_node.properties().find(|p| p.name.contains("bootargs")) { let bootargs_len = bootargs.data.len(); let env_base_slice = unsafe { slice::from_raw_parts_mut(env_base as *mut u8, bootargs_len) }; env_base_slice[..bootargs_len].clone_from_slice(bootargs.data); bootargs_len } else { 0 } } pub fn fill_memory_map(dtb_base: usize, dtb_size: usize) { let data = unsafe { slice::from_raw_parts(dtb_base as *const u8, dtb_size) }; let dt = fdt::DeviceTree::new(data).unwrap(); let (address_cells, size_cells) = root_cell_sz(&dt).unwrap(); let mut ranges: [(usize, usize); 10] = [(0,0); 10]; let nranges = memory_ranges(&dt, address_cells as usize, size_cells as usize, &mut ranges); for index in (0..nranges) { let (base, size) = ranges[index]; unsafe { MEMORY_MAP[index] = MemoryArea { base_addr: base as u64, length: size as u64, _type: 1, acpi: 0, }; } } }
{ let memory_node = dt.find_node("/memory").unwrap(); let reg = memory_node.properties().find(|p| p.name.contains("reg")).unwrap(); let chunk_sz = (address_cells + size_cells) * 4; let chunk_count = (reg.data.len() / chunk_sz); let mut index = 0; for chunk in reg.data.chunks(chunk_sz as usize) { if index == chunk_count { return index; } let (base, size) = chunk.split_at((address_cells * 4) as usize); let mut b = 0; for base_chunk in base.rchunks(4) { b += BE::read_u32(base_chunk); } let mut s = 0; for sz_chunk in size.rchunks(4) { s += BE::read_u32(sz_chunk); }
identifier_body
monomorphized-callees-with-ty-params-3314.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. trait Serializer { } trait Serializable { fn serialize<S:Serializer>(&self, s: S); } impl Serializable for int { fn serialize<S:Serializer>(&self, _s: S) { } } struct F<A> { a: A } impl<A:Serializable> Serializable for F<A> { fn serialize<S:Serializer>(&self, s: S)
} impl Serializer for int { } pub fn main() { let foo = F { a: 1 }; foo.serialize(1); let bar = F { a: F {a: 1 } }; bar.serialize(2); }
{ self.a.serialize(s); }
identifier_body
monomorphized-callees-with-ty-params-3314.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. trait Serializer { } trait Serializable { fn serialize<S:Serializer>(&self, s: S); } impl Serializable for int { fn serialize<S:Serializer>(&self, _s: S) { } } struct F<A> { a: A } impl<A:Serializable> Serializable for F<A> { fn serialize<S:Serializer>(&self, s: S) { self.a.serialize(s); } } impl Serializer for int { } pub fn
() { let foo = F { a: 1 }; foo.serialize(1); let bar = F { a: F {a: 1 } }; bar.serialize(2); }
main
identifier_name
monomorphized-callees-with-ty-params-3314.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.
trait Serializable { fn serialize<S:Serializer>(&self, s: S); } impl Serializable for int { fn serialize<S:Serializer>(&self, _s: S) { } } struct F<A> { a: A } impl<A:Serializable> Serializable for F<A> { fn serialize<S:Serializer>(&self, s: S) { self.a.serialize(s); } } impl Serializer for int { } pub fn main() { let foo = F { a: 1 }; foo.serialize(1); let bar = F { a: F {a: 1 } }; bar.serialize(2); }
trait Serializer { }
random_line_split
window_builder.rs
use std::{collections::HashMap, sync::mpsc}; use super::{Shell, Window}; use crate::{ render::RenderContext2D, utils::Rectangle, window_adapter::WindowAdapter, WindowRequest, WindowSettings, }; /// The `WindowBuilder` is used to construct an os independent window /// shell that will communicate with the supported render backends. pub struct WindowBuilder<'a, A:'static> where A: WindowAdapter, { adapter: A, always_on_top: bool, borderless: bool, bounds: Rectangle, fonts: HashMap<String, &'static [u8]>, request_receiver: Option<mpsc::Receiver<WindowRequest>>, resizeable: bool, shell: &'a mut Shell<A>, title: String, } impl<'a, A> WindowBuilder<'a, A> where A: WindowAdapter, { /// Creates the window builder from a settings object. pub fn from_settings(settings: WindowSettings, shell: &'a mut Shell<A>, adapter: A) -> Self { WindowBuilder { adapter, always_on_top: settings.always_on_top, borderless: settings.borderless, bounds: Rectangle::new(settings.position, (settings.size.0, settings.size.1)), fonts: settings.fonts, request_receiver: None, resizeable: settings.resizeable, shell, title: settings.title, } } /// Sets always_on_top. pub fn always_on_top(mut self, always_on_top: bool) -> Self { self.always_on_top = always_on_top; self } /// Sets borderless. pub fn borderless(mut self, borderless: bool) -> Self { self.borderless = borderless; self } /// Sets the bounds. pub fn bounds(mut self, bounds: impl Into<Rectangle>) -> Self { self.bounds = bounds.into(); self } /// Builds the window shell. The shell will be linked to the application `Shell`. pub fn build(self) { let mut render_context = RenderContext2D::new(self.bounds.width(), self.bounds.height()); let mut flags = vec![]; if self.resizeable { flags.push(orbclient::WindowFlag::Resizable); } if self.borderless { flags.push(orbclient::WindowFlag::Borderless); } if self.always_on_top
let window = orbclient::Window::new_flags( self.bounds.x() as i32, self.bounds.y() as i32, self.bounds.width() as u32, self.bounds.height() as u32, self.title.as_str(), &flags, ) .expect("WindowBuilder: Could not create an orblient window."); for (family, font) in self.fonts { render_context.register_font(&family, font); } self.shell.window_shells.push(Window::new( self.adapter, render_context, self.request_receiver, window, )); } /// Registers a new font via a string that will identify the font family. pub fn font(mut self, family: impl Into<String>, font_file: &'static [u8]) -> Self { self.fonts.insert(family.into(), font_file); self } /// Creates a new window builder. pub fn new(shell: &'a mut Shell<A>, adapter: A) -> Self { WindowBuilder { adapter, always_on_top: false, borderless: false, bounds: Rectangle::new((0.0, 0.0), (100.0, 75.0)), fonts: HashMap::new(), request_receiver: None, resizeable: false, shell, title: String::default(), } } /// Mark window as resizeable. pub fn resizeable(mut self, resizeable: bool) -> Self { self.resizeable = resizeable; self } /// Register a window request receiver to communicate with the /// window shell via interprocess communication. pub fn request_receiver(mut self, request_receiver: mpsc::Receiver<WindowRequest>) -> Self { self.request_receiver = Some(request_receiver); self } /// Sets the window title. pub fn title(mut self, title: impl Into<String>) -> Self { self.title = title.into(); self } }
{ flags.push(orbclient::WindowFlag::Front); }
conditional_block
window_builder.rs
use std::{collections::HashMap, sync::mpsc}; use super::{Shell, Window}; use crate::{ render::RenderContext2D, utils::Rectangle, window_adapter::WindowAdapter, WindowRequest, WindowSettings, }; /// The `WindowBuilder` is used to construct an os independent window /// shell that will communicate with the supported render backends. pub struct WindowBuilder<'a, A:'static> where A: WindowAdapter, { adapter: A, always_on_top: bool, borderless: bool, bounds: Rectangle, fonts: HashMap<String, &'static [u8]>, request_receiver: Option<mpsc::Receiver<WindowRequest>>, resizeable: bool, shell: &'a mut Shell<A>, title: String, } impl<'a, A> WindowBuilder<'a, A> where A: WindowAdapter, { /// Creates the window builder from a settings object. pub fn from_settings(settings: WindowSettings, shell: &'a mut Shell<A>, adapter: A) -> Self { WindowBuilder { adapter, always_on_top: settings.always_on_top, borderless: settings.borderless, bounds: Rectangle::new(settings.position, (settings.size.0, settings.size.1)), fonts: settings.fonts, request_receiver: None, resizeable: settings.resizeable, shell, title: settings.title, } } /// Sets always_on_top. pub fn always_on_top(mut self, always_on_top: bool) -> Self { self.always_on_top = always_on_top; self } /// Sets borderless. pub fn borderless(mut self, borderless: bool) -> Self { self.borderless = borderless; self } /// Sets the bounds. pub fn bounds(mut self, bounds: impl Into<Rectangle>) -> Self { self.bounds = bounds.into(); self } /// Builds the window shell. The shell will be linked to the application `Shell`. pub fn build(self) { let mut render_context = RenderContext2D::new(self.bounds.width(), self.bounds.height()); let mut flags = vec![]; if self.resizeable { flags.push(orbclient::WindowFlag::Resizable); } if self.borderless { flags.push(orbclient::WindowFlag::Borderless); } if self.always_on_top { flags.push(orbclient::WindowFlag::Front); } let window = orbclient::Window::new_flags( self.bounds.x() as i32, self.bounds.y() as i32, self.bounds.width() as u32, self.bounds.height() as u32, self.title.as_str(), &flags, ) .expect("WindowBuilder: Could not create an orblient window."); for (family, font) in self.fonts { render_context.register_font(&family, font); } self.shell.window_shells.push(Window::new( self.adapter, render_context, self.request_receiver, window, )); } /// Registers a new font via a string that will identify the font family. pub fn font(mut self, family: impl Into<String>, font_file: &'static [u8]) -> Self { self.fonts.insert(family.into(), font_file); self } /// Creates a new window builder. pub fn new(shell: &'a mut Shell<A>, adapter: A) -> Self
/// Mark window as resizeable. pub fn resizeable(mut self, resizeable: bool) -> Self { self.resizeable = resizeable; self } /// Register a window request receiver to communicate with the /// window shell via interprocess communication. pub fn request_receiver(mut self, request_receiver: mpsc::Receiver<WindowRequest>) -> Self { self.request_receiver = Some(request_receiver); self } /// Sets the window title. pub fn title(mut self, title: impl Into<String>) -> Self { self.title = title.into(); self } }
{ WindowBuilder { adapter, always_on_top: false, borderless: false, bounds: Rectangle::new((0.0, 0.0), (100.0, 75.0)), fonts: HashMap::new(), request_receiver: None, resizeable: false, shell, title: String::default(), } }
identifier_body
window_builder.rs
use std::{collections::HashMap, sync::mpsc}; use super::{Shell, Window}; use crate::{ render::RenderContext2D, utils::Rectangle, window_adapter::WindowAdapter, WindowRequest, WindowSettings, }; /// The `WindowBuilder` is used to construct an os independent window /// shell that will communicate with the supported render backends. pub struct WindowBuilder<'a, A:'static> where A: WindowAdapter, { adapter: A, always_on_top: bool, borderless: bool, bounds: Rectangle, fonts: HashMap<String, &'static [u8]>, request_receiver: Option<mpsc::Receiver<WindowRequest>>, resizeable: bool, shell: &'a mut Shell<A>, title: String, } impl<'a, A> WindowBuilder<'a, A> where A: WindowAdapter, { /// Creates the window builder from a settings object. pub fn from_settings(settings: WindowSettings, shell: &'a mut Shell<A>, adapter: A) -> Self { WindowBuilder {
always_on_top: settings.always_on_top, borderless: settings.borderless, bounds: Rectangle::new(settings.position, (settings.size.0, settings.size.1)), fonts: settings.fonts, request_receiver: None, resizeable: settings.resizeable, shell, title: settings.title, } } /// Sets always_on_top. pub fn always_on_top(mut self, always_on_top: bool) -> Self { self.always_on_top = always_on_top; self } /// Sets borderless. pub fn borderless(mut self, borderless: bool) -> Self { self.borderless = borderless; self } /// Sets the bounds. pub fn bounds(mut self, bounds: impl Into<Rectangle>) -> Self { self.bounds = bounds.into(); self } /// Builds the window shell. The shell will be linked to the application `Shell`. pub fn build(self) { let mut render_context = RenderContext2D::new(self.bounds.width(), self.bounds.height()); let mut flags = vec![]; if self.resizeable { flags.push(orbclient::WindowFlag::Resizable); } if self.borderless { flags.push(orbclient::WindowFlag::Borderless); } if self.always_on_top { flags.push(orbclient::WindowFlag::Front); } let window = orbclient::Window::new_flags( self.bounds.x() as i32, self.bounds.y() as i32, self.bounds.width() as u32, self.bounds.height() as u32, self.title.as_str(), &flags, ) .expect("WindowBuilder: Could not create an orblient window."); for (family, font) in self.fonts { render_context.register_font(&family, font); } self.shell.window_shells.push(Window::new( self.adapter, render_context, self.request_receiver, window, )); } /// Registers a new font via a string that will identify the font family. pub fn font(mut self, family: impl Into<String>, font_file: &'static [u8]) -> Self { self.fonts.insert(family.into(), font_file); self } /// Creates a new window builder. pub fn new(shell: &'a mut Shell<A>, adapter: A) -> Self { WindowBuilder { adapter, always_on_top: false, borderless: false, bounds: Rectangle::new((0.0, 0.0), (100.0, 75.0)), fonts: HashMap::new(), request_receiver: None, resizeable: false, shell, title: String::default(), } } /// Mark window as resizeable. pub fn resizeable(mut self, resizeable: bool) -> Self { self.resizeable = resizeable; self } /// Register a window request receiver to communicate with the /// window shell via interprocess communication. pub fn request_receiver(mut self, request_receiver: mpsc::Receiver<WindowRequest>) -> Self { self.request_receiver = Some(request_receiver); self } /// Sets the window title. pub fn title(mut self, title: impl Into<String>) -> Self { self.title = title.into(); self } }
adapter,
random_line_split
window_builder.rs
use std::{collections::HashMap, sync::mpsc}; use super::{Shell, Window}; use crate::{ render::RenderContext2D, utils::Rectangle, window_adapter::WindowAdapter, WindowRequest, WindowSettings, }; /// The `WindowBuilder` is used to construct an os independent window /// shell that will communicate with the supported render backends. pub struct WindowBuilder<'a, A:'static> where A: WindowAdapter, { adapter: A, always_on_top: bool, borderless: bool, bounds: Rectangle, fonts: HashMap<String, &'static [u8]>, request_receiver: Option<mpsc::Receiver<WindowRequest>>, resizeable: bool, shell: &'a mut Shell<A>, title: String, } impl<'a, A> WindowBuilder<'a, A> where A: WindowAdapter, { /// Creates the window builder from a settings object. pub fn from_settings(settings: WindowSettings, shell: &'a mut Shell<A>, adapter: A) -> Self { WindowBuilder { adapter, always_on_top: settings.always_on_top, borderless: settings.borderless, bounds: Rectangle::new(settings.position, (settings.size.0, settings.size.1)), fonts: settings.fonts, request_receiver: None, resizeable: settings.resizeable, shell, title: settings.title, } } /// Sets always_on_top. pub fn always_on_top(mut self, always_on_top: bool) -> Self { self.always_on_top = always_on_top; self } /// Sets borderless. pub fn borderless(mut self, borderless: bool) -> Self { self.borderless = borderless; self } /// Sets the bounds. pub fn bounds(mut self, bounds: impl Into<Rectangle>) -> Self { self.bounds = bounds.into(); self } /// Builds the window shell. The shell will be linked to the application `Shell`. pub fn build(self) { let mut render_context = RenderContext2D::new(self.bounds.width(), self.bounds.height()); let mut flags = vec![]; if self.resizeable { flags.push(orbclient::WindowFlag::Resizable); } if self.borderless { flags.push(orbclient::WindowFlag::Borderless); } if self.always_on_top { flags.push(orbclient::WindowFlag::Front); } let window = orbclient::Window::new_flags( self.bounds.x() as i32, self.bounds.y() as i32, self.bounds.width() as u32, self.bounds.height() as u32, self.title.as_str(), &flags, ) .expect("WindowBuilder: Could not create an orblient window."); for (family, font) in self.fonts { render_context.register_font(&family, font); } self.shell.window_shells.push(Window::new( self.adapter, render_context, self.request_receiver, window, )); } /// Registers a new font via a string that will identify the font family. pub fn font(mut self, family: impl Into<String>, font_file: &'static [u8]) -> Self { self.fonts.insert(family.into(), font_file); self } /// Creates a new window builder. pub fn
(shell: &'a mut Shell<A>, adapter: A) -> Self { WindowBuilder { adapter, always_on_top: false, borderless: false, bounds: Rectangle::new((0.0, 0.0), (100.0, 75.0)), fonts: HashMap::new(), request_receiver: None, resizeable: false, shell, title: String::default(), } } /// Mark window as resizeable. pub fn resizeable(mut self, resizeable: bool) -> Self { self.resizeable = resizeable; self } /// Register a window request receiver to communicate with the /// window shell via interprocess communication. pub fn request_receiver(mut self, request_receiver: mpsc::Receiver<WindowRequest>) -> Self { self.request_receiver = Some(request_receiver); self } /// Sets the window title. pub fn title(mut self, title: impl Into<String>) -> Self { self.title = title.into(); self } }
new
identifier_name
geometry.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 cssparser::ToCss; use euclid::length::Length; use euclid::num::Zero; use euclid::point::Point2D; use euclid::rect::Rect; use euclid::size::Size2D; use std::default::Default; use std::fmt; use std::i32; use std::ops::{Add, Sub, Neg, Mul, Div, Rem}; use rustc_serialize::{Encoder, Encodable}; // Units for use with euclid::length and euclid::scale_factor. /// A normalized "pixel" at the default resolution for the display. /// /// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it /// should approximate a device-independent reference length. This unit corresponds to Android's /// "density-independent pixel" (dip), Mac OS X's "point", and Windows "device-independent pixel." /// /// The relationship between DevicePixel and ScreenPx is defined by the OS. On most low-dpi /// screens, one ScreenPx is equal to one DevicePixel. But on high-density screens it can be /// some larger number. For example, by default on Apple "retina" displays, one ScreenPx equals /// two DevicePixels. On Android "MDPI" displays, one ScreenPx equals 1.5 device pixels. /// /// The ratio between ScreenPx and DevicePixel for a given display be found by calling /// `servo::windowing::WindowMethods::hidpi_factor`. #[derive(Debug, Copy, Clone)] pub enum ScreenPx {} /// One CSS "px" in the coordinate system of the "initial viewport": /// http://www.w3.org/TR/css-device-adapt/#initial-viewport /// /// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user. This is /// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport /// so it still exactly fits the visible area. /// /// At the default zoom level of 100%, one PagePx is equal to one ScreenPx. However, if the /// document is zoomed in or out then this scale may be larger or smaller. #[derive(RustcEncodable, Debug, Copy, Clone)] pub enum ViewportPx {} /// One CSS "px" in the root coordinate system for the content document. /// /// PagePx is equal to ViewportPx multiplied by a "viewport zoom" factor controlled by the user. /// This is the mobile-style "pinch zoom" that enlarges content without reflowing it. When the /// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size /// as the viewable area. #[derive(RustcEncodable, Debug, Copy, Clone)] pub enum PagePx {} /// The number of app units in a pixel. pub const AU_PER_PX: i32 = 60; // In summary, the hierarchy of pixel units and the factors to convert from one to the next: // // DevicePixel // / hidpi_ratio => ScreenPx // / desktop_zoom => ViewportPx // / pinch_zoom => PagePx // An Au is an "App Unit" and represents 1/60th of a CSS pixel. It was // originally proposed in 2002 as a standard unit of measure in Gecko. // See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info. // // FIXME: Implement Au using Length and ScaleFactor instead of a custom type. #[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Eq, Ord, Deserialize, Serialize)] pub struct Au(pub i32); impl Default for Au { #[inline] fn default() -> Au { Au(0) } } impl Zero for Au { #[inline] fn zero() -> Au { Au(0) } } pub static ZERO_POINT: Point2D<Au> = Point2D { x: Au(0), y: Au(0), }; pub static ZERO_RECT: Rect<Au> = Rect { origin: Point2D { x: Au(0), y: Au(0), }, size: Size2D { width: Au(0), height: Au(0), } }; pub static MAX_RECT: Rect<Au> = Rect { origin: Point2D { x: Au(i32::MIN / 2), y: Au(i32::MIN / 2), }, size: Size2D { width: MAX_AU, height: MAX_AU, } }; pub const MIN_AU: Au = Au(i32::MIN); pub const MAX_AU: Au = Au(i32::MAX); impl Encodable for Au { fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { e.emit_f64(self.to_f64_px()) } } impl fmt::Debug for Au { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}px", self.to_f64_px()) } } impl ToCss for Au { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}px", self.to_f64_px()) } } impl Add for Au { type Output = Au; #[inline] fn add(self, other: Au) -> Au { Au(self.0.wrapping_add(other.0)) } } impl Sub for Au { type Output = Au; #[inline] fn sub(self, other: Au) -> Au { Au(self.0.wrapping_sub(other.0)) } } impl Mul<i32> for Au { type Output = Au; #[inline] fn mul(self, other: i32) -> Au { Au(self.0.wrapping_mul(other)) } } impl Div<i32> for Au { type Output = Au; #[inline] fn div(self, other: i32) -> Au { Au(self.0 / other) } } impl Rem<i32> for Au { type Output = Au; #[inline] fn rem(self, other: i32) -> Au { Au(self.0 % other) } } impl Neg for Au { type Output = Au; #[inline] fn neg(self) -> Au { Au(-self.0) } } impl Au { /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs! #[inline] pub fn new(value: i32) -> Au { Au(value) } #[inline] pub fn scale_by(self, factor: f32) -> Au { Au(((self.0 as f32) * factor) as i32) } #[inline] pub fn from_px(px: i32) -> Au { Au((px * AU_PER_PX) as i32) } #[inline] pub fn from_page_px(px: Length<PagePx, f32>) -> Au { Au((px.get() * (AU_PER_PX as f32)) as i32) } /// Rounds this app unit down to the pixel towards zero and returns it. #[inline] pub fn to_px(self) -> i32 { self.0 / AU_PER_PX } /// Rounds this app unit down to the previous (left or top) pixel and returns it. #[inline] pub fn to_prev_px(self) -> i32 { ((self.0 as f64) / (AU_PER_PX as f64)).floor() as i32 } /// Rounds this app unit up to the next (right or bottom) pixel and returns it. #[inline] pub fn to_next_px(self) -> i32 { ((self.0 as f64) / (AU_PER_PX as f64)).ceil() as i32 } #[inline] pub fn to_nearest_px(self) -> i32 { ((self.0 as f64) / (AU_PER_PX as f64)).round() as i32 } #[inline] pub fn to_nearest_pixel(self, pixels_per_px: f32) -> f32 { ((self.0 as f32) / (AU_PER_PX as f32) * pixels_per_px).round() / pixels_per_px } #[inline] pub fn to_f32_px(self) -> f32 { (self.0 as f32) / (AU_PER_PX as f32) } #[inline] pub fn to_f64_px(self) -> f64 { (self.0 as f64) / (AU_PER_PX as f64) } #[inline] pub fn to_snapped(self) -> Au { let res = self.0 % AU_PER_PX; return if res >= 30i32 { return Au(self.0 - res + AU_PER_PX) } else { return Au(self.0 - res) }; } #[inline] pub fn from_f32_px(px: f32) -> Au { Au((px * (AU_PER_PX as f32)) as i32) } #[inline] pub fn from_pt(pt: f64) -> Au { Au::from_f64_px(pt_to_px(pt)) } #[inline] pub fn from_f64_px(px: f64) -> Au { Au((px * (AU_PER_PX as f64)) as i32) } } // assumes 72 points per inch, and 96 px per inch pub fn pt_to_px(pt: f64) -> f64 { pt / 72. * 96. } // assumes 72 points per inch, and 96 px per inch pub fn px_to_pt(px: f64) -> f64 { px / 96. * 72. } /// Returns true if the rect contains the given point. Points on the top or left sides of the rect /// are considered inside the rectangle, while points on the right or bottom sides of the rect are /// not considered inside the rectangle. pub fn
<T: PartialOrd + Add<T, Output=T>>(rect: Rect<T>, point: Point2D<T>) -> bool { point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width && point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height } /// A helper function to convert a rect of `f32` pixels to a rect of app units. pub fn f32_rect_to_au_rect(rect: Rect<f32>) -> Rect<Au> { Rect::new(Point2D::new(Au::from_f32_px(rect.origin.x), Au::from_f32_px(rect.origin.y)), Size2D::new(Au::from_f32_px(rect.size.width), Au::from_f32_px(rect.size.height))) } /// A helper function to convert a rect of `Au` pixels to a rect of f32 units. pub fn au_rect_to_f32_rect(rect: Rect<Au>) -> Rect<f32> { Rect::new(Point2D::new(rect.origin.x.to_f32_px(), rect.origin.y.to_f32_px()), Size2D::new(rect.size.width.to_f32_px(), rect.size.height.to_f32_px())) }
rect_contains_point
identifier_name
geometry.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 cssparser::ToCss; use euclid::length::Length; use euclid::num::Zero; use euclid::point::Point2D; use euclid::rect::Rect; use euclid::size::Size2D; use std::default::Default; use std::fmt; use std::i32; use std::ops::{Add, Sub, Neg, Mul, Div, Rem}; use rustc_serialize::{Encoder, Encodable}; // Units for use with euclid::length and euclid::scale_factor. /// A normalized "pixel" at the default resolution for the display. /// /// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it /// should approximate a device-independent reference length. This unit corresponds to Android's /// "density-independent pixel" (dip), Mac OS X's "point", and Windows "device-independent pixel." /// /// The relationship between DevicePixel and ScreenPx is defined by the OS. On most low-dpi /// screens, one ScreenPx is equal to one DevicePixel. But on high-density screens it can be /// some larger number. For example, by default on Apple "retina" displays, one ScreenPx equals /// two DevicePixels. On Android "MDPI" displays, one ScreenPx equals 1.5 device pixels. /// /// The ratio between ScreenPx and DevicePixel for a given display be found by calling /// `servo::windowing::WindowMethods::hidpi_factor`. #[derive(Debug, Copy, Clone)] pub enum ScreenPx {} /// One CSS "px" in the coordinate system of the "initial viewport": /// http://www.w3.org/TR/css-device-adapt/#initial-viewport /// /// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user. This is /// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport /// so it still exactly fits the visible area. /// /// At the default zoom level of 100%, one PagePx is equal to one ScreenPx. However, if the /// document is zoomed in or out then this scale may be larger or smaller. #[derive(RustcEncodable, Debug, Copy, Clone)] pub enum ViewportPx {} /// One CSS "px" in the root coordinate system for the content document. /// /// PagePx is equal to ViewportPx multiplied by a "viewport zoom" factor controlled by the user. /// This is the mobile-style "pinch zoom" that enlarges content without reflowing it. When the /// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size /// as the viewable area. #[derive(RustcEncodable, Debug, Copy, Clone)] pub enum PagePx {} /// The number of app units in a pixel. pub const AU_PER_PX: i32 = 60; // In summary, the hierarchy of pixel units and the factors to convert from one to the next: // // DevicePixel // / hidpi_ratio => ScreenPx // / desktop_zoom => ViewportPx // / pinch_zoom => PagePx // An Au is an "App Unit" and represents 1/60th of a CSS pixel. It was // originally proposed in 2002 as a standard unit of measure in Gecko. // See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info. // // FIXME: Implement Au using Length and ScaleFactor instead of a custom type. #[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Eq, Ord, Deserialize, Serialize)] pub struct Au(pub i32); impl Default for Au { #[inline] fn default() -> Au { Au(0) } } impl Zero for Au { #[inline] fn zero() -> Au { Au(0) } } pub static ZERO_POINT: Point2D<Au> = Point2D { x: Au(0), y: Au(0), }; pub static ZERO_RECT: Rect<Au> = Rect {
y: Au(0), }, size: Size2D { width: Au(0), height: Au(0), } }; pub static MAX_RECT: Rect<Au> = Rect { origin: Point2D { x: Au(i32::MIN / 2), y: Au(i32::MIN / 2), }, size: Size2D { width: MAX_AU, height: MAX_AU, } }; pub const MIN_AU: Au = Au(i32::MIN); pub const MAX_AU: Au = Au(i32::MAX); impl Encodable for Au { fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { e.emit_f64(self.to_f64_px()) } } impl fmt::Debug for Au { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}px", self.to_f64_px()) } } impl ToCss for Au { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}px", self.to_f64_px()) } } impl Add for Au { type Output = Au; #[inline] fn add(self, other: Au) -> Au { Au(self.0.wrapping_add(other.0)) } } impl Sub for Au { type Output = Au; #[inline] fn sub(self, other: Au) -> Au { Au(self.0.wrapping_sub(other.0)) } } impl Mul<i32> for Au { type Output = Au; #[inline] fn mul(self, other: i32) -> Au { Au(self.0.wrapping_mul(other)) } } impl Div<i32> for Au { type Output = Au; #[inline] fn div(self, other: i32) -> Au { Au(self.0 / other) } } impl Rem<i32> for Au { type Output = Au; #[inline] fn rem(self, other: i32) -> Au { Au(self.0 % other) } } impl Neg for Au { type Output = Au; #[inline] fn neg(self) -> Au { Au(-self.0) } } impl Au { /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs! #[inline] pub fn new(value: i32) -> Au { Au(value) } #[inline] pub fn scale_by(self, factor: f32) -> Au { Au(((self.0 as f32) * factor) as i32) } #[inline] pub fn from_px(px: i32) -> Au { Au((px * AU_PER_PX) as i32) } #[inline] pub fn from_page_px(px: Length<PagePx, f32>) -> Au { Au((px.get() * (AU_PER_PX as f32)) as i32) } /// Rounds this app unit down to the pixel towards zero and returns it. #[inline] pub fn to_px(self) -> i32 { self.0 / AU_PER_PX } /// Rounds this app unit down to the previous (left or top) pixel and returns it. #[inline] pub fn to_prev_px(self) -> i32 { ((self.0 as f64) / (AU_PER_PX as f64)).floor() as i32 } /// Rounds this app unit up to the next (right or bottom) pixel and returns it. #[inline] pub fn to_next_px(self) -> i32 { ((self.0 as f64) / (AU_PER_PX as f64)).ceil() as i32 } #[inline] pub fn to_nearest_px(self) -> i32 { ((self.0 as f64) / (AU_PER_PX as f64)).round() as i32 } #[inline] pub fn to_nearest_pixel(self, pixels_per_px: f32) -> f32 { ((self.0 as f32) / (AU_PER_PX as f32) * pixels_per_px).round() / pixels_per_px } #[inline] pub fn to_f32_px(self) -> f32 { (self.0 as f32) / (AU_PER_PX as f32) } #[inline] pub fn to_f64_px(self) -> f64 { (self.0 as f64) / (AU_PER_PX as f64) } #[inline] pub fn to_snapped(self) -> Au { let res = self.0 % AU_PER_PX; return if res >= 30i32 { return Au(self.0 - res + AU_PER_PX) } else { return Au(self.0 - res) }; } #[inline] pub fn from_f32_px(px: f32) -> Au { Au((px * (AU_PER_PX as f32)) as i32) } #[inline] pub fn from_pt(pt: f64) -> Au { Au::from_f64_px(pt_to_px(pt)) } #[inline] pub fn from_f64_px(px: f64) -> Au { Au((px * (AU_PER_PX as f64)) as i32) } } // assumes 72 points per inch, and 96 px per inch pub fn pt_to_px(pt: f64) -> f64 { pt / 72. * 96. } // assumes 72 points per inch, and 96 px per inch pub fn px_to_pt(px: f64) -> f64 { px / 96. * 72. } /// Returns true if the rect contains the given point. Points on the top or left sides of the rect /// are considered inside the rectangle, while points on the right or bottom sides of the rect are /// not considered inside the rectangle. pub fn rect_contains_point<T: PartialOrd + Add<T, Output=T>>(rect: Rect<T>, point: Point2D<T>) -> bool { point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width && point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height } /// A helper function to convert a rect of `f32` pixels to a rect of app units. pub fn f32_rect_to_au_rect(rect: Rect<f32>) -> Rect<Au> { Rect::new(Point2D::new(Au::from_f32_px(rect.origin.x), Au::from_f32_px(rect.origin.y)), Size2D::new(Au::from_f32_px(rect.size.width), Au::from_f32_px(rect.size.height))) } /// A helper function to convert a rect of `Au` pixels to a rect of f32 units. pub fn au_rect_to_f32_rect(rect: Rect<Au>) -> Rect<f32> { Rect::new(Point2D::new(rect.origin.x.to_f32_px(), rect.origin.y.to_f32_px()), Size2D::new(rect.size.width.to_f32_px(), rect.size.height.to_f32_px())) }
origin: Point2D { x: Au(0),
random_line_split
geometry.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 cssparser::ToCss; use euclid::length::Length; use euclid::num::Zero; use euclid::point::Point2D; use euclid::rect::Rect; use euclid::size::Size2D; use std::default::Default; use std::fmt; use std::i32; use std::ops::{Add, Sub, Neg, Mul, Div, Rem}; use rustc_serialize::{Encoder, Encodable}; // Units for use with euclid::length and euclid::scale_factor. /// A normalized "pixel" at the default resolution for the display. /// /// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it /// should approximate a device-independent reference length. This unit corresponds to Android's /// "density-independent pixel" (dip), Mac OS X's "point", and Windows "device-independent pixel." /// /// The relationship between DevicePixel and ScreenPx is defined by the OS. On most low-dpi /// screens, one ScreenPx is equal to one DevicePixel. But on high-density screens it can be /// some larger number. For example, by default on Apple "retina" displays, one ScreenPx equals /// two DevicePixels. On Android "MDPI" displays, one ScreenPx equals 1.5 device pixels. /// /// The ratio between ScreenPx and DevicePixel for a given display be found by calling /// `servo::windowing::WindowMethods::hidpi_factor`. #[derive(Debug, Copy, Clone)] pub enum ScreenPx {} /// One CSS "px" in the coordinate system of the "initial viewport": /// http://www.w3.org/TR/css-device-adapt/#initial-viewport /// /// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user. This is /// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport /// so it still exactly fits the visible area. /// /// At the default zoom level of 100%, one PagePx is equal to one ScreenPx. However, if the /// document is zoomed in or out then this scale may be larger or smaller. #[derive(RustcEncodable, Debug, Copy, Clone)] pub enum ViewportPx {} /// One CSS "px" in the root coordinate system for the content document. /// /// PagePx is equal to ViewportPx multiplied by a "viewport zoom" factor controlled by the user. /// This is the mobile-style "pinch zoom" that enlarges content without reflowing it. When the /// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size /// as the viewable area. #[derive(RustcEncodable, Debug, Copy, Clone)] pub enum PagePx {} /// The number of app units in a pixel. pub const AU_PER_PX: i32 = 60; // In summary, the hierarchy of pixel units and the factors to convert from one to the next: // // DevicePixel // / hidpi_ratio => ScreenPx // / desktop_zoom => ViewportPx // / pinch_zoom => PagePx // An Au is an "App Unit" and represents 1/60th of a CSS pixel. It was // originally proposed in 2002 as a standard unit of measure in Gecko. // See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info. // // FIXME: Implement Au using Length and ScaleFactor instead of a custom type. #[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Eq, Ord, Deserialize, Serialize)] pub struct Au(pub i32); impl Default for Au { #[inline] fn default() -> Au { Au(0) } } impl Zero for Au { #[inline] fn zero() -> Au { Au(0) } } pub static ZERO_POINT: Point2D<Au> = Point2D { x: Au(0), y: Au(0), }; pub static ZERO_RECT: Rect<Au> = Rect { origin: Point2D { x: Au(0), y: Au(0), }, size: Size2D { width: Au(0), height: Au(0), } }; pub static MAX_RECT: Rect<Au> = Rect { origin: Point2D { x: Au(i32::MIN / 2), y: Au(i32::MIN / 2), }, size: Size2D { width: MAX_AU, height: MAX_AU, } }; pub const MIN_AU: Au = Au(i32::MIN); pub const MAX_AU: Au = Au(i32::MAX); impl Encodable for Au { fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { e.emit_f64(self.to_f64_px()) } } impl fmt::Debug for Au { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}px", self.to_f64_px()) } } impl ToCss for Au { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}px", self.to_f64_px()) } } impl Add for Au { type Output = Au; #[inline] fn add(self, other: Au) -> Au { Au(self.0.wrapping_add(other.0)) } } impl Sub for Au { type Output = Au; #[inline] fn sub(self, other: Au) -> Au { Au(self.0.wrapping_sub(other.0)) } } impl Mul<i32> for Au { type Output = Au; #[inline] fn mul(self, other: i32) -> Au { Au(self.0.wrapping_mul(other)) } } impl Div<i32> for Au { type Output = Au; #[inline] fn div(self, other: i32) -> Au { Au(self.0 / other) } } impl Rem<i32> for Au { type Output = Au; #[inline] fn rem(self, other: i32) -> Au { Au(self.0 % other) } } impl Neg for Au { type Output = Au; #[inline] fn neg(self) -> Au { Au(-self.0) } } impl Au { /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs! #[inline] pub fn new(value: i32) -> Au { Au(value) } #[inline] pub fn scale_by(self, factor: f32) -> Au { Au(((self.0 as f32) * factor) as i32) } #[inline] pub fn from_px(px: i32) -> Au { Au((px * AU_PER_PX) as i32) } #[inline] pub fn from_page_px(px: Length<PagePx, f32>) -> Au { Au((px.get() * (AU_PER_PX as f32)) as i32) } /// Rounds this app unit down to the pixel towards zero and returns it. #[inline] pub fn to_px(self) -> i32 { self.0 / AU_PER_PX } /// Rounds this app unit down to the previous (left or top) pixel and returns it. #[inline] pub fn to_prev_px(self) -> i32 { ((self.0 as f64) / (AU_PER_PX as f64)).floor() as i32 } /// Rounds this app unit up to the next (right or bottom) pixel and returns it. #[inline] pub fn to_next_px(self) -> i32 { ((self.0 as f64) / (AU_PER_PX as f64)).ceil() as i32 } #[inline] pub fn to_nearest_px(self) -> i32 { ((self.0 as f64) / (AU_PER_PX as f64)).round() as i32 } #[inline] pub fn to_nearest_pixel(self, pixels_per_px: f32) -> f32 { ((self.0 as f32) / (AU_PER_PX as f32) * pixels_per_px).round() / pixels_per_px } #[inline] pub fn to_f32_px(self) -> f32 { (self.0 as f32) / (AU_PER_PX as f32) } #[inline] pub fn to_f64_px(self) -> f64 { (self.0 as f64) / (AU_PER_PX as f64) } #[inline] pub fn to_snapped(self) -> Au { let res = self.0 % AU_PER_PX; return if res >= 30i32 { return Au(self.0 - res + AU_PER_PX) } else
; } #[inline] pub fn from_f32_px(px: f32) -> Au { Au((px * (AU_PER_PX as f32)) as i32) } #[inline] pub fn from_pt(pt: f64) -> Au { Au::from_f64_px(pt_to_px(pt)) } #[inline] pub fn from_f64_px(px: f64) -> Au { Au((px * (AU_PER_PX as f64)) as i32) } } // assumes 72 points per inch, and 96 px per inch pub fn pt_to_px(pt: f64) -> f64 { pt / 72. * 96. } // assumes 72 points per inch, and 96 px per inch pub fn px_to_pt(px: f64) -> f64 { px / 96. * 72. } /// Returns true if the rect contains the given point. Points on the top or left sides of the rect /// are considered inside the rectangle, while points on the right or bottom sides of the rect are /// not considered inside the rectangle. pub fn rect_contains_point<T: PartialOrd + Add<T, Output=T>>(rect: Rect<T>, point: Point2D<T>) -> bool { point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width && point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height } /// A helper function to convert a rect of `f32` pixels to a rect of app units. pub fn f32_rect_to_au_rect(rect: Rect<f32>) -> Rect<Au> { Rect::new(Point2D::new(Au::from_f32_px(rect.origin.x), Au::from_f32_px(rect.origin.y)), Size2D::new(Au::from_f32_px(rect.size.width), Au::from_f32_px(rect.size.height))) } /// A helper function to convert a rect of `Au` pixels to a rect of f32 units. pub fn au_rect_to_f32_rect(rect: Rect<Au>) -> Rect<f32> { Rect::new(Point2D::new(rect.origin.x.to_f32_px(), rect.origin.y.to_f32_px()), Size2D::new(rect.size.width.to_f32_px(), rect.size.height.to_f32_px())) }
{ return Au(self.0 - res) }
conditional_block
geometry.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 cssparser::ToCss; use euclid::length::Length; use euclid::num::Zero; use euclid::point::Point2D; use euclid::rect::Rect; use euclid::size::Size2D; use std::default::Default; use std::fmt; use std::i32; use std::ops::{Add, Sub, Neg, Mul, Div, Rem}; use rustc_serialize::{Encoder, Encodable}; // Units for use with euclid::length and euclid::scale_factor. /// A normalized "pixel" at the default resolution for the display. /// /// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it /// should approximate a device-independent reference length. This unit corresponds to Android's /// "density-independent pixel" (dip), Mac OS X's "point", and Windows "device-independent pixel." /// /// The relationship between DevicePixel and ScreenPx is defined by the OS. On most low-dpi /// screens, one ScreenPx is equal to one DevicePixel. But on high-density screens it can be /// some larger number. For example, by default on Apple "retina" displays, one ScreenPx equals /// two DevicePixels. On Android "MDPI" displays, one ScreenPx equals 1.5 device pixels. /// /// The ratio between ScreenPx and DevicePixel for a given display be found by calling /// `servo::windowing::WindowMethods::hidpi_factor`. #[derive(Debug, Copy, Clone)] pub enum ScreenPx {} /// One CSS "px" in the coordinate system of the "initial viewport": /// http://www.w3.org/TR/css-device-adapt/#initial-viewport /// /// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user. This is /// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport /// so it still exactly fits the visible area. /// /// At the default zoom level of 100%, one PagePx is equal to one ScreenPx. However, if the /// document is zoomed in or out then this scale may be larger or smaller. #[derive(RustcEncodable, Debug, Copy, Clone)] pub enum ViewportPx {} /// One CSS "px" in the root coordinate system for the content document. /// /// PagePx is equal to ViewportPx multiplied by a "viewport zoom" factor controlled by the user. /// This is the mobile-style "pinch zoom" that enlarges content without reflowing it. When the /// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size /// as the viewable area. #[derive(RustcEncodable, Debug, Copy, Clone)] pub enum PagePx {} /// The number of app units in a pixel. pub const AU_PER_PX: i32 = 60; // In summary, the hierarchy of pixel units and the factors to convert from one to the next: // // DevicePixel // / hidpi_ratio => ScreenPx // / desktop_zoom => ViewportPx // / pinch_zoom => PagePx // An Au is an "App Unit" and represents 1/60th of a CSS pixel. It was // originally proposed in 2002 as a standard unit of measure in Gecko. // See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info. // // FIXME: Implement Au using Length and ScaleFactor instead of a custom type. #[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Eq, Ord, Deserialize, Serialize)] pub struct Au(pub i32); impl Default for Au { #[inline] fn default() -> Au { Au(0) } } impl Zero for Au { #[inline] fn zero() -> Au { Au(0) } } pub static ZERO_POINT: Point2D<Au> = Point2D { x: Au(0), y: Au(0), }; pub static ZERO_RECT: Rect<Au> = Rect { origin: Point2D { x: Au(0), y: Au(0), }, size: Size2D { width: Au(0), height: Au(0), } }; pub static MAX_RECT: Rect<Au> = Rect { origin: Point2D { x: Au(i32::MIN / 2), y: Au(i32::MIN / 2), }, size: Size2D { width: MAX_AU, height: MAX_AU, } }; pub const MIN_AU: Au = Au(i32::MIN); pub const MAX_AU: Au = Au(i32::MAX); impl Encodable for Au { fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { e.emit_f64(self.to_f64_px()) } } impl fmt::Debug for Au { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}px", self.to_f64_px()) } } impl ToCss for Au { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}px", self.to_f64_px()) } } impl Add for Au { type Output = Au; #[inline] fn add(self, other: Au) -> Au { Au(self.0.wrapping_add(other.0)) } } impl Sub for Au { type Output = Au; #[inline] fn sub(self, other: Au) -> Au { Au(self.0.wrapping_sub(other.0)) } } impl Mul<i32> for Au { type Output = Au; #[inline] fn mul(self, other: i32) -> Au { Au(self.0.wrapping_mul(other)) } } impl Div<i32> for Au { type Output = Au; #[inline] fn div(self, other: i32) -> Au { Au(self.0 / other) } } impl Rem<i32> for Au { type Output = Au; #[inline] fn rem(self, other: i32) -> Au { Au(self.0 % other) } } impl Neg for Au { type Output = Au; #[inline] fn neg(self) -> Au { Au(-self.0) } } impl Au { /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs! #[inline] pub fn new(value: i32) -> Au { Au(value) } #[inline] pub fn scale_by(self, factor: f32) -> Au { Au(((self.0 as f32) * factor) as i32) } #[inline] pub fn from_px(px: i32) -> Au { Au((px * AU_PER_PX) as i32) } #[inline] pub fn from_page_px(px: Length<PagePx, f32>) -> Au { Au((px.get() * (AU_PER_PX as f32)) as i32) } /// Rounds this app unit down to the pixel towards zero and returns it. #[inline] pub fn to_px(self) -> i32
/// Rounds this app unit down to the previous (left or top) pixel and returns it. #[inline] pub fn to_prev_px(self) -> i32 { ((self.0 as f64) / (AU_PER_PX as f64)).floor() as i32 } /// Rounds this app unit up to the next (right or bottom) pixel and returns it. #[inline] pub fn to_next_px(self) -> i32 { ((self.0 as f64) / (AU_PER_PX as f64)).ceil() as i32 } #[inline] pub fn to_nearest_px(self) -> i32 { ((self.0 as f64) / (AU_PER_PX as f64)).round() as i32 } #[inline] pub fn to_nearest_pixel(self, pixels_per_px: f32) -> f32 { ((self.0 as f32) / (AU_PER_PX as f32) * pixels_per_px).round() / pixels_per_px } #[inline] pub fn to_f32_px(self) -> f32 { (self.0 as f32) / (AU_PER_PX as f32) } #[inline] pub fn to_f64_px(self) -> f64 { (self.0 as f64) / (AU_PER_PX as f64) } #[inline] pub fn to_snapped(self) -> Au { let res = self.0 % AU_PER_PX; return if res >= 30i32 { return Au(self.0 - res + AU_PER_PX) } else { return Au(self.0 - res) }; } #[inline] pub fn from_f32_px(px: f32) -> Au { Au((px * (AU_PER_PX as f32)) as i32) } #[inline] pub fn from_pt(pt: f64) -> Au { Au::from_f64_px(pt_to_px(pt)) } #[inline] pub fn from_f64_px(px: f64) -> Au { Au((px * (AU_PER_PX as f64)) as i32) } } // assumes 72 points per inch, and 96 px per inch pub fn pt_to_px(pt: f64) -> f64 { pt / 72. * 96. } // assumes 72 points per inch, and 96 px per inch pub fn px_to_pt(px: f64) -> f64 { px / 96. * 72. } /// Returns true if the rect contains the given point. Points on the top or left sides of the rect /// are considered inside the rectangle, while points on the right or bottom sides of the rect are /// not considered inside the rectangle. pub fn rect_contains_point<T: PartialOrd + Add<T, Output=T>>(rect: Rect<T>, point: Point2D<T>) -> bool { point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width && point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height } /// A helper function to convert a rect of `f32` pixels to a rect of app units. pub fn f32_rect_to_au_rect(rect: Rect<f32>) -> Rect<Au> { Rect::new(Point2D::new(Au::from_f32_px(rect.origin.x), Au::from_f32_px(rect.origin.y)), Size2D::new(Au::from_f32_px(rect.size.width), Au::from_f32_px(rect.size.height))) } /// A helper function to convert a rect of `Au` pixels to a rect of f32 units. pub fn au_rect_to_f32_rect(rect: Rect<Au>) -> Rect<f32> { Rect::new(Point2D::new(rect.origin.x.to_f32_px(), rect.origin.y.to_f32_px()), Size2D::new(rect.size.width.to_f32_px(), rect.size.height.to_f32_px())) }
{ self.0 / AU_PER_PX }
identifier_body
util.rs
/* * Copyright 2020 Clint Byrum * * 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 crate::codec::{Packet, PacketMagic}; use crate::constants::*; use bytes::{Buf, Bytes};
} else if input[0] == b'1' { true } else { false } } pub fn new_res(ptype: u32, data: Bytes) -> Packet { Packet { magic: PacketMagic::RES, ptype: ptype, psize: data.len() as u32, data: data, } } pub fn new_req(ptype: u32, data: Bytes) -> Packet { Packet { magic: PacketMagic::REQ, ptype: ptype, psize: data.len() as u32, data: data, } } pub fn next_field(buf: &mut Bytes) -> Bytes { match buf[..].iter().position(|b| *b == b'\0') { Some(null_pos) => { let value = buf.split_to(null_pos); buf.advance(1); value } None => { let buflen = buf.len(); buf.split_to(buflen) } } } pub fn no_response() -> Packet { Packet { magic: PacketMagic::TEXT, ptype: ADMIN_RESPONSE, psize: 0, data: Bytes::new(), } }
pub fn bytes2bool(input: &Bytes) -> bool { if input.len() != 1 { false
random_line_split
util.rs
/* * Copyright 2020 Clint Byrum * * 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 crate::codec::{Packet, PacketMagic}; use crate::constants::*; use bytes::{Buf, Bytes}; pub fn bytes2bool(input: &Bytes) -> bool { if input.len()!= 1 { false } else if input[0] == b'1' { true } else { false } } pub fn new_res(ptype: u32, data: Bytes) -> Packet { Packet { magic: PacketMagic::RES, ptype: ptype, psize: data.len() as u32, data: data, } } pub fn new_req(ptype: u32, data: Bytes) -> Packet { Packet { magic: PacketMagic::REQ, ptype: ptype, psize: data.len() as u32, data: data, } } pub fn next_field(buf: &mut Bytes) -> Bytes { match buf[..].iter().position(|b| *b == b'\0') { Some(null_pos) => { let value = buf.split_to(null_pos); buf.advance(1); value } None => { let buflen = buf.len(); buf.split_to(buflen) } } } pub fn no_response() -> Packet
{ Packet { magic: PacketMagic::TEXT, ptype: ADMIN_RESPONSE, psize: 0, data: Bytes::new(), } }
identifier_body
util.rs
/* * Copyright 2020 Clint Byrum * * 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 crate::codec::{Packet, PacketMagic}; use crate::constants::*; use bytes::{Buf, Bytes}; pub fn bytes2bool(input: &Bytes) -> bool { if input.len()!= 1 { false } else if input[0] == b'1' { true } else { false } } pub fn new_res(ptype: u32, data: Bytes) -> Packet { Packet { magic: PacketMagic::RES, ptype: ptype, psize: data.len() as u32, data: data, } } pub fn
(ptype: u32, data: Bytes) -> Packet { Packet { magic: PacketMagic::REQ, ptype: ptype, psize: data.len() as u32, data: data, } } pub fn next_field(buf: &mut Bytes) -> Bytes { match buf[..].iter().position(|b| *b == b'\0') { Some(null_pos) => { let value = buf.split_to(null_pos); buf.advance(1); value } None => { let buflen = buf.len(); buf.split_to(buflen) } } } pub fn no_response() -> Packet { Packet { magic: PacketMagic::TEXT, ptype: ADMIN_RESPONSE, psize: 0, data: Bytes::new(), } }
new_req
identifier_name
messageevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::MessageEventBinding; use dom::bindings::codegen::Bindings::MessageEventBinding::MessageEventMethods; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::bindings::trace::RootedTraceableBox; use dom::event::Event; use dom::eventtarget::EventTarget; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use js::jsapi::{HandleValue, Heap, JSContext}; use js::jsval::JSVal; use servo_atoms::Atom; #[dom_struct] pub struct MessageEvent { event: Event, data: Heap<JSVal>, origin: DOMString, lastEventId: DOMString, } impl MessageEvent { pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<MessageEvent> { MessageEvent::new_initialized(global, HandleValue::undefined(), DOMString::new(), DOMString::new()) } pub fn new_initialized(global: &GlobalScope, data: HandleValue, origin: DOMString, lastEventId: DOMString) -> DomRoot<MessageEvent> { let ev = Box::new(MessageEvent { event: Event::new_inherited(), data: Heap::default(), origin: origin, lastEventId: lastEventId, }); let ev = reflect_dom_object(ev, global, MessageEventBinding::Wrap); ev.data.set(data.get()); ev } pub fn new(global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, data: HandleValue, origin: DOMString, lastEventId: DOMString) -> DomRoot<MessageEvent> { let ev = MessageEvent::new_initialized(global, data, origin, lastEventId); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } pub fn Constructor(global: &GlobalScope, type_: DOMString, init: RootedTraceableBox<MessageEventBinding::MessageEventInit>) -> Fallible<DomRoot<MessageEvent>> { let ev = MessageEvent::new(global, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, init.data.handle(), init.origin.clone(), init.lastEventId.clone()); Ok(ev) } } impl MessageEvent { pub fn dispatch_jsval(target: &EventTarget, scope: &GlobalScope, message: HandleValue) { let messageevent = MessageEvent::new( scope, atom!("message"), false, false, message, DOMString::new(), DOMString::new()); messageevent.upcast::<Event>().fire(target); } } impl MessageEventMethods for MessageEvent { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-messageevent-data unsafe fn Data(&self, _cx: *mut JSContext) -> JSVal { self.data.get() } // https://html.spec.whatwg.org/multipage/#dom-messageevent-origin fn Origin(&self) -> DOMString { self.origin.clone() } // https://html.spec.whatwg.org/multipage/#dom-messageevent-lasteventid fn LastEventId(&self) -> DOMString { self.lastEventId.clone() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted()
} }
random_line_split
messageevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::MessageEventBinding; use dom::bindings::codegen::Bindings::MessageEventBinding::MessageEventMethods; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::bindings::trace::RootedTraceableBox; use dom::event::Event; use dom::eventtarget::EventTarget; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use js::jsapi::{HandleValue, Heap, JSContext}; use js::jsval::JSVal; use servo_atoms::Atom; #[dom_struct] pub struct MessageEvent { event: Event, data: Heap<JSVal>, origin: DOMString, lastEventId: DOMString, } impl MessageEvent { pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<MessageEvent> { MessageEvent::new_initialized(global, HandleValue::undefined(), DOMString::new(), DOMString::new()) } pub fn new_initialized(global: &GlobalScope, data: HandleValue, origin: DOMString, lastEventId: DOMString) -> DomRoot<MessageEvent> { let ev = Box::new(MessageEvent { event: Event::new_inherited(), data: Heap::default(), origin: origin, lastEventId: lastEventId, }); let ev = reflect_dom_object(ev, global, MessageEventBinding::Wrap); ev.data.set(data.get()); ev } pub fn new(global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, data: HandleValue, origin: DOMString, lastEventId: DOMString) -> DomRoot<MessageEvent> { let ev = MessageEvent::new_initialized(global, data, origin, lastEventId); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } pub fn Constructor(global: &GlobalScope, type_: DOMString, init: RootedTraceableBox<MessageEventBinding::MessageEventInit>) -> Fallible<DomRoot<MessageEvent>> { let ev = MessageEvent::new(global, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, init.data.handle(), init.origin.clone(), init.lastEventId.clone()); Ok(ev) } } impl MessageEvent { pub fn dispatch_jsval(target: &EventTarget, scope: &GlobalScope, message: HandleValue) { let messageevent = MessageEvent::new( scope, atom!("message"), false, false, message, DOMString::new(), DOMString::new()); messageevent.upcast::<Event>().fire(target); } } impl MessageEventMethods for MessageEvent { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-messageevent-data unsafe fn Data(&self, _cx: *mut JSContext) -> JSVal { self.data.get() } // https://html.spec.whatwg.org/multipage/#dom-messageevent-origin fn Origin(&self) -> DOMString { self.origin.clone() } // https://html.spec.whatwg.org/multipage/#dom-messageevent-lasteventid fn LastEventId(&self) -> DOMString
// https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
{ self.lastEventId.clone() }
identifier_body
messageevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::MessageEventBinding; use dom::bindings::codegen::Bindings::MessageEventBinding::MessageEventMethods; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::bindings::trace::RootedTraceableBox; use dom::event::Event; use dom::eventtarget::EventTarget; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use js::jsapi::{HandleValue, Heap, JSContext}; use js::jsval::JSVal; use servo_atoms::Atom; #[dom_struct] pub struct
{ event: Event, data: Heap<JSVal>, origin: DOMString, lastEventId: DOMString, } impl MessageEvent { pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<MessageEvent> { MessageEvent::new_initialized(global, HandleValue::undefined(), DOMString::new(), DOMString::new()) } pub fn new_initialized(global: &GlobalScope, data: HandleValue, origin: DOMString, lastEventId: DOMString) -> DomRoot<MessageEvent> { let ev = Box::new(MessageEvent { event: Event::new_inherited(), data: Heap::default(), origin: origin, lastEventId: lastEventId, }); let ev = reflect_dom_object(ev, global, MessageEventBinding::Wrap); ev.data.set(data.get()); ev } pub fn new(global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, data: HandleValue, origin: DOMString, lastEventId: DOMString) -> DomRoot<MessageEvent> { let ev = MessageEvent::new_initialized(global, data, origin, lastEventId); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } pub fn Constructor(global: &GlobalScope, type_: DOMString, init: RootedTraceableBox<MessageEventBinding::MessageEventInit>) -> Fallible<DomRoot<MessageEvent>> { let ev = MessageEvent::new(global, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, init.data.handle(), init.origin.clone(), init.lastEventId.clone()); Ok(ev) } } impl MessageEvent { pub fn dispatch_jsval(target: &EventTarget, scope: &GlobalScope, message: HandleValue) { let messageevent = MessageEvent::new( scope, atom!("message"), false, false, message, DOMString::new(), DOMString::new()); messageevent.upcast::<Event>().fire(target); } } impl MessageEventMethods for MessageEvent { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-messageevent-data unsafe fn Data(&self, _cx: *mut JSContext) -> JSVal { self.data.get() } // https://html.spec.whatwg.org/multipage/#dom-messageevent-origin fn Origin(&self) -> DOMString { self.origin.clone() } // https://html.spec.whatwg.org/multipage/#dom-messageevent-lasteventid fn LastEventId(&self) -> DOMString { self.lastEventId.clone() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
MessageEvent
identifier_name
window.rs
use std::fmt; use std::ops::Range; use std::iter::IntoIterator; use types::{State, BoardView}; use board::Board; #[derive(Clone, Copy)] pub struct Window<'a> { pub min_x: i32, pub min_y: i32, pub max_x: i32, pub max_y: i32, board: &'a Board } impl<'a> Window<'a> { pub fn new(board: &'a Board, min_x: i32, min_y: i32, max_x: i32, max_y: i32) -> Window<'a> { Window { min_x: min_x, min_y: min_y, max_x: max_x, max_y: max_y, board: board } } } impl<'a> IntoIterator for Window<'a> { type Item = (i32, i32, State); type IntoIter = Iter<'a>; fn into_iter(self) -> Iter<'a> { Iter { window: self, x: self.min_x, // TODO: Change to self.min_y...self.max_y when available ys: self.min_y..self.max_y + 1 } } } impl<'a> fmt::Display for Window<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { // Change this to self.min_x...self.max_x when available for x in self.min_x..self.max_x + 1 { for y in self.min_y..self.max_y + 1 { let c = match self.board.cell_state(x, y) { State::Alive => 'X', State::Dead => '_' }; try!(fmt::Write::write_char(fmt, c)); } if x!= self.max_x { try!(fmt::Write::write_char(fmt, '\n')); } } Ok(()) } } pub struct Iter<'a> { window: Window<'a>, x: i32, ys: Range<i32>, } impl<'a> Iterator for Iter<'a> { type Item = (i32, i32, State); fn next(&mut self) -> Option<(i32, i32, State)>
} impl<'a> BoardView for Window<'a> { fn cell_state(&self, x: i32, y: i32) -> State { self.board.cell_state(x, y) } fn as_window<'b>(&'b self) -> Window<'b> { *self } fn iter<'b>(&'b self) -> Iter<'b> { Iter { window: *self, x: self.min_x, ys: self.min_y..self.max_y + 1 } } fn window<'b>(&'b self, min_x: i32, min_y: i32, max_x: i32, max_y: i32) -> Window<'b> { Window { min_x: min_x, min_y: min_y, max_x: max_x, max_y: max_y, board: self.board } } fn window_offsets<'b>(&'b self, offset_x: i32, offset_y: i32, dim_x: i32, dim_y: i32) -> Window<'b> { Window { min_x: self.min_x + offset_x, min_y: self.min_y + offset_y, max_x: self.min_x + offset_x + dim_x, max_y: self.min_y + offset_y + dim_y, board: self.board } } }
{ loop { if self.x == self.window.max_x + 1 { return None; } match self.ys.next() { Some(y) => { let state = self.window.cell_state(self.x, y); return Some((self.x, y, state)) }, None => { self.ys = 0..self.window.max_y + 1; self.x += 1; } } } }
identifier_body
window.rs
use std::fmt; use std::ops::Range; use std::iter::IntoIterator; use types::{State, BoardView}; use board::Board; #[derive(Clone, Copy)] pub struct Window<'a> { pub min_x: i32, pub min_y: i32, pub max_x: i32, pub max_y: i32, board: &'a Board } impl<'a> Window<'a> { pub fn new(board: &'a Board, min_x: i32, min_y: i32, max_x: i32, max_y: i32) -> Window<'a> { Window { min_x: min_x, min_y: min_y, max_x: max_x, max_y: max_y, board: board } } } impl<'a> IntoIterator for Window<'a> { type Item = (i32, i32, State); type IntoIter = Iter<'a>; fn into_iter(self) -> Iter<'a> { Iter { window: self, x: self.min_x, // TODO: Change to self.min_y...self.max_y when available ys: self.min_y..self.max_y + 1 } } } impl<'a> fmt::Display for Window<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { // Change this to self.min_x...self.max_x when available for x in self.min_x..self.max_x + 1 { for y in self.min_y..self.max_y + 1 { let c = match self.board.cell_state(x, y) { State::Alive => 'X', State::Dead => '_' }; try!(fmt::Write::write_char(fmt, c)); } if x!= self.max_x { try!(fmt::Write::write_char(fmt, '\n')); } } Ok(()) } } pub struct Iter<'a> { window: Window<'a>, x: i32, ys: Range<i32>, } impl<'a> Iterator for Iter<'a> { type Item = (i32, i32, State); fn next(&mut self) -> Option<(i32, i32, State)> { loop {
match self.ys.next() { Some(y) => { let state = self.window.cell_state(self.x, y); return Some((self.x, y, state)) }, None => { self.ys = 0..self.window.max_y + 1; self.x += 1; } } } } } impl<'a> BoardView for Window<'a> { fn cell_state(&self, x: i32, y: i32) -> State { self.board.cell_state(x, y) } fn as_window<'b>(&'b self) -> Window<'b> { *self } fn iter<'b>(&'b self) -> Iter<'b> { Iter { window: *self, x: self.min_x, ys: self.min_y..self.max_y + 1 } } fn window<'b>(&'b self, min_x: i32, min_y: i32, max_x: i32, max_y: i32) -> Window<'b> { Window { min_x: min_x, min_y: min_y, max_x: max_x, max_y: max_y, board: self.board } } fn window_offsets<'b>(&'b self, offset_x: i32, offset_y: i32, dim_x: i32, dim_y: i32) -> Window<'b> { Window { min_x: self.min_x + offset_x, min_y: self.min_y + offset_y, max_x: self.min_x + offset_x + dim_x, max_y: self.min_y + offset_y + dim_y, board: self.board } } }
if self.x == self.window.max_x + 1 { return None; }
random_line_split
window.rs
use std::fmt; use std::ops::Range; use std::iter::IntoIterator; use types::{State, BoardView}; use board::Board; #[derive(Clone, Copy)] pub struct Window<'a> { pub min_x: i32, pub min_y: i32, pub max_x: i32, pub max_y: i32, board: &'a Board } impl<'a> Window<'a> { pub fn new(board: &'a Board, min_x: i32, min_y: i32, max_x: i32, max_y: i32) -> Window<'a> { Window { min_x: min_x, min_y: min_y, max_x: max_x, max_y: max_y, board: board } } } impl<'a> IntoIterator for Window<'a> { type Item = (i32, i32, State); type IntoIter = Iter<'a>; fn into_iter(self) -> Iter<'a> { Iter { window: self, x: self.min_x, // TODO: Change to self.min_y...self.max_y when available ys: self.min_y..self.max_y + 1 } } } impl<'a> fmt::Display for Window<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { // Change this to self.min_x...self.max_x when available for x in self.min_x..self.max_x + 1 { for y in self.min_y..self.max_y + 1 { let c = match self.board.cell_state(x, y) { State::Alive => 'X', State::Dead => '_' }; try!(fmt::Write::write_char(fmt, c)); } if x!= self.max_x { try!(fmt::Write::write_char(fmt, '\n')); } } Ok(()) } } pub struct Iter<'a> { window: Window<'a>, x: i32, ys: Range<i32>, } impl<'a> Iterator for Iter<'a> { type Item = (i32, i32, State); fn next(&mut self) -> Option<(i32, i32, State)> { loop { if self.x == self.window.max_x + 1 { return None; } match self.ys.next() { Some(y) => { let state = self.window.cell_state(self.x, y); return Some((self.x, y, state)) }, None => { self.ys = 0..self.window.max_y + 1; self.x += 1; } } } } } impl<'a> BoardView for Window<'a> { fn cell_state(&self, x: i32, y: i32) -> State { self.board.cell_state(x, y) } fn as_window<'b>(&'b self) -> Window<'b> { *self } fn
<'b>(&'b self) -> Iter<'b> { Iter { window: *self, x: self.min_x, ys: self.min_y..self.max_y + 1 } } fn window<'b>(&'b self, min_x: i32, min_y: i32, max_x: i32, max_y: i32) -> Window<'b> { Window { min_x: min_x, min_y: min_y, max_x: max_x, max_y: max_y, board: self.board } } fn window_offsets<'b>(&'b self, offset_x: i32, offset_y: i32, dim_x: i32, dim_y: i32) -> Window<'b> { Window { min_x: self.min_x + offset_x, min_y: self.min_y + offset_y, max_x: self.min_x + offset_x + dim_x, max_y: self.min_y + offset_y + dim_y, board: self.board } } }
iter
identifier_name
100_doors_unoptimized.rs
// Implements http://rosettacode.org/wiki/100_doors // this is the unoptimized version that performs all 100 // passes, as per the original description of the problem #![feature(core)] use std::iter::range_step_inclusive; #[cfg(not(test))] fn
() { // states for the 100 doors // uses a vector of booleans, // where state==false means the door is closed let mut doors = [false; 100]; solve(&mut doors); for (idx, door) in doors.iter().enumerate() { println!("door {} open: {}", idx+1, door); } } // unoptimized solution for the 100 Doors problem, // performs all 100 passes and mutates the vector with // the states in place fn solve(doors: &mut [bool]) { for pass in 1..101 { for door in range_step_inclusive(pass, 100, pass) { // flip the state of the door doors[door-1] =!doors[door-1] } } } #[test] fn solution() { let mut doors = [false;100]; solve(&mut doors); // test that the doors with index corresponding to // a perfect square are now open for i in 1..11 { assert!(doors[i*i - 1]); } }
main
identifier_name
100_doors_unoptimized.rs
// Implements http://rosettacode.org/wiki/100_doors // this is the unoptimized version that performs all 100 // passes, as per the original description of the problem #![feature(core)] use std::iter::range_step_inclusive; #[cfg(not(test))] fn main() { // states for the 100 doors // uses a vector of booleans, // where state==false means the door is closed let mut doors = [false; 100]; solve(&mut doors); for (idx, door) in doors.iter().enumerate() { println!("door {} open: {}", idx+1, door); } } // unoptimized solution for the 100 Doors problem, // performs all 100 passes and mutates the vector with // the states in place fn solve(doors: &mut [bool]) { for pass in 1..101 { for door in range_step_inclusive(pass, 100, pass) { // flip the state of the door doors[door-1] =!doors[door-1] } } } #[test]
// test that the doors with index corresponding to // a perfect square are now open for i in 1..11 { assert!(doors[i*i - 1]); } }
fn solution() { let mut doors = [false;100]; solve(&mut doors);
random_line_split
100_doors_unoptimized.rs
// Implements http://rosettacode.org/wiki/100_doors // this is the unoptimized version that performs all 100 // passes, as per the original description of the problem #![feature(core)] use std::iter::range_step_inclusive; #[cfg(not(test))] fn main() { // states for the 100 doors // uses a vector of booleans, // where state==false means the door is closed let mut doors = [false; 100]; solve(&mut doors); for (idx, door) in doors.iter().enumerate() { println!("door {} open: {}", idx+1, door); } } // unoptimized solution for the 100 Doors problem, // performs all 100 passes and mutates the vector with // the states in place fn solve(doors: &mut [bool])
#[test] fn solution() { let mut doors = [false;100]; solve(&mut doors); // test that the doors with index corresponding to // a perfect square are now open for i in 1..11 { assert!(doors[i*i - 1]); } }
{ for pass in 1..101 { for door in range_step_inclusive(pass, 100, pass) { // flip the state of the door doors[door-1] = !doors[door-1] } } }
identifier_body
secret.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::fmt; use std::ops::Deref; use std::str::FromStr; use secp256k1::key; use bigint::hash::H256; use {Error}; #[derive(Clone, PartialEq, Eq)] pub struct Secret { inner: H256, } impl fmt::Debug for Secret { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "Secret: 0x{:x}{:x}..{:x}{:x}", self.inner[0], self.inner[1], self.inner[30], self.inner[31]) } } impl Secret { fn from_slice_unchecked(key: &[u8]) -> Self { assert_eq!(32, key.len(), "Caller should provide 32-byte length slice"); let mut h = H256::default(); h.copy_from_slice(&key[0..32]); Secret { inner: h } } pub fn from_slice(key: &[u8]) -> Result<Self, Error> { let secret = key::SecretKey::from_slice(&super::SECP256K1, key)?; Ok(secret.into()) } } impl FromStr for Secret { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let hash = H256::from_str(s).map_err(|e| Error::Custom(format!("{:?}", e)))?; Self::from_slice(&hash) } } impl From<key::SecretKey> for Secret { fn from(key: key::SecretKey) -> Self { Self::from_slice_unchecked(&key[0..32]) } } impl Deref for Secret { type Target = H256; fn deref(&self) -> &Self::Target
}
{ &self.inner }
identifier_body
secret.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::fmt; use std::ops::Deref; use std::str::FromStr; use secp256k1::key; use bigint::hash::H256; use {Error}; #[derive(Clone, PartialEq, Eq)] pub struct Secret { inner: H256, } impl fmt::Debug for Secret { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "Secret: 0x{:x}{:x}..{:x}{:x}", self.inner[0], self.inner[1], self.inner[30], self.inner[31]) } } impl Secret { fn
(key: &[u8]) -> Self { assert_eq!(32, key.len(), "Caller should provide 32-byte length slice"); let mut h = H256::default(); h.copy_from_slice(&key[0..32]); Secret { inner: h } } pub fn from_slice(key: &[u8]) -> Result<Self, Error> { let secret = key::SecretKey::from_slice(&super::SECP256K1, key)?; Ok(secret.into()) } } impl FromStr for Secret { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let hash = H256::from_str(s).map_err(|e| Error::Custom(format!("{:?}", e)))?; Self::from_slice(&hash) } } impl From<key::SecretKey> for Secret { fn from(key: key::SecretKey) -> Self { Self::from_slice_unchecked(&key[0..32]) } } impl Deref for Secret { type Target = H256; fn deref(&self) -> &Self::Target { &self.inner } }
from_slice_unchecked
identifier_name
secret.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::fmt; use std::ops::Deref; use std::str::FromStr; use secp256k1::key; use bigint::hash::H256; use {Error};
impl fmt::Debug for Secret { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "Secret: 0x{:x}{:x}..{:x}{:x}", self.inner[0], self.inner[1], self.inner[30], self.inner[31]) } } impl Secret { fn from_slice_unchecked(key: &[u8]) -> Self { assert_eq!(32, key.len(), "Caller should provide 32-byte length slice"); let mut h = H256::default(); h.copy_from_slice(&key[0..32]); Secret { inner: h } } pub fn from_slice(key: &[u8]) -> Result<Self, Error> { let secret = key::SecretKey::from_slice(&super::SECP256K1, key)?; Ok(secret.into()) } } impl FromStr for Secret { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let hash = H256::from_str(s).map_err(|e| Error::Custom(format!("{:?}", e)))?; Self::from_slice(&hash) } } impl From<key::SecretKey> for Secret { fn from(key: key::SecretKey) -> Self { Self::from_slice_unchecked(&key[0..32]) } } impl Deref for Secret { type Target = H256; fn deref(&self) -> &Self::Target { &self.inner } }
#[derive(Clone, PartialEq, Eq)] pub struct Secret { inner: H256, }
random_line_split
package.rs
use super::module::module_from_declarations; use crate::error::ValidationError; use crate::parser::PackageDecl; use crate::prelude::std_module; use crate::repr::{ModuleIx, ModuleRepr, Package}; use crate::Location; use cranelift_entity::PrimaryMap; use std::collections::HashMap; pub fn package_from_declarations( package_decls: &[PackageDecl], ) -> Result<Package, ValidationError> { let mut pkg = PackageBuilder::new(); for decl in package_decls { match decl { PackageDecl::Module { name, location, decls, } =>
} } Ok(pkg.build()) } pub struct PackageBuilder { name_decls: HashMap<String, (ModuleIx, Option<Location>)>, repr: Package, } impl PackageBuilder { pub fn new() -> Self { let mut repr = Package { names: PrimaryMap::new(), modules: PrimaryMap::new(), }; let mut name_decls = HashMap::new(); repr.names.push("std".to_owned()); let base_ix = repr.modules.push(std_module()); name_decls.insert("std".to_owned(), (base_ix, None)); Self { name_decls, repr } } pub fn introduce_name( &mut self, name: &str, location: Location, ) -> Result<ModuleIx, ValidationError> { if let Some((_, prev_loc)) = self.name_decls.get(name) { match prev_loc { Some(prev_loc) => { Err(ValidationError::NameAlreadyExists { name: name.to_owned(), at_location: location, previous_location: *prev_loc, })?; } None => { Err(ValidationError::Syntax { expected: "non-reserved module name", location: location, })?; } } } let ix = self.repr.names.push(name.to_owned()); self.name_decls .insert(name.to_owned(), (ix, Some(location))); Ok(ix) } pub fn repr(&self) -> &Package { &self.repr } pub fn define_module(&mut self, ix: ModuleIx, mod_repr: ModuleRepr) { assert!(self.repr.names.is_valid(ix)); let pushed_ix = self.repr.modules.push(mod_repr); assert_eq!(ix, pushed_ix); } pub fn build(self) -> Package { self.repr } } #[cfg(test)] mod test { use super::*; use crate::parser::Parser; use crate::Package; fn pkg_(syntax: &str) -> Result<Package, ValidationError> { let mut parser = Parser::new(syntax); let decls = parser.match_package_decls().expect("parses"); package_from_declarations(&decls) } #[test] fn one_empty_mod() { let pkg = pkg_("mod empty {}").expect("valid package"); let empty = pkg.module("empty").expect("mod empty exists"); assert_eq!(empty.name(), "empty"); assert_eq!(empty.datatypes().collect::<Vec<_>>().len(), 0); assert_eq!(empty.functions().collect::<Vec<_>>().len(), 0); } #[test] fn multiple_empty_mod() { let pkg = pkg_("mod empty1 {} mod empty2{}mod\nempty3{//\n}").expect("valid package"); let _ = pkg.module("empty1").expect("mod empty1 exists"); let _ = pkg.module("empty2").expect("mod empty2 exists"); let _ = pkg.module("empty3").expect("mod empty3 exists"); } #[test] fn mod_with_a_type() { let pkg = pkg_("mod foo { type bar = u8; }").expect("valid package"); let foo = pkg.module("foo").expect("mod foo exists"); let _bar = foo.datatype("bar").expect("foo::bar exists"); } #[test] fn no_mod_std_name() { let err = pkg_("mod std {}").err().expect("error package"); assert_eq!( err, ValidationError::Syntax { expected: "non-reserved module name", location: Location { line: 1, column: 0 }, } ); } #[test] fn no_mod_duplicate_name() { let err = pkg_("mod foo {}\nmod foo {}").err().expect("error package"); assert_eq!( err, ValidationError::NameAlreadyExists { name: "foo".to_owned(), at_location: Location { line: 2, column: 0 }, previous_location: Location { line: 1, column: 0 }, } ); } }
{ let module_ix = pkg.introduce_name(name, *location)?; let module_repr = module_from_declarations(pkg.repr(), module_ix, &decls)?; pkg.define_module(module_ix, module_repr); }
conditional_block
package.rs
use super::module::module_from_declarations; use crate::error::ValidationError; use crate::parser::PackageDecl; use crate::prelude::std_module; use crate::repr::{ModuleIx, ModuleRepr, Package}; use crate::Location; use cranelift_entity::PrimaryMap; use std::collections::HashMap; pub fn package_from_declarations( package_decls: &[PackageDecl], ) -> Result<Package, ValidationError> { let mut pkg = PackageBuilder::new(); for decl in package_decls { match decl { PackageDecl::Module { name, location, decls, } => { let module_ix = pkg.introduce_name(name, *location)?; let module_repr = module_from_declarations(pkg.repr(), module_ix, &decls)?; pkg.define_module(module_ix, module_repr); } } } Ok(pkg.build()) } pub struct PackageBuilder { name_decls: HashMap<String, (ModuleIx, Option<Location>)>, repr: Package, } impl PackageBuilder { pub fn new() -> Self { let mut repr = Package { names: PrimaryMap::new(), modules: PrimaryMap::new(), }; let mut name_decls = HashMap::new(); repr.names.push("std".to_owned()); let base_ix = repr.modules.push(std_module()); name_decls.insert("std".to_owned(), (base_ix, None)); Self { name_decls, repr } } pub fn introduce_name( &mut self, name: &str, location: Location, ) -> Result<ModuleIx, ValidationError> { if let Some((_, prev_loc)) = self.name_decls.get(name) { match prev_loc { Some(prev_loc) => { Err(ValidationError::NameAlreadyExists { name: name.to_owned(), at_location: location, previous_location: *prev_loc, })?; } None => { Err(ValidationError::Syntax { expected: "non-reserved module name", location: location, })?; } } } let ix = self.repr.names.push(name.to_owned()); self.name_decls .insert(name.to_owned(), (ix, Some(location))); Ok(ix) } pub fn repr(&self) -> &Package { &self.repr } pub fn define_module(&mut self, ix: ModuleIx, mod_repr: ModuleRepr) { assert!(self.repr.names.is_valid(ix)); let pushed_ix = self.repr.modules.push(mod_repr); assert_eq!(ix, pushed_ix); } pub fn build(self) -> Package { self.repr } } #[cfg(test)] mod test { use super::*; use crate::parser::Parser; use crate::Package; fn pkg_(syntax: &str) -> Result<Package, ValidationError> { let mut parser = Parser::new(syntax); let decls = parser.match_package_decls().expect("parses"); package_from_declarations(&decls) } #[test] fn one_empty_mod() { let pkg = pkg_("mod empty {}").expect("valid package"); let empty = pkg.module("empty").expect("mod empty exists"); assert_eq!(empty.name(), "empty"); assert_eq!(empty.datatypes().collect::<Vec<_>>().len(), 0); assert_eq!(empty.functions().collect::<Vec<_>>().len(), 0); } #[test] fn multiple_empty_mod() { let pkg = pkg_("mod empty1 {} mod empty2{}mod\nempty3{//\n}").expect("valid package"); let _ = pkg.module("empty1").expect("mod empty1 exists"); let _ = pkg.module("empty2").expect("mod empty2 exists"); let _ = pkg.module("empty3").expect("mod empty3 exists"); } #[test] fn mod_with_a_type() { let pkg = pkg_("mod foo { type bar = u8; }").expect("valid package"); let foo = pkg.module("foo").expect("mod foo exists");
#[test] fn no_mod_std_name() { let err = pkg_("mod std {}").err().expect("error package"); assert_eq!( err, ValidationError::Syntax { expected: "non-reserved module name", location: Location { line: 1, column: 0 }, } ); } #[test] fn no_mod_duplicate_name() { let err = pkg_("mod foo {}\nmod foo {}").err().expect("error package"); assert_eq!( err, ValidationError::NameAlreadyExists { name: "foo".to_owned(), at_location: Location { line: 2, column: 0 }, previous_location: Location { line: 1, column: 0 }, } ); } }
let _bar = foo.datatype("bar").expect("foo::bar exists"); }
random_line_split
package.rs
use super::module::module_from_declarations; use crate::error::ValidationError; use crate::parser::PackageDecl; use crate::prelude::std_module; use crate::repr::{ModuleIx, ModuleRepr, Package}; use crate::Location; use cranelift_entity::PrimaryMap; use std::collections::HashMap; pub fn package_from_declarations( package_decls: &[PackageDecl], ) -> Result<Package, ValidationError> { let mut pkg = PackageBuilder::new(); for decl in package_decls { match decl { PackageDecl::Module { name, location, decls, } => { let module_ix = pkg.introduce_name(name, *location)?; let module_repr = module_from_declarations(pkg.repr(), module_ix, &decls)?; pkg.define_module(module_ix, module_repr); } } } Ok(pkg.build()) } pub struct PackageBuilder { name_decls: HashMap<String, (ModuleIx, Option<Location>)>, repr: Package, } impl PackageBuilder { pub fn new() -> Self { let mut repr = Package { names: PrimaryMap::new(), modules: PrimaryMap::new(), }; let mut name_decls = HashMap::new(); repr.names.push("std".to_owned()); let base_ix = repr.modules.push(std_module()); name_decls.insert("std".to_owned(), (base_ix, None)); Self { name_decls, repr } } pub fn introduce_name( &mut self, name: &str, location: Location, ) -> Result<ModuleIx, ValidationError> { if let Some((_, prev_loc)) = self.name_decls.get(name) { match prev_loc { Some(prev_loc) => { Err(ValidationError::NameAlreadyExists { name: name.to_owned(), at_location: location, previous_location: *prev_loc, })?; } None => { Err(ValidationError::Syntax { expected: "non-reserved module name", location: location, })?; } } } let ix = self.repr.names.push(name.to_owned()); self.name_decls .insert(name.to_owned(), (ix, Some(location))); Ok(ix) } pub fn repr(&self) -> &Package
pub fn define_module(&mut self, ix: ModuleIx, mod_repr: ModuleRepr) { assert!(self.repr.names.is_valid(ix)); let pushed_ix = self.repr.modules.push(mod_repr); assert_eq!(ix, pushed_ix); } pub fn build(self) -> Package { self.repr } } #[cfg(test)] mod test { use super::*; use crate::parser::Parser; use crate::Package; fn pkg_(syntax: &str) -> Result<Package, ValidationError> { let mut parser = Parser::new(syntax); let decls = parser.match_package_decls().expect("parses"); package_from_declarations(&decls) } #[test] fn one_empty_mod() { let pkg = pkg_("mod empty {}").expect("valid package"); let empty = pkg.module("empty").expect("mod empty exists"); assert_eq!(empty.name(), "empty"); assert_eq!(empty.datatypes().collect::<Vec<_>>().len(), 0); assert_eq!(empty.functions().collect::<Vec<_>>().len(), 0); } #[test] fn multiple_empty_mod() { let pkg = pkg_("mod empty1 {} mod empty2{}mod\nempty3{//\n}").expect("valid package"); let _ = pkg.module("empty1").expect("mod empty1 exists"); let _ = pkg.module("empty2").expect("mod empty2 exists"); let _ = pkg.module("empty3").expect("mod empty3 exists"); } #[test] fn mod_with_a_type() { let pkg = pkg_("mod foo { type bar = u8; }").expect("valid package"); let foo = pkg.module("foo").expect("mod foo exists"); let _bar = foo.datatype("bar").expect("foo::bar exists"); } #[test] fn no_mod_std_name() { let err = pkg_("mod std {}").err().expect("error package"); assert_eq!( err, ValidationError::Syntax { expected: "non-reserved module name", location: Location { line: 1, column: 0 }, } ); } #[test] fn no_mod_duplicate_name() { let err = pkg_("mod foo {}\nmod foo {}").err().expect("error package"); assert_eq!( err, ValidationError::NameAlreadyExists { name: "foo".to_owned(), at_location: Location { line: 2, column: 0 }, previous_location: Location { line: 1, column: 0 }, } ); } }
{ &self.repr }
identifier_body
package.rs
use super::module::module_from_declarations; use crate::error::ValidationError; use crate::parser::PackageDecl; use crate::prelude::std_module; use crate::repr::{ModuleIx, ModuleRepr, Package}; use crate::Location; use cranelift_entity::PrimaryMap; use std::collections::HashMap; pub fn
( package_decls: &[PackageDecl], ) -> Result<Package, ValidationError> { let mut pkg = PackageBuilder::new(); for decl in package_decls { match decl { PackageDecl::Module { name, location, decls, } => { let module_ix = pkg.introduce_name(name, *location)?; let module_repr = module_from_declarations(pkg.repr(), module_ix, &decls)?; pkg.define_module(module_ix, module_repr); } } } Ok(pkg.build()) } pub struct PackageBuilder { name_decls: HashMap<String, (ModuleIx, Option<Location>)>, repr: Package, } impl PackageBuilder { pub fn new() -> Self { let mut repr = Package { names: PrimaryMap::new(), modules: PrimaryMap::new(), }; let mut name_decls = HashMap::new(); repr.names.push("std".to_owned()); let base_ix = repr.modules.push(std_module()); name_decls.insert("std".to_owned(), (base_ix, None)); Self { name_decls, repr } } pub fn introduce_name( &mut self, name: &str, location: Location, ) -> Result<ModuleIx, ValidationError> { if let Some((_, prev_loc)) = self.name_decls.get(name) { match prev_loc { Some(prev_loc) => { Err(ValidationError::NameAlreadyExists { name: name.to_owned(), at_location: location, previous_location: *prev_loc, })?; } None => { Err(ValidationError::Syntax { expected: "non-reserved module name", location: location, })?; } } } let ix = self.repr.names.push(name.to_owned()); self.name_decls .insert(name.to_owned(), (ix, Some(location))); Ok(ix) } pub fn repr(&self) -> &Package { &self.repr } pub fn define_module(&mut self, ix: ModuleIx, mod_repr: ModuleRepr) { assert!(self.repr.names.is_valid(ix)); let pushed_ix = self.repr.modules.push(mod_repr); assert_eq!(ix, pushed_ix); } pub fn build(self) -> Package { self.repr } } #[cfg(test)] mod test { use super::*; use crate::parser::Parser; use crate::Package; fn pkg_(syntax: &str) -> Result<Package, ValidationError> { let mut parser = Parser::new(syntax); let decls = parser.match_package_decls().expect("parses"); package_from_declarations(&decls) } #[test] fn one_empty_mod() { let pkg = pkg_("mod empty {}").expect("valid package"); let empty = pkg.module("empty").expect("mod empty exists"); assert_eq!(empty.name(), "empty"); assert_eq!(empty.datatypes().collect::<Vec<_>>().len(), 0); assert_eq!(empty.functions().collect::<Vec<_>>().len(), 0); } #[test] fn multiple_empty_mod() { let pkg = pkg_("mod empty1 {} mod empty2{}mod\nempty3{//\n}").expect("valid package"); let _ = pkg.module("empty1").expect("mod empty1 exists"); let _ = pkg.module("empty2").expect("mod empty2 exists"); let _ = pkg.module("empty3").expect("mod empty3 exists"); } #[test] fn mod_with_a_type() { let pkg = pkg_("mod foo { type bar = u8; }").expect("valid package"); let foo = pkg.module("foo").expect("mod foo exists"); let _bar = foo.datatype("bar").expect("foo::bar exists"); } #[test] fn no_mod_std_name() { let err = pkg_("mod std {}").err().expect("error package"); assert_eq!( err, ValidationError::Syntax { expected: "non-reserved module name", location: Location { line: 1, column: 0 }, } ); } #[test] fn no_mod_duplicate_name() { let err = pkg_("mod foo {}\nmod foo {}").err().expect("error package"); assert_eq!( err, ValidationError::NameAlreadyExists { name: "foo".to_owned(), at_location: Location { line: 2, column: 0 }, previous_location: Location { line: 1, column: 0 }, } ); } }
package_from_declarations
identifier_name
2-1-literals.rs
fn main()
// Use underscores to improve readibility! println!("One million is written as {}", 1_000_000u32); }
{ // Addition with unsigned integer println!("1 + 3 = {}", 1u32 + 3); // Subtraction with signed integer // Rust refuses to compile if there is an overflow println!("1 - 3 = {}", 1i32 - 3); // Boolean logic println!("true AND false is {}", true && false); println!("true OR false is {}", true || false); println!("NOT false is {}", !true); // Bitwise operations println!("0110 AND 0011 is {:04b}", 0b0110u32 & 0b0011); println!("0110 OR 0011 is {:04b}", 0b0110u32 | 0b0011); println!("0110 XOR 0011 is {:04b}", 0b0110u32 ^ 0b0011); println!("1 << 5 is {}", 1u32 << 5); println!("0x80 >> 2 is 0x{:x}", 0x80u32 >> 2);
identifier_body
2-1-literals.rs
fn
() { // Addition with unsigned integer println!("1 + 3 = {}", 1u32 + 3); // Subtraction with signed integer // Rust refuses to compile if there is an overflow println!("1 - 3 = {}", 1i32 - 3); // Boolean logic println!("true AND false is {}", true && false); println!("true OR false is {}", true || false); println!("NOT false is {}",!true); // Bitwise operations println!("0110 AND 0011 is {:04b}", 0b0110u32 & 0b0011); println!("0110 OR 0011 is {:04b}", 0b0110u32 | 0b0011); println!("0110 XOR 0011 is {:04b}", 0b0110u32 ^ 0b0011); println!("1 << 5 is {}", 1u32 << 5); println!("0x80 >> 2 is 0x{:x}", 0x80u32 >> 2); // Use underscores to improve readibility! println!("One million is written as {}", 1_000_000u32); }
main
identifier_name
2-1-literals.rs
fn main() { // Addition with unsigned integer
// Rust refuses to compile if there is an overflow println!("1 - 3 = {}", 1i32 - 3); // Boolean logic println!("true AND false is {}", true && false); println!("true OR false is {}", true || false); println!("NOT false is {}",!true); // Bitwise operations println!("0110 AND 0011 is {:04b}", 0b0110u32 & 0b0011); println!("0110 OR 0011 is {:04b}", 0b0110u32 | 0b0011); println!("0110 XOR 0011 is {:04b}", 0b0110u32 ^ 0b0011); println!("1 << 5 is {}", 1u32 << 5); println!("0x80 >> 2 is 0x{:x}", 0x80u32 >> 2); // Use underscores to improve readibility! println!("One million is written as {}", 1_000_000u32); }
println!("1 + 3 = {}", 1u32 + 3); // Subtraction with signed integer
random_line_split
timer.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::time::{Duration, Instant}; use gotham::state::State; use gotham_derive::StateData; use hyper::{Body, Response}; use super::Middleware; #[derive(StateData, Debug, Copy, Clone)] pub struct RequestStartTime(pub Instant); #[derive(StateData, Debug, Copy, Clone)] pub struct HeadersDuration(pub Duration); #[derive(Clone)] pub struct TimerMiddleware; impl TimerMiddleware { pub fn new() -> Self { TimerMiddleware } } #[async_trait::async_trait] impl Middleware for TimerMiddleware { async fn inbound(&self, state: &mut State) -> Option<Response<Body>> { state.put(RequestStartTime(Instant::now())); None } async fn outbound(&self, state: &mut State, _response: &mut Response<Body>) { if let Some(RequestStartTime(start)) = state.try_borrow()
} }
{ let headers_duration = start.elapsed(); state.put(HeadersDuration(headers_duration)); }
conditional_block
timer.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::time::{Duration, Instant}; use gotham::state::State; use gotham_derive::StateData; use hyper::{Body, Response}; use super::Middleware; #[derive(StateData, Debug, Copy, Clone)] pub struct RequestStartTime(pub Instant); #[derive(StateData, Debug, Copy, Clone)] pub struct HeadersDuration(pub Duration); #[derive(Clone)] pub struct TimerMiddleware; impl TimerMiddleware { pub fn new() -> Self { TimerMiddleware } }
#[async_trait::async_trait] impl Middleware for TimerMiddleware { async fn inbound(&self, state: &mut State) -> Option<Response<Body>> { state.put(RequestStartTime(Instant::now())); None } async fn outbound(&self, state: &mut State, _response: &mut Response<Body>) { if let Some(RequestStartTime(start)) = state.try_borrow() { let headers_duration = start.elapsed(); state.put(HeadersDuration(headers_duration)); } } }
random_line_split
timer.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::time::{Duration, Instant}; use gotham::state::State; use gotham_derive::StateData; use hyper::{Body, Response}; use super::Middleware; #[derive(StateData, Debug, Copy, Clone)] pub struct
(pub Instant); #[derive(StateData, Debug, Copy, Clone)] pub struct HeadersDuration(pub Duration); #[derive(Clone)] pub struct TimerMiddleware; impl TimerMiddleware { pub fn new() -> Self { TimerMiddleware } } #[async_trait::async_trait] impl Middleware for TimerMiddleware { async fn inbound(&self, state: &mut State) -> Option<Response<Body>> { state.put(RequestStartTime(Instant::now())); None } async fn outbound(&self, state: &mut State, _response: &mut Response<Body>) { if let Some(RequestStartTime(start)) = state.try_borrow() { let headers_duration = start.elapsed(); state.put(HeadersDuration(headers_duration)); } } }
RequestStartTime
identifier_name
filter_profile.rs
#!/bin/bash #![forbid(unsafe_code)]/* This line is ignored by bash # This block is ignored by rustc pushd $(dirname "$0")/../ source scripts/config.sh RUSTC="$(pwd)/build/bin/cg_clif" popd PROFILE=$1 OUTPUT=$2 exec $RUSTC -Zunstable-options -Cllvm-args=mode=jit -Cprefer-dynamic $0 #*/ //! This program filters away uninteresting samples and trims uninteresting frames for stackcollapse //! profiles. //! //! Usage:./filter_profile.rs <profile in stackcollapse format> <output file> //! //! This file is specially crafted to be both a valid bash script and valid rust source file. If //! executed as bash script this will run the rust source using cg_clif in JIT mode. use std::io::Write; fn main() -> Result<(), Box<dyn std::error::Error>> { let profile_name = std::env::var("PROFILE").unwrap(); let output_name = std::env::var("OUTPUT").unwrap(); if profile_name.is_empty() || output_name.is_empty() { println!("Usage:./filter_profile.rs <profile in stackcollapse format> <output file>"); std::process::exit(1); } let profile = std::fs::read_to_string(profile_name) .map_err(|err| format!("Failed to read profile {}", err))?; let mut output = std::fs::OpenOptions::new() .create(true) .write(true) .truncate(true) .open(output_name)?; for line in profile.lines() { let mut stack = &line[..line.rfind(" ").unwrap()]; let count = &line[line.rfind(" ").unwrap() + 1..]; // Filter away uninteresting samples if!stack.contains("rustc_codegen_cranelift") { continue; } if stack.contains("rustc_mir::monomorphize::partitioning::collect_and_partition_mono_items") || stack.contains("rustc_incremental::assert_dep_graph::assert_dep_graph") || stack.contains("rustc_symbol_mangling::test::report_symbol_names") { continue; } // Trim start if let Some(index) = stack.find("rustc_interface::passes::configure_and_expand") { stack = &stack[index..]; } else if let Some(index) = stack.find("rustc_interface::passes::analysis") { stack = &stack[index..]; } else if let Some(index) = stack.find("rustc_interface::passes::start_codegen") { stack = &stack[index..]; } else if let Some(index) = stack.find("rustc_interface::queries::Linker::link") { stack = &stack[index..]; } if let Some(index) = stack.find("rustc_codegen_cranelift::driver::aot::module_codegen") { stack = &stack[index..]; } // Trim end const MALLOC: &str = "malloc"; if let Some(index) = stack.find(MALLOC) {
const FREE: &str = "free"; if let Some(index) = stack.find(FREE) { stack = &stack[..index + FREE.len()]; } const TYPECK_ITEM_BODIES: &str = "rustc_typeck::check::typeck_item_bodies"; if let Some(index) = stack.find(TYPECK_ITEM_BODIES) { stack = &stack[..index + TYPECK_ITEM_BODIES.len()]; } const COLLECT_AND_PARTITION_MONO_ITEMS: &str = "rustc_mir::monomorphize::partitioning::collect_and_partition_mono_items"; if let Some(index) = stack.find(COLLECT_AND_PARTITION_MONO_ITEMS) { stack = &stack[..index + COLLECT_AND_PARTITION_MONO_ITEMS.len()]; } const ASSERT_DEP_GRAPH: &str = "rustc_incremental::assert_dep_graph::assert_dep_graph"; if let Some(index) = stack.find(ASSERT_DEP_GRAPH) { stack = &stack[..index + ASSERT_DEP_GRAPH.len()]; } const REPORT_SYMBOL_NAMES: &str = "rustc_symbol_mangling::test::report_symbol_names"; if let Some(index) = stack.find(REPORT_SYMBOL_NAMES) { stack = &stack[..index + REPORT_SYMBOL_NAMES.len()]; } const ENCODE_METADATA: &str = "rustc_middle::ty::context::TyCtxt::encode_metadata"; if let Some(index) = stack.find(ENCODE_METADATA) { stack = &stack[..index + ENCODE_METADATA.len()]; } const SUBST_AND_NORMALIZE_ERASING_REGIONS: &str = "rustc_middle::ty::normalize_erasing_regions::<impl rustc_middle::ty::context::TyCtxt>::subst_and_normalize_erasing_regions"; if let Some(index) = stack.find(SUBST_AND_NORMALIZE_ERASING_REGIONS) { stack = &stack[..index + SUBST_AND_NORMALIZE_ERASING_REGIONS.len()]; } const NORMALIZE_ERASING_LATE_BOUND_REGIONS: &str = "rustc_middle::ty::normalize_erasing_regions::<impl rustc_middle::ty::context::TyCtxt>::normalize_erasing_late_bound_regions"; if let Some(index) = stack.find(NORMALIZE_ERASING_LATE_BOUND_REGIONS) { stack = &stack[..index + NORMALIZE_ERASING_LATE_BOUND_REGIONS.len()]; } const INST_BUILD: &str = "<cranelift_frontend::frontend::FuncInstBuilder as cranelift_codegen::ir::builder::InstBuilderBase>::build"; if let Some(index) = stack.find(INST_BUILD) { stack = &stack[..index + INST_BUILD.len()]; } output.write_all(stack.as_bytes())?; output.write_all(&*b" ")?; output.write_all(count.as_bytes())?; output.write_all(&*b"\n")?; } Ok(()) }
stack = &stack[..index + MALLOC.len()]; }
random_line_split
filter_profile.rs
#!/bin/bash #![forbid(unsafe_code)]/* This line is ignored by bash # This block is ignored by rustc pushd $(dirname "$0")/../ source scripts/config.sh RUSTC="$(pwd)/build/bin/cg_clif" popd PROFILE=$1 OUTPUT=$2 exec $RUSTC -Zunstable-options -Cllvm-args=mode=jit -Cprefer-dynamic $0 #*/ //! This program filters away uninteresting samples and trims uninteresting frames for stackcollapse //! profiles. //! //! Usage:./filter_profile.rs <profile in stackcollapse format> <output file> //! //! This file is specially crafted to be both a valid bash script and valid rust source file. If //! executed as bash script this will run the rust source using cg_clif in JIT mode. use std::io::Write; fn
() -> Result<(), Box<dyn std::error::Error>> { let profile_name = std::env::var("PROFILE").unwrap(); let output_name = std::env::var("OUTPUT").unwrap(); if profile_name.is_empty() || output_name.is_empty() { println!("Usage:./filter_profile.rs <profile in stackcollapse format> <output file>"); std::process::exit(1); } let profile = std::fs::read_to_string(profile_name) .map_err(|err| format!("Failed to read profile {}", err))?; let mut output = std::fs::OpenOptions::new() .create(true) .write(true) .truncate(true) .open(output_name)?; for line in profile.lines() { let mut stack = &line[..line.rfind(" ").unwrap()]; let count = &line[line.rfind(" ").unwrap() + 1..]; // Filter away uninteresting samples if!stack.contains("rustc_codegen_cranelift") { continue; } if stack.contains("rustc_mir::monomorphize::partitioning::collect_and_partition_mono_items") || stack.contains("rustc_incremental::assert_dep_graph::assert_dep_graph") || stack.contains("rustc_symbol_mangling::test::report_symbol_names") { continue; } // Trim start if let Some(index) = stack.find("rustc_interface::passes::configure_and_expand") { stack = &stack[index..]; } else if let Some(index) = stack.find("rustc_interface::passes::analysis") { stack = &stack[index..]; } else if let Some(index) = stack.find("rustc_interface::passes::start_codegen") { stack = &stack[index..]; } else if let Some(index) = stack.find("rustc_interface::queries::Linker::link") { stack = &stack[index..]; } if let Some(index) = stack.find("rustc_codegen_cranelift::driver::aot::module_codegen") { stack = &stack[index..]; } // Trim end const MALLOC: &str = "malloc"; if let Some(index) = stack.find(MALLOC) { stack = &stack[..index + MALLOC.len()]; } const FREE: &str = "free"; if let Some(index) = stack.find(FREE) { stack = &stack[..index + FREE.len()]; } const TYPECK_ITEM_BODIES: &str = "rustc_typeck::check::typeck_item_bodies"; if let Some(index) = stack.find(TYPECK_ITEM_BODIES) { stack = &stack[..index + TYPECK_ITEM_BODIES.len()]; } const COLLECT_AND_PARTITION_MONO_ITEMS: &str = "rustc_mir::monomorphize::partitioning::collect_and_partition_mono_items"; if let Some(index) = stack.find(COLLECT_AND_PARTITION_MONO_ITEMS) { stack = &stack[..index + COLLECT_AND_PARTITION_MONO_ITEMS.len()]; } const ASSERT_DEP_GRAPH: &str = "rustc_incremental::assert_dep_graph::assert_dep_graph"; if let Some(index) = stack.find(ASSERT_DEP_GRAPH) { stack = &stack[..index + ASSERT_DEP_GRAPH.len()]; } const REPORT_SYMBOL_NAMES: &str = "rustc_symbol_mangling::test::report_symbol_names"; if let Some(index) = stack.find(REPORT_SYMBOL_NAMES) { stack = &stack[..index + REPORT_SYMBOL_NAMES.len()]; } const ENCODE_METADATA: &str = "rustc_middle::ty::context::TyCtxt::encode_metadata"; if let Some(index) = stack.find(ENCODE_METADATA) { stack = &stack[..index + ENCODE_METADATA.len()]; } const SUBST_AND_NORMALIZE_ERASING_REGIONS: &str = "rustc_middle::ty::normalize_erasing_regions::<impl rustc_middle::ty::context::TyCtxt>::subst_and_normalize_erasing_regions"; if let Some(index) = stack.find(SUBST_AND_NORMALIZE_ERASING_REGIONS) { stack = &stack[..index + SUBST_AND_NORMALIZE_ERASING_REGIONS.len()]; } const NORMALIZE_ERASING_LATE_BOUND_REGIONS: &str = "rustc_middle::ty::normalize_erasing_regions::<impl rustc_middle::ty::context::TyCtxt>::normalize_erasing_late_bound_regions"; if let Some(index) = stack.find(NORMALIZE_ERASING_LATE_BOUND_REGIONS) { stack = &stack[..index + NORMALIZE_ERASING_LATE_BOUND_REGIONS.len()]; } const INST_BUILD: &str = "<cranelift_frontend::frontend::FuncInstBuilder as cranelift_codegen::ir::builder::InstBuilderBase>::build"; if let Some(index) = stack.find(INST_BUILD) { stack = &stack[..index + INST_BUILD.len()]; } output.write_all(stack.as_bytes())?; output.write_all(&*b" ")?; output.write_all(count.as_bytes())?; output.write_all(&*b"\n")?; } Ok(()) }
main
identifier_name
filter_profile.rs
#!/bin/bash #![forbid(unsafe_code)]/* This line is ignored by bash # This block is ignored by rustc pushd $(dirname "$0")/../ source scripts/config.sh RUSTC="$(pwd)/build/bin/cg_clif" popd PROFILE=$1 OUTPUT=$2 exec $RUSTC -Zunstable-options -Cllvm-args=mode=jit -Cprefer-dynamic $0 #*/ //! This program filters away uninteresting samples and trims uninteresting frames for stackcollapse //! profiles. //! //! Usage:./filter_profile.rs <profile in stackcollapse format> <output file> //! //! This file is specially crafted to be both a valid bash script and valid rust source file. If //! executed as bash script this will run the rust source using cg_clif in JIT mode. use std::io::Write; fn main() -> Result<(), Box<dyn std::error::Error>> { let profile_name = std::env::var("PROFILE").unwrap(); let output_name = std::env::var("OUTPUT").unwrap(); if profile_name.is_empty() || output_name.is_empty() { println!("Usage:./filter_profile.rs <profile in stackcollapse format> <output file>"); std::process::exit(1); } let profile = std::fs::read_to_string(profile_name) .map_err(|err| format!("Failed to read profile {}", err))?; let mut output = std::fs::OpenOptions::new() .create(true) .write(true) .truncate(true) .open(output_name)?; for line in profile.lines() { let mut stack = &line[..line.rfind(" ").unwrap()]; let count = &line[line.rfind(" ").unwrap() + 1..]; // Filter away uninteresting samples if!stack.contains("rustc_codegen_cranelift") { continue; } if stack.contains("rustc_mir::monomorphize::partitioning::collect_and_partition_mono_items") || stack.contains("rustc_incremental::assert_dep_graph::assert_dep_graph") || stack.contains("rustc_symbol_mangling::test::report_symbol_names") { continue; } // Trim start if let Some(index) = stack.find("rustc_interface::passes::configure_and_expand") { stack = &stack[index..]; } else if let Some(index) = stack.find("rustc_interface::passes::analysis") { stack = &stack[index..]; } else if let Some(index) = stack.find("rustc_interface::passes::start_codegen") { stack = &stack[index..]; } else if let Some(index) = stack.find("rustc_interface::queries::Linker::link") { stack = &stack[index..]; } if let Some(index) = stack.find("rustc_codegen_cranelift::driver::aot::module_codegen") { stack = &stack[index..]; } // Trim end const MALLOC: &str = "malloc"; if let Some(index) = stack.find(MALLOC) { stack = &stack[..index + MALLOC.len()]; } const FREE: &str = "free"; if let Some(index) = stack.find(FREE) { stack = &stack[..index + FREE.len()]; } const TYPECK_ITEM_BODIES: &str = "rustc_typeck::check::typeck_item_bodies"; if let Some(index) = stack.find(TYPECK_ITEM_BODIES) { stack = &stack[..index + TYPECK_ITEM_BODIES.len()]; } const COLLECT_AND_PARTITION_MONO_ITEMS: &str = "rustc_mir::monomorphize::partitioning::collect_and_partition_mono_items"; if let Some(index) = stack.find(COLLECT_AND_PARTITION_MONO_ITEMS) { stack = &stack[..index + COLLECT_AND_PARTITION_MONO_ITEMS.len()]; } const ASSERT_DEP_GRAPH: &str = "rustc_incremental::assert_dep_graph::assert_dep_graph"; if let Some(index) = stack.find(ASSERT_DEP_GRAPH) { stack = &stack[..index + ASSERT_DEP_GRAPH.len()]; } const REPORT_SYMBOL_NAMES: &str = "rustc_symbol_mangling::test::report_symbol_names"; if let Some(index) = stack.find(REPORT_SYMBOL_NAMES) { stack = &stack[..index + REPORT_SYMBOL_NAMES.len()]; } const ENCODE_METADATA: &str = "rustc_middle::ty::context::TyCtxt::encode_metadata"; if let Some(index) = stack.find(ENCODE_METADATA) { stack = &stack[..index + ENCODE_METADATA.len()]; } const SUBST_AND_NORMALIZE_ERASING_REGIONS: &str = "rustc_middle::ty::normalize_erasing_regions::<impl rustc_middle::ty::context::TyCtxt>::subst_and_normalize_erasing_regions"; if let Some(index) = stack.find(SUBST_AND_NORMALIZE_ERASING_REGIONS)
const NORMALIZE_ERASING_LATE_BOUND_REGIONS: &str = "rustc_middle::ty::normalize_erasing_regions::<impl rustc_middle::ty::context::TyCtxt>::normalize_erasing_late_bound_regions"; if let Some(index) = stack.find(NORMALIZE_ERASING_LATE_BOUND_REGIONS) { stack = &stack[..index + NORMALIZE_ERASING_LATE_BOUND_REGIONS.len()]; } const INST_BUILD: &str = "<cranelift_frontend::frontend::FuncInstBuilder as cranelift_codegen::ir::builder::InstBuilderBase>::build"; if let Some(index) = stack.find(INST_BUILD) { stack = &stack[..index + INST_BUILD.len()]; } output.write_all(stack.as_bytes())?; output.write_all(&*b" ")?; output.write_all(count.as_bytes())?; output.write_all(&*b"\n")?; } Ok(()) }
{ stack = &stack[..index + SUBST_AND_NORMALIZE_ERASING_REGIONS.len()]; }
conditional_block
filter_profile.rs
#!/bin/bash #![forbid(unsafe_code)]/* This line is ignored by bash # This block is ignored by rustc pushd $(dirname "$0")/../ source scripts/config.sh RUSTC="$(pwd)/build/bin/cg_clif" popd PROFILE=$1 OUTPUT=$2 exec $RUSTC -Zunstable-options -Cllvm-args=mode=jit -Cprefer-dynamic $0 #*/ //! This program filters away uninteresting samples and trims uninteresting frames for stackcollapse //! profiles. //! //! Usage:./filter_profile.rs <profile in stackcollapse format> <output file> //! //! This file is specially crafted to be both a valid bash script and valid rust source file. If //! executed as bash script this will run the rust source using cg_clif in JIT mode. use std::io::Write; fn main() -> Result<(), Box<dyn std::error::Error>>
if!stack.contains("rustc_codegen_cranelift") { continue; } if stack.contains("rustc_mir::monomorphize::partitioning::collect_and_partition_mono_items") || stack.contains("rustc_incremental::assert_dep_graph::assert_dep_graph") || stack.contains("rustc_symbol_mangling::test::report_symbol_names") { continue; } // Trim start if let Some(index) = stack.find("rustc_interface::passes::configure_and_expand") { stack = &stack[index..]; } else if let Some(index) = stack.find("rustc_interface::passes::analysis") { stack = &stack[index..]; } else if let Some(index) = stack.find("rustc_interface::passes::start_codegen") { stack = &stack[index..]; } else if let Some(index) = stack.find("rustc_interface::queries::Linker::link") { stack = &stack[index..]; } if let Some(index) = stack.find("rustc_codegen_cranelift::driver::aot::module_codegen") { stack = &stack[index..]; } // Trim end const MALLOC: &str = "malloc"; if let Some(index) = stack.find(MALLOC) { stack = &stack[..index + MALLOC.len()]; } const FREE: &str = "free"; if let Some(index) = stack.find(FREE) { stack = &stack[..index + FREE.len()]; } const TYPECK_ITEM_BODIES: &str = "rustc_typeck::check::typeck_item_bodies"; if let Some(index) = stack.find(TYPECK_ITEM_BODIES) { stack = &stack[..index + TYPECK_ITEM_BODIES.len()]; } const COLLECT_AND_PARTITION_MONO_ITEMS: &str = "rustc_mir::monomorphize::partitioning::collect_and_partition_mono_items"; if let Some(index) = stack.find(COLLECT_AND_PARTITION_MONO_ITEMS) { stack = &stack[..index + COLLECT_AND_PARTITION_MONO_ITEMS.len()]; } const ASSERT_DEP_GRAPH: &str = "rustc_incremental::assert_dep_graph::assert_dep_graph"; if let Some(index) = stack.find(ASSERT_DEP_GRAPH) { stack = &stack[..index + ASSERT_DEP_GRAPH.len()]; } const REPORT_SYMBOL_NAMES: &str = "rustc_symbol_mangling::test::report_symbol_names"; if let Some(index) = stack.find(REPORT_SYMBOL_NAMES) { stack = &stack[..index + REPORT_SYMBOL_NAMES.len()]; } const ENCODE_METADATA: &str = "rustc_middle::ty::context::TyCtxt::encode_metadata"; if let Some(index) = stack.find(ENCODE_METADATA) { stack = &stack[..index + ENCODE_METADATA.len()]; } const SUBST_AND_NORMALIZE_ERASING_REGIONS: &str = "rustc_middle::ty::normalize_erasing_regions::<impl rustc_middle::ty::context::TyCtxt>::subst_and_normalize_erasing_regions"; if let Some(index) = stack.find(SUBST_AND_NORMALIZE_ERASING_REGIONS) { stack = &stack[..index + SUBST_AND_NORMALIZE_ERASING_REGIONS.len()]; } const NORMALIZE_ERASING_LATE_BOUND_REGIONS: &str = "rustc_middle::ty::normalize_erasing_regions::<impl rustc_middle::ty::context::TyCtxt>::normalize_erasing_late_bound_regions"; if let Some(index) = stack.find(NORMALIZE_ERASING_LATE_BOUND_REGIONS) { stack = &stack[..index + NORMALIZE_ERASING_LATE_BOUND_REGIONS.len()]; } const INST_BUILD: &str = "<cranelift_frontend::frontend::FuncInstBuilder as cranelift_codegen::ir::builder::InstBuilderBase>::build"; if let Some(index) = stack.find(INST_BUILD) { stack = &stack[..index + INST_BUILD.len()]; } output.write_all(stack.as_bytes())?; output.write_all(&*b" ")?; output.write_all(count.as_bytes())?; output.write_all(&*b"\n")?; } Ok(()) }
{ let profile_name = std::env::var("PROFILE").unwrap(); let output_name = std::env::var("OUTPUT").unwrap(); if profile_name.is_empty() || output_name.is_empty() { println!("Usage: ./filter_profile.rs <profile in stackcollapse format> <output file>"); std::process::exit(1); } let profile = std::fs::read_to_string(profile_name) .map_err(|err| format!("Failed to read profile {}", err))?; let mut output = std::fs::OpenOptions::new() .create(true) .write(true) .truncate(true) .open(output_name)?; for line in profile.lines() { let mut stack = &line[..line.rfind(" ").unwrap()]; let count = &line[line.rfind(" ").unwrap() + 1..]; // Filter away uninteresting samples
identifier_body
fatdb.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use hash::H256; use sha3::Hashable; use hashdb::HashDB; use super::{TrieDB, Trie, TrieDBIterator, TrieItem, TrieIterator, Query}; /// A `Trie` implementation which hashes keys and uses a generic `HashDB` backing database. /// Additionaly it stores inserted hash-key mappings for later retrieval. /// /// Use it as a `Trie` or `TrieMut` trait object. pub struct FatDB<'db> { raw: TrieDB<'db>, } impl<'db> FatDB<'db> { /// Create a new trie with the backing database `db` and empty `root` /// Initialise to the state entailed by the genesis block. /// This guarantees the trie is built correctly. pub fn new(db: &'db HashDB, root: &'db H256) -> super::Result<Self> { let fatdb = FatDB { raw: TrieDB::new(db, root)? }; Ok(fatdb) } /// Get the backing database. pub fn db(&self) -> &HashDB { self.raw.db() } } impl<'db> Trie for FatDB<'db> { fn iter<'a>(&'a self) -> super::Result<Box<TrieIterator<Item = TrieItem> + 'a>> { FatDBIterator::new(&self.raw).map(|iter| Box::new(iter) as Box<_>) } fn root(&self) -> &H256 { self.raw.root() } fn contains(&self, key: &[u8]) -> super::Result<bool> { self.raw.contains(&key.sha3()) } fn get_with<'a, 'key, Q: Query>(&'a self, key: &'key [u8], query: Q) -> super::Result<Option<Q::Item>> where 'a: 'key
} /// Itarator over inserted pairs of key values. pub struct FatDBIterator<'db> { trie_iterator: TrieDBIterator<'db>, trie: &'db TrieDB<'db>, } impl<'db> FatDBIterator<'db> { /// Creates new iterator. pub fn new(trie: &'db TrieDB) -> super::Result<Self> { Ok(FatDBIterator { trie_iterator: TrieDBIterator::new(trie)?, trie: trie, }) } } impl<'db> TrieIterator for FatDBIterator<'db> { fn seek(&mut self, key: &[u8]) -> super::Result<()> { self.trie_iterator.seek(&key.sha3()) } } impl<'db> Iterator for FatDBIterator<'db> { type Item = TrieItem<'db>; fn next(&mut self) -> Option<Self::Item> { self.trie_iterator.next() .map(|res| res.map(|(hash, value)| { let aux_hash = hash.sha3(); (self.trie.db().get(&aux_hash).expect("Missing fatdb hash").into_vec(), value) }) ) } } #[test] fn fatdb_to_trie() { use memorydb::MemoryDB; use hashdb::DBValue; use trie::{FatDBMut, TrieMut}; let mut memdb = MemoryDB::new(); let mut root = H256::default(); { let mut t = FatDBMut::new(&mut memdb, &mut root); t.insert(&[0x01u8, 0x23], &[0x01u8, 0x23]).unwrap(); } let t = FatDB::new(&memdb, &root).unwrap(); assert_eq!(t.get(&[0x01u8, 0x23]).unwrap().unwrap(), DBValue::from_slice(&[0x01u8, 0x23])); assert_eq!(t.iter().unwrap().map(Result::unwrap).collect::<Vec<_>>(), vec![(vec![0x01u8, 0x23], DBValue::from_slice(&[0x01u8, 0x23] as &[u8]))]); }
{ self.raw.get_with(&key.sha3(), query) }
identifier_body
fatdb.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use hash::H256; use sha3::Hashable; use hashdb::HashDB; use super::{TrieDB, Trie, TrieDBIterator, TrieItem, TrieIterator, Query};
pub struct FatDB<'db> { raw: TrieDB<'db>, } impl<'db> FatDB<'db> { /// Create a new trie with the backing database `db` and empty `root` /// Initialise to the state entailed by the genesis block. /// This guarantees the trie is built correctly. pub fn new(db: &'db HashDB, root: &'db H256) -> super::Result<Self> { let fatdb = FatDB { raw: TrieDB::new(db, root)? }; Ok(fatdb) } /// Get the backing database. pub fn db(&self) -> &HashDB { self.raw.db() } } impl<'db> Trie for FatDB<'db> { fn iter<'a>(&'a self) -> super::Result<Box<TrieIterator<Item = TrieItem> + 'a>> { FatDBIterator::new(&self.raw).map(|iter| Box::new(iter) as Box<_>) } fn root(&self) -> &H256 { self.raw.root() } fn contains(&self, key: &[u8]) -> super::Result<bool> { self.raw.contains(&key.sha3()) } fn get_with<'a, 'key, Q: Query>(&'a self, key: &'key [u8], query: Q) -> super::Result<Option<Q::Item>> where 'a: 'key { self.raw.get_with(&key.sha3(), query) } } /// Itarator over inserted pairs of key values. pub struct FatDBIterator<'db> { trie_iterator: TrieDBIterator<'db>, trie: &'db TrieDB<'db>, } impl<'db> FatDBIterator<'db> { /// Creates new iterator. pub fn new(trie: &'db TrieDB) -> super::Result<Self> { Ok(FatDBIterator { trie_iterator: TrieDBIterator::new(trie)?, trie: trie, }) } } impl<'db> TrieIterator for FatDBIterator<'db> { fn seek(&mut self, key: &[u8]) -> super::Result<()> { self.trie_iterator.seek(&key.sha3()) } } impl<'db> Iterator for FatDBIterator<'db> { type Item = TrieItem<'db>; fn next(&mut self) -> Option<Self::Item> { self.trie_iterator.next() .map(|res| res.map(|(hash, value)| { let aux_hash = hash.sha3(); (self.trie.db().get(&aux_hash).expect("Missing fatdb hash").into_vec(), value) }) ) } } #[test] fn fatdb_to_trie() { use memorydb::MemoryDB; use hashdb::DBValue; use trie::{FatDBMut, TrieMut}; let mut memdb = MemoryDB::new(); let mut root = H256::default(); { let mut t = FatDBMut::new(&mut memdb, &mut root); t.insert(&[0x01u8, 0x23], &[0x01u8, 0x23]).unwrap(); } let t = FatDB::new(&memdb, &root).unwrap(); assert_eq!(t.get(&[0x01u8, 0x23]).unwrap().unwrap(), DBValue::from_slice(&[0x01u8, 0x23])); assert_eq!(t.iter().unwrap().map(Result::unwrap).collect::<Vec<_>>(), vec![(vec![0x01u8, 0x23], DBValue::from_slice(&[0x01u8, 0x23] as &[u8]))]); }
/// A `Trie` implementation which hashes keys and uses a generic `HashDB` backing database. /// Additionaly it stores inserted hash-key mappings for later retrieval. /// /// Use it as a `Trie` or `TrieMut` trait object.
random_line_split
fatdb.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use hash::H256; use sha3::Hashable; use hashdb::HashDB; use super::{TrieDB, Trie, TrieDBIterator, TrieItem, TrieIterator, Query}; /// A `Trie` implementation which hashes keys and uses a generic `HashDB` backing database. /// Additionaly it stores inserted hash-key mappings for later retrieval. /// /// Use it as a `Trie` or `TrieMut` trait object. pub struct FatDB<'db> { raw: TrieDB<'db>, } impl<'db> FatDB<'db> { /// Create a new trie with the backing database `db` and empty `root` /// Initialise to the state entailed by the genesis block. /// This guarantees the trie is built correctly. pub fn new(db: &'db HashDB, root: &'db H256) -> super::Result<Self> { let fatdb = FatDB { raw: TrieDB::new(db, root)? }; Ok(fatdb) } /// Get the backing database. pub fn db(&self) -> &HashDB { self.raw.db() } } impl<'db> Trie for FatDB<'db> { fn
<'a>(&'a self) -> super::Result<Box<TrieIterator<Item = TrieItem> + 'a>> { FatDBIterator::new(&self.raw).map(|iter| Box::new(iter) as Box<_>) } fn root(&self) -> &H256 { self.raw.root() } fn contains(&self, key: &[u8]) -> super::Result<bool> { self.raw.contains(&key.sha3()) } fn get_with<'a, 'key, Q: Query>(&'a self, key: &'key [u8], query: Q) -> super::Result<Option<Q::Item>> where 'a: 'key { self.raw.get_with(&key.sha3(), query) } } /// Itarator over inserted pairs of key values. pub struct FatDBIterator<'db> { trie_iterator: TrieDBIterator<'db>, trie: &'db TrieDB<'db>, } impl<'db> FatDBIterator<'db> { /// Creates new iterator. pub fn new(trie: &'db TrieDB) -> super::Result<Self> { Ok(FatDBIterator { trie_iterator: TrieDBIterator::new(trie)?, trie: trie, }) } } impl<'db> TrieIterator for FatDBIterator<'db> { fn seek(&mut self, key: &[u8]) -> super::Result<()> { self.trie_iterator.seek(&key.sha3()) } } impl<'db> Iterator for FatDBIterator<'db> { type Item = TrieItem<'db>; fn next(&mut self) -> Option<Self::Item> { self.trie_iterator.next() .map(|res| res.map(|(hash, value)| { let aux_hash = hash.sha3(); (self.trie.db().get(&aux_hash).expect("Missing fatdb hash").into_vec(), value) }) ) } } #[test] fn fatdb_to_trie() { use memorydb::MemoryDB; use hashdb::DBValue; use trie::{FatDBMut, TrieMut}; let mut memdb = MemoryDB::new(); let mut root = H256::default(); { let mut t = FatDBMut::new(&mut memdb, &mut root); t.insert(&[0x01u8, 0x23], &[0x01u8, 0x23]).unwrap(); } let t = FatDB::new(&memdb, &root).unwrap(); assert_eq!(t.get(&[0x01u8, 0x23]).unwrap().unwrap(), DBValue::from_slice(&[0x01u8, 0x23])); assert_eq!(t.iter().unwrap().map(Result::unwrap).collect::<Vec<_>>(), vec![(vec![0x01u8, 0x23], DBValue::from_slice(&[0x01u8, 0x23] as &[u8]))]); }
iter
identifier_name
getat_func.rs
//! # getat_func //! //! Split function which returns only the requested item from the created array. //! #[cfg(test)] #[path = "getat_func_test.rs"] mod getat_func_test; use envmnt; pub(crate) fn invoke(function_args: &Vec<String>) -> Vec<String>
let split_by_char = split_by.chars().next().unwrap(); let value = envmnt::get_or(&env_key, ""); if value.len() > index { let splitted = value.split(split_by_char); let splitted_vec: Vec<String> = splitted.map(|str_value| str_value.to_string()).collect(); let value = splitted_vec[index].clone(); vec![value] } else { vec![] } }
{ if function_args.len() != 3 { error!( "split expects only 3 arguments (environment variable name, split by character, index)" ); } let env_key = function_args[0].clone(); let split_by = function_args[1].clone(); let index: usize = match function_args[2].parse() { Ok(value) => value, Err(error) => { error!("Invalid index value: {}", &error); return vec![]; // should not get here } }; if split_by.len() != 1 { error!("split expects a single character separator"); }
identifier_body
getat_func.rs
//! # getat_func //! //! Split function which returns only the requested item from the created array. //! #[cfg(test)] #[path = "getat_func_test.rs"] mod getat_func_test; use envmnt; pub(crate) fn invoke(function_args: &Vec<String>) -> Vec<String> { if function_args.len()!= 3 { error!( "split expects only 3 arguments (environment variable name, split by character, index)" ); }
let env_key = function_args[0].clone(); let split_by = function_args[1].clone(); let index: usize = match function_args[2].parse() { Ok(value) => value, Err(error) => { error!("Invalid index value: {}", &error); return vec![]; // should not get here } }; if split_by.len()!= 1 { error!("split expects a single character separator"); } let split_by_char = split_by.chars().next().unwrap(); let value = envmnt::get_or(&env_key, ""); if value.len() > index { let splitted = value.split(split_by_char); let splitted_vec: Vec<String> = splitted.map(|str_value| str_value.to_string()).collect(); let value = splitted_vec[index].clone(); vec![value] } else { vec![] } }
random_line_split