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
fixed_bug_long_thin_box_one_shot_manifold3.rs
/*! * # Expected behaviour: * The box stands vertically until it falls asleep. * The box should not fall (horizontally) on the ground. * The box should not traverse the ground. * * # Symptoms: * The long, thin, box fails to collide with the plane: it just ignores it. * * # Cause:
* contact surface is small, all contacts will be invalidated whenever the incremental contact * manifold will get a new point from the one-shot generator. * * # Solution: * Rotate the object wrt the contact center, not wrt the object center. * * # Limitations of the solution: * This will create only a three-points manifold for a small axis-alligned cube, instead of four. */ extern crate nalgebra as na; extern crate ncollide3d; extern crate nphysics3d; extern crate nphysics_testbed3d; use na::{Point3, Vector3}; use ncollide3d::shape::{Cuboid, Plane, ShapeHandle}; use nphysics3d::object::{ColliderDesc, RigidBodyDesc}; use nphysics3d::world::World; use nphysics_testbed3d::Testbed; fn main() { /* * World */ let mut world = World::new(); world.set_gravity(Vector3::new(r!(0.0), r!(-9.81), r!(0.0))); /* * Plane */ let ground_shape = ShapeHandle::new(Plane::new(Vector3::y_axis())); ColliderDesc::new(ground_shape).build(&mut world); /* * Create the box */ let rad = r!(0.1); let x = rad; let y = rad + 10.0; let z = rad; let geom = ShapeHandle::new(Cuboid::new(Vector3::new(rad, rad * 10.0, rad))); let collider_desc = ColliderDesc::new(geom).density(r!(1.0)); RigidBodyDesc::new() .collider(&collider_desc) .translation(Vector3::new(x, y, z)) .build(&mut world); /* * Set up the testbed. */ let mut testbed = Testbed::new(world); testbed.look_at(Point3::new(-30.0, 30.0, -30.0), Point3::new(0.0, 0.0, 0.0)); testbed.run(); }
* The one shot contact manifold generator was incorrect in this case. This generator rotated the * object wrt its center to sample the contact manifold. If the object is long and the theoretical
random_line_split
fixed_bug_long_thin_box_one_shot_manifold3.rs
/*! * # Expected behaviour: * The box stands vertically until it falls asleep. * The box should not fall (horizontally) on the ground. * The box should not traverse the ground. * * # Symptoms: * The long, thin, box fails to collide with the plane: it just ignores it. * * # Cause: * The one shot contact manifold generator was incorrect in this case. This generator rotated the * object wrt its center to sample the contact manifold. If the object is long and the theoretical * contact surface is small, all contacts will be invalidated whenever the incremental contact * manifold will get a new point from the one-shot generator. * * # Solution: * Rotate the object wrt the contact center, not wrt the object center. * * # Limitations of the solution: * This will create only a three-points manifold for a small axis-alligned cube, instead of four. */ extern crate nalgebra as na; extern crate ncollide3d; extern crate nphysics3d; extern crate nphysics_testbed3d; use na::{Point3, Vector3}; use ncollide3d::shape::{Cuboid, Plane, ShapeHandle}; use nphysics3d::object::{ColliderDesc, RigidBodyDesc}; use nphysics3d::world::World; use nphysics_testbed3d::Testbed; fn
() { /* * World */ let mut world = World::new(); world.set_gravity(Vector3::new(r!(0.0), r!(-9.81), r!(0.0))); /* * Plane */ let ground_shape = ShapeHandle::new(Plane::new(Vector3::y_axis())); ColliderDesc::new(ground_shape).build(&mut world); /* * Create the box */ let rad = r!(0.1); let x = rad; let y = rad + 10.0; let z = rad; let geom = ShapeHandle::new(Cuboid::new(Vector3::new(rad, rad * 10.0, rad))); let collider_desc = ColliderDesc::new(geom).density(r!(1.0)); RigidBodyDesc::new() .collider(&collider_desc) .translation(Vector3::new(x, y, z)) .build(&mut world); /* * Set up the testbed. */ let mut testbed = Testbed::new(world); testbed.look_at(Point3::new(-30.0, 30.0, -30.0), Point3::new(0.0, 0.0, 0.0)); testbed.run(); }
main
identifier_name
button.rs
//! Easy use of buttons. use peripheral; /// The user button. pub static BUTTONS: [Button; 1] = [Button { i: 0 }]; /// A single button. pub struct Button { i: u8, } impl Button { /// Read the state of the button. pub fn pressed(&self) -> bool { let idr = &peripheral::gpioa().idr;
match self.i { 0 => idr.read().idr0(), _ => false } } } /// Initializes the necessary stuff to enable the button. /// /// # Safety /// /// - Must be called once /// - Must be called in an interrupt-free environment pub unsafe fn init() { let rcc = peripheral::rcc_mut(); // RCC: Enable GPIOA rcc.ahb1enr.modify(|_, w| w.gpioaen(true)); } /// An enum over the Buttons, each Button is associated but its name. pub enum Buttons { /// User User, } impl Buttons { /// Read the state of this button. pub fn pressed(&self) -> bool { match *self { Buttons::User => BUTTONS[0].pressed() } } }
random_line_split
button.rs
//! Easy use of buttons. use peripheral; /// The user button. pub static BUTTONS: [Button; 1] = [Button { i: 0 }]; /// A single button. pub struct
{ i: u8, } impl Button { /// Read the state of the button. pub fn pressed(&self) -> bool { let idr = &peripheral::gpioa().idr; match self.i { 0 => idr.read().idr0(), _ => false } } } /// Initializes the necessary stuff to enable the button. /// /// # Safety /// /// - Must be called once /// - Must be called in an interrupt-free environment pub unsafe fn init() { let rcc = peripheral::rcc_mut(); // RCC: Enable GPIOA rcc.ahb1enr.modify(|_, w| w.gpioaen(true)); } /// An enum over the Buttons, each Button is associated but its name. pub enum Buttons { /// User User, } impl Buttons { /// Read the state of this button. pub fn pressed(&self) -> bool { match *self { Buttons::User => BUTTONS[0].pressed() } } }
Button
identifier_name
js.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/. */ //! Smart pointers for the JS-managed DOM objects. //! //! The DOM is made up of Rust types whose lifetime is entirely controlled by the whims of //! the SpiderMonkey garbage collector. The types in this module are designed to ensure //! that any interactions with said Rust types only occur on values that will remain alive //! the entire time. //! //! Here is a brief overview of the important types: //! //! - `JSRef<T>`: a freely-copyable reference to a rooted value. //! - `Root<T>`: a stack-based reference to a rooted value. //! - `JS<T>`: a pointer to JS-owned memory that can automatically be traced by the GC when //! encountered as a field of a Rust structure. //! - `Temporary<T>`: a value that will remain rooted for the duration of its lifetime. //! //! The rule of thumb is as follows: //! //! - All methods return `Temporary<T>`, to ensure the value remains alive until it is stored //! somewhere that is reachable by the GC. //! - All functions take `JSRef<T>` arguments, to ensure that they will remain uncollected for //! the duration of their usage. //! - All types contain `JS<T>` fields and derive the `Encodable` trait, to ensure that they are //! transitively marked as reachable by the GC if the enclosing value is reachable. //! - All methods for type `T` are implemented for `JSRef<T>`, to ensure that the self value //! will not be collected for the duration of the method call. //! //! Both `Temporary<T>` and `JS<T>` do not allow access to their inner value without explicitly //! creating a stack-based root via the `root` method. This returns a `Root<T>`, which causes //! the JS-owned value to be uncollectable for the duration of the `Root` object's lifetime. //! A `JSRef<T>` can be obtained from a `Root<T>` either by dereferencing the `Root<T>` (`*rooted`) //! or explicitly calling the `root_ref` method. These `JSRef<T>` values are not allowed to //! outlive their originating `Root<T>`, to ensure that all interactions with the enclosed value //! only occur when said value is uncollectable, and will cause static lifetime errors if //! misused. //! //! Other miscellaneous helper traits: //! //! - `OptionalRootable` and `OptionalRootedRootable`: make rooting `Option` values easy via a `root` method //! - `ResultRootable`: make rooting successful `Result` values easy //! - `TemporaryPushable`: allows mutating vectors of `JS<T>` with new elements of `JSRef`/`Temporary` //! - `OptionalSettable`: allows assigning `Option` values of `JSRef`/`Temporary` to fields of `Option<JS<T>>` //! - `RootedReference`: makes obtaining an `Option<JSRef<T>>` from an `Option<Root<T>>` easy use dom::bindings::utils::{Reflector, Reflectable}; use dom::node::Node; use dom::xmlhttprequest::{XMLHttpRequest, TrustedXHRAddress}; use dom::worker::{Worker, TrustedWorkerAddress}; use js::jsapi::JSObject; use layout_interface::TrustedNodeAddress; use script_task::StackRoots; use std::cell::{Cell, RefCell}; use std::kinds::marker::ContravariantLifetime; use std::mem; /// A type that represents a JS-owned value that is rooted for the lifetime of this value. /// Importantly, it requires explicit rooting in order to interact with the inner value. /// Can be assigned into JS-owned member fields (i.e. `JS<T>` types) safely via the /// `JS<T>::assign` method or `OptionalSettable::assign` (for `Option<JS<T>>` fields). #[allow(unrooted_must_root)] pub struct Temporary<T> { inner: JS<T>, /// On-stack JS pointer to assuage conservative stack scanner _js_ptr: *mut JSObject, } impl<T> PartialEq for Temporary<T> { fn eq(&self, other: &Temporary<T>) -> bool { self.inner == other.inner } } impl<T: Reflectable> Temporary<T> { /// Create a new `Temporary` value from a JS-owned value. pub fn new(inner: JS<T>) -> Temporary<T> { Temporary { inner: inner, _js_ptr: inner.reflector().get_jsobject(), } } /// Create a new `Temporary` value from a rooted value. pub fn from_rooted<'a>(root: JSRef<'a, T>) -> Temporary<T> { Temporary::new(JS::from_rooted(root)) } /// Create a stack-bounded root for this value. pub fn root<'a, 'b>(self) -> Root<'a, 'b, T> { let collection = StackRoots.get().unwrap(); unsafe { (**collection).new_root(&self.inner) } } unsafe fn inner(&self) -> JS<T> { self.inner.clone() } //XXXjdm It would be lovely if this could be private. pub unsafe fn transmute<To>(self) -> Temporary<To> { mem::transmute(self) } } /// A rooted, JS-owned value. Must only be used as a field in other JS-owned types. #[must_root] pub struct JS<T> { ptr: *const T } impl<T> PartialEq for JS<T> { #[allow(unrooted_must_root)] fn eq(&self, other: &JS<T>) -> bool { self.ptr == other.ptr } } impl <T> Clone for JS<T> { #[inline] fn clone(&self) -> JS<T> { JS { ptr: self.ptr.clone() } } } impl JS<Node> { /// Create a new JS-owned value wrapped from an address known to be a `Node` pointer. pub unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> JS<Node> { let TrustedNodeAddress(addr) = inner; JS { ptr: addr as *const Node } } } impl JS<XMLHttpRequest> { pub unsafe fn from_trusted_xhr_address(inner: TrustedXHRAddress) -> JS<XMLHttpRequest> { let TrustedXHRAddress(addr) = inner; JS { ptr: addr as *const XMLHttpRequest } } } impl JS<Worker> { pub unsafe fn from_trusted_worker_address(inner: TrustedWorkerAddress) -> JS<Worker> { let TrustedWorkerAddress(addr) = inner; JS { ptr: addr as *const Worker } } } impl<T: Reflectable> JS<T> { /// Create a new JS-owned value wrapped from a raw Rust pointer. pub unsafe fn from_raw(raw: *const T) -> JS<T> { JS { ptr: raw } } /// Root this JS-owned value to prevent its collection as garbage. pub fn root<'a, 'b>(&self) -> Root<'a, 'b, T> { let collection = StackRoots.get().unwrap(); unsafe { (**collection).new_root(self) } } } impl<T: Assignable<U>, U: Reflectable> JS<U> { pub fn from_rooted(root: T) -> JS<U> { unsafe { root.get_js() } } } //XXXjdm This is disappointing. This only gets called from trace hooks, in theory, // so it's safe to assume that self is rooted and thereby safe to access. impl<T: Reflectable> Reflectable for JS<T> { fn
<'a>(&'a self) -> &'a Reflector { unsafe { (*self.unsafe_get()).reflector() } } } impl<T: Reflectable> JS<T> { /// Returns an unsafe pointer to the interior of this JS object without touching the borrow /// flags. This is the only method that be safely accessed from layout. (The fact that this /// is unsafe is what necessitates the layout wrappers.) pub unsafe fn unsafe_get(&self) -> *mut T { mem::transmute_copy(&self.ptr) } /// Store an unrooted value in this field. This is safe under the assumption that JS<T> /// values are only used as fields in DOM types that are reachable in the GC graph, /// so this unrooted value becomes transitively rooted for the lifetime of its new owner. pub fn assign(&mut self, val: Temporary<T>) { *self = unsafe { val.inner() }; } } impl<From, To> JS<From> { //XXXjdm It would be lovely if this could be private. pub unsafe fn transmute(self) -> JS<To> { mem::transmute(self) } pub unsafe fn transmute_copy(&self) -> JS<To> { mem::transmute_copy(self) } } /// Get an `Option<JSRef<T>>` out of an `Option<Root<T>>` pub trait RootedReference<T> { fn root_ref<'a>(&'a self) -> Option<JSRef<'a, T>>; } impl<'a, 'b, T: Reflectable> RootedReference<T> for Option<Root<'a, 'b, T>> { fn root_ref<'a>(&'a self) -> Option<JSRef<'a, T>> { self.as_ref().map(|root| root.root_ref()) } } /// Get an `Option<Option<JSRef<T>>>` out of an `Option<Option<Root<T>>>` pub trait OptionalRootedReference<T> { fn root_ref<'a>(&'a self) -> Option<Option<JSRef<'a, T>>>; } impl<'a, 'b, T: Reflectable> OptionalRootedReference<T> for Option<Option<Root<'a, 'b, T>>> { fn root_ref<'a>(&'a self) -> Option<Option<JSRef<'a, T>>> { self.as_ref().map(|inner| inner.root_ref()) } } /// Trait that allows extracting a `JS<T>` value from a variety of rooting-related containers, /// which in general is an unsafe operation since they can outlive the rooted lifetime of the /// original value. /*definitely not public*/ trait Assignable<T> { unsafe fn get_js(&self) -> JS<T>; } impl<T> Assignable<T> for JS<T> { unsafe fn get_js(&self) -> JS<T> { self.clone() } } impl<'a, T: Reflectable> Assignable<T> for JSRef<'a, T> { unsafe fn get_js(&self) -> JS<T> { self.unrooted() } } impl<T: Reflectable> Assignable<T> for Temporary<T> { unsafe fn get_js(&self) -> JS<T> { self.inner() } } /// Assign an optional rootable value (either of `JS<T>` or `Temporary<T>`) to an optional /// field of a DOM type (ie. `Option<JS<T>>`) pub trait OptionalSettable<T> { fn assign(&self, val: Option<T>); } impl<T: Assignable<U>, U: Reflectable> OptionalSettable<T> for Cell<Option<JS<U>>> { fn assign(&self, val: Option<T>) { self.set(val.map(|val| unsafe { val.get_js() })); } } /// Root a rootable `Option` type (used for `Option<Temporary<T>>`) pub trait OptionalRootable<T> { fn root<'a, 'b>(self) -> Option<Root<'a, 'b, T>>; } impl<T: Reflectable> OptionalRootable<T> for Option<Temporary<T>> { fn root<'a, 'b>(self) -> Option<Root<'a, 'b, T>> { self.map(|inner| inner.root()) } } /// Return an unrooted type for storing in optional DOM fields pub trait OptionalUnrootable<T> { fn unrooted(&self) -> Option<JS<T>>; } impl<'a, T: Reflectable> OptionalUnrootable<T> for Option<JSRef<'a, T>> { fn unrooted(&self) -> Option<JS<T>> { self.as_ref().map(|inner| JS::from_rooted(*inner)) } } /// Root a rootable `Option` type (used for `Option<JS<T>>`) pub trait OptionalRootedRootable<T> { fn root<'a, 'b>(&self) -> Option<Root<'a, 'b, T>>; } impl<T: Reflectable> OptionalRootedRootable<T> for Option<JS<T>> { fn root<'a, 'b>(&self) -> Option<Root<'a, 'b, T>> { self.as_ref().map(|inner| inner.root()) } } /// Root a rootable `Option<Option>` type (used for `Option<Option<JS<T>>>`) pub trait OptionalOptionalRootedRootable<T> { fn root<'a, 'b>(&self) -> Option<Option<Root<'a, 'b, T>>>; } impl<T: Reflectable> OptionalOptionalRootedRootable<T> for Option<Option<JS<T>>> { fn root<'a, 'b>(&self) -> Option<Option<Root<'a, 'b, T>>> { self.as_ref().map(|inner| inner.root()) } } /// Root a rootable `Result` type (any of `Temporary<T>` or `JS<T>`) pub trait ResultRootable<T,U> { fn root<'a, 'b>(self) -> Result<Root<'a, 'b, T>, U>; } impl<T: Reflectable, U> ResultRootable<T, U> for Result<Temporary<T>, U> { fn root<'a, 'b>(self) -> Result<Root<'a, 'b, T>, U> { self.map(|inner| inner.root()) } } impl<T: Reflectable, U> ResultRootable<T, U> for Result<JS<T>, U> { fn root<'a, 'b>(self) -> Result<Root<'a, 'b, T>, U> { self.map(|inner| inner.root()) } } /// Provides a facility to push unrooted values onto lists of rooted values. This is safe /// under the assumption that said lists are reachable via the GC graph, and therefore the /// new values are transitively rooted for the lifetime of their new owner. pub trait TemporaryPushable<T> { fn push_unrooted(&mut self, val: &T); fn insert_unrooted(&mut self, index: uint, val: &T); } impl<T: Assignable<U>, U: Reflectable> TemporaryPushable<T> for Vec<JS<U>> { fn push_unrooted(&mut self, val: &T) { self.push(unsafe { val.get_js() }); } fn insert_unrooted(&mut self, index: uint, val: &T) { self.insert(index, unsafe { val.get_js() }); } } /// An opaque, LIFO rooting mechanism. pub struct RootCollection { roots: RefCell<Vec<*mut JSObject>>, } impl RootCollection { /// Create an empty collection of roots pub fn new() -> RootCollection { RootCollection { roots: RefCell::new(vec!()), } } /// Create a new stack-bounded root that will not outlive this collection #[allow(unrooted_must_root)] fn new_root<'a, 'b, T: Reflectable>(&'a self, unrooted: &JS<T>) -> Root<'a, 'b, T> { Root::new(self, unrooted) } /// Track a stack-based root to ensure LIFO root ordering fn root<'a, 'b, T: Reflectable>(&self, untracked: &Root<'a, 'b, T>) { let mut roots = self.roots.borrow_mut(); roots.push(untracked.js_ptr); debug!(" rooting {:?}", untracked.js_ptr); } /// Stop tracking a stack-based root, asserting if LIFO root ordering has been violated fn unroot<'a, 'b, T: Reflectable>(&self, rooted: &Root<'a, 'b, T>) { let mut roots = self.roots.borrow_mut(); debug!("unrooting {:?} (expecting {:?}", roots.last().unwrap(), rooted.js_ptr); assert!(*roots.last().unwrap() == rooted.js_ptr); roots.pop().unwrap(); } } /// A rooted JS value. The JS value is pinned for the duration of this object's lifetime; /// roots are additive, so this object's destruction will not invalidate other roots /// for the same JS value. `Root`s cannot outlive the associated `RootCollection` object. /// Attempts to transfer ownership of a `Root` via moving will trigger dynamic unrooting /// failures due to incorrect ordering. pub struct Root<'a, 'b, T> { /// List that ensures correct dynamic root ordering root_list: &'a RootCollection, /// Reference to rooted value that must not outlive this container jsref: JSRef<'b, T>, /// On-stack JS pointer to assuage conservative stack scanner js_ptr: *mut JSObject, } impl<'a, 'b, T: Reflectable> Root<'a, 'b, T> { /// Create a new stack-bounded root for the provided JS-owned value. /// It cannot not outlive its associated `RootCollection`, and it contains a `JSRef` /// which cannot outlive this new `Root`. fn new(roots: &'a RootCollection, unrooted: &JS<T>) -> Root<'a, 'b, T> { let root = Root { root_list: roots, jsref: JSRef { ptr: unrooted.ptr.clone(), chain: ContravariantLifetime, }, js_ptr: unrooted.reflector().get_jsobject(), }; roots.root(&root); root } /// Obtain a safe reference to the wrapped JS owned-value that cannot outlive /// the lifetime of this root. pub fn root_ref<'b>(&'b self) -> JSRef<'b,T> { self.jsref.clone() } } #[unsafe_destructor] impl<'a, 'b, T: Reflectable> Drop for Root<'a, 'b, T> { fn drop(&mut self) { self.root_list.unroot(self); } } impl<'a, 'b, T: Reflectable> Deref<JSRef<'b, T>> for Root<'a, 'b, T> { fn deref<'c>(&'c self) -> &'c JSRef<'b, T> { &self.jsref } } impl<'a, T: Reflectable> Deref<T> for JSRef<'a, T> { fn deref<'b>(&'b self) -> &'b T { unsafe { &*self.ptr } } } /// Encapsulates a reference to something that is guaranteed to be alive. This is freely copyable. pub struct JSRef<'a, T> { ptr: *const T, chain: ContravariantLifetime<'a>, } impl<'a, T> Clone for JSRef<'a, T> { fn clone(&self) -> JSRef<'a, T> { JSRef { ptr: self.ptr.clone(), chain: self.chain, } } } impl<'a, T> PartialEq for JSRef<'a, T> { fn eq(&self, other: &JSRef<T>) -> bool { self.ptr == other.ptr } } impl<'a,T> JSRef<'a,T> { //XXXjdm It would be lovely if this could be private. pub unsafe fn transmute<To>(self) -> JSRef<'a, To> { mem::transmute(self) } // FIXME(zwarich): It would be nice to get rid of this entirely. pub unsafe fn transmute_borrowed<'b, To>(&'b self) -> &'b JSRef<'a, To> { mem::transmute(self) } pub fn unrooted(&self) -> JS<T> { JS { ptr: self.ptr } } } impl<'a, T: Reflectable> Reflectable for JSRef<'a, T> { fn reflector<'a>(&'a self) -> &'a Reflector { self.deref().reflector() } }
reflector
identifier_name
js.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/. */ //! Smart pointers for the JS-managed DOM objects. //! //! The DOM is made up of Rust types whose lifetime is entirely controlled by the whims of //! the SpiderMonkey garbage collector. The types in this module are designed to ensure //! that any interactions with said Rust types only occur on values that will remain alive //! the entire time. //! //! Here is a brief overview of the important types: //! //! - `JSRef<T>`: a freely-copyable reference to a rooted value. //! - `Root<T>`: a stack-based reference to a rooted value. //! - `JS<T>`: a pointer to JS-owned memory that can automatically be traced by the GC when //! encountered as a field of a Rust structure. //! - `Temporary<T>`: a value that will remain rooted for the duration of its lifetime. //! //! The rule of thumb is as follows: //! //! - All methods return `Temporary<T>`, to ensure the value remains alive until it is stored //! somewhere that is reachable by the GC. //! - All functions take `JSRef<T>` arguments, to ensure that they will remain uncollected for //! the duration of their usage. //! - All types contain `JS<T>` fields and derive the `Encodable` trait, to ensure that they are //! transitively marked as reachable by the GC if the enclosing value is reachable. //! - All methods for type `T` are implemented for `JSRef<T>`, to ensure that the self value //! will not be collected for the duration of the method call. //! //! Both `Temporary<T>` and `JS<T>` do not allow access to their inner value without explicitly //! creating a stack-based root via the `root` method. This returns a `Root<T>`, which causes //! the JS-owned value to be uncollectable for the duration of the `Root` object's lifetime. //! A `JSRef<T>` can be obtained from a `Root<T>` either by dereferencing the `Root<T>` (`*rooted`) //! or explicitly calling the `root_ref` method. These `JSRef<T>` values are not allowed to //! outlive their originating `Root<T>`, to ensure that all interactions with the enclosed value //! only occur when said value is uncollectable, and will cause static lifetime errors if //! misused. //! //! Other miscellaneous helper traits: //! //! - `OptionalRootable` and `OptionalRootedRootable`: make rooting `Option` values easy via a `root` method //! - `ResultRootable`: make rooting successful `Result` values easy //! - `TemporaryPushable`: allows mutating vectors of `JS<T>` with new elements of `JSRef`/`Temporary` //! - `OptionalSettable`: allows assigning `Option` values of `JSRef`/`Temporary` to fields of `Option<JS<T>>` //! - `RootedReference`: makes obtaining an `Option<JSRef<T>>` from an `Option<Root<T>>` easy use dom::bindings::utils::{Reflector, Reflectable}; use dom::node::Node; use dom::xmlhttprequest::{XMLHttpRequest, TrustedXHRAddress}; use dom::worker::{Worker, TrustedWorkerAddress}; use js::jsapi::JSObject; use layout_interface::TrustedNodeAddress; use script_task::StackRoots; use std::cell::{Cell, RefCell}; use std::kinds::marker::ContravariantLifetime; use std::mem; /// A type that represents a JS-owned value that is rooted for the lifetime of this value. /// Importantly, it requires explicit rooting in order to interact with the inner value. /// Can be assigned into JS-owned member fields (i.e. `JS<T>` types) safely via the /// `JS<T>::assign` method or `OptionalSettable::assign` (for `Option<JS<T>>` fields). #[allow(unrooted_must_root)] pub struct Temporary<T> { inner: JS<T>, /// On-stack JS pointer to assuage conservative stack scanner _js_ptr: *mut JSObject, } impl<T> PartialEq for Temporary<T> { fn eq(&self, other: &Temporary<T>) -> bool { self.inner == other.inner } } impl<T: Reflectable> Temporary<T> { /// Create a new `Temporary` value from a JS-owned value. pub fn new(inner: JS<T>) -> Temporary<T> { Temporary { inner: inner, _js_ptr: inner.reflector().get_jsobject(), } } /// Create a new `Temporary` value from a rooted value. pub fn from_rooted<'a>(root: JSRef<'a, T>) -> Temporary<T> { Temporary::new(JS::from_rooted(root)) } /// Create a stack-bounded root for this value. pub fn root<'a, 'b>(self) -> Root<'a, 'b, T> { let collection = StackRoots.get().unwrap(); unsafe { (**collection).new_root(&self.inner) } } unsafe fn inner(&self) -> JS<T> { self.inner.clone() } //XXXjdm It would be lovely if this could be private. pub unsafe fn transmute<To>(self) -> Temporary<To> { mem::transmute(self) } } /// A rooted, JS-owned value. Must only be used as a field in other JS-owned types. #[must_root] pub struct JS<T> { ptr: *const T } impl<T> PartialEq for JS<T> { #[allow(unrooted_must_root)] fn eq(&self, other: &JS<T>) -> bool { self.ptr == other.ptr } } impl <T> Clone for JS<T> { #[inline] fn clone(&self) -> JS<T> { JS { ptr: self.ptr.clone() } } } impl JS<Node> { /// Create a new JS-owned value wrapped from an address known to be a `Node` pointer. pub unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> JS<Node> { let TrustedNodeAddress(addr) = inner; JS { ptr: addr as *const Node } } } impl JS<XMLHttpRequest> { pub unsafe fn from_trusted_xhr_address(inner: TrustedXHRAddress) -> JS<XMLHttpRequest> { let TrustedXHRAddress(addr) = inner; JS { ptr: addr as *const XMLHttpRequest } } } impl JS<Worker> { pub unsafe fn from_trusted_worker_address(inner: TrustedWorkerAddress) -> JS<Worker> { let TrustedWorkerAddress(addr) = inner; JS { ptr: addr as *const Worker } } } impl<T: Reflectable> JS<T> { /// Create a new JS-owned value wrapped from a raw Rust pointer. pub unsafe fn from_raw(raw: *const T) -> JS<T> { JS { ptr: raw } } /// Root this JS-owned value to prevent its collection as garbage. pub fn root<'a, 'b>(&self) -> Root<'a, 'b, T> { let collection = StackRoots.get().unwrap(); unsafe { (**collection).new_root(self) } } } impl<T: Assignable<U>, U: Reflectable> JS<U> { pub fn from_rooted(root: T) -> JS<U> { unsafe { root.get_js() } } } //XXXjdm This is disappointing. This only gets called from trace hooks, in theory, // so it's safe to assume that self is rooted and thereby safe to access. impl<T: Reflectable> Reflectable for JS<T> { fn reflector<'a>(&'a self) -> &'a Reflector { unsafe { (*self.unsafe_get()).reflector() } } } impl<T: Reflectable> JS<T> { /// Returns an unsafe pointer to the interior of this JS object without touching the borrow /// flags. This is the only method that be safely accessed from layout. (The fact that this /// is unsafe is what necessitates the layout wrappers.) pub unsafe fn unsafe_get(&self) -> *mut T { mem::transmute_copy(&self.ptr) } /// Store an unrooted value in this field. This is safe under the assumption that JS<T> /// values are only used as fields in DOM types that are reachable in the GC graph, /// so this unrooted value becomes transitively rooted for the lifetime of its new owner. pub fn assign(&mut self, val: Temporary<T>) { *self = unsafe { val.inner() }; } } impl<From, To> JS<From> { //XXXjdm It would be lovely if this could be private. pub unsafe fn transmute(self) -> JS<To> { mem::transmute(self) } pub unsafe fn transmute_copy(&self) -> JS<To> { mem::transmute_copy(self) } } /// Get an `Option<JSRef<T>>` out of an `Option<Root<T>>` pub trait RootedReference<T> { fn root_ref<'a>(&'a self) -> Option<JSRef<'a, T>>; } impl<'a, 'b, T: Reflectable> RootedReference<T> for Option<Root<'a, 'b, T>> { fn root_ref<'a>(&'a self) -> Option<JSRef<'a, T>> { self.as_ref().map(|root| root.root_ref()) } } /// Get an `Option<Option<JSRef<T>>>` out of an `Option<Option<Root<T>>>` pub trait OptionalRootedReference<T> { fn root_ref<'a>(&'a self) -> Option<Option<JSRef<'a, T>>>; } impl<'a, 'b, T: Reflectable> OptionalRootedReference<T> for Option<Option<Root<'a, 'b, T>>> { fn root_ref<'a>(&'a self) -> Option<Option<JSRef<'a, T>>> { self.as_ref().map(|inner| inner.root_ref()) } } /// Trait that allows extracting a `JS<T>` value from a variety of rooting-related containers, /// which in general is an unsafe operation since they can outlive the rooted lifetime of the /// original value. /*definitely not public*/ trait Assignable<T> { unsafe fn get_js(&self) -> JS<T>; } impl<T> Assignable<T> for JS<T> { unsafe fn get_js(&self) -> JS<T> { self.clone() } } impl<'a, T: Reflectable> Assignable<T> for JSRef<'a, T> { unsafe fn get_js(&self) -> JS<T> { self.unrooted() } } impl<T: Reflectable> Assignable<T> for Temporary<T> { unsafe fn get_js(&self) -> JS<T> { self.inner() } } /// Assign an optional rootable value (either of `JS<T>` or `Temporary<T>`) to an optional /// field of a DOM type (ie. `Option<JS<T>>`) pub trait OptionalSettable<T> { fn assign(&self, val: Option<T>); } impl<T: Assignable<U>, U: Reflectable> OptionalSettable<T> for Cell<Option<JS<U>>> { fn assign(&self, val: Option<T>) { self.set(val.map(|val| unsafe { val.get_js() })); } } /// Root a rootable `Option` type (used for `Option<Temporary<T>>`) pub trait OptionalRootable<T> { fn root<'a, 'b>(self) -> Option<Root<'a, 'b, T>>; } impl<T: Reflectable> OptionalRootable<T> for Option<Temporary<T>> { fn root<'a, 'b>(self) -> Option<Root<'a, 'b, T>> { self.map(|inner| inner.root()) } } /// Return an unrooted type for storing in optional DOM fields pub trait OptionalUnrootable<T> { fn unrooted(&self) -> Option<JS<T>>; } impl<'a, T: Reflectable> OptionalUnrootable<T> for Option<JSRef<'a, T>> { fn unrooted(&self) -> Option<JS<T>> { self.as_ref().map(|inner| JS::from_rooted(*inner)) } } /// Root a rootable `Option` type (used for `Option<JS<T>>`) pub trait OptionalRootedRootable<T> { fn root<'a, 'b>(&self) -> Option<Root<'a, 'b, T>>; } impl<T: Reflectable> OptionalRootedRootable<T> for Option<JS<T>> { fn root<'a, 'b>(&self) -> Option<Root<'a, 'b, T>>
} /// Root a rootable `Option<Option>` type (used for `Option<Option<JS<T>>>`) pub trait OptionalOptionalRootedRootable<T> { fn root<'a, 'b>(&self) -> Option<Option<Root<'a, 'b, T>>>; } impl<T: Reflectable> OptionalOptionalRootedRootable<T> for Option<Option<JS<T>>> { fn root<'a, 'b>(&self) -> Option<Option<Root<'a, 'b, T>>> { self.as_ref().map(|inner| inner.root()) } } /// Root a rootable `Result` type (any of `Temporary<T>` or `JS<T>`) pub trait ResultRootable<T,U> { fn root<'a, 'b>(self) -> Result<Root<'a, 'b, T>, U>; } impl<T: Reflectable, U> ResultRootable<T, U> for Result<Temporary<T>, U> { fn root<'a, 'b>(self) -> Result<Root<'a, 'b, T>, U> { self.map(|inner| inner.root()) } } impl<T: Reflectable, U> ResultRootable<T, U> for Result<JS<T>, U> { fn root<'a, 'b>(self) -> Result<Root<'a, 'b, T>, U> { self.map(|inner| inner.root()) } } /// Provides a facility to push unrooted values onto lists of rooted values. This is safe /// under the assumption that said lists are reachable via the GC graph, and therefore the /// new values are transitively rooted for the lifetime of their new owner. pub trait TemporaryPushable<T> { fn push_unrooted(&mut self, val: &T); fn insert_unrooted(&mut self, index: uint, val: &T); } impl<T: Assignable<U>, U: Reflectable> TemporaryPushable<T> for Vec<JS<U>> { fn push_unrooted(&mut self, val: &T) { self.push(unsafe { val.get_js() }); } fn insert_unrooted(&mut self, index: uint, val: &T) { self.insert(index, unsafe { val.get_js() }); } } /// An opaque, LIFO rooting mechanism. pub struct RootCollection { roots: RefCell<Vec<*mut JSObject>>, } impl RootCollection { /// Create an empty collection of roots pub fn new() -> RootCollection { RootCollection { roots: RefCell::new(vec!()), } } /// Create a new stack-bounded root that will not outlive this collection #[allow(unrooted_must_root)] fn new_root<'a, 'b, T: Reflectable>(&'a self, unrooted: &JS<T>) -> Root<'a, 'b, T> { Root::new(self, unrooted) } /// Track a stack-based root to ensure LIFO root ordering fn root<'a, 'b, T: Reflectable>(&self, untracked: &Root<'a, 'b, T>) { let mut roots = self.roots.borrow_mut(); roots.push(untracked.js_ptr); debug!(" rooting {:?}", untracked.js_ptr); } /// Stop tracking a stack-based root, asserting if LIFO root ordering has been violated fn unroot<'a, 'b, T: Reflectable>(&self, rooted: &Root<'a, 'b, T>) { let mut roots = self.roots.borrow_mut(); debug!("unrooting {:?} (expecting {:?}", roots.last().unwrap(), rooted.js_ptr); assert!(*roots.last().unwrap() == rooted.js_ptr); roots.pop().unwrap(); } } /// A rooted JS value. The JS value is pinned for the duration of this object's lifetime; /// roots are additive, so this object's destruction will not invalidate other roots /// for the same JS value. `Root`s cannot outlive the associated `RootCollection` object. /// Attempts to transfer ownership of a `Root` via moving will trigger dynamic unrooting /// failures due to incorrect ordering. pub struct Root<'a, 'b, T> { /// List that ensures correct dynamic root ordering root_list: &'a RootCollection, /// Reference to rooted value that must not outlive this container jsref: JSRef<'b, T>, /// On-stack JS pointer to assuage conservative stack scanner js_ptr: *mut JSObject, } impl<'a, 'b, T: Reflectable> Root<'a, 'b, T> { /// Create a new stack-bounded root for the provided JS-owned value. /// It cannot not outlive its associated `RootCollection`, and it contains a `JSRef` /// which cannot outlive this new `Root`. fn new(roots: &'a RootCollection, unrooted: &JS<T>) -> Root<'a, 'b, T> { let root = Root { root_list: roots, jsref: JSRef { ptr: unrooted.ptr.clone(), chain: ContravariantLifetime, }, js_ptr: unrooted.reflector().get_jsobject(), }; roots.root(&root); root } /// Obtain a safe reference to the wrapped JS owned-value that cannot outlive /// the lifetime of this root. pub fn root_ref<'b>(&'b self) -> JSRef<'b,T> { self.jsref.clone() } } #[unsafe_destructor] impl<'a, 'b, T: Reflectable> Drop for Root<'a, 'b, T> { fn drop(&mut self) { self.root_list.unroot(self); } } impl<'a, 'b, T: Reflectable> Deref<JSRef<'b, T>> for Root<'a, 'b, T> { fn deref<'c>(&'c self) -> &'c JSRef<'b, T> { &self.jsref } } impl<'a, T: Reflectable> Deref<T> for JSRef<'a, T> { fn deref<'b>(&'b self) -> &'b T { unsafe { &*self.ptr } } } /// Encapsulates a reference to something that is guaranteed to be alive. This is freely copyable. pub struct JSRef<'a, T> { ptr: *const T, chain: ContravariantLifetime<'a>, } impl<'a, T> Clone for JSRef<'a, T> { fn clone(&self) -> JSRef<'a, T> { JSRef { ptr: self.ptr.clone(), chain: self.chain, } } } impl<'a, T> PartialEq for JSRef<'a, T> { fn eq(&self, other: &JSRef<T>) -> bool { self.ptr == other.ptr } } impl<'a,T> JSRef<'a,T> { //XXXjdm It would be lovely if this could be private. pub unsafe fn transmute<To>(self) -> JSRef<'a, To> { mem::transmute(self) } // FIXME(zwarich): It would be nice to get rid of this entirely. pub unsafe fn transmute_borrowed<'b, To>(&'b self) -> &'b JSRef<'a, To> { mem::transmute(self) } pub fn unrooted(&self) -> JS<T> { JS { ptr: self.ptr } } } impl<'a, T: Reflectable> Reflectable for JSRef<'a, T> { fn reflector<'a>(&'a self) -> &'a Reflector { self.deref().reflector() } }
{ self.as_ref().map(|inner| inner.root()) }
identifier_body
js.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/. */ //! Smart pointers for the JS-managed DOM objects. //! //! The DOM is made up of Rust types whose lifetime is entirely controlled by the whims of //! the SpiderMonkey garbage collector. The types in this module are designed to ensure //! that any interactions with said Rust types only occur on values that will remain alive //! the entire time. //! //! Here is a brief overview of the important types: //! //! - `JSRef<T>`: a freely-copyable reference to a rooted value. //! - `Root<T>`: a stack-based reference to a rooted value. //! - `JS<T>`: a pointer to JS-owned memory that can automatically be traced by the GC when //! encountered as a field of a Rust structure. //! - `Temporary<T>`: a value that will remain rooted for the duration of its lifetime. //! //! The rule of thumb is as follows: //! //! - All methods return `Temporary<T>`, to ensure the value remains alive until it is stored //! somewhere that is reachable by the GC. //! - All functions take `JSRef<T>` arguments, to ensure that they will remain uncollected for //! the duration of their usage. //! - All types contain `JS<T>` fields and derive the `Encodable` trait, to ensure that they are //! transitively marked as reachable by the GC if the enclosing value is reachable. //! - All methods for type `T` are implemented for `JSRef<T>`, to ensure that the self value //! will not be collected for the duration of the method call. //! //! Both `Temporary<T>` and `JS<T>` do not allow access to their inner value without explicitly //! creating a stack-based root via the `root` method. This returns a `Root<T>`, which causes //! the JS-owned value to be uncollectable for the duration of the `Root` object's lifetime. //! A `JSRef<T>` can be obtained from a `Root<T>` either by dereferencing the `Root<T>` (`*rooted`) //! or explicitly calling the `root_ref` method. These `JSRef<T>` values are not allowed to //! outlive their originating `Root<T>`, to ensure that all interactions with the enclosed value //! only occur when said value is uncollectable, and will cause static lifetime errors if //! misused. //! //! Other miscellaneous helper traits: //! //! - `OptionalRootable` and `OptionalRootedRootable`: make rooting `Option` values easy via a `root` method //! - `ResultRootable`: make rooting successful `Result` values easy //! - `TemporaryPushable`: allows mutating vectors of `JS<T>` with new elements of `JSRef`/`Temporary` //! - `OptionalSettable`: allows assigning `Option` values of `JSRef`/`Temporary` to fields of `Option<JS<T>>` //! - `RootedReference`: makes obtaining an `Option<JSRef<T>>` from an `Option<Root<T>>` easy use dom::bindings::utils::{Reflector, Reflectable}; use dom::node::Node; use dom::xmlhttprequest::{XMLHttpRequest, TrustedXHRAddress}; use dom::worker::{Worker, TrustedWorkerAddress}; use js::jsapi::JSObject; use layout_interface::TrustedNodeAddress; use script_task::StackRoots; use std::cell::{Cell, RefCell}; use std::kinds::marker::ContravariantLifetime; use std::mem; /// A type that represents a JS-owned value that is rooted for the lifetime of this value. /// Importantly, it requires explicit rooting in order to interact with the inner value. /// Can be assigned into JS-owned member fields (i.e. `JS<T>` types) safely via the /// `JS<T>::assign` method or `OptionalSettable::assign` (for `Option<JS<T>>` fields). #[allow(unrooted_must_root)] pub struct Temporary<T> { inner: JS<T>, /// On-stack JS pointer to assuage conservative stack scanner _js_ptr: *mut JSObject, } impl<T> PartialEq for Temporary<T> { fn eq(&self, other: &Temporary<T>) -> bool { self.inner == other.inner } } impl<T: Reflectable> Temporary<T> { /// Create a new `Temporary` value from a JS-owned value. pub fn new(inner: JS<T>) -> Temporary<T> { Temporary { inner: inner, _js_ptr: inner.reflector().get_jsobject(), } } /// Create a new `Temporary` value from a rooted value. pub fn from_rooted<'a>(root: JSRef<'a, T>) -> Temporary<T> { Temporary::new(JS::from_rooted(root)) } /// Create a stack-bounded root for this value. pub fn root<'a, 'b>(self) -> Root<'a, 'b, T> { let collection = StackRoots.get().unwrap(); unsafe { (**collection).new_root(&self.inner) } } unsafe fn inner(&self) -> JS<T> { self.inner.clone() } //XXXjdm It would be lovely if this could be private. pub unsafe fn transmute<To>(self) -> Temporary<To> { mem::transmute(self) } } /// A rooted, JS-owned value. Must only be used as a field in other JS-owned types. #[must_root] pub struct JS<T> { ptr: *const T } impl<T> PartialEq for JS<T> { #[allow(unrooted_must_root)] fn eq(&self, other: &JS<T>) -> bool { self.ptr == other.ptr } } impl <T> Clone for JS<T> { #[inline] fn clone(&self) -> JS<T> { JS { ptr: self.ptr.clone() } } } impl JS<Node> { /// Create a new JS-owned value wrapped from an address known to be a `Node` pointer. pub unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> JS<Node> { let TrustedNodeAddress(addr) = inner; JS { ptr: addr as *const Node } } } impl JS<XMLHttpRequest> { pub unsafe fn from_trusted_xhr_address(inner: TrustedXHRAddress) -> JS<XMLHttpRequest> { let TrustedXHRAddress(addr) = inner; JS { ptr: addr as *const XMLHttpRequest } } } impl JS<Worker> { pub unsafe fn from_trusted_worker_address(inner: TrustedWorkerAddress) -> JS<Worker> { let TrustedWorkerAddress(addr) = inner; JS {
} } } impl<T: Reflectable> JS<T> { /// Create a new JS-owned value wrapped from a raw Rust pointer. pub unsafe fn from_raw(raw: *const T) -> JS<T> { JS { ptr: raw } } /// Root this JS-owned value to prevent its collection as garbage. pub fn root<'a, 'b>(&self) -> Root<'a, 'b, T> { let collection = StackRoots.get().unwrap(); unsafe { (**collection).new_root(self) } } } impl<T: Assignable<U>, U: Reflectable> JS<U> { pub fn from_rooted(root: T) -> JS<U> { unsafe { root.get_js() } } } //XXXjdm This is disappointing. This only gets called from trace hooks, in theory, // so it's safe to assume that self is rooted and thereby safe to access. impl<T: Reflectable> Reflectable for JS<T> { fn reflector<'a>(&'a self) -> &'a Reflector { unsafe { (*self.unsafe_get()).reflector() } } } impl<T: Reflectable> JS<T> { /// Returns an unsafe pointer to the interior of this JS object without touching the borrow /// flags. This is the only method that be safely accessed from layout. (The fact that this /// is unsafe is what necessitates the layout wrappers.) pub unsafe fn unsafe_get(&self) -> *mut T { mem::transmute_copy(&self.ptr) } /// Store an unrooted value in this field. This is safe under the assumption that JS<T> /// values are only used as fields in DOM types that are reachable in the GC graph, /// so this unrooted value becomes transitively rooted for the lifetime of its new owner. pub fn assign(&mut self, val: Temporary<T>) { *self = unsafe { val.inner() }; } } impl<From, To> JS<From> { //XXXjdm It would be lovely if this could be private. pub unsafe fn transmute(self) -> JS<To> { mem::transmute(self) } pub unsafe fn transmute_copy(&self) -> JS<To> { mem::transmute_copy(self) } } /// Get an `Option<JSRef<T>>` out of an `Option<Root<T>>` pub trait RootedReference<T> { fn root_ref<'a>(&'a self) -> Option<JSRef<'a, T>>; } impl<'a, 'b, T: Reflectable> RootedReference<T> for Option<Root<'a, 'b, T>> { fn root_ref<'a>(&'a self) -> Option<JSRef<'a, T>> { self.as_ref().map(|root| root.root_ref()) } } /// Get an `Option<Option<JSRef<T>>>` out of an `Option<Option<Root<T>>>` pub trait OptionalRootedReference<T> { fn root_ref<'a>(&'a self) -> Option<Option<JSRef<'a, T>>>; } impl<'a, 'b, T: Reflectable> OptionalRootedReference<T> for Option<Option<Root<'a, 'b, T>>> { fn root_ref<'a>(&'a self) -> Option<Option<JSRef<'a, T>>> { self.as_ref().map(|inner| inner.root_ref()) } } /// Trait that allows extracting a `JS<T>` value from a variety of rooting-related containers, /// which in general is an unsafe operation since they can outlive the rooted lifetime of the /// original value. /*definitely not public*/ trait Assignable<T> { unsafe fn get_js(&self) -> JS<T>; } impl<T> Assignable<T> for JS<T> { unsafe fn get_js(&self) -> JS<T> { self.clone() } } impl<'a, T: Reflectable> Assignable<T> for JSRef<'a, T> { unsafe fn get_js(&self) -> JS<T> { self.unrooted() } } impl<T: Reflectable> Assignable<T> for Temporary<T> { unsafe fn get_js(&self) -> JS<T> { self.inner() } } /// Assign an optional rootable value (either of `JS<T>` or `Temporary<T>`) to an optional /// field of a DOM type (ie. `Option<JS<T>>`) pub trait OptionalSettable<T> { fn assign(&self, val: Option<T>); } impl<T: Assignable<U>, U: Reflectable> OptionalSettable<T> for Cell<Option<JS<U>>> { fn assign(&self, val: Option<T>) { self.set(val.map(|val| unsafe { val.get_js() })); } } /// Root a rootable `Option` type (used for `Option<Temporary<T>>`) pub trait OptionalRootable<T> { fn root<'a, 'b>(self) -> Option<Root<'a, 'b, T>>; } impl<T: Reflectable> OptionalRootable<T> for Option<Temporary<T>> { fn root<'a, 'b>(self) -> Option<Root<'a, 'b, T>> { self.map(|inner| inner.root()) } } /// Return an unrooted type for storing in optional DOM fields pub trait OptionalUnrootable<T> { fn unrooted(&self) -> Option<JS<T>>; } impl<'a, T: Reflectable> OptionalUnrootable<T> for Option<JSRef<'a, T>> { fn unrooted(&self) -> Option<JS<T>> { self.as_ref().map(|inner| JS::from_rooted(*inner)) } } /// Root a rootable `Option` type (used for `Option<JS<T>>`) pub trait OptionalRootedRootable<T> { fn root<'a, 'b>(&self) -> Option<Root<'a, 'b, T>>; } impl<T: Reflectable> OptionalRootedRootable<T> for Option<JS<T>> { fn root<'a, 'b>(&self) -> Option<Root<'a, 'b, T>> { self.as_ref().map(|inner| inner.root()) } } /// Root a rootable `Option<Option>` type (used for `Option<Option<JS<T>>>`) pub trait OptionalOptionalRootedRootable<T> { fn root<'a, 'b>(&self) -> Option<Option<Root<'a, 'b, T>>>; } impl<T: Reflectable> OptionalOptionalRootedRootable<T> for Option<Option<JS<T>>> { fn root<'a, 'b>(&self) -> Option<Option<Root<'a, 'b, T>>> { self.as_ref().map(|inner| inner.root()) } } /// Root a rootable `Result` type (any of `Temporary<T>` or `JS<T>`) pub trait ResultRootable<T,U> { fn root<'a, 'b>(self) -> Result<Root<'a, 'b, T>, U>; } impl<T: Reflectable, U> ResultRootable<T, U> for Result<Temporary<T>, U> { fn root<'a, 'b>(self) -> Result<Root<'a, 'b, T>, U> { self.map(|inner| inner.root()) } } impl<T: Reflectable, U> ResultRootable<T, U> for Result<JS<T>, U> { fn root<'a, 'b>(self) -> Result<Root<'a, 'b, T>, U> { self.map(|inner| inner.root()) } } /// Provides a facility to push unrooted values onto lists of rooted values. This is safe /// under the assumption that said lists are reachable via the GC graph, and therefore the /// new values are transitively rooted for the lifetime of their new owner. pub trait TemporaryPushable<T> { fn push_unrooted(&mut self, val: &T); fn insert_unrooted(&mut self, index: uint, val: &T); } impl<T: Assignable<U>, U: Reflectable> TemporaryPushable<T> for Vec<JS<U>> { fn push_unrooted(&mut self, val: &T) { self.push(unsafe { val.get_js() }); } fn insert_unrooted(&mut self, index: uint, val: &T) { self.insert(index, unsafe { val.get_js() }); } } /// An opaque, LIFO rooting mechanism. pub struct RootCollection { roots: RefCell<Vec<*mut JSObject>>, } impl RootCollection { /// Create an empty collection of roots pub fn new() -> RootCollection { RootCollection { roots: RefCell::new(vec!()), } } /// Create a new stack-bounded root that will not outlive this collection #[allow(unrooted_must_root)] fn new_root<'a, 'b, T: Reflectable>(&'a self, unrooted: &JS<T>) -> Root<'a, 'b, T> { Root::new(self, unrooted) } /// Track a stack-based root to ensure LIFO root ordering fn root<'a, 'b, T: Reflectable>(&self, untracked: &Root<'a, 'b, T>) { let mut roots = self.roots.borrow_mut(); roots.push(untracked.js_ptr); debug!(" rooting {:?}", untracked.js_ptr); } /// Stop tracking a stack-based root, asserting if LIFO root ordering has been violated fn unroot<'a, 'b, T: Reflectable>(&self, rooted: &Root<'a, 'b, T>) { let mut roots = self.roots.borrow_mut(); debug!("unrooting {:?} (expecting {:?}", roots.last().unwrap(), rooted.js_ptr); assert!(*roots.last().unwrap() == rooted.js_ptr); roots.pop().unwrap(); } } /// A rooted JS value. The JS value is pinned for the duration of this object's lifetime; /// roots are additive, so this object's destruction will not invalidate other roots /// for the same JS value. `Root`s cannot outlive the associated `RootCollection` object. /// Attempts to transfer ownership of a `Root` via moving will trigger dynamic unrooting /// failures due to incorrect ordering. pub struct Root<'a, 'b, T> { /// List that ensures correct dynamic root ordering root_list: &'a RootCollection, /// Reference to rooted value that must not outlive this container jsref: JSRef<'b, T>, /// On-stack JS pointer to assuage conservative stack scanner js_ptr: *mut JSObject, } impl<'a, 'b, T: Reflectable> Root<'a, 'b, T> { /// Create a new stack-bounded root for the provided JS-owned value. /// It cannot not outlive its associated `RootCollection`, and it contains a `JSRef` /// which cannot outlive this new `Root`. fn new(roots: &'a RootCollection, unrooted: &JS<T>) -> Root<'a, 'b, T> { let root = Root { root_list: roots, jsref: JSRef { ptr: unrooted.ptr.clone(), chain: ContravariantLifetime, }, js_ptr: unrooted.reflector().get_jsobject(), }; roots.root(&root); root } /// Obtain a safe reference to the wrapped JS owned-value that cannot outlive /// the lifetime of this root. pub fn root_ref<'b>(&'b self) -> JSRef<'b,T> { self.jsref.clone() } } #[unsafe_destructor] impl<'a, 'b, T: Reflectable> Drop for Root<'a, 'b, T> { fn drop(&mut self) { self.root_list.unroot(self); } } impl<'a, 'b, T: Reflectable> Deref<JSRef<'b, T>> for Root<'a, 'b, T> { fn deref<'c>(&'c self) -> &'c JSRef<'b, T> { &self.jsref } } impl<'a, T: Reflectable> Deref<T> for JSRef<'a, T> { fn deref<'b>(&'b self) -> &'b T { unsafe { &*self.ptr } } } /// Encapsulates a reference to something that is guaranteed to be alive. This is freely copyable. pub struct JSRef<'a, T> { ptr: *const T, chain: ContravariantLifetime<'a>, } impl<'a, T> Clone for JSRef<'a, T> { fn clone(&self) -> JSRef<'a, T> { JSRef { ptr: self.ptr.clone(), chain: self.chain, } } } impl<'a, T> PartialEq for JSRef<'a, T> { fn eq(&self, other: &JSRef<T>) -> bool { self.ptr == other.ptr } } impl<'a,T> JSRef<'a,T> { //XXXjdm It would be lovely if this could be private. pub unsafe fn transmute<To>(self) -> JSRef<'a, To> { mem::transmute(self) } // FIXME(zwarich): It would be nice to get rid of this entirely. pub unsafe fn transmute_borrowed<'b, To>(&'b self) -> &'b JSRef<'a, To> { mem::transmute(self) } pub fn unrooted(&self) -> JS<T> { JS { ptr: self.ptr } } } impl<'a, T: Reflectable> Reflectable for JSRef<'a, T> { fn reflector<'a>(&'a self) -> &'a Reflector { self.deref().reflector() } }
ptr: addr as *const Worker
random_line_split
column_family.rs
// Copyright 2020 Tyler Neely // // 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::{db::MultiThreaded, ffi, Options}; use std::sync::Arc; /// The name of the default column family. /// /// The column family with this name is created implicitly whenever column /// families are used. pub const DEFAULT_COLUMN_FAMILY_NAME: &str = "default"; /// A descriptor for a RocksDB column family. /// /// A description of the column family, containing the name and `Options`. pub struct ColumnFamilyDescriptor { pub(crate) name: String, pub(crate) options: Options, } impl ColumnFamilyDescriptor { // Create a new column family descriptor with the specified name and options. pub fn new<S>(name: S, options: Options) -> Self where S: Into<String>, {
name: name.into(), options, } } } /// An opaque type used to represent a column family. Returned from some functions, and used /// in others pub struct ColumnFamily { pub(crate) inner: *mut ffi::rocksdb_column_family_handle_t, } /// A specialized opaque type used to represent a column family by the [`MultiThreaded`] /// mode. Clone (and Copy) is derived to behave like `&ColumnFamily` (this is used for /// single-threaded mode). `Clone`/`Copy` is safe because this lifetime is bound to DB like /// iterators/snapshots. On top of it, this is as cheap and small as `&ColumnFamily` because /// this only has a single pointer-wide field. pub struct BoundColumnFamily<'a> { pub(crate) inner: *mut ffi::rocksdb_column_family_handle_t, pub(crate) multi_threaded_cfs: std::marker::PhantomData<&'a MultiThreaded>, } // internal struct which isn't exposed to public api. // but its memory will be exposed after transmute()-ing to BoundColumnFamily. // ColumnFamily's lifetime should be bound to DB. But, db holds cfs and cfs can't easily // self-reference DB as its lifetime due to rust's type system pub(crate) struct UnboundColumnFamily { pub(crate) inner: *mut ffi::rocksdb_column_family_handle_t, } impl UnboundColumnFamily { pub(crate) fn bound_column_family<'a>(self: Arc<Self>) -> Arc<BoundColumnFamily<'a>> { // SAFETY: the new BoundColumnFamily here just adding lifetime, // so that column family handle won't outlive db. unsafe { std::mem::transmute(self) } } } fn destroy_handle(handle: *mut ffi::rocksdb_column_family_handle_t) { // SAFETY: This should be called only from various Drop::drop(), strictly keeping a 1-to-1 // ownership to avoid double invocation to the rocksdb function with same handle. unsafe { ffi::rocksdb_column_family_handle_destroy(handle); } } impl Drop for ColumnFamily { fn drop(&mut self) { destroy_handle(self.inner); } } // these behaviors must be identical between BoundColumnFamily and UnboundColumnFamily // due to the unsafe transmute() in bound_column_family()! impl<'a> Drop for BoundColumnFamily<'a> { fn drop(&mut self) { destroy_handle(self.inner); } } impl Drop for UnboundColumnFamily { fn drop(&mut self) { destroy_handle(self.inner); } } /// Handy type alias to hide actual type difference to reference [`ColumnFamily`] /// depending on the `multi-threaded-cf` crate feature. #[cfg(not(feature = "multi-threaded-cf"))] pub type ColumnFamilyRef<'a> = &'a ColumnFamily; #[cfg(feature = "multi-threaded-cf")] pub type ColumnFamilyRef<'a> = Arc<BoundColumnFamily<'a>>; /// Utility trait to accept both supported references to `ColumnFamily` /// (`&ColumnFamily` and `BoundColumnFamily`) pub trait AsColumnFamilyRef { fn inner(&self) -> *mut ffi::rocksdb_column_family_handle_t; } impl AsColumnFamilyRef for ColumnFamily { fn inner(&self) -> *mut ffi::rocksdb_column_family_handle_t { self.inner } } impl<'a> AsColumnFamilyRef for &'a ColumnFamily { fn inner(&self) -> *mut ffi::rocksdb_column_family_handle_t { self.inner } } // Only implement for Arc-ed BoundColumnFamily as this tightly coupled and // implementation detail, considering use of std::mem::transmute. BoundColumnFamily // isn't expected to be used as naked. // Also, ColumnFamilyRef might not be Arc<BoundColumnFamily<'a>> depending crate // feature flags so, we can't use the type alias here. impl<'a> AsColumnFamilyRef for Arc<BoundColumnFamily<'a>> { fn inner(&self) -> *mut ffi::rocksdb_column_family_handle_t { self.inner } } unsafe impl Send for ColumnFamily {} unsafe impl<'a> Send for BoundColumnFamily<'a> {}
Self {
random_line_split
column_family.rs
// Copyright 2020 Tyler Neely // // 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::{db::MultiThreaded, ffi, Options}; use std::sync::Arc; /// The name of the default column family. /// /// The column family with this name is created implicitly whenever column /// families are used. pub const DEFAULT_COLUMN_FAMILY_NAME: &str = "default"; /// A descriptor for a RocksDB column family. /// /// A description of the column family, containing the name and `Options`. pub struct
{ pub(crate) name: String, pub(crate) options: Options, } impl ColumnFamilyDescriptor { // Create a new column family descriptor with the specified name and options. pub fn new<S>(name: S, options: Options) -> Self where S: Into<String>, { Self { name: name.into(), options, } } } /// An opaque type used to represent a column family. Returned from some functions, and used /// in others pub struct ColumnFamily { pub(crate) inner: *mut ffi::rocksdb_column_family_handle_t, } /// A specialized opaque type used to represent a column family by the [`MultiThreaded`] /// mode. Clone (and Copy) is derived to behave like `&ColumnFamily` (this is used for /// single-threaded mode). `Clone`/`Copy` is safe because this lifetime is bound to DB like /// iterators/snapshots. On top of it, this is as cheap and small as `&ColumnFamily` because /// this only has a single pointer-wide field. pub struct BoundColumnFamily<'a> { pub(crate) inner: *mut ffi::rocksdb_column_family_handle_t, pub(crate) multi_threaded_cfs: std::marker::PhantomData<&'a MultiThreaded>, } // internal struct which isn't exposed to public api. // but its memory will be exposed after transmute()-ing to BoundColumnFamily. // ColumnFamily's lifetime should be bound to DB. But, db holds cfs and cfs can't easily // self-reference DB as its lifetime due to rust's type system pub(crate) struct UnboundColumnFamily { pub(crate) inner: *mut ffi::rocksdb_column_family_handle_t, } impl UnboundColumnFamily { pub(crate) fn bound_column_family<'a>(self: Arc<Self>) -> Arc<BoundColumnFamily<'a>> { // SAFETY: the new BoundColumnFamily here just adding lifetime, // so that column family handle won't outlive db. unsafe { std::mem::transmute(self) } } } fn destroy_handle(handle: *mut ffi::rocksdb_column_family_handle_t) { // SAFETY: This should be called only from various Drop::drop(), strictly keeping a 1-to-1 // ownership to avoid double invocation to the rocksdb function with same handle. unsafe { ffi::rocksdb_column_family_handle_destroy(handle); } } impl Drop for ColumnFamily { fn drop(&mut self) { destroy_handle(self.inner); } } // these behaviors must be identical between BoundColumnFamily and UnboundColumnFamily // due to the unsafe transmute() in bound_column_family()! impl<'a> Drop for BoundColumnFamily<'a> { fn drop(&mut self) { destroy_handle(self.inner); } } impl Drop for UnboundColumnFamily { fn drop(&mut self) { destroy_handle(self.inner); } } /// Handy type alias to hide actual type difference to reference [`ColumnFamily`] /// depending on the `multi-threaded-cf` crate feature. #[cfg(not(feature = "multi-threaded-cf"))] pub type ColumnFamilyRef<'a> = &'a ColumnFamily; #[cfg(feature = "multi-threaded-cf")] pub type ColumnFamilyRef<'a> = Arc<BoundColumnFamily<'a>>; /// Utility trait to accept both supported references to `ColumnFamily` /// (`&ColumnFamily` and `BoundColumnFamily`) pub trait AsColumnFamilyRef { fn inner(&self) -> *mut ffi::rocksdb_column_family_handle_t; } impl AsColumnFamilyRef for ColumnFamily { fn inner(&self) -> *mut ffi::rocksdb_column_family_handle_t { self.inner } } impl<'a> AsColumnFamilyRef for &'a ColumnFamily { fn inner(&self) -> *mut ffi::rocksdb_column_family_handle_t { self.inner } } // Only implement for Arc-ed BoundColumnFamily as this tightly coupled and // implementation detail, considering use of std::mem::transmute. BoundColumnFamily // isn't expected to be used as naked. // Also, ColumnFamilyRef might not be Arc<BoundColumnFamily<'a>> depending crate // feature flags so, we can't use the type alias here. impl<'a> AsColumnFamilyRef for Arc<BoundColumnFamily<'a>> { fn inner(&self) -> *mut ffi::rocksdb_column_family_handle_t { self.inner } } unsafe impl Send for ColumnFamily {} unsafe impl<'a> Send for BoundColumnFamily<'a> {}
ColumnFamilyDescriptor
identifier_name
issue-662-cannot-find-T-in-this-scope.rs
/* automatically generated by rust-bindgen */ #![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct RefPtr<T> { pub a: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>, } impl<T> Default for RefPtr<T> { fn
() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct nsMainThreadPtrHolder<T> { pub a: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>, } impl<T> Default for nsMainThreadPtrHolder<T> { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct nsMainThreadPtrHandle<T> { pub mPtr: RefPtr<nsMainThreadPtrHolder<T>>, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>, } impl<T> Default for nsMainThreadPtrHandle<T> { fn default() -> Self { unsafe { ::std::mem::zeroed() } } }
default
identifier_name
issue-662-cannot-find-T-in-this-scope.rs
/* automatically generated by rust-bindgen */ #![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct RefPtr<T> {
} impl<T> Default for RefPtr<T> { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct nsMainThreadPtrHolder<T> { pub a: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>, } impl<T> Default for nsMainThreadPtrHolder<T> { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct nsMainThreadPtrHandle<T> { pub mPtr: RefPtr<nsMainThreadPtrHolder<T>>, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>, } impl<T> Default for nsMainThreadPtrHandle<T> { fn default() -> Self { unsafe { ::std::mem::zeroed() } } }
pub a: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>,
random_line_split
thread.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 actor::{Actor, ActorMessageStatus, ActorRegistry}; use protocol::JsonPacketStream; use rustc_serialize::json; use std::net::TcpStream; #[derive(RustcEncodable)] struct ThreadAttachedReply { from: String, __type__: String, actor: String, poppedFrames: Vec<PoppedFrameMsg>, why: WhyMsg, } #[derive(RustcEncodable)] enum PoppedFrameMsg {} #[derive(RustcEncodable)] struct WhyMsg { __type__: String, } #[derive(RustcEncodable)] struct ThreadResumedReply {
struct ReconfigureReply { from: String } pub struct ThreadActor { name: String, } impl ThreadActor { pub fn new(name: String) -> ThreadActor { ThreadActor { name: name, } } } impl Actor for ThreadActor { fn name(&self) -> String { self.name.clone() } fn handle_message(&self, registry: &ActorRegistry, msg_type: &str, _msg: &json::Object, stream: &mut TcpStream) -> Result<ActorMessageStatus, ()> { Ok(match msg_type { "attach" => { let msg = ThreadAttachedReply { from: self.name(), __type__: "paused".to_owned(), actor: registry.new_name("pause"), poppedFrames: vec![], why: WhyMsg { __type__: "attached".to_owned() }, }; stream.write_json_packet(&msg); ActorMessageStatus::Processed }, "resume" => { let msg = ThreadResumedReply { from: self.name(), __type__: "resumed".to_owned(), }; stream.write_json_packet(&msg); ActorMessageStatus::Processed }, "reconfigure" => { stream.write_json_packet(&ReconfigureReply { from: self.name() }); ActorMessageStatus::Processed } _ => ActorMessageStatus::Ignored, }) } }
from: String, __type__: String, } #[derive(RustcEncodable)]
random_line_split
thread.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 actor::{Actor, ActorMessageStatus, ActorRegistry}; use protocol::JsonPacketStream; use rustc_serialize::json; use std::net::TcpStream; #[derive(RustcEncodable)] struct ThreadAttachedReply { from: String, __type__: String, actor: String, poppedFrames: Vec<PoppedFrameMsg>, why: WhyMsg, } #[derive(RustcEncodable)] enum PoppedFrameMsg {} #[derive(RustcEncodable)] struct WhyMsg { __type__: String, } #[derive(RustcEncodable)] struct ThreadResumedReply { from: String, __type__: String, } #[derive(RustcEncodable)] struct ReconfigureReply { from: String } pub struct ThreadActor { name: String, } impl ThreadActor { pub fn new(name: String) -> ThreadActor { ThreadActor { name: name, } } } impl Actor for ThreadActor { fn name(&self) -> String { self.name.clone() } fn handle_message(&self, registry: &ActorRegistry, msg_type: &str, _msg: &json::Object, stream: &mut TcpStream) -> Result<ActorMessageStatus, ()> { Ok(match msg_type { "attach" => { let msg = ThreadAttachedReply { from: self.name(), __type__: "paused".to_owned(), actor: registry.new_name("pause"), poppedFrames: vec![], why: WhyMsg { __type__: "attached".to_owned() }, }; stream.write_json_packet(&msg); ActorMessageStatus::Processed }, "resume" =>
, "reconfigure" => { stream.write_json_packet(&ReconfigureReply { from: self.name() }); ActorMessageStatus::Processed } _ => ActorMessageStatus::Ignored, }) } }
{ let msg = ThreadResumedReply { from: self.name(), __type__: "resumed".to_owned(), }; stream.write_json_packet(&msg); ActorMessageStatus::Processed }
conditional_block
thread.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 actor::{Actor, ActorMessageStatus, ActorRegistry}; use protocol::JsonPacketStream; use rustc_serialize::json; use std::net::TcpStream; #[derive(RustcEncodable)] struct ThreadAttachedReply { from: String, __type__: String, actor: String, poppedFrames: Vec<PoppedFrameMsg>, why: WhyMsg, } #[derive(RustcEncodable)] enum PoppedFrameMsg {} #[derive(RustcEncodable)] struct WhyMsg { __type__: String, } #[derive(RustcEncodable)] struct ThreadResumedReply { from: String, __type__: String, } #[derive(RustcEncodable)] struct ReconfigureReply { from: String } pub struct ThreadActor { name: String, } impl ThreadActor { pub fn new(name: String) -> ThreadActor { ThreadActor { name: name, } } } impl Actor for ThreadActor { fn name(&self) -> String { self.name.clone() } fn
(&self, registry: &ActorRegistry, msg_type: &str, _msg: &json::Object, stream: &mut TcpStream) -> Result<ActorMessageStatus, ()> { Ok(match msg_type { "attach" => { let msg = ThreadAttachedReply { from: self.name(), __type__: "paused".to_owned(), actor: registry.new_name("pause"), poppedFrames: vec![], why: WhyMsg { __type__: "attached".to_owned() }, }; stream.write_json_packet(&msg); ActorMessageStatus::Processed }, "resume" => { let msg = ThreadResumedReply { from: self.name(), __type__: "resumed".to_owned(), }; stream.write_json_packet(&msg); ActorMessageStatus::Processed }, "reconfigure" => { stream.write_json_packet(&ReconfigureReply { from: self.name() }); ActorMessageStatus::Processed } _ => ActorMessageStatus::Ignored, }) } }
handle_message
identifier_name
main.rs
use gtk::prelude::*; use relm::Widget; use relm_derive::{widget, Msg}; /// The messages sent to the `Win` widget. #[derive(Msg)] pub enum Msg { Increment, Quit, } /// The model the `Win` widget uses. /// This is current count of the counter. pub struct Model { counter: u64, } /// The widget containing the main window and the counter. #[widget] impl Widget for Win { /// Get the default model for the widget. /// The counter will start at `0`. fn model() -> Model { Model { counter: 0 } } /// This will be called when a message was sent. fn update(&mut self, event: Msg) { match event { // Increment the counter Msg::Increment => { self.model.counter += 1; } // Quit the application Msg::Quit => gtk::main_quit(), } } // This macro builds the application. view! { gtk::Window { gtk::Box { // The label showing the text. gtk::Label { // The text in the label. Will be updated when `self.model.counter` changed. label: &self.model.counter.to_string() }, // The button to increment the counter. gtk::Button { label: "Count", // Clicking the button will send the `Increment` message to the `Win` widget. clicked => Msg::Increment }
}, delete_event(_, _) => (Msg::Quit, Inhibit(false)), } } } fn main() { // Run the application. Win::run(()).expect("Win::run failed"); }
random_line_split
main.rs
use gtk::prelude::*; use relm::Widget; use relm_derive::{widget, Msg}; /// The messages sent to the `Win` widget. #[derive(Msg)] pub enum Msg { Increment, Quit, } /// The model the `Win` widget uses. /// This is current count of the counter. pub struct Model { counter: u64, } /// The widget containing the main window and the counter. #[widget] impl Widget for Win { /// Get the default model for the widget. /// The counter will start at `0`. fn model() -> Model { Model { counter: 0 } } /// This will be called when a message was sent. fn update(&mut self, event: Msg) { match event { // Increment the counter Msg::Increment =>
// Quit the application Msg::Quit => gtk::main_quit(), } } // This macro builds the application. view! { gtk::Window { gtk::Box { // The label showing the text. gtk::Label { // The text in the label. Will be updated when `self.model.counter` changed. label: &self.model.counter.to_string() }, // The button to increment the counter. gtk::Button { label: "Count", // Clicking the button will send the `Increment` message to the `Win` widget. clicked => Msg::Increment } }, delete_event(_, _) => (Msg::Quit, Inhibit(false)), } } } fn main() { // Run the application. Win::run(()).expect("Win::run failed"); }
{ self.model.counter += 1; }
conditional_block
main.rs
use gtk::prelude::*; use relm::Widget; use relm_derive::{widget, Msg}; /// The messages sent to the `Win` widget. #[derive(Msg)] pub enum Msg { Increment, Quit, } /// The model the `Win` widget uses. /// This is current count of the counter. pub struct Model { counter: u64, } /// The widget containing the main window and the counter. #[widget] impl Widget for Win { /// Get the default model for the widget. /// The counter will start at `0`. fn model() -> Model { Model { counter: 0 } } /// This will be called when a message was sent. fn update(&mut self, event: Msg) { match event { // Increment the counter Msg::Increment => { self.model.counter += 1; } // Quit the application Msg::Quit => gtk::main_quit(), } } // This macro builds the application. view! { gtk::Window { gtk::Box { // The label showing the text. gtk::Label { // The text in the label. Will be updated when `self.model.counter` changed. label: &self.model.counter.to_string() }, // The button to increment the counter. gtk::Button { label: "Count", // Clicking the button will send the `Increment` message to the `Win` widget. clicked => Msg::Increment } }, delete_event(_, _) => (Msg::Quit, Inhibit(false)), } } } fn
() { // Run the application. Win::run(()).expect("Win::run failed"); }
main
identifier_name
db.rs
use super::{ entities::*, error::RepoError, repositories::*, util::{ geo::{MapBbox, MapPoint}, time::{Timestamp, TimestampMs}, }, }; use anyhow::Result as Fallible; type Result<T> = std::result::Result<T, RepoError>; #[derive(Clone, Debug)] pub struct MostPopularTagsParams { pub min_count: Option<u64>, pub max_count: Option<u64>, } #[derive(Clone, Debug)] pub struct RecentlyChangedEntriesParams { pub since: Option<TimestampMs>, pub until: Option<TimestampMs>, } pub trait PlaceRepo { fn get_place(&self, id: &str) -> Result<(Place, ReviewStatus)>; fn get_places(&self, ids: &[&str]) -> Result<Vec<(Place, ReviewStatus)>>; fn all_places(&self) -> Result<Vec<(Place, ReviewStatus)>>; fn count_places(&self) -> Result<usize>; fn recently_changed_places( &self, params: &RecentlyChangedEntriesParams, pagination: &Pagination, ) -> Result<Vec<(Place, ReviewStatus, ActivityLog)>>; fn most_popular_place_revision_tags( &self, params: &MostPopularTagsParams, pagination: &Pagination, ) -> Result<Vec<TagFrequency>>; fn review_places( &self, ids: &[&str], status: ReviewStatus, activity: &ActivityLog, ) -> Result<usize>; fn create_or_update_place(&self, place: Place) -> Result<()>; fn get_place_history(&self, id: &str) -> Result<PlaceHistory>; } pub trait EventGateway { fn create_event(&self, _: Event) -> Result<()>; fn update_event(&self, _: &Event) -> Result<()>; fn archive_events(&self, ids: &[&str], archived: Timestamp) -> Result<usize>; fn get_event(&self, id: &str) -> Result<Event>; fn get_events_chronologically(&self, ids: &[&str]) -> Result<Vec<Event>>; fn all_events_chronologically(&self) -> Result<Vec<Event>>; fn count_events(&self) -> Result<usize>; // Delete an event, but only if tagged with at least one of the given tags // Ok(Some(())) => Found and deleted // Ok(None) => No matching tags // TODO: Use explicit result semantics fn delete_event_with_matching_tags(&self, id: &str, tags: &[&str]) -> Result<Option<()>>; } pub trait UserGateway { fn create_user(&self, user: &User) -> Result<()>; fn update_user(&self, user: &User) -> Result<()>; fn delete_user_by_email(&self, email: &str) -> Result<()>; fn all_users(&self) -> Result<Vec<User>>; fn count_users(&self) -> Result<usize>; fn get_user_by_email(&self, email: &str) -> Result<User>; fn try_get_user_by_email(&self, email: &str) -> Result<Option<User>>; } pub trait OrganizationGateway { fn create_org(&mut self, _: Organization) -> Result<()>; fn get_org_by_api_token(&self, token: &str) -> Result<Organization>; fn get_all_tags_owned_by_orgs(&self) -> Result<Vec<String>>; } //TODO: // - TagGeatway // - SubscriptionGateway #[derive(Clone, Debug, Default)] pub struct Pagination { pub offset: Option<u64>, pub limit: Option<u64>, } pub trait Db: PlaceRepo + UserGateway + EventGateway + OrganizationGateway + CommentRepository + RatingRepository + UserTokenRepo { fn create_tag_if_it_does_not_exist(&self, _: &Tag) -> Result<()>; fn all_categories(&self) -> Result<Vec<Category>> { Ok(vec![ Category::new_non_profit(), Category::new_commercial(), Category::new_event(), ]) } fn all_tags(&self) -> Result<Vec<Tag>>; fn count_tags(&self) -> Result<usize>; fn create_bbox_subscription(&self, _: &BboxSubscription) -> Result<()>; fn all_bbox_subscriptions(&self) -> Result<Vec<BboxSubscription>>; fn all_bbox_subscriptions_by_email(&self, user_email: &str) -> Result<Vec<BboxSubscription>>; fn delete_bbox_subscriptions_by_email(&self, user_email: &str) -> Result<()>; } #[derive(Copy, Clone, Debug)] pub enum IndexQueryMode { WithRating, WithoutRating, } #[derive(Debug, Default, Clone)] pub struct IndexQuery<'a, 'b> { // status = None: Don't filter by review status, i.e. return all entries // independent of their current review status // status = Some(empty vector): Exclude all invisible/inexistent entries, i.e. // return only visible/existent entries // status = Some(non-empty vector): Include entries only if their current review
// status matches one of the given values pub status: Option<Vec<ReviewStatus>>, pub include_bbox: Option<MapBbox>, pub exclude_bbox: Option<MapBbox>, pub categories: Vec<&'a str>, pub ids: Vec<&'b str>, pub hash_tags: Vec<String>, pub text_tags: Vec<String>, pub text: Option<String>, pub ts_min_lb: Option<Timestamp>, // lower bound (inclusive) pub ts_min_ub: Option<Timestamp>, // upper bound (inclusive) pub ts_max_lb: Option<Timestamp>, // lower bound (inclusive) pub ts_max_ub: Option<Timestamp>, // upper bound (inclusive) } pub trait Indexer { fn flush_index(&mut self) -> Fallible<()>; } pub trait IdIndex { fn query_ids( &self, mode: IndexQueryMode, query: &IndexQuery, limit: usize, ) -> Fallible<Vec<Id>>; } pub trait IdIndexer: Indexer + IdIndex { fn remove_by_id(&self, id: &Id) -> Fallible<()>; } #[derive(Debug, Default, Clone)] pub struct IndexedPlace { pub id: String, pub status: Option<ReviewStatus>, pub pos: MapPoint, pub title: String, pub description: String, pub tags: Vec<String>, pub ratings: AvgRatings, } pub trait PlaceIndex { fn query_places(&self, query: &IndexQuery, limit: usize) -> Fallible<Vec<IndexedPlace>>; } pub trait PlaceIndexer: IdIndexer + PlaceIndex { fn add_or_update_place( &self, place: &Place, status: ReviewStatus, ratings: &AvgRatings, ) -> Fallible<()>; } pub trait EventIndexer: IdIndexer { fn add_or_update_event(&self, event: &Event) -> Fallible<()>; } pub trait EventAndPlaceIndexer: PlaceIndexer + EventIndexer {}
random_line_split
db.rs
use super::{ entities::*, error::RepoError, repositories::*, util::{ geo::{MapBbox, MapPoint}, time::{Timestamp, TimestampMs}, }, }; use anyhow::Result as Fallible; type Result<T> = std::result::Result<T, RepoError>; #[derive(Clone, Debug)] pub struct MostPopularTagsParams { pub min_count: Option<u64>, pub max_count: Option<u64>, } #[derive(Clone, Debug)] pub struct RecentlyChangedEntriesParams { pub since: Option<TimestampMs>, pub until: Option<TimestampMs>, } pub trait PlaceRepo { fn get_place(&self, id: &str) -> Result<(Place, ReviewStatus)>; fn get_places(&self, ids: &[&str]) -> Result<Vec<(Place, ReviewStatus)>>; fn all_places(&self) -> Result<Vec<(Place, ReviewStatus)>>; fn count_places(&self) -> Result<usize>; fn recently_changed_places( &self, params: &RecentlyChangedEntriesParams, pagination: &Pagination, ) -> Result<Vec<(Place, ReviewStatus, ActivityLog)>>; fn most_popular_place_revision_tags( &self, params: &MostPopularTagsParams, pagination: &Pagination, ) -> Result<Vec<TagFrequency>>; fn review_places( &self, ids: &[&str], status: ReviewStatus, activity: &ActivityLog, ) -> Result<usize>; fn create_or_update_place(&self, place: Place) -> Result<()>; fn get_place_history(&self, id: &str) -> Result<PlaceHistory>; } pub trait EventGateway { fn create_event(&self, _: Event) -> Result<()>; fn update_event(&self, _: &Event) -> Result<()>; fn archive_events(&self, ids: &[&str], archived: Timestamp) -> Result<usize>; fn get_event(&self, id: &str) -> Result<Event>; fn get_events_chronologically(&self, ids: &[&str]) -> Result<Vec<Event>>; fn all_events_chronologically(&self) -> Result<Vec<Event>>; fn count_events(&self) -> Result<usize>; // Delete an event, but only if tagged with at least one of the given tags // Ok(Some(())) => Found and deleted // Ok(None) => No matching tags // TODO: Use explicit result semantics fn delete_event_with_matching_tags(&self, id: &str, tags: &[&str]) -> Result<Option<()>>; } pub trait UserGateway { fn create_user(&self, user: &User) -> Result<()>; fn update_user(&self, user: &User) -> Result<()>; fn delete_user_by_email(&self, email: &str) -> Result<()>; fn all_users(&self) -> Result<Vec<User>>; fn count_users(&self) -> Result<usize>; fn get_user_by_email(&self, email: &str) -> Result<User>; fn try_get_user_by_email(&self, email: &str) -> Result<Option<User>>; } pub trait OrganizationGateway { fn create_org(&mut self, _: Organization) -> Result<()>; fn get_org_by_api_token(&self, token: &str) -> Result<Organization>; fn get_all_tags_owned_by_orgs(&self) -> Result<Vec<String>>; } //TODO: // - TagGeatway // - SubscriptionGateway #[derive(Clone, Debug, Default)] pub struct Pagination { pub offset: Option<u64>, pub limit: Option<u64>, } pub trait Db: PlaceRepo + UserGateway + EventGateway + OrganizationGateway + CommentRepository + RatingRepository + UserTokenRepo { fn create_tag_if_it_does_not_exist(&self, _: &Tag) -> Result<()>; fn all_categories(&self) -> Result<Vec<Category>> { Ok(vec![ Category::new_non_profit(), Category::new_commercial(), Category::new_event(), ]) } fn all_tags(&self) -> Result<Vec<Tag>>; fn count_tags(&self) -> Result<usize>; fn create_bbox_subscription(&self, _: &BboxSubscription) -> Result<()>; fn all_bbox_subscriptions(&self) -> Result<Vec<BboxSubscription>>; fn all_bbox_subscriptions_by_email(&self, user_email: &str) -> Result<Vec<BboxSubscription>>; fn delete_bbox_subscriptions_by_email(&self, user_email: &str) -> Result<()>; } #[derive(Copy, Clone, Debug)] pub enum IndexQueryMode { WithRating, WithoutRating, } #[derive(Debug, Default, Clone)] pub struct
<'a, 'b> { // status = None: Don't filter by review status, i.e. return all entries // independent of their current review status // status = Some(empty vector): Exclude all invisible/inexistent entries, i.e. // return only visible/existent entries // status = Some(non-empty vector): Include entries only if their current review // status matches one of the given values pub status: Option<Vec<ReviewStatus>>, pub include_bbox: Option<MapBbox>, pub exclude_bbox: Option<MapBbox>, pub categories: Vec<&'a str>, pub ids: Vec<&'b str>, pub hash_tags: Vec<String>, pub text_tags: Vec<String>, pub text: Option<String>, pub ts_min_lb: Option<Timestamp>, // lower bound (inclusive) pub ts_min_ub: Option<Timestamp>, // upper bound (inclusive) pub ts_max_lb: Option<Timestamp>, // lower bound (inclusive) pub ts_max_ub: Option<Timestamp>, // upper bound (inclusive) } pub trait Indexer { fn flush_index(&mut self) -> Fallible<()>; } pub trait IdIndex { fn query_ids( &self, mode: IndexQueryMode, query: &IndexQuery, limit: usize, ) -> Fallible<Vec<Id>>; } pub trait IdIndexer: Indexer + IdIndex { fn remove_by_id(&self, id: &Id) -> Fallible<()>; } #[derive(Debug, Default, Clone)] pub struct IndexedPlace { pub id: String, pub status: Option<ReviewStatus>, pub pos: MapPoint, pub title: String, pub description: String, pub tags: Vec<String>, pub ratings: AvgRatings, } pub trait PlaceIndex { fn query_places(&self, query: &IndexQuery, limit: usize) -> Fallible<Vec<IndexedPlace>>; } pub trait PlaceIndexer: IdIndexer + PlaceIndex { fn add_or_update_place( &self, place: &Place, status: ReviewStatus, ratings: &AvgRatings, ) -> Fallible<()>; } pub trait EventIndexer: IdIndexer { fn add_or_update_event(&self, event: &Event) -> Fallible<()>; } pub trait EventAndPlaceIndexer: PlaceIndexer + EventIndexer {}
IndexQuery
identifier_name
msgsend-pipes.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. // A port of the simplistic benchmark from // // http://github.com/PaulKeeble/ScalaVErlangAgents // // I *think* it's the same, more or less. extern crate time; use std::os; use std::task; use std::uint; fn move_out<T>(_x: T) {} enum request { get_count, bytes(uint), stop } fn server(requests: &Receiver<request>, responses: &Sender<uint>) { let mut count: uint = 0; let mut done = false; while!done { match requests.recv_opt() { Ok(get_count) => { responses.send(count.clone()); } Ok(bytes(b)) => { //println!("server: received {:?} bytes", b); count += b; } Err(..) => { done = true; } _ => { } }
} responses.send(count); //println!("server exiting"); } fn run(args: &[~str]) { let (to_parent, from_child) = channel(); let size = from_str::<uint>(args[1]).unwrap(); let workers = from_str::<uint>(args[2]).unwrap(); let num_bytes = 100; let start = time::precise_time_s(); let mut worker_results = Vec::new(); let from_parent = if workers == 1 { let (to_child, from_parent) = channel(); let mut builder = task::task(); worker_results.push(builder.future_result()); builder.spawn(proc() { for _ in range(0u, size / workers) { //println!("worker {:?}: sending {:?} bytes", i, num_bytes); to_child.send(bytes(num_bytes)); } //println!("worker {:?} exiting", i); }); from_parent } else { let (to_child, from_parent) = channel(); for _ in range(0u, workers) { let to_child = to_child.clone(); let mut builder = task::task(); worker_results.push(builder.future_result()); builder.spawn(proc() { for _ in range(0u, size / workers) { //println!("worker {:?}: sending {:?} bytes", i, num_bytes); to_child.send(bytes(num_bytes)); } //println!("worker {:?} exiting", i); }); } from_parent }; task::spawn(proc() { server(&from_parent, &to_parent); }); for r in worker_results.iter() { r.recv(); } //println!("sending stop message"); //to_child.send(stop); //move_out(to_child); let result = from_child.recv(); let end = time::precise_time_s(); let elapsed = end - start; print!("Count is {:?}\n", result); print!("Test took {:?} seconds\n", elapsed); let thruput = ((size / workers * workers) as f64) / (elapsed as f64); print!("Throughput={} per sec\n", thruput); assert_eq!(result, num_bytes * size); } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(), "1000000".to_owned(), "8".to_owned()) } else if args.len() <= 1u { vec!("".to_owned(), "10000".to_owned(), "4".to_owned()) } else { args.clone().move_iter().collect() }; println!("{:?}", args); run(args.as_slice()); }
random_line_split
msgsend-pipes.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. // A port of the simplistic benchmark from // // http://github.com/PaulKeeble/ScalaVErlangAgents // // I *think* it's the same, more or less. extern crate time; use std::os; use std::task; use std::uint; fn move_out<T>(_x: T) {} enum request { get_count, bytes(uint), stop } fn server(requests: &Receiver<request>, responses: &Sender<uint>) { let mut count: uint = 0; let mut done = false; while!done { match requests.recv_opt() { Ok(get_count) => { responses.send(count.clone()); } Ok(bytes(b)) => { //println!("server: received {:?} bytes", b); count += b; } Err(..) => { done = true; } _ =>
} } responses.send(count); //println!("server exiting"); } fn run(args: &[~str]) { let (to_parent, from_child) = channel(); let size = from_str::<uint>(args[1]).unwrap(); let workers = from_str::<uint>(args[2]).unwrap(); let num_bytes = 100; let start = time::precise_time_s(); let mut worker_results = Vec::new(); let from_parent = if workers == 1 { let (to_child, from_parent) = channel(); let mut builder = task::task(); worker_results.push(builder.future_result()); builder.spawn(proc() { for _ in range(0u, size / workers) { //println!("worker {:?}: sending {:?} bytes", i, num_bytes); to_child.send(bytes(num_bytes)); } //println!("worker {:?} exiting", i); }); from_parent } else { let (to_child, from_parent) = channel(); for _ in range(0u, workers) { let to_child = to_child.clone(); let mut builder = task::task(); worker_results.push(builder.future_result()); builder.spawn(proc() { for _ in range(0u, size / workers) { //println!("worker {:?}: sending {:?} bytes", i, num_bytes); to_child.send(bytes(num_bytes)); } //println!("worker {:?} exiting", i); }); } from_parent }; task::spawn(proc() { server(&from_parent, &to_parent); }); for r in worker_results.iter() { r.recv(); } //println!("sending stop message"); //to_child.send(stop); //move_out(to_child); let result = from_child.recv(); let end = time::precise_time_s(); let elapsed = end - start; print!("Count is {:?}\n", result); print!("Test took {:?} seconds\n", elapsed); let thruput = ((size / workers * workers) as f64) / (elapsed as f64); print!("Throughput={} per sec\n", thruput); assert_eq!(result, num_bytes * size); } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(), "1000000".to_owned(), "8".to_owned()) } else if args.len() <= 1u { vec!("".to_owned(), "10000".to_owned(), "4".to_owned()) } else { args.clone().move_iter().collect() }; println!("{:?}", args); run(args.as_slice()); }
{ }
conditional_block
msgsend-pipes.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. // A port of the simplistic benchmark from // // http://github.com/PaulKeeble/ScalaVErlangAgents // // I *think* it's the same, more or less. extern crate time; use std::os; use std::task; use std::uint; fn move_out<T>(_x: T) {} enum request { get_count, bytes(uint), stop } fn server(requests: &Receiver<request>, responses: &Sender<uint>)
fn run(args: &[~str]) { let (to_parent, from_child) = channel(); let size = from_str::<uint>(args[1]).unwrap(); let workers = from_str::<uint>(args[2]).unwrap(); let num_bytes = 100; let start = time::precise_time_s(); let mut worker_results = Vec::new(); let from_parent = if workers == 1 { let (to_child, from_parent) = channel(); let mut builder = task::task(); worker_results.push(builder.future_result()); builder.spawn(proc() { for _ in range(0u, size / workers) { //println!("worker {:?}: sending {:?} bytes", i, num_bytes); to_child.send(bytes(num_bytes)); } //println!("worker {:?} exiting", i); }); from_parent } else { let (to_child, from_parent) = channel(); for _ in range(0u, workers) { let to_child = to_child.clone(); let mut builder = task::task(); worker_results.push(builder.future_result()); builder.spawn(proc() { for _ in range(0u, size / workers) { //println!("worker {:?}: sending {:?} bytes", i, num_bytes); to_child.send(bytes(num_bytes)); } //println!("worker {:?} exiting", i); }); } from_parent }; task::spawn(proc() { server(&from_parent, &to_parent); }); for r in worker_results.iter() { r.recv(); } //println!("sending stop message"); //to_child.send(stop); //move_out(to_child); let result = from_child.recv(); let end = time::precise_time_s(); let elapsed = end - start; print!("Count is {:?}\n", result); print!("Test took {:?} seconds\n", elapsed); let thruput = ((size / workers * workers) as f64) / (elapsed as f64); print!("Throughput={} per sec\n", thruput); assert_eq!(result, num_bytes * size); } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(), "1000000".to_owned(), "8".to_owned()) } else if args.len() <= 1u { vec!("".to_owned(), "10000".to_owned(), "4".to_owned()) } else { args.clone().move_iter().collect() }; println!("{:?}", args); run(args.as_slice()); }
{ let mut count: uint = 0; let mut done = false; while !done { match requests.recv_opt() { Ok(get_count) => { responses.send(count.clone()); } Ok(bytes(b)) => { //println!("server: received {:?} bytes", b); count += b; } Err(..) => { done = true; } _ => { } } } responses.send(count); //println!("server exiting"); }
identifier_body
msgsend-pipes.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. // A port of the simplistic benchmark from // // http://github.com/PaulKeeble/ScalaVErlangAgents // // I *think* it's the same, more or less. extern crate time; use std::os; use std::task; use std::uint; fn move_out<T>(_x: T) {} enum request { get_count, bytes(uint), stop } fn
(requests: &Receiver<request>, responses: &Sender<uint>) { let mut count: uint = 0; let mut done = false; while!done { match requests.recv_opt() { Ok(get_count) => { responses.send(count.clone()); } Ok(bytes(b)) => { //println!("server: received {:?} bytes", b); count += b; } Err(..) => { done = true; } _ => { } } } responses.send(count); //println!("server exiting"); } fn run(args: &[~str]) { let (to_parent, from_child) = channel(); let size = from_str::<uint>(args[1]).unwrap(); let workers = from_str::<uint>(args[2]).unwrap(); let num_bytes = 100; let start = time::precise_time_s(); let mut worker_results = Vec::new(); let from_parent = if workers == 1 { let (to_child, from_parent) = channel(); let mut builder = task::task(); worker_results.push(builder.future_result()); builder.spawn(proc() { for _ in range(0u, size / workers) { //println!("worker {:?}: sending {:?} bytes", i, num_bytes); to_child.send(bytes(num_bytes)); } //println!("worker {:?} exiting", i); }); from_parent } else { let (to_child, from_parent) = channel(); for _ in range(0u, workers) { let to_child = to_child.clone(); let mut builder = task::task(); worker_results.push(builder.future_result()); builder.spawn(proc() { for _ in range(0u, size / workers) { //println!("worker {:?}: sending {:?} bytes", i, num_bytes); to_child.send(bytes(num_bytes)); } //println!("worker {:?} exiting", i); }); } from_parent }; task::spawn(proc() { server(&from_parent, &to_parent); }); for r in worker_results.iter() { r.recv(); } //println!("sending stop message"); //to_child.send(stop); //move_out(to_child); let result = from_child.recv(); let end = time::precise_time_s(); let elapsed = end - start; print!("Count is {:?}\n", result); print!("Test took {:?} seconds\n", elapsed); let thruput = ((size / workers * workers) as f64) / (elapsed as f64); print!("Throughput={} per sec\n", thruput); assert_eq!(result, num_bytes * size); } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(), "1000000".to_owned(), "8".to_owned()) } else if args.len() <= 1u { vec!("".to_owned(), "10000".to_owned(), "4".to_owned()) } else { args.clone().move_iter().collect() }; println!("{:?}", args); run(args.as_slice()); }
server
identifier_name
util.rs
/* Copyright 2013 10gen Inc. * * 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 extra::treemap::*; use url=extra::net::url; // since "decode" also in url use bson::encode::*; use bson::formattable::*; /** * Utility module for use internal and external to crate. * Users must access functionality for proper use of options, etc. */ #[deriving(Clone,Eq)] pub struct MongoErr { //err_code : int, err_type : ~str, err_name : ~str, err_msg : ~str, // TODO: error codes for finer granularity of error provenance (than // just a bunch of strings, e.g. connection error, run_command // error, BSON parsing error, etc.) } /** * MongoErr to propagate errors. */ impl MongoErr { /** * Creates a new MongoErr of given type (e.g. "connection", "query"), * name (more specific error), and msg (description of error). */ pub fn new(typ : ~str, name : ~str, msg : ~str) -> MongoErr { MongoErr { err_type : typ, err_name : name, err_msg : msg } } /** * Like to_str, but omits staring "ERR | ". */ pub fn tail(&self) -> ~str { fmt!("%s | %s => %s", self.err_type, self.err_name, self.err_msg) } } impl ToStr for MongoErr { /** * Prints a MongoErr to string in a standard format. */ pub fn to_str(&self) -> ~str { fmt!("ERR | %s | %s => %s", self.err_type, self.err_name, self.err_msg) } } pub struct MongoUri { user : Option<url::UserInfo>, hosts : ~[~str], ports : ~[uint], db : ~str, options : url::Query, // XXX tmp } impl FromStr for MongoUri { pub fn from_str(s : &str) -> Option<MongoUri> { // uri doesn't *quite* work with Rust's URL from_str, // so we massage things a little let mut uri = s.to_owned(); // look for possible host list and substitute colons let start = match uri.find_str("@") { Some(ind) => ind, None => match uri.find_str("://") { Some(ind) => ind+2, None => return None, // know cannot be uri }, }; let end = match uri.find_str("?") { Some(ind) => { if ind <= start { uri.len() } else { ind } } None => uri.len(), }; let repl_str = "RUST.DRIVER.COLON.REPLACE"; let fst = uri.slice(0, start).to_owned(); let middle = uri.slice(start, end).replace(":", repl_str).to_owned(); let lst = uri.slice(end, uri.len()).to_owned(); uri = fmt!("%s%s%s", fst, middle, lst); // now try to parse match FromStr::from_str::<url::Url>(uri) { Some(url) => { if url.scheme!= ~"mongodb" { return None; } if (url.path.len() > 0 && url.path.char_at(0)!= '/') || (url.query.len() > 0 && url.path.len() <= 0) || (uri.find_str("?").is_some() && url.path.find_str("/").is_none()) { return None; } let mut host_str = url.host.to_owned(); host_str = host_str.replace(repl_str, ":"); let mut hosts_iter = host_str.split_iter(','); let mut hosts_full = ~[]; for hosts_iter.advance |h| { hosts_full.push(h); } let mut hosts = ~[]; let mut ports = ~[]; if url.port.is_some() { if hosts_full.len() > 1 { return None; } else { match FromStr::from_str::<uint>(url.port.clone().unwrap()) { Some(p) => ports.push(p), None => return None, } } } for hosts_full.iter().advance |&h| { match parse_host(h) { Ok((host_str, po)) => { hosts.push(host_str); ports.push(po); } Err(_) => return None, } } let result = Some(MongoUri { user : url.user.clone(), hosts : hosts, ports : ports, db : if url.path.len() > 1 { url.path.slice_from(1).to_owned() } else { ~"" }, options : url.query.clone(), }); result } None => None, } } } /** * CRUD option flags. * If options ever change, modify: * util.rs: appropriate enums (_FLAGs or _OPTIONs) * coll.rs: appropriate flag and option helper parser functions */ pub enum UPDATE_FLAG { UPSERT = 1 << 0, MULTI = 1 << 1, } pub enum UPDATE_OPTION { // nothing yet // update as update operation takes more options; // intended for non-mask-type options } pub enum INSERT_FLAG { CONT_ON_ERR = 1 << 0, } pub enum
{ // nothing yet // update as insert operation takes more options; // intended for non-mask-type options } pub enum QUERY_FLAG { // bit 0 reserved CUR_TAILABLE = 1 << 1, SLAVE_OK = 1 << 2, OPLOG_REPLAY = 1 << 3, // driver should not set NO_CUR_TIMEOUT = 1 << 4, AWAIT_DATA = 1 << 5, EXHAUST = 1 << 6, PARTIAL = 1 << 7, } pub enum QUERY_OPTION { // update as query operation takes more options; // intended for non-mask-type options NSKIP(int), NRET(int), } pub enum DELETE_FLAG { SINGLE_REMOVE = 1 << 0, } pub enum DELETE_OPTION { // nothing yet // update as delete operation takes more options; // intended for non-mask-type options } /** * Reply flags, but user shouldn't deal with them directly. */ pub enum REPLY_FLAG { CUR_NOT_FOUND = 1 << 0, QUERY_FAIL = 1 << 1, SHARD_CONFIG_STALE = 1 << 2, // driver should ignore AWAIT_CAPABLE = 1 << 3, } #[deriving(Clone,Eq)] pub enum QuerySpec { SpecObj(BsonDocument), SpecNotation(~str) } impl ToStr for QuerySpec { pub fn to_str(&self) -> ~str { match self { &SpecObj(ref bson) => bson.fields.to_str(), &SpecNotation(ref s) => s.clone(), } } } #[deriving(Eq)] pub struct TagSet { tags : TreeMap<~str, ~str>, } impl Clone for TagSet { pub fn clone(&self) -> TagSet { let mut tags = TreeMap::new(); for self.tags.iter().advance |(&k,&v)| { tags.insert(k, v); } TagSet { tags : tags } } } impl BsonFormattable for TagSet { pub fn to_bson_t(&self) -> Document { let mut ts_doc = BsonDocument::new(); for self.tags.iter().advance |(&k,&v)| { ts_doc.put(k, UString(v)); } Embedded(~ts_doc) } pub fn from_bson_t(doc : &Document) -> Result<TagSet, ~str> { let mut ts = TagSet::new(~[]); match doc { &Embedded(ref bson_doc) => { for bson_doc.fields.iter().advance |&(@k,@v)| { match v { UString(s) => ts.set(k,s), _ => return Err(~"not TagSet struct (val not UString)"), } } } _ => return Err(~"not TagSet struct (not Embedded BsonDocument)"), } Ok(ts) } } impl TagSet { pub fn new(tag_list : &[(&str, &str)]) -> TagSet { let mut tags = TreeMap::new(); for tag_list.iter().advance |&(field, val)| { tags.insert(field.to_owned(), val.to_owned()); } TagSet { tags : tags } } pub fn get_ref<'a>(&'a self, field : ~str) -> Option<&'a ~str> { self.tags.find(&field) } pub fn get_mut_ref<'a>(&'a mut self, field : ~str) -> Option<&'a mut ~str> { self.tags.find_mut(&field) } /** * Sets tag in TagSet, whether or not it existed previously. */ pub fn set(&mut self, field : ~str, val : ~str) { self.tags.remove(&field); if val.len()!= 0 { self.tags.insert(field, val); } } /** * Returns if self matches the other TagSet, * i.e. if all of the other TagSet's tags are * in self's TagSet. * * Usage: member.matches(tagset) */ pub fn matches(&self, other : &TagSet) -> bool { for other.tags.iter().advance |(f0, &v0)| { match self.tags.find(f0) { None => return false, Some(v1) => { if v0!= *v1 { return false; } } } } true } } #[deriving(Clone, Eq)] pub enum WRITE_CONCERN { JOURNAL(bool), // wait for next journal commit? W_N(int), // replicate to how many? (number) W_STR(~str), // replicate to how many? (string, e.g. "majority") W_TAGSET(TagSet), // replicate to what tagset? WTIMEOUT(int), // timeout after how many ms? FSYNC(bool), // wait for write to disk? } #[deriving(Clone, Eq)] pub enum READ_PREFERENCE { PRIMARY_ONLY, PRIMARY_PREF(Option<~[TagSet]>), SECONDARY_ONLY(Option<~[TagSet]>), SECONDARY_PREF(Option<~[TagSet]>), NEAREST(Option<~[TagSet]>), } /** * Collections. */ pub enum COLLECTION_FLAG { AUTOINDEX_ID = 1 << 0, // enable automatic index on _id? } pub enum COLLECTION_OPTION { CAPPED(uint), // max size of capped collection SIZE(uint), // preallocated size of uncapped collection MAX_DOCS(uint), // max cap in number of documents } /** * Misc */ pub static LITTLE_ENDIAN_TRUE : bool = true; pub static MONGO_DEFAULT_PORT : uint = 27017; pub static MONGO_RECONN_MSECS : u64 = (1000*3); pub static MONGO_TIMEOUT_SECS : u64 = 30; // XXX units... pub static LOCALHOST : &'static str = &'static "127.0.0.1"; // XXX tmp /// INTERNAL UTILITIES /** * Special collections for database operations, but generally, users should not * access directly. */ pub static SYSTEM_NAMESPACE : &'static str = &'static "system.namespaces"; pub static SYSTEM_INDEX : &'static str = &'static "system.indexes"; pub static SYSTEM_PROFILE : &'static str = &'static "system.profile"; pub static SYSTEM_USERS : &'static str = &'static "system.users"; pub static SYSTEM_COMMAND : &'static str = &'static "$cmd"; pub static SYSTEM_JS : &'static str = &'static "system.js"; pub static SYSTEM_REPLSET : &'static str = &'static "system.replset"; // macro for compressing options array into single i32 flag macro_rules! process_flags( ($options:ident) => ( match $options { None => 0i32, Some(opt_array) => { let mut tmp = 0i32; for opt_array.iter().advance |&f| { tmp |= f as i32; } tmp } } ); ) pub fn parse_host(host_str : &str) -> Result<(~str, uint), MongoErr> { let mut port_str = fmt!("%?", MONGO_DEFAULT_PORT); let mut ip_str = match host_str.find_str(":") { None => { host_str.to_owned() } Some(i) => { port_str = host_str.slice_from(i+1).to_owned(); host_str.slice_to(i).to_owned() } }; if ip_str == ~"localhost" { ip_str = LOCALHOST.to_owned(); } // XXX must exist better soln match FromStr::from_str::<uint>(port_str) { None => Err(MongoErr::new( ~"util::parse_host", ~"unexpected host string format", fmt!("host string should be \"[IP ~str]:[uint]\", found %s:%s", ip_str, port_str))), Some(k) => Ok((ip_str, k)), } } pub fn parse_tags(tag_str : &str) -> Result<Option<TagSet>, MongoErr> { if tag_str.find_str(":").is_some() { let mut tags = TagSet::new([]); let mut it = tag_str.split_iter(','); for it.advance |tag| { match tag.find_str(":") { Some(i) => { tags.set( tag.slice_to(i).to_owned(), tag.slice_from(i+1).to_owned()); } None => return Err(MongoErr::new( ~"util::parse_tags", ~"improperly specified tags", fmt!("missing colon in tag %s", tag))), } } Ok(if tags.tags.len() > 0 { Some(tags) } else { None }) } else if tag_str.len() == 0 { Ok(None) } else { Err(MongoErr::new( ~"util::parse_tags", ~"improper tag specification", fmt!("expected comma-delimited string of colon-separated pairs, got %s", tag_str))) } }
INSERT_OPTION
identifier_name
util.rs
/* Copyright 2013 10gen Inc. * * 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 extra::treemap::*; use url=extra::net::url; // since "decode" also in url use bson::encode::*; use bson::formattable::*; /** * Utility module for use internal and external to crate. * Users must access functionality for proper use of options, etc. */ #[deriving(Clone,Eq)] pub struct MongoErr { //err_code : int, err_type : ~str, err_name : ~str, err_msg : ~str, // TODO: error codes for finer granularity of error provenance (than // just a bunch of strings, e.g. connection error, run_command // error, BSON parsing error, etc.) } /** * MongoErr to propagate errors. */ impl MongoErr { /** * Creates a new MongoErr of given type (e.g. "connection", "query"), * name (more specific error), and msg (description of error). */ pub fn new(typ : ~str, name : ~str, msg : ~str) -> MongoErr { MongoErr { err_type : typ, err_name : name, err_msg : msg } } /** * Like to_str, but omits staring "ERR | ". */ pub fn tail(&self) -> ~str { fmt!("%s | %s => %s", self.err_type, self.err_name, self.err_msg) } } impl ToStr for MongoErr { /** * Prints a MongoErr to string in a standard format. */ pub fn to_str(&self) -> ~str { fmt!("ERR | %s | %s => %s", self.err_type, self.err_name, self.err_msg) } } pub struct MongoUri { user : Option<url::UserInfo>, hosts : ~[~str], ports : ~[uint], db : ~str, options : url::Query, // XXX tmp } impl FromStr for MongoUri { pub fn from_str(s : &str) -> Option<MongoUri> { // uri doesn't *quite* work with Rust's URL from_str, // so we massage things a little let mut uri = s.to_owned(); // look for possible host list and substitute colons let start = match uri.find_str("@") { Some(ind) => ind, None => match uri.find_str("://") { Some(ind) => ind+2, None => return None, // know cannot be uri }, }; let end = match uri.find_str("?") { Some(ind) => { if ind <= start { uri.len() } else { ind } } None => uri.len(), }; let repl_str = "RUST.DRIVER.COLON.REPLACE"; let fst = uri.slice(0, start).to_owned(); let middle = uri.slice(start, end).replace(":", repl_str).to_owned(); let lst = uri.slice(end, uri.len()).to_owned(); uri = fmt!("%s%s%s", fst, middle, lst); // now try to parse match FromStr::from_str::<url::Url>(uri) { Some(url) => { if url.scheme!= ~"mongodb" { return None; } if (url.path.len() > 0 && url.path.char_at(0)!= '/') || (url.query.len() > 0 && url.path.len() <= 0) || (uri.find_str("?").is_some() && url.path.find_str("/").is_none()) { return None; } let mut host_str = url.host.to_owned(); host_str = host_str.replace(repl_str, ":"); let mut hosts_iter = host_str.split_iter(','); let mut hosts_full = ~[]; for hosts_iter.advance |h| { hosts_full.push(h); } let mut hosts = ~[]; let mut ports = ~[]; if url.port.is_some() { if hosts_full.len() > 1 { return None; } else { match FromStr::from_str::<uint>(url.port.clone().unwrap()) { Some(p) => ports.push(p), None => return None, } } } for hosts_full.iter().advance |&h| { match parse_host(h) { Ok((host_str, po)) => { hosts.push(host_str); ports.push(po); } Err(_) => return None, } } let result = Some(MongoUri { user : url.user.clone(), hosts : hosts, ports : ports, db : if url.path.len() > 1 { url.path.slice_from(1).to_owned() } else { ~"" }, options : url.query.clone(), }); result } None => None, } } } /** * CRUD option flags. * If options ever change, modify: * util.rs: appropriate enums (_FLAGs or _OPTIONs) * coll.rs: appropriate flag and option helper parser functions */ pub enum UPDATE_FLAG { UPSERT = 1 << 0, MULTI = 1 << 1, } pub enum UPDATE_OPTION { // nothing yet // update as update operation takes more options; // intended for non-mask-type options } pub enum INSERT_FLAG { CONT_ON_ERR = 1 << 0, } pub enum INSERT_OPTION { // nothing yet // update as insert operation takes more options; // intended for non-mask-type options } pub enum QUERY_FLAG { // bit 0 reserved CUR_TAILABLE = 1 << 1, SLAVE_OK = 1 << 2, OPLOG_REPLAY = 1 << 3, // driver should not set NO_CUR_TIMEOUT = 1 << 4, AWAIT_DATA = 1 << 5, EXHAUST = 1 << 6, PARTIAL = 1 << 7, } pub enum QUERY_OPTION { // update as query operation takes more options; // intended for non-mask-type options NSKIP(int), NRET(int), } pub enum DELETE_FLAG { SINGLE_REMOVE = 1 << 0, } pub enum DELETE_OPTION { // nothing yet // update as delete operation takes more options; // intended for non-mask-type options } /** * Reply flags, but user shouldn't deal with them directly. */ pub enum REPLY_FLAG { CUR_NOT_FOUND = 1 << 0, QUERY_FAIL = 1 << 1, SHARD_CONFIG_STALE = 1 << 2, // driver should ignore AWAIT_CAPABLE = 1 << 3, } #[deriving(Clone,Eq)] pub enum QuerySpec { SpecObj(BsonDocument), SpecNotation(~str) } impl ToStr for QuerySpec { pub fn to_str(&self) -> ~str { match self { &SpecObj(ref bson) => bson.fields.to_str(), &SpecNotation(ref s) => s.clone(), } } } #[deriving(Eq)] pub struct TagSet { tags : TreeMap<~str, ~str>, } impl Clone for TagSet { pub fn clone(&self) -> TagSet { let mut tags = TreeMap::new(); for self.tags.iter().advance |(&k,&v)| { tags.insert(k, v); } TagSet { tags : tags } } } impl BsonFormattable for TagSet { pub fn to_bson_t(&self) -> Document { let mut ts_doc = BsonDocument::new(); for self.tags.iter().advance |(&k,&v)| { ts_doc.put(k, UString(v)); } Embedded(~ts_doc) } pub fn from_bson_t(doc : &Document) -> Result<TagSet, ~str> { let mut ts = TagSet::new(~[]); match doc { &Embedded(ref bson_doc) => { for bson_doc.fields.iter().advance |&(@k,@v)| { match v { UString(s) => ts.set(k,s), _ => return Err(~"not TagSet struct (val not UString)"), } } } _ => return Err(~"not TagSet struct (not Embedded BsonDocument)"),
} impl TagSet { pub fn new(tag_list : &[(&str, &str)]) -> TagSet { let mut tags = TreeMap::new(); for tag_list.iter().advance |&(field, val)| { tags.insert(field.to_owned(), val.to_owned()); } TagSet { tags : tags } } pub fn get_ref<'a>(&'a self, field : ~str) -> Option<&'a ~str> { self.tags.find(&field) } pub fn get_mut_ref<'a>(&'a mut self, field : ~str) -> Option<&'a mut ~str> { self.tags.find_mut(&field) } /** * Sets tag in TagSet, whether or not it existed previously. */ pub fn set(&mut self, field : ~str, val : ~str) { self.tags.remove(&field); if val.len()!= 0 { self.tags.insert(field, val); } } /** * Returns if self matches the other TagSet, * i.e. if all of the other TagSet's tags are * in self's TagSet. * * Usage: member.matches(tagset) */ pub fn matches(&self, other : &TagSet) -> bool { for other.tags.iter().advance |(f0, &v0)| { match self.tags.find(f0) { None => return false, Some(v1) => { if v0!= *v1 { return false; } } } } true } } #[deriving(Clone, Eq)] pub enum WRITE_CONCERN { JOURNAL(bool), // wait for next journal commit? W_N(int), // replicate to how many? (number) W_STR(~str), // replicate to how many? (string, e.g. "majority") W_TAGSET(TagSet), // replicate to what tagset? WTIMEOUT(int), // timeout after how many ms? FSYNC(bool), // wait for write to disk? } #[deriving(Clone, Eq)] pub enum READ_PREFERENCE { PRIMARY_ONLY, PRIMARY_PREF(Option<~[TagSet]>), SECONDARY_ONLY(Option<~[TagSet]>), SECONDARY_PREF(Option<~[TagSet]>), NEAREST(Option<~[TagSet]>), } /** * Collections. */ pub enum COLLECTION_FLAG { AUTOINDEX_ID = 1 << 0, // enable automatic index on _id? } pub enum COLLECTION_OPTION { CAPPED(uint), // max size of capped collection SIZE(uint), // preallocated size of uncapped collection MAX_DOCS(uint), // max cap in number of documents } /** * Misc */ pub static LITTLE_ENDIAN_TRUE : bool = true; pub static MONGO_DEFAULT_PORT : uint = 27017; pub static MONGO_RECONN_MSECS : u64 = (1000*3); pub static MONGO_TIMEOUT_SECS : u64 = 30; // XXX units... pub static LOCALHOST : &'static str = &'static "127.0.0.1"; // XXX tmp /// INTERNAL UTILITIES /** * Special collections for database operations, but generally, users should not * access directly. */ pub static SYSTEM_NAMESPACE : &'static str = &'static "system.namespaces"; pub static SYSTEM_INDEX : &'static str = &'static "system.indexes"; pub static SYSTEM_PROFILE : &'static str = &'static "system.profile"; pub static SYSTEM_USERS : &'static str = &'static "system.users"; pub static SYSTEM_COMMAND : &'static str = &'static "$cmd"; pub static SYSTEM_JS : &'static str = &'static "system.js"; pub static SYSTEM_REPLSET : &'static str = &'static "system.replset"; // macro for compressing options array into single i32 flag macro_rules! process_flags( ($options:ident) => ( match $options { None => 0i32, Some(opt_array) => { let mut tmp = 0i32; for opt_array.iter().advance |&f| { tmp |= f as i32; } tmp } } ); ) pub fn parse_host(host_str : &str) -> Result<(~str, uint), MongoErr> { let mut port_str = fmt!("%?", MONGO_DEFAULT_PORT); let mut ip_str = match host_str.find_str(":") { None => { host_str.to_owned() } Some(i) => { port_str = host_str.slice_from(i+1).to_owned(); host_str.slice_to(i).to_owned() } }; if ip_str == ~"localhost" { ip_str = LOCALHOST.to_owned(); } // XXX must exist better soln match FromStr::from_str::<uint>(port_str) { None => Err(MongoErr::new( ~"util::parse_host", ~"unexpected host string format", fmt!("host string should be \"[IP ~str]:[uint]\", found %s:%s", ip_str, port_str))), Some(k) => Ok((ip_str, k)), } } pub fn parse_tags(tag_str : &str) -> Result<Option<TagSet>, MongoErr> { if tag_str.find_str(":").is_some() { let mut tags = TagSet::new([]); let mut it = tag_str.split_iter(','); for it.advance |tag| { match tag.find_str(":") { Some(i) => { tags.set( tag.slice_to(i).to_owned(), tag.slice_from(i+1).to_owned()); } None => return Err(MongoErr::new( ~"util::parse_tags", ~"improperly specified tags", fmt!("missing colon in tag %s", tag))), } } Ok(if tags.tags.len() > 0 { Some(tags) } else { None }) } else if tag_str.len() == 0 { Ok(None) } else { Err(MongoErr::new( ~"util::parse_tags", ~"improper tag specification", fmt!("expected comma-delimited string of colon-separated pairs, got %s", tag_str))) } }
} Ok(ts) }
random_line_split
font.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 geom::{Point2D, Rect, Size2D}; use std::borrow::ToOwned; use std::mem; use std::slice; use std::rc::Rc; use std::cell::RefCell; use util::cache::HashCache; use util::smallvec::SmallVec8; use style::computed_values::{font_stretch, font_variant, font_weight}; use style::properties::style_structs::Font as FontStyle; use std::sync::Arc; use platform::font_context::FontContextHandle; use platform::font::{FontHandle, FontTable}; use util::geometry::Au; use text::glyph::{GlyphStore, GlyphId}; use text::shaping::ShaperMethods; use text::Shaper; use font_template::FontTemplateDescriptor; use platform::font_template::FontTemplateData; // FontHandle encapsulates access to the platform's font API, // e.g. quartz, FreeType. It provides access to metrics and tables // needed by the text shaper as well as access to the underlying font // resources needed by the graphics layer to draw glyphs. pub trait FontHandleMethods { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<Self,()>; fn template(&self) -> Arc<FontTemplateData>; fn family_name(&self) -> String; fn face_name(&self) -> String; fn is_italic(&self) -> bool; fn boldness(&self) -> font_weight::T; fn stretchiness(&self) -> font_stretch::T; fn glyph_index(&self, codepoint: char) -> Option<GlyphId>; fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>; fn glyph_h_kerning(&self, GlyphId, GlyphId) -> FractionalPixel; fn metrics(&self) -> FontMetrics; fn get_table_for_tag(&self, FontTableTag) -> Option<FontTable>; } // Used to abstract over the shaper's choice of fixed int representation. pub type FractionalPixel = f64; pub type FontTableTag = u32; pub trait FontTableTagConversions { fn tag_to_str(&self) -> String; } impl FontTableTagConversions for FontTableTag { fn tag_to_str(&self) -> String { unsafe { let pointer = mem::transmute::<&u32, *const u8>(self); let mut bytes = slice::from_raw_parts(pointer, 4).to_vec(); bytes.reverse(); String::from_utf8_unchecked(bytes) } } } pub trait FontTableMethods { fn with_buffer<F>(&self, F) where F: FnOnce(*const u8, usize); } #[derive(Clone, Debug)] pub struct FontMetrics { pub underline_size: Au, pub underline_offset: Au, pub strikeout_size: Au, pub strikeout_offset: Au, pub leading: Au, pub x_height: Au, pub em_size: Au, pub ascent: Au, pub descent: Au, pub max_advance: Au, pub average_advance: Au, pub line_gap: Au, } pub type SpecifiedFontStyle = FontStyle; pub type UsedFontStyle = FontStyle; pub struct Font { pub handle: FontHandle, pub metrics: FontMetrics, pub variant: font_variant::T, pub descriptor: FontTemplateDescriptor, pub requested_pt_size: Au, pub actual_pt_size: Au, pub shaper: Option<Shaper>, pub shape_cache: HashCache<ShapeCacheEntry,Arc<GlyphStore>>, pub glyph_advance_cache: HashCache<u32,FractionalPixel>, } bitflags! { flags ShapingFlags: u8 { #[doc="Set if the text is entirely whitespace."] const IS_WHITESPACE_SHAPING_FLAG = 0x01, #[doc="Set if we are to ignore ligatures."] const IGNORE_LIGATURES_SHAPING_FLAG = 0x02, #[doc="Set if we are to disable kerning."] const DISABLE_KERNING_SHAPING_FLAG = 0x04 } } /// Various options that control text shaping. #[derive(Clone, Eq, PartialEq, Hash, Copy)] pub struct ShapingOptions { /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property. /// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null. pub letter_spacing: Option<Au>, /// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property. pub word_spacing: Au, /// Various flags. pub flags: ShapingFlags, } /// An entry in the shape cache. #[derive(Clone, Eq, PartialEq, Hash)] pub struct ShapeCacheEntry { text: String, options: ShapingOptions, } impl Font { pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc<GlyphStore> { self.make_shaper(options); //FIXME: find the equivalent of Equiv and the old ShapeCacheEntryRef let shaper = &self.shaper; let lookup_key = ShapeCacheEntry { text: text.to_owned(), options: options.clone(), }; match self.shape_cache.find(&lookup_key) { None => {} Some(glyphs) => return glyphs.clone(), } let mut glyphs = GlyphStore::new(text.chars().count(), options.flags.contains(IS_WHITESPACE_SHAPING_FLAG)); shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs); let glyphs = Arc::new(glyphs); self.shape_cache.insert(ShapeCacheEntry { text: text.to_owned(), options: *options, }, glyphs.clone()); glyphs } fn make_shaper<'a>(&'a mut self, options: &ShapingOptions) -> &'a Shaper { // fast path: already created a shaper match self.shaper { Some(ref mut shaper) => { shaper.set_options(options); return shaper }, None => {} } let shaper = Shaper::new(self, options); self.shaper = Some(shaper); self.shaper.as_ref().unwrap() } pub fn get_table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let result = self.handle.get_table_for_tag(tag); let status = if result.is_some() { "Found" } else { "Didn't find" }; debug!("{} font table[{}] with family={}, face={}", status, tag.tag_to_str(), self.handle.family_name(), self.handle.face_name()); return result; } #[inline] pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { let codepoint = match self.variant { font_variant::T::small_caps => codepoint.to_uppercase().next().unwrap(), //FIXME: #5938 font_variant::T::normal => codepoint, }; self.handle.glyph_index(codepoint) } pub fn glyph_h_kerning(&mut self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { self.handle.glyph_h_kerning(first_glyph, second_glyph) } pub fn glyph_h_advance(&mut self, glyph: GlyphId) -> FractionalPixel { let handle = &self.handle; self.glyph_advance_cache.find_or_create(&glyph, |glyph| { match handle.glyph_h_advance(*glyph) { Some(adv) => adv, None => 10f64 as FractionalPixel // FIXME: Need fallback strategy } }) } }
pub fonts: SmallVec8<Rc<RefCell<Font>>>, } impl FontGroup { pub fn new(fonts: SmallVec8<Rc<RefCell<Font>>>) -> FontGroup { FontGroup { fonts: fonts, } } } pub struct RunMetrics { // may be negative due to negative width (i.e., kerning of '.' in 'P.T.') pub advance_width: Au, pub ascent: Au, // nonzero pub descent: Au, // nonzero // this bounding box is relative to the left origin baseline. // so, bounding_box.position.y = -ascent pub bounding_box: Rect<Au> } impl RunMetrics { pub fn new(advance: Au, ascent: Au, descent: Au) -> RunMetrics { let bounds = Rect(Point2D(Au(0), -ascent), Size2D(advance, ascent + descent)); // TODO(Issue #125): support loose and tight bounding boxes; using the // ascent+descent and advance is sometimes too generous and // looking at actual glyph extents can yield a tighter box. RunMetrics { advance_width: advance, bounding_box: bounds, ascent: ascent, descent: descent, } } }
pub struct FontGroup {
random_line_split
font.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 geom::{Point2D, Rect, Size2D}; use std::borrow::ToOwned; use std::mem; use std::slice; use std::rc::Rc; use std::cell::RefCell; use util::cache::HashCache; use util::smallvec::SmallVec8; use style::computed_values::{font_stretch, font_variant, font_weight}; use style::properties::style_structs::Font as FontStyle; use std::sync::Arc; use platform::font_context::FontContextHandle; use platform::font::{FontHandle, FontTable}; use util::geometry::Au; use text::glyph::{GlyphStore, GlyphId}; use text::shaping::ShaperMethods; use text::Shaper; use font_template::FontTemplateDescriptor; use platform::font_template::FontTemplateData; // FontHandle encapsulates access to the platform's font API, // e.g. quartz, FreeType. It provides access to metrics and tables // needed by the text shaper as well as access to the underlying font // resources needed by the graphics layer to draw glyphs. pub trait FontHandleMethods { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<Self,()>; fn template(&self) -> Arc<FontTemplateData>; fn family_name(&self) -> String; fn face_name(&self) -> String; fn is_italic(&self) -> bool; fn boldness(&self) -> font_weight::T; fn stretchiness(&self) -> font_stretch::T; fn glyph_index(&self, codepoint: char) -> Option<GlyphId>; fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>; fn glyph_h_kerning(&self, GlyphId, GlyphId) -> FractionalPixel; fn metrics(&self) -> FontMetrics; fn get_table_for_tag(&self, FontTableTag) -> Option<FontTable>; } // Used to abstract over the shaper's choice of fixed int representation. pub type FractionalPixel = f64; pub type FontTableTag = u32; pub trait FontTableTagConversions { fn tag_to_str(&self) -> String; } impl FontTableTagConversions for FontTableTag { fn tag_to_str(&self) -> String { unsafe { let pointer = mem::transmute::<&u32, *const u8>(self); let mut bytes = slice::from_raw_parts(pointer, 4).to_vec(); bytes.reverse(); String::from_utf8_unchecked(bytes) } } } pub trait FontTableMethods { fn with_buffer<F>(&self, F) where F: FnOnce(*const u8, usize); } #[derive(Clone, Debug)] pub struct FontMetrics { pub underline_size: Au, pub underline_offset: Au, pub strikeout_size: Au, pub strikeout_offset: Au, pub leading: Au, pub x_height: Au, pub em_size: Au, pub ascent: Au, pub descent: Au, pub max_advance: Au, pub average_advance: Au, pub line_gap: Au, } pub type SpecifiedFontStyle = FontStyle; pub type UsedFontStyle = FontStyle; pub struct Font { pub handle: FontHandle, pub metrics: FontMetrics, pub variant: font_variant::T, pub descriptor: FontTemplateDescriptor, pub requested_pt_size: Au, pub actual_pt_size: Au, pub shaper: Option<Shaper>, pub shape_cache: HashCache<ShapeCacheEntry,Arc<GlyphStore>>, pub glyph_advance_cache: HashCache<u32,FractionalPixel>, } bitflags! { flags ShapingFlags: u8 { #[doc="Set if the text is entirely whitespace."] const IS_WHITESPACE_SHAPING_FLAG = 0x01, #[doc="Set if we are to ignore ligatures."] const IGNORE_LIGATURES_SHAPING_FLAG = 0x02, #[doc="Set if we are to disable kerning."] const DISABLE_KERNING_SHAPING_FLAG = 0x04 } } /// Various options that control text shaping. #[derive(Clone, Eq, PartialEq, Hash, Copy)] pub struct ShapingOptions { /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property. /// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null. pub letter_spacing: Option<Au>, /// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property. pub word_spacing: Au, /// Various flags. pub flags: ShapingFlags, } /// An entry in the shape cache. #[derive(Clone, Eq, PartialEq, Hash)] pub struct ShapeCacheEntry { text: String, options: ShapingOptions, } impl Font { pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc<GlyphStore> { self.make_shaper(options); //FIXME: find the equivalent of Equiv and the old ShapeCacheEntryRef let shaper = &self.shaper; let lookup_key = ShapeCacheEntry { text: text.to_owned(), options: options.clone(), }; match self.shape_cache.find(&lookup_key) { None => {} Some(glyphs) => return glyphs.clone(), } let mut glyphs = GlyphStore::new(text.chars().count(), options.flags.contains(IS_WHITESPACE_SHAPING_FLAG)); shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs); let glyphs = Arc::new(glyphs); self.shape_cache.insert(ShapeCacheEntry { text: text.to_owned(), options: *options, }, glyphs.clone()); glyphs } fn make_shaper<'a>(&'a mut self, options: &ShapingOptions) -> &'a Shaper { // fast path: already created a shaper match self.shaper { Some(ref mut shaper) => { shaper.set_options(options); return shaper }, None => {} } let shaper = Shaper::new(self, options); self.shaper = Some(shaper); self.shaper.as_ref().unwrap() } pub fn get_table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let result = self.handle.get_table_for_tag(tag); let status = if result.is_some() { "Found" } else
; debug!("{} font table[{}] with family={}, face={}", status, tag.tag_to_str(), self.handle.family_name(), self.handle.face_name()); return result; } #[inline] pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { let codepoint = match self.variant { font_variant::T::small_caps => codepoint.to_uppercase().next().unwrap(), //FIXME: #5938 font_variant::T::normal => codepoint, }; self.handle.glyph_index(codepoint) } pub fn glyph_h_kerning(&mut self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { self.handle.glyph_h_kerning(first_glyph, second_glyph) } pub fn glyph_h_advance(&mut self, glyph: GlyphId) -> FractionalPixel { let handle = &self.handle; self.glyph_advance_cache.find_or_create(&glyph, |glyph| { match handle.glyph_h_advance(*glyph) { Some(adv) => adv, None => 10f64 as FractionalPixel // FIXME: Need fallback strategy } }) } } pub struct FontGroup { pub fonts: SmallVec8<Rc<RefCell<Font>>>, } impl FontGroup { pub fn new(fonts: SmallVec8<Rc<RefCell<Font>>>) -> FontGroup { FontGroup { fonts: fonts, } } } pub struct RunMetrics { // may be negative due to negative width (i.e., kerning of '.' in 'P.T.') pub advance_width: Au, pub ascent: Au, // nonzero pub descent: Au, // nonzero // this bounding box is relative to the left origin baseline. // so, bounding_box.position.y = -ascent pub bounding_box: Rect<Au> } impl RunMetrics { pub fn new(advance: Au, ascent: Au, descent: Au) -> RunMetrics { let bounds = Rect(Point2D(Au(0), -ascent), Size2D(advance, ascent + descent)); // TODO(Issue #125): support loose and tight bounding boxes; using the // ascent+descent and advance is sometimes too generous and // looking at actual glyph extents can yield a tighter box. RunMetrics { advance_width: advance, bounding_box: bounds, ascent: ascent, descent: descent, } } }
{ "Didn't find" }
conditional_block
font.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 geom::{Point2D, Rect, Size2D}; use std::borrow::ToOwned; use std::mem; use std::slice; use std::rc::Rc; use std::cell::RefCell; use util::cache::HashCache; use util::smallvec::SmallVec8; use style::computed_values::{font_stretch, font_variant, font_weight}; use style::properties::style_structs::Font as FontStyle; use std::sync::Arc; use platform::font_context::FontContextHandle; use platform::font::{FontHandle, FontTable}; use util::geometry::Au; use text::glyph::{GlyphStore, GlyphId}; use text::shaping::ShaperMethods; use text::Shaper; use font_template::FontTemplateDescriptor; use platform::font_template::FontTemplateData; // FontHandle encapsulates access to the platform's font API, // e.g. quartz, FreeType. It provides access to metrics and tables // needed by the text shaper as well as access to the underlying font // resources needed by the graphics layer to draw glyphs. pub trait FontHandleMethods { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<Self,()>; fn template(&self) -> Arc<FontTemplateData>; fn family_name(&self) -> String; fn face_name(&self) -> String; fn is_italic(&self) -> bool; fn boldness(&self) -> font_weight::T; fn stretchiness(&self) -> font_stretch::T; fn glyph_index(&self, codepoint: char) -> Option<GlyphId>; fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>; fn glyph_h_kerning(&self, GlyphId, GlyphId) -> FractionalPixel; fn metrics(&self) -> FontMetrics; fn get_table_for_tag(&self, FontTableTag) -> Option<FontTable>; } // Used to abstract over the shaper's choice of fixed int representation. pub type FractionalPixel = f64; pub type FontTableTag = u32; pub trait FontTableTagConversions { fn tag_to_str(&self) -> String; } impl FontTableTagConversions for FontTableTag { fn tag_to_str(&self) -> String { unsafe { let pointer = mem::transmute::<&u32, *const u8>(self); let mut bytes = slice::from_raw_parts(pointer, 4).to_vec(); bytes.reverse(); String::from_utf8_unchecked(bytes) } } } pub trait FontTableMethods { fn with_buffer<F>(&self, F) where F: FnOnce(*const u8, usize); } #[derive(Clone, Debug)] pub struct FontMetrics { pub underline_size: Au, pub underline_offset: Au, pub strikeout_size: Au, pub strikeout_offset: Au, pub leading: Au, pub x_height: Au, pub em_size: Au, pub ascent: Au, pub descent: Au, pub max_advance: Au, pub average_advance: Au, pub line_gap: Au, } pub type SpecifiedFontStyle = FontStyle; pub type UsedFontStyle = FontStyle; pub struct Font { pub handle: FontHandle, pub metrics: FontMetrics, pub variant: font_variant::T, pub descriptor: FontTemplateDescriptor, pub requested_pt_size: Au, pub actual_pt_size: Au, pub shaper: Option<Shaper>, pub shape_cache: HashCache<ShapeCacheEntry,Arc<GlyphStore>>, pub glyph_advance_cache: HashCache<u32,FractionalPixel>, } bitflags! { flags ShapingFlags: u8 { #[doc="Set if the text is entirely whitespace."] const IS_WHITESPACE_SHAPING_FLAG = 0x01, #[doc="Set if we are to ignore ligatures."] const IGNORE_LIGATURES_SHAPING_FLAG = 0x02, #[doc="Set if we are to disable kerning."] const DISABLE_KERNING_SHAPING_FLAG = 0x04 } } /// Various options that control text shaping. #[derive(Clone, Eq, PartialEq, Hash, Copy)] pub struct ShapingOptions { /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property. /// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null. pub letter_spacing: Option<Au>, /// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property. pub word_spacing: Au, /// Various flags. pub flags: ShapingFlags, } /// An entry in the shape cache. #[derive(Clone, Eq, PartialEq, Hash)] pub struct ShapeCacheEntry { text: String, options: ShapingOptions, } impl Font { pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc<GlyphStore> { self.make_shaper(options); //FIXME: find the equivalent of Equiv and the old ShapeCacheEntryRef let shaper = &self.shaper; let lookup_key = ShapeCacheEntry { text: text.to_owned(), options: options.clone(), }; match self.shape_cache.find(&lookup_key) { None => {} Some(glyphs) => return glyphs.clone(), } let mut glyphs = GlyphStore::new(text.chars().count(), options.flags.contains(IS_WHITESPACE_SHAPING_FLAG)); shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs); let glyphs = Arc::new(glyphs); self.shape_cache.insert(ShapeCacheEntry { text: text.to_owned(), options: *options, }, glyphs.clone()); glyphs } fn make_shaper<'a>(&'a mut self, options: &ShapingOptions) -> &'a Shaper { // fast path: already created a shaper match self.shaper { Some(ref mut shaper) => { shaper.set_options(options); return shaper }, None => {} } let shaper = Shaper::new(self, options); self.shaper = Some(shaper); self.shaper.as_ref().unwrap() } pub fn get_table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let result = self.handle.get_table_for_tag(tag); let status = if result.is_some() { "Found" } else { "Didn't find" }; debug!("{} font table[{}] with family={}, face={}", status, tag.tag_to_str(), self.handle.family_name(), self.handle.face_name()); return result; } #[inline] pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { let codepoint = match self.variant { font_variant::T::small_caps => codepoint.to_uppercase().next().unwrap(), //FIXME: #5938 font_variant::T::normal => codepoint, }; self.handle.glyph_index(codepoint) } pub fn glyph_h_kerning(&mut self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { self.handle.glyph_h_kerning(first_glyph, second_glyph) } pub fn glyph_h_advance(&mut self, glyph: GlyphId) -> FractionalPixel { let handle = &self.handle; self.glyph_advance_cache.find_or_create(&glyph, |glyph| { match handle.glyph_h_advance(*glyph) { Some(adv) => adv, None => 10f64 as FractionalPixel // FIXME: Need fallback strategy } }) } } pub struct FontGroup { pub fonts: SmallVec8<Rc<RefCell<Font>>>, } impl FontGroup { pub fn new(fonts: SmallVec8<Rc<RefCell<Font>>>) -> FontGroup { FontGroup { fonts: fonts, } } } pub struct RunMetrics { // may be negative due to negative width (i.e., kerning of '.' in 'P.T.') pub advance_width: Au, pub ascent: Au, // nonzero pub descent: Au, // nonzero // this bounding box is relative to the left origin baseline. // so, bounding_box.position.y = -ascent pub bounding_box: Rect<Au> } impl RunMetrics { pub fn
(advance: Au, ascent: Au, descent: Au) -> RunMetrics { let bounds = Rect(Point2D(Au(0), -ascent), Size2D(advance, ascent + descent)); // TODO(Issue #125): support loose and tight bounding boxes; using the // ascent+descent and advance is sometimes too generous and // looking at actual glyph extents can yield a tighter box. RunMetrics { advance_width: advance, bounding_box: bounds, ascent: ascent, descent: descent, } } }
new
identifier_name
font.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 geom::{Point2D, Rect, Size2D}; use std::borrow::ToOwned; use std::mem; use std::slice; use std::rc::Rc; use std::cell::RefCell; use util::cache::HashCache; use util::smallvec::SmallVec8; use style::computed_values::{font_stretch, font_variant, font_weight}; use style::properties::style_structs::Font as FontStyle; use std::sync::Arc; use platform::font_context::FontContextHandle; use platform::font::{FontHandle, FontTable}; use util::geometry::Au; use text::glyph::{GlyphStore, GlyphId}; use text::shaping::ShaperMethods; use text::Shaper; use font_template::FontTemplateDescriptor; use platform::font_template::FontTemplateData; // FontHandle encapsulates access to the platform's font API, // e.g. quartz, FreeType. It provides access to metrics and tables // needed by the text shaper as well as access to the underlying font // resources needed by the graphics layer to draw glyphs. pub trait FontHandleMethods { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<Self,()>; fn template(&self) -> Arc<FontTemplateData>; fn family_name(&self) -> String; fn face_name(&self) -> String; fn is_italic(&self) -> bool; fn boldness(&self) -> font_weight::T; fn stretchiness(&self) -> font_stretch::T; fn glyph_index(&self, codepoint: char) -> Option<GlyphId>; fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>; fn glyph_h_kerning(&self, GlyphId, GlyphId) -> FractionalPixel; fn metrics(&self) -> FontMetrics; fn get_table_for_tag(&self, FontTableTag) -> Option<FontTable>; } // Used to abstract over the shaper's choice of fixed int representation. pub type FractionalPixel = f64; pub type FontTableTag = u32; pub trait FontTableTagConversions { fn tag_to_str(&self) -> String; } impl FontTableTagConversions for FontTableTag { fn tag_to_str(&self) -> String { unsafe { let pointer = mem::transmute::<&u32, *const u8>(self); let mut bytes = slice::from_raw_parts(pointer, 4).to_vec(); bytes.reverse(); String::from_utf8_unchecked(bytes) } } } pub trait FontTableMethods { fn with_buffer<F>(&self, F) where F: FnOnce(*const u8, usize); } #[derive(Clone, Debug)] pub struct FontMetrics { pub underline_size: Au, pub underline_offset: Au, pub strikeout_size: Au, pub strikeout_offset: Au, pub leading: Au, pub x_height: Au, pub em_size: Au, pub ascent: Au, pub descent: Au, pub max_advance: Au, pub average_advance: Au, pub line_gap: Au, } pub type SpecifiedFontStyle = FontStyle; pub type UsedFontStyle = FontStyle; pub struct Font { pub handle: FontHandle, pub metrics: FontMetrics, pub variant: font_variant::T, pub descriptor: FontTemplateDescriptor, pub requested_pt_size: Au, pub actual_pt_size: Au, pub shaper: Option<Shaper>, pub shape_cache: HashCache<ShapeCacheEntry,Arc<GlyphStore>>, pub glyph_advance_cache: HashCache<u32,FractionalPixel>, } bitflags! { flags ShapingFlags: u8 { #[doc="Set if the text is entirely whitespace."] const IS_WHITESPACE_SHAPING_FLAG = 0x01, #[doc="Set if we are to ignore ligatures."] const IGNORE_LIGATURES_SHAPING_FLAG = 0x02, #[doc="Set if we are to disable kerning."] const DISABLE_KERNING_SHAPING_FLAG = 0x04 } } /// Various options that control text shaping. #[derive(Clone, Eq, PartialEq, Hash, Copy)] pub struct ShapingOptions { /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property. /// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null. pub letter_spacing: Option<Au>, /// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property. pub word_spacing: Au, /// Various flags. pub flags: ShapingFlags, } /// An entry in the shape cache. #[derive(Clone, Eq, PartialEq, Hash)] pub struct ShapeCacheEntry { text: String, options: ShapingOptions, } impl Font { pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc<GlyphStore> { self.make_shaper(options); //FIXME: find the equivalent of Equiv and the old ShapeCacheEntryRef let shaper = &self.shaper; let lookup_key = ShapeCacheEntry { text: text.to_owned(), options: options.clone(), }; match self.shape_cache.find(&lookup_key) { None => {} Some(glyphs) => return glyphs.clone(), } let mut glyphs = GlyphStore::new(text.chars().count(), options.flags.contains(IS_WHITESPACE_SHAPING_FLAG)); shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs); let glyphs = Arc::new(glyphs); self.shape_cache.insert(ShapeCacheEntry { text: text.to_owned(), options: *options, }, glyphs.clone()); glyphs } fn make_shaper<'a>(&'a mut self, options: &ShapingOptions) -> &'a Shaper { // fast path: already created a shaper match self.shaper { Some(ref mut shaper) => { shaper.set_options(options); return shaper }, None => {} } let shaper = Shaper::new(self, options); self.shaper = Some(shaper); self.shaper.as_ref().unwrap() } pub fn get_table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let result = self.handle.get_table_for_tag(tag); let status = if result.is_some() { "Found" } else { "Didn't find" }; debug!("{} font table[{}] with family={}, face={}", status, tag.tag_to_str(), self.handle.family_name(), self.handle.face_name()); return result; } #[inline] pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { let codepoint = match self.variant { font_variant::T::small_caps => codepoint.to_uppercase().next().unwrap(), //FIXME: #5938 font_variant::T::normal => codepoint, }; self.handle.glyph_index(codepoint) } pub fn glyph_h_kerning(&mut self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel
pub fn glyph_h_advance(&mut self, glyph: GlyphId) -> FractionalPixel { let handle = &self.handle; self.glyph_advance_cache.find_or_create(&glyph, |glyph| { match handle.glyph_h_advance(*glyph) { Some(adv) => adv, None => 10f64 as FractionalPixel // FIXME: Need fallback strategy } }) } } pub struct FontGroup { pub fonts: SmallVec8<Rc<RefCell<Font>>>, } impl FontGroup { pub fn new(fonts: SmallVec8<Rc<RefCell<Font>>>) -> FontGroup { FontGroup { fonts: fonts, } } } pub struct RunMetrics { // may be negative due to negative width (i.e., kerning of '.' in 'P.T.') pub advance_width: Au, pub ascent: Au, // nonzero pub descent: Au, // nonzero // this bounding box is relative to the left origin baseline. // so, bounding_box.position.y = -ascent pub bounding_box: Rect<Au> } impl RunMetrics { pub fn new(advance: Au, ascent: Au, descent: Au) -> RunMetrics { let bounds = Rect(Point2D(Au(0), -ascent), Size2D(advance, ascent + descent)); // TODO(Issue #125): support loose and tight bounding boxes; using the // ascent+descent and advance is sometimes too generous and // looking at actual glyph extents can yield a tighter box. RunMetrics { advance_width: advance, bounding_box: bounds, ascent: ascent, descent: descent, } } }
{ self.handle.glyph_h_kerning(first_glyph, second_glyph) }
identifier_body
rename-directory.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. // This test can't be a unit test in std, // because it needs TempDir, which is in extra // ignore-cross-compile #![feature(rustc_private, path_ext)] extern crate rustc_back; use std::ffi::CString; use std::fs::{self, File, PathExt}; use rustc_back::tempdir::TempDir; fn rename_directory()
pub fn main() { rename_directory() }
{ let tmpdir = TempDir::new("rename_directory").ok().expect("rename_directory failed"); let tmpdir = tmpdir.path(); let old_path = tmpdir.join("foo/bar/baz"); fs::create_dir_all(&old_path).unwrap(); let test_file = &old_path.join("temp.txt"); File::create(test_file).unwrap(); let new_path = tmpdir.join("quux/blat"); fs::create_dir_all(&new_path).unwrap(); fs::rename(&old_path, &new_path.join("newdir")); assert!(new_path.join("newdir").is_dir()); assert!(new_path.join("newdir/temp.txt").exists()); }
identifier_body
rename-directory.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. // This test can't be a unit test in std, // because it needs TempDir, which is in extra // ignore-cross-compile #![feature(rustc_private, path_ext)] extern crate rustc_back; use std::ffi::CString; use std::fs::{self, File, PathExt}; use rustc_back::tempdir::TempDir; fn rename_directory() { let tmpdir = TempDir::new("rename_directory").ok().expect("rename_directory failed"); let tmpdir = tmpdir.path(); let old_path = tmpdir.join("foo/bar/baz"); fs::create_dir_all(&old_path).unwrap(); let test_file = &old_path.join("temp.txt"); File::create(test_file).unwrap(); let new_path = tmpdir.join("quux/blat"); fs::create_dir_all(&new_path).unwrap(); fs::rename(&old_path, &new_path.join("newdir")); assert!(new_path.join("newdir").is_dir()); assert!(new_path.join("newdir/temp.txt").exists()); }
pub fn main() { rename_directory() }
random_line_split
rename-directory.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. // This test can't be a unit test in std, // because it needs TempDir, which is in extra // ignore-cross-compile #![feature(rustc_private, path_ext)] extern crate rustc_back; use std::ffi::CString; use std::fs::{self, File, PathExt}; use rustc_back::tempdir::TempDir; fn rename_directory() { let tmpdir = TempDir::new("rename_directory").ok().expect("rename_directory failed"); let tmpdir = tmpdir.path(); let old_path = tmpdir.join("foo/bar/baz"); fs::create_dir_all(&old_path).unwrap(); let test_file = &old_path.join("temp.txt"); File::create(test_file).unwrap(); let new_path = tmpdir.join("quux/blat"); fs::create_dir_all(&new_path).unwrap(); fs::rename(&old_path, &new_path.join("newdir")); assert!(new_path.join("newdir").is_dir()); assert!(new_path.join("newdir/temp.txt").exists()); } pub fn
() { rename_directory() }
main
identifier_name
enum-discrim-autosizing.rs
// run-pass #![allow(dead_code)] #![allow(overflowing_literals)] use std::mem::size_of; enum Ei8 { Ai8 = -1, Bi8 = 0 } enum Eu8 { Au8 = 0, Bu8 = 0x80 } enum Ei16 { Ai16 = -1, Bi16 = 0x80 } enum Eu16 { Au16 = 0, Bu16 = 0x8000 } enum Ei32 { Ai32 = -1, Bi32 = 0x8000 } enum
{ Au32 = 0, Bu32 = 0x8000_0000 } enum Ei64 { Ai64 = -1, Bi64 = 0x8000_0000 } pub fn main() { assert_eq!(size_of::<Ei8>(), 1); assert_eq!(size_of::<Eu8>(), 1); assert_eq!(size_of::<Ei16>(), 2); assert_eq!(size_of::<Eu16>(), 2); assert_eq!(size_of::<Ei32>(), 4); assert_eq!(size_of::<Eu32>(), 4); #[cfg(target_pointer_width = "64")] assert_eq!(size_of::<Ei64>(), 8); #[cfg(target_pointer_width = "32")] assert_eq!(size_of::<Ei64>(), 4); }
Eu32
identifier_name
enum-discrim-autosizing.rs
// run-pass #![allow(dead_code)] #![allow(overflowing_literals)] use std::mem::size_of; enum Ei8 { Ai8 = -1, Bi8 = 0 } enum Eu8 { Au8 = 0, Bu8 = 0x80 } enum Ei16 { Ai16 = -1, Bi16 = 0x80 } enum Eu16 { Au16 = 0, Bu16 = 0x8000 }
enum Ei32 { Ai32 = -1, Bi32 = 0x8000 } enum Eu32 { Au32 = 0, Bu32 = 0x8000_0000 } enum Ei64 { Ai64 = -1, Bi64 = 0x8000_0000 } pub fn main() { assert_eq!(size_of::<Ei8>(), 1); assert_eq!(size_of::<Eu8>(), 1); assert_eq!(size_of::<Ei16>(), 2); assert_eq!(size_of::<Eu16>(), 2); assert_eq!(size_of::<Ei32>(), 4); assert_eq!(size_of::<Eu32>(), 4); #[cfg(target_pointer_width = "64")] assert_eq!(size_of::<Ei64>(), 8); #[cfg(target_pointer_width = "32")] assert_eq!(size_of::<Ei64>(), 4); }
random_line_split
mod.rs
use rand::{thread_rng, Rng}; pub mod model; mod grid; pub use self::grid::Grid; pub use self::model::Model; // A direction that the snake head can travel in #[derive(Clone, Copy, PartialEq)] pub enum Direction { Up, Down, Left, Right, } impl Direction { pub fn is_opposite_direction(&self, other: Direction) -> bool { match *self { Direction::Up => other == Direction::Down, Direction::Down => other == Direction::Up, Direction::Left => other == Direction::Right, Direction::Right => other == Direction::Left, } } } // A cell in the grid is either empty, occupied by a snake part (with a direction the // tail should continue in when it hits it), or contains a piece of food. #[derive(Clone)] pub enum GridCell { Empty, Food, SnakePart, } impl GridCell { pub fn change_cell(&mut self, value: GridCell) { *self = value; } pub fn is_empty(&self) -> bool { match *self { GridCell::Empty => true, _ => false, } } pub fn
(&self) -> bool { match *self { GridCell::Food => true, _ => false, } } } // A cell locaiton in the arena #[derive(Clone, Copy)] pub struct CellLocation { x: usize, y: usize, } impl CellLocation { pub fn get_neighbour(&self, direction: Direction) -> CellLocation { match direction { Direction::Up => { CellLocation { x: self.x + 1, y: self.y, } } Direction::Down => { CellLocation { x: self.x - 1, y: self.y, } } Direction::Left => { CellLocation { x: self.x, y: self.y - 1, } } Direction::Right => { CellLocation { x: self.x, y: self.y + 1, } } } } }
is_food
identifier_name
mod.rs
use rand::{thread_rng, Rng}; pub mod model; mod grid; pub use self::grid::Grid; pub use self::model::Model; // A direction that the snake head can travel in #[derive(Clone, Copy, PartialEq)] pub enum Direction { Up, Down, Left, Right, } impl Direction { pub fn is_opposite_direction(&self, other: Direction) -> bool { match *self { Direction::Up => other == Direction::Down, Direction::Down => other == Direction::Up, Direction::Left => other == Direction::Right, Direction::Right => other == Direction::Left, }
#[derive(Clone)] pub enum GridCell { Empty, Food, SnakePart, } impl GridCell { pub fn change_cell(&mut self, value: GridCell) { *self = value; } pub fn is_empty(&self) -> bool { match *self { GridCell::Empty => true, _ => false, } } pub fn is_food(&self) -> bool { match *self { GridCell::Food => true, _ => false, } } } // A cell locaiton in the arena #[derive(Clone, Copy)] pub struct CellLocation { x: usize, y: usize, } impl CellLocation { pub fn get_neighbour(&self, direction: Direction) -> CellLocation { match direction { Direction::Up => { CellLocation { x: self.x + 1, y: self.y, } } Direction::Down => { CellLocation { x: self.x - 1, y: self.y, } } Direction::Left => { CellLocation { x: self.x, y: self.y - 1, } } Direction::Right => { CellLocation { x: self.x, y: self.y + 1, } } } } }
} } // A cell in the grid is either empty, occupied by a snake part (with a direction the // tail should continue in when it hits it), or contains a piece of food.
random_line_split
s3.rs
//! This implements S3 sync for the symbolserver. use std::result::Result as StdResult; use std::env; use std::io::{Read, Cursor}; use rusoto::{ProvideAwsCredentials, AwsCredentials, CredentialsError, ChainProvider}; use rusoto::s3::{S3Client, ListObjectsRequest, GetObjectRequest, Object, ListObjectsError}; use chrono::{Duration, UTC}; use hyper::client::{Client as HyperClient, ProxyConfig}; use hyper::client::RedirectPolicy; use hyper::net::{HttpConnector, HttpsConnector}; use hyper_native_tls::NativeTlsClient; use url::Url; use super::sdk::SdkInfo; use super::config::Config; use super::memdb::stash::RemoteSdk; use super::{ErrorKind, Result, ResultExt}; struct FlexibleCredentialsProvider { chain_provider: ChainProvider, access_key: Option<String>, secret_key: Option<String>, } /// Abstracts over S3 operations pub struct S3 { url: Url, client: S3Client<FlexibleCredentialsProvider, HyperClient>, } impl ProvideAwsCredentials for FlexibleCredentialsProvider { fn credentials(&self) -> StdResult<AwsCredentials, CredentialsError> { if_chain! { if let Some(ref access_key) = self.access_key; if let Some(ref secret_key) = self.secret_key; then { Ok(AwsCredentials::new(access_key.to_string(), secret_key.to_string(), None, UTC::now() + Duration::seconds(3600))) } else { self.chain_provider.credentials() } } } } fn filename_from_key(key: &str) -> Option<&str> { key.rsplitn(2, '/').next() } fn unquote_etag(quoted_etag: Option<String>) -> Option<String> { quoted_etag.and_then(|etag| { if etag.len() > 2 && &etag[..1] == "\"" && &etag[etag.len() - 1..] == "\"" { Some(etag[1..etag.len() - 1].into()) } else { None } }) } pub fn new_hyper_client() -> Result<HyperClient> { let ssl = NativeTlsClient::new().chain_err(|| format!("Couldn't create NativeTlsClient."))?; let mut client = if let Ok(proxy_url) = env::var("http_proxy") { info!("Using HTTP proxy at {}", proxy_url); let proxy : Url = proxy_url.parse()?; let proxy_config = ProxyConfig::new( "http", proxy.host_str().unwrap().to_string(), proxy.port().unwrap(), HttpConnector, ssl); HyperClient::with_proxy_config(proxy_config) } else { let connector = HttpsConnector::new(ssl); HyperClient::with_connector(connector) }; client.set_redirect_policy(RedirectPolicy::FollowAll); Ok(client) } impl S3 { /// Creates an S3 abstraction from a given config. pub fn from_config(config: &Config) -> Result<S3> { Ok(S3 { url: config.get_aws_bucket_url()?, client: S3Client::new(new_hyper_client().chain_err( || "Could not configure TLS layer")?, FlexibleCredentialsProvider { chain_provider: ChainProvider::new(), access_key: config.get_aws_access_key().map(|x| x.to_string()), secret_key: config.get_aws_secret_key().map(|x| x.to_string()), }, config.get_aws_region()?) }) } fn
(&self) -> &str { self.url.host_str().unwrap() } fn bucket_prefix(&self) -> String { let path = self.url.path().trim_matches('/'); if path.len() == 0 { "".into() } else { format!("{}/", path) } } fn object_to_remote_sdk(&self, obj: Object) -> Option<RemoteSdk> { if_chain! { if let Some(key) = obj.key; if key.ends_with(".memdbz"); if let Some(filename) = filename_from_key(&key); if let Some(info) = SdkInfo::from_filename(filename); if let Some(etag) = unquote_etag(obj.e_tag); if let Some(size) = obj.size; then { Some(RemoteSdk::new(filename.into(), info, etag, size as u64)) } else { None } } } /// Requests the list of all compressed SDKs in the bucket pub fn list_upstream_sdks(&self) -> Result<Vec<RemoteSdk>> { let mut request = ListObjectsRequest::default(); request.bucket = self.bucket_name().into(); request.prefix = Some(self.bucket_prefix()); // this is the only place where we currently explicitly check for S3 // HTTP errors because realistically that call is always going ot be // the first one that happens. This gives us better detection in // the health check for raw network errors to better report // downtime. let out = match self.client.list_objects(&request) { Ok(out) => out, Err(ListObjectsError::HttpDispatch(err)) => { return Err(ErrorKind::S3Unavailable(err.to_string()).into()); } Err(err) => { return Err(err).chain_err(|| "Failed to fetch SDKs from S3")?; } }; let mut rv = vec![]; for obj in out.contents.unwrap_or_else(|| vec![]) { if let Some(remote_sdk) = self.object_to_remote_sdk(obj) { rv.push(remote_sdk); } } Ok(rv) } /// Downloads a given remote SDK and returns a reader to the /// bytes in the SDK. /// /// The files downloaded are XZ compressed. pub fn download_sdk(&self, sdk: &RemoteSdk) -> Result<Box<Read>> { let request = GetObjectRequest { bucket: self.bucket_name().into(), key: format!("{}/{}", self.bucket_prefix() .trim_right_matches('/'), sdk.filename()), response_content_type: Some("application/octet-stream".to_owned()), ..Default::default() }; let out = self.client.get_object(&request) .chain_err(|| "Failed to fetch SDK from S3")?; // XXX: this really should not read into memory but we are currently // restricted by rusoto here. https://github.com/rusoto/rusoto/issues/481 Ok(Box::new(Cursor::new(out.body.unwrap_or_else(|| vec![])))) } }
bucket_name
identifier_name
s3.rs
//! This implements S3 sync for the symbolserver. use std::result::Result as StdResult; use std::env; use std::io::{Read, Cursor}; use rusoto::{ProvideAwsCredentials, AwsCredentials, CredentialsError, ChainProvider}; use rusoto::s3::{S3Client, ListObjectsRequest, GetObjectRequest, Object, ListObjectsError}; use chrono::{Duration, UTC}; use hyper::client::{Client as HyperClient, ProxyConfig}; use hyper::client::RedirectPolicy; use hyper::net::{HttpConnector, HttpsConnector}; use hyper_native_tls::NativeTlsClient; use url::Url; use super::sdk::SdkInfo; use super::config::Config; use super::memdb::stash::RemoteSdk; use super::{ErrorKind, Result, ResultExt}; struct FlexibleCredentialsProvider { chain_provider: ChainProvider, access_key: Option<String>, secret_key: Option<String>, } /// Abstracts over S3 operations pub struct S3 { url: Url, client: S3Client<FlexibleCredentialsProvider, HyperClient>, } impl ProvideAwsCredentials for FlexibleCredentialsProvider { fn credentials(&self) -> StdResult<AwsCredentials, CredentialsError> { if_chain! { if let Some(ref access_key) = self.access_key; if let Some(ref secret_key) = self.secret_key; then { Ok(AwsCredentials::new(access_key.to_string(), secret_key.to_string(), None, UTC::now() + Duration::seconds(3600))) } else { self.chain_provider.credentials() } } } } fn filename_from_key(key: &str) -> Option<&str> { key.rsplitn(2, '/').next() } fn unquote_etag(quoted_etag: Option<String>) -> Option<String> { quoted_etag.and_then(|etag| { if etag.len() > 2 && &etag[..1] == "\"" && &etag[etag.len() - 1..] == "\"" { Some(etag[1..etag.len() - 1].into()) } else { None } }) } pub fn new_hyper_client() -> Result<HyperClient> { let ssl = NativeTlsClient::new().chain_err(|| format!("Couldn't create NativeTlsClient."))?; let mut client = if let Ok(proxy_url) = env::var("http_proxy") { info!("Using HTTP proxy at {}", proxy_url); let proxy : Url = proxy_url.parse()?; let proxy_config = ProxyConfig::new( "http", proxy.host_str().unwrap().to_string(), proxy.port().unwrap(), HttpConnector, ssl); HyperClient::with_proxy_config(proxy_config) } else { let connector = HttpsConnector::new(ssl); HyperClient::with_connector(connector) }; client.set_redirect_policy(RedirectPolicy::FollowAll); Ok(client) } impl S3 { /// Creates an S3 abstraction from a given config. pub fn from_config(config: &Config) -> Result<S3> { Ok(S3 { url: config.get_aws_bucket_url()?, client: S3Client::new(new_hyper_client().chain_err( || "Could not configure TLS layer")?, FlexibleCredentialsProvider { chain_provider: ChainProvider::new(), access_key: config.get_aws_access_key().map(|x| x.to_string()), secret_key: config.get_aws_secret_key().map(|x| x.to_string()), }, config.get_aws_region()?) }) } fn bucket_name(&self) -> &str { self.url.host_str().unwrap() } fn bucket_prefix(&self) -> String { let path = self.url.path().trim_matches('/'); if path.len() == 0 { "".into() } else { format!("{}/", path) } } fn object_to_remote_sdk(&self, obj: Object) -> Option<RemoteSdk> { if_chain! { if let Some(key) = obj.key; if key.ends_with(".memdbz"); if let Some(filename) = filename_from_key(&key); if let Some(info) = SdkInfo::from_filename(filename); if let Some(etag) = unquote_etag(obj.e_tag); if let Some(size) = obj.size; then { Some(RemoteSdk::new(filename.into(), info, etag, size as u64)) } else { None } } } /// Requests the list of all compressed SDKs in the bucket pub fn list_upstream_sdks(&self) -> Result<Vec<RemoteSdk>> { let mut request = ListObjectsRequest::default(); request.bucket = self.bucket_name().into(); request.prefix = Some(self.bucket_prefix()); // this is the only place where we currently explicitly check for S3 // HTTP errors because realistically that call is always going ot be // the first one that happens. This gives us better detection in // the health check for raw network errors to better report // downtime. let out = match self.client.list_objects(&request) { Ok(out) => out, Err(ListObjectsError::HttpDispatch(err)) => { return Err(ErrorKind::S3Unavailable(err.to_string()).into()); } Err(err) => {
let mut rv = vec![]; for obj in out.contents.unwrap_or_else(|| vec![]) { if let Some(remote_sdk) = self.object_to_remote_sdk(obj) { rv.push(remote_sdk); } } Ok(rv) } /// Downloads a given remote SDK and returns a reader to the /// bytes in the SDK. /// /// The files downloaded are XZ compressed. pub fn download_sdk(&self, sdk: &RemoteSdk) -> Result<Box<Read>> { let request = GetObjectRequest { bucket: self.bucket_name().into(), key: format!("{}/{}", self.bucket_prefix() .trim_right_matches('/'), sdk.filename()), response_content_type: Some("application/octet-stream".to_owned()), ..Default::default() }; let out = self.client.get_object(&request) .chain_err(|| "Failed to fetch SDK from S3")?; // XXX: this really should not read into memory but we are currently // restricted by rusoto here. https://github.com/rusoto/rusoto/issues/481 Ok(Box::new(Cursor::new(out.body.unwrap_or_else(|| vec![])))) } }
return Err(err).chain_err(|| "Failed to fetch SDKs from S3")?; } };
random_line_split
s3.rs
//! This implements S3 sync for the symbolserver. use std::result::Result as StdResult; use std::env; use std::io::{Read, Cursor}; use rusoto::{ProvideAwsCredentials, AwsCredentials, CredentialsError, ChainProvider}; use rusoto::s3::{S3Client, ListObjectsRequest, GetObjectRequest, Object, ListObjectsError}; use chrono::{Duration, UTC}; use hyper::client::{Client as HyperClient, ProxyConfig}; use hyper::client::RedirectPolicy; use hyper::net::{HttpConnector, HttpsConnector}; use hyper_native_tls::NativeTlsClient; use url::Url; use super::sdk::SdkInfo; use super::config::Config; use super::memdb::stash::RemoteSdk; use super::{ErrorKind, Result, ResultExt}; struct FlexibleCredentialsProvider { chain_provider: ChainProvider, access_key: Option<String>, secret_key: Option<String>, } /// Abstracts over S3 operations pub struct S3 { url: Url, client: S3Client<FlexibleCredentialsProvider, HyperClient>, } impl ProvideAwsCredentials for FlexibleCredentialsProvider { fn credentials(&self) -> StdResult<AwsCredentials, CredentialsError>
} fn filename_from_key(key: &str) -> Option<&str> { key.rsplitn(2, '/').next() } fn unquote_etag(quoted_etag: Option<String>) -> Option<String> { quoted_etag.and_then(|etag| { if etag.len() > 2 && &etag[..1] == "\"" && &etag[etag.len() - 1..] == "\"" { Some(etag[1..etag.len() - 1].into()) } else { None } }) } pub fn new_hyper_client() -> Result<HyperClient> { let ssl = NativeTlsClient::new().chain_err(|| format!("Couldn't create NativeTlsClient."))?; let mut client = if let Ok(proxy_url) = env::var("http_proxy") { info!("Using HTTP proxy at {}", proxy_url); let proxy : Url = proxy_url.parse()?; let proxy_config = ProxyConfig::new( "http", proxy.host_str().unwrap().to_string(), proxy.port().unwrap(), HttpConnector, ssl); HyperClient::with_proxy_config(proxy_config) } else { let connector = HttpsConnector::new(ssl); HyperClient::with_connector(connector) }; client.set_redirect_policy(RedirectPolicy::FollowAll); Ok(client) } impl S3 { /// Creates an S3 abstraction from a given config. pub fn from_config(config: &Config) -> Result<S3> { Ok(S3 { url: config.get_aws_bucket_url()?, client: S3Client::new(new_hyper_client().chain_err( || "Could not configure TLS layer")?, FlexibleCredentialsProvider { chain_provider: ChainProvider::new(), access_key: config.get_aws_access_key().map(|x| x.to_string()), secret_key: config.get_aws_secret_key().map(|x| x.to_string()), }, config.get_aws_region()?) }) } fn bucket_name(&self) -> &str { self.url.host_str().unwrap() } fn bucket_prefix(&self) -> String { let path = self.url.path().trim_matches('/'); if path.len() == 0 { "".into() } else { format!("{}/", path) } } fn object_to_remote_sdk(&self, obj: Object) -> Option<RemoteSdk> { if_chain! { if let Some(key) = obj.key; if key.ends_with(".memdbz"); if let Some(filename) = filename_from_key(&key); if let Some(info) = SdkInfo::from_filename(filename); if let Some(etag) = unquote_etag(obj.e_tag); if let Some(size) = obj.size; then { Some(RemoteSdk::new(filename.into(), info, etag, size as u64)) } else { None } } } /// Requests the list of all compressed SDKs in the bucket pub fn list_upstream_sdks(&self) -> Result<Vec<RemoteSdk>> { let mut request = ListObjectsRequest::default(); request.bucket = self.bucket_name().into(); request.prefix = Some(self.bucket_prefix()); // this is the only place where we currently explicitly check for S3 // HTTP errors because realistically that call is always going ot be // the first one that happens. This gives us better detection in // the health check for raw network errors to better report // downtime. let out = match self.client.list_objects(&request) { Ok(out) => out, Err(ListObjectsError::HttpDispatch(err)) => { return Err(ErrorKind::S3Unavailable(err.to_string()).into()); } Err(err) => { return Err(err).chain_err(|| "Failed to fetch SDKs from S3")?; } }; let mut rv = vec![]; for obj in out.contents.unwrap_or_else(|| vec![]) { if let Some(remote_sdk) = self.object_to_remote_sdk(obj) { rv.push(remote_sdk); } } Ok(rv) } /// Downloads a given remote SDK and returns a reader to the /// bytes in the SDK. /// /// The files downloaded are XZ compressed. pub fn download_sdk(&self, sdk: &RemoteSdk) -> Result<Box<Read>> { let request = GetObjectRequest { bucket: self.bucket_name().into(), key: format!("{}/{}", self.bucket_prefix() .trim_right_matches('/'), sdk.filename()), response_content_type: Some("application/octet-stream".to_owned()), ..Default::default() }; let out = self.client.get_object(&request) .chain_err(|| "Failed to fetch SDK from S3")?; // XXX: this really should not read into memory but we are currently // restricted by rusoto here. https://github.com/rusoto/rusoto/issues/481 Ok(Box::new(Cursor::new(out.body.unwrap_or_else(|| vec![])))) } }
{ if_chain! { if let Some(ref access_key) = self.access_key; if let Some(ref secret_key) = self.secret_key; then { Ok(AwsCredentials::new(access_key.to_string(), secret_key.to_string(), None, UTC::now() + Duration::seconds(3600))) } else { self.chain_provider.credentials() } } }
identifier_body
mod.rs
// include/uapi/asm-generic/socket.h // arch/alpha/include/uapi/asm/socket.h // tools/include/uapi/asm-generic/socket.h // arch/mips/include/uapi/asm/socket.h pub const SOL_SOCKET: ::c_int = 1; // Defined in unix/linux_like/mod.rs // pub const SO_DEBUG: ::c_int = 1; pub const SO_REUSEADDR: ::c_int = 2; pub const SO_TYPE: ::c_int = 3; pub const SO_ERROR: ::c_int = 4; pub const SO_DONTROUTE: ::c_int = 5; pub const SO_BROADCAST: ::c_int = 6; pub const SO_SNDBUF: ::c_int = 7; pub const SO_RCVBUF: ::c_int = 8; pub const SO_KEEPALIVE: ::c_int = 9; pub const SO_OOBINLINE: ::c_int = 10; pub const SO_NO_CHECK: ::c_int = 11; pub const SO_PRIORITY: ::c_int = 12; pub const SO_LINGER: ::c_int = 13; pub const SO_BSDCOMPAT: ::c_int = 14; pub const SO_REUSEPORT: ::c_int = 15; pub const SO_PASSCRED: ::c_int = 16; pub const SO_PEERCRED: ::c_int = 17; pub const SO_RCVLOWAT: ::c_int = 18; pub const SO_SNDLOWAT: ::c_int = 19; pub const SO_RCVTIMEO: ::c_int = 20; pub const SO_SNDTIMEO: ::c_int = 21; // pub const SO_RCVTIMEO_OLD: ::c_int = 20;
pub const SO_SECURITY_ENCRYPTION_TRANSPORT: ::c_int = 23; pub const SO_SECURITY_ENCRYPTION_NETWORK: ::c_int = 24; pub const SO_BINDTODEVICE: ::c_int = 25; pub const SO_ATTACH_FILTER: ::c_int = 26; pub const SO_DETACH_FILTER: ::c_int = 27; pub const SO_GET_FILTER: ::c_int = SO_ATTACH_FILTER; pub const SO_PEERNAME: ::c_int = 28; pub const SO_TIMESTAMP: ::c_int = 29; // pub const SO_TIMESTAMP_OLD: ::c_int = 29; pub const SO_ACCEPTCONN: ::c_int = 30; pub const SO_PEERSEC: ::c_int = 31; pub const SO_SNDBUFFORCE: ::c_int = 32; pub const SO_RCVBUFFORCE: ::c_int = 33; pub const SO_PASSSEC: ::c_int = 34; pub const SO_TIMESTAMPNS: ::c_int = 35; // pub const SO_TIMESTAMPNS_OLD: ::c_int = 35; pub const SO_MARK: ::c_int = 36; pub const SO_TIMESTAMPING: ::c_int = 37; // pub const SO_TIMESTAMPING_OLD: ::c_int = 37; pub const SO_PROTOCOL: ::c_int = 38; pub const SO_DOMAIN: ::c_int = 39; pub const SO_RXQ_OVFL: ::c_int = 40; pub const SO_WIFI_STATUS: ::c_int = 41; pub const SCM_WIFI_STATUS: ::c_int = SO_WIFI_STATUS; pub const SO_PEEK_OFF: ::c_int = 42; pub const SO_NOFCS: ::c_int = 43; pub const SO_LOCK_FILTER: ::c_int = 44; pub const SO_SELECT_ERR_QUEUE: ::c_int = 45; pub const SO_BUSY_POLL: ::c_int = 46; pub const SO_MAX_PACING_RATE: ::c_int = 47; pub const SO_BPF_EXTENSIONS: ::c_int = 48; pub const SO_INCOMING_CPU: ::c_int = 49; pub const SO_ATTACH_BPF: ::c_int = 50; pub const SO_DETACH_BPF: ::c_int = SO_DETACH_FILTER; pub const SO_ATTACH_REUSEPORT_CBPF: ::c_int = 51; pub const SO_ATTACH_REUSEPORT_EBPF: ::c_int = 52; pub const SO_CNX_ADVICE: ::c_int = 53; pub const SCM_TIMESTAMPING_OPT_STATS: ::c_int = 54; pub const SO_MEMINFO: ::c_int = 55; pub const SO_INCOMING_NAPI_ID: ::c_int = 56; pub const SO_COOKIE: ::c_int = 57; pub const SCM_TIMESTAMPING_PKTINFO: ::c_int = 58; pub const SO_PEERGROUPS: ::c_int = 59; pub const SO_ZEROCOPY: ::c_int = 60; pub const SO_TXTIME: ::c_int = 61; pub const SCM_TXTIME: ::c_int = SO_TXTIME; pub const SO_BINDTOIFINDEX: ::c_int = 62; cfg_if! { // Some of these platforms in CI already have these constants. // But they may still not have those _OLD ones. if #[cfg(all(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64"), not(target_env = "musl")))] { pub const SO_TIMESTAMP_NEW: ::c_int = 63; pub const SO_TIMESTAMPNS_NEW: ::c_int = 64; pub const SO_TIMESTAMPING_NEW: ::c_int = 65; pub const SO_RCVTIMEO_NEW: ::c_int = 66; pub const SO_SNDTIMEO_NEW: ::c_int = 67; pub const SO_DETACH_REUSEPORT_BPF: ::c_int = 68; } } // pub const SO_PREFER_BUSY_POLL: ::c_int = 69; // pub const SO_BUSY_POLL_BUDGET: ::c_int = 70; // Defined in unix/linux_like/mod.rs // pub const SCM_TIMESTAMP: ::c_int = SO_TIMESTAMP; pub const SCM_TIMESTAMPNS: ::c_int = SO_TIMESTAMPNS; pub const SCM_TIMESTAMPING: ::c_int = SO_TIMESTAMPING;
// pub const SO_SNDTIMEO_OLD: ::c_int = 21; pub const SO_SECURITY_AUTHENTICATION: ::c_int = 22;
random_line_split
tests.rs
// Copyright (c) 2016-2021 Snowplow Analytics Ltd. All rights reserved. // // This program is licensed to you under the Apache License Version 2.0, and // you may not use this file except in compliance with the Apache License // Version 2.0. You may obtain a copy of the Apache License Version 2.0 at // http://www.apache.org/licenses/LICENSE-2.0. // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License Version 2.0 is distributed on an "AS // IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the Apache License Version 2.0 for the specific language // governing permissions and limitations there under. // use factotum::factfile::*; use daggy::*; use factotum::tests::*; #[test] fn recursive_find_ok() { let mut dag = Dag::<Task, ()>::new(); let parent = make_task("root", &vec![]); let idx = dag.add_node(parent); let task_child1 = make_task("child1", &vec![]); dag.add_child(idx, (), task_child1); let task_child2 = make_task("child2", &vec![]); let (_, child2) = dag.add_child(idx, (), task_child2); let grandchild_node = make_task("grandchild", &vec![]); let (_, grandchild_idx) = dag.add_child(child2, (), grandchild_node); if let Some((found_idx, found_node)) = super::find_task_recursive(&dag, "grandchild", idx) { assert_eq!(found_idx, grandchild_idx); assert_eq!(found_node.name, "grandchild"); } else { panic!("couldn't find value"); } } #[test] fn get_tasks_in_order_basic() { let mut dag = Dag::<Task, ()>::new(); let parent = make_task("root", &vec![]); let root_idx: NodeIndex = dag.add_node(parent); let child1 = make_task("child1", &vec![]); let child2 = make_task("child2", &vec![]); dag.add_child(root_idx, (), child1); let (_, child2_idx) = dag.add_child(root_idx, (), child2); let grandchild = make_task("grandchild", &vec![]); dag.add_child(child2_idx, (), grandchild); let expected = vec![vec!["root"], vec!["child2", "child1"], vec!["grandchild"]]; let mut actual: Vec<Vec<&Task>> = vec![]; super::get_tasks_in_order(&dag, &vec![root_idx], &mut actual); compare_tasks(expected, actual); } #[test] fn check_valid_subtree() { // root <-- start here // / \ // child1 child2 // \ // grandchild // let mut dag = Dag::<Task, ()>::new(); let parent = make_task("root", &vec![]); let root_idx: NodeIndex = dag.add_node(parent); let child1 = make_task("child1", &vec![]); let child2 = make_task("child2", &vec![]); dag.add_child(root_idx, (), child1); let (_, child2_idx) = dag.add_child(root_idx, (), child2); let grandchild = make_task("grandchild", &vec![]); dag.add_child(child2_idx, (), grandchild); assert_eq!(true, super::is_proper_sub_tree(&dag, root_idx)); } #[test] fn check_invalid_subtree() { // root <-- start here ok // / \ // child1 child2 <-- start here fails // \ \ // grandchild // // let mut dag = Dag::<Task, ()>::new(); let parent = make_task("root", &vec![]); let root_idx: NodeIndex = dag.add_node(parent); let child1 = make_task("child1", &vec![]); let child2 = make_task("child2", &vec![]); let (_, child1_idx) = dag.add_child(root_idx, (), child1); let (_, child2_idx) = dag.add_child(root_idx, (), child2); let grandchild = make_task("grandchild", &vec![]); let (_, grandchild_idx) = dag.add_child(child2_idx, (), grandchild);
assert_eq!(false, super::is_proper_sub_tree(&dag, child2_idx)); assert_eq!(true, super::is_proper_sub_tree(&dag, root_idx)); }
dag.add_edge(child1_idx, grandchild_idx, ()).ok().unwrap();
random_line_split
tests.rs
// Copyright (c) 2016-2021 Snowplow Analytics Ltd. All rights reserved. // // This program is licensed to you under the Apache License Version 2.0, and // you may not use this file except in compliance with the Apache License // Version 2.0. You may obtain a copy of the Apache License Version 2.0 at // http://www.apache.org/licenses/LICENSE-2.0. // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License Version 2.0 is distributed on an "AS // IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the Apache License Version 2.0 for the specific language // governing permissions and limitations there under. // use factotum::factfile::*; use daggy::*; use factotum::tests::*; #[test] fn
() { let mut dag = Dag::<Task, ()>::new(); let parent = make_task("root", &vec![]); let idx = dag.add_node(parent); let task_child1 = make_task("child1", &vec![]); dag.add_child(idx, (), task_child1); let task_child2 = make_task("child2", &vec![]); let (_, child2) = dag.add_child(idx, (), task_child2); let grandchild_node = make_task("grandchild", &vec![]); let (_, grandchild_idx) = dag.add_child(child2, (), grandchild_node); if let Some((found_idx, found_node)) = super::find_task_recursive(&dag, "grandchild", idx) { assert_eq!(found_idx, grandchild_idx); assert_eq!(found_node.name, "grandchild"); } else { panic!("couldn't find value"); } } #[test] fn get_tasks_in_order_basic() { let mut dag = Dag::<Task, ()>::new(); let parent = make_task("root", &vec![]); let root_idx: NodeIndex = dag.add_node(parent); let child1 = make_task("child1", &vec![]); let child2 = make_task("child2", &vec![]); dag.add_child(root_idx, (), child1); let (_, child2_idx) = dag.add_child(root_idx, (), child2); let grandchild = make_task("grandchild", &vec![]); dag.add_child(child2_idx, (), grandchild); let expected = vec![vec!["root"], vec!["child2", "child1"], vec!["grandchild"]]; let mut actual: Vec<Vec<&Task>> = vec![]; super::get_tasks_in_order(&dag, &vec![root_idx], &mut actual); compare_tasks(expected, actual); } #[test] fn check_valid_subtree() { // root <-- start here // / \ // child1 child2 // \ // grandchild // let mut dag = Dag::<Task, ()>::new(); let parent = make_task("root", &vec![]); let root_idx: NodeIndex = dag.add_node(parent); let child1 = make_task("child1", &vec![]); let child2 = make_task("child2", &vec![]); dag.add_child(root_idx, (), child1); let (_, child2_idx) = dag.add_child(root_idx, (), child2); let grandchild = make_task("grandchild", &vec![]); dag.add_child(child2_idx, (), grandchild); assert_eq!(true, super::is_proper_sub_tree(&dag, root_idx)); } #[test] fn check_invalid_subtree() { // root <-- start here ok // / \ // child1 child2 <-- start here fails // \ \ // grandchild // // let mut dag = Dag::<Task, ()>::new(); let parent = make_task("root", &vec![]); let root_idx: NodeIndex = dag.add_node(parent); let child1 = make_task("child1", &vec![]); let child2 = make_task("child2", &vec![]); let (_, child1_idx) = dag.add_child(root_idx, (), child1); let (_, child2_idx) = dag.add_child(root_idx, (), child2); let grandchild = make_task("grandchild", &vec![]); let (_, grandchild_idx) = dag.add_child(child2_idx, (), grandchild); dag.add_edge(child1_idx, grandchild_idx, ()).ok().unwrap(); assert_eq!(false, super::is_proper_sub_tree(&dag, child2_idx)); assert_eq!(true, super::is_proper_sub_tree(&dag, root_idx)); }
recursive_find_ok
identifier_name
tests.rs
// Copyright (c) 2016-2021 Snowplow Analytics Ltd. All rights reserved. // // This program is licensed to you under the Apache License Version 2.0, and // you may not use this file except in compliance with the Apache License // Version 2.0. You may obtain a copy of the Apache License Version 2.0 at // http://www.apache.org/licenses/LICENSE-2.0. // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License Version 2.0 is distributed on an "AS // IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the Apache License Version 2.0 for the specific language // governing permissions and limitations there under. // use factotum::factfile::*; use daggy::*; use factotum::tests::*; #[test] fn recursive_find_ok() { let mut dag = Dag::<Task, ()>::new(); let parent = make_task("root", &vec![]); let idx = dag.add_node(parent); let task_child1 = make_task("child1", &vec![]); dag.add_child(idx, (), task_child1); let task_child2 = make_task("child2", &vec![]); let (_, child2) = dag.add_child(idx, (), task_child2); let grandchild_node = make_task("grandchild", &vec![]); let (_, grandchild_idx) = dag.add_child(child2, (), grandchild_node); if let Some((found_idx, found_node)) = super::find_task_recursive(&dag, "grandchild", idx) { assert_eq!(found_idx, grandchild_idx); assert_eq!(found_node.name, "grandchild"); } else
} #[test] fn get_tasks_in_order_basic() { let mut dag = Dag::<Task, ()>::new(); let parent = make_task("root", &vec![]); let root_idx: NodeIndex = dag.add_node(parent); let child1 = make_task("child1", &vec![]); let child2 = make_task("child2", &vec![]); dag.add_child(root_idx, (), child1); let (_, child2_idx) = dag.add_child(root_idx, (), child2); let grandchild = make_task("grandchild", &vec![]); dag.add_child(child2_idx, (), grandchild); let expected = vec![vec!["root"], vec!["child2", "child1"], vec!["grandchild"]]; let mut actual: Vec<Vec<&Task>> = vec![]; super::get_tasks_in_order(&dag, &vec![root_idx], &mut actual); compare_tasks(expected, actual); } #[test] fn check_valid_subtree() { // root <-- start here // / \ // child1 child2 // \ // grandchild // let mut dag = Dag::<Task, ()>::new(); let parent = make_task("root", &vec![]); let root_idx: NodeIndex = dag.add_node(parent); let child1 = make_task("child1", &vec![]); let child2 = make_task("child2", &vec![]); dag.add_child(root_idx, (), child1); let (_, child2_idx) = dag.add_child(root_idx, (), child2); let grandchild = make_task("grandchild", &vec![]); dag.add_child(child2_idx, (), grandchild); assert_eq!(true, super::is_proper_sub_tree(&dag, root_idx)); } #[test] fn check_invalid_subtree() { // root <-- start here ok // / \ // child1 child2 <-- start here fails // \ \ // grandchild // // let mut dag = Dag::<Task, ()>::new(); let parent = make_task("root", &vec![]); let root_idx: NodeIndex = dag.add_node(parent); let child1 = make_task("child1", &vec![]); let child2 = make_task("child2", &vec![]); let (_, child1_idx) = dag.add_child(root_idx, (), child1); let (_, child2_idx) = dag.add_child(root_idx, (), child2); let grandchild = make_task("grandchild", &vec![]); let (_, grandchild_idx) = dag.add_child(child2_idx, (), grandchild); dag.add_edge(child1_idx, grandchild_idx, ()).ok().unwrap(); assert_eq!(false, super::is_proper_sub_tree(&dag, child2_idx)); assert_eq!(true, super::is_proper_sub_tree(&dag, root_idx)); }
{ panic!("couldn't find value"); }
conditional_block
tests.rs
// Copyright (c) 2016-2021 Snowplow Analytics Ltd. All rights reserved. // // This program is licensed to you under the Apache License Version 2.0, and // you may not use this file except in compliance with the Apache License // Version 2.0. You may obtain a copy of the Apache License Version 2.0 at // http://www.apache.org/licenses/LICENSE-2.0. // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License Version 2.0 is distributed on an "AS // IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the Apache License Version 2.0 for the specific language // governing permissions and limitations there under. // use factotum::factfile::*; use daggy::*; use factotum::tests::*; #[test] fn recursive_find_ok() { let mut dag = Dag::<Task, ()>::new(); let parent = make_task("root", &vec![]); let idx = dag.add_node(parent); let task_child1 = make_task("child1", &vec![]); dag.add_child(idx, (), task_child1); let task_child2 = make_task("child2", &vec![]); let (_, child2) = dag.add_child(idx, (), task_child2); let grandchild_node = make_task("grandchild", &vec![]); let (_, grandchild_idx) = dag.add_child(child2, (), grandchild_node); if let Some((found_idx, found_node)) = super::find_task_recursive(&dag, "grandchild", idx) { assert_eq!(found_idx, grandchild_idx); assert_eq!(found_node.name, "grandchild"); } else { panic!("couldn't find value"); } } #[test] fn get_tasks_in_order_basic()
super::get_tasks_in_order(&dag, &vec![root_idx], &mut actual); compare_tasks(expected, actual); } #[test] fn check_valid_subtree() { // root <-- start here // / \ // child1 child2 // \ // grandchild // let mut dag = Dag::<Task, ()>::new(); let parent = make_task("root", &vec![]); let root_idx: NodeIndex = dag.add_node(parent); let child1 = make_task("child1", &vec![]); let child2 = make_task("child2", &vec![]); dag.add_child(root_idx, (), child1); let (_, child2_idx) = dag.add_child(root_idx, (), child2); let grandchild = make_task("grandchild", &vec![]); dag.add_child(child2_idx, (), grandchild); assert_eq!(true, super::is_proper_sub_tree(&dag, root_idx)); } #[test] fn check_invalid_subtree() { // root <-- start here ok // / \ // child1 child2 <-- start here fails // \ \ // grandchild // // let mut dag = Dag::<Task, ()>::new(); let parent = make_task("root", &vec![]); let root_idx: NodeIndex = dag.add_node(parent); let child1 = make_task("child1", &vec![]); let child2 = make_task("child2", &vec![]); let (_, child1_idx) = dag.add_child(root_idx, (), child1); let (_, child2_idx) = dag.add_child(root_idx, (), child2); let grandchild = make_task("grandchild", &vec![]); let (_, grandchild_idx) = dag.add_child(child2_idx, (), grandchild); dag.add_edge(child1_idx, grandchild_idx, ()).ok().unwrap(); assert_eq!(false, super::is_proper_sub_tree(&dag, child2_idx)); assert_eq!(true, super::is_proper_sub_tree(&dag, root_idx)); }
{ let mut dag = Dag::<Task, ()>::new(); let parent = make_task("root", &vec![]); let root_idx: NodeIndex = dag.add_node(parent); let child1 = make_task("child1", &vec![]); let child2 = make_task("child2", &vec![]); dag.add_child(root_idx, (), child1); let (_, child2_idx) = dag.add_child(root_idx, (), child2); let grandchild = make_task("grandchild", &vec![]); dag.add_child(child2_idx, (), grandchild); let expected = vec![vec!["root"], vec!["child2", "child1"], vec!["grandchild"]]; let mut actual: Vec<Vec<&Task>> = vec![];
identifier_body
graph500-bfs.rs
// xfail-pretty // 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. #[legacy_modes]; #[allow(deprecated_mode)]; /*! An implementation of the Graph500 Breadth First Search problem in Rust. */ extern mod std; use std::arc; use std::time; use std::deque::Deque; use std::par; use core::hashmap::linear::{LinearMap, LinearSet}; use core::io::WriterUtil; use core::int::abs; use core::rand::RngUtil; type node_id = i64; type graph = ~[~[node_id]]; type bfs_result = ~[node_id]; fn make_edges(scale: uint, edgefactor: uint) -> ~[(node_id, node_id)] { let r = rand::xorshift(); fn choose_edge(i: node_id, j: node_id, scale: uint, r: @rand::Rng) -> (node_id, node_id) { let A = 0.57; let B = 0.19; let C = 0.19; if scale == 0u { (i, j) } else { let i = i * 2i64; let j = j * 2i64; let scale = scale - 1u; let x = r.gen_float(); if x < A { choose_edge(i, j, scale, r) } else { let x = x - A; if x < B { choose_edge(i + 1i64, j, scale, r) } else { let x = x - B; if x < C { choose_edge(i, j + 1i64, scale, r) } else { choose_edge(i + 1i64, j + 1i64, scale, r) } } } } } do vec::from_fn((1u << scale) * edgefactor) |_i| { choose_edge(0i64, 0i64, scale, r) } } fn make_graph(N: uint, edges: ~[(node_id, node_id)]) -> graph { let mut graph = do vec::from_fn(N) |_i| { LinearSet::new() }; do vec::each(edges) |e| { match *e { (i, j) => { graph[i].insert(j); graph[j].insert(i); } } true } do vec::map_consume(graph) |mut v| { let mut vec = ~[]; do v.consume |i| { vec.push(i); } vec } } fn gen_search_keys(graph: &[~[node_id]], n: uint) -> ~[node_id] { let mut keys = LinearSet::new(); let r = rand::Rng(); while keys.len() < n { let k = r.gen_uint_range(0u, graph.len()); if graph[k].len() > 0u && vec::any(graph[k], |i| { *i!= k as node_id }) { keys.insert(k as node_id); } } let mut vec = ~[]; do keys.consume |i| { vec.push(i); } return vec; } /** * Returns a vector of all the parents in the BFS tree rooted at key. * * Nodes that are unreachable have a parent of -1. */ fn bfs(graph: graph, key: node_id) -> bfs_result { let mut marks : ~[node_id] = vec::from_elem(vec::len(graph), -1i64); let mut q = Deque::new(); q.add_back(key); marks[key] = key; while!q.is_empty() { let t = q.pop_front(); do graph[t].each() |k| { if marks[*k] == -1i64 { marks[*k] = t; q.add_back(*k); } true }; } marks } /** * Another version of the bfs function. * * This one uses the same algorithm as the parallel one, just without * using the parallel vector operators. */ fn bfs2(graph: graph, key: node_id) -> bfs_result { // This works by doing functional updates of a color vector. enum color { white, // node_id marks which node turned this gray/black. // the node id later becomes the parent. gray(node_id), black(node_id) }; let mut colors = do vec::from_fn(graph.len()) |i| { if i as node_id == key { gray(key) } else { white } }; fn is_gray(c: &color) -> bool { match *c { gray(_) => { true } _ => { false } } } let mut i = 0; while vec::any(colors, is_gray) { // Do the BFS. info!("PBFS iteration %?", i); i += 1; colors = do colors.mapi() |i, c| { let c : color = *c; match c { white => { let i = i as node_id; let neighbors = copy graph[i]; let mut color = white;
do neighbors.each() |k| { if is_gray(&colors[*k]) { color = gray(*k); false } else { true } }; color } gray(parent) => { black(parent) } black(parent) => { black(parent) } } } } // Convert the results. do vec::map(colors) |c| { match *c { white => { -1i64 } black(parent) => { parent } _ => { fail!(~"Found remaining gray nodes in BFS") } } } } /// A parallel version of the bfs function. fn pbfs(&&graph: arc::ARC<graph>, key: node_id) -> bfs_result { // This works by doing functional updates of a color vector. enum color { white, // node_id marks which node turned this gray/black. // the node id later becomes the parent. gray(node_id), black(node_id) }; let graph_vec = arc::get(&graph); // FIXME #3387 requires this temp let mut colors = do vec::from_fn(graph_vec.len()) |i| { if i as node_id == key { gray(key) } else { white } }; #[inline(always)] fn is_gray(c: &color) -> bool { match *c { gray(_) => { true } _ => { false } } } fn is_gray_factory() -> ~fn(c: &color) -> bool { let r: ~fn(c: &color) -> bool = is_gray; r } let mut i = 0; while par::any(colors, is_gray_factory) { // Do the BFS. info!("PBFS iteration %?", i); i += 1; let old_len = colors.len(); let color = arc::ARC(colors); let color_vec = arc::get(&color); // FIXME #3387 requires this temp colors = do par::mapi(*color_vec) { let colors = arc::clone(&color); let graph = arc::clone(&graph); let result: ~fn(+x: uint, +y: &color) -> color = |i, c| { let colors = arc::get(&colors); let graph = arc::get(&graph); match *c { white => { let i = i as node_id; let neighbors = copy graph[i]; let mut color = white; do neighbors.each() |k| { if is_gray(&colors[*k]) { color = gray(*k); false } else { true } }; color } gray(parent) => { black(parent) } black(parent) => { black(parent) } } }; result }; assert!((colors.len() == old_len)); } // Convert the results. do par::map(colors) { let result: ~fn(c: &color) -> i64 = |c| { match *c { white => { -1i64 } black(parent) => { parent } _ => { fail!(~"Found remaining gray nodes in BFS") } } }; result } } /// Performs at least some of the validation in the Graph500 spec. fn validate(edges: ~[(node_id, node_id)], root: node_id, tree: bfs_result) -> bool { // There are 5 things to test. Below is code for each of them. // 1. The BFS tree is a tree and does not contain cycles. // // We do this by iterating over the tree, and tracing each of the // parent chains back to the root. While we do this, we also // compute the levels for each node. info!(~"Verifying tree structure..."); let mut status = true; let level = do tree.map() |parent| { let mut parent = *parent; let mut path = ~[]; if parent == -1i64 { // This node was not in the tree. -1 } else { while parent!= root { if vec::contains(path, &parent) { status = false; } path.push(parent); parent = tree[parent]; } // The length of the path back to the root is the current // level. path.len() as int } }; if!status { return status } // 2. Each tree edge connects vertices whose BFS levels differ by // exactly one. info!(~"Verifying tree edges..."); let status = do tree.alli() |k, parent| { if *parent!= root && *parent!= -1i64 { level[*parent] == level[k] - 1 } else { true } }; if!status { return status } // 3. Every edge in the input list has vertices with levels that // differ by at most one or that both are not in the BFS tree. info!(~"Verifying graph edges..."); let status = do edges.all() |e| { let (u, v) = *e; abs(level[u] - level[v]) <= 1 }; if!status { return status } // 4. The BFS tree spans an entire connected component's vertices. // This is harder. We'll skip it for now... // 5. A node and its parent are joined by an edge of the original // graph. info!(~"Verifying tree and graph edges..."); let status = do par::alli(tree) { let edges = copy edges; let result: ~fn(+x: uint, v: &i64) -> bool = |u, v| { let u = u as node_id; if *v == -1i64 || u == root { true } else { edges.contains(&(u, *v)) || edges.contains(&(*v, u)) } }; result }; if!status { return status } // If we get through here, all the tests passed! true } fn main() { let args = os::args(); let args = if os::getenv(~"RUST_BENCH").is_some() { ~[~"", ~"15", ~"48"] } else if args.len() <= 1 { ~[~"", ~"10", ~"16"] } else { args }; let scale = uint::from_str(args[1]).get(); let num_keys = uint::from_str(args[2]).get(); let do_validate = false; let do_sequential = true; let start = time::precise_time_s(); let edges = make_edges(scale, 16); let stop = time::precise_time_s(); io::stdout().write_line(fmt!("Generated %? edges in %? seconds.", vec::len(edges), stop - start)); let start = time::precise_time_s(); let graph = make_graph(1 << scale, copy edges); let stop = time::precise_time_s(); let mut total_edges = 0; vec::each(graph, |edges| { total_edges += edges.len(); true }); io::stdout().write_line(fmt!("Generated graph with %? edges in %? seconds.", total_edges / 2, stop - start)); let mut total_seq = 0.0; let mut total_par = 0.0; let graph_arc = arc::ARC(copy graph); do gen_search_keys(graph, num_keys).map() |root| { io::stdout().write_line(~""); io::stdout().write_line(fmt!("Search key: %?", root)); if do_sequential { let start = time::precise_time_s(); let bfs_tree = bfs(copy graph, *root); let stop = time::precise_time_s(); //total_seq += stop - start; io::stdout().write_line( fmt!("Sequential BFS completed in %? seconds.", stop - start)); if do_validate { let start = time::precise_time_s(); assert!((validate(copy edges, *root, bfs_tree))); let stop = time::precise_time_s(); io::stdout().write_line( fmt!("Validation completed in %? seconds.", stop - start)); } let start = time::precise_time_s(); let bfs_tree = bfs2(copy graph, *root); let stop = time::precise_time_s(); total_seq += stop - start; io::stdout().write_line( fmt!("Alternate Sequential BFS completed in %? seconds.", stop - start)); if do_validate { let start = time::precise_time_s(); assert!((validate(copy edges, *root, bfs_tree))); let stop = time::precise_time_s(); io::stdout().write_line( fmt!("Validation completed in %? seconds.", stop - start)); } } let start = time::precise_time_s(); let bfs_tree = pbfs(graph_arc, *root); let stop = time::precise_time_s(); total_par += stop - start; io::stdout().write_line(fmt!("Parallel BFS completed in %? seconds.", stop - start)); if do_validate { let start = time::precise_time_s(); assert!((validate(copy edges, *root, bfs_tree))); let stop = time::precise_time_s(); io::stdout().write_line(fmt!("Validation completed in %? seconds.", stop - start)); } }; io::stdout().write_line(~""); io::stdout().write_line( fmt!("Total sequential: %? \t Total Parallel: %? \t Speedup: %?x", total_seq, total_par, total_seq / total_par)); }
random_line_split
graph500-bfs.rs
// xfail-pretty // 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. #[legacy_modes]; #[allow(deprecated_mode)]; /*! An implementation of the Graph500 Breadth First Search problem in Rust. */ extern mod std; use std::arc; use std::time; use std::deque::Deque; use std::par; use core::hashmap::linear::{LinearMap, LinearSet}; use core::io::WriterUtil; use core::int::abs; use core::rand::RngUtil; type node_id = i64; type graph = ~[~[node_id]]; type bfs_result = ~[node_id]; fn make_edges(scale: uint, edgefactor: uint) -> ~[(node_id, node_id)] { let r = rand::xorshift(); fn
(i: node_id, j: node_id, scale: uint, r: @rand::Rng) -> (node_id, node_id) { let A = 0.57; let B = 0.19; let C = 0.19; if scale == 0u { (i, j) } else { let i = i * 2i64; let j = j * 2i64; let scale = scale - 1u; let x = r.gen_float(); if x < A { choose_edge(i, j, scale, r) } else { let x = x - A; if x < B { choose_edge(i + 1i64, j, scale, r) } else { let x = x - B; if x < C { choose_edge(i, j + 1i64, scale, r) } else { choose_edge(i + 1i64, j + 1i64, scale, r) } } } } } do vec::from_fn((1u << scale) * edgefactor) |_i| { choose_edge(0i64, 0i64, scale, r) } } fn make_graph(N: uint, edges: ~[(node_id, node_id)]) -> graph { let mut graph = do vec::from_fn(N) |_i| { LinearSet::new() }; do vec::each(edges) |e| { match *e { (i, j) => { graph[i].insert(j); graph[j].insert(i); } } true } do vec::map_consume(graph) |mut v| { let mut vec = ~[]; do v.consume |i| { vec.push(i); } vec } } fn gen_search_keys(graph: &[~[node_id]], n: uint) -> ~[node_id] { let mut keys = LinearSet::new(); let r = rand::Rng(); while keys.len() < n { let k = r.gen_uint_range(0u, graph.len()); if graph[k].len() > 0u && vec::any(graph[k], |i| { *i!= k as node_id }) { keys.insert(k as node_id); } } let mut vec = ~[]; do keys.consume |i| { vec.push(i); } return vec; } /** * Returns a vector of all the parents in the BFS tree rooted at key. * * Nodes that are unreachable have a parent of -1. */ fn bfs(graph: graph, key: node_id) -> bfs_result { let mut marks : ~[node_id] = vec::from_elem(vec::len(graph), -1i64); let mut q = Deque::new(); q.add_back(key); marks[key] = key; while!q.is_empty() { let t = q.pop_front(); do graph[t].each() |k| { if marks[*k] == -1i64 { marks[*k] = t; q.add_back(*k); } true }; } marks } /** * Another version of the bfs function. * * This one uses the same algorithm as the parallel one, just without * using the parallel vector operators. */ fn bfs2(graph: graph, key: node_id) -> bfs_result { // This works by doing functional updates of a color vector. enum color { white, // node_id marks which node turned this gray/black. // the node id later becomes the parent. gray(node_id), black(node_id) }; let mut colors = do vec::from_fn(graph.len()) |i| { if i as node_id == key { gray(key) } else { white } }; fn is_gray(c: &color) -> bool { match *c { gray(_) => { true } _ => { false } } } let mut i = 0; while vec::any(colors, is_gray) { // Do the BFS. info!("PBFS iteration %?", i); i += 1; colors = do colors.mapi() |i, c| { let c : color = *c; match c { white => { let i = i as node_id; let neighbors = copy graph[i]; let mut color = white; do neighbors.each() |k| { if is_gray(&colors[*k]) { color = gray(*k); false } else { true } }; color } gray(parent) => { black(parent) } black(parent) => { black(parent) } } } } // Convert the results. do vec::map(colors) |c| { match *c { white => { -1i64 } black(parent) => { parent } _ => { fail!(~"Found remaining gray nodes in BFS") } } } } /// A parallel version of the bfs function. fn pbfs(&&graph: arc::ARC<graph>, key: node_id) -> bfs_result { // This works by doing functional updates of a color vector. enum color { white, // node_id marks which node turned this gray/black. // the node id later becomes the parent. gray(node_id), black(node_id) }; let graph_vec = arc::get(&graph); // FIXME #3387 requires this temp let mut colors = do vec::from_fn(graph_vec.len()) |i| { if i as node_id == key { gray(key) } else { white } }; #[inline(always)] fn is_gray(c: &color) -> bool { match *c { gray(_) => { true } _ => { false } } } fn is_gray_factory() -> ~fn(c: &color) -> bool { let r: ~fn(c: &color) -> bool = is_gray; r } let mut i = 0; while par::any(colors, is_gray_factory) { // Do the BFS. info!("PBFS iteration %?", i); i += 1; let old_len = colors.len(); let color = arc::ARC(colors); let color_vec = arc::get(&color); // FIXME #3387 requires this temp colors = do par::mapi(*color_vec) { let colors = arc::clone(&color); let graph = arc::clone(&graph); let result: ~fn(+x: uint, +y: &color) -> color = |i, c| { let colors = arc::get(&colors); let graph = arc::get(&graph); match *c { white => { let i = i as node_id; let neighbors = copy graph[i]; let mut color = white; do neighbors.each() |k| { if is_gray(&colors[*k]) { color = gray(*k); false } else { true } }; color } gray(parent) => { black(parent) } black(parent) => { black(parent) } } }; result }; assert!((colors.len() == old_len)); } // Convert the results. do par::map(colors) { let result: ~fn(c: &color) -> i64 = |c| { match *c { white => { -1i64 } black(parent) => { parent } _ => { fail!(~"Found remaining gray nodes in BFS") } } }; result } } /// Performs at least some of the validation in the Graph500 spec. fn validate(edges: ~[(node_id, node_id)], root: node_id, tree: bfs_result) -> bool { // There are 5 things to test. Below is code for each of them. // 1. The BFS tree is a tree and does not contain cycles. // // We do this by iterating over the tree, and tracing each of the // parent chains back to the root. While we do this, we also // compute the levels for each node. info!(~"Verifying tree structure..."); let mut status = true; let level = do tree.map() |parent| { let mut parent = *parent; let mut path = ~[]; if parent == -1i64 { // This node was not in the tree. -1 } else { while parent!= root { if vec::contains(path, &parent) { status = false; } path.push(parent); parent = tree[parent]; } // The length of the path back to the root is the current // level. path.len() as int } }; if!status { return status } // 2. Each tree edge connects vertices whose BFS levels differ by // exactly one. info!(~"Verifying tree edges..."); let status = do tree.alli() |k, parent| { if *parent!= root && *parent!= -1i64 { level[*parent] == level[k] - 1 } else { true } }; if!status { return status } // 3. Every edge in the input list has vertices with levels that // differ by at most one or that both are not in the BFS tree. info!(~"Verifying graph edges..."); let status = do edges.all() |e| { let (u, v) = *e; abs(level[u] - level[v]) <= 1 }; if!status { return status } // 4. The BFS tree spans an entire connected component's vertices. // This is harder. We'll skip it for now... // 5. A node and its parent are joined by an edge of the original // graph. info!(~"Verifying tree and graph edges..."); let status = do par::alli(tree) { let edges = copy edges; let result: ~fn(+x: uint, v: &i64) -> bool = |u, v| { let u = u as node_id; if *v == -1i64 || u == root { true } else { edges.contains(&(u, *v)) || edges.contains(&(*v, u)) } }; result }; if!status { return status } // If we get through here, all the tests passed! true } fn main() { let args = os::args(); let args = if os::getenv(~"RUST_BENCH").is_some() { ~[~"", ~"15", ~"48"] } else if args.len() <= 1 { ~[~"", ~"10", ~"16"] } else { args }; let scale = uint::from_str(args[1]).get(); let num_keys = uint::from_str(args[2]).get(); let do_validate = false; let do_sequential = true; let start = time::precise_time_s(); let edges = make_edges(scale, 16); let stop = time::precise_time_s(); io::stdout().write_line(fmt!("Generated %? edges in %? seconds.", vec::len(edges), stop - start)); let start = time::precise_time_s(); let graph = make_graph(1 << scale, copy edges); let stop = time::precise_time_s(); let mut total_edges = 0; vec::each(graph, |edges| { total_edges += edges.len(); true }); io::stdout().write_line(fmt!("Generated graph with %? edges in %? seconds.", total_edges / 2, stop - start)); let mut total_seq = 0.0; let mut total_par = 0.0; let graph_arc = arc::ARC(copy graph); do gen_search_keys(graph, num_keys).map() |root| { io::stdout().write_line(~""); io::stdout().write_line(fmt!("Search key: %?", root)); if do_sequential { let start = time::precise_time_s(); let bfs_tree = bfs(copy graph, *root); let stop = time::precise_time_s(); //total_seq += stop - start; io::stdout().write_line( fmt!("Sequential BFS completed in %? seconds.", stop - start)); if do_validate { let start = time::precise_time_s(); assert!((validate(copy edges, *root, bfs_tree))); let stop = time::precise_time_s(); io::stdout().write_line( fmt!("Validation completed in %? seconds.", stop - start)); } let start = time::precise_time_s(); let bfs_tree = bfs2(copy graph, *root); let stop = time::precise_time_s(); total_seq += stop - start; io::stdout().write_line( fmt!("Alternate Sequential BFS completed in %? seconds.", stop - start)); if do_validate { let start = time::precise_time_s(); assert!((validate(copy edges, *root, bfs_tree))); let stop = time::precise_time_s(); io::stdout().write_line( fmt!("Validation completed in %? seconds.", stop - start)); } } let start = time::precise_time_s(); let bfs_tree = pbfs(graph_arc, *root); let stop = time::precise_time_s(); total_par += stop - start; io::stdout().write_line(fmt!("Parallel BFS completed in %? seconds.", stop - start)); if do_validate { let start = time::precise_time_s(); assert!((validate(copy edges, *root, bfs_tree))); let stop = time::precise_time_s(); io::stdout().write_line(fmt!("Validation completed in %? seconds.", stop - start)); } }; io::stdout().write_line(~""); io::stdout().write_line( fmt!("Total sequential: %? \t Total Parallel: %? \t Speedup: %?x", total_seq, total_par, total_seq / total_par)); }
choose_edge
identifier_name
graph500-bfs.rs
// xfail-pretty // 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. #[legacy_modes]; #[allow(deprecated_mode)]; /*! An implementation of the Graph500 Breadth First Search problem in Rust. */ extern mod std; use std::arc; use std::time; use std::deque::Deque; use std::par; use core::hashmap::linear::{LinearMap, LinearSet}; use core::io::WriterUtil; use core::int::abs; use core::rand::RngUtil; type node_id = i64; type graph = ~[~[node_id]]; type bfs_result = ~[node_id]; fn make_edges(scale: uint, edgefactor: uint) -> ~[(node_id, node_id)] { let r = rand::xorshift(); fn choose_edge(i: node_id, j: node_id, scale: uint, r: @rand::Rng) -> (node_id, node_id) { let A = 0.57; let B = 0.19; let C = 0.19; if scale == 0u { (i, j) } else { let i = i * 2i64; let j = j * 2i64; let scale = scale - 1u; let x = r.gen_float(); if x < A { choose_edge(i, j, scale, r) } else { let x = x - A; if x < B { choose_edge(i + 1i64, j, scale, r) } else { let x = x - B; if x < C { choose_edge(i, j + 1i64, scale, r) } else { choose_edge(i + 1i64, j + 1i64, scale, r) } } } } } do vec::from_fn((1u << scale) * edgefactor) |_i| { choose_edge(0i64, 0i64, scale, r) } } fn make_graph(N: uint, edges: ~[(node_id, node_id)]) -> graph { let mut graph = do vec::from_fn(N) |_i| { LinearSet::new() }; do vec::each(edges) |e| { match *e { (i, j) => { graph[i].insert(j); graph[j].insert(i); } } true } do vec::map_consume(graph) |mut v| { let mut vec = ~[]; do v.consume |i| { vec.push(i); } vec } } fn gen_search_keys(graph: &[~[node_id]], n: uint) -> ~[node_id] { let mut keys = LinearSet::new(); let r = rand::Rng(); while keys.len() < n { let k = r.gen_uint_range(0u, graph.len()); if graph[k].len() > 0u && vec::any(graph[k], |i| { *i!= k as node_id }) { keys.insert(k as node_id); } } let mut vec = ~[]; do keys.consume |i| { vec.push(i); } return vec; } /** * Returns a vector of all the parents in the BFS tree rooted at key. * * Nodes that are unreachable have a parent of -1. */ fn bfs(graph: graph, key: node_id) -> bfs_result { let mut marks : ~[node_id] = vec::from_elem(vec::len(graph), -1i64); let mut q = Deque::new(); q.add_back(key); marks[key] = key; while!q.is_empty() { let t = q.pop_front(); do graph[t].each() |k| { if marks[*k] == -1i64 { marks[*k] = t; q.add_back(*k); } true }; } marks } /** * Another version of the bfs function. * * This one uses the same algorithm as the parallel one, just without * using the parallel vector operators. */ fn bfs2(graph: graph, key: node_id) -> bfs_result { // This works by doing functional updates of a color vector. enum color { white, // node_id marks which node turned this gray/black. // the node id later becomes the parent. gray(node_id), black(node_id) }; let mut colors = do vec::from_fn(graph.len()) |i| { if i as node_id == key { gray(key) } else { white } }; fn is_gray(c: &color) -> bool { match *c { gray(_) => { true } _ => { false } } } let mut i = 0; while vec::any(colors, is_gray) { // Do the BFS. info!("PBFS iteration %?", i); i += 1; colors = do colors.mapi() |i, c| { let c : color = *c; match c { white => { let i = i as node_id; let neighbors = copy graph[i]; let mut color = white; do neighbors.each() |k| { if is_gray(&colors[*k]) { color = gray(*k); false } else { true } }; color } gray(parent) => { black(parent) } black(parent) => { black(parent) } } } } // Convert the results. do vec::map(colors) |c| { match *c { white => { -1i64 } black(parent) => { parent } _ => { fail!(~"Found remaining gray nodes in BFS") } } } } /// A parallel version of the bfs function. fn pbfs(&&graph: arc::ARC<graph>, key: node_id) -> bfs_result { // This works by doing functional updates of a color vector. enum color { white, // node_id marks which node turned this gray/black. // the node id later becomes the parent. gray(node_id), black(node_id) }; let graph_vec = arc::get(&graph); // FIXME #3387 requires this temp let mut colors = do vec::from_fn(graph_vec.len()) |i| { if i as node_id == key { gray(key) } else { white } }; #[inline(always)] fn is_gray(c: &color) -> bool { match *c { gray(_) => { true } _ => { false } } } fn is_gray_factory() -> ~fn(c: &color) -> bool
let mut i = 0; while par::any(colors, is_gray_factory) { // Do the BFS. info!("PBFS iteration %?", i); i += 1; let old_len = colors.len(); let color = arc::ARC(colors); let color_vec = arc::get(&color); // FIXME #3387 requires this temp colors = do par::mapi(*color_vec) { let colors = arc::clone(&color); let graph = arc::clone(&graph); let result: ~fn(+x: uint, +y: &color) -> color = |i, c| { let colors = arc::get(&colors); let graph = arc::get(&graph); match *c { white => { let i = i as node_id; let neighbors = copy graph[i]; let mut color = white; do neighbors.each() |k| { if is_gray(&colors[*k]) { color = gray(*k); false } else { true } }; color } gray(parent) => { black(parent) } black(parent) => { black(parent) } } }; result }; assert!((colors.len() == old_len)); } // Convert the results. do par::map(colors) { let result: ~fn(c: &color) -> i64 = |c| { match *c { white => { -1i64 } black(parent) => { parent } _ => { fail!(~"Found remaining gray nodes in BFS") } } }; result } } /// Performs at least some of the validation in the Graph500 spec. fn validate(edges: ~[(node_id, node_id)], root: node_id, tree: bfs_result) -> bool { // There are 5 things to test. Below is code for each of them. // 1. The BFS tree is a tree and does not contain cycles. // // We do this by iterating over the tree, and tracing each of the // parent chains back to the root. While we do this, we also // compute the levels for each node. info!(~"Verifying tree structure..."); let mut status = true; let level = do tree.map() |parent| { let mut parent = *parent; let mut path = ~[]; if parent == -1i64 { // This node was not in the tree. -1 } else { while parent!= root { if vec::contains(path, &parent) { status = false; } path.push(parent); parent = tree[parent]; } // The length of the path back to the root is the current // level. path.len() as int } }; if!status { return status } // 2. Each tree edge connects vertices whose BFS levels differ by // exactly one. info!(~"Verifying tree edges..."); let status = do tree.alli() |k, parent| { if *parent!= root && *parent!= -1i64 { level[*parent] == level[k] - 1 } else { true } }; if!status { return status } // 3. Every edge in the input list has vertices with levels that // differ by at most one or that both are not in the BFS tree. info!(~"Verifying graph edges..."); let status = do edges.all() |e| { let (u, v) = *e; abs(level[u] - level[v]) <= 1 }; if!status { return status } // 4. The BFS tree spans an entire connected component's vertices. // This is harder. We'll skip it for now... // 5. A node and its parent are joined by an edge of the original // graph. info!(~"Verifying tree and graph edges..."); let status = do par::alli(tree) { let edges = copy edges; let result: ~fn(+x: uint, v: &i64) -> bool = |u, v| { let u = u as node_id; if *v == -1i64 || u == root { true } else { edges.contains(&(u, *v)) || edges.contains(&(*v, u)) } }; result }; if!status { return status } // If we get through here, all the tests passed! true } fn main() { let args = os::args(); let args = if os::getenv(~"RUST_BENCH").is_some() { ~[~"", ~"15", ~"48"] } else if args.len() <= 1 { ~[~"", ~"10", ~"16"] } else { args }; let scale = uint::from_str(args[1]).get(); let num_keys = uint::from_str(args[2]).get(); let do_validate = false; let do_sequential = true; let start = time::precise_time_s(); let edges = make_edges(scale, 16); let stop = time::precise_time_s(); io::stdout().write_line(fmt!("Generated %? edges in %? seconds.", vec::len(edges), stop - start)); let start = time::precise_time_s(); let graph = make_graph(1 << scale, copy edges); let stop = time::precise_time_s(); let mut total_edges = 0; vec::each(graph, |edges| { total_edges += edges.len(); true }); io::stdout().write_line(fmt!("Generated graph with %? edges in %? seconds.", total_edges / 2, stop - start)); let mut total_seq = 0.0; let mut total_par = 0.0; let graph_arc = arc::ARC(copy graph); do gen_search_keys(graph, num_keys).map() |root| { io::stdout().write_line(~""); io::stdout().write_line(fmt!("Search key: %?", root)); if do_sequential { let start = time::precise_time_s(); let bfs_tree = bfs(copy graph, *root); let stop = time::precise_time_s(); //total_seq += stop - start; io::stdout().write_line( fmt!("Sequential BFS completed in %? seconds.", stop - start)); if do_validate { let start = time::precise_time_s(); assert!((validate(copy edges, *root, bfs_tree))); let stop = time::precise_time_s(); io::stdout().write_line( fmt!("Validation completed in %? seconds.", stop - start)); } let start = time::precise_time_s(); let bfs_tree = bfs2(copy graph, *root); let stop = time::precise_time_s(); total_seq += stop - start; io::stdout().write_line( fmt!("Alternate Sequential BFS completed in %? seconds.", stop - start)); if do_validate { let start = time::precise_time_s(); assert!((validate(copy edges, *root, bfs_tree))); let stop = time::precise_time_s(); io::stdout().write_line( fmt!("Validation completed in %? seconds.", stop - start)); } } let start = time::precise_time_s(); let bfs_tree = pbfs(graph_arc, *root); let stop = time::precise_time_s(); total_par += stop - start; io::stdout().write_line(fmt!("Parallel BFS completed in %? seconds.", stop - start)); if do_validate { let start = time::precise_time_s(); assert!((validate(copy edges, *root, bfs_tree))); let stop = time::precise_time_s(); io::stdout().write_line(fmt!("Validation completed in %? seconds.", stop - start)); } }; io::stdout().write_line(~""); io::stdout().write_line( fmt!("Total sequential: %? \t Total Parallel: %? \t Speedup: %?x", total_seq, total_par, total_seq / total_par)); }
{ let r: ~fn(c: &color) -> bool = is_gray; r }
identifier_body
graph500-bfs.rs
// xfail-pretty // 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. #[legacy_modes]; #[allow(deprecated_mode)]; /*! An implementation of the Graph500 Breadth First Search problem in Rust. */ extern mod std; use std::arc; use std::time; use std::deque::Deque; use std::par; use core::hashmap::linear::{LinearMap, LinearSet}; use core::io::WriterUtil; use core::int::abs; use core::rand::RngUtil; type node_id = i64; type graph = ~[~[node_id]]; type bfs_result = ~[node_id]; fn make_edges(scale: uint, edgefactor: uint) -> ~[(node_id, node_id)] { let r = rand::xorshift(); fn choose_edge(i: node_id, j: node_id, scale: uint, r: @rand::Rng) -> (node_id, node_id) { let A = 0.57; let B = 0.19; let C = 0.19; if scale == 0u { (i, j) } else { let i = i * 2i64; let j = j * 2i64; let scale = scale - 1u; let x = r.gen_float(); if x < A { choose_edge(i, j, scale, r) } else { let x = x - A; if x < B { choose_edge(i + 1i64, j, scale, r) } else { let x = x - B; if x < C { choose_edge(i, j + 1i64, scale, r) } else { choose_edge(i + 1i64, j + 1i64, scale, r) } } } } } do vec::from_fn((1u << scale) * edgefactor) |_i| { choose_edge(0i64, 0i64, scale, r) } } fn make_graph(N: uint, edges: ~[(node_id, node_id)]) -> graph { let mut graph = do vec::from_fn(N) |_i| { LinearSet::new() }; do vec::each(edges) |e| { match *e { (i, j) => { graph[i].insert(j); graph[j].insert(i); } } true } do vec::map_consume(graph) |mut v| { let mut vec = ~[]; do v.consume |i| { vec.push(i); } vec } } fn gen_search_keys(graph: &[~[node_id]], n: uint) -> ~[node_id] { let mut keys = LinearSet::new(); let r = rand::Rng(); while keys.len() < n { let k = r.gen_uint_range(0u, graph.len()); if graph[k].len() > 0u && vec::any(graph[k], |i| { *i!= k as node_id }) { keys.insert(k as node_id); } } let mut vec = ~[]; do keys.consume |i| { vec.push(i); } return vec; } /** * Returns a vector of all the parents in the BFS tree rooted at key. * * Nodes that are unreachable have a parent of -1. */ fn bfs(graph: graph, key: node_id) -> bfs_result { let mut marks : ~[node_id] = vec::from_elem(vec::len(graph), -1i64); let mut q = Deque::new(); q.add_back(key); marks[key] = key; while!q.is_empty() { let t = q.pop_front(); do graph[t].each() |k| { if marks[*k] == -1i64 { marks[*k] = t; q.add_back(*k); } true }; } marks } /** * Another version of the bfs function. * * This one uses the same algorithm as the parallel one, just without * using the parallel vector operators. */ fn bfs2(graph: graph, key: node_id) -> bfs_result { // This works by doing functional updates of a color vector. enum color { white, // node_id marks which node turned this gray/black. // the node id later becomes the parent. gray(node_id), black(node_id) }; let mut colors = do vec::from_fn(graph.len()) |i| { if i as node_id == key { gray(key) } else { white } }; fn is_gray(c: &color) -> bool { match *c { gray(_) => { true } _ => { false } } } let mut i = 0; while vec::any(colors, is_gray) { // Do the BFS. info!("PBFS iteration %?", i); i += 1; colors = do colors.mapi() |i, c| { let c : color = *c; match c { white => { let i = i as node_id; let neighbors = copy graph[i]; let mut color = white; do neighbors.each() |k| { if is_gray(&colors[*k]) { color = gray(*k); false } else { true } }; color } gray(parent) => { black(parent) } black(parent) => { black(parent) } } } } // Convert the results. do vec::map(colors) |c| { match *c { white => { -1i64 } black(parent) => { parent } _ => { fail!(~"Found remaining gray nodes in BFS") } } } } /// A parallel version of the bfs function. fn pbfs(&&graph: arc::ARC<graph>, key: node_id) -> bfs_result { // This works by doing functional updates of a color vector. enum color { white, // node_id marks which node turned this gray/black. // the node id later becomes the parent. gray(node_id), black(node_id) }; let graph_vec = arc::get(&graph); // FIXME #3387 requires this temp let mut colors = do vec::from_fn(graph_vec.len()) |i| { if i as node_id == key { gray(key) } else { white } }; #[inline(always)] fn is_gray(c: &color) -> bool { match *c { gray(_) => { true } _ => { false } } } fn is_gray_factory() -> ~fn(c: &color) -> bool { let r: ~fn(c: &color) -> bool = is_gray; r } let mut i = 0; while par::any(colors, is_gray_factory) { // Do the BFS. info!("PBFS iteration %?", i); i += 1; let old_len = colors.len(); let color = arc::ARC(colors); let color_vec = arc::get(&color); // FIXME #3387 requires this temp colors = do par::mapi(*color_vec) { let colors = arc::clone(&color); let graph = arc::clone(&graph); let result: ~fn(+x: uint, +y: &color) -> color = |i, c| { let colors = arc::get(&colors); let graph = arc::get(&graph); match *c { white => { let i = i as node_id; let neighbors = copy graph[i]; let mut color = white; do neighbors.each() |k| { if is_gray(&colors[*k]) { color = gray(*k); false } else { true } }; color } gray(parent) => { black(parent) } black(parent) => { black(parent) } } }; result }; assert!((colors.len() == old_len)); } // Convert the results. do par::map(colors) { let result: ~fn(c: &color) -> i64 = |c| { match *c { white => { -1i64 } black(parent) => { parent } _ => { fail!(~"Found remaining gray nodes in BFS") } } }; result } } /// Performs at least some of the validation in the Graph500 spec. fn validate(edges: ~[(node_id, node_id)], root: node_id, tree: bfs_result) -> bool { // There are 5 things to test. Below is code for each of them. // 1. The BFS tree is a tree and does not contain cycles. // // We do this by iterating over the tree, and tracing each of the // parent chains back to the root. While we do this, we also // compute the levels for each node. info!(~"Verifying tree structure..."); let mut status = true; let level = do tree.map() |parent| { let mut parent = *parent; let mut path = ~[]; if parent == -1i64 { // This node was not in the tree. -1 } else
}; if!status { return status } // 2. Each tree edge connects vertices whose BFS levels differ by // exactly one. info!(~"Verifying tree edges..."); let status = do tree.alli() |k, parent| { if *parent!= root && *parent!= -1i64 { level[*parent] == level[k] - 1 } else { true } }; if!status { return status } // 3. Every edge in the input list has vertices with levels that // differ by at most one or that both are not in the BFS tree. info!(~"Verifying graph edges..."); let status = do edges.all() |e| { let (u, v) = *e; abs(level[u] - level[v]) <= 1 }; if!status { return status } // 4. The BFS tree spans an entire connected component's vertices. // This is harder. We'll skip it for now... // 5. A node and its parent are joined by an edge of the original // graph. info!(~"Verifying tree and graph edges..."); let status = do par::alli(tree) { let edges = copy edges; let result: ~fn(+x: uint, v: &i64) -> bool = |u, v| { let u = u as node_id; if *v == -1i64 || u == root { true } else { edges.contains(&(u, *v)) || edges.contains(&(*v, u)) } }; result }; if!status { return status } // If we get through here, all the tests passed! true } fn main() { let args = os::args(); let args = if os::getenv(~"RUST_BENCH").is_some() { ~[~"", ~"15", ~"48"] } else if args.len() <= 1 { ~[~"", ~"10", ~"16"] } else { args }; let scale = uint::from_str(args[1]).get(); let num_keys = uint::from_str(args[2]).get(); let do_validate = false; let do_sequential = true; let start = time::precise_time_s(); let edges = make_edges(scale, 16); let stop = time::precise_time_s(); io::stdout().write_line(fmt!("Generated %? edges in %? seconds.", vec::len(edges), stop - start)); let start = time::precise_time_s(); let graph = make_graph(1 << scale, copy edges); let stop = time::precise_time_s(); let mut total_edges = 0; vec::each(graph, |edges| { total_edges += edges.len(); true }); io::stdout().write_line(fmt!("Generated graph with %? edges in %? seconds.", total_edges / 2, stop - start)); let mut total_seq = 0.0; let mut total_par = 0.0; let graph_arc = arc::ARC(copy graph); do gen_search_keys(graph, num_keys).map() |root| { io::stdout().write_line(~""); io::stdout().write_line(fmt!("Search key: %?", root)); if do_sequential { let start = time::precise_time_s(); let bfs_tree = bfs(copy graph, *root); let stop = time::precise_time_s(); //total_seq += stop - start; io::stdout().write_line( fmt!("Sequential BFS completed in %? seconds.", stop - start)); if do_validate { let start = time::precise_time_s(); assert!((validate(copy edges, *root, bfs_tree))); let stop = time::precise_time_s(); io::stdout().write_line( fmt!("Validation completed in %? seconds.", stop - start)); } let start = time::precise_time_s(); let bfs_tree = bfs2(copy graph, *root); let stop = time::precise_time_s(); total_seq += stop - start; io::stdout().write_line( fmt!("Alternate Sequential BFS completed in %? seconds.", stop - start)); if do_validate { let start = time::precise_time_s(); assert!((validate(copy edges, *root, bfs_tree))); let stop = time::precise_time_s(); io::stdout().write_line( fmt!("Validation completed in %? seconds.", stop - start)); } } let start = time::precise_time_s(); let bfs_tree = pbfs(graph_arc, *root); let stop = time::precise_time_s(); total_par += stop - start; io::stdout().write_line(fmt!("Parallel BFS completed in %? seconds.", stop - start)); if do_validate { let start = time::precise_time_s(); assert!((validate(copy edges, *root, bfs_tree))); let stop = time::precise_time_s(); io::stdout().write_line(fmt!("Validation completed in %? seconds.", stop - start)); } }; io::stdout().write_line(~""); io::stdout().write_line( fmt!("Total sequential: %? \t Total Parallel: %? \t Speedup: %?x", total_seq, total_par, total_seq / total_par)); }
{ while parent != root { if vec::contains(path, &parent) { status = false; } path.push(parent); parent = tree[parent]; } // The length of the path back to the root is the current // level. path.len() as int }
conditional_block
tlsf.rs
// // Copyright 2017 yvt, all rights reserved. // // Licensed under the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>. This file may // not be copied, modified,or distributed except // according to those terms. // #![feature(test)] extern crate test; extern crate unreachable; extern crate xalloc; use test::Bencher; use unreachable::UncheckedOptionExt; use xalloc::*; struct Xorshift32(u32); impl Xorshift32 { fn next(&mut self) -> u32 { self.0 ^= self.0 << 13; self.0 ^= self.0 >> 17; self.0 ^= self.0 << 5; !self.0 } } #[bench] fn systlsf_random(b: &mut Bencher) { let mut v: Vec<_> = (0..512).map(|_| None).collect(); let mut sa = SysTlsf::with_capacity(512u32, 512); b.iter(|| unsafe { let mut r = Xorshift32(0x11451419); for _ in 0..65536 { let i = ((r.next() >> 8) & 511) as usize; if v[i].is_some() { sa.dealloc_unchecked(v[i].take().unchecked_unwrap()); } else { v[i] = Some(sa.alloc(1u32).unchecked_unwrap().0); } } for x in v.iter_mut() { if let Some(x) = x.take() { sa.dealloc_unchecked(x); } } }); } #[bench] fn sys_random(b: &mut Bencher) { let mut v: Vec<_> = (0..512).map(|_| None).collect(); b.iter(|| { let mut r = Xorshift32(0x11451419); for _ in 0..65536 { let i = ((r.next() >> 8) & 511) as usize; if v[i].is_some() { v[i].take(); } else { v[i] = Some(Box::new(1u32)); } } for x in v.iter_mut() { x.take(); } }); } #[bench] fn systlsf_stack(b: &mut Bencher) { let mut sa = SysTlsf::with_capacity(65536u32, 65536); let mut v = Vec::with_capacity(65536); b.iter(|| unsafe { for _ in 0..65536 { v.push(sa.alloc(1u32).unchecked_unwrap().0); } while let Some(x) = v.pop() { sa.dealloc_unchecked(x);
#[bench] fn sys_stack(b: &mut Bencher) { let mut v = Vec::with_capacity(65536); b.iter(|| { for _ in 0..65536 { v.push(Box::new(1u32)); } while let Some(_) = v.pop() {} }); }
} }); }
random_line_split
tlsf.rs
// // Copyright 2017 yvt, all rights reserved. // // Licensed under the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>. This file may // not be copied, modified,or distributed except // according to those terms. // #![feature(test)] extern crate test; extern crate unreachable; extern crate xalloc; use test::Bencher; use unreachable::UncheckedOptionExt; use xalloc::*; struct Xorshift32(u32); impl Xorshift32 { fn next(&mut self) -> u32 { self.0 ^= self.0 << 13; self.0 ^= self.0 >> 17; self.0 ^= self.0 << 5; !self.0 } } #[bench] fn systlsf_random(b: &mut Bencher) { let mut v: Vec<_> = (0..512).map(|_| None).collect(); let mut sa = SysTlsf::with_capacity(512u32, 512); b.iter(|| unsafe { let mut r = Xorshift32(0x11451419); for _ in 0..65536 { let i = ((r.next() >> 8) & 511) as usize; if v[i].is_some() { sa.dealloc_unchecked(v[i].take().unchecked_unwrap()); } else
} for x in v.iter_mut() { if let Some(x) = x.take() { sa.dealloc_unchecked(x); } } }); } #[bench] fn sys_random(b: &mut Bencher) { let mut v: Vec<_> = (0..512).map(|_| None).collect(); b.iter(|| { let mut r = Xorshift32(0x11451419); for _ in 0..65536 { let i = ((r.next() >> 8) & 511) as usize; if v[i].is_some() { v[i].take(); } else { v[i] = Some(Box::new(1u32)); } } for x in v.iter_mut() { x.take(); } }); } #[bench] fn systlsf_stack(b: &mut Bencher) { let mut sa = SysTlsf::with_capacity(65536u32, 65536); let mut v = Vec::with_capacity(65536); b.iter(|| unsafe { for _ in 0..65536 { v.push(sa.alloc(1u32).unchecked_unwrap().0); } while let Some(x) = v.pop() { sa.dealloc_unchecked(x); } }); } #[bench] fn sys_stack(b: &mut Bencher) { let mut v = Vec::with_capacity(65536); b.iter(|| { for _ in 0..65536 { v.push(Box::new(1u32)); } while let Some(_) = v.pop() {} }); }
{ v[i] = Some(sa.alloc(1u32).unchecked_unwrap().0); }
conditional_block
tlsf.rs
// // Copyright 2017 yvt, all rights reserved. // // Licensed under the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>. This file may // not be copied, modified,or distributed except // according to those terms. // #![feature(test)] extern crate test; extern crate unreachable; extern crate xalloc; use test::Bencher; use unreachable::UncheckedOptionExt; use xalloc::*; struct Xorshift32(u32); impl Xorshift32 { fn next(&mut self) -> u32 { self.0 ^= self.0 << 13; self.0 ^= self.0 >> 17; self.0 ^= self.0 << 5; !self.0 } } #[bench] fn systlsf_random(b: &mut Bencher) { let mut v: Vec<_> = (0..512).map(|_| None).collect(); let mut sa = SysTlsf::with_capacity(512u32, 512); b.iter(|| unsafe { let mut r = Xorshift32(0x11451419); for _ in 0..65536 { let i = ((r.next() >> 8) & 511) as usize; if v[i].is_some() { sa.dealloc_unchecked(v[i].take().unchecked_unwrap()); } else { v[i] = Some(sa.alloc(1u32).unchecked_unwrap().0); } } for x in v.iter_mut() { if let Some(x) = x.take() { sa.dealloc_unchecked(x); } } }); } #[bench] fn
(b: &mut Bencher) { let mut v: Vec<_> = (0..512).map(|_| None).collect(); b.iter(|| { let mut r = Xorshift32(0x11451419); for _ in 0..65536 { let i = ((r.next() >> 8) & 511) as usize; if v[i].is_some() { v[i].take(); } else { v[i] = Some(Box::new(1u32)); } } for x in v.iter_mut() { x.take(); } }); } #[bench] fn systlsf_stack(b: &mut Bencher) { let mut sa = SysTlsf::with_capacity(65536u32, 65536); let mut v = Vec::with_capacity(65536); b.iter(|| unsafe { for _ in 0..65536 { v.push(sa.alloc(1u32).unchecked_unwrap().0); } while let Some(x) = v.pop() { sa.dealloc_unchecked(x); } }); } #[bench] fn sys_stack(b: &mut Bencher) { let mut v = Vec::with_capacity(65536); b.iter(|| { for _ in 0..65536 { v.push(Box::new(1u32)); } while let Some(_) = v.pop() {} }); }
sys_random
identifier_name
tlsf.rs
// // Copyright 2017 yvt, all rights reserved. // // Licensed under the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>. This file may // not be copied, modified,or distributed except // according to those terms. // #![feature(test)] extern crate test; extern crate unreachable; extern crate xalloc; use test::Bencher; use unreachable::UncheckedOptionExt; use xalloc::*; struct Xorshift32(u32); impl Xorshift32 { fn next(&mut self) -> u32 { self.0 ^= self.0 << 13; self.0 ^= self.0 >> 17; self.0 ^= self.0 << 5; !self.0 } } #[bench] fn systlsf_random(b: &mut Bencher) { let mut v: Vec<_> = (0..512).map(|_| None).collect(); let mut sa = SysTlsf::with_capacity(512u32, 512); b.iter(|| unsafe { let mut r = Xorshift32(0x11451419); for _ in 0..65536 { let i = ((r.next() >> 8) & 511) as usize; if v[i].is_some() { sa.dealloc_unchecked(v[i].take().unchecked_unwrap()); } else { v[i] = Some(sa.alloc(1u32).unchecked_unwrap().0); } } for x in v.iter_mut() { if let Some(x) = x.take() { sa.dealloc_unchecked(x); } } }); } #[bench] fn sys_random(b: &mut Bencher) { let mut v: Vec<_> = (0..512).map(|_| None).collect(); b.iter(|| { let mut r = Xorshift32(0x11451419); for _ in 0..65536 { let i = ((r.next() >> 8) & 511) as usize; if v[i].is_some() { v[i].take(); } else { v[i] = Some(Box::new(1u32)); } } for x in v.iter_mut() { x.take(); } }); } #[bench] fn systlsf_stack(b: &mut Bencher) { let mut sa = SysTlsf::with_capacity(65536u32, 65536); let mut v = Vec::with_capacity(65536); b.iter(|| unsafe { for _ in 0..65536 { v.push(sa.alloc(1u32).unchecked_unwrap().0); } while let Some(x) = v.pop() { sa.dealloc_unchecked(x); } }); } #[bench] fn sys_stack(b: &mut Bencher)
{ let mut v = Vec::with_capacity(65536); b.iter(|| { for _ in 0..65536 { v.push(Box::new(1u32)); } while let Some(_) = v.pop() {} }); }
identifier_body
restrictions.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. //! Computes the restrictions that result from a borrow. use borrowck::*; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::mem_categorization::Categorization; use rustc::ty; use syntax_pos::Span; use borrowck::ToInteriorKind; use std::rc::Rc; #[derive(Debug)] pub enum RestrictionResult<'tcx> { Safe, SafeIf(Rc<LoanPath<'tcx>>, Vec<Rc<LoanPath<'tcx>>>) } pub fn compute_restrictions<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, span: Span, cause: euv::LoanCause, cmt: &mc::cmt_<'tcx>, loan_region: ty::Region<'tcx>) -> RestrictionResult<'tcx> { let ctxt = RestrictionsContext { bccx, span, cause, loan_region, }; ctxt.restrict(cmt) } /////////////////////////////////////////////////////////////////////////// // Private struct RestrictionsContext<'a, 'tcx: 'a> { bccx: &'a BorrowckCtxt<'a, 'tcx>, span: Span, loan_region: ty::Region<'tcx>, cause: euv::LoanCause, } impl<'a, 'tcx> RestrictionsContext<'a, 'tcx> { fn
(&self, cmt: &mc::cmt_<'tcx>) -> RestrictionResult<'tcx> { debug!("restrict(cmt={:?})", cmt); let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty)); match cmt.cat.clone() { Categorization::Rvalue(..) => { // Effectively, rvalues are stored into a // non-aliasable temporary on the stack. Since they // are inherently non-aliasable, they can only be // accessed later through the borrow itself and hence // must inherently comply with its terms. RestrictionResult::Safe } Categorization::ThreadLocal(..) => { // Thread-locals are statics that have a scope, with // no underlying structure to provide restrictions. RestrictionResult::Safe } Categorization::Local(local_id) => { // R-Variable, locally declared let lp = new_lp(LpVar(local_id)); RestrictionResult::SafeIf(lp.clone(), vec![lp]) } Categorization::Upvar(mc::Upvar { id,.. }) => { // R-Variable, captured into closure let lp = new_lp(LpUpvar(id)); RestrictionResult::SafeIf(lp.clone(), vec![lp]) } Categorization::Downcast(cmt_base, _) => { // When we borrow the interior of an enum, we have to // ensure the enum itself is not mutated, because that // could cause the type of the memory to change. self.restrict(&cmt_base) } Categorization::Interior(cmt_base, interior) => { // R-Field // // Overwriting the base would not change the type of // the memory, so no additional restrictions are // needed. let opt_variant_id = match cmt_base.cat { Categorization::Downcast(_, variant_id) => Some(variant_id), _ => None }; let interior = interior.cleaned(); let base_ty = cmt_base.ty; let result = self.restrict(&cmt_base); // Borrowing one union field automatically borrows all its fields. match base_ty.sty { ty::Adt(adt_def, _) if adt_def.is_union() => match result { RestrictionResult::Safe => RestrictionResult::Safe, RestrictionResult::SafeIf(base_lp, mut base_vec) => { for (i, field) in adt_def.non_enum_variant().fields.iter().enumerate() { let field = InteriorKind::InteriorField( mc::FieldIndex(i, field.ident.name) ); let field_ty = if field == interior { cmt.ty } else { self.bccx.tcx.types.err // Doesn't matter }; let sibling_lp_kind = LpExtend(base_lp.clone(), cmt.mutbl, LpInterior(opt_variant_id, field)); let sibling_lp = Rc::new(LoanPath::new(sibling_lp_kind, field_ty)); base_vec.push(sibling_lp); } let lp = new_lp(LpExtend(base_lp, cmt.mutbl, LpInterior(opt_variant_id, interior))); RestrictionResult::SafeIf(lp, base_vec) } }, _ => self.extend(result, &cmt, LpInterior(opt_variant_id, interior)) } } Categorization::StaticItem => { RestrictionResult::Safe } Categorization::Deref(cmt_base, pk) => { match pk { mc::Unique => { // R-Deref-Send-Pointer // // When we borrow the interior of a box, we // cannot permit the base to be mutated, because that // would cause the unique pointer to be freed. // // Eventually we should make these non-special and // just rely on Deref<T> implementation. let result = self.restrict(&cmt_base); self.extend(result, &cmt, LpDeref(pk)) } mc::BorrowedPtr(bk, lt) => { // R-Deref-[Mut-]Borrowed if!self.bccx.is_subregion_of(self.loan_region, lt) { self.bccx.report( BckError { span: self.span, cause: BorrowViolation(self.cause), cmt: &cmt_base, code: err_borrowed_pointer_too_short( self.loan_region, lt)}); return RestrictionResult::Safe; } match bk { ty::ImmBorrow => RestrictionResult::Safe, ty::MutBorrow | ty::UniqueImmBorrow => { // R-Deref-Mut-Borrowed // // The referent can be aliased after the // references lifetime ends (by a newly-unfrozen // borrow). let result = self.restrict(&cmt_base); self.extend(result, &cmt, LpDeref(pk)) } } } // Borrowck is not relevant for raw pointers mc::UnsafePtr(..) => RestrictionResult::Safe } } } } fn extend(&self, result: RestrictionResult<'tcx>, cmt: &mc::cmt_<'tcx>, elem: LoanPathElem<'tcx>) -> RestrictionResult<'tcx> { match result { RestrictionResult::Safe => RestrictionResult::Safe, RestrictionResult::SafeIf(base_lp, mut base_vec) => { let v = LpExtend(base_lp, cmt.mutbl, elem); let lp = Rc::new(LoanPath::new(v, cmt.ty)); base_vec.push(lp.clone()); RestrictionResult::SafeIf(lp, base_vec) } } } }
restrict
identifier_name
restrictions.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. //! Computes the restrictions that result from a borrow. use borrowck::*; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::mem_categorization::Categorization; use rustc::ty; use syntax_pos::Span; use borrowck::ToInteriorKind; use std::rc::Rc; #[derive(Debug)] pub enum RestrictionResult<'tcx> { Safe, SafeIf(Rc<LoanPath<'tcx>>, Vec<Rc<LoanPath<'tcx>>>) } pub fn compute_restrictions<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, span: Span, cause: euv::LoanCause, cmt: &mc::cmt_<'tcx>, loan_region: ty::Region<'tcx>) -> RestrictionResult<'tcx> { let ctxt = RestrictionsContext { bccx, span, cause, loan_region, }; ctxt.restrict(cmt) } /////////////////////////////////////////////////////////////////////////// // Private struct RestrictionsContext<'a, 'tcx: 'a> { bccx: &'a BorrowckCtxt<'a, 'tcx>, span: Span, loan_region: ty::Region<'tcx>, cause: euv::LoanCause, } impl<'a, 'tcx> RestrictionsContext<'a, 'tcx> { fn restrict(&self, cmt: &mc::cmt_<'tcx>) -> RestrictionResult<'tcx> { debug!("restrict(cmt={:?})", cmt); let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty)); match cmt.cat.clone() { Categorization::Rvalue(..) => { // Effectively, rvalues are stored into a // non-aliasable temporary on the stack. Since they // are inherently non-aliasable, they can only be // accessed later through the borrow itself and hence // must inherently comply with its terms. RestrictionResult::Safe } Categorization::ThreadLocal(..) => { // Thread-locals are statics that have a scope, with // no underlying structure to provide restrictions. RestrictionResult::Safe } Categorization::Local(local_id) => { // R-Variable, locally declared let lp = new_lp(LpVar(local_id)); RestrictionResult::SafeIf(lp.clone(), vec![lp]) } Categorization::Upvar(mc::Upvar { id,.. }) => { // R-Variable, captured into closure let lp = new_lp(LpUpvar(id)); RestrictionResult::SafeIf(lp.clone(), vec![lp]) } Categorization::Downcast(cmt_base, _) => { // When we borrow the interior of an enum, we have to // ensure the enum itself is not mutated, because that // could cause the type of the memory to change. self.restrict(&cmt_base) } Categorization::Interior(cmt_base, interior) => { // R-Field // // Overwriting the base would not change the type of // the memory, so no additional restrictions are // needed. let opt_variant_id = match cmt_base.cat { Categorization::Downcast(_, variant_id) => Some(variant_id), _ => None }; let interior = interior.cleaned(); let base_ty = cmt_base.ty; let result = self.restrict(&cmt_base); // Borrowing one union field automatically borrows all its fields. match base_ty.sty { ty::Adt(adt_def, _) if adt_def.is_union() => match result { RestrictionResult::Safe => RestrictionResult::Safe, RestrictionResult::SafeIf(base_lp, mut base_vec) => { for (i, field) in adt_def.non_enum_variant().fields.iter().enumerate() { let field = InteriorKind::InteriorField( mc::FieldIndex(i, field.ident.name) ); let field_ty = if field == interior { cmt.ty } else { self.bccx.tcx.types.err // Doesn't matter }; let sibling_lp_kind = LpExtend(base_lp.clone(), cmt.mutbl, LpInterior(opt_variant_id, field)); let sibling_lp = Rc::new(LoanPath::new(sibling_lp_kind, field_ty)); base_vec.push(sibling_lp); } let lp = new_lp(LpExtend(base_lp, cmt.mutbl, LpInterior(opt_variant_id, interior))); RestrictionResult::SafeIf(lp, base_vec) } }, _ => self.extend(result, &cmt, LpInterior(opt_variant_id, interior)) } } Categorization::StaticItem => { RestrictionResult::Safe } Categorization::Deref(cmt_base, pk) => { match pk { mc::Unique => { // R-Deref-Send-Pointer // // When we borrow the interior of a box, we // cannot permit the base to be mutated, because that // would cause the unique pointer to be freed. // // Eventually we should make these non-special and // just rely on Deref<T> implementation. let result = self.restrict(&cmt_base); self.extend(result, &cmt, LpDeref(pk)) } mc::BorrowedPtr(bk, lt) => { // R-Deref-[Mut-]Borrowed if!self.bccx.is_subregion_of(self.loan_region, lt) { self.bccx.report( BckError { span: self.span, cause: BorrowViolation(self.cause), cmt: &cmt_base, code: err_borrowed_pointer_too_short( self.loan_region, lt)}); return RestrictionResult::Safe; } match bk { ty::ImmBorrow => RestrictionResult::Safe, ty::MutBorrow | ty::UniqueImmBorrow => { // R-Deref-Mut-Borrowed // // The referent can be aliased after the // references lifetime ends (by a newly-unfrozen // borrow). let result = self.restrict(&cmt_base); self.extend(result, &cmt, LpDeref(pk)) } } } // Borrowck is not relevant for raw pointers mc::UnsafePtr(..) => RestrictionResult::Safe } } } } fn extend(&self, result: RestrictionResult<'tcx>, cmt: &mc::cmt_<'tcx>, elem: LoanPathElem<'tcx>) -> RestrictionResult<'tcx>
}
{ match result { RestrictionResult::Safe => RestrictionResult::Safe, RestrictionResult::SafeIf(base_lp, mut base_vec) => { let v = LpExtend(base_lp, cmt.mutbl, elem); let lp = Rc::new(LoanPath::new(v, cmt.ty)); base_vec.push(lp.clone()); RestrictionResult::SafeIf(lp, base_vec) } } }
identifier_body
restrictions.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. //! Computes the restrictions that result from a borrow. use borrowck::*; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::mem_categorization::Categorization; use rustc::ty; use syntax_pos::Span; use borrowck::ToInteriorKind; use std::rc::Rc; #[derive(Debug)] pub enum RestrictionResult<'tcx> { Safe, SafeIf(Rc<LoanPath<'tcx>>, Vec<Rc<LoanPath<'tcx>>>) } pub fn compute_restrictions<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, span: Span, cause: euv::LoanCause, cmt: &mc::cmt_<'tcx>, loan_region: ty::Region<'tcx>) -> RestrictionResult<'tcx> { let ctxt = RestrictionsContext { bccx, span, cause, loan_region, }; ctxt.restrict(cmt) } /////////////////////////////////////////////////////////////////////////// // Private struct RestrictionsContext<'a, 'tcx: 'a> { bccx: &'a BorrowckCtxt<'a, 'tcx>, span: Span, loan_region: ty::Region<'tcx>, cause: euv::LoanCause, } impl<'a, 'tcx> RestrictionsContext<'a, 'tcx> { fn restrict(&self, cmt: &mc::cmt_<'tcx>) -> RestrictionResult<'tcx> { debug!("restrict(cmt={:?})", cmt); let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty)); match cmt.cat.clone() { Categorization::Rvalue(..) => { // Effectively, rvalues are stored into a // non-aliasable temporary on the stack. Since they // are inherently non-aliasable, they can only be // accessed later through the borrow itself and hence // must inherently comply with its terms. RestrictionResult::Safe } Categorization::ThreadLocal(..) => { // Thread-locals are statics that have a scope, with // no underlying structure to provide restrictions. RestrictionResult::Safe } Categorization::Local(local_id) => { // R-Variable, locally declared let lp = new_lp(LpVar(local_id)); RestrictionResult::SafeIf(lp.clone(), vec![lp]) } Categorization::Upvar(mc::Upvar { id,.. }) => { // R-Variable, captured into closure let lp = new_lp(LpUpvar(id)); RestrictionResult::SafeIf(lp.clone(), vec![lp]) } Categorization::Downcast(cmt_base, _) => { // When we borrow the interior of an enum, we have to // ensure the enum itself is not mutated, because that // could cause the type of the memory to change. self.restrict(&cmt_base) } Categorization::Interior(cmt_base, interior) => { // R-Field // // Overwriting the base would not change the type of // the memory, so no additional restrictions are // needed. let opt_variant_id = match cmt_base.cat { Categorization::Downcast(_, variant_id) => Some(variant_id), _ => None }; let interior = interior.cleaned(); let base_ty = cmt_base.ty; let result = self.restrict(&cmt_base); // Borrowing one union field automatically borrows all its fields. match base_ty.sty { ty::Adt(adt_def, _) if adt_def.is_union() => match result { RestrictionResult::Safe => RestrictionResult::Safe, RestrictionResult::SafeIf(base_lp, mut base_vec) => { for (i, field) in adt_def.non_enum_variant().fields.iter().enumerate() { let field = InteriorKind::InteriorField( mc::FieldIndex(i, field.ident.name) ); let field_ty = if field == interior { cmt.ty } else { self.bccx.tcx.types.err // Doesn't matter }; let sibling_lp_kind = LpExtend(base_lp.clone(), cmt.mutbl, LpInterior(opt_variant_id, field)); let sibling_lp = Rc::new(LoanPath::new(sibling_lp_kind, field_ty)); base_vec.push(sibling_lp); } let lp = new_lp(LpExtend(base_lp, cmt.mutbl, LpInterior(opt_variant_id, interior))); RestrictionResult::SafeIf(lp, base_vec) } }, _ => self.extend(result, &cmt, LpInterior(opt_variant_id, interior)) } } Categorization::StaticItem => { RestrictionResult::Safe }
Categorization::Deref(cmt_base, pk) => { match pk { mc::Unique => { // R-Deref-Send-Pointer // // When we borrow the interior of a box, we // cannot permit the base to be mutated, because that // would cause the unique pointer to be freed. // // Eventually we should make these non-special and // just rely on Deref<T> implementation. let result = self.restrict(&cmt_base); self.extend(result, &cmt, LpDeref(pk)) } mc::BorrowedPtr(bk, lt) => { // R-Deref-[Mut-]Borrowed if!self.bccx.is_subregion_of(self.loan_region, lt) { self.bccx.report( BckError { span: self.span, cause: BorrowViolation(self.cause), cmt: &cmt_base, code: err_borrowed_pointer_too_short( self.loan_region, lt)}); return RestrictionResult::Safe; } match bk { ty::ImmBorrow => RestrictionResult::Safe, ty::MutBorrow | ty::UniqueImmBorrow => { // R-Deref-Mut-Borrowed // // The referent can be aliased after the // references lifetime ends (by a newly-unfrozen // borrow). let result = self.restrict(&cmt_base); self.extend(result, &cmt, LpDeref(pk)) } } } // Borrowck is not relevant for raw pointers mc::UnsafePtr(..) => RestrictionResult::Safe } } } } fn extend(&self, result: RestrictionResult<'tcx>, cmt: &mc::cmt_<'tcx>, elem: LoanPathElem<'tcx>) -> RestrictionResult<'tcx> { match result { RestrictionResult::Safe => RestrictionResult::Safe, RestrictionResult::SafeIf(base_lp, mut base_vec) => { let v = LpExtend(base_lp, cmt.mutbl, elem); let lp = Rc::new(LoanPath::new(v, cmt.ty)); base_vec.push(lp.clone()); RestrictionResult::SafeIf(lp, base_vec) } } } }
random_line_split
status_reporter.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::{ errors::{BuildProjectError, Error}, source_for_location, FsSourceReader, SourceReader, }; use common::Diagnostic; use graphql_cli::DiagnosticPrinter; use log::{error, info}; use std::path::PathBuf; pub trait StatusReporter { fn build_starts(&self); fn build_completes(&self); fn build_errors(&self, error: &Error); } pub struct ConsoleStatusReporter { source_reader: Box<dyn SourceReader + Send + Sync>, root_dir: PathBuf, } impl ConsoleStatusReporter { pub fn new(root_dir: PathBuf) -> Self { Self { root_dir, source_reader: Box::new(FsSourceReader), } } } impl ConsoleStatusReporter { fn print_error(&self, error: &Error) { match error { Error::DiagnosticsError { errors } => { for diagnostic in errors { self.print_diagnostic(diagnostic); } } Error::BuildProjectsErrors { errors } => { for error in errors { self.print_project_error(error); } }
error => { error!("{}", error); } } } fn print_project_error(&self, error: &BuildProjectError) { match error { BuildProjectError::ValidationErrors { errors } => { for diagnostic in errors { self.print_diagnostic(diagnostic); } } BuildProjectError::PersistErrors { errors } => { for error in errors { error!("{}", error); } } _ => { error!("{}", error); } } } fn print_diagnostic(&self, diagnostic: &Diagnostic) { let printer = DiagnosticPrinter::new(|source_location| { source_for_location(&self.root_dir, source_location, self.source_reader.as_ref()) }); error!("{}", printer.diagnostic_to_string(diagnostic)); } } impl StatusReporter for ConsoleStatusReporter { fn build_starts(&self) {} fn build_completes(&self) {} fn build_errors(&self, error: &Error) { self.print_error(error); if!matches!(error, Error::Cancelled) { error!("Compilation failed."); } } }
Error::Cancelled => { info!("Compilation cancelled due to new changes."); }
random_line_split
status_reporter.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::{ errors::{BuildProjectError, Error}, source_for_location, FsSourceReader, SourceReader, }; use common::Diagnostic; use graphql_cli::DiagnosticPrinter; use log::{error, info}; use std::path::PathBuf; pub trait StatusReporter { fn build_starts(&self); fn build_completes(&self); fn build_errors(&self, error: &Error); } pub struct
{ source_reader: Box<dyn SourceReader + Send + Sync>, root_dir: PathBuf, } impl ConsoleStatusReporter { pub fn new(root_dir: PathBuf) -> Self { Self { root_dir, source_reader: Box::new(FsSourceReader), } } } impl ConsoleStatusReporter { fn print_error(&self, error: &Error) { match error { Error::DiagnosticsError { errors } => { for diagnostic in errors { self.print_diagnostic(diagnostic); } } Error::BuildProjectsErrors { errors } => { for error in errors { self.print_project_error(error); } } Error::Cancelled => { info!("Compilation cancelled due to new changes."); } error => { error!("{}", error); } } } fn print_project_error(&self, error: &BuildProjectError) { match error { BuildProjectError::ValidationErrors { errors } => { for diagnostic in errors { self.print_diagnostic(diagnostic); } } BuildProjectError::PersistErrors { errors } => { for error in errors { error!("{}", error); } } _ => { error!("{}", error); } } } fn print_diagnostic(&self, diagnostic: &Diagnostic) { let printer = DiagnosticPrinter::new(|source_location| { source_for_location(&self.root_dir, source_location, self.source_reader.as_ref()) }); error!("{}", printer.diagnostic_to_string(diagnostic)); } } impl StatusReporter for ConsoleStatusReporter { fn build_starts(&self) {} fn build_completes(&self) {} fn build_errors(&self, error: &Error) { self.print_error(error); if!matches!(error, Error::Cancelled) { error!("Compilation failed."); } } }
ConsoleStatusReporter
identifier_name
status_reporter.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::{ errors::{BuildProjectError, Error}, source_for_location, FsSourceReader, SourceReader, }; use common::Diagnostic; use graphql_cli::DiagnosticPrinter; use log::{error, info}; use std::path::PathBuf; pub trait StatusReporter { fn build_starts(&self); fn build_completes(&self); fn build_errors(&self, error: &Error); } pub struct ConsoleStatusReporter { source_reader: Box<dyn SourceReader + Send + Sync>, root_dir: PathBuf, } impl ConsoleStatusReporter { pub fn new(root_dir: PathBuf) -> Self { Self { root_dir, source_reader: Box::new(FsSourceReader), } } } impl ConsoleStatusReporter { fn print_error(&self, error: &Error) { match error { Error::DiagnosticsError { errors } => { for diagnostic in errors { self.print_diagnostic(diagnostic); } } Error::BuildProjectsErrors { errors } =>
Error::Cancelled => { info!("Compilation cancelled due to new changes."); } error => { error!("{}", error); } } } fn print_project_error(&self, error: &BuildProjectError) { match error { BuildProjectError::ValidationErrors { errors } => { for diagnostic in errors { self.print_diagnostic(diagnostic); } } BuildProjectError::PersistErrors { errors } => { for error in errors { error!("{}", error); } } _ => { error!("{}", error); } } } fn print_diagnostic(&self, diagnostic: &Diagnostic) { let printer = DiagnosticPrinter::new(|source_location| { source_for_location(&self.root_dir, source_location, self.source_reader.as_ref()) }); error!("{}", printer.diagnostic_to_string(diagnostic)); } } impl StatusReporter for ConsoleStatusReporter { fn build_starts(&self) {} fn build_completes(&self) {} fn build_errors(&self, error: &Error) { self.print_error(error); if!matches!(error, Error::Cancelled) { error!("Compilation failed."); } } }
{ for error in errors { self.print_project_error(error); } }
conditional_block
status_reporter.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::{ errors::{BuildProjectError, Error}, source_for_location, FsSourceReader, SourceReader, }; use common::Diagnostic; use graphql_cli::DiagnosticPrinter; use log::{error, info}; use std::path::PathBuf; pub trait StatusReporter { fn build_starts(&self); fn build_completes(&self); fn build_errors(&self, error: &Error); } pub struct ConsoleStatusReporter { source_reader: Box<dyn SourceReader + Send + Sync>, root_dir: PathBuf, } impl ConsoleStatusReporter { pub fn new(root_dir: PathBuf) -> Self { Self { root_dir, source_reader: Box::new(FsSourceReader), } } } impl ConsoleStatusReporter { fn print_error(&self, error: &Error) { match error { Error::DiagnosticsError { errors } => { for diagnostic in errors { self.print_diagnostic(diagnostic); } } Error::BuildProjectsErrors { errors } => { for error in errors { self.print_project_error(error); } } Error::Cancelled => { info!("Compilation cancelled due to new changes."); } error => { error!("{}", error); } } } fn print_project_error(&self, error: &BuildProjectError) { match error { BuildProjectError::ValidationErrors { errors } => { for diagnostic in errors { self.print_diagnostic(diagnostic); } } BuildProjectError::PersistErrors { errors } => { for error in errors { error!("{}", error); } } _ => { error!("{}", error); } } } fn print_diagnostic(&self, diagnostic: &Diagnostic)
} impl StatusReporter for ConsoleStatusReporter { fn build_starts(&self) {} fn build_completes(&self) {} fn build_errors(&self, error: &Error) { self.print_error(error); if!matches!(error, Error::Cancelled) { error!("Compilation failed."); } } }
{ let printer = DiagnosticPrinter::new(|source_location| { source_for_location(&self.root_dir, source_location, self.source_reader.as_ref()) }); error!("{}", printer.diagnostic_to_string(diagnostic)); }
identifier_body
explicit-self-generic.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. #![allow(unknown_features)] #![feature(box_syntax)] #[derive(Copy, Clone)] struct LM { resize_at: usize, size: usize } enum HashMap<K,V> { HashMap_(LM, Vec<(K,V)>) } fn linear_map<K,V>() -> HashMap<K,V> { HashMap::HashMap_(LM{ resize_at: 32, size: 0}, Vec::new()) } impl<K,V> HashMap<K,V> { pub fn len(&mut self) -> usize { match *self { HashMap::HashMap_(ref l, _) => l.size } } } pub fn
() { let mut m: Box<_> = box linear_map::<(),()>(); assert_eq!(m.len(), 0); }
main
identifier_name
explicit-self-generic.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. #![allow(unknown_features)] #![feature(box_syntax)]
#[derive(Copy, Clone)] struct LM { resize_at: usize, size: usize } enum HashMap<K,V> { HashMap_(LM, Vec<(K,V)>) } fn linear_map<K,V>() -> HashMap<K,V> { HashMap::HashMap_(LM{ resize_at: 32, size: 0}, Vec::new()) } impl<K,V> HashMap<K,V> { pub fn len(&mut self) -> usize { match *self { HashMap::HashMap_(ref l, _) => l.size } } } pub fn main() { let mut m: Box<_> = box linear_map::<(),()>(); assert_eq!(m.len(), 0); }
random_line_split
explicit-self-generic.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. #![allow(unknown_features)] #![feature(box_syntax)] #[derive(Copy, Clone)] struct LM { resize_at: usize, size: usize } enum HashMap<K,V> { HashMap_(LM, Vec<(K,V)>) } fn linear_map<K,V>() -> HashMap<K,V> { HashMap::HashMap_(LM{ resize_at: 32, size: 0}, Vec::new()) } impl<K,V> HashMap<K,V> { pub fn len(&mut self) -> usize
} pub fn main() { let mut m: Box<_> = box linear_map::<(),()>(); assert_eq!(m.len(), 0); }
{ match *self { HashMap::HashMap_(ref l, _) => l.size } }
identifier_body
bitwise.rs
// -*- rust -*- // 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. #[cfg(target_arch = "x86")] fn target() { assert!((-1000 as uint >> 3u == 536870787u)); } #[cfg(target_arch = "x86_64")] fn
() { assert!((-1000 as uint >> 3u == 2305843009213693827u)); } fn general() { let mut a: int = 1; let mut b: int = 2; a ^= b; b ^= a; a = a ^ b; debug!(a); debug!(b); assert!((b == 1)); assert!((a == 2)); assert!((!0xf0 & 0xff == 0xf)); assert!((0xf0 | 0xf == 0xff)); assert!((0xf << 4 == 0xf0)); assert!((0xf0 >> 4 == 0xf)); assert!((-16 >> 2 == -4)); assert!((0b1010_1010 | 0b0101_0101 == 0xff)); } pub fn main() { general(); target(); }
target
identifier_name
bitwise.rs
// -*- rust -*- // 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. #[cfg(target_arch = "x86")] fn target() { assert!((-1000 as uint >> 3u == 536870787u)); } #[cfg(target_arch = "x86_64")] fn target() { assert!((-1000 as uint >> 3u == 2305843009213693827u)); } fn general() { let mut a: int = 1; let mut b: int = 2; a ^= b; b ^= a; a = a ^ b; debug!(a); debug!(b); assert!((b == 1)); assert!((a == 2)); assert!((!0xf0 & 0xff == 0xf)); assert!((0xf0 | 0xf == 0xff)); assert!((0xf << 4 == 0xf0)); assert!((0xf0 >> 4 == 0xf)); assert!((-16 >> 2 == -4)); assert!((0b1010_1010 | 0b0101_0101 == 0xff)); } pub fn main()
{ general(); target(); }
identifier_body
bitwise.rs
// 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. #[cfg(target_arch = "x86")] fn target() { assert!((-1000 as uint >> 3u == 536870787u)); } #[cfg(target_arch = "x86_64")] fn target() { assert!((-1000 as uint >> 3u == 2305843009213693827u)); } fn general() { let mut a: int = 1; let mut b: int = 2; a ^= b; b ^= a; a = a ^ b; debug!(a); debug!(b); assert!((b == 1)); assert!((a == 2)); assert!((!0xf0 & 0xff == 0xf)); assert!((0xf0 | 0xf == 0xff)); assert!((0xf << 4 == 0xf0)); assert!((0xf0 >> 4 == 0xf)); assert!((-16 >> 2 == -4)); assert!((0b1010_1010 | 0b0101_0101 == 0xff)); } pub fn main() { general(); target(); }
// -*- rust -*- // 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. //
random_line_split
sdl2.rs
use self::sdl2::event::Event; use self::sdl2::keyboard::Keycode; use self::sdl2::pixels::{Color, PixelFormatEnum}; use self::sdl2::rect::Rect; use self::sdl2::render::{Texture, TextureCreator, WindowCanvas}; use self::sdl2::video::WindowContext; use sdl2; use std::collections::HashMap; use std::path::Path; use std::sync::mpsc::{Receiver, Sender}; use std::time::{Duration, Instant}; use super::{BackendMessage, EmulatorBackend}; use crate::config::EmulatorAppConfig; use crate::emulator::EmulationMessage; use crate::input::get_key_bindings; use rustboylib::gpu::{RGB, SCREEN_H, SCREEN_W}; /// The SDL 2 backend, using rust-sdl2. pub struct BackendSDL2; impl BackendSDL2 { fn render_display<'a>( tc: &'a TextureCreator<WindowContext>, wc: &mut WindowCanvas, frame_buffer: &[RGB], scale_h: u32, scale_v: u32, ) -> Texture<'a> { let (w, w_scale) = (SCREEN_W as i32, scale_h as i32); let (h, h_scale) = (SCREEN_H as i32, scale_v as i32); let mut texture = tc .create_texture_target( PixelFormatEnum::RGB24, (SCREEN_W as u32) * scale_h, (SCREEN_H as u32) * scale_v, ) .expect("BackendSDL2::render_display: texture creation error"); wc.with_texture_canvas(&mut texture, |texture_canvas| { for y in 0i32..(h as i32) { for x in 0i32..(w as i32) { let color = frame_buffer[(y * w + x) as usize]; texture_canvas.set_draw_color(Color::RGB(color.r, color.g, color.b)); texture_canvas .fill_rect(Rect::new(x * w_scale, y * h_scale, scale_h, scale_v)) .expect("BackendSDL2::render_display: texture canvas fill rect error"); } } }) .expect("BackendSDL2::render_display: texture canvas error"); texture } } impl EmulatorBackend for BackendSDL2 { fn run( &mut self, config: EmulatorAppConfig, tx: Sender<BackendMessage>, rx: Receiver<EmulationMessage>, ) { use crate::backend::BackendMessage::*; use crate::emulator::EmulationMessage::*; info!("starting the main application thread."); // Input bindings let key_binds = match get_key_bindings::<Keycode>( &config.get_keyboard_binding(), &keycode_from_symbol_hm(), ) { Ok(hm) => hm, Err(why) => { error!("SDL2 backend input : {}", why); return; } }; // Window size let (scale_h, scale_v) = config.compute_display_scale(); let w = (SCREEN_W as u32) * (scale_h as u32); let h = (SCREEN_H as u32) * (scale_v as u32); info!("display scale = ({}, {}).", scale_h, scale_v); // SDL 2 initialization let sdl_context = sdl2::init().unwrap(); let ttf_context = sdl2::ttf::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let window = match video_subsystem .window(config.get_title(), w, h) .position_centered() .opengl() .build() { Ok(window) => window, Err(why) => { error!("SDL2 backend failed to create the window : {}", why); return; } };
let texture_creator = canvas.texture_creator(); canvas.set_draw_color(Color::RGB(0, 0, 0)); canvas.clear(); let mut events = sdl_context.event_pump().unwrap(); let font = ttf_context .load_font(Path::new("assets/OpenSans-Regular.ttf"), 48) .expect("could not load 'assets/OpenSans-Regular.ttf'"); // is the emulation paused? let mut paused = false; // avoid spamming 'Event::KeyDown' events for the same key let mut last_key: Option<Keycode> = None; // FPS count let mut fps = 0; let mut fps_timer = Instant::now(); let one_second = Duration::new(1, 0); let show_fps = config.get_display_fps(); let fps_font_color = Color::RGBA(255, 255, 255, 255); let fps_target_rect = sdl2::rect::Rect::new(0, 0, 70, 40); let fps_surface = font.render("0").blended(fps_font_color).unwrap(); let mut fps_texture = texture_creator .create_texture_from_surface(&fps_surface) .unwrap(); // Main loop 'ui: loop { // Event loop for event in events.poll_iter() { match event { Event::Quit {.. } => { paused = true; tx.send(Quit).unwrap(); } Event::KeyDown { keycode: Some(keycode), .. } => { if last_key.is_some() && keycode == last_key.unwrap() { continue; } match keycode { // quit Keycode::Escape => { paused = true; tx.send(Quit).unwrap(); } // toggle pause Keycode::Return => { paused =!paused; tx.send(UpdateRunStatus(paused)).unwrap(); } _ => { if!paused { if let Some(keypad_key) = key_binds.get(&keycode) { tx.send(KeyDown(*keypad_key)).unwrap(); } } } } last_key = Some(keycode); } Event::KeyUp { keycode: Some(keycode), .. } if!paused => { if let Some(keypad_key) = key_binds.get(&keycode) { tx.send(KeyUp(*keypad_key)).unwrap(); } if last_key.is_some() && keycode == last_key.unwrap() { last_key = None; } } _ => continue, } } // Signals from the VM match rx.try_recv() { Ok(emulation_message) => match emulation_message { UpdateDisplay(frame_buffer) => { let texture = BackendSDL2::render_display( &texture_creator, &mut canvas, &frame_buffer, scale_h as u32, scale_v as u32, ); canvas .copy(&texture, None, Some(Rect::new(0, 0, w, h))) .expect("BackendSDL2: canvas texture copy error"); } Finished => break 'ui, }, _ => {} } // FPS count fps += 1; if fps_timer.elapsed() >= one_second { fps_timer = Instant::now(); let text = format!("{}", fps); fps = 0; let surface = font.render(&text[..]).blended(fps_font_color).unwrap(); fps_texture = texture_creator .create_texture_from_surface(&surface) .unwrap(); } if show_fps { canvas .copy(&fps_texture, None, Some(fps_target_rect)) .unwrap(); } canvas.present(); } info!("terminating the main application thread."); } } pub fn keycode_from_symbol_hm() -> HashMap<String, Keycode> { let mut hm = HashMap::new(); hm.insert("Up".into(), Keycode::Up); hm.insert("Down".into(), Keycode::Down); hm.insert("Left".into(), Keycode::Left); hm.insert("Right".into(), Keycode::Right); hm.insert("Numpad0".into(), Keycode::Kp0); hm.insert("Numpad1".into(), Keycode::Kp1); hm.insert("Numpad2".into(), Keycode::Kp2); hm.insert("Numpad3".into(), Keycode::Kp3); hm.insert("Numpad4".into(), Keycode::Kp4); hm.insert("Numpad5".into(), Keycode::Kp5); hm.insert("Numpad6".into(), Keycode::Kp6); hm.insert("Numpad7".into(), Keycode::Kp7); hm.insert("Numpad8".into(), Keycode::Kp8); hm.insert("Numpad9".into(), Keycode::Kp9); hm.insert("NumpadPlus".into(), Keycode::KpPlus); hm.insert("NumpadMinus".into(), Keycode::KpMinus); hm.insert("NumpadMultiply".into(), Keycode::KpMultiply); hm.insert("NumpadDivide".into(), Keycode::KpDivide); // reference : https://wiki.libsdl.org/SDL_Keycode // and : "keycode.rs" from https://github.com/AngryLawyer/rust-sdl2/ let mut sdl2_key_names = Vec::<String>::new(); for c in b'A'..b'Z' + 1 { sdl2_key_names.push((c as char).to_string()); } for i in 1..13 { sdl2_key_names.push(format!("F{}", i)); } // F1-F12 for key_name in sdl2_key_names { let key_code = match Keycode::from_name(&key_name[..]) { Some(code) => code, None => panic!("SDL2 backend : invalid keycode \"{}\"", key_name), }; hm.insert(key_name.clone(), key_code); } hm } #[cfg(test)] mod test { use super::sdl2::keyboard::Keycode; use crate::input::get_key_bindings; use crate::input::KeyboardBinding::FromConfigFile; use rustboylib::joypad::JoypadKey; #[test] fn test_keyboard_hm_from_config() { let keycode_symbol_hm = super::keycode_from_symbol_hm(); let key_binds = get_key_bindings::<Keycode>( &FromConfigFile("tests/backend_input.toml".into()), &keycode_symbol_hm, ) .unwrap(); assert_eq!(*key_binds.get(&Keycode::Up).unwrap(), JoypadKey::Up); assert_eq!(*key_binds.get(&Keycode::Down).unwrap(), JoypadKey::Down); assert_eq!(*key_binds.get(&Keycode::Left).unwrap(), JoypadKey::Left); assert_eq!(*key_binds.get(&Keycode::Right).unwrap(), JoypadKey::Right); assert_eq!(*key_binds.get(&Keycode::Kp1).unwrap(), JoypadKey::Select); assert_eq!(*key_binds.get(&Keycode::Kp3).unwrap(), JoypadKey::Start); assert_eq!(*key_binds.get(&Keycode::E).unwrap(), JoypadKey::A); assert_eq!(*key_binds.get(&Keycode::T).unwrap(), JoypadKey::B); } }
let mut canvas = window.into_canvas().accelerated().build().unwrap();
random_line_split
sdl2.rs
use self::sdl2::event::Event; use self::sdl2::keyboard::Keycode; use self::sdl2::pixels::{Color, PixelFormatEnum}; use self::sdl2::rect::Rect; use self::sdl2::render::{Texture, TextureCreator, WindowCanvas}; use self::sdl2::video::WindowContext; use sdl2; use std::collections::HashMap; use std::path::Path; use std::sync::mpsc::{Receiver, Sender}; use std::time::{Duration, Instant}; use super::{BackendMessage, EmulatorBackend}; use crate::config::EmulatorAppConfig; use crate::emulator::EmulationMessage; use crate::input::get_key_bindings; use rustboylib::gpu::{RGB, SCREEN_H, SCREEN_W}; /// The SDL 2 backend, using rust-sdl2. pub struct BackendSDL2; impl BackendSDL2 { fn render_display<'a>( tc: &'a TextureCreator<WindowContext>, wc: &mut WindowCanvas, frame_buffer: &[RGB], scale_h: u32, scale_v: u32, ) -> Texture<'a> { let (w, w_scale) = (SCREEN_W as i32, scale_h as i32); let (h, h_scale) = (SCREEN_H as i32, scale_v as i32); let mut texture = tc .create_texture_target( PixelFormatEnum::RGB24, (SCREEN_W as u32) * scale_h, (SCREEN_H as u32) * scale_v, ) .expect("BackendSDL2::render_display: texture creation error"); wc.with_texture_canvas(&mut texture, |texture_canvas| { for y in 0i32..(h as i32) { for x in 0i32..(w as i32) { let color = frame_buffer[(y * w + x) as usize]; texture_canvas.set_draw_color(Color::RGB(color.r, color.g, color.b)); texture_canvas .fill_rect(Rect::new(x * w_scale, y * h_scale, scale_h, scale_v)) .expect("BackendSDL2::render_display: texture canvas fill rect error"); } } }) .expect("BackendSDL2::render_display: texture canvas error"); texture } } impl EmulatorBackend for BackendSDL2 { fn run( &mut self, config: EmulatorAppConfig, tx: Sender<BackendMessage>, rx: Receiver<EmulationMessage>, )
let w = (SCREEN_W as u32) * (scale_h as u32); let h = (SCREEN_H as u32) * (scale_v as u32); info!("display scale = ({}, {}).", scale_h, scale_v); // SDL 2 initialization let sdl_context = sdl2::init().unwrap(); let ttf_context = sdl2::ttf::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let window = match video_subsystem .window(config.get_title(), w, h) .position_centered() .opengl() .build() { Ok(window) => window, Err(why) => { error!("SDL2 backend failed to create the window : {}", why); return; } }; let mut canvas = window.into_canvas().accelerated().build().unwrap(); let texture_creator = canvas.texture_creator(); canvas.set_draw_color(Color::RGB(0, 0, 0)); canvas.clear(); let mut events = sdl_context.event_pump().unwrap(); let font = ttf_context .load_font(Path::new("assets/OpenSans-Regular.ttf"), 48) .expect("could not load 'assets/OpenSans-Regular.ttf'"); // is the emulation paused? let mut paused = false; // avoid spamming 'Event::KeyDown' events for the same key let mut last_key: Option<Keycode> = None; // FPS count let mut fps = 0; let mut fps_timer = Instant::now(); let one_second = Duration::new(1, 0); let show_fps = config.get_display_fps(); let fps_font_color = Color::RGBA(255, 255, 255, 255); let fps_target_rect = sdl2::rect::Rect::new(0, 0, 70, 40); let fps_surface = font.render("0").blended(fps_font_color).unwrap(); let mut fps_texture = texture_creator .create_texture_from_surface(&fps_surface) .unwrap(); // Main loop 'ui: loop { // Event loop for event in events.poll_iter() { match event { Event::Quit {.. } => { paused = true; tx.send(Quit).unwrap(); } Event::KeyDown { keycode: Some(keycode), .. } => { if last_key.is_some() && keycode == last_key.unwrap() { continue; } match keycode { // quit Keycode::Escape => { paused = true; tx.send(Quit).unwrap(); } // toggle pause Keycode::Return => { paused =!paused; tx.send(UpdateRunStatus(paused)).unwrap(); } _ => { if!paused { if let Some(keypad_key) = key_binds.get(&keycode) { tx.send(KeyDown(*keypad_key)).unwrap(); } } } } last_key = Some(keycode); } Event::KeyUp { keycode: Some(keycode), .. } if!paused => { if let Some(keypad_key) = key_binds.get(&keycode) { tx.send(KeyUp(*keypad_key)).unwrap(); } if last_key.is_some() && keycode == last_key.unwrap() { last_key = None; } } _ => continue, } } // Signals from the VM match rx.try_recv() { Ok(emulation_message) => match emulation_message { UpdateDisplay(frame_buffer) => { let texture = BackendSDL2::render_display( &texture_creator, &mut canvas, &frame_buffer, scale_h as u32, scale_v as u32, ); canvas .copy(&texture, None, Some(Rect::new(0, 0, w, h))) .expect("BackendSDL2: canvas texture copy error"); } Finished => break 'ui, }, _ => {} } // FPS count fps += 1; if fps_timer.elapsed() >= one_second { fps_timer = Instant::now(); let text = format!("{}", fps); fps = 0; let surface = font.render(&text[..]).blended(fps_font_color).unwrap(); fps_texture = texture_creator .create_texture_from_surface(&surface) .unwrap(); } if show_fps { canvas .copy(&fps_texture, None, Some(fps_target_rect)) .unwrap(); } canvas.present(); } info!("terminating the main application thread."); } } pub fn keycode_from_symbol_hm() -> HashMap<String, Keycode> { let mut hm = HashMap::new(); hm.insert("Up".into(), Keycode::Up); hm.insert("Down".into(), Keycode::Down); hm.insert("Left".into(), Keycode::Left); hm.insert("Right".into(), Keycode::Right); hm.insert("Numpad0".into(), Keycode::Kp0); hm.insert("Numpad1".into(), Keycode::Kp1); hm.insert("Numpad2".into(), Keycode::Kp2); hm.insert("Numpad3".into(), Keycode::Kp3); hm.insert("Numpad4".into(), Keycode::Kp4); hm.insert("Numpad5".into(), Keycode::Kp5); hm.insert("Numpad6".into(), Keycode::Kp6); hm.insert("Numpad7".into(), Keycode::Kp7); hm.insert("Numpad8".into(), Keycode::Kp8); hm.insert("Numpad9".into(), Keycode::Kp9); hm.insert("NumpadPlus".into(), Keycode::KpPlus); hm.insert("NumpadMinus".into(), Keycode::KpMinus); hm.insert("NumpadMultiply".into(), Keycode::KpMultiply); hm.insert("NumpadDivide".into(), Keycode::KpDivide); // reference : https://wiki.libsdl.org/SDL_Keycode // and : "keycode.rs" from https://github.com/AngryLawyer/rust-sdl2/ let mut sdl2_key_names = Vec::<String>::new(); for c in b'A'..b'Z' + 1 { sdl2_key_names.push((c as char).to_string()); } for i in 1..13 { sdl2_key_names.push(format!("F{}", i)); } // F1-F12 for key_name in sdl2_key_names { let key_code = match Keycode::from_name(&key_name[..]) { Some(code) => code, None => panic!("SDL2 backend : invalid keycode \"{}\"", key_name), }; hm.insert(key_name.clone(), key_code); } hm } #[cfg(test)] mod test { use super::sdl2::keyboard::Keycode; use crate::input::get_key_bindings; use crate::input::KeyboardBinding::FromConfigFile; use rustboylib::joypad::JoypadKey; #[test] fn test_keyboard_hm_from_config() { let keycode_symbol_hm = super::keycode_from_symbol_hm(); let key_binds = get_key_bindings::<Keycode>( &FromConfigFile("tests/backend_input.toml".into()), &keycode_symbol_hm, ) .unwrap(); assert_eq!(*key_binds.get(&Keycode::Up).unwrap(), JoypadKey::Up); assert_eq!(*key_binds.get(&Keycode::Down).unwrap(), JoypadKey::Down); assert_eq!(*key_binds.get(&Keycode::Left).unwrap(), JoypadKey::Left); assert_eq!(*key_binds.get(&Keycode::Right).unwrap(), JoypadKey::Right); assert_eq!(*key_binds.get(&Keycode::Kp1).unwrap(), JoypadKey::Select); assert_eq!(*key_binds.get(&Keycode::Kp3).unwrap(), JoypadKey::Start); assert_eq!(*key_binds.get(&Keycode::E).unwrap(), JoypadKey::A); assert_eq!(*key_binds.get(&Keycode::T).unwrap(), JoypadKey::B); } }
{ use crate::backend::BackendMessage::*; use crate::emulator::EmulationMessage::*; info!("starting the main application thread."); // Input bindings let key_binds = match get_key_bindings::<Keycode>( &config.get_keyboard_binding(), &keycode_from_symbol_hm(), ) { Ok(hm) => hm, Err(why) => { error!("SDL2 backend input : {}", why); return; } }; // Window size let (scale_h, scale_v) = config.compute_display_scale();
identifier_body
sdl2.rs
use self::sdl2::event::Event; use self::sdl2::keyboard::Keycode; use self::sdl2::pixels::{Color, PixelFormatEnum}; use self::sdl2::rect::Rect; use self::sdl2::render::{Texture, TextureCreator, WindowCanvas}; use self::sdl2::video::WindowContext; use sdl2; use std::collections::HashMap; use std::path::Path; use std::sync::mpsc::{Receiver, Sender}; use std::time::{Duration, Instant}; use super::{BackendMessage, EmulatorBackend}; use crate::config::EmulatorAppConfig; use crate::emulator::EmulationMessage; use crate::input::get_key_bindings; use rustboylib::gpu::{RGB, SCREEN_H, SCREEN_W}; /// The SDL 2 backend, using rust-sdl2. pub struct BackendSDL2; impl BackendSDL2 { fn render_display<'a>( tc: &'a TextureCreator<WindowContext>, wc: &mut WindowCanvas, frame_buffer: &[RGB], scale_h: u32, scale_v: u32, ) -> Texture<'a> { let (w, w_scale) = (SCREEN_W as i32, scale_h as i32); let (h, h_scale) = (SCREEN_H as i32, scale_v as i32); let mut texture = tc .create_texture_target( PixelFormatEnum::RGB24, (SCREEN_W as u32) * scale_h, (SCREEN_H as u32) * scale_v, ) .expect("BackendSDL2::render_display: texture creation error"); wc.with_texture_canvas(&mut texture, |texture_canvas| { for y in 0i32..(h as i32) { for x in 0i32..(w as i32) { let color = frame_buffer[(y * w + x) as usize]; texture_canvas.set_draw_color(Color::RGB(color.r, color.g, color.b)); texture_canvas .fill_rect(Rect::new(x * w_scale, y * h_scale, scale_h, scale_v)) .expect("BackendSDL2::render_display: texture canvas fill rect error"); } } }) .expect("BackendSDL2::render_display: texture canvas error"); texture } } impl EmulatorBackend for BackendSDL2 { fn run( &mut self, config: EmulatorAppConfig, tx: Sender<BackendMessage>, rx: Receiver<EmulationMessage>, ) { use crate::backend::BackendMessage::*; use crate::emulator::EmulationMessage::*; info!("starting the main application thread."); // Input bindings let key_binds = match get_key_bindings::<Keycode>( &config.get_keyboard_binding(), &keycode_from_symbol_hm(), ) { Ok(hm) => hm, Err(why) => { error!("SDL2 backend input : {}", why); return; } }; // Window size let (scale_h, scale_v) = config.compute_display_scale(); let w = (SCREEN_W as u32) * (scale_h as u32); let h = (SCREEN_H as u32) * (scale_v as u32); info!("display scale = ({}, {}).", scale_h, scale_v); // SDL 2 initialization let sdl_context = sdl2::init().unwrap(); let ttf_context = sdl2::ttf::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let window = match video_subsystem .window(config.get_title(), w, h) .position_centered() .opengl() .build() { Ok(window) => window, Err(why) => { error!("SDL2 backend failed to create the window : {}", why); return; } }; let mut canvas = window.into_canvas().accelerated().build().unwrap(); let texture_creator = canvas.texture_creator(); canvas.set_draw_color(Color::RGB(0, 0, 0)); canvas.clear(); let mut events = sdl_context.event_pump().unwrap(); let font = ttf_context .load_font(Path::new("assets/OpenSans-Regular.ttf"), 48) .expect("could not load 'assets/OpenSans-Regular.ttf'"); // is the emulation paused? let mut paused = false; // avoid spamming 'Event::KeyDown' events for the same key let mut last_key: Option<Keycode> = None; // FPS count let mut fps = 0; let mut fps_timer = Instant::now(); let one_second = Duration::new(1, 0); let show_fps = config.get_display_fps(); let fps_font_color = Color::RGBA(255, 255, 255, 255); let fps_target_rect = sdl2::rect::Rect::new(0, 0, 70, 40); let fps_surface = font.render("0").blended(fps_font_color).unwrap(); let mut fps_texture = texture_creator .create_texture_from_surface(&fps_surface) .unwrap(); // Main loop 'ui: loop { // Event loop for event in events.poll_iter() { match event { Event::Quit {.. } => { paused = true; tx.send(Quit).unwrap(); } Event::KeyDown { keycode: Some(keycode), .. } => { if last_key.is_some() && keycode == last_key.unwrap() { continue; } match keycode { // quit Keycode::Escape => { paused = true; tx.send(Quit).unwrap(); } // toggle pause Keycode::Return => { paused =!paused; tx.send(UpdateRunStatus(paused)).unwrap(); } _ => { if!paused
} } last_key = Some(keycode); } Event::KeyUp { keycode: Some(keycode), .. } if!paused => { if let Some(keypad_key) = key_binds.get(&keycode) { tx.send(KeyUp(*keypad_key)).unwrap(); } if last_key.is_some() && keycode == last_key.unwrap() { last_key = None; } } _ => continue, } } // Signals from the VM match rx.try_recv() { Ok(emulation_message) => match emulation_message { UpdateDisplay(frame_buffer) => { let texture = BackendSDL2::render_display( &texture_creator, &mut canvas, &frame_buffer, scale_h as u32, scale_v as u32, ); canvas .copy(&texture, None, Some(Rect::new(0, 0, w, h))) .expect("BackendSDL2: canvas texture copy error"); } Finished => break 'ui, }, _ => {} } // FPS count fps += 1; if fps_timer.elapsed() >= one_second { fps_timer = Instant::now(); let text = format!("{}", fps); fps = 0; let surface = font.render(&text[..]).blended(fps_font_color).unwrap(); fps_texture = texture_creator .create_texture_from_surface(&surface) .unwrap(); } if show_fps { canvas .copy(&fps_texture, None, Some(fps_target_rect)) .unwrap(); } canvas.present(); } info!("terminating the main application thread."); } } pub fn keycode_from_symbol_hm() -> HashMap<String, Keycode> { let mut hm = HashMap::new(); hm.insert("Up".into(), Keycode::Up); hm.insert("Down".into(), Keycode::Down); hm.insert("Left".into(), Keycode::Left); hm.insert("Right".into(), Keycode::Right); hm.insert("Numpad0".into(), Keycode::Kp0); hm.insert("Numpad1".into(), Keycode::Kp1); hm.insert("Numpad2".into(), Keycode::Kp2); hm.insert("Numpad3".into(), Keycode::Kp3); hm.insert("Numpad4".into(), Keycode::Kp4); hm.insert("Numpad5".into(), Keycode::Kp5); hm.insert("Numpad6".into(), Keycode::Kp6); hm.insert("Numpad7".into(), Keycode::Kp7); hm.insert("Numpad8".into(), Keycode::Kp8); hm.insert("Numpad9".into(), Keycode::Kp9); hm.insert("NumpadPlus".into(), Keycode::KpPlus); hm.insert("NumpadMinus".into(), Keycode::KpMinus); hm.insert("NumpadMultiply".into(), Keycode::KpMultiply); hm.insert("NumpadDivide".into(), Keycode::KpDivide); // reference : https://wiki.libsdl.org/SDL_Keycode // and : "keycode.rs" from https://github.com/AngryLawyer/rust-sdl2/ let mut sdl2_key_names = Vec::<String>::new(); for c in b'A'..b'Z' + 1 { sdl2_key_names.push((c as char).to_string()); } for i in 1..13 { sdl2_key_names.push(format!("F{}", i)); } // F1-F12 for key_name in sdl2_key_names { let key_code = match Keycode::from_name(&key_name[..]) { Some(code) => code, None => panic!("SDL2 backend : invalid keycode \"{}\"", key_name), }; hm.insert(key_name.clone(), key_code); } hm } #[cfg(test)] mod test { use super::sdl2::keyboard::Keycode; use crate::input::get_key_bindings; use crate::input::KeyboardBinding::FromConfigFile; use rustboylib::joypad::JoypadKey; #[test] fn test_keyboard_hm_from_config() { let keycode_symbol_hm = super::keycode_from_symbol_hm(); let key_binds = get_key_bindings::<Keycode>( &FromConfigFile("tests/backend_input.toml".into()), &keycode_symbol_hm, ) .unwrap(); assert_eq!(*key_binds.get(&Keycode::Up).unwrap(), JoypadKey::Up); assert_eq!(*key_binds.get(&Keycode::Down).unwrap(), JoypadKey::Down); assert_eq!(*key_binds.get(&Keycode::Left).unwrap(), JoypadKey::Left); assert_eq!(*key_binds.get(&Keycode::Right).unwrap(), JoypadKey::Right); assert_eq!(*key_binds.get(&Keycode::Kp1).unwrap(), JoypadKey::Select); assert_eq!(*key_binds.get(&Keycode::Kp3).unwrap(), JoypadKey::Start); assert_eq!(*key_binds.get(&Keycode::E).unwrap(), JoypadKey::A); assert_eq!(*key_binds.get(&Keycode::T).unwrap(), JoypadKey::B); } }
{ if let Some(keypad_key) = key_binds.get(&keycode) { tx.send(KeyDown(*keypad_key)).unwrap(); } }
conditional_block
sdl2.rs
use self::sdl2::event::Event; use self::sdl2::keyboard::Keycode; use self::sdl2::pixels::{Color, PixelFormatEnum}; use self::sdl2::rect::Rect; use self::sdl2::render::{Texture, TextureCreator, WindowCanvas}; use self::sdl2::video::WindowContext; use sdl2; use std::collections::HashMap; use std::path::Path; use std::sync::mpsc::{Receiver, Sender}; use std::time::{Duration, Instant}; use super::{BackendMessage, EmulatorBackend}; use crate::config::EmulatorAppConfig; use crate::emulator::EmulationMessage; use crate::input::get_key_bindings; use rustboylib::gpu::{RGB, SCREEN_H, SCREEN_W}; /// The SDL 2 backend, using rust-sdl2. pub struct
; impl BackendSDL2 { fn render_display<'a>( tc: &'a TextureCreator<WindowContext>, wc: &mut WindowCanvas, frame_buffer: &[RGB], scale_h: u32, scale_v: u32, ) -> Texture<'a> { let (w, w_scale) = (SCREEN_W as i32, scale_h as i32); let (h, h_scale) = (SCREEN_H as i32, scale_v as i32); let mut texture = tc .create_texture_target( PixelFormatEnum::RGB24, (SCREEN_W as u32) * scale_h, (SCREEN_H as u32) * scale_v, ) .expect("BackendSDL2::render_display: texture creation error"); wc.with_texture_canvas(&mut texture, |texture_canvas| { for y in 0i32..(h as i32) { for x in 0i32..(w as i32) { let color = frame_buffer[(y * w + x) as usize]; texture_canvas.set_draw_color(Color::RGB(color.r, color.g, color.b)); texture_canvas .fill_rect(Rect::new(x * w_scale, y * h_scale, scale_h, scale_v)) .expect("BackendSDL2::render_display: texture canvas fill rect error"); } } }) .expect("BackendSDL2::render_display: texture canvas error"); texture } } impl EmulatorBackend for BackendSDL2 { fn run( &mut self, config: EmulatorAppConfig, tx: Sender<BackendMessage>, rx: Receiver<EmulationMessage>, ) { use crate::backend::BackendMessage::*; use crate::emulator::EmulationMessage::*; info!("starting the main application thread."); // Input bindings let key_binds = match get_key_bindings::<Keycode>( &config.get_keyboard_binding(), &keycode_from_symbol_hm(), ) { Ok(hm) => hm, Err(why) => { error!("SDL2 backend input : {}", why); return; } }; // Window size let (scale_h, scale_v) = config.compute_display_scale(); let w = (SCREEN_W as u32) * (scale_h as u32); let h = (SCREEN_H as u32) * (scale_v as u32); info!("display scale = ({}, {}).", scale_h, scale_v); // SDL 2 initialization let sdl_context = sdl2::init().unwrap(); let ttf_context = sdl2::ttf::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let window = match video_subsystem .window(config.get_title(), w, h) .position_centered() .opengl() .build() { Ok(window) => window, Err(why) => { error!("SDL2 backend failed to create the window : {}", why); return; } }; let mut canvas = window.into_canvas().accelerated().build().unwrap(); let texture_creator = canvas.texture_creator(); canvas.set_draw_color(Color::RGB(0, 0, 0)); canvas.clear(); let mut events = sdl_context.event_pump().unwrap(); let font = ttf_context .load_font(Path::new("assets/OpenSans-Regular.ttf"), 48) .expect("could not load 'assets/OpenSans-Regular.ttf'"); // is the emulation paused? let mut paused = false; // avoid spamming 'Event::KeyDown' events for the same key let mut last_key: Option<Keycode> = None; // FPS count let mut fps = 0; let mut fps_timer = Instant::now(); let one_second = Duration::new(1, 0); let show_fps = config.get_display_fps(); let fps_font_color = Color::RGBA(255, 255, 255, 255); let fps_target_rect = sdl2::rect::Rect::new(0, 0, 70, 40); let fps_surface = font.render("0").blended(fps_font_color).unwrap(); let mut fps_texture = texture_creator .create_texture_from_surface(&fps_surface) .unwrap(); // Main loop 'ui: loop { // Event loop for event in events.poll_iter() { match event { Event::Quit {.. } => { paused = true; tx.send(Quit).unwrap(); } Event::KeyDown { keycode: Some(keycode), .. } => { if last_key.is_some() && keycode == last_key.unwrap() { continue; } match keycode { // quit Keycode::Escape => { paused = true; tx.send(Quit).unwrap(); } // toggle pause Keycode::Return => { paused =!paused; tx.send(UpdateRunStatus(paused)).unwrap(); } _ => { if!paused { if let Some(keypad_key) = key_binds.get(&keycode) { tx.send(KeyDown(*keypad_key)).unwrap(); } } } } last_key = Some(keycode); } Event::KeyUp { keycode: Some(keycode), .. } if!paused => { if let Some(keypad_key) = key_binds.get(&keycode) { tx.send(KeyUp(*keypad_key)).unwrap(); } if last_key.is_some() && keycode == last_key.unwrap() { last_key = None; } } _ => continue, } } // Signals from the VM match rx.try_recv() { Ok(emulation_message) => match emulation_message { UpdateDisplay(frame_buffer) => { let texture = BackendSDL2::render_display( &texture_creator, &mut canvas, &frame_buffer, scale_h as u32, scale_v as u32, ); canvas .copy(&texture, None, Some(Rect::new(0, 0, w, h))) .expect("BackendSDL2: canvas texture copy error"); } Finished => break 'ui, }, _ => {} } // FPS count fps += 1; if fps_timer.elapsed() >= one_second { fps_timer = Instant::now(); let text = format!("{}", fps); fps = 0; let surface = font.render(&text[..]).blended(fps_font_color).unwrap(); fps_texture = texture_creator .create_texture_from_surface(&surface) .unwrap(); } if show_fps { canvas .copy(&fps_texture, None, Some(fps_target_rect)) .unwrap(); } canvas.present(); } info!("terminating the main application thread."); } } pub fn keycode_from_symbol_hm() -> HashMap<String, Keycode> { let mut hm = HashMap::new(); hm.insert("Up".into(), Keycode::Up); hm.insert("Down".into(), Keycode::Down); hm.insert("Left".into(), Keycode::Left); hm.insert("Right".into(), Keycode::Right); hm.insert("Numpad0".into(), Keycode::Kp0); hm.insert("Numpad1".into(), Keycode::Kp1); hm.insert("Numpad2".into(), Keycode::Kp2); hm.insert("Numpad3".into(), Keycode::Kp3); hm.insert("Numpad4".into(), Keycode::Kp4); hm.insert("Numpad5".into(), Keycode::Kp5); hm.insert("Numpad6".into(), Keycode::Kp6); hm.insert("Numpad7".into(), Keycode::Kp7); hm.insert("Numpad8".into(), Keycode::Kp8); hm.insert("Numpad9".into(), Keycode::Kp9); hm.insert("NumpadPlus".into(), Keycode::KpPlus); hm.insert("NumpadMinus".into(), Keycode::KpMinus); hm.insert("NumpadMultiply".into(), Keycode::KpMultiply); hm.insert("NumpadDivide".into(), Keycode::KpDivide); // reference : https://wiki.libsdl.org/SDL_Keycode // and : "keycode.rs" from https://github.com/AngryLawyer/rust-sdl2/ let mut sdl2_key_names = Vec::<String>::new(); for c in b'A'..b'Z' + 1 { sdl2_key_names.push((c as char).to_string()); } for i in 1..13 { sdl2_key_names.push(format!("F{}", i)); } // F1-F12 for key_name in sdl2_key_names { let key_code = match Keycode::from_name(&key_name[..]) { Some(code) => code, None => panic!("SDL2 backend : invalid keycode \"{}\"", key_name), }; hm.insert(key_name.clone(), key_code); } hm } #[cfg(test)] mod test { use super::sdl2::keyboard::Keycode; use crate::input::get_key_bindings; use crate::input::KeyboardBinding::FromConfigFile; use rustboylib::joypad::JoypadKey; #[test] fn test_keyboard_hm_from_config() { let keycode_symbol_hm = super::keycode_from_symbol_hm(); let key_binds = get_key_bindings::<Keycode>( &FromConfigFile("tests/backend_input.toml".into()), &keycode_symbol_hm, ) .unwrap(); assert_eq!(*key_binds.get(&Keycode::Up).unwrap(), JoypadKey::Up); assert_eq!(*key_binds.get(&Keycode::Down).unwrap(), JoypadKey::Down); assert_eq!(*key_binds.get(&Keycode::Left).unwrap(), JoypadKey::Left); assert_eq!(*key_binds.get(&Keycode::Right).unwrap(), JoypadKey::Right); assert_eq!(*key_binds.get(&Keycode::Kp1).unwrap(), JoypadKey::Select); assert_eq!(*key_binds.get(&Keycode::Kp3).unwrap(), JoypadKey::Start); assert_eq!(*key_binds.get(&Keycode::E).unwrap(), JoypadKey::A); assert_eq!(*key_binds.get(&Keycode::T).unwrap(), JoypadKey::B); } }
BackendSDL2
identifier_name
main.rs
use std::net::{TcpListener}; use std::io::{BufReader, BufWriter, BufRead, Write}; use std::thread; fn main() { let listener = match TcpListener::bind("127.0.0.1:8888") { Ok(v) => { println!("127.0.0.1:8888 binded."); v }, Err(e) => { panic!("bind failed : {:?}", e) } }; let mut threads = vec![]; for stream in listener.incoming() { let client = match stream { Ok(v) => { println!("new client accepted! {:?}", v.peer_addr().unwrap()); v }, Err(e) => { panic!("accept failed : {:?}", e); } }; let handle = thread::spawn(move || { let mut reader = BufReader::new(&client); let mut writer = BufWriter::new(&client); let mut line = String::new(); loop { match reader.read_line(&mut line) { Ok(_len) if _len > 0 => { println!("[{:?}] {}",
client.peer_addr().unwrap(), line.trim()); }, Ok(_) => { break } Err(e) => { println!("[LOG][ERROR] read error! {:?}", e); break } } write!(writer, "{}", line); match writer.flush() { Err(e) => { println!("[LOG][ERROR] flush error. {:?}", e); }, _ => {} } line.clear(); } println!("client disconnected. {:?}", client.peer_addr().unwrap()); }); threads.push(handle); } for each in threads { match each.join() { Err(e) => { println!("[LOG][ERROR] thread join error. {:?}", e); }, _ => {} } } }
random_line_split
main.rs
use std::net::{TcpListener}; use std::io::{BufReader, BufWriter, BufRead, Write}; use std::thread; fn main()
match reader.read_line(&mut line) { Ok(_len) if _len > 0 => { println!("[{:?}] {}", client.peer_addr().unwrap(), line.trim()); }, Ok(_) => { break } Err(e) => { println!("[LOG][ERROR] read error! {:?}", e); break } } write!(writer, "{}", line); match writer.flush() { Err(e) => { println!("[LOG][ERROR] flush error. {:?}", e); }, _ => {} } line.clear(); } println!("client disconnected. {:?}", client.peer_addr().unwrap()); }); threads.push(handle); } for each in threads { match each.join() { Err(e) => { println!("[LOG][ERROR] thread join error. {:?}", e); }, _ => {} } } }
{ let listener = match TcpListener::bind("127.0.0.1:8888") { Ok(v) => { println!("127.0.0.1:8888 binded."); v }, Err(e) => { panic!("bind failed : {:?}", e) } }; let mut threads = vec![]; for stream in listener.incoming() { let client = match stream { Ok(v) => { println!("new client accepted! {:?}", v.peer_addr().unwrap()); v }, Err(e) => { panic!("accept failed : {:?}", e); } }; let handle = thread::spawn(move || { let mut reader = BufReader::new(&client); let mut writer = BufWriter::new(&client); let mut line = String::new(); loop {
identifier_body
main.rs
use std::net::{TcpListener}; use std::io::{BufReader, BufWriter, BufRead, Write}; use std::thread; fn
() { let listener = match TcpListener::bind("127.0.0.1:8888") { Ok(v) => { println!("127.0.0.1:8888 binded."); v }, Err(e) => { panic!("bind failed : {:?}", e) } }; let mut threads = vec![]; for stream in listener.incoming() { let client = match stream { Ok(v) => { println!("new client accepted! {:?}", v.peer_addr().unwrap()); v }, Err(e) => { panic!("accept failed : {:?}", e); } }; let handle = thread::spawn(move || { let mut reader = BufReader::new(&client); let mut writer = BufWriter::new(&client); let mut line = String::new(); loop { match reader.read_line(&mut line) { Ok(_len) if _len > 0 => { println!("[{:?}] {}", client.peer_addr().unwrap(), line.trim()); }, Ok(_) => { break } Err(e) => { println!("[LOG][ERROR] read error! {:?}", e); break } } write!(writer, "{}", line); match writer.flush() { Err(e) => { println!("[LOG][ERROR] flush error. {:?}", e); }, _ => {} } line.clear(); } println!("client disconnected. {:?}", client.peer_addr().unwrap()); }); threads.push(handle); } for each in threads { match each.join() { Err(e) => { println!("[LOG][ERROR] thread join error. {:?}", e); }, _ => {} } } }
main
identifier_name
main.rs
use std::net::{TcpListener}; use std::io::{BufReader, BufWriter, BufRead, Write}; use std::thread; fn main() { let listener = match TcpListener::bind("127.0.0.1:8888") { Ok(v) => { println!("127.0.0.1:8888 binded."); v }, Err(e) => { panic!("bind failed : {:?}", e) } }; let mut threads = vec![]; for stream in listener.incoming() { let client = match stream { Ok(v) => { println!("new client accepted! {:?}", v.peer_addr().unwrap()); v }, Err(e) => { panic!("accept failed : {:?}", e); } }; let handle = thread::spawn(move || { let mut reader = BufReader::new(&client); let mut writer = BufWriter::new(&client); let mut line = String::new(); loop { match reader.read_line(&mut line) { Ok(_len) if _len > 0 => { println!("[{:?}] {}", client.peer_addr().unwrap(), line.trim()); }, Ok(_) => { break } Err(e) => { println!("[LOG][ERROR] read error! {:?}", e); break } } write!(writer, "{}", line); match writer.flush() { Err(e) => { println!("[LOG][ERROR] flush error. {:?}", e); }, _ => {} } line.clear(); } println!("client disconnected. {:?}", client.peer_addr().unwrap()); }); threads.push(handle); } for each in threads { match each.join() { Err(e) => { println!("[LOG][ERROR] thread join error. {:?}", e); }, _ =>
} } }
{}
conditional_block
scheduler.rs
/* diosix virtual CPU scheduler * * This is, for now, really really simple. * Making it fairer and adaptive to workloads is the ultimate goal. * * (c) Chris Williams, 2018-2021. * * See LICENSE for usage and copying. */ use super::lock::Mutex; use alloc::collections::vec_deque::VecDeque; use hashbrown::hash_map::HashMap; use platform::timer::TimerValue; use super::error::Cause; use super::vcore::{VirtualCore, Priority}; use super::pcore::{self, PhysicalCore, PhysicalCoreID}; use super::hardware; use super::message; use super::capsule::{self, CapsuleState}; pub type TimesliceCount = u64; /* prevent physical CPU time starvation: allow a normal virtual core to run after this number of timeslices have been spent running high priority virtual cores */ const HIGH_PRIO_TIMESLICES_MAX: TimesliceCount = 10; /* max how long a virtual core is allowed to run before a scheduling decision is made */ const TIMESLICE_LENGTH: TimerValue = TimerValue::Milliseconds(50); /* define the shortest time between now and another interrupt and rescheduling decision. this is to stop supervisor kernels spamming the scheduling system with lots of short reschedulings */ const TIMESLICE_MIN_LENGTH: TimerValue = TimerValue::Milliseconds(5); /* duration a system maintence core (one that can't run supervisor code) must wait before looking for fixed work to do. also the length in between application cores can attempt to perform housekeeping */ const MAINTENANCE_LENGTH: TimerValue = TimerValue::Seconds(5); /* these are the global wait queues. while each physical CPU core gets its own pair of high-normal wait queues, virtual cores waiting to be assigned to a physical CPU sit in these global queues. when a physical CPU runs out of queued virtual cores, it pulls one from these global queues. a physical CPU core can ask fellow CPUs to push virtual cores onto the global queues via messages */ lazy_static! { static ref GLOBAL_QUEUES: Mutex<ScheduleQueues> = Mutex::new("global scheduler queue", ScheduleQueues::new()); static ref WORKLOAD: Mutex<HashMap<PhysicalCoreID, usize>> = Mutex::new("workload balancer", HashMap::new()); static ref LAST_HOUSEKEEP_CHECK: Mutex<TimerValue> = Mutex::new("housekeeper tracking", TimerValue::Exact(0)); } #[derive(PartialEq, Clone, Copy, Debug)] pub enum SearchMode { MustFind, /* when searching for something to run, keep looping until successful */ CheckOnce /* search just once for something else to run, return to environment otherwise */ } /* queue a virtual core in global wait list */ pub fn queue(to_queue: VirtualCore) { GLOBAL_QUEUES.lock().queue(to_queue); } /* activate preemptive multitasking. each physical CPU core should call this to start running workloads - be them user/supervisor or management tasks <= returns OK, or error code on failure */ pub fn start() -> Result<(), Cause> { hardware::scheduler_timer_start(); Ok(()) } /* make a decision on whether to run another virtual core, or return to the currently running core (if possible). ping() is called when a scheduler timer IRQ comes in */ pub fn ping() { let time_now = hardware::scheduler_get_timer_now(); let frequency = hardware::scheduler_get_timer_frequency(); if time_now.is_none() || frequency.is_none() { /* check to see if anything needs to run and bail out if no timer hardware can be found (and yet we're still getting IRQs?) */ run_next(SearchMode::CheckOnce); return; } /* get down to the exact timer values */ let frequency = frequency.unwrap(); let time_now = time_now.unwrap().to_exact(frequency); /* if the virtual core we're running is doomed, skip straight to forcing a reschedule of another vcore */ match (pcore::PhysicalCore::this().get_timer_sched_last(), pcore::PhysicalCore::this().is_vcore_doomed()) { (Some(v), false) => { let timeslice_length = TIMESLICE_LENGTH.to_exact(frequency); let mut last_scheduled_at = v.to_exact(frequency); /* if the capsule we're running in is valid then perform a time slice check. if it's not valid, ensure the capsule is torn down or restarted for this virtual core. when all vcores are removed from the capsule, it will either be deleted or restarted, depending on its state */ let capsule_state = capsule::get_current_state(); match capsule_state { Some(CapsuleState::Valid) => { /* check to see if we've reached the end of this physical CPU core's time slice. a virtual code has the pcore for TIMESLICE_LENGTH of time before a mandatory scheduling decision is made */ if time_now - last_scheduled_at >= timeslice_length { /* it's been a while since we last made a decision, so force one now */ run_next(SearchMode::CheckOnce); pcore::PhysicalCore::this().set_timer_sched_last(Some(TimerValue::Exact(time_now))); last_scheduled_at = time_now; } }, _ => { /* it is safe to call destroy_current() and restart_current() multiple times per vcore until the capsule is dead or restarted */ if let Err(_e) = match capsule_state { Some(CapsuleState::Dying) => capsule::destroy_current(), Some(CapsuleState::Restarting) => capsule::restart_current(), _ => Ok(()) } { hvalert!("BUG: Capsule update failure {:?} in scheduler ({:?})", _e, capsule_state) } /* capsule we're running in is no longer valid so force a reschedule */ run_next(SearchMode::MustFind); pcore::PhysicalCore::this().set_timer_sched_last(Some(TimerValue::Exact(time_now))); last_scheduled_at = time_now; } } /* check to make sure timer target is correct for whatever virtual core we're about to run. run_next() may have set a new timer irq target, or changed the virtual core we're running. there may be a supervisor-level timer IRQ upcoming. make sure the physical core timer target value is appropriate. */ if let Some(timer_target) = hardware::scheduler_get_timer_next_at() { let mut timer_target = timer_target.to_exact(frequency); /* avoid skipping over any pending supervisor timer IRQ: reduce latency between capsule timer interrupts being raised and capsule cores scheduled to pick up said IRQs */ if let Some(supervisor_target) = pcore::PhysicalCore::get_virtualcore_timer_target() { timer_target = supervisor_target.to_exact(frequency); } /* if the target is already behind us, discard it and interrupt at end of this timeslice. if the target is too far ahead, curtail it to the end of this timeslice */ if timer_target <= time_now || timer_target > last_scheduled_at + timeslice_length { timer_target = last_scheduled_at + timeslice_length; } hardware::scheduler_timer_at(TimerValue::Exact(timer_target)); } }, /* if not we've not scheduled anything yet, or whatever we were running is now invalid, we must find something (else) to run */ (None, _) | (_, true) => { run_next(SearchMode::MustFind); pcore::PhysicalCore::this().set_timer_sched_last(Some(TimerValue::Exact(time_now))); } } } /* find something else to run, or return to whatever we were running if allowed. call this function when a virtual core's timeslice has expired, or it has crashed or stopped running and we can't return to it. this function will return regardless if this physical CPU core is unable to run virtual cores. => search_mode = define whether or not to continue searching for another virtual core to run, or check once to see if something else is waiting */ fn run_next(search_mode: SearchMode) { /* check for housekeeping */ housekeeping(); /* don't bother scheduling if we can't run the code-to-schedule because there's no supervisor mode support */ if pcore::PhysicalCore::smode_supported() == true { /* check for something to do */ loop { let mut something_found = true; /* check to see if there's anything waiting to be picked up for this physical CPU from a global queue. if so, then adopt it so it can get a chance to run */ match GLOBAL_QUEUES.lock().dequeue() { /* we've found a virtual CPU core to run, so switch to that */ Some(orphan) => { let mut workloads = WORKLOAD.lock(); let pcore_id = PhysicalCore::get_id(); /* increment counter of how many virtual cores this physical CPU core has taken from the global queue */ if let Some(count) = workloads.get_mut(&pcore_id) { *count = *count + 1; } else { workloads.insert(pcore_id, 1); } pcore::context_switch(orphan); }, /* otherwise, try to take a virtual CPU core waiting for this physical CPU core and run it */ _ => match PhysicalCore::dequeue() { Some(virtcore) => pcore::context_switch(virtcore), /* waiting virtual CPU core found, queuing now */ _ => something_found = false /* nothing else to run */ } } /* if we've found something, or only searching once, exit the search loop */ if something_found == true || search_mode == SearchMode::CheckOnce { break; } /* still here? see if there's a capsule waiting to be restarted and give us something to do */ capsulehousekeeper!(); } /* at this point, we've got a virtual core to run. tell the timer system to call us back soon */ hardware::scheduler_timer_next_in(TIMESLICE_LENGTH); } else { hardware::scheduler_timer_next_in(MAINTENANCE_LENGTH); /* we'll be back some time later */ } } /* perform any housekeeping duties defined by the various parts of the system */ fn
() { /* perform integrity checks */ #[cfg(feature = "integritychecks")] { if let Err(val) = pcore::PhysicalCore::integrity_check() { hvalert!("CPU private stack overflowed (0x{:x}). Halting!", val); loop {} } } /* avoid blocking on the house keeping lock */ if LAST_HOUSEKEEP_CHECK.is_locked() == true { return; } let mut last_check = LAST_HOUSEKEEP_CHECK.lock(); /* only perform housekeeping once every MAINTENANCE_LENGTH-long period */ match (hardware::scheduler_get_timer_now(), hardware::scheduler_get_timer_frequency()) { (Some(time_now), Some(frequency)) => { let time_now = time_now.to_exact(frequency); let last_check_value = (*last_check).to_exact(frequency); let maintence_length = MAINTENANCE_LENGTH.to_exact(frequency); /* wait until we're at least MAINTENANCE_LENGTH into boot */ if time_now > maintence_length { if time_now - last_check_value < maintence_length { /* not enough MAINTENANCE_LENGTH time has passed */ return; } /* mark when we last performed housekeeping */ *last_check = TimerValue::Exact(time_now); } else { /* flush debug and bail out */ debughousekeeper!(); return; } }, (_, _) => { /* no timer. output debug and bail out */ debughousekeeper!(); return; } } debughousekeeper!(); /* drain the debug logs to the debug hardware port */ heaphousekeeper!(); /* return any unused regions of physical memory */ physmemhousekeeper!(); /* tidy up any physical memory structures */ capsulehousekeeper!(); /* restart capsules that crashed or rebooted */ /* if the global queues are empty then work out which physical CPU core has the most number of virtual cores and is therefore the busiest */ let global_queue_lock = GLOBAL_QUEUES.lock(); if global_queue_lock.total_queued() > 0 { let mut highest_count = 0; let mut busiest_pcore: Option<PhysicalCoreID> = None; let workloads = WORKLOAD.lock(); for (&pcoreid, &vcore_count) in workloads.iter() { if vcore_count > highest_count { highest_count = vcore_count; busiest_pcore = Some(pcoreid); } } /* ask the busiest core to send one virtual core back to the global queue but only if it has enough to share: it must have more than one virtual core */ if highest_count > 1 { if let Some(pid) = busiest_pcore { if let Ok(m) = message::Message::new(message::Recipient::send_to_pcore(pid), message::MessageContent::DisownQueuedVirtualCore) { match message::send(m) { Err(e) => hvalert!("Failed to message physical CPU {} during load balancing: {:?}", pid, e), Ok(()) => () }; } } } } } /* maintain a simple two-level round-robin scheduler per physical CPU core. we can make it more fancy later. the hypervisor tries to dish out physical CPU time fairly among capsules, and let the capsule supervisors work out how best to allocate their time to userspace code. picking the next virtual CPU core to run should be O(1) or as close as possible to it. */ pub struct ScheduleQueues { high: VecDeque<VirtualCore>, low: VecDeque<VirtualCore>, high_timeslices: TimesliceCount } impl ScheduleQueues { /* initialize a new set of scheduler queues */ pub fn new() -> ScheduleQueues { ScheduleQueues { high: VecDeque::<VirtualCore>::new(), low: VecDeque::<VirtualCore>::new(), high_timeslices: 0 } } /* run the given virtual core by switching to its supervisor context. this also updates NORM_PRIO_TICKS. if the current physical CPU was already running a virtual core, that virtual core is queued up in the waiting list by context_switch() */ pub fn run(&mut self, to_run: VirtualCore) { /* if we're about to run a normal virtual core, then reset counter since a normal virtual core ran. if we're running a non-normal virtual core, then increase the count. */ match to_run.get_priority() { Priority::Normal => self.high_timeslices = 0, Priority::High => self.high_timeslices = self.high_timeslices + 1 }; pcore::context_switch(to_run); } /* add the given virtual core to the appropriate waiting queue. put it to the back so that other virtual cores get a chance to run */ pub fn queue(&mut self, to_queue: VirtualCore) { match to_queue.get_priority() { Priority::High => self.high.push_back(to_queue), Priority::Normal => self.low.push_back(to_queue) } } /* remove a virtual core from the waiting list queues, selected by priority with safeguards to prevent CPU time starvation. Returns selected virtual core or None for no other virtual cores waiting */ pub fn dequeue(&mut self) -> Option<VirtualCore> { /* has a normal virtual core been waiting for ages? */ if self.high_timeslices > HIGH_PRIO_TIMESLICES_MAX { match self.low.pop_front() { Some(t) => return Some(t), None => () }; } /* check the high priority queue for anything waiting. if not, then try the normal priority queue */ match self.high.pop_front() { Some(t) => Some(t), None => self.low.pop_front() } } /* return the total number of virtual cores queued */ pub fn total_queued(&self) -> usize { self.high.len() + self.low.len() } }
housekeeping
identifier_name
scheduler.rs
/* diosix virtual CPU scheduler * * This is, for now, really really simple. * Making it fairer and adaptive to workloads is the ultimate goal. * * (c) Chris Williams, 2018-2021. * * See LICENSE for usage and copying. */ use super::lock::Mutex; use alloc::collections::vec_deque::VecDeque; use hashbrown::hash_map::HashMap; use platform::timer::TimerValue; use super::error::Cause; use super::vcore::{VirtualCore, Priority}; use super::pcore::{self, PhysicalCore, PhysicalCoreID}; use super::hardware; use super::message; use super::capsule::{self, CapsuleState}; pub type TimesliceCount = u64; /* prevent physical CPU time starvation: allow a normal virtual core to run after this number of timeslices have been spent running high priority virtual cores */ const HIGH_PRIO_TIMESLICES_MAX: TimesliceCount = 10; /* max how long a virtual core is allowed to run before a scheduling decision is made */ const TIMESLICE_LENGTH: TimerValue = TimerValue::Milliseconds(50); /* define the shortest time between now and another interrupt and rescheduling decision. this is to stop supervisor kernels spamming the scheduling system with lots of short reschedulings */ const TIMESLICE_MIN_LENGTH: TimerValue = TimerValue::Milliseconds(5); /* duration a system maintence core (one that can't run supervisor code) must wait before looking for fixed work to do. also the length in between application cores can attempt to perform housekeeping */ const MAINTENANCE_LENGTH: TimerValue = TimerValue::Seconds(5); /* these are the global wait queues. while each physical CPU core gets its own pair of high-normal wait queues, virtual cores waiting to be assigned to a physical CPU sit in these global queues. when a physical CPU runs out of queued virtual cores, it pulls one from these global queues. a physical CPU core can ask fellow CPUs to push virtual cores onto the global queues via messages */ lazy_static! { static ref GLOBAL_QUEUES: Mutex<ScheduleQueues> = Mutex::new("global scheduler queue", ScheduleQueues::new()); static ref WORKLOAD: Mutex<HashMap<PhysicalCoreID, usize>> = Mutex::new("workload balancer", HashMap::new()); static ref LAST_HOUSEKEEP_CHECK: Mutex<TimerValue> = Mutex::new("housekeeper tracking", TimerValue::Exact(0)); } #[derive(PartialEq, Clone, Copy, Debug)] pub enum SearchMode { MustFind, /* when searching for something to run, keep looping until successful */ CheckOnce /* search just once for something else to run, return to environment otherwise */ } /* queue a virtual core in global wait list */ pub fn queue(to_queue: VirtualCore) { GLOBAL_QUEUES.lock().queue(to_queue); } /* activate preemptive multitasking. each physical CPU core should call this to start running workloads - be them user/supervisor or management tasks <= returns OK, or error code on failure */ pub fn start() -> Result<(), Cause> { hardware::scheduler_timer_start(); Ok(()) } /* make a decision on whether to run another virtual core, or return to the currently running core (if possible). ping() is called when a scheduler timer IRQ comes in */ pub fn ping()
(Some(v), false) => { let timeslice_length = TIMESLICE_LENGTH.to_exact(frequency); let mut last_scheduled_at = v.to_exact(frequency); /* if the capsule we're running in is valid then perform a time slice check. if it's not valid, ensure the capsule is torn down or restarted for this virtual core. when all vcores are removed from the capsule, it will either be deleted or restarted, depending on its state */ let capsule_state = capsule::get_current_state(); match capsule_state { Some(CapsuleState::Valid) => { /* check to see if we've reached the end of this physical CPU core's time slice. a virtual code has the pcore for TIMESLICE_LENGTH of time before a mandatory scheduling decision is made */ if time_now - last_scheduled_at >= timeslice_length { /* it's been a while since we last made a decision, so force one now */ run_next(SearchMode::CheckOnce); pcore::PhysicalCore::this().set_timer_sched_last(Some(TimerValue::Exact(time_now))); last_scheduled_at = time_now; } }, _ => { /* it is safe to call destroy_current() and restart_current() multiple times per vcore until the capsule is dead or restarted */ if let Err(_e) = match capsule_state { Some(CapsuleState::Dying) => capsule::destroy_current(), Some(CapsuleState::Restarting) => capsule::restart_current(), _ => Ok(()) } { hvalert!("BUG: Capsule update failure {:?} in scheduler ({:?})", _e, capsule_state) } /* capsule we're running in is no longer valid so force a reschedule */ run_next(SearchMode::MustFind); pcore::PhysicalCore::this().set_timer_sched_last(Some(TimerValue::Exact(time_now))); last_scheduled_at = time_now; } } /* check to make sure timer target is correct for whatever virtual core we're about to run. run_next() may have set a new timer irq target, or changed the virtual core we're running. there may be a supervisor-level timer IRQ upcoming. make sure the physical core timer target value is appropriate. */ if let Some(timer_target) = hardware::scheduler_get_timer_next_at() { let mut timer_target = timer_target.to_exact(frequency); /* avoid skipping over any pending supervisor timer IRQ: reduce latency between capsule timer interrupts being raised and capsule cores scheduled to pick up said IRQs */ if let Some(supervisor_target) = pcore::PhysicalCore::get_virtualcore_timer_target() { timer_target = supervisor_target.to_exact(frequency); } /* if the target is already behind us, discard it and interrupt at end of this timeslice. if the target is too far ahead, curtail it to the end of this timeslice */ if timer_target <= time_now || timer_target > last_scheduled_at + timeslice_length { timer_target = last_scheduled_at + timeslice_length; } hardware::scheduler_timer_at(TimerValue::Exact(timer_target)); } }, /* if not we've not scheduled anything yet, or whatever we were running is now invalid, we must find something (else) to run */ (None, _) | (_, true) => { run_next(SearchMode::MustFind); pcore::PhysicalCore::this().set_timer_sched_last(Some(TimerValue::Exact(time_now))); } } } /* find something else to run, or return to whatever we were running if allowed. call this function when a virtual core's timeslice has expired, or it has crashed or stopped running and we can't return to it. this function will return regardless if this physical CPU core is unable to run virtual cores. => search_mode = define whether or not to continue searching for another virtual core to run, or check once to see if something else is waiting */ fn run_next(search_mode: SearchMode) { /* check for housekeeping */ housekeeping(); /* don't bother scheduling if we can't run the code-to-schedule because there's no supervisor mode support */ if pcore::PhysicalCore::smode_supported() == true { /* check for something to do */ loop { let mut something_found = true; /* check to see if there's anything waiting to be picked up for this physical CPU from a global queue. if so, then adopt it so it can get a chance to run */ match GLOBAL_QUEUES.lock().dequeue() { /* we've found a virtual CPU core to run, so switch to that */ Some(orphan) => { let mut workloads = WORKLOAD.lock(); let pcore_id = PhysicalCore::get_id(); /* increment counter of how many virtual cores this physical CPU core has taken from the global queue */ if let Some(count) = workloads.get_mut(&pcore_id) { *count = *count + 1; } else { workloads.insert(pcore_id, 1); } pcore::context_switch(orphan); }, /* otherwise, try to take a virtual CPU core waiting for this physical CPU core and run it */ _ => match PhysicalCore::dequeue() { Some(virtcore) => pcore::context_switch(virtcore), /* waiting virtual CPU core found, queuing now */ _ => something_found = false /* nothing else to run */ } } /* if we've found something, or only searching once, exit the search loop */ if something_found == true || search_mode == SearchMode::CheckOnce { break; } /* still here? see if there's a capsule waiting to be restarted and give us something to do */ capsulehousekeeper!(); } /* at this point, we've got a virtual core to run. tell the timer system to call us back soon */ hardware::scheduler_timer_next_in(TIMESLICE_LENGTH); } else { hardware::scheduler_timer_next_in(MAINTENANCE_LENGTH); /* we'll be back some time later */ } } /* perform any housekeeping duties defined by the various parts of the system */ fn housekeeping() { /* perform integrity checks */ #[cfg(feature = "integritychecks")] { if let Err(val) = pcore::PhysicalCore::integrity_check() { hvalert!("CPU private stack overflowed (0x{:x}). Halting!", val); loop {} } } /* avoid blocking on the house keeping lock */ if LAST_HOUSEKEEP_CHECK.is_locked() == true { return; } let mut last_check = LAST_HOUSEKEEP_CHECK.lock(); /* only perform housekeeping once every MAINTENANCE_LENGTH-long period */ match (hardware::scheduler_get_timer_now(), hardware::scheduler_get_timer_frequency()) { (Some(time_now), Some(frequency)) => { let time_now = time_now.to_exact(frequency); let last_check_value = (*last_check).to_exact(frequency); let maintence_length = MAINTENANCE_LENGTH.to_exact(frequency); /* wait until we're at least MAINTENANCE_LENGTH into boot */ if time_now > maintence_length { if time_now - last_check_value < maintence_length { /* not enough MAINTENANCE_LENGTH time has passed */ return; } /* mark when we last performed housekeeping */ *last_check = TimerValue::Exact(time_now); } else { /* flush debug and bail out */ debughousekeeper!(); return; } }, (_, _) => { /* no timer. output debug and bail out */ debughousekeeper!(); return; } } debughousekeeper!(); /* drain the debug logs to the debug hardware port */ heaphousekeeper!(); /* return any unused regions of physical memory */ physmemhousekeeper!(); /* tidy up any physical memory structures */ capsulehousekeeper!(); /* restart capsules that crashed or rebooted */ /* if the global queues are empty then work out which physical CPU core has the most number of virtual cores and is therefore the busiest */ let global_queue_lock = GLOBAL_QUEUES.lock(); if global_queue_lock.total_queued() > 0 { let mut highest_count = 0; let mut busiest_pcore: Option<PhysicalCoreID> = None; let workloads = WORKLOAD.lock(); for (&pcoreid, &vcore_count) in workloads.iter() { if vcore_count > highest_count { highest_count = vcore_count; busiest_pcore = Some(pcoreid); } } /* ask the busiest core to send one virtual core back to the global queue but only if it has enough to share: it must have more than one virtual core */ if highest_count > 1 { if let Some(pid) = busiest_pcore { if let Ok(m) = message::Message::new(message::Recipient::send_to_pcore(pid), message::MessageContent::DisownQueuedVirtualCore) { match message::send(m) { Err(e) => hvalert!("Failed to message physical CPU {} during load balancing: {:?}", pid, e), Ok(()) => () }; } } } } } /* maintain a simple two-level round-robin scheduler per physical CPU core. we can make it more fancy later. the hypervisor tries to dish out physical CPU time fairly among capsules, and let the capsule supervisors work out how best to allocate their time to userspace code. picking the next virtual CPU core to run should be O(1) or as close as possible to it. */ pub struct ScheduleQueues { high: VecDeque<VirtualCore>, low: VecDeque<VirtualCore>, high_timeslices: TimesliceCount } impl ScheduleQueues { /* initialize a new set of scheduler queues */ pub fn new() -> ScheduleQueues { ScheduleQueues { high: VecDeque::<VirtualCore>::new(), low: VecDeque::<VirtualCore>::new(), high_timeslices: 0 } } /* run the given virtual core by switching to its supervisor context. this also updates NORM_PRIO_TICKS. if the current physical CPU was already running a virtual core, that virtual core is queued up in the waiting list by context_switch() */ pub fn run(&mut self, to_run: VirtualCore) { /* if we're about to run a normal virtual core, then reset counter since a normal virtual core ran. if we're running a non-normal virtual core, then increase the count. */ match to_run.get_priority() { Priority::Normal => self.high_timeslices = 0, Priority::High => self.high_timeslices = self.high_timeslices + 1 }; pcore::context_switch(to_run); } /* add the given virtual core to the appropriate waiting queue. put it to the back so that other virtual cores get a chance to run */ pub fn queue(&mut self, to_queue: VirtualCore) { match to_queue.get_priority() { Priority::High => self.high.push_back(to_queue), Priority::Normal => self.low.push_back(to_queue) } } /* remove a virtual core from the waiting list queues, selected by priority with safeguards to prevent CPU time starvation. Returns selected virtual core or None for no other virtual cores waiting */ pub fn dequeue(&mut self) -> Option<VirtualCore> { /* has a normal virtual core been waiting for ages? */ if self.high_timeslices > HIGH_PRIO_TIMESLICES_MAX { match self.low.pop_front() { Some(t) => return Some(t), None => () }; } /* check the high priority queue for anything waiting. if not, then try the normal priority queue */ match self.high.pop_front() { Some(t) => Some(t), None => self.low.pop_front() } } /* return the total number of virtual cores queued */ pub fn total_queued(&self) -> usize { self.high.len() + self.low.len() } }
{ let time_now = hardware::scheduler_get_timer_now(); let frequency = hardware::scheduler_get_timer_frequency(); if time_now.is_none() || frequency.is_none() { /* check to see if anything needs to run and bail out if no timer hardware can be found (and yet we're still getting IRQs?) */ run_next(SearchMode::CheckOnce); return; } /* get down to the exact timer values */ let frequency = frequency.unwrap(); let time_now = time_now.unwrap().to_exact(frequency); /* if the virtual core we're running is doomed, skip straight to forcing a reschedule of another vcore */ match (pcore::PhysicalCore::this().get_timer_sched_last(), pcore::PhysicalCore::this().is_vcore_doomed()) {
identifier_body
scheduler.rs
/* diosix virtual CPU scheduler * * This is, for now, really really simple. * Making it fairer and adaptive to workloads is the ultimate goal. * * (c) Chris Williams, 2018-2021. * * See LICENSE for usage and copying. */ use super::lock::Mutex; use alloc::collections::vec_deque::VecDeque; use hashbrown::hash_map::HashMap; use platform::timer::TimerValue; use super::error::Cause; use super::vcore::{VirtualCore, Priority}; use super::pcore::{self, PhysicalCore, PhysicalCoreID}; use super::hardware; use super::message; use super::capsule::{self, CapsuleState}; pub type TimesliceCount = u64; /* prevent physical CPU time starvation: allow a normal virtual core to run after this number of timeslices have been spent running high priority virtual cores */ const HIGH_PRIO_TIMESLICES_MAX: TimesliceCount = 10; /* max how long a virtual core is allowed to run before a scheduling decision is made */ const TIMESLICE_LENGTH: TimerValue = TimerValue::Milliseconds(50); /* define the shortest time between now and another interrupt and rescheduling decision. this is to stop supervisor kernels spamming the scheduling system with lots of short reschedulings */ const TIMESLICE_MIN_LENGTH: TimerValue = TimerValue::Milliseconds(5); /* duration a system maintence core (one that can't run supervisor code) must wait before looking for fixed work to do. also the length in between application cores can attempt to perform housekeeping */ const MAINTENANCE_LENGTH: TimerValue = TimerValue::Seconds(5); /* these are the global wait queues. while each physical CPU core gets its own pair of high-normal wait queues, virtual cores waiting to be assigned to a physical CPU sit in these global queues. when a physical CPU runs out of queued virtual cores, it pulls one from these global queues. a physical CPU core can ask fellow CPUs to push virtual cores onto the global queues via messages */ lazy_static! { static ref GLOBAL_QUEUES: Mutex<ScheduleQueues> = Mutex::new("global scheduler queue", ScheduleQueues::new()); static ref WORKLOAD: Mutex<HashMap<PhysicalCoreID, usize>> = Mutex::new("workload balancer", HashMap::new()); static ref LAST_HOUSEKEEP_CHECK: Mutex<TimerValue> = Mutex::new("housekeeper tracking", TimerValue::Exact(0)); } #[derive(PartialEq, Clone, Copy, Debug)] pub enum SearchMode { MustFind, /* when searching for something to run, keep looping until successful */ CheckOnce /* search just once for something else to run, return to environment otherwise */ } /* queue a virtual core in global wait list */ pub fn queue(to_queue: VirtualCore) { GLOBAL_QUEUES.lock().queue(to_queue); } /* activate preemptive multitasking. each physical CPU core should call this to start running workloads - be them user/supervisor or management tasks
Ok(()) } /* make a decision on whether to run another virtual core, or return to the currently running core (if possible). ping() is called when a scheduler timer IRQ comes in */ pub fn ping() { let time_now = hardware::scheduler_get_timer_now(); let frequency = hardware::scheduler_get_timer_frequency(); if time_now.is_none() || frequency.is_none() { /* check to see if anything needs to run and bail out if no timer hardware can be found (and yet we're still getting IRQs?) */ run_next(SearchMode::CheckOnce); return; } /* get down to the exact timer values */ let frequency = frequency.unwrap(); let time_now = time_now.unwrap().to_exact(frequency); /* if the virtual core we're running is doomed, skip straight to forcing a reschedule of another vcore */ match (pcore::PhysicalCore::this().get_timer_sched_last(), pcore::PhysicalCore::this().is_vcore_doomed()) { (Some(v), false) => { let timeslice_length = TIMESLICE_LENGTH.to_exact(frequency); let mut last_scheduled_at = v.to_exact(frequency); /* if the capsule we're running in is valid then perform a time slice check. if it's not valid, ensure the capsule is torn down or restarted for this virtual core. when all vcores are removed from the capsule, it will either be deleted or restarted, depending on its state */ let capsule_state = capsule::get_current_state(); match capsule_state { Some(CapsuleState::Valid) => { /* check to see if we've reached the end of this physical CPU core's time slice. a virtual code has the pcore for TIMESLICE_LENGTH of time before a mandatory scheduling decision is made */ if time_now - last_scheduled_at >= timeslice_length { /* it's been a while since we last made a decision, so force one now */ run_next(SearchMode::CheckOnce); pcore::PhysicalCore::this().set_timer_sched_last(Some(TimerValue::Exact(time_now))); last_scheduled_at = time_now; } }, _ => { /* it is safe to call destroy_current() and restart_current() multiple times per vcore until the capsule is dead or restarted */ if let Err(_e) = match capsule_state { Some(CapsuleState::Dying) => capsule::destroy_current(), Some(CapsuleState::Restarting) => capsule::restart_current(), _ => Ok(()) } { hvalert!("BUG: Capsule update failure {:?} in scheduler ({:?})", _e, capsule_state) } /* capsule we're running in is no longer valid so force a reschedule */ run_next(SearchMode::MustFind); pcore::PhysicalCore::this().set_timer_sched_last(Some(TimerValue::Exact(time_now))); last_scheduled_at = time_now; } } /* check to make sure timer target is correct for whatever virtual core we're about to run. run_next() may have set a new timer irq target, or changed the virtual core we're running. there may be a supervisor-level timer IRQ upcoming. make sure the physical core timer target value is appropriate. */ if let Some(timer_target) = hardware::scheduler_get_timer_next_at() { let mut timer_target = timer_target.to_exact(frequency); /* avoid skipping over any pending supervisor timer IRQ: reduce latency between capsule timer interrupts being raised and capsule cores scheduled to pick up said IRQs */ if let Some(supervisor_target) = pcore::PhysicalCore::get_virtualcore_timer_target() { timer_target = supervisor_target.to_exact(frequency); } /* if the target is already behind us, discard it and interrupt at end of this timeslice. if the target is too far ahead, curtail it to the end of this timeslice */ if timer_target <= time_now || timer_target > last_scheduled_at + timeslice_length { timer_target = last_scheduled_at + timeslice_length; } hardware::scheduler_timer_at(TimerValue::Exact(timer_target)); } }, /* if not we've not scheduled anything yet, or whatever we were running is now invalid, we must find something (else) to run */ (None, _) | (_, true) => { run_next(SearchMode::MustFind); pcore::PhysicalCore::this().set_timer_sched_last(Some(TimerValue::Exact(time_now))); } } } /* find something else to run, or return to whatever we were running if allowed. call this function when a virtual core's timeslice has expired, or it has crashed or stopped running and we can't return to it. this function will return regardless if this physical CPU core is unable to run virtual cores. => search_mode = define whether or not to continue searching for another virtual core to run, or check once to see if something else is waiting */ fn run_next(search_mode: SearchMode) { /* check for housekeeping */ housekeeping(); /* don't bother scheduling if we can't run the code-to-schedule because there's no supervisor mode support */ if pcore::PhysicalCore::smode_supported() == true { /* check for something to do */ loop { let mut something_found = true; /* check to see if there's anything waiting to be picked up for this physical CPU from a global queue. if so, then adopt it so it can get a chance to run */ match GLOBAL_QUEUES.lock().dequeue() { /* we've found a virtual CPU core to run, so switch to that */ Some(orphan) => { let mut workloads = WORKLOAD.lock(); let pcore_id = PhysicalCore::get_id(); /* increment counter of how many virtual cores this physical CPU core has taken from the global queue */ if let Some(count) = workloads.get_mut(&pcore_id) { *count = *count + 1; } else { workloads.insert(pcore_id, 1); } pcore::context_switch(orphan); }, /* otherwise, try to take a virtual CPU core waiting for this physical CPU core and run it */ _ => match PhysicalCore::dequeue() { Some(virtcore) => pcore::context_switch(virtcore), /* waiting virtual CPU core found, queuing now */ _ => something_found = false /* nothing else to run */ } } /* if we've found something, or only searching once, exit the search loop */ if something_found == true || search_mode == SearchMode::CheckOnce { break; } /* still here? see if there's a capsule waiting to be restarted and give us something to do */ capsulehousekeeper!(); } /* at this point, we've got a virtual core to run. tell the timer system to call us back soon */ hardware::scheduler_timer_next_in(TIMESLICE_LENGTH); } else { hardware::scheduler_timer_next_in(MAINTENANCE_LENGTH); /* we'll be back some time later */ } } /* perform any housekeeping duties defined by the various parts of the system */ fn housekeeping() { /* perform integrity checks */ #[cfg(feature = "integritychecks")] { if let Err(val) = pcore::PhysicalCore::integrity_check() { hvalert!("CPU private stack overflowed (0x{:x}). Halting!", val); loop {} } } /* avoid blocking on the house keeping lock */ if LAST_HOUSEKEEP_CHECK.is_locked() == true { return; } let mut last_check = LAST_HOUSEKEEP_CHECK.lock(); /* only perform housekeeping once every MAINTENANCE_LENGTH-long period */ match (hardware::scheduler_get_timer_now(), hardware::scheduler_get_timer_frequency()) { (Some(time_now), Some(frequency)) => { let time_now = time_now.to_exact(frequency); let last_check_value = (*last_check).to_exact(frequency); let maintence_length = MAINTENANCE_LENGTH.to_exact(frequency); /* wait until we're at least MAINTENANCE_LENGTH into boot */ if time_now > maintence_length { if time_now - last_check_value < maintence_length { /* not enough MAINTENANCE_LENGTH time has passed */ return; } /* mark when we last performed housekeeping */ *last_check = TimerValue::Exact(time_now); } else { /* flush debug and bail out */ debughousekeeper!(); return; } }, (_, _) => { /* no timer. output debug and bail out */ debughousekeeper!(); return; } } debughousekeeper!(); /* drain the debug logs to the debug hardware port */ heaphousekeeper!(); /* return any unused regions of physical memory */ physmemhousekeeper!(); /* tidy up any physical memory structures */ capsulehousekeeper!(); /* restart capsules that crashed or rebooted */ /* if the global queues are empty then work out which physical CPU core has the most number of virtual cores and is therefore the busiest */ let global_queue_lock = GLOBAL_QUEUES.lock(); if global_queue_lock.total_queued() > 0 { let mut highest_count = 0; let mut busiest_pcore: Option<PhysicalCoreID> = None; let workloads = WORKLOAD.lock(); for (&pcoreid, &vcore_count) in workloads.iter() { if vcore_count > highest_count { highest_count = vcore_count; busiest_pcore = Some(pcoreid); } } /* ask the busiest core to send one virtual core back to the global queue but only if it has enough to share: it must have more than one virtual core */ if highest_count > 1 { if let Some(pid) = busiest_pcore { if let Ok(m) = message::Message::new(message::Recipient::send_to_pcore(pid), message::MessageContent::DisownQueuedVirtualCore) { match message::send(m) { Err(e) => hvalert!("Failed to message physical CPU {} during load balancing: {:?}", pid, e), Ok(()) => () }; } } } } } /* maintain a simple two-level round-robin scheduler per physical CPU core. we can make it more fancy later. the hypervisor tries to dish out physical CPU time fairly among capsules, and let the capsule supervisors work out how best to allocate their time to userspace code. picking the next virtual CPU core to run should be O(1) or as close as possible to it. */ pub struct ScheduleQueues { high: VecDeque<VirtualCore>, low: VecDeque<VirtualCore>, high_timeslices: TimesliceCount } impl ScheduleQueues { /* initialize a new set of scheduler queues */ pub fn new() -> ScheduleQueues { ScheduleQueues { high: VecDeque::<VirtualCore>::new(), low: VecDeque::<VirtualCore>::new(), high_timeslices: 0 } } /* run the given virtual core by switching to its supervisor context. this also updates NORM_PRIO_TICKS. if the current physical CPU was already running a virtual core, that virtual core is queued up in the waiting list by context_switch() */ pub fn run(&mut self, to_run: VirtualCore) { /* if we're about to run a normal virtual core, then reset counter since a normal virtual core ran. if we're running a non-normal virtual core, then increase the count. */ match to_run.get_priority() { Priority::Normal => self.high_timeslices = 0, Priority::High => self.high_timeslices = self.high_timeslices + 1 }; pcore::context_switch(to_run); } /* add the given virtual core to the appropriate waiting queue. put it to the back so that other virtual cores get a chance to run */ pub fn queue(&mut self, to_queue: VirtualCore) { match to_queue.get_priority() { Priority::High => self.high.push_back(to_queue), Priority::Normal => self.low.push_back(to_queue) } } /* remove a virtual core from the waiting list queues, selected by priority with safeguards to prevent CPU time starvation. Returns selected virtual core or None for no other virtual cores waiting */ pub fn dequeue(&mut self) -> Option<VirtualCore> { /* has a normal virtual core been waiting for ages? */ if self.high_timeslices > HIGH_PRIO_TIMESLICES_MAX { match self.low.pop_front() { Some(t) => return Some(t), None => () }; } /* check the high priority queue for anything waiting. if not, then try the normal priority queue */ match self.high.pop_front() { Some(t) => Some(t), None => self.low.pop_front() } } /* return the total number of virtual cores queued */ pub fn total_queued(&self) -> usize { self.high.len() + self.low.len() } }
<= returns OK, or error code on failure */ pub fn start() -> Result<(), Cause> { hardware::scheduler_timer_start();
random_line_split
types.rs
use std::fmt; use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)] pub enum Severity { Unknown, Low, Medium, High, Critical, } impl Default for Severity { fn default() -> Self { Self::Unknown } } impl fmt::Display for Severity { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match *self { Self::Low => "Low risk", Self::Medium => "Medium risk", Self::High => "High risk", Self::Critical => "Critical risk", Self::Unknown => "Unknown risk", }) } } impl Severity { pub const fn to_color(self) -> term::color::Color { match self { Self::Low => term::color::YELLOW, Self::Medium => term::color::BRIGHT_YELLOW, Self::High => term::color::RED, Self::Critical => term::color::BRIGHT_RED, _ => term::color::WHITE, } } } #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)] pub enum Status { Unknown, #[serde(rename = "Not affected")] NotAffected, Vulnerable, Fixed, Testing, } impl Default for Status { fn
() -> Self { Self::Unknown } } #[derive(Deserialize)] #[serde(transparent)] pub struct Avgs { pub avgs: Vec<Avg>, } #[derive(Serialize, Deserialize, Clone, Default)] pub struct Avg { pub name: String, pub packages: Vec<String>, pub status: Status, #[serde(rename = "type")] pub kind: String, pub severity: Severity, pub fixed: Option<String>, pub issues: Vec<String>, } #[derive(PartialOrd, Ord, PartialEq, Eq)] pub struct Affected { pub package: String, pub cves: Vec<String>, pub severity: Severity, pub status: Status, pub fixed: Option<String>, pub kind: Vec<String>, } impl Affected { pub fn new(package: &str) -> Self { Self { package: package.to_string(), cves: Vec::new(), kind: Vec::new(), severity: Severity::Unknown, status: Status::Unknown, fixed: None, } } }
default
identifier_name
types.rs
use std::fmt; use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)] pub enum Severity { Unknown, Low, Medium, High, Critical, } impl Default for Severity { fn default() -> Self { Self::Unknown } } impl fmt::Display for Severity { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match *self { Self::Low => "Low risk", Self::Medium => "Medium risk", Self::High => "High risk", Self::Critical => "Critical risk", Self::Unknown => "Unknown risk", }) } } impl Severity { pub const fn to_color(self) -> term::color::Color { match self { Self::Low => term::color::YELLOW, Self::Medium => term::color::BRIGHT_YELLOW, Self::High => term::color::RED, Self::Critical => term::color::BRIGHT_RED, _ => term::color::WHITE, } } } #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)] pub enum Status { Unknown, #[serde(rename = "Not affected")] NotAffected, Vulnerable, Fixed, Testing, } impl Default for Status { fn default() -> Self { Self::Unknown } } #[derive(Deserialize)] #[serde(transparent)] pub struct Avgs { pub avgs: Vec<Avg>, } #[derive(Serialize, Deserialize, Clone, Default)] pub struct Avg { pub name: String, pub packages: Vec<String>, pub status: Status, #[serde(rename = "type")] pub kind: String,
#[derive(PartialOrd, Ord, PartialEq, Eq)] pub struct Affected { pub package: String, pub cves: Vec<String>, pub severity: Severity, pub status: Status, pub fixed: Option<String>, pub kind: Vec<String>, } impl Affected { pub fn new(package: &str) -> Self { Self { package: package.to_string(), cves: Vec::new(), kind: Vec::new(), severity: Severity::Unknown, status: Status::Unknown, fixed: None, } } }
pub severity: Severity, pub fixed: Option<String>, pub issues: Vec<String>, }
random_line_split
main.rs
#[macro_use] extern crate clap; extern crate sdl2; use clap::App; use sdl2::event::Event; use std::fs::File; use std::path::Path; use std::thread; use std::time::Duration; mod cpu; mod display; mod emulator; mod keypad; mod memory; mod speaker; use crate::cpu::*; use crate::display::*; use crate::emulator::Emulator; use crate::keypad::*; fn main() { // Load configuration // TODO: Implement memory_size, display_width and display_height parameters let yaml = load_yaml!("cli.yml"); let parameters = App::from_yaml(yaml).get_matches(); let rom = parameters.value_of("rom").unwrap(); let clock_rate = value_t!(parameters, "clock_rate", f32).unwrap(); let ignore_unknown_instructions = parameters.is_present("ignore_unknown_instructions"); let program_address = value_t!(parameters, "program_address", usize).unwrap(); let display_scale = value_t!(parameters, "display_scale", u8).unwrap(); let sound = parameters.is_present("sound"); let debug_cpu = parameters.is_present("debug_cpu"); let debug_memory = parameters.is_present("debug_memory"); if clock_rate <= 0.0 { panic!("parameter \"clock_rate\" must be > 0"); } if display_scale <= 0 { panic!("parameter \"display_scale\" must be > 0"); } // Initialize emulator let mut emulator = Emulator::new( clock_rate, ignore_unknown_instructions, program_address, display_scale, ); let mut rom_file = match File::open(&Path::new(rom)) { Ok(rom_file) => rom_file,
Err(_) => panic!("The specified ROM file does not exist"), }; emulator.load_rom(&mut rom_file).unwrap(); // Initialize rodeo // This needs to be done before SDL2 initialization: https://github.com/RustAudio/rodio/issues/214 rodio::default_output_device(); // Initialize SDL2 let sdl2_context = sdl2::init().unwrap(); let mut sdl2_events = sdl2_context.event_pump().unwrap(); let sdl2_timing = sdl2_context.timer().unwrap(); let sdl2_video = sdl2_context.video().unwrap(); let window = emulator.display.create_window(&sdl2_video, rom); let mut renderer = window.into_canvas().build().unwrap(); // Game loop let mut last_step_time = get_time(&sdl2_timing); 'running: loop { let processing_start = get_time(&sdl2_timing); // Events for event in sdl2_events.poll_iter() { match event { Event::Quit {.. } => break 'running, Event::KeyDown { keycode: Some(keycode), .. } => emulator.keypad.key_down(keycode), Event::KeyUp { keycode: Some(keycode), .. } => emulator.keypad.key_up(keycode), _ => (), } } // Emulation let delta_time = (get_time(&sdl2_timing) - last_step_time) * 1000 / sdl2_timing.performance_frequency(); emulator.step( delta_time as f32, &mut renderer, sound, debug_cpu, debug_memory, ); let frame_wait_duration = 1.0 / emulator.cpu.get_clock_rate() * 1000.0; let processing_time = (get_time(&sdl2_timing) - processing_start) * 1000 / sdl2_timing.performance_frequency(); let sleep_time = if frame_wait_duration as u32 > processing_time as u32 { frame_wait_duration as u32 - processing_time as u32 } else { 0 }; last_step_time = get_time(&sdl2_timing); thread::sleep(Duration::new(0, sleep_time * 1000000)); } } fn get_time(sdl2_timing: &sdl2::TimerSubsystem) -> u64 { sdl2_timing.performance_counter() }
random_line_split
main.rs
#[macro_use] extern crate clap; extern crate sdl2; use clap::App; use sdl2::event::Event; use std::fs::File; use std::path::Path; use std::thread; use std::time::Duration; mod cpu; mod display; mod emulator; mod keypad; mod memory; mod speaker; use crate::cpu::*; use crate::display::*; use crate::emulator::Emulator; use crate::keypad::*; fn main() { // Load configuration // TODO: Implement memory_size, display_width and display_height parameters let yaml = load_yaml!("cli.yml"); let parameters = App::from_yaml(yaml).get_matches(); let rom = parameters.value_of("rom").unwrap(); let clock_rate = value_t!(parameters, "clock_rate", f32).unwrap(); let ignore_unknown_instructions = parameters.is_present("ignore_unknown_instructions"); let program_address = value_t!(parameters, "program_address", usize).unwrap(); let display_scale = value_t!(parameters, "display_scale", u8).unwrap(); let sound = parameters.is_present("sound"); let debug_cpu = parameters.is_present("debug_cpu"); let debug_memory = parameters.is_present("debug_memory"); if clock_rate <= 0.0 { panic!("parameter \"clock_rate\" must be > 0"); } if display_scale <= 0 { panic!("parameter \"display_scale\" must be > 0"); } // Initialize emulator let mut emulator = Emulator::new( clock_rate, ignore_unknown_instructions, program_address, display_scale, ); let mut rom_file = match File::open(&Path::new(rom)) { Ok(rom_file) => rom_file, Err(_) => panic!("The specified ROM file does not exist"), }; emulator.load_rom(&mut rom_file).unwrap(); // Initialize rodeo // This needs to be done before SDL2 initialization: https://github.com/RustAudio/rodio/issues/214 rodio::default_output_device(); // Initialize SDL2 let sdl2_context = sdl2::init().unwrap(); let mut sdl2_events = sdl2_context.event_pump().unwrap(); let sdl2_timing = sdl2_context.timer().unwrap(); let sdl2_video = sdl2_context.video().unwrap(); let window = emulator.display.create_window(&sdl2_video, rom); let mut renderer = window.into_canvas().build().unwrap(); // Game loop let mut last_step_time = get_time(&sdl2_timing); 'running: loop { let processing_start = get_time(&sdl2_timing); // Events for event in sdl2_events.poll_iter() { match event { Event::Quit {.. } => break 'running, Event::KeyDown { keycode: Some(keycode), .. } => emulator.keypad.key_down(keycode), Event::KeyUp { keycode: Some(keycode), .. } => emulator.keypad.key_up(keycode), _ => (), } } // Emulation let delta_time = (get_time(&sdl2_timing) - last_step_time) * 1000 / sdl2_timing.performance_frequency(); emulator.step( delta_time as f32, &mut renderer, sound, debug_cpu, debug_memory, ); let frame_wait_duration = 1.0 / emulator.cpu.get_clock_rate() * 1000.0; let processing_time = (get_time(&sdl2_timing) - processing_start) * 1000 / sdl2_timing.performance_frequency(); let sleep_time = if frame_wait_duration as u32 > processing_time as u32 { frame_wait_duration as u32 - processing_time as u32 } else { 0 }; last_step_time = get_time(&sdl2_timing); thread::sleep(Duration::new(0, sleep_time * 1000000)); } } fn get_time(sdl2_timing: &sdl2::TimerSubsystem) -> u64
{ sdl2_timing.performance_counter() }
identifier_body
main.rs
#[macro_use] extern crate clap; extern crate sdl2; use clap::App; use sdl2::event::Event; use std::fs::File; use std::path::Path; use std::thread; use std::time::Duration; mod cpu; mod display; mod emulator; mod keypad; mod memory; mod speaker; use crate::cpu::*; use crate::display::*; use crate::emulator::Emulator; use crate::keypad::*; fn main() { // Load configuration // TODO: Implement memory_size, display_width and display_height parameters let yaml = load_yaml!("cli.yml"); let parameters = App::from_yaml(yaml).get_matches(); let rom = parameters.value_of("rom").unwrap(); let clock_rate = value_t!(parameters, "clock_rate", f32).unwrap(); let ignore_unknown_instructions = parameters.is_present("ignore_unknown_instructions"); let program_address = value_t!(parameters, "program_address", usize).unwrap(); let display_scale = value_t!(parameters, "display_scale", u8).unwrap(); let sound = parameters.is_present("sound"); let debug_cpu = parameters.is_present("debug_cpu"); let debug_memory = parameters.is_present("debug_memory"); if clock_rate <= 0.0 { panic!("parameter \"clock_rate\" must be > 0"); } if display_scale <= 0 { panic!("parameter \"display_scale\" must be > 0"); } // Initialize emulator let mut emulator = Emulator::new( clock_rate, ignore_unknown_instructions, program_address, display_scale, ); let mut rom_file = match File::open(&Path::new(rom)) { Ok(rom_file) => rom_file, Err(_) => panic!("The specified ROM file does not exist"), }; emulator.load_rom(&mut rom_file).unwrap(); // Initialize rodeo // This needs to be done before SDL2 initialization: https://github.com/RustAudio/rodio/issues/214 rodio::default_output_device(); // Initialize SDL2 let sdl2_context = sdl2::init().unwrap(); let mut sdl2_events = sdl2_context.event_pump().unwrap(); let sdl2_timing = sdl2_context.timer().unwrap(); let sdl2_video = sdl2_context.video().unwrap(); let window = emulator.display.create_window(&sdl2_video, rom); let mut renderer = window.into_canvas().build().unwrap(); // Game loop let mut last_step_time = get_time(&sdl2_timing); 'running: loop { let processing_start = get_time(&sdl2_timing); // Events for event in sdl2_events.poll_iter() { match event { Event::Quit {.. } => break 'running, Event::KeyDown { keycode: Some(keycode), .. } => emulator.keypad.key_down(keycode), Event::KeyUp { keycode: Some(keycode), .. } => emulator.keypad.key_up(keycode), _ => (), } } // Emulation let delta_time = (get_time(&sdl2_timing) - last_step_time) * 1000 / sdl2_timing.performance_frequency(); emulator.step( delta_time as f32, &mut renderer, sound, debug_cpu, debug_memory, ); let frame_wait_duration = 1.0 / emulator.cpu.get_clock_rate() * 1000.0; let processing_time = (get_time(&sdl2_timing) - processing_start) * 1000 / sdl2_timing.performance_frequency(); let sleep_time = if frame_wait_duration as u32 > processing_time as u32 { frame_wait_duration as u32 - processing_time as u32 } else { 0 }; last_step_time = get_time(&sdl2_timing); thread::sleep(Duration::new(0, sleep_time * 1000000)); } } fn
(sdl2_timing: &sdl2::TimerSubsystem) -> u64 { sdl2_timing.performance_counter() }
get_time
identifier_name
calendar.rs
// Evelyn: Your personal assistant, project manager and calendar // Copyright (C) 2017 Gregory Jensen // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use core::calendar; use core::error_messages::{EvelynBaseError, EvelynServiceError}; use model; use model::calendar as calendar_model; use processing; use serde_json; use server::routing::{RouterInput, RouterOutput}; use std::sync::Arc;
match request_model_de { Ok(request_model) => { let session_token_model = validate_session!(processor_data, request_model); match calendar::calendar_add_event(request_model, session_token_model, processor_data) { None => { RouterOutput { response_body: serde_json::to_string(&calendar_model::CalendarAddEventResponseModel { error: None, }) .unwrap(), } }, Some(e) => { RouterOutput { response_body: serde_json::to_string(&calendar_model::CalendarAddEventResponseModel { error: Some(From::from(EvelynServiceError::AddCalendarEvent(e))), }) .unwrap(), } }, } }, Err(e) => { trace!("{}", e); let response = calendar_model::CalendarAddEventResponseModel { error: Some(From::from(EvelynServiceError::CouldNotDecodeTheRequestPayload(e))), }; RouterOutput { response_body: serde_json::to_string(&response).unwrap(), } }, } }
pub fn calendar_add_event_processor( router_input: RouterInput, processor_data: Arc<processing::ProcessorData>, ) -> RouterOutput { let request_model_de: Result<calendar_model::CalendarAddEventRequestModel, _> = serde_json::from_str(&router_input.request_body);
random_line_split
calendar.rs
// Evelyn: Your personal assistant, project manager and calendar // Copyright (C) 2017 Gregory Jensen // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use core::calendar; use core::error_messages::{EvelynBaseError, EvelynServiceError}; use model; use model::calendar as calendar_model; use processing; use serde_json; use server::routing::{RouterInput, RouterOutput}; use std::sync::Arc; pub fn calendar_add_event_processor( router_input: RouterInput, processor_data: Arc<processing::ProcessorData>, ) -> RouterOutput { let request_model_de: Result<calendar_model::CalendarAddEventRequestModel, _> = serde_json::from_str(&router_input.request_body); match request_model_de { Ok(request_model) =>
} } , Err(e) => { trace!("{}", e); let response = calendar_model::CalendarAddEventResponseModel { error: Some(From::from(EvelynServiceError::CouldNotDecodeTheRequestPayload(e))), }; RouterOutput { response_body: serde_json::to_string(&response).unwrap(), } }, } }
{ let session_token_model = validate_session!(processor_data, request_model); match calendar::calendar_add_event(request_model, session_token_model, processor_data) { None => { RouterOutput { response_body: serde_json::to_string(&calendar_model::CalendarAddEventResponseModel { error: None, }) .unwrap(), } }, Some(e) => { RouterOutput { response_body: serde_json::to_string(&calendar_model::CalendarAddEventResponseModel { error: Some(From::from(EvelynServiceError::AddCalendarEvent(e))), }) .unwrap(), } },
conditional_block
calendar.rs
// Evelyn: Your personal assistant, project manager and calendar // Copyright (C) 2017 Gregory Jensen // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use core::calendar; use core::error_messages::{EvelynBaseError, EvelynServiceError}; use model; use model::calendar as calendar_model; use processing; use serde_json; use server::routing::{RouterInput, RouterOutput}; use std::sync::Arc; pub fn
( router_input: RouterInput, processor_data: Arc<processing::ProcessorData>, ) -> RouterOutput { let request_model_de: Result<calendar_model::CalendarAddEventRequestModel, _> = serde_json::from_str(&router_input.request_body); match request_model_de { Ok(request_model) => { let session_token_model = validate_session!(processor_data, request_model); match calendar::calendar_add_event(request_model, session_token_model, processor_data) { None => { RouterOutput { response_body: serde_json::to_string(&calendar_model::CalendarAddEventResponseModel { error: None, }) .unwrap(), } }, Some(e) => { RouterOutput { response_body: serde_json::to_string(&calendar_model::CalendarAddEventResponseModel { error: Some(From::from(EvelynServiceError::AddCalendarEvent(e))), }) .unwrap(), } }, } }, Err(e) => { trace!("{}", e); let response = calendar_model::CalendarAddEventResponseModel { error: Some(From::from(EvelynServiceError::CouldNotDecodeTheRequestPayload(e))), }; RouterOutput { response_body: serde_json::to_string(&response).unwrap(), } }, } }
calendar_add_event_processor
identifier_name
calendar.rs
// Evelyn: Your personal assistant, project manager and calendar // Copyright (C) 2017 Gregory Jensen // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use core::calendar; use core::error_messages::{EvelynBaseError, EvelynServiceError}; use model; use model::calendar as calendar_model; use processing; use serde_json; use server::routing::{RouterInput, RouterOutput}; use std::sync::Arc; pub fn calendar_add_event_processor( router_input: RouterInput, processor_data: Arc<processing::ProcessorData>, ) -> RouterOutput
}) .unwrap(), } }, } }, Err(e) => { trace!("{}", e); let response = calendar_model::CalendarAddEventResponseModel { error: Some(From::from(EvelynServiceError::CouldNotDecodeTheRequestPayload(e))), }; RouterOutput { response_body: serde_json::to_string(&response).unwrap(), } }, } }
{ let request_model_de: Result<calendar_model::CalendarAddEventRequestModel, _> = serde_json::from_str(&router_input.request_body); match request_model_de { Ok(request_model) => { let session_token_model = validate_session!(processor_data, request_model); match calendar::calendar_add_event(request_model, session_token_model, processor_data) { None => { RouterOutput { response_body: serde_json::to_string(&calendar_model::CalendarAddEventResponseModel { error: None, }) .unwrap(), } }, Some(e) => { RouterOutput { response_body: serde_json::to_string(&calendar_model::CalendarAddEventResponseModel { error: Some(From::from(EvelynServiceError::AddCalendarEvent(e))),
identifier_body
expr-if-struct.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. // -*- rust -*- // Tests for if as expressions returning nominal types struct I { i: int } fn test_rec() { let rs = if true { I {i: 100} } else
; assert!((rs.i == 100)); } enum mood { happy, sad, } impl cmp::Eq for mood { fn eq(&self, other: &mood) -> bool { ((*self) as uint) == ((*other) as uint) } fn ne(&self, other: &mood) -> bool {!(*self).eq(other) } } fn test_tag() { let rs = if true { happy } else { sad }; assert!((rs == happy)); } pub fn main() { test_rec(); test_tag(); }
{ I {i: 101} }
conditional_block
expr-if-struct.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.
// -*- rust -*- // Tests for if as expressions returning nominal types struct I { i: int } fn test_rec() { let rs = if true { I {i: 100} } else { I {i: 101} }; assert!((rs.i == 100)); } enum mood { happy, sad, } impl cmp::Eq for mood { fn eq(&self, other: &mood) -> bool { ((*self) as uint) == ((*other) as uint) } fn ne(&self, other: &mood) -> bool {!(*self).eq(other) } } fn test_tag() { let rs = if true { happy } else { sad }; assert!((rs == happy)); } pub fn main() { test_rec(); test_tag(); }
random_line_split
expr-if-struct.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. // -*- rust -*- // Tests for if as expressions returning nominal types struct I { i: int } fn test_rec() { let rs = if true { I {i: 100} } else { I {i: 101} }; assert!((rs.i == 100)); } enum mood { happy, sad, } impl cmp::Eq for mood { fn eq(&self, other: &mood) -> bool { ((*self) as uint) == ((*other) as uint) } fn ne(&self, other: &mood) -> bool {!(*self).eq(other) } } fn test_tag() { let rs = if true { happy } else { sad }; assert!((rs == happy)); } pub fn
() { test_rec(); test_tag(); }
main
identifier_name
logger.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use rocksdb::{DBInfoLogLevel as InfoLogLevel, Logger}; // TODO(yiwu): abstract the Logger interface. #[derive(Default)] pub struct RocksdbLogger; impl Logger for RocksdbLogger { fn logv(&self, log_level: InfoLogLevel, log: &str) { match log_level { InfoLogLevel::Header => info!(#"rocksdb_log_header", "{}", log), InfoLogLevel::Debug => debug!(#"rocksdb_log", "{}", log), InfoLogLevel::Info => info!(#"rocksdb_log", "{}", log), InfoLogLevel::Warn => warn!(#"rocksdb_log", "{}", log), InfoLogLevel::Error => error!(#"rocksdb_log", "{}", log), InfoLogLevel::Fatal => crit!(#"rocksdb_log", "{}", log), _ => {} } } } #[derive(Default)] pub struct RaftDBLogger; impl Logger for RaftDBLogger { fn
(&self, log_level: InfoLogLevel, log: &str) { match log_level { InfoLogLevel::Header => info!(#"raftdb_log_header", "{}", log), InfoLogLevel::Debug => debug!(#"raftdb_log", "{}", log), InfoLogLevel::Info => info!(#"raftdb_log", "{}", log), InfoLogLevel::Warn => warn!(#"raftdb_log", "{}", log), InfoLogLevel::Error => error!(#"raftdb_log", "{}", log), InfoLogLevel::Fatal => crit!(#"raftdb_log", "{}", log), _ => {} } } }
logv
identifier_name
logger.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use rocksdb::{DBInfoLogLevel as InfoLogLevel, Logger}; // TODO(yiwu): abstract the Logger interface. #[derive(Default)] pub struct RocksdbLogger; impl Logger for RocksdbLogger { fn logv(&self, log_level: InfoLogLevel, log: &str) { match log_level { InfoLogLevel::Header => info!(#"rocksdb_log_header", "{}", log), InfoLogLevel::Debug => debug!(#"rocksdb_log", "{}", log), InfoLogLevel::Info => info!(#"rocksdb_log", "{}", log), InfoLogLevel::Warn => warn!(#"rocksdb_log", "{}", log),
} } } #[derive(Default)] pub struct RaftDBLogger; impl Logger for RaftDBLogger { fn logv(&self, log_level: InfoLogLevel, log: &str) { match log_level { InfoLogLevel::Header => info!(#"raftdb_log_header", "{}", log), InfoLogLevel::Debug => debug!(#"raftdb_log", "{}", log), InfoLogLevel::Info => info!(#"raftdb_log", "{}", log), InfoLogLevel::Warn => warn!(#"raftdb_log", "{}", log), InfoLogLevel::Error => error!(#"raftdb_log", "{}", log), InfoLogLevel::Fatal => crit!(#"raftdb_log", "{}", log), _ => {} } } }
InfoLogLevel::Error => error!(#"rocksdb_log", "{}", log), InfoLogLevel::Fatal => crit!(#"rocksdb_log", "{}", log), _ => {}
random_line_split
logger.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use rocksdb::{DBInfoLogLevel as InfoLogLevel, Logger}; // TODO(yiwu): abstract the Logger interface. #[derive(Default)] pub struct RocksdbLogger; impl Logger for RocksdbLogger { fn logv(&self, log_level: InfoLogLevel, log: &str) { match log_level { InfoLogLevel::Header => info!(#"rocksdb_log_header", "{}", log), InfoLogLevel::Debug => debug!(#"rocksdb_log", "{}", log), InfoLogLevel::Info => info!(#"rocksdb_log", "{}", log), InfoLogLevel::Warn => warn!(#"rocksdb_log", "{}", log), InfoLogLevel::Error => error!(#"rocksdb_log", "{}", log), InfoLogLevel::Fatal => crit!(#"rocksdb_log", "{}", log), _ => {} } } } #[derive(Default)] pub struct RaftDBLogger; impl Logger for RaftDBLogger { fn logv(&self, log_level: InfoLogLevel, log: &str)
}
{ match log_level { InfoLogLevel::Header => info!(#"raftdb_log_header", "{}", log), InfoLogLevel::Debug => debug!(#"raftdb_log", "{}", log), InfoLogLevel::Info => info!(#"raftdb_log", "{}", log), InfoLogLevel::Warn => warn!(#"raftdb_log", "{}", log), InfoLogLevel::Error => error!(#"raftdb_log", "{}", log), InfoLogLevel::Fatal => crit!(#"raftdb_log", "{}", log), _ => {} } }
identifier_body
mod.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA.
pub mod nfs_records; pub mod nfs2_records; pub mod nfs3_records; pub mod nfs4_records; pub mod nfs4; pub mod nfs; pub mod log; //#[cfg(feature = "lua")] //pub mod lua;
*/ pub mod types; pub mod rpc_records;
random_line_split
pair.rs
use error::{NcclError, ErrorKind}; use value::Value; use ::TryInto; use std::ops::{Index, IndexMut}; use std::error::Error; /// Struct that contains configuration information. /// /// Examples: /// /// ``` /// let p = nccl::parse_file("examples/config.nccl").unwrap(); /// let ports = p["server"]["port"].keys_as::<i64>().unwrap(); /// /// println!("Operating on ports:"); /// for port in ports.iter() { /// println!(" {}", port); /// } /// ``` #[derive(Clone, Debug, PartialEq)] pub struct Pair { key: Value, value: Vec<Pair> } impl Pair { /// Creates a new Pair. pub fn new<T: Into<Value>>(key: T) -> Self { Pair { key: key.into(), value: vec![] } } /// Adds a value to a Pair. /// /// Examples: /// /// ``` /// let mut p = nccl::Pair::new("hello"); /// p.add(true); /// p.add("world"); /// ``` pub fn add<T: Into<Value>>(&mut self, value: T) { self.value.push(Pair::new(value.into())); } /// Recursively adds a slice to a Pair. pub fn add_slice(&mut self, path: &[Value]) { let s = self.traverse_path(&path[0..path.len() - 1]); if!s.has_key(&path[path.len() - 1]) { s.add(&path[path.len() - 1]); } } /// Adds a Pair to a Pair. pub fn add_pair(&mut self, pair: Pair)
/// Test if a pair has a key. /// /// Examples: /// /// ``` /// use nccl::NcclError; /// let mut p = nccl::parse_file("examples/config.nccl").unwrap(); /// assert!(p.has_key("server")); /// assert!(p["server"]["port"].has_key(80)); /// ``` pub fn has_key<T>(&self, key: T) -> bool where Value: From<T> { let k = key.into(); for item in &self.value { if item.key == k { return true; } } false } /// Test if a pair has a path of values. Use `vec_into!` to make /// this method easier to use. /// /// Examples: /// /// ``` /// # #[macro_use] extern crate nccl; fn main() { /// let mut p = nccl::parse_file("examples/config.nccl").unwrap(); /// assert!(p.has_path(vec_into!["server", "port", 80])); /// # } /// ``` pub fn has_path(&self, path: Vec<Value>) -> bool { if path.is_empty() { true } else if self.has_key(path[0].clone()) { self[path[0].clone()].has_path(path[1..path.len()].to_vec()) } else { false } } /// Traverses a Pair using a slice, adding the item if it does not exist. pub fn traverse_path(&mut self, path: &[Value]) -> &mut Pair { if path.is_empty() { self } else { if!self.has_key(&path[0]) { self.add(&path[0]); } self.get(&path[0]).unwrap().traverse_path(&path[1..path.len()]) } } /// Gets a child Pair from a Pair. Used by Pair's implementation of Index. /// /// ``` /// let mut p = nccl::Pair::new("top_level"); /// p.add("hello!"); /// p.get("hello!").unwrap(); /// ``` pub fn get<T>(&mut self, value: T) -> Result<&mut Pair, Box<dyn Error>> where Value: From<T> { let v = value.into(); if self.value.is_empty() { return Err(Box::new(NcclError::new(ErrorKind::KeyNotFound, &format!("Pair does not have key: {}", v), 0))); } else { for item in &mut self.value { if item.key == v { return Ok(item); } } } Err(Box::new(NcclError::new(ErrorKind::KeyNotFound, &format!("Could not find key: {}", v), 0))) } /// Gets a mutable child Pair from a Pair. Used by Pair's implementation of /// IndexMut. /// /// ``` /// let mut p = nccl::Pair::new("top_level"); /// p.add(32); /// p.get(32).unwrap(); /// ``` pub fn get_ref<T>(&self, value: T) -> Result<&Pair, Box<dyn Error>> where Value: From<T> { let v = value.into(); if self.value.is_empty() { return Ok(self); } else { for item in &self.value { if item.key == v { return Ok(item); } } } Err(Box::new(NcclError::new(ErrorKind::KeyNotFound, &format!("Could not find key: {}", v), 0))) } /// Returns the value of a pair as a string. /// ``` /// let config = nccl::parse_file("examples/long.nccl").unwrap(); /// assert_eq!(config["bool too"].value().unwrap(), "false"); /// ``` pub fn value(&self) -> Option<String> { if self.value.len() == 1 { Some(format!("{}", self.value[0].key.clone())) } else { None } } /// Returns the value of the key or a default value. pub fn value_or(&self, or: String) -> String { self.value().unwrap_or(or) } fn value_raw(&self) -> Option<Value> { if self.value.len() == 1 { Some(self.value[0].key.clone()) } else { None } } /// Gets the value of a key as a specified type, if there is only one. /// /// Examples: /// /// ``` /// let p = nccl::parse_file("examples/long.nccl").unwrap(); /// assert!(!p["bool too"].value_as::<bool>().unwrap()); /// ``` pub fn value_as<T>(&self) -> Result<T, Box<dyn Error>> where Value: TryInto<T> { match self.value_raw() { Some(v) => match v.try_into() { Ok(t) => Ok(t), Err(_) => Err(Box::new(NcclError::new(ErrorKind::IntoError, "Could not convert to T", 0))) }, None => Err(Box::new(NcclError::new(ErrorKind::MultipleValues, "Could not convert value: multiple values. Use keys() or keys_as()", 0))) } } /// Gets the value of a key as a specified type or a default value. pub fn value_as_or<T>(&self, or: T) -> T where Value: TryInto<T> { self.value_as::<T>().unwrap_or(or) } fn keys(&self) -> Vec<Value> { self.value.clone().into_iter().map(|x| x.key).collect() } /// Gets keys of a value as a vector of T. /// /// Examples: /// /// ``` /// let config = nccl::parse_file("examples/config.nccl").unwrap(); /// let ports = config["server"]["port"].keys_as::<i64>().unwrap(); /// assert_eq!(ports, vec![80, 443]); /// ``` pub fn keys_as<T>(&self) -> Result<Vec<T>, Box<dyn Error>> where Value: TryInto<T> { let mut v: Vec<T> = vec![]; for key in self.keys() { match key.try_into() { Ok(k) => v.push(k), Err(_) => return Err(Box::new(NcclError::new(ErrorKind::IntoError, "Could not convert to T", 0))) } } Ok(v) } /// Gets keys of a value as a vector of T or returns a default vector. pub fn keys_as_or<T>(&self, or: Vec<T>) -> Vec<T> where Value: TryInto<T> { self.keys_as::<T>().unwrap_or(or) } /// Pretty-prints a Pair. /// /// Examples: /// /// ``` /// let config = nccl::parse_file("examples/config.nccl").unwrap(); /// config.pretty_print(); /// /// // String("__top_level__") /// // String("server") /// // String("domain") /// // String("example.com") /// // String("www.example.com") /// // String("port") /// // Integer(80) /// // Integer(443) /// // String("root") /// // String("/var/www/html") /// ``` /// pub fn pretty_print(&self) { self.pp_rec(0); } fn pp_rec(&self, indent: u32) { for _ in 0..indent { print!(" "); } println!("{:?}", self.key); for value in &self.value { value.pp_rec(indent + 1); } } } impl<T> Index<T> for Pair where Value: From<T> { type Output = Pair; fn index(&self, i: T) -> &Pair { self.get_ref(i).unwrap() } } impl<T> IndexMut<T> for Pair where Value: From<T> { fn index_mut(&mut self, i: T) -> &mut Pair { self.get(i).unwrap() } }
{ if !self.has_key(&pair.key) { self.value.push(pair); } else { self[&pair.key].value = pair.value; } }
identifier_body
pair.rs
use error::{NcclError, ErrorKind}; use value::Value; use ::TryInto; use std::ops::{Index, IndexMut}; use std::error::Error; /// Struct that contains configuration information. /// /// Examples: /// /// ``` /// let p = nccl::parse_file("examples/config.nccl").unwrap(); /// let ports = p["server"]["port"].keys_as::<i64>().unwrap(); /// /// println!("Operating on ports:"); /// for port in ports.iter() { /// println!(" {}", port); /// } /// ``` #[derive(Clone, Debug, PartialEq)] pub struct Pair { key: Value, value: Vec<Pair> } impl Pair { /// Creates a new Pair. pub fn new<T: Into<Value>>(key: T) -> Self { Pair { key: key.into(), value: vec![] } } /// Adds a value to a Pair. /// /// Examples: /// /// ``` /// let mut p = nccl::Pair::new("hello"); /// p.add(true); /// p.add("world"); /// ``` pub fn add<T: Into<Value>>(&mut self, value: T) { self.value.push(Pair::new(value.into())); } /// Recursively adds a slice to a Pair. pub fn add_slice(&mut self, path: &[Value]) { let s = self.traverse_path(&path[0..path.len() - 1]); if!s.has_key(&path[path.len() - 1]) { s.add(&path[path.len() - 1]); } } /// Adds a Pair to a Pair. pub fn add_pair(&mut self, pair: Pair) { if!self.has_key(&pair.key) { self.value.push(pair); } else { self[&pair.key].value = pair.value; } } /// Test if a pair has a key. /// /// Examples: /// /// ``` /// use nccl::NcclError; /// let mut p = nccl::parse_file("examples/config.nccl").unwrap(); /// assert!(p.has_key("server")); /// assert!(p["server"]["port"].has_key(80)); /// ``` pub fn has_key<T>(&self, key: T) -> bool where Value: From<T> { let k = key.into(); for item in &self.value { if item.key == k { return true; } } false } /// Test if a pair has a path of values. Use `vec_into!` to make /// this method easier to use. /// /// Examples: /// /// ``` /// # #[macro_use] extern crate nccl; fn main() { /// let mut p = nccl::parse_file("examples/config.nccl").unwrap(); /// assert!(p.has_path(vec_into!["server", "port", 80])); /// # } /// ``` pub fn has_path(&self, path: Vec<Value>) -> bool { if path.is_empty() { true } else if self.has_key(path[0].clone()) { self[path[0].clone()].has_path(path[1..path.len()].to_vec()) } else { false } } /// Traverses a Pair using a slice, adding the item if it does not exist. pub fn traverse_path(&mut self, path: &[Value]) -> &mut Pair { if path.is_empty() { self } else { if!self.has_key(&path[0]) { self.add(&path[0]); } self.get(&path[0]).unwrap().traverse_path(&path[1..path.len()]) } } /// Gets a child Pair from a Pair. Used by Pair's implementation of Index. /// /// ``` /// let mut p = nccl::Pair::new("top_level"); /// p.add("hello!"); /// p.get("hello!").unwrap(); /// ``` pub fn get<T>(&mut self, value: T) -> Result<&mut Pair, Box<dyn Error>> where Value: From<T> { let v = value.into(); if self.value.is_empty() { return Err(Box::new(NcclError::new(ErrorKind::KeyNotFound, &format!("Pair does not have key: {}", v), 0))); } else { for item in &mut self.value { if item.key == v { return Ok(item); } } } Err(Box::new(NcclError::new(ErrorKind::KeyNotFound, &format!("Could not find key: {}", v), 0))) } /// Gets a mutable child Pair from a Pair. Used by Pair's implementation of /// IndexMut. /// /// ``` /// let mut p = nccl::Pair::new("top_level"); /// p.add(32); /// p.get(32).unwrap(); /// ``` pub fn get_ref<T>(&self, value: T) -> Result<&Pair, Box<dyn Error>> where Value: From<T> { let v = value.into(); if self.value.is_empty() { return Ok(self); } else { for item in &self.value { if item.key == v { return Ok(item); } } } Err(Box::new(NcclError::new(ErrorKind::KeyNotFound, &format!("Could not find key: {}", v), 0))) } /// Returns the value of a pair as a string. /// ``` /// let config = nccl::parse_file("examples/long.nccl").unwrap(); /// assert_eq!(config["bool too"].value().unwrap(), "false"); /// ``` pub fn value(&self) -> Option<String> { if self.value.len() == 1 { Some(format!("{}", self.value[0].key.clone())) } else { None } } /// Returns the value of the key or a default value. pub fn value_or(&self, or: String) -> String { self.value().unwrap_or(or) } fn value_raw(&self) -> Option<Value> { if self.value.len() == 1 { Some(self.value[0].key.clone()) } else { None
/// Gets the value of a key as a specified type, if there is only one. /// /// Examples: /// /// ``` /// let p = nccl::parse_file("examples/long.nccl").unwrap(); /// assert!(!p["bool too"].value_as::<bool>().unwrap()); /// ``` pub fn value_as<T>(&self) -> Result<T, Box<dyn Error>> where Value: TryInto<T> { match self.value_raw() { Some(v) => match v.try_into() { Ok(t) => Ok(t), Err(_) => Err(Box::new(NcclError::new(ErrorKind::IntoError, "Could not convert to T", 0))) }, None => Err(Box::new(NcclError::new(ErrorKind::MultipleValues, "Could not convert value: multiple values. Use keys() or keys_as()", 0))) } } /// Gets the value of a key as a specified type or a default value. pub fn value_as_or<T>(&self, or: T) -> T where Value: TryInto<T> { self.value_as::<T>().unwrap_or(or) } fn keys(&self) -> Vec<Value> { self.value.clone().into_iter().map(|x| x.key).collect() } /// Gets keys of a value as a vector of T. /// /// Examples: /// /// ``` /// let config = nccl::parse_file("examples/config.nccl").unwrap(); /// let ports = config["server"]["port"].keys_as::<i64>().unwrap(); /// assert_eq!(ports, vec![80, 443]); /// ``` pub fn keys_as<T>(&self) -> Result<Vec<T>, Box<dyn Error>> where Value: TryInto<T> { let mut v: Vec<T> = vec![]; for key in self.keys() { match key.try_into() { Ok(k) => v.push(k), Err(_) => return Err(Box::new(NcclError::new(ErrorKind::IntoError, "Could not convert to T", 0))) } } Ok(v) } /// Gets keys of a value as a vector of T or returns a default vector. pub fn keys_as_or<T>(&self, or: Vec<T>) -> Vec<T> where Value: TryInto<T> { self.keys_as::<T>().unwrap_or(or) } /// Pretty-prints a Pair. /// /// Examples: /// /// ``` /// let config = nccl::parse_file("examples/config.nccl").unwrap(); /// config.pretty_print(); /// /// // String("__top_level__") /// // String("server") /// // String("domain") /// // String("example.com") /// // String("www.example.com") /// // String("port") /// // Integer(80) /// // Integer(443) /// // String("root") /// // String("/var/www/html") /// ``` /// pub fn pretty_print(&self) { self.pp_rec(0); } fn pp_rec(&self, indent: u32) { for _ in 0..indent { print!(" "); } println!("{:?}", self.key); for value in &self.value { value.pp_rec(indent + 1); } } } impl<T> Index<T> for Pair where Value: From<T> { type Output = Pair; fn index(&self, i: T) -> &Pair { self.get_ref(i).unwrap() } } impl<T> IndexMut<T> for Pair where Value: From<T> { fn index_mut(&mut self, i: T) -> &mut Pair { self.get(i).unwrap() } }
} }
random_line_split
pair.rs
use error::{NcclError, ErrorKind}; use value::Value; use ::TryInto; use std::ops::{Index, IndexMut}; use std::error::Error; /// Struct that contains configuration information. /// /// Examples: /// /// ``` /// let p = nccl::parse_file("examples/config.nccl").unwrap(); /// let ports = p["server"]["port"].keys_as::<i64>().unwrap(); /// /// println!("Operating on ports:"); /// for port in ports.iter() { /// println!(" {}", port); /// } /// ``` #[derive(Clone, Debug, PartialEq)] pub struct Pair { key: Value, value: Vec<Pair> } impl Pair { /// Creates a new Pair. pub fn new<T: Into<Value>>(key: T) -> Self { Pair { key: key.into(), value: vec![] } } /// Adds a value to a Pair. /// /// Examples: /// /// ``` /// let mut p = nccl::Pair::new("hello"); /// p.add(true); /// p.add("world"); /// ``` pub fn add<T: Into<Value>>(&mut self, value: T) { self.value.push(Pair::new(value.into())); } /// Recursively adds a slice to a Pair. pub fn add_slice(&mut self, path: &[Value]) { let s = self.traverse_path(&path[0..path.len() - 1]); if!s.has_key(&path[path.len() - 1]) { s.add(&path[path.len() - 1]); } } /// Adds a Pair to a Pair. pub fn add_pair(&mut self, pair: Pair) { if!self.has_key(&pair.key) { self.value.push(pair); } else { self[&pair.key].value = pair.value; } } /// Test if a pair has a key. /// /// Examples: /// /// ``` /// use nccl::NcclError; /// let mut p = nccl::parse_file("examples/config.nccl").unwrap(); /// assert!(p.has_key("server")); /// assert!(p["server"]["port"].has_key(80)); /// ``` pub fn has_key<T>(&self, key: T) -> bool where Value: From<T> { let k = key.into(); for item in &self.value { if item.key == k { return true; } } false } /// Test if a pair has a path of values. Use `vec_into!` to make /// this method easier to use. /// /// Examples: /// /// ``` /// # #[macro_use] extern crate nccl; fn main() { /// let mut p = nccl::parse_file("examples/config.nccl").unwrap(); /// assert!(p.has_path(vec_into!["server", "port", 80])); /// # } /// ``` pub fn has_path(&self, path: Vec<Value>) -> bool { if path.is_empty() { true } else if self.has_key(path[0].clone()) { self[path[0].clone()].has_path(path[1..path.len()].to_vec()) } else { false } } /// Traverses a Pair using a slice, adding the item if it does not exist. pub fn traverse_path(&mut self, path: &[Value]) -> &mut Pair { if path.is_empty() { self } else { if!self.has_key(&path[0]) { self.add(&path[0]); } self.get(&path[0]).unwrap().traverse_path(&path[1..path.len()]) } } /// Gets a child Pair from a Pair. Used by Pair's implementation of Index. /// /// ``` /// let mut p = nccl::Pair::new("top_level"); /// p.add("hello!"); /// p.get("hello!").unwrap(); /// ``` pub fn get<T>(&mut self, value: T) -> Result<&mut Pair, Box<dyn Error>> where Value: From<T> { let v = value.into(); if self.value.is_empty() { return Err(Box::new(NcclError::new(ErrorKind::KeyNotFound, &format!("Pair does not have key: {}", v), 0))); } else { for item in &mut self.value { if item.key == v { return Ok(item); } } } Err(Box::new(NcclError::new(ErrorKind::KeyNotFound, &format!("Could not find key: {}", v), 0))) } /// Gets a mutable child Pair from a Pair. Used by Pair's implementation of /// IndexMut. /// /// ``` /// let mut p = nccl::Pair::new("top_level"); /// p.add(32); /// p.get(32).unwrap(); /// ``` pub fn get_ref<T>(&self, value: T) -> Result<&Pair, Box<dyn Error>> where Value: From<T> { let v = value.into(); if self.value.is_empty() { return Ok(self); } else { for item in &self.value { if item.key == v { return Ok(item); } } } Err(Box::new(NcclError::new(ErrorKind::KeyNotFound, &format!("Could not find key: {}", v), 0))) } /// Returns the value of a pair as a string. /// ``` /// let config = nccl::parse_file("examples/long.nccl").unwrap(); /// assert_eq!(config["bool too"].value().unwrap(), "false"); /// ``` pub fn value(&self) -> Option<String> { if self.value.len() == 1 { Some(format!("{}", self.value[0].key.clone())) } else { None } } /// Returns the value of the key or a default value. pub fn value_or(&self, or: String) -> String { self.value().unwrap_or(or) } fn value_raw(&self) -> Option<Value> { if self.value.len() == 1
else { None } } /// Gets the value of a key as a specified type, if there is only one. /// /// Examples: /// /// ``` /// let p = nccl::parse_file("examples/long.nccl").unwrap(); /// assert!(!p["bool too"].value_as::<bool>().unwrap()); /// ``` pub fn value_as<T>(&self) -> Result<T, Box<dyn Error>> where Value: TryInto<T> { match self.value_raw() { Some(v) => match v.try_into() { Ok(t) => Ok(t), Err(_) => Err(Box::new(NcclError::new(ErrorKind::IntoError, "Could not convert to T", 0))) }, None => Err(Box::new(NcclError::new(ErrorKind::MultipleValues, "Could not convert value: multiple values. Use keys() or keys_as()", 0))) } } /// Gets the value of a key as a specified type or a default value. pub fn value_as_or<T>(&self, or: T) -> T where Value: TryInto<T> { self.value_as::<T>().unwrap_or(or) } fn keys(&self) -> Vec<Value> { self.value.clone().into_iter().map(|x| x.key).collect() } /// Gets keys of a value as a vector of T. /// /// Examples: /// /// ``` /// let config = nccl::parse_file("examples/config.nccl").unwrap(); /// let ports = config["server"]["port"].keys_as::<i64>().unwrap(); /// assert_eq!(ports, vec![80, 443]); /// ``` pub fn keys_as<T>(&self) -> Result<Vec<T>, Box<dyn Error>> where Value: TryInto<T> { let mut v: Vec<T> = vec![]; for key in self.keys() { match key.try_into() { Ok(k) => v.push(k), Err(_) => return Err(Box::new(NcclError::new(ErrorKind::IntoError, "Could not convert to T", 0))) } } Ok(v) } /// Gets keys of a value as a vector of T or returns a default vector. pub fn keys_as_or<T>(&self, or: Vec<T>) -> Vec<T> where Value: TryInto<T> { self.keys_as::<T>().unwrap_or(or) } /// Pretty-prints a Pair. /// /// Examples: /// /// ``` /// let config = nccl::parse_file("examples/config.nccl").unwrap(); /// config.pretty_print(); /// /// // String("__top_level__") /// // String("server") /// // String("domain") /// // String("example.com") /// // String("www.example.com") /// // String("port") /// // Integer(80) /// // Integer(443) /// // String("root") /// // String("/var/www/html") /// ``` /// pub fn pretty_print(&self) { self.pp_rec(0); } fn pp_rec(&self, indent: u32) { for _ in 0..indent { print!(" "); } println!("{:?}", self.key); for value in &self.value { value.pp_rec(indent + 1); } } } impl<T> Index<T> for Pair where Value: From<T> { type Output = Pair; fn index(&self, i: T) -> &Pair { self.get_ref(i).unwrap() } } impl<T> IndexMut<T> for Pair where Value: From<T> { fn index_mut(&mut self, i: T) -> &mut Pair { self.get(i).unwrap() } }
{ Some(self.value[0].key.clone()) }
conditional_block
pair.rs
use error::{NcclError, ErrorKind}; use value::Value; use ::TryInto; use std::ops::{Index, IndexMut}; use std::error::Error; /// Struct that contains configuration information. /// /// Examples: /// /// ``` /// let p = nccl::parse_file("examples/config.nccl").unwrap(); /// let ports = p["server"]["port"].keys_as::<i64>().unwrap(); /// /// println!("Operating on ports:"); /// for port in ports.iter() { /// println!(" {}", port); /// } /// ``` #[derive(Clone, Debug, PartialEq)] pub struct Pair { key: Value, value: Vec<Pair> } impl Pair { /// Creates a new Pair. pub fn new<T: Into<Value>>(key: T) -> Self { Pair { key: key.into(), value: vec![] } } /// Adds a value to a Pair. /// /// Examples: /// /// ``` /// let mut p = nccl::Pair::new("hello"); /// p.add(true); /// p.add("world"); /// ``` pub fn add<T: Into<Value>>(&mut self, value: T) { self.value.push(Pair::new(value.into())); } /// Recursively adds a slice to a Pair. pub fn add_slice(&mut self, path: &[Value]) { let s = self.traverse_path(&path[0..path.len() - 1]); if!s.has_key(&path[path.len() - 1]) { s.add(&path[path.len() - 1]); } } /// Adds a Pair to a Pair. pub fn add_pair(&mut self, pair: Pair) { if!self.has_key(&pair.key) { self.value.push(pair); } else { self[&pair.key].value = pair.value; } } /// Test if a pair has a key. /// /// Examples: /// /// ``` /// use nccl::NcclError; /// let mut p = nccl::parse_file("examples/config.nccl").unwrap(); /// assert!(p.has_key("server")); /// assert!(p["server"]["port"].has_key(80)); /// ``` pub fn has_key<T>(&self, key: T) -> bool where Value: From<T> { let k = key.into(); for item in &self.value { if item.key == k { return true; } } false } /// Test if a pair has a path of values. Use `vec_into!` to make /// this method easier to use. /// /// Examples: /// /// ``` /// # #[macro_use] extern crate nccl; fn main() { /// let mut p = nccl::parse_file("examples/config.nccl").unwrap(); /// assert!(p.has_path(vec_into!["server", "port", 80])); /// # } /// ``` pub fn
(&self, path: Vec<Value>) -> bool { if path.is_empty() { true } else if self.has_key(path[0].clone()) { self[path[0].clone()].has_path(path[1..path.len()].to_vec()) } else { false } } /// Traverses a Pair using a slice, adding the item if it does not exist. pub fn traverse_path(&mut self, path: &[Value]) -> &mut Pair { if path.is_empty() { self } else { if!self.has_key(&path[0]) { self.add(&path[0]); } self.get(&path[0]).unwrap().traverse_path(&path[1..path.len()]) } } /// Gets a child Pair from a Pair. Used by Pair's implementation of Index. /// /// ``` /// let mut p = nccl::Pair::new("top_level"); /// p.add("hello!"); /// p.get("hello!").unwrap(); /// ``` pub fn get<T>(&mut self, value: T) -> Result<&mut Pair, Box<dyn Error>> where Value: From<T> { let v = value.into(); if self.value.is_empty() { return Err(Box::new(NcclError::new(ErrorKind::KeyNotFound, &format!("Pair does not have key: {}", v), 0))); } else { for item in &mut self.value { if item.key == v { return Ok(item); } } } Err(Box::new(NcclError::new(ErrorKind::KeyNotFound, &format!("Could not find key: {}", v), 0))) } /// Gets a mutable child Pair from a Pair. Used by Pair's implementation of /// IndexMut. /// /// ``` /// let mut p = nccl::Pair::new("top_level"); /// p.add(32); /// p.get(32).unwrap(); /// ``` pub fn get_ref<T>(&self, value: T) -> Result<&Pair, Box<dyn Error>> where Value: From<T> { let v = value.into(); if self.value.is_empty() { return Ok(self); } else { for item in &self.value { if item.key == v { return Ok(item); } } } Err(Box::new(NcclError::new(ErrorKind::KeyNotFound, &format!("Could not find key: {}", v), 0))) } /// Returns the value of a pair as a string. /// ``` /// let config = nccl::parse_file("examples/long.nccl").unwrap(); /// assert_eq!(config["bool too"].value().unwrap(), "false"); /// ``` pub fn value(&self) -> Option<String> { if self.value.len() == 1 { Some(format!("{}", self.value[0].key.clone())) } else { None } } /// Returns the value of the key or a default value. pub fn value_or(&self, or: String) -> String { self.value().unwrap_or(or) } fn value_raw(&self) -> Option<Value> { if self.value.len() == 1 { Some(self.value[0].key.clone()) } else { None } } /// Gets the value of a key as a specified type, if there is only one. /// /// Examples: /// /// ``` /// let p = nccl::parse_file("examples/long.nccl").unwrap(); /// assert!(!p["bool too"].value_as::<bool>().unwrap()); /// ``` pub fn value_as<T>(&self) -> Result<T, Box<dyn Error>> where Value: TryInto<T> { match self.value_raw() { Some(v) => match v.try_into() { Ok(t) => Ok(t), Err(_) => Err(Box::new(NcclError::new(ErrorKind::IntoError, "Could not convert to T", 0))) }, None => Err(Box::new(NcclError::new(ErrorKind::MultipleValues, "Could not convert value: multiple values. Use keys() or keys_as()", 0))) } } /// Gets the value of a key as a specified type or a default value. pub fn value_as_or<T>(&self, or: T) -> T where Value: TryInto<T> { self.value_as::<T>().unwrap_or(or) } fn keys(&self) -> Vec<Value> { self.value.clone().into_iter().map(|x| x.key).collect() } /// Gets keys of a value as a vector of T. /// /// Examples: /// /// ``` /// let config = nccl::parse_file("examples/config.nccl").unwrap(); /// let ports = config["server"]["port"].keys_as::<i64>().unwrap(); /// assert_eq!(ports, vec![80, 443]); /// ``` pub fn keys_as<T>(&self) -> Result<Vec<T>, Box<dyn Error>> where Value: TryInto<T> { let mut v: Vec<T> = vec![]; for key in self.keys() { match key.try_into() { Ok(k) => v.push(k), Err(_) => return Err(Box::new(NcclError::new(ErrorKind::IntoError, "Could not convert to T", 0))) } } Ok(v) } /// Gets keys of a value as a vector of T or returns a default vector. pub fn keys_as_or<T>(&self, or: Vec<T>) -> Vec<T> where Value: TryInto<T> { self.keys_as::<T>().unwrap_or(or) } /// Pretty-prints a Pair. /// /// Examples: /// /// ``` /// let config = nccl::parse_file("examples/config.nccl").unwrap(); /// config.pretty_print(); /// /// // String("__top_level__") /// // String("server") /// // String("domain") /// // String("example.com") /// // String("www.example.com") /// // String("port") /// // Integer(80) /// // Integer(443) /// // String("root") /// // String("/var/www/html") /// ``` /// pub fn pretty_print(&self) { self.pp_rec(0); } fn pp_rec(&self, indent: u32) { for _ in 0..indent { print!(" "); } println!("{:?}", self.key); for value in &self.value { value.pp_rec(indent + 1); } } } impl<T> Index<T> for Pair where Value: From<T> { type Output = Pair; fn index(&self, i: T) -> &Pair { self.get_ref(i).unwrap() } } impl<T> IndexMut<T> for Pair where Value: From<T> { fn index_mut(&mut self, i: T) -> &mut Pair { self.get(i).unwrap() } }
has_path
identifier_name
trackevent.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::audiotrack::AudioTrack; use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindings::TrackEventBinding; use crate::dom::bindings::codegen::Bindings::TrackEventBinding::TrackEventMethods; use crate::dom::bindings::codegen::UnionTypes::VideoTrackOrAudioTrackOrTextTrack; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::event::Event; use crate::dom::globalscope::GlobalScope; use crate::dom::texttrack::TextTrack; use crate::dom::videotrack::VideoTrack; use crate::dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; #[must_root] #[derive(JSTraceable, MallocSizeOf)] enum MediaTrack { Video(Dom<VideoTrack>), Audio(Dom<AudioTrack>), Text(Dom<TextTrack>), } #[dom_struct] pub struct TrackEvent { event: Event, track: Option<MediaTrack>, } impl TrackEvent { #[allow(unrooted_must_root)] fn new_inherited(track: &Option<VideoTrackOrAudioTrackOrTextTrack>) -> TrackEvent { let media_track = match track { Some(VideoTrackOrAudioTrackOrTextTrack::VideoTrack(VideoTrack)) => { Some(MediaTrack::Video(Dom::from_ref(VideoTrack))) }, Some(VideoTrackOrAudioTrackOrTextTrack::AudioTrack(AudioTrack)) => { Some(MediaTrack::Audio(Dom::from_ref(AudioTrack))) }, Some(VideoTrackOrAudioTrackOrTextTrack::TextTrack(TextTrack)) => { Some(MediaTrack::Text(Dom::from_ref(TextTrack))) }, None => None, }; TrackEvent { event: Event::new_inherited(), track: media_track, } } pub fn new( global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, track: &Option<VideoTrackOrAudioTrackOrTextTrack>, ) -> DomRoot<TrackEvent> { let te = reflect_dom_object( Box::new(TrackEvent::new_inherited(&track)), global, TrackEventBinding::Wrap, ); { let event = te.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } te } pub fn Constructor( window: &Window, type_: DOMString, init: &TrackEventBinding::TrackEventInit, ) -> Fallible<DomRoot<TrackEvent>>
} impl TrackEventMethods for TrackEvent { // https://html.spec.whatwg.org/multipage/#dom-trackevent-track fn GetTrack(&self) -> Option<VideoTrackOrAudioTrackOrTextTrack> { match &self.track { Some(MediaTrack::Video(VideoTrack)) => Some( VideoTrackOrAudioTrackOrTextTrack::VideoTrack(DomRoot::from_ref(VideoTrack)), ), Some(MediaTrack::Audio(AudioTrack)) => Some( VideoTrackOrAudioTrackOrTextTrack::AudioTrack(DomRoot::from_ref(AudioTrack)), ), Some(MediaTrack::Text(TextTrack)) => Some( VideoTrackOrAudioTrackOrTextTrack::TextTrack(DomRoot::from_ref(TextTrack)), ), None => None, } } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
{ Ok(TrackEvent::new( &window.global(), Atom::from(type_), init.parent.bubbles, init.parent.cancelable, &init.track, )) }
identifier_body
trackevent.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::audiotrack::AudioTrack; use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindings::TrackEventBinding; use crate::dom::bindings::codegen::Bindings::TrackEventBinding::TrackEventMethods; use crate::dom::bindings::codegen::UnionTypes::VideoTrackOrAudioTrackOrTextTrack; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::event::Event; use crate::dom::globalscope::GlobalScope; use crate::dom::texttrack::TextTrack; use crate::dom::videotrack::VideoTrack; use crate::dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; #[must_root] #[derive(JSTraceable, MallocSizeOf)] enum
{ Video(Dom<VideoTrack>), Audio(Dom<AudioTrack>), Text(Dom<TextTrack>), } #[dom_struct] pub struct TrackEvent { event: Event, track: Option<MediaTrack>, } impl TrackEvent { #[allow(unrooted_must_root)] fn new_inherited(track: &Option<VideoTrackOrAudioTrackOrTextTrack>) -> TrackEvent { let media_track = match track { Some(VideoTrackOrAudioTrackOrTextTrack::VideoTrack(VideoTrack)) => { Some(MediaTrack::Video(Dom::from_ref(VideoTrack))) }, Some(VideoTrackOrAudioTrackOrTextTrack::AudioTrack(AudioTrack)) => { Some(MediaTrack::Audio(Dom::from_ref(AudioTrack))) }, Some(VideoTrackOrAudioTrackOrTextTrack::TextTrack(TextTrack)) => { Some(MediaTrack::Text(Dom::from_ref(TextTrack))) }, None => None, }; TrackEvent { event: Event::new_inherited(), track: media_track, } } pub fn new( global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, track: &Option<VideoTrackOrAudioTrackOrTextTrack>, ) -> DomRoot<TrackEvent> { let te = reflect_dom_object( Box::new(TrackEvent::new_inherited(&track)), global, TrackEventBinding::Wrap, ); { let event = te.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } te } pub fn Constructor( window: &Window, type_: DOMString, init: &TrackEventBinding::TrackEventInit, ) -> Fallible<DomRoot<TrackEvent>> { Ok(TrackEvent::new( &window.global(), Atom::from(type_), init.parent.bubbles, init.parent.cancelable, &init.track, )) } } impl TrackEventMethods for TrackEvent { // https://html.spec.whatwg.org/multipage/#dom-trackevent-track fn GetTrack(&self) -> Option<VideoTrackOrAudioTrackOrTextTrack> { match &self.track { Some(MediaTrack::Video(VideoTrack)) => Some( VideoTrackOrAudioTrackOrTextTrack::VideoTrack(DomRoot::from_ref(VideoTrack)), ), Some(MediaTrack::Audio(AudioTrack)) => Some( VideoTrackOrAudioTrackOrTextTrack::AudioTrack(DomRoot::from_ref(AudioTrack)), ), Some(MediaTrack::Text(TextTrack)) => Some( VideoTrackOrAudioTrackOrTextTrack::TextTrack(DomRoot::from_ref(TextTrack)), ), None => None, } } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
MediaTrack
identifier_name
trackevent.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::audiotrack::AudioTrack; use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindings::TrackEventBinding; use crate::dom::bindings::codegen::Bindings::TrackEventBinding::TrackEventMethods; use crate::dom::bindings::codegen::UnionTypes::VideoTrackOrAudioTrackOrTextTrack; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::event::Event; use crate::dom::globalscope::GlobalScope; use crate::dom::texttrack::TextTrack; use crate::dom::videotrack::VideoTrack; use crate::dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; #[must_root] #[derive(JSTraceable, MallocSizeOf)] enum MediaTrack { Video(Dom<VideoTrack>), Audio(Dom<AudioTrack>), Text(Dom<TextTrack>), } #[dom_struct] pub struct TrackEvent { event: Event, track: Option<MediaTrack>, } impl TrackEvent { #[allow(unrooted_must_root)] fn new_inherited(track: &Option<VideoTrackOrAudioTrackOrTextTrack>) -> TrackEvent { let media_track = match track { Some(VideoTrackOrAudioTrackOrTextTrack::VideoTrack(VideoTrack)) => { Some(MediaTrack::Video(Dom::from_ref(VideoTrack))) }, Some(VideoTrackOrAudioTrackOrTextTrack::AudioTrack(AudioTrack)) => { Some(MediaTrack::Audio(Dom::from_ref(AudioTrack))) }, Some(VideoTrackOrAudioTrackOrTextTrack::TextTrack(TextTrack)) => { Some(MediaTrack::Text(Dom::from_ref(TextTrack))) }, None => None, }; TrackEvent { event: Event::new_inherited(), track: media_track, } } pub fn new( global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, track: &Option<VideoTrackOrAudioTrackOrTextTrack>, ) -> DomRoot<TrackEvent> { let te = reflect_dom_object( Box::new(TrackEvent::new_inherited(&track)), global, TrackEventBinding::Wrap, ); { let event = te.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } te }
type_: DOMString, init: &TrackEventBinding::TrackEventInit, ) -> Fallible<DomRoot<TrackEvent>> { Ok(TrackEvent::new( &window.global(), Atom::from(type_), init.parent.bubbles, init.parent.cancelable, &init.track, )) } } impl TrackEventMethods for TrackEvent { // https://html.spec.whatwg.org/multipage/#dom-trackevent-track fn GetTrack(&self) -> Option<VideoTrackOrAudioTrackOrTextTrack> { match &self.track { Some(MediaTrack::Video(VideoTrack)) => Some( VideoTrackOrAudioTrackOrTextTrack::VideoTrack(DomRoot::from_ref(VideoTrack)), ), Some(MediaTrack::Audio(AudioTrack)) => Some( VideoTrackOrAudioTrackOrTextTrack::AudioTrack(DomRoot::from_ref(AudioTrack)), ), Some(MediaTrack::Text(TextTrack)) => Some( VideoTrackOrAudioTrackOrTextTrack::TextTrack(DomRoot::from_ref(TextTrack)), ), None => None, } } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
pub fn Constructor( window: &Window,
random_line_split
text.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/. */ //! Text layout. use layout::box::{RenderBox, RenderBoxBase, TextRenderBox, UnscannedTextRenderBoxClass}; use gfx::text::text_run::TextRun; use servo_util::range::Range; pub struct TextBoxData { run: @TextRun, range: Range, } impl TextBoxData { pub fn new(run: @TextRun, range: Range) -> TextBoxData { TextBoxData { run: run, range: range, } } } pub fn adapt_textbox_with_range(mut base: RenderBoxBase, run: @TextRun, range: Range) -> TextRenderBox { assert!(range.begin() < run.char_len()); assert!(range.end() <= run.char_len()); assert!(range.length() > 0); debug!("Creating textbox with span: (strlen=%u, off=%u, len=%u) of textrun: %s", run.char_len(), range.begin(), range.length(), run.text); let new_text_data = TextBoxData::new(run, range); let metrics = run.metrics_for_range(&range); base.position.size = metrics.bounding_box.size; TextRenderBox { base: base, text_data: new_text_data, } } pub trait UnscannedMethods { /// Copies out the text from an unscanned text box. Fails if this is not an unscanned text box. fn raw_text(&self) -> ~str; } impl UnscannedMethods for RenderBox { fn raw_text(&self) -> ~str
}
{ match *self { UnscannedTextRenderBoxClass(text_box) => copy text_box.text, _ => fail!(~"unsupported operation: box.raw_text() on non-unscanned text box."), } }
identifier_body