file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
lib.rs
This module re-exports everything and includes free functions for all traits methods doing out-of-place modifications. * You can import the whole prelude using: ```.ignore use nalgebra::*; ``` The preferred way to use **nalgebra** is to import types and traits explicitly, and call free-functions using the `na::` prefix: ```.rust extern crate nalgebra as na; use na::{Vec3, Rot3, Rotation}; fn main() { let a = Vec3::new(1.0f64, 1.0, 1.0); let mut b = Rot3::new(na::zero()); b.append_rotation_mut(&a); assert!(na::approx_eq(&na::rotation(&b), &a)); } ``` ## Features **nalgebra** is meant to be a general-purpose, low-dimensional, linear algebra library, with an optimized set of tools for computer graphics and physics. Those features include: * Vectors with static sizes: `Vec0`, `Vec1`, `Vec2`, `Vec3`, `Vec4`, `Vec5`, `Vec6`. * Points with static sizes: `Pnt0`, `Pnt1`, `Pnt2`, `Pnt3`, `Pnt4`, `Pnt5`, `Pnt6`. * Square matrices with static sizes: `Mat1`, `Mat2`, `Mat3`, `Mat4`, `Mat5`, `Mat6 `. * Rotation matrices: `Rot2`, `Rot3`, `Rot4`. * Quaternions: `Quat`, `UnitQuat`. * Isometries: `Iso2`, `Iso3`, `Iso4`. * 3D projections for computer graphics: `Persp3`, `PerspMat3`, `Ortho3`, `OrthoMat3`. * Dynamically sized vector: `DVec`. * Dynamically sized (square or rectangular) matrix: `DMat`. * A few methods for data analysis: `Cov`, `Mean`. * Almost one trait per functionality: useful for generic programming. * Operator overloading using multidispatch. ## **nalgebra** in use Here are some projects using **nalgebra**. Feel free to add your project to this list if you happen to use **nalgebra**! * [nphysics](https://github.com/sebcrozet/nphysics): a real-time physics engine. * [ncollide](https://github.com/sebcrozet/ncollide): a collision detection library. * [kiss3d](https://github.com/sebcrozet/kiss3d): a minimalistic graphics engine. * [nrays](https://github.com/sebcrozet/nrays): a ray tracer. */ #![deny(non_camel_case_types)] #![deny(unused_parens)] #![deny(non_upper_case_globals)] #![deny(unused_qualifications)] #![deny(unused_results)] #![warn(missing_docs)] #![doc(html_root_url = "http://nalgebra.org/doc")] extern crate rustc_serialize; extern crate rand; extern crate num; #[cfg(feature="arbitrary")] extern crate quickcheck; use std::cmp; use std::ops::{Neg, Mul}; use num::{Zero, One}; pub use traits::{ Absolute, AbsoluteRotate, ApproxEq, Axpy, Basis, BaseFloat, BaseNum, Bounded, Cast, Col, ColSlice, RowSlice, Cov, Cross, CrossMatrix, Det, Diag, Dim, Dot, EigenQR, Eye, FloatPnt, FloatVec, FromHomogeneous, Indexable, Inv, Iterable, IterableMut, Mat, Mean, Norm, NumPnt, NumVec, Orig, Outer, POrd, POrdering, PntAsVec, Repeat, Rotate, Rotation, RotationMatrix, RotationWithTranslation, RotationTo, Row, Shape, SquareMat, ToHomogeneous, Transform, Transformation, Translate, Translation, Transpose, UniformSphereSample }; pub use structs::{ Identity, DMat, DVec, DVec1, DVec2, DVec3, DVec4, DVec5, DVec6, Iso2, Iso3, Iso4, Mat1, Mat2, Mat3, Mat4, Mat5, Mat6, Rot2, Rot3, Rot4, Vec0, Vec1, Vec2, Vec3, Vec4, Vec5, Vec6, Pnt0, Pnt1, Pnt2, Pnt3, Pnt4, Pnt5, Pnt6, Persp3, PerspMat3, Ortho3, OrthoMat3, Quat, UnitQuat }; pub use linalg::{ qr, householder_matrix, cholesky }; mod structs; mod traits; mod linalg; mod macros; // mod lower_triangular; // mod chol; /// Change the input value to ensure it is on the range `[min, max]`. #[inline(always)] pub fn clamp<T: PartialOrd>(val: T, min: T, max: T) -> T { if val > min { if val < max { val } else { max } } else { min } } /// Same as `cmp::max`. #[inline(always)] pub fn max<T: Ord>(a: T, b: T) -> T { cmp::max(a, b) } /// Same as `cmp::min`. #[inline(always)] pub fn min<T: Ord>(a: T, b: T) -> T { cmp::min(a, b) } /// Returns the infimum of `a` and `b`. #[inline(always)] pub fn inf<T: POrd>(a: &T, b: &T) -> T { POrd::inf(a, b) } /// Returns the supremum of `a` and `b`. #[inline(always)] pub fn sup<T: POrd>(a: &T, b: &T) -> T { POrd::sup(a, b) } /// Compare `a` and `b` using a partial ordering relation. #[inline(always)] pub fn partial_cmp<T: POrd>(a: &T, b: &T) -> POrdering { POrd::partial_cmp(a, b) } /// Returns `true` iff `a` and `b` are comparable and `a < b`. #[inline(always)] pub fn partial_lt<T: POrd>(a: &T, b: &T) -> bool { POrd::partial_lt(a, b) } /// Returns `true` iff `a` and `b` are comparable and `a <= b`. #[inline(always)] pub fn partial_le<T: POrd>(a: &T, b: &T) -> bool { POrd::partial_le(a, b) } /// Returns `true` iff `a` and `b` are comparable and `a > b`. #[inline(always)] pub fn partial_gt<T: POrd>(a: &T, b: &T) -> bool { POrd::partial_gt(a, b) } /// Returns `true` iff `a` and `b` are comparable and `a >= b`. #[inline(always)] pub fn partial_ge<T: POrd>(a: &T, b: &T) -> bool { POrd::partial_ge(a, b) } /// Return the minimum of `a` and `b` if they are comparable. #[inline(always)] pub fn partial_min<'a, T: POrd>(a: &'a T, b: &'a T) -> Option<&'a T> { POrd::partial_min(a, b) } /// Return the maximum of `a` and `b` if they are comparable. #[inline(always)] pub fn partial_max<'a, T: POrd>(a: &'a T, b: &'a T) -> Option<&'a T> { POrd::partial_max(a, b) } /// Clamp `value` between `min` and `max`. Returns `None` if `value` is not comparable to /// `min` or `max`. #[inline(always)] pub fn partial_clamp<'a, T: POrd>(value: &'a T, min: &'a T, max: &'a T) -> Option<&'a T> { POrd::partial_clamp(value, min, max) } // // // Constructors // // /// Create a special identity object. /// /// Same as `Identity::new()`. #[inline(always)] pub fn identity() -> Identity { Identity::new() } /// Create a zero-valued value. /// /// This is the same as `std::num::zero()`. #[inline(always)] pub fn zero<T: Zero>() -> T { Zero::zero() } /// Tests is a value is iqual to zero. #[inline(always)] pub fn is_zero<T: Zero>(val: &T) -> bool { val.is_zero() } /// Create a one-valued value. /// /// This is the same as `std::num::one()`. #[inline(always)] pub fn one<T: One>() -> T { One::one() } // // // Geometry // // /// Returns the trivial origin of an affine space. #[inline(always)] pub fn orig<P: Orig>() -> P { Orig::orig() } /// Returns the center of two points. #[inline] pub fn center<N: BaseFloat, P: FloatPnt<N, V>, V: Copy + Norm<N>>(a: &P, b: &P) -> P { let _2 = one::<N>() + one(); (*a + *b.as_vec()) / _2 } /* * FloatPnt */ /// Returns the distance between two points. #[inline(always)] pub fn dist<N: BaseFloat, P: FloatPnt<N, V>, V: Norm<N>>(a: &P, b: &P) -> N {
/// Returns the squared distance between two points. #[inline(always)] pub fn sqdist<N: BaseFloat, P: FloatPnt<N, V>, V: Norm<N>>(a: &P, b: &P) -> N { a.sqdist(b) } /* * Translation<V> */ /// Gets the translation applicable by `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Iso3}; /// /// fn main() { /// let t = Iso3::new(Vec3::new(1.0f64, 1.0, 1.0), na::zero()); /// let trans = na::translation(&t); /// /// assert!(trans == Vec3::new(1.0, 1.0, 1.0)); /// } /// ``` #[inline(always)] pub fn translation<V, M: Translation<V>>(m: &M) -> V { m.translation() } /// Gets the inverse translation applicable by `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Iso3}; /// /// fn main() { /// let t = Iso3::new(Vec3::new(1.0f64, 1.0, 1.0), na::zero()); /// let itrans = na::inv_translation(&t); /// /// assert!(itrans == Vec3::new(-1.0, -1.0, -1.0)); /// } /// ``` #[inline(always)] pub fn inv_translation<V, M: Translation<V>>(m: &M) -> V { m.inv_translation() } /// Applies the translation `v` to a copy of `m`. #[inline(always)] pub fn append_translation<V, M: Translation<V>>(m: &M, v: &V) -> M { Translation::append_translation(m, v) } /* * Translate<P> */ /// Applies a translation to a point. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Pnt3, Vec3, Iso3}; /// /// fn main() { /// let t = Iso3::new(Vec3::new(1.0f64, 1.0, 1.0), na::zero()); /// let p = Pnt3::new(2.0, 2.0, 2.0); /// /// let tp = na::translate(&t, &p); /// /// assert!(tp == Pnt3::new(3.0, 3.0, 3.0)) /// } /// ``` #[inline(always)] pub fn translate<P, M: Translate<P>>(m: &M, p: &P) -> P { m.translate(p) } /// Applies an inverse translation to a point. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Pnt3, Vec3, Iso3}; /// /// fn main() { /// let t = Iso3::new(Vec3::new(1.0f64, 1.0, 1.0), na::zero()); /// let p = Pnt3::new(2.0, 2.0, 2.0); /// /// let tp = na::inv_translate(&t, &p); /// /// assert!(na::approx_eq(&tp, &Pnt3::new(1.0, 1.0, 1.0))) /// } #[inline(always)] pub fn inv_translate<P, M: Translate<P>>(m: &M, p: &P) -> P { m.inv_translate(p) } /* * Rotation<V> */ /// Gets the rotation applicable by `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Rot3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(1.0f64, 1.0, 1.0)); /// /// assert!(na::approx_eq(&na::rotation(&t), &Vec3::new(1.0, 1.0, 1.0))); /// } /// ``` #[inline(always)] pub fn rotation<V, M: Rotation<V>>(m: &M) -> V { m.rotation() } /// Gets the inverse rotation applicable by `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Rot3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(1.0f64, 1.0, 1.0)); /// /// assert!(na::approx_eq(&na::inv_rotation(&t), &Vec3::new(-1.0, -1.0, -1.0))); /// } /// ``` #[inline(always)] pub fn inv_rotation<V, M: Rotation<V>>(m: &M) -> V { m.inv_rotation() } // FIXME: this example is a bit shity /// Applies the rotation `v` to a copy of `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Rot3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(0.0f64, 0.0, 0.0)); /// let v = Vec3::new(1.0, 1.0, 1.0); /// let rt = na::append_rotation(&t, &v); /// /// assert!(na::approx_eq(&na::rotation(&rt), &Vec3::new(1.0, 1.0, 1.0))) /// } /// ``` #[inline(always)] pub fn append_rotation<V, M: Rotation<V>>(m: &M, v: &V) -> M { Rotation::append_rotation(m, v) } // FIXME: this example is a bit shity /// Pre-applies the rotation `v` to a copy of `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Rot3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(0.0f64, 0.0, 0.0)); /// let v = Vec3::new(1.0, 1.0, 1.0); /// let rt = na::prepend_rotation(&t, &v); /// /// assert!(na::approx_eq(&na::rotation(&rt), &Vec3::new(1.0, 1.0, 1.0))) /// } /// ``` #[inline(always)] pub fn prepend_rotation<V, M: Rotation<V>>(m: &M, v: &V) -> M { Rotation::prepend_rotation(m, v) } /* * Rotate<V> */ /// Applies a rotation to a vector. /// /// ```rust /// extern crate nalgebra as na; /// use na::{BaseFloat, Rot3, Vec3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(0.0f64, 0.0, 0.5 * <f64 as BaseFloat>::pi())); /// let v = Vec3::new(1.0, 0.0, 0.0); /// /// let tv = na::rotate(&t, &v); /// /// assert!(na::approx_eq(&tv, &Vec3::new(0.0, 1.0, 0.0))) /// } /// ``` #[inline(always)] pub fn rotate<V, M: Rotate<V>>(m: &M, v: &V) -> V { m.rotate(v) } /// Applies an inverse rotation to a vector. /// /// ```rust /// extern crate nalgebra as na; /// use na::{BaseFloat, Rot3, Vec3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(0.0f64, 0.0, 0.5 * <f64 as BaseFloat>::pi())); /// let v = Vec3::new(1.0, 0.0, 0.0); /// /// let tv = na::inv_rotate(&t, &v); /// /// assert!(na::approx_eq(&tv, &Vec3::new(0.0, -1.0, 0.0))) /// } /// ``` #[inline(always)] pub fn inv_rotate<V, M: Rotate<V>>(m: &M, v: &V) -> V { m.inv_rotate(v) } /* * RotationWithTranslation<LV, AV> */ /// Rotates a copy of `m` by `amount` using `center` as the pivot point. #[inline(always)] pub fn append_rotation_wrt_point<LV: Neg<Output = LV> + Copy, AV, M: RotationWithTranslation<LV, AV>>( m: &M, amount: &AV, center: &LV) -> M { RotationWithTranslation::append_rotation_wrt_point(m, amount, center) } /// Rotates a copy of `m` by `amount` using `m.translation()` as the pivot point. #[inline(always)] pub fn append_rotation_wrt_center<LV: Neg<Output = LV> + Copy, AV, M: RotationWithTranslation<LV, AV>>( m: &M, amount: &AV) -> M { RotationWithTranslation::append_rotation_wrt_center(m, amount) } /* * RotationTo */ /// Computes the angle of the rotation needed to transfom `a` to `b`. #[inline(always)] pub fn angle_between<V: RotationTo>(a: &V, b: &V) -> V::AngleType { a.angle_to(b) } /// Computes the rotation needed to transform `a` to `b`. #[inline(always)] pub fn rotation_between<V: RotationTo>(a: &V, b: &V) -> V::DeltaRotationType { a.rotation_to(b) } /* * RotationMatrix<LV, AV, R> */ /// Builds a rotation matrix from `r`. #[inline(always)] pub fn to_rot_mat<N, LV, AV, R, M>(r: &R) -> M where R: RotationMatrix<N, LV, AV, Output = M>, M: SquareMat<N, LV> + Rotation<AV> + Copy, LV: Mul<M, Output = LV> { // FIXME: rust-lang/rust#20413 r.to_rot_mat() } /* * AbsoluteRotate<V> */ /// Applies a rotation using the absolute values of its components. #[inline(always)] pub fn absolute_rotate<V, M: AbsoluteRotate<V>>(m: &M, v: &V) -> V { m.absolute_rotate(v) } /* * Transformation<T> */ /// Gets the transformation applicable by `m`. #[inline(always)] pub fn transformation<T, M: Transformation<T>>(m: &M) -> T { m.transformation() } /// Gets the inverse transformation applicable by `m`. #[inline(always)] pub fn inv_transformation<T, M: Transformation<T>>(m: &M) -> T { m.inv_transformation() } /// Gets a transformed copy of `m`. #[inline(always)] pub fn append_transformation<T, M: Transformation<T>>(m: &M, t: &T) -> M { Transformation::append_transformation(m, t) } /* * Transform<V> */ /// Applies a transformation to a vector. #[inline(always)] pub fn transform<V, M: Transform<V>>(m: &M, v: &V) -> V { m.transform(v) } /// Applies an inverse transformation to a vector. #[inline(always)] pub fn inv_transform<V, M: Transform<V>>(m: &M, v: &V) -> V { m.inv_transform(v) } /* * Dot<N> */ /// Computes the dot product of two vectors. #[inline(always)] pub fn dot<V: Dot<N>, N>(a: &V, b: &V) -> N { Dot::dot(a, b) } /* * Norm<N> */ /// Computes the L2 norm of a vector. #[inline(always)] pub fn norm<V: Norm<N>, N: BaseFloat>(v: &V) -> N { Norm::norm(v) } /// Computes the squared L2 norm of a vector. #[inline(always)] pub fn sqnorm<V: Norm<N>, N: BaseFloat>(v: &V) -> N { Norm::sqnorm(v) } /// Gets the normalized version of a vector. #[inline(always)] pub fn normalize<V: Norm<N>, N: BaseFloat>(v: &V) -> V { Norm::normalize(v) } /* * Det<N> */ /// Computes the determinant of a square matrix. #[inline(always)] pub fn det<M: Det<N>, N>(m: &M) -> N { Det::det(m) } /* * Cross<V> */ /// Computes the cross product of two vectors. #[inline(always)] pub fn cross<LV: Cross>(a: &LV, b: &LV) -> LV::CrossProductType { Cross::cross(a, b) } /* * CrossMatrix<M> */ /// Given a vector, computes the matrix which, when multiplied by another vector, computes a cross /// product. #[inline(always)] pub fn cross_matrix<V: CrossMatrix<M>, M>(v: &V) -> M { CrossMatrix::cross_matrix(v) } /* * ToHomogeneous<U> */ /// Converts a matrix or vector to homogeneous coordinates. #[inline(always)] pub fn to_homogeneous<M: ToHomogeneous<Res>, Res>(m: &M) -> Res { ToHomogeneous::to_homogeneous(m) } /* * FromHomogeneous<U> */ /// Converts a matrix or vector from homogeneous coordinates. /// /// w-normalization is appied. #[inline(always)] pub fn from_homogeneous<M, Res: FromHomogeneous<M>>(m: &M) -> Res { FromHomogeneous::from(m) } /* * UniformSphereSample */ /// Samples the unit sphere living on the dimension as the samples types. /// /// The number of sampling point is implementation-specific. It is always uniform. #[inline(always)] pub fn sample_sphere<V: UniformSphereSample, F: FnMut(V)>(f: F) { UniformSphereSample::sample(f) } // // // Operations // // /* * AproxEq<N> */ /// Tests approximate equality. #[inline(always)] pub fn approx_eq<T: ApproxEq<N>, N>(a: &T, b: &T) -> bool { ApproxEq::approx_eq(a, b) } /// Tests approximate equality using a custom epsilon. #[inline(always)] pub fn approx_eq_eps<T: ApproxEq<N>, N>(a: &T, b: &T, eps: &N) -> bool { ApproxEq::approx_eq_eps(a, b, eps) } /* * Absolute<A> */ /// Computes a component-wise absolute value. #[inline(always)] pub fn abs<M: Absolute<Res>, Res>(m: &M) -> Res { Absolute::abs(m) } /* * Inv */ /// Gets an inverted copy of a matrix. #[inline(always)] pub fn inv<M: Inv>(m: &M) -> Option<M> { Inv::inv(m) } /* * Transpose */ /// Gets a transposed copy of a matrix. #[inline(always)] pub fn transpose<M: Transpose>(m: &M) -> M { Transpose::transpose(m) } /* * Outer<M> */ /// Computes the outer product of two vectors. #[inline(always)] pub fn outer<V: Outer>(a: &V, b: &V) -> V::OuterProductType { Outer::outer(a, b) } /* * Cov<M> */ /// Computes the covariance of a set of observations. #[inline(always)] pub fn cov<M: Cov<Res>, Res>(observations: &M) -> Res { Cov::cov(observations) } /* * Mean<N> */ /// Computes the mean of a set of observations. #[inline(always)] pub fn mean<N, M: Mean<N>>(observations: &M) -> N { Mean::mean(observations) } /* * EigenQR<N, V> */ /// Computes the eigenvalues and eigenvectors of a square matrix usin the QR algorithm. #[inline(always)] pub fn eigen_qr<N, V, M>(m: &M, eps: &N, niter: usize) -> (M, V) where V: Mul<M, Output = V>, M: EigenQR<N, V> { EigenQR::eigen_qr(m, eps, niter) } // // // Structure // // /* * Eye */ /// Construct the identity matrix for a given dimension #[inline(always)] pub fn new_identity<M: Eye>(dim: usize) -> M { Eye::new_identity(dim) } /* * Repeat */ /// Create an object by repeating a value. /// /// Same as `Identity::new()`. #[inline(always)] pub fn repeat<N, T: Repeat<N>>(val: N) -> T { Repeat::repeat(val) } /* * Basis */ /// Computes the canonical basis for a given dimension. #[inline(always)] pub fn canonical_basis<V: Basis, F: FnMut(V) -> bool>(f: F) { Basis::canonical_basis(f) } /// Computes the basis of the orthonormal subspace of a given vector. #[inline(always)] pub fn orthonormal_subspace_basis<V: Basis, F: FnMut(V) -> bool>(v: &V, f: F) { Basis::orthonormal_subspace_basis(v, f) } /// Gets the (0-based) i-th element of the canonical basis of V. #[inline] pub fn canonical_basis_element<V: Basis>(i: usize) -> Option<V> { Basis::canonical_basis_element(i) } /* * Row<R> */ /* * Col<C> */ /* * Diag<V> */ /// Gets the diagonal of a square matrix. #[inline(always)] pub fn diag<M: Diag<V>, V>(m: &M) -> V { m.diag() } /* * Dim */ /// Gets the dimension an object lives in. /// /// Same as `Dim::dim::(None::<V>)`. #[inline(always)] pub fn dim<V: Dim>() -> usize { Dim::dim(None::<V>) } /// Gets the indexable range of an object. #[inline(always)] pub fn shape<V: Shape<I>, I>(v: &V) -> I { v.shape() } /* * Cast<T> */ /// Converts an object from one type to another. /// /// For primitive types, this is the same as the
a.dist(b) }
identifier_body
lib.rs
This module re-exports everything and includes free functions for all traits methods doing out-of-place modifications. * You can import the whole prelude using: ```.ignore use nalgebra::*; ``` The preferred way to use **nalgebra** is to import types and traits explicitly, and call free-functions using the `na::` prefix: ```.rust extern crate nalgebra as na; use na::{Vec3, Rot3, Rotation}; fn main() { let a = Vec3::new(1.0f64, 1.0, 1.0); let mut b = Rot3::new(na::zero()); b.append_rotation_mut(&a); assert!(na::approx_eq(&na::rotation(&b), &a)); } ``` ## Features **nalgebra** is meant to be a general-purpose, low-dimensional, linear algebra library, with an optimized set of tools for computer graphics and physics. Those features include: * Vectors with static sizes: `Vec0`, `Vec1`, `Vec2`, `Vec3`, `Vec4`, `Vec5`, `Vec6`. * Points with static sizes: `Pnt0`, `Pnt1`, `Pnt2`, `Pnt3`, `Pnt4`, `Pnt5`, `Pnt6`. * Square matrices with static sizes: `Mat1`, `Mat2`, `Mat3`, `Mat4`, `Mat5`, `Mat6 `. * Rotation matrices: `Rot2`, `Rot3`, `Rot4`. * Quaternions: `Quat`, `UnitQuat`. * Isometries: `Iso2`, `Iso3`, `Iso4`. * 3D projections for computer graphics: `Persp3`, `PerspMat3`, `Ortho3`, `OrthoMat3`. * Dynamically sized vector: `DVec`. * Dynamically sized (square or rectangular) matrix: `DMat`. * A few methods for data analysis: `Cov`, `Mean`. * Almost one trait per functionality: useful for generic programming. * Operator overloading using multidispatch. ## **nalgebra** in use Here are some projects using **nalgebra**. Feel free to add your project to this list if you happen to use **nalgebra**! * [nphysics](https://github.com/sebcrozet/nphysics): a real-time physics engine. * [ncollide](https://github.com/sebcrozet/ncollide): a collision detection library. * [kiss3d](https://github.com/sebcrozet/kiss3d): a minimalistic graphics engine. * [nrays](https://github.com/sebcrozet/nrays): a ray tracer. */ #![deny(non_camel_case_types)] #![deny(unused_parens)] #![deny(non_upper_case_globals)] #![deny(unused_qualifications)] #![deny(unused_results)] #![warn(missing_docs)] #![doc(html_root_url = "http://nalgebra.org/doc")] extern crate rustc_serialize; extern crate rand; extern crate num; #[cfg(feature="arbitrary")] extern crate quickcheck; use std::cmp; use std::ops::{Neg, Mul}; use num::{Zero, One}; pub use traits::{ Absolute, AbsoluteRotate, ApproxEq, Axpy, Basis, BaseFloat, BaseNum, Bounded, Cast, Col, ColSlice, RowSlice, Cov, Cross, CrossMatrix, Det, Diag, Dim, Dot, EigenQR, Eye, FloatPnt, FloatVec, FromHomogeneous, Indexable, Inv, Iterable, IterableMut, Mat, Mean, Norm, NumPnt, NumVec, Orig, Outer, POrd, POrdering, PntAsVec, Repeat, Rotate, Rotation, RotationMatrix, RotationWithTranslation, RotationTo, Row, Shape, SquareMat, ToHomogeneous, Transform, Transformation, Translate, Translation, Transpose, UniformSphereSample }; pub use structs::{ Identity, DMat, DVec, DVec1, DVec2, DVec3, DVec4, DVec5, DVec6, Iso2, Iso3, Iso4, Mat1, Mat2, Mat3, Mat4, Mat5, Mat6, Rot2, Rot3, Rot4, Vec0, Vec1, Vec2, Vec3, Vec4, Vec5, Vec6, Pnt0, Pnt1, Pnt2, Pnt3, Pnt4, Pnt5, Pnt6, Persp3, PerspMat3, Ortho3, OrthoMat3, Quat, UnitQuat }; pub use linalg::{ qr, householder_matrix, cholesky }; mod structs; mod traits; mod linalg; mod macros; // mod lower_triangular; // mod chol; /// Change the input value to ensure it is on the range `[min, max]`. #[inline(always)] pub fn clamp<T: PartialOrd>(val: T, min: T, max: T) -> T { if val > min { if val < max { val } else { max } } else { min } } /// Same as `cmp::max`. #[inline(always)] pub fn max<T: Ord>(a: T, b: T) -> T { cmp::max(a, b) } /// Same as `cmp::min`. #[inline(always)] pub fn min<T: Ord>(a: T, b: T) -> T { cmp::min(a, b) } /// Returns the infimum of `a` and `b`. #[inline(always)] pub fn inf<T: POrd>(a: &T, b: &T) -> T { POrd::inf(a, b) } /// Returns the supremum of `a` and `b`. #[inline(always)] pub fn sup<T: POrd>(a: &T, b: &T) -> T { POrd::sup(a, b) } /// Compare `a` and `b` using a partial ordering relation. #[inline(always)] pub fn partial_cmp<T: POrd>(a: &T, b: &T) -> POrdering { POrd::partial_cmp(a, b) } /// Returns `true` iff `a` and `b` are comparable and `a < b`. #[inline(always)] pub fn partial_lt<T: POrd>(a: &T, b: &T) -> bool { POrd::partial_lt(a, b) } /// Returns `true` iff `a` and `b` are comparable and `a <= b`. #[inline(always)] pub fn partial_le<T: POrd>(a: &T, b: &T) -> bool { POrd::partial_le(a, b) } /// Returns `true` iff `a` and `b` are comparable and `a > b`. #[inline(always)] pub fn partial_gt<T: POrd>(a: &T, b: &T) -> bool { POrd::partial_gt(a, b) } /// Returns `true` iff `a` and `b` are comparable and `a >= b`. #[inline(always)] pub fn partial_ge<T: POrd>(a: &T, b: &T) -> bool { POrd::partial_ge(a, b) } /// Return the minimum of `a` and `b` if they are comparable. #[inline(always)] pub fn partial_min<'a, T: POrd>(a: &'a T, b: &'a T) -> Option<&'a T> { POrd::partial_min(a, b) } /// Return the maximum of `a` and `b` if they are comparable. #[inline(always)] pub fn partial_max<'a, T: POrd>(a: &'a T, b: &'a T) -> Option<&'a T> { POrd::partial_max(a, b) } /// Clamp `value` between `min` and `max`. Returns `None` if `value` is not comparable to /// `min` or `max`. #[inline(always)] pub fn partial_clamp<'a, T: POrd>(value: &'a T, min: &'a T, max: &'a T) -> Option<&'a T> { POrd::partial_clamp(value, min, max) } // // // Constructors // // /// Create a special identity object. /// /// Same as `Identity::new()`. #[inline(always)] pub fn identity() -> Identity { Identity::new() } /// Create a zero-valued value. /// /// This is the same as `std::num::zero()`. #[inline(always)] pub fn zero<T: Zero>() -> T { Zero::zero() } /// Tests is a value is iqual to zero. #[inline(always)] pub fn is_zero<T: Zero>(val: &T) -> bool { val.is_zero() } /// Create a one-valued value. /// /// This is the same as `std::num::one()`. #[inline(always)] pub fn one<T: One>() -> T { One::one() } // // // Geometry // // /// Returns the trivial origin of an affine space. #[inline(always)] pub fn orig<P: Orig>() -> P { Orig::orig() } /// Returns the center of two points. #[inline] pub fn center<N: BaseFloat, P: FloatPnt<N, V>, V: Copy + Norm<N>>(a: &P, b: &P) -> P { let _2 = one::<N>() + one(); (*a + *b.as_vec()) / _2 } /* * FloatPnt */ /// Returns the distance between two points. #[inline(always)] pub fn dist<N: BaseFloat, P: FloatPnt<N, V>, V: Norm<N>>(a: &P, b: &P) -> N { a.dist(b) } /// Returns the squared distance between two points. #[inline(always)] pub fn sqdist<N: BaseFloat, P: FloatPnt<N, V>, V: Norm<N>>(a: &P, b: &P) -> N { a.sqdist(b) } /* * Translation<V> */ /// Gets the translation applicable by `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Iso3}; /// /// fn main() { /// let t = Iso3::new(Vec3::new(1.0f64, 1.0, 1.0), na::zero()); /// let trans = na::translation(&t); /// /// assert!(trans == Vec3::new(1.0, 1.0, 1.0)); /// } /// ``` #[inline(always)] pub fn translation<V, M: Translation<V>>(m: &M) -> V { m.translation() } /// Gets the inverse translation applicable by `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Iso3}; /// /// fn main() { /// let t = Iso3::new(Vec3::new(1.0f64, 1.0, 1.0), na::zero()); /// let itrans = na::inv_translation(&t); /// /// assert!(itrans == Vec3::new(-1.0, -1.0, -1.0)); /// } /// ``` #[inline(always)] pub fn inv_translation<V, M: Translation<V>>(m: &M) -> V { m.inv_translation() } /// Applies the translation `v` to a copy of `m`. #[inline(always)] pub fn append_translation<V, M: Translation<V>>(m: &M, v: &V) -> M { Translation::append_translation(m, v) } /* * Translate<P> */ /// Applies a translation to a point. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Pnt3, Vec3, Iso3}; /// /// fn main() { /// let t = Iso3::new(Vec3::new(1.0f64, 1.0, 1.0), na::zero()); /// let p = Pnt3::new(2.0, 2.0, 2.0); /// /// let tp = na::translate(&t, &p); /// /// assert!(tp == Pnt3::new(3.0, 3.0, 3.0))
/// } /// ``` #[inline(always)] pub fn translate<P, M: Translate<P>>(m: &M, p: &P) -> P { m.translate(p) } /// Applies an inverse translation to a point. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Pnt3, Vec3, Iso3}; /// /// fn main() { /// let t = Iso3::new(Vec3::new(1.0f64, 1.0, 1.0), na::zero()); /// let p = Pnt3::new(2.0, 2.0, 2.0); /// /// let tp = na::inv_translate(&t, &p); /// /// assert!(na::approx_eq(&tp, &Pnt3::new(1.0, 1.0, 1.0))) /// } #[inline(always)] pub fn inv_translate<P, M: Translate<P>>(m: &M, p: &P) -> P { m.inv_translate(p) } /* * Rotation<V> */ /// Gets the rotation applicable by `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Rot3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(1.0f64, 1.0, 1.0)); /// /// assert!(na::approx_eq(&na::rotation(&t), &Vec3::new(1.0, 1.0, 1.0))); /// } /// ``` #[inline(always)] pub fn rotation<V, M: Rotation<V>>(m: &M) -> V { m.rotation() } /// Gets the inverse rotation applicable by `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Rot3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(1.0f64, 1.0, 1.0)); /// /// assert!(na::approx_eq(&na::inv_rotation(&t), &Vec3::new(-1.0, -1.0, -1.0))); /// } /// ``` #[inline(always)] pub fn inv_rotation<V, M: Rotation<V>>(m: &M) -> V { m.inv_rotation() } // FIXME: this example is a bit shity /// Applies the rotation `v` to a copy of `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Rot3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(0.0f64, 0.0, 0.0)); /// let v = Vec3::new(1.0, 1.0, 1.0); /// let rt = na::append_rotation(&t, &v); /// /// assert!(na::approx_eq(&na::rotation(&rt), &Vec3::new(1.0, 1.0, 1.0))) /// } /// ``` #[inline(always)] pub fn append_rotation<V, M: Rotation<V>>(m: &M, v: &V) -> M { Rotation::append_rotation(m, v) } // FIXME: this example is a bit shity /// Pre-applies the rotation `v` to a copy of `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Rot3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(0.0f64, 0.0, 0.0)); /// let v = Vec3::new(1.0, 1.0, 1.0); /// let rt = na::prepend_rotation(&t, &v); /// /// assert!(na::approx_eq(&na::rotation(&rt), &Vec3::new(1.0, 1.0, 1.0))) /// } /// ``` #[inline(always)] pub fn prepend_rotation<V, M: Rotation<V>>(m: &M, v: &V) -> M { Rotation::prepend_rotation(m, v) } /* * Rotate<V> */ /// Applies a rotation to a vector. /// /// ```rust /// extern crate nalgebra as na; /// use na::{BaseFloat, Rot3, Vec3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(0.0f64, 0.0, 0.5 * <f64 as BaseFloat>::pi())); /// let v = Vec3::new(1.0, 0.0, 0.0); /// /// let tv = na::rotate(&t, &v); /// /// assert!(na::approx_eq(&tv, &Vec3::new(0.0, 1.0, 0.0))) /// } /// ``` #[inline(always)] pub fn rotate<V, M: Rotate<V>>(m: &M, v: &V) -> V { m.rotate(v) } /// Applies an inverse rotation to a vector. /// /// ```rust /// extern crate nalgebra as na; /// use na::{BaseFloat, Rot3, Vec3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(0.0f64, 0.0, 0.5 * <f64 as BaseFloat>::pi())); /// let v = Vec3::new(1.0, 0.0, 0.0); /// /// let tv = na::inv_rotate(&t, &v); /// /// assert!(na::approx_eq(&tv, &Vec3::new(0.0, -1.0, 0.0))) /// } /// ``` #[inline(always)] pub fn inv_rotate<V, M: Rotate<V>>(m: &M, v: &V) -> V { m.inv_rotate(v) } /* * RotationWithTranslation<LV, AV> */ /// Rotates a copy of `m` by `amount` using `center` as the pivot point. #[inline(always)] pub fn append_rotation_wrt_point<LV: Neg<Output = LV> + Copy, AV, M: RotationWithTranslation<LV, AV>>( m: &M, amount: &AV, center: &LV) -> M { RotationWithTranslation::append_rotation_wrt_point(m, amount, center) } /// Rotates a copy of `m` by `amount` using `m.translation()` as the pivot point. #[inline(always)] pub fn append_rotation_wrt_center<LV: Neg<Output = LV> + Copy, AV, M: RotationWithTranslation<LV, AV>>( m: &M, amount: &AV) -> M { RotationWithTranslation::append_rotation_wrt_center(m, amount) } /* * RotationTo */ /// Computes the angle of the rotation needed to transfom `a` to `b`. #[inline(always)] pub fn angle_between<V: RotationTo>(a: &V, b: &V) -> V::AngleType { a.angle_to(b) } /// Computes the rotation needed to transform `a` to `b`. #[inline(always)] pub fn rotation_between<V: RotationTo>(a: &V, b: &V) -> V::DeltaRotationType { a.rotation_to(b) } /* * RotationMatrix<LV, AV, R> */ /// Builds a rotation matrix from `r`. #[inline(always)] pub fn to_rot_mat<N, LV, AV, R, M>(r: &R) -> M where R: RotationMatrix<N, LV, AV, Output = M>, M: SquareMat<N, LV> + Rotation<AV> + Copy, LV: Mul<M, Output = LV> { // FIXME: rust-lang/rust#20413 r.to_rot_mat() } /* * AbsoluteRotate<V> */ /// Applies a rotation using the absolute values of its components. #[inline(always)] pub fn absolute_rotate<V, M: AbsoluteRotate<V>>(m: &M, v: &V) -> V { m.absolute_rotate(v) } /* * Transformation<T> */ /// Gets the transformation applicable by `m`. #[inline(always)] pub fn transformation<T, M: Transformation<T>>(m: &M) -> T { m.transformation() } /// Gets the inverse transformation applicable by `m`. #[inline(always)] pub fn inv_transformation<T, M: Transformation<T>>(m: &M) -> T { m.inv_transformation() } /// Gets a transformed copy of `m`. #[inline(always)] pub fn append_transformation<T, M: Transformation<T>>(m: &M, t: &T) -> M { Transformation::append_transformation(m, t) } /* * Transform<V> */ /// Applies a transformation to a vector. #[inline(always)] pub fn transform<V, M: Transform<V>>(m: &M, v: &V) -> V { m.transform(v) } /// Applies an inverse transformation to a vector. #[inline(always)] pub fn inv_transform<V, M: Transform<V>>(m: &M, v: &V) -> V { m.inv_transform(v) } /* * Dot<N> */ /// Computes the dot product of two vectors. #[inline(always)] pub fn dot<V: Dot<N>, N>(a: &V, b: &V) -> N { Dot::dot(a, b) } /* * Norm<N> */ /// Computes the L2 norm of a vector. #[inline(always)] pub fn norm<V: Norm<N>, N: BaseFloat>(v: &V) -> N { Norm::norm(v) } /// Computes the squared L2 norm of a vector. #[inline(always)] pub fn sqnorm<V: Norm<N>, N: BaseFloat>(v: &V) -> N { Norm::sqnorm(v) } /// Gets the normalized version of a vector. #[inline(always)] pub fn normalize<V: Norm<N>, N: BaseFloat>(v: &V) -> V { Norm::normalize(v) } /* * Det<N> */ /// Computes the determinant of a square matrix. #[inline(always)] pub fn det<M: Det<N>, N>(m: &M) -> N { Det::det(m) } /* * Cross<V> */ /// Computes the cross product of two vectors. #[inline(always)] pub fn cross<LV: Cross>(a: &LV, b: &LV) -> LV::CrossProductType { Cross::cross(a, b) } /* * CrossMatrix<M> */ /// Given a vector, computes the matrix which, when multiplied by another vector, computes a cross /// product. #[inline(always)] pub fn cross_matrix<V: CrossMatrix<M>, M>(v: &V) -> M { CrossMatrix::cross_matrix(v) } /* * ToHomogeneous<U> */ /// Converts a matrix or vector to homogeneous coordinates. #[inline(always)] pub fn to_homogeneous<M: ToHomogeneous<Res>, Res>(m: &M) -> Res { ToHomogeneous::to_homogeneous(m) } /* * FromHomogeneous<U> */ /// Converts a matrix or vector from homogeneous coordinates. /// /// w-normalization is appied. #[inline(always)] pub fn from_homogeneous<M, Res: FromHomogeneous<M>>(m: &M) -> Res { FromHomogeneous::from(m) } /* * UniformSphereSample */ /// Samples the unit sphere living on the dimension as the samples types. /// /// The number of sampling point is implementation-specific. It is always uniform. #[inline(always)] pub fn sample_sphere<V: UniformSphereSample, F: FnMut(V)>(f: F) { UniformSphereSample::sample(f) } // // // Operations // // /* * AproxEq<N> */ /// Tests approximate equality. #[inline(always)] pub fn approx_eq<T: ApproxEq<N>, N>(a: &T, b: &T) -> bool { ApproxEq::approx_eq(a, b) } /// Tests approximate equality using a custom epsilon. #[inline(always)] pub fn approx_eq_eps<T: ApproxEq<N>, N>(a: &T, b: &T, eps: &N) -> bool { ApproxEq::approx_eq_eps(a, b, eps) } /* * Absolute<A> */ /// Computes a component-wise absolute value. #[inline(always)] pub fn abs<M: Absolute<Res>, Res>(m: &M) -> Res { Absolute::abs(m) } /* * Inv */ /// Gets an inverted copy of a matrix. #[inline(always)] pub fn inv<M: Inv>(m: &M) -> Option<M> { Inv::inv(m) } /* * Transpose */ /// Gets a transposed copy of a matrix. #[inline(always)] pub fn transpose<M: Transpose>(m: &M) -> M { Transpose::transpose(m) } /* * Outer<M> */ /// Computes the outer product of two vectors. #[inline(always)] pub fn outer<V: Outer>(a: &V, b: &V) -> V::OuterProductType { Outer::outer(a, b) } /* * Cov<M> */ /// Computes the covariance of a set of observations. #[inline(always)] pub fn cov<M: Cov<Res>, Res>(observations: &M) -> Res { Cov::cov(observations) } /* * Mean<N> */ /// Computes the mean of a set of observations. #[inline(always)] pub fn mean<N, M: Mean<N>>(observations: &M) -> N { Mean::mean(observations) } /* * EigenQR<N, V> */ /// Computes the eigenvalues and eigenvectors of a square matrix usin the QR algorithm. #[inline(always)] pub fn eigen_qr<N, V, M>(m: &M, eps: &N, niter: usize) -> (M, V) where V: Mul<M, Output = V>, M: EigenQR<N, V> { EigenQR::eigen_qr(m, eps, niter) } // // // Structure // // /* * Eye */ /// Construct the identity matrix for a given dimension #[inline(always)] pub fn new_identity<M: Eye>(dim: usize) -> M { Eye::new_identity(dim) } /* * Repeat */ /// Create an object by repeating a value. /// /// Same as `Identity::new()`. #[inline(always)] pub fn repeat<N, T: Repeat<N>>(val: N) -> T { Repeat::repeat(val) } /* * Basis */ /// Computes the canonical basis for a given dimension. #[inline(always)] pub fn canonical_basis<V: Basis, F: FnMut(V) -> bool>(f: F) { Basis::canonical_basis(f) } /// Computes the basis of the orthonormal subspace of a given vector. #[inline(always)] pub fn orthonormal_subspace_basis<V: Basis, F: FnMut(V) -> bool>(v: &V, f: F) { Basis::orthonormal_subspace_basis(v, f) } /// Gets the (0-based) i-th element of the canonical basis of V. #[inline] pub fn canonical_basis_element<V: Basis>(i: usize) -> Option<V> { Basis::canonical_basis_element(i) } /* * Row<R> */ /* * Col<C> */ /* * Diag<V> */ /// Gets the diagonal of a square matrix. #[inline(always)] pub fn diag<M: Diag<V>, V>(m: &M) -> V { m.diag() } /* * Dim */ /// Gets the dimension an object lives in. /// /// Same as `Dim::dim::(None::<V>)`. #[inline(always)] pub fn dim<V: Dim>() -> usize { Dim::dim(None::<V>) } /// Gets the indexable range of an object. #[inline(always)] pub fn shape<V: Shape<I>, I>(v: &V) -> I { v.shape() } /* * Cast<T> */ /// Converts an object from one type to another. /// /// For primitive types, this is the same as the
random_line_split
lib.rs
This module re-exports everything and includes free functions for all traits methods doing out-of-place modifications. * You can import the whole prelude using: ```.ignore use nalgebra::*; ``` The preferred way to use **nalgebra** is to import types and traits explicitly, and call free-functions using the `na::` prefix: ```.rust extern crate nalgebra as na; use na::{Vec3, Rot3, Rotation}; fn main() { let a = Vec3::new(1.0f64, 1.0, 1.0); let mut b = Rot3::new(na::zero()); b.append_rotation_mut(&a); assert!(na::approx_eq(&na::rotation(&b), &a)); } ``` ## Features **nalgebra** is meant to be a general-purpose, low-dimensional, linear algebra library, with an optimized set of tools for computer graphics and physics. Those features include: * Vectors with static sizes: `Vec0`, `Vec1`, `Vec2`, `Vec3`, `Vec4`, `Vec5`, `Vec6`. * Points with static sizes: `Pnt0`, `Pnt1`, `Pnt2`, `Pnt3`, `Pnt4`, `Pnt5`, `Pnt6`. * Square matrices with static sizes: `Mat1`, `Mat2`, `Mat3`, `Mat4`, `Mat5`, `Mat6 `. * Rotation matrices: `Rot2`, `Rot3`, `Rot4`. * Quaternions: `Quat`, `UnitQuat`. * Isometries: `Iso2`, `Iso3`, `Iso4`. * 3D projections for computer graphics: `Persp3`, `PerspMat3`, `Ortho3`, `OrthoMat3`. * Dynamically sized vector: `DVec`. * Dynamically sized (square or rectangular) matrix: `DMat`. * A few methods for data analysis: `Cov`, `Mean`. * Almost one trait per functionality: useful for generic programming. * Operator overloading using multidispatch. ## **nalgebra** in use Here are some projects using **nalgebra**. Feel free to add your project to this list if you happen to use **nalgebra**! * [nphysics](https://github.com/sebcrozet/nphysics): a real-time physics engine. * [ncollide](https://github.com/sebcrozet/ncollide): a collision detection library. * [kiss3d](https://github.com/sebcrozet/kiss3d): a minimalistic graphics engine. * [nrays](https://github.com/sebcrozet/nrays): a ray tracer. */ #![deny(non_camel_case_types)] #![deny(unused_parens)] #![deny(non_upper_case_globals)] #![deny(unused_qualifications)] #![deny(unused_results)] #![warn(missing_docs)] #![doc(html_root_url = "http://nalgebra.org/doc")] extern crate rustc_serialize; extern crate rand; extern crate num; #[cfg(feature="arbitrary")] extern crate quickcheck; use std::cmp; use std::ops::{Neg, Mul}; use num::{Zero, One}; pub use traits::{ Absolute, AbsoluteRotate, ApproxEq, Axpy, Basis, BaseFloat, BaseNum, Bounded, Cast, Col, ColSlice, RowSlice, Cov, Cross, CrossMatrix, Det, Diag, Dim, Dot, EigenQR, Eye, FloatPnt, FloatVec, FromHomogeneous, Indexable, Inv, Iterable, IterableMut, Mat, Mean, Norm, NumPnt, NumVec, Orig, Outer, POrd, POrdering, PntAsVec, Repeat, Rotate, Rotation, RotationMatrix, RotationWithTranslation, RotationTo, Row, Shape, SquareMat, ToHomogeneous, Transform, Transformation, Translate, Translation, Transpose, UniformSphereSample }; pub use structs::{ Identity, DMat, DVec, DVec1, DVec2, DVec3, DVec4, DVec5, DVec6, Iso2, Iso3, Iso4, Mat1, Mat2, Mat3, Mat4, Mat5, Mat6, Rot2, Rot3, Rot4, Vec0, Vec1, Vec2, Vec3, Vec4, Vec5, Vec6, Pnt0, Pnt1, Pnt2, Pnt3, Pnt4, Pnt5, Pnt6, Persp3, PerspMat3, Ortho3, OrthoMat3, Quat, UnitQuat }; pub use linalg::{ qr, householder_matrix, cholesky }; mod structs; mod traits; mod linalg; mod macros; // mod lower_triangular; // mod chol; /// Change the input value to ensure it is on the range `[min, max]`. #[inline(always)] pub fn clamp<T: PartialOrd>(val: T, min: T, max: T) -> T { if val > min { if val < max {
else { max } } else { min } } /// Same as `cmp::max`. #[inline(always)] pub fn max<T: Ord>(a: T, b: T) -> T { cmp::max(a, b) } /// Same as `cmp::min`. #[inline(always)] pub fn min<T: Ord>(a: T, b: T) -> T { cmp::min(a, b) } /// Returns the infimum of `a` and `b`. #[inline(always)] pub fn inf<T: POrd>(a: &T, b: &T) -> T { POrd::inf(a, b) } /// Returns the supremum of `a` and `b`. #[inline(always)] pub fn sup<T: POrd>(a: &T, b: &T) -> T { POrd::sup(a, b) } /// Compare `a` and `b` using a partial ordering relation. #[inline(always)] pub fn partial_cmp<T: POrd>(a: &T, b: &T) -> POrdering { POrd::partial_cmp(a, b) } /// Returns `true` iff `a` and `b` are comparable and `a < b`. #[inline(always)] pub fn partial_lt<T: POrd>(a: &T, b: &T) -> bool { POrd::partial_lt(a, b) } /// Returns `true` iff `a` and `b` are comparable and `a <= b`. #[inline(always)] pub fn partial_le<T: POrd>(a: &T, b: &T) -> bool { POrd::partial_le(a, b) } /// Returns `true` iff `a` and `b` are comparable and `a > b`. #[inline(always)] pub fn partial_gt<T: POrd>(a: &T, b: &T) -> bool { POrd::partial_gt(a, b) } /// Returns `true` iff `a` and `b` are comparable and `a >= b`. #[inline(always)] pub fn partial_ge<T: POrd>(a: &T, b: &T) -> bool { POrd::partial_ge(a, b) } /// Return the minimum of `a` and `b` if they are comparable. #[inline(always)] pub fn partial_min<'a, T: POrd>(a: &'a T, b: &'a T) -> Option<&'a T> { POrd::partial_min(a, b) } /// Return the maximum of `a` and `b` if they are comparable. #[inline(always)] pub fn partial_max<'a, T: POrd>(a: &'a T, b: &'a T) -> Option<&'a T> { POrd::partial_max(a, b) } /// Clamp `value` between `min` and `max`. Returns `None` if `value` is not comparable to /// `min` or `max`. #[inline(always)] pub fn partial_clamp<'a, T: POrd>(value: &'a T, min: &'a T, max: &'a T) -> Option<&'a T> { POrd::partial_clamp(value, min, max) } // // // Constructors // // /// Create a special identity object. /// /// Same as `Identity::new()`. #[inline(always)] pub fn identity() -> Identity { Identity::new() } /// Create a zero-valued value. /// /// This is the same as `std::num::zero()`. #[inline(always)] pub fn zero<T: Zero>() -> T { Zero::zero() } /// Tests is a value is iqual to zero. #[inline(always)] pub fn is_zero<T: Zero>(val: &T) -> bool { val.is_zero() } /// Create a one-valued value. /// /// This is the same as `std::num::one()`. #[inline(always)] pub fn one<T: One>() -> T { One::one() } // // // Geometry // // /// Returns the trivial origin of an affine space. #[inline(always)] pub fn orig<P: Orig>() -> P { Orig::orig() } /// Returns the center of two points. #[inline] pub fn center<N: BaseFloat, P: FloatPnt<N, V>, V: Copy + Norm<N>>(a: &P, b: &P) -> P { let _2 = one::<N>() + one(); (*a + *b.as_vec()) / _2 } /* * FloatPnt */ /// Returns the distance between two points. #[inline(always)] pub fn dist<N: BaseFloat, P: FloatPnt<N, V>, V: Norm<N>>(a: &P, b: &P) -> N { a.dist(b) } /// Returns the squared distance between two points. #[inline(always)] pub fn sqdist<N: BaseFloat, P: FloatPnt<N, V>, V: Norm<N>>(a: &P, b: &P) -> N { a.sqdist(b) } /* * Translation<V> */ /// Gets the translation applicable by `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Iso3}; /// /// fn main() { /// let t = Iso3::new(Vec3::new(1.0f64, 1.0, 1.0), na::zero()); /// let trans = na::translation(&t); /// /// assert!(trans == Vec3::new(1.0, 1.0, 1.0)); /// } /// ``` #[inline(always)] pub fn translation<V, M: Translation<V>>(m: &M) -> V { m.translation() } /// Gets the inverse translation applicable by `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Iso3}; /// /// fn main() { /// let t = Iso3::new(Vec3::new(1.0f64, 1.0, 1.0), na::zero()); /// let itrans = na::inv_translation(&t); /// /// assert!(itrans == Vec3::new(-1.0, -1.0, -1.0)); /// } /// ``` #[inline(always)] pub fn inv_translation<V, M: Translation<V>>(m: &M) -> V { m.inv_translation() } /// Applies the translation `v` to a copy of `m`. #[inline(always)] pub fn append_translation<V, M: Translation<V>>(m: &M, v: &V) -> M { Translation::append_translation(m, v) } /* * Translate<P> */ /// Applies a translation to a point. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Pnt3, Vec3, Iso3}; /// /// fn main() { /// let t = Iso3::new(Vec3::new(1.0f64, 1.0, 1.0), na::zero()); /// let p = Pnt3::new(2.0, 2.0, 2.0); /// /// let tp = na::translate(&t, &p); /// /// assert!(tp == Pnt3::new(3.0, 3.0, 3.0)) /// } /// ``` #[inline(always)] pub fn translate<P, M: Translate<P>>(m: &M, p: &P) -> P { m.translate(p) } /// Applies an inverse translation to a point. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Pnt3, Vec3, Iso3}; /// /// fn main() { /// let t = Iso3::new(Vec3::new(1.0f64, 1.0, 1.0), na::zero()); /// let p = Pnt3::new(2.0, 2.0, 2.0); /// /// let tp = na::inv_translate(&t, &p); /// /// assert!(na::approx_eq(&tp, &Pnt3::new(1.0, 1.0, 1.0))) /// } #[inline(always)] pub fn inv_translate<P, M: Translate<P>>(m: &M, p: &P) -> P { m.inv_translate(p) } /* * Rotation<V> */ /// Gets the rotation applicable by `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Rot3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(1.0f64, 1.0, 1.0)); /// /// assert!(na::approx_eq(&na::rotation(&t), &Vec3::new(1.0, 1.0, 1.0))); /// } /// ``` #[inline(always)] pub fn rotation<V, M: Rotation<V>>(m: &M) -> V { m.rotation() } /// Gets the inverse rotation applicable by `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Rot3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(1.0f64, 1.0, 1.0)); /// /// assert!(na::approx_eq(&na::inv_rotation(&t), &Vec3::new(-1.0, -1.0, -1.0))); /// } /// ``` #[inline(always)] pub fn inv_rotation<V, M: Rotation<V>>(m: &M) -> V { m.inv_rotation() } // FIXME: this example is a bit shity /// Applies the rotation `v` to a copy of `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Rot3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(0.0f64, 0.0, 0.0)); /// let v = Vec3::new(1.0, 1.0, 1.0); /// let rt = na::append_rotation(&t, &v); /// /// assert!(na::approx_eq(&na::rotation(&rt), &Vec3::new(1.0, 1.0, 1.0))) /// } /// ``` #[inline(always)] pub fn append_rotation<V, M: Rotation<V>>(m: &M, v: &V) -> M { Rotation::append_rotation(m, v) } // FIXME: this example is a bit shity /// Pre-applies the rotation `v` to a copy of `m`. /// /// ```rust /// extern crate nalgebra as na; /// use na::{Vec3, Rot3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(0.0f64, 0.0, 0.0)); /// let v = Vec3::new(1.0, 1.0, 1.0); /// let rt = na::prepend_rotation(&t, &v); /// /// assert!(na::approx_eq(&na::rotation(&rt), &Vec3::new(1.0, 1.0, 1.0))) /// } /// ``` #[inline(always)] pub fn prepend_rotation<V, M: Rotation<V>>(m: &M, v: &V) -> M { Rotation::prepend_rotation(m, v) } /* * Rotate<V> */ /// Applies a rotation to a vector. /// /// ```rust /// extern crate nalgebra as na; /// use na::{BaseFloat, Rot3, Vec3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(0.0f64, 0.0, 0.5 * <f64 as BaseFloat>::pi())); /// let v = Vec3::new(1.0, 0.0, 0.0); /// /// let tv = na::rotate(&t, &v); /// /// assert!(na::approx_eq(&tv, &Vec3::new(0.0, 1.0, 0.0))) /// } /// ``` #[inline(always)] pub fn rotate<V, M: Rotate<V>>(m: &M, v: &V) -> V { m.rotate(v) } /// Applies an inverse rotation to a vector. /// /// ```rust /// extern crate nalgebra as na; /// use na::{BaseFloat, Rot3, Vec3}; /// /// fn main() { /// let t = Rot3::new(Vec3::new(0.0f64, 0.0, 0.5 * <f64 as BaseFloat>::pi())); /// let v = Vec3::new(1.0, 0.0, 0.0); /// /// let tv = na::inv_rotate(&t, &v); /// /// assert!(na::approx_eq(&tv, &Vec3::new(0.0, -1.0, 0.0))) /// } /// ``` #[inline(always)] pub fn inv_rotate<V, M: Rotate<V>>(m: &M, v: &V) -> V { m.inv_rotate(v) } /* * RotationWithTranslation<LV, AV> */ /// Rotates a copy of `m` by `amount` using `center` as the pivot point. #[inline(always)] pub fn append_rotation_wrt_point<LV: Neg<Output = LV> + Copy, AV, M: RotationWithTranslation<LV, AV>>( m: &M, amount: &AV, center: &LV) -> M { RotationWithTranslation::append_rotation_wrt_point(m, amount, center) } /// Rotates a copy of `m` by `amount` using `m.translation()` as the pivot point. #[inline(always)] pub fn append_rotation_wrt_center<LV: Neg<Output = LV> + Copy, AV, M: RotationWithTranslation<LV, AV>>( m: &M, amount: &AV) -> M { RotationWithTranslation::append_rotation_wrt_center(m, amount) } /* * RotationTo */ /// Computes the angle of the rotation needed to transfom `a` to `b`. #[inline(always)] pub fn angle_between<V: RotationTo>(a: &V, b: &V) -> V::AngleType { a.angle_to(b) } /// Computes the rotation needed to transform `a` to `b`. #[inline(always)] pub fn rotation_between<V: RotationTo>(a: &V, b: &V) -> V::DeltaRotationType { a.rotation_to(b) } /* * RotationMatrix<LV, AV, R> */ /// Builds a rotation matrix from `r`. #[inline(always)] pub fn to_rot_mat<N, LV, AV, R, M>(r: &R) -> M where R: RotationMatrix<N, LV, AV, Output = M>, M: SquareMat<N, LV> + Rotation<AV> + Copy, LV: Mul<M, Output = LV> { // FIXME: rust-lang/rust#20413 r.to_rot_mat() } /* * AbsoluteRotate<V> */ /// Applies a rotation using the absolute values of its components. #[inline(always)] pub fn absolute_rotate<V, M: AbsoluteRotate<V>>(m: &M, v: &V) -> V { m.absolute_rotate(v) } /* * Transformation<T> */ /// Gets the transformation applicable by `m`. #[inline(always)] pub fn transformation<T, M: Transformation<T>>(m: &M) -> T { m.transformation() } /// Gets the inverse transformation applicable by `m`. #[inline(always)] pub fn inv_transformation<T, M: Transformation<T>>(m: &M) -> T { m.inv_transformation() } /// Gets a transformed copy of `m`. #[inline(always)] pub fn append_transformation<T, M: Transformation<T>>(m: &M, t: &T) -> M { Transformation::append_transformation(m, t) } /* * Transform<V> */ /// Applies a transformation to a vector. #[inline(always)] pub fn transform<V, M: Transform<V>>(m: &M, v: &V) -> V { m.transform(v) } /// Applies an inverse transformation to a vector. #[inline(always)] pub fn inv_transform<V, M: Transform<V>>(m: &M, v: &V) -> V { m.inv_transform(v) } /* * Dot<N> */ /// Computes the dot product of two vectors. #[inline(always)] pub fn dot<V: Dot<N>, N>(a: &V, b: &V) -> N { Dot::dot(a, b) } /* * Norm<N> */ /// Computes the L2 norm of a vector. #[inline(always)] pub fn norm<V: Norm<N>, N: BaseFloat>(v: &V) -> N { Norm::norm(v) } /// Computes the squared L2 norm of a vector. #[inline(always)] pub fn sqnorm<V: Norm<N>, N: BaseFloat>(v: &V) -> N { Norm::sqnorm(v) } /// Gets the normalized version of a vector. #[inline(always)] pub fn normalize<V: Norm<N>, N: BaseFloat>(v: &V) -> V { Norm::normalize(v) } /* * Det<N> */ /// Computes the determinant of a square matrix. #[inline(always)] pub fn det<M: Det<N>, N>(m: &M) -> N { Det::det(m) } /* * Cross<V> */ /// Computes the cross product of two vectors. #[inline(always)] pub fn cross<LV: Cross>(a: &LV, b: &LV) -> LV::CrossProductType { Cross::cross(a, b) } /* * CrossMatrix<M> */ /// Given a vector, computes the matrix which, when multiplied by another vector, computes a cross /// product. #[inline(always)] pub fn cross_matrix<V: CrossMatrix<M>, M>(v: &V) -> M { CrossMatrix::cross_matrix(v) } /* * ToHomogeneous<U> */ /// Converts a matrix or vector to homogeneous coordinates. #[inline(always)] pub fn to_homogeneous<M: ToHomogeneous<Res>, Res>(m: &M) -> Res { ToHomogeneous::to_homogeneous(m) } /* * FromHomogeneous<U> */ /// Converts a matrix or vector from homogeneous coordinates. /// /// w-normalization is appied. #[inline(always)] pub fn from_homogeneous<M, Res: FromHomogeneous<M>>(m: &M) -> Res { FromHomogeneous::from(m) } /* * UniformSphereSample */ /// Samples the unit sphere living on the dimension as the samples types. /// /// The number of sampling point is implementation-specific. It is always uniform. #[inline(always)] pub fn sample_sphere<V: UniformSphereSample, F: FnMut(V)>(f: F) { UniformSphereSample::sample(f) } // // // Operations // // /* * AproxEq<N> */ /// Tests approximate equality. #[inline(always)] pub fn approx_eq<T: ApproxEq<N>, N>(a: &T, b: &T) -> bool { ApproxEq::approx_eq(a, b) } /// Tests approximate equality using a custom epsilon. #[inline(always)] pub fn approx_eq_eps<T: ApproxEq<N>, N>(a: &T, b: &T, eps: &N) -> bool { ApproxEq::approx_eq_eps(a, b, eps) } /* * Absolute<A> */ /// Computes a component-wise absolute value. #[inline(always)] pub fn abs<M: Absolute<Res>, Res>(m: &M) -> Res { Absolute::abs(m) } /* * Inv */ /// Gets an inverted copy of a matrix. #[inline(always)] pub fn inv<M: Inv>(m: &M) -> Option<M> { Inv::inv(m) } /* * Transpose */ /// Gets a transposed copy of a matrix. #[inline(always)] pub fn transpose<M: Transpose>(m: &M) -> M { Transpose::transpose(m) } /* * Outer<M> */ /// Computes the outer product of two vectors. #[inline(always)] pub fn outer<V: Outer>(a: &V, b: &V) -> V::OuterProductType { Outer::outer(a, b) } /* * Cov<M> */ /// Computes the covariance of a set of observations. #[inline(always)] pub fn cov<M: Cov<Res>, Res>(observations: &M) -> Res { Cov::cov(observations) } /* * Mean<N> */ /// Computes the mean of a set of observations. #[inline(always)] pub fn mean<N, M: Mean<N>>(observations: &M) -> N { Mean::mean(observations) } /* * EigenQR<N, V> */ /// Computes the eigenvalues and eigenvectors of a square matrix usin the QR algorithm. #[inline(always)] pub fn eigen_qr<N, V, M>(m: &M, eps: &N, niter: usize) -> (M, V) where V: Mul<M, Output = V>, M: EigenQR<N, V> { EigenQR::eigen_qr(m, eps, niter) } // // // Structure // // /* * Eye */ /// Construct the identity matrix for a given dimension #[inline(always)] pub fn new_identity<M: Eye>(dim: usize) -> M { Eye::new_identity(dim) } /* * Repeat */ /// Create an object by repeating a value. /// /// Same as `Identity::new()`. #[inline(always)] pub fn repeat<N, T: Repeat<N>>(val: N) -> T { Repeat::repeat(val) } /* * Basis */ /// Computes the canonical basis for a given dimension. #[inline(always)] pub fn canonical_basis<V: Basis, F: FnMut(V) -> bool>(f: F) { Basis::canonical_basis(f) } /// Computes the basis of the orthonormal subspace of a given vector. #[inline(always)] pub fn orthonormal_subspace_basis<V: Basis, F: FnMut(V) -> bool>(v: &V, f: F) { Basis::orthonormal_subspace_basis(v, f) } /// Gets the (0-based) i-th element of the canonical basis of V. #[inline] pub fn canonical_basis_element<V: Basis>(i: usize) -> Option<V> { Basis::canonical_basis_element(i) } /* * Row<R> */ /* * Col<C> */ /* * Diag<V> */ /// Gets the diagonal of a square matrix. #[inline(always)] pub fn diag<M: Diag<V>, V>(m: &M) -> V { m.diag() } /* * Dim */ /// Gets the dimension an object lives in. /// /// Same as `Dim::dim::(None::<V>)`. #[inline(always)] pub fn dim<V: Dim>() -> usize { Dim::dim(None::<V>) } /// Gets the indexable range of an object. #[inline(always)] pub fn shape<V: Shape<I>, I>(v: &V) -> I { v.shape() } /* * Cast<T> */ /// Converts an object from one type to another. /// /// For primitive types, this is the same as the
val }
conditional_block
utils.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::collections::HashSet; use std::sync::Mutex; use futures::future::BoxFuture; use futures::TryStreamExt; use crate::errors::programming; use crate::Result; use crate::Set; use crate::Vertex; /// Pre-process a parent function that might have cycles. /// Return a new parent function that won't have cycles. /// /// This function is not fast. Only use it on small graphs. pub fn break_parent_func_cycle<F>(parent_func: F) -> impl Fn(Vertex) -> Result<Vec<Vertex>> where F: Fn(Vertex) -> Result<Vec<Vertex>>, { #[derive(Default)] struct State { /// Previously calculated parents. known: HashMap<Vertex, Vec<Vertex>>, } impl State { fn is_ancestor(&self, ancestor: &Vertex, descentant: &Vertex) -> bool { if ancestor == descentant { return true; } let mut to_visit = vec![descentant]; let mut visited = HashSet::new(); while let Some(v) = to_visit.pop() { if!visited.insert(v) { continue; } if let Some(parents) = self.known.get(&v) { for p in parents { if p == ancestor { return true; } to_visit.push(p); } } } false } } let state: Mutex<State> = Default::default(); move |v: Vertex| -> Result<Vec<Vertex>> { let mut state = state.lock().unwrap(); if let Some(parents) = state.known.get(&v) { return Ok(parents.clone()); } let parents = parent_func(v.clone())?; let mut result = Vec::with_capacity(parents.len()); for p in parents { if!state.is_ancestor(&v, &p) { // Not a cycle. result.push(p); } } state.known.insert(v, result.clone()); Ok(result) } } /// Given a `set` (sub-graph) and a filter function that selects "known" /// subset of its input, apply filter to `set`. /// /// The filter funtion must have following properties: /// - filter(xs) + filter(ys) = filter(xs + ys) /// - If its input contains both X and Y and X is an ancestor of Y in the /// sub-graph, and its output contains Y, then its output must also /// contain Y's ancestor X. /// In other words, if vertex X is considered known, then ancestors /// of X are also known. /// /// This function has a similar signature with `filter`, but it utilizes /// the above properties to test (much) less vertexes for a large input /// set. /// /// The idea of the algorithm comes from Mercurial's `setdiscovery.py`, /// introduced by [1]. `setdiscovery.py` is used to figure out what /// commits are needed to be pushed or pulled. /// /// [1]: https://www.mercurial-scm.org/repo/hg/rev/cb98fed52495 pub async fn filter_known<'a>( set: Set, filter_known_func: &( dyn (Fn(&[Vertex]) -> BoxFuture<'a, Result<Vec<Vertex>>>) + Send + Sync + 'a ), ) -> Result<Set> { // Figure out unassigned (missing) vertexes that do need to be inserted. // // remaining: subset not categorized. // known: subset categorized as "known" // unknown: subset categorized as "unknown" // // See [1] for the algorithm, basically: // - Take a subset (sample) of "remaining". // - Check the subset (sample). Divide it into (new_known, new_unknown). // - known |= ancestors(new_known) // - unknown |= descendants(new_unknown) // - remaining -= known | unknown // - Repeat until "remaining" becomes empty. let mut remaining = set; let subdag = match remaining.dag() { Some(dag) => dag, None => return programming("filter_known requires set to associate to a Dag"), }; let mut known = Set::empty(); for i in 1usize.. { let remaining_old_len = remaining.count().await?; if remaining_old_len == 0 { break; } // Sample: heads, roots, and the "middle point" from "remaining". let sample = if i <= 2 { // But for the first few queries, let's just check the roots. // This could reduce remote lookups, when we only need to // query the roots to rule out all `remaining` vertexes. subdag.roots(remaining.clone()).await? } else { subdag .roots(remaining.clone()) .await? .union(&subdag.heads(remaining.clone()).await?) .union(&remaining.skip((remaining_old_len as u64) / 2).take(1)) }; let sample: Vec<Vertex> = sample.iter().await?.try_collect().await?; let new_known = filter_known_func(&sample).await?; let new_unknown: Vec<Vertex> = { let filtered_set: HashSet<Vertex> = new_known.iter().cloned().collect(); sample .iter() .filter(|v|!filtered_set.contains(v)) .cloned() .collect() }; let new_known = Set::from_static_names(new_known); let new_unknown = Set::from_static_names(new_unknown); let new_known = subdag.ancestors(new_known).await?; let new_unknown = subdag.descendants(new_unknown).await?; remaining = remaining.difference(&new_known.union(&new_unknown)); let remaining_new_len = remaining.count().await?; let known_old_len = known.count().await?; known = known.union(&new_known); let known_new_len = known.count().await?; tracing::trace!( target: "dag::utils::filter_known", "#{} remaining {} => {}, known: {} => {}", i, remaining_old_len, remaining_new_len, known_old_len, known_new_len ); } Ok(known) } #[cfg(test)] mod tests { use super::*; #[test] fn test_break_parent_func_cycle() -> Result<()> { let parent_func = |n: Vertex| -> Result<Vec<Vertex>> { Ok(vec![n, v("1"), v("2")]) }; let parent_func_no_cycle = break_parent_func_cycle(parent_func); assert_eq!(parent_func_no_cycle(v("A"))?, vec![v("1"), v("2")]); assert_eq!(parent_func_no_cycle(v("1"))?, vec![v("2")]); assert_eq!(parent_func_no_cycle(v("2"))?, vec![]); Ok(()) } #[test] fn test_break_parent_func_cycle_linear() -> Result<()> { let parent_func = |n: Vertex| -> Result<Vec<Vertex>> { let list = "0123456789".chars().map(|c| v(c)).collect::<Vec<_>>(); let parents = match list.iter().position(|x| x == &n) { Some(i) if i > 0 => vec![list[i - 1].clone()], _ => vec![], }; Ok(parents) }; let parent_func_no_cycle = break_parent_func_cycle(parent_func); assert_eq!(parent_func_no_cycle(v("2"))?, vec![v("1")]); assert_eq!(parent_func_no_cycle(v("9"))?, vec![v("8")]); assert_eq!(parent_func_no_cycle(v("8"))?, vec![v("7")]); assert_eq!(parent_func_no_cycle(v("1"))?, vec![v("0")]); assert_eq!(parent_func_no_cycle(v("5"))?, vec![v("4")]); assert_eq!(parent_func_no_cycle(v("6"))?, vec![v("5")]); assert_eq!(parent_func_no_cycle(v("4"))?, vec![v("3")]); assert_eq!(parent_func_no_cycle(v("0"))?, vec![]); assert_eq!(parent_func_no_cycle(v("3"))?, vec![v("2")]); assert_eq!(parent_func_no_cycle(v("7"))?, vec![v("6")]); Ok(()) } /// Quickly create a Vertex. fn
(name: impl ToString) -> Vertex { Vertex::copy_from(name.to_string().as_bytes()) } }
v
identifier_name
utils.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::collections::HashSet; use std::sync::Mutex; use futures::future::BoxFuture; use futures::TryStreamExt; use crate::errors::programming; use crate::Result; use crate::Set; use crate::Vertex; /// Pre-process a parent function that might have cycles. /// Return a new parent function that won't have cycles. /// /// This function is not fast. Only use it on small graphs. pub fn break_parent_func_cycle<F>(parent_func: F) -> impl Fn(Vertex) -> Result<Vec<Vertex>> where F: Fn(Vertex) -> Result<Vec<Vertex>>, { #[derive(Default)] struct State { /// Previously calculated parents. known: HashMap<Vertex, Vec<Vertex>>, } impl State { fn is_ancestor(&self, ancestor: &Vertex, descentant: &Vertex) -> bool { if ancestor == descentant { return true; } let mut to_visit = vec![descentant]; let mut visited = HashSet::new(); while let Some(v) = to_visit.pop() { if!visited.insert(v) { continue; } if let Some(parents) = self.known.get(&v) { for p in parents { if p == ancestor
to_visit.push(p); } } } false } } let state: Mutex<State> = Default::default(); move |v: Vertex| -> Result<Vec<Vertex>> { let mut state = state.lock().unwrap(); if let Some(parents) = state.known.get(&v) { return Ok(parents.clone()); } let parents = parent_func(v.clone())?; let mut result = Vec::with_capacity(parents.len()); for p in parents { if!state.is_ancestor(&v, &p) { // Not a cycle. result.push(p); } } state.known.insert(v, result.clone()); Ok(result) } } /// Given a `set` (sub-graph) and a filter function that selects "known" /// subset of its input, apply filter to `set`. /// /// The filter funtion must have following properties: /// - filter(xs) + filter(ys) = filter(xs + ys) /// - If its input contains both X and Y and X is an ancestor of Y in the /// sub-graph, and its output contains Y, then its output must also /// contain Y's ancestor X. /// In other words, if vertex X is considered known, then ancestors /// of X are also known. /// /// This function has a similar signature with `filter`, but it utilizes /// the above properties to test (much) less vertexes for a large input /// set. /// /// The idea of the algorithm comes from Mercurial's `setdiscovery.py`, /// introduced by [1]. `setdiscovery.py` is used to figure out what /// commits are needed to be pushed or pulled. /// /// [1]: https://www.mercurial-scm.org/repo/hg/rev/cb98fed52495 pub async fn filter_known<'a>( set: Set, filter_known_func: &( dyn (Fn(&[Vertex]) -> BoxFuture<'a, Result<Vec<Vertex>>>) + Send + Sync + 'a ), ) -> Result<Set> { // Figure out unassigned (missing) vertexes that do need to be inserted. // // remaining: subset not categorized. // known: subset categorized as "known" // unknown: subset categorized as "unknown" // // See [1] for the algorithm, basically: // - Take a subset (sample) of "remaining". // - Check the subset (sample). Divide it into (new_known, new_unknown). // - known |= ancestors(new_known) // - unknown |= descendants(new_unknown) // - remaining -= known | unknown // - Repeat until "remaining" becomes empty. let mut remaining = set; let subdag = match remaining.dag() { Some(dag) => dag, None => return programming("filter_known requires set to associate to a Dag"), }; let mut known = Set::empty(); for i in 1usize.. { let remaining_old_len = remaining.count().await?; if remaining_old_len == 0 { break; } // Sample: heads, roots, and the "middle point" from "remaining". let sample = if i <= 2 { // But for the first few queries, let's just check the roots. // This could reduce remote lookups, when we only need to // query the roots to rule out all `remaining` vertexes. subdag.roots(remaining.clone()).await? } else { subdag .roots(remaining.clone()) .await? .union(&subdag.heads(remaining.clone()).await?) .union(&remaining.skip((remaining_old_len as u64) / 2).take(1)) }; let sample: Vec<Vertex> = sample.iter().await?.try_collect().await?; let new_known = filter_known_func(&sample).await?; let new_unknown: Vec<Vertex> = { let filtered_set: HashSet<Vertex> = new_known.iter().cloned().collect(); sample .iter() .filter(|v|!filtered_set.contains(v)) .cloned() .collect() }; let new_known = Set::from_static_names(new_known); let new_unknown = Set::from_static_names(new_unknown); let new_known = subdag.ancestors(new_known).await?; let new_unknown = subdag.descendants(new_unknown).await?; remaining = remaining.difference(&new_known.union(&new_unknown)); let remaining_new_len = remaining.count().await?; let known_old_len = known.count().await?; known = known.union(&new_known); let known_new_len = known.count().await?; tracing::trace!( target: "dag::utils::filter_known", "#{} remaining {} => {}, known: {} => {}", i, remaining_old_len, remaining_new_len, known_old_len, known_new_len ); } Ok(known) } #[cfg(test)] mod tests { use super::*; #[test] fn test_break_parent_func_cycle() -> Result<()> { let parent_func = |n: Vertex| -> Result<Vec<Vertex>> { Ok(vec![n, v("1"), v("2")]) }; let parent_func_no_cycle = break_parent_func_cycle(parent_func); assert_eq!(parent_func_no_cycle(v("A"))?, vec![v("1"), v("2")]); assert_eq!(parent_func_no_cycle(v("1"))?, vec![v("2")]); assert_eq!(parent_func_no_cycle(v("2"))?, vec![]); Ok(()) } #[test] fn test_break_parent_func_cycle_linear() -> Result<()> { let parent_func = |n: Vertex| -> Result<Vec<Vertex>> { let list = "0123456789".chars().map(|c| v(c)).collect::<Vec<_>>(); let parents = match list.iter().position(|x| x == &n) { Some(i) if i > 0 => vec![list[i - 1].clone()], _ => vec![], }; Ok(parents) }; let parent_func_no_cycle = break_parent_func_cycle(parent_func); assert_eq!(parent_func_no_cycle(v("2"))?, vec![v("1")]); assert_eq!(parent_func_no_cycle(v("9"))?, vec![v("8")]); assert_eq!(parent_func_no_cycle(v("8"))?, vec![v("7")]); assert_eq!(parent_func_no_cycle(v("1"))?, vec![v("0")]); assert_eq!(parent_func_no_cycle(v("5"))?, vec![v("4")]); assert_eq!(parent_func_no_cycle(v("6"))?, vec![v("5")]); assert_eq!(parent_func_no_cycle(v("4"))?, vec![v("3")]); assert_eq!(parent_func_no_cycle(v("0"))?, vec![]); assert_eq!(parent_func_no_cycle(v("3"))?, vec![v("2")]); assert_eq!(parent_func_no_cycle(v("7"))?, vec![v("6")]); Ok(()) } /// Quickly create a Vertex. fn v(name: impl ToString) -> Vertex { Vertex::copy_from(name.to_string().as_bytes()) } }
{ return true; }
conditional_block
utils.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::collections::HashSet; use std::sync::Mutex; use futures::future::BoxFuture; use futures::TryStreamExt; use crate::errors::programming; use crate::Result; use crate::Set; use crate::Vertex; /// Pre-process a parent function that might have cycles. /// Return a new parent function that won't have cycles. /// /// This function is not fast. Only use it on small graphs. pub fn break_parent_func_cycle<F>(parent_func: F) -> impl Fn(Vertex) -> Result<Vec<Vertex>> where F: Fn(Vertex) -> Result<Vec<Vertex>>, { #[derive(Default)] struct State { /// Previously calculated parents. known: HashMap<Vertex, Vec<Vertex>>, } impl State { fn is_ancestor(&self, ancestor: &Vertex, descentant: &Vertex) -> bool { if ancestor == descentant { return true; } let mut to_visit = vec![descentant]; let mut visited = HashSet::new(); while let Some(v) = to_visit.pop() { if!visited.insert(v) { continue; }
return true; } to_visit.push(p); } } } false } } let state: Mutex<State> = Default::default(); move |v: Vertex| -> Result<Vec<Vertex>> { let mut state = state.lock().unwrap(); if let Some(parents) = state.known.get(&v) { return Ok(parents.clone()); } let parents = parent_func(v.clone())?; let mut result = Vec::with_capacity(parents.len()); for p in parents { if!state.is_ancestor(&v, &p) { // Not a cycle. result.push(p); } } state.known.insert(v, result.clone()); Ok(result) } } /// Given a `set` (sub-graph) and a filter function that selects "known" /// subset of its input, apply filter to `set`. /// /// The filter funtion must have following properties: /// - filter(xs) + filter(ys) = filter(xs + ys) /// - If its input contains both X and Y and X is an ancestor of Y in the /// sub-graph, and its output contains Y, then its output must also /// contain Y's ancestor X. /// In other words, if vertex X is considered known, then ancestors /// of X are also known. /// /// This function has a similar signature with `filter`, but it utilizes /// the above properties to test (much) less vertexes for a large input /// set. /// /// The idea of the algorithm comes from Mercurial's `setdiscovery.py`, /// introduced by [1]. `setdiscovery.py` is used to figure out what /// commits are needed to be pushed or pulled. /// /// [1]: https://www.mercurial-scm.org/repo/hg/rev/cb98fed52495 pub async fn filter_known<'a>( set: Set, filter_known_func: &( dyn (Fn(&[Vertex]) -> BoxFuture<'a, Result<Vec<Vertex>>>) + Send + Sync + 'a ), ) -> Result<Set> { // Figure out unassigned (missing) vertexes that do need to be inserted. // // remaining: subset not categorized. // known: subset categorized as "known" // unknown: subset categorized as "unknown" // // See [1] for the algorithm, basically: // - Take a subset (sample) of "remaining". // - Check the subset (sample). Divide it into (new_known, new_unknown). // - known |= ancestors(new_known) // - unknown |= descendants(new_unknown) // - remaining -= known | unknown // - Repeat until "remaining" becomes empty. let mut remaining = set; let subdag = match remaining.dag() { Some(dag) => dag, None => return programming("filter_known requires set to associate to a Dag"), }; let mut known = Set::empty(); for i in 1usize.. { let remaining_old_len = remaining.count().await?; if remaining_old_len == 0 { break; } // Sample: heads, roots, and the "middle point" from "remaining". let sample = if i <= 2 { // But for the first few queries, let's just check the roots. // This could reduce remote lookups, when we only need to // query the roots to rule out all `remaining` vertexes. subdag.roots(remaining.clone()).await? } else { subdag .roots(remaining.clone()) .await? .union(&subdag.heads(remaining.clone()).await?) .union(&remaining.skip((remaining_old_len as u64) / 2).take(1)) }; let sample: Vec<Vertex> = sample.iter().await?.try_collect().await?; let new_known = filter_known_func(&sample).await?; let new_unknown: Vec<Vertex> = { let filtered_set: HashSet<Vertex> = new_known.iter().cloned().collect(); sample .iter() .filter(|v|!filtered_set.contains(v)) .cloned() .collect() }; let new_known = Set::from_static_names(new_known); let new_unknown = Set::from_static_names(new_unknown); let new_known = subdag.ancestors(new_known).await?; let new_unknown = subdag.descendants(new_unknown).await?; remaining = remaining.difference(&new_known.union(&new_unknown)); let remaining_new_len = remaining.count().await?; let known_old_len = known.count().await?; known = known.union(&new_known); let known_new_len = known.count().await?; tracing::trace!( target: "dag::utils::filter_known", "#{} remaining {} => {}, known: {} => {}", i, remaining_old_len, remaining_new_len, known_old_len, known_new_len ); } Ok(known) } #[cfg(test)] mod tests { use super::*; #[test] fn test_break_parent_func_cycle() -> Result<()> { let parent_func = |n: Vertex| -> Result<Vec<Vertex>> { Ok(vec![n, v("1"), v("2")]) }; let parent_func_no_cycle = break_parent_func_cycle(parent_func); assert_eq!(parent_func_no_cycle(v("A"))?, vec![v("1"), v("2")]); assert_eq!(parent_func_no_cycle(v("1"))?, vec![v("2")]); assert_eq!(parent_func_no_cycle(v("2"))?, vec![]); Ok(()) } #[test] fn test_break_parent_func_cycle_linear() -> Result<()> { let parent_func = |n: Vertex| -> Result<Vec<Vertex>> { let list = "0123456789".chars().map(|c| v(c)).collect::<Vec<_>>(); let parents = match list.iter().position(|x| x == &n) { Some(i) if i > 0 => vec![list[i - 1].clone()], _ => vec![], }; Ok(parents) }; let parent_func_no_cycle = break_parent_func_cycle(parent_func); assert_eq!(parent_func_no_cycle(v("2"))?, vec![v("1")]); assert_eq!(parent_func_no_cycle(v("9"))?, vec![v("8")]); assert_eq!(parent_func_no_cycle(v("8"))?, vec![v("7")]); assert_eq!(parent_func_no_cycle(v("1"))?, vec![v("0")]); assert_eq!(parent_func_no_cycle(v("5"))?, vec![v("4")]); assert_eq!(parent_func_no_cycle(v("6"))?, vec![v("5")]); assert_eq!(parent_func_no_cycle(v("4"))?, vec![v("3")]); assert_eq!(parent_func_no_cycle(v("0"))?, vec![]); assert_eq!(parent_func_no_cycle(v("3"))?, vec![v("2")]); assert_eq!(parent_func_no_cycle(v("7"))?, vec![v("6")]); Ok(()) } /// Quickly create a Vertex. fn v(name: impl ToString) -> Vertex { Vertex::copy_from(name.to_string().as_bytes()) } }
if let Some(parents) = self.known.get(&v) { for p in parents { if p == ancestor {
random_line_split
utils.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::collections::HashSet; use std::sync::Mutex; use futures::future::BoxFuture; use futures::TryStreamExt; use crate::errors::programming; use crate::Result; use crate::Set; use crate::Vertex; /// Pre-process a parent function that might have cycles. /// Return a new parent function that won't have cycles. /// /// This function is not fast. Only use it on small graphs. pub fn break_parent_func_cycle<F>(parent_func: F) -> impl Fn(Vertex) -> Result<Vec<Vertex>> where F: Fn(Vertex) -> Result<Vec<Vertex>>, { #[derive(Default)] struct State { /// Previously calculated parents. known: HashMap<Vertex, Vec<Vertex>>, } impl State { fn is_ancestor(&self, ancestor: &Vertex, descentant: &Vertex) -> bool { if ancestor == descentant { return true; } let mut to_visit = vec![descentant]; let mut visited = HashSet::new(); while let Some(v) = to_visit.pop() { if!visited.insert(v) { continue; } if let Some(parents) = self.known.get(&v) { for p in parents { if p == ancestor { return true; } to_visit.push(p); } } } false } } let state: Mutex<State> = Default::default(); move |v: Vertex| -> Result<Vec<Vertex>> { let mut state = state.lock().unwrap(); if let Some(parents) = state.known.get(&v) { return Ok(parents.clone()); } let parents = parent_func(v.clone())?; let mut result = Vec::with_capacity(parents.len()); for p in parents { if!state.is_ancestor(&v, &p) { // Not a cycle. result.push(p); } } state.known.insert(v, result.clone()); Ok(result) } } /// Given a `set` (sub-graph) and a filter function that selects "known" /// subset of its input, apply filter to `set`. /// /// The filter funtion must have following properties: /// - filter(xs) + filter(ys) = filter(xs + ys) /// - If its input contains both X and Y and X is an ancestor of Y in the /// sub-graph, and its output contains Y, then its output must also /// contain Y's ancestor X. /// In other words, if vertex X is considered known, then ancestors /// of X are also known. /// /// This function has a similar signature with `filter`, but it utilizes /// the above properties to test (much) less vertexes for a large input /// set. /// /// The idea of the algorithm comes from Mercurial's `setdiscovery.py`, /// introduced by [1]. `setdiscovery.py` is used to figure out what /// commits are needed to be pushed or pulled. /// /// [1]: https://www.mercurial-scm.org/repo/hg/rev/cb98fed52495 pub async fn filter_known<'a>( set: Set, filter_known_func: &( dyn (Fn(&[Vertex]) -> BoxFuture<'a, Result<Vec<Vertex>>>) + Send + Sync + 'a ), ) -> Result<Set> { // Figure out unassigned (missing) vertexes that do need to be inserted. // // remaining: subset not categorized. // known: subset categorized as "known" // unknown: subset categorized as "unknown" // // See [1] for the algorithm, basically: // - Take a subset (sample) of "remaining". // - Check the subset (sample). Divide it into (new_known, new_unknown). // - known |= ancestors(new_known) // - unknown |= descendants(new_unknown) // - remaining -= known | unknown // - Repeat until "remaining" becomes empty. let mut remaining = set; let subdag = match remaining.dag() { Some(dag) => dag, None => return programming("filter_known requires set to associate to a Dag"), }; let mut known = Set::empty(); for i in 1usize.. { let remaining_old_len = remaining.count().await?; if remaining_old_len == 0 { break; } // Sample: heads, roots, and the "middle point" from "remaining". let sample = if i <= 2 { // But for the first few queries, let's just check the roots. // This could reduce remote lookups, when we only need to // query the roots to rule out all `remaining` vertexes. subdag.roots(remaining.clone()).await? } else { subdag .roots(remaining.clone()) .await? .union(&subdag.heads(remaining.clone()).await?) .union(&remaining.skip((remaining_old_len as u64) / 2).take(1)) }; let sample: Vec<Vertex> = sample.iter().await?.try_collect().await?; let new_known = filter_known_func(&sample).await?; let new_unknown: Vec<Vertex> = { let filtered_set: HashSet<Vertex> = new_known.iter().cloned().collect(); sample .iter() .filter(|v|!filtered_set.contains(v)) .cloned() .collect() }; let new_known = Set::from_static_names(new_known); let new_unknown = Set::from_static_names(new_unknown); let new_known = subdag.ancestors(new_known).await?; let new_unknown = subdag.descendants(new_unknown).await?; remaining = remaining.difference(&new_known.union(&new_unknown)); let remaining_new_len = remaining.count().await?; let known_old_len = known.count().await?; known = known.union(&new_known); let known_new_len = known.count().await?; tracing::trace!( target: "dag::utils::filter_known", "#{} remaining {} => {}, known: {} => {}", i, remaining_old_len, remaining_new_len, known_old_len, known_new_len ); } Ok(known) } #[cfg(test)] mod tests { use super::*; #[test] fn test_break_parent_func_cycle() -> Result<()>
#[test] fn test_break_parent_func_cycle_linear() -> Result<()> { let parent_func = |n: Vertex| -> Result<Vec<Vertex>> { let list = "0123456789".chars().map(|c| v(c)).collect::<Vec<_>>(); let parents = match list.iter().position(|x| x == &n) { Some(i) if i > 0 => vec![list[i - 1].clone()], _ => vec![], }; Ok(parents) }; let parent_func_no_cycle = break_parent_func_cycle(parent_func); assert_eq!(parent_func_no_cycle(v("2"))?, vec![v("1")]); assert_eq!(parent_func_no_cycle(v("9"))?, vec![v("8")]); assert_eq!(parent_func_no_cycle(v("8"))?, vec![v("7")]); assert_eq!(parent_func_no_cycle(v("1"))?, vec![v("0")]); assert_eq!(parent_func_no_cycle(v("5"))?, vec![v("4")]); assert_eq!(parent_func_no_cycle(v("6"))?, vec![v("5")]); assert_eq!(parent_func_no_cycle(v("4"))?, vec![v("3")]); assert_eq!(parent_func_no_cycle(v("0"))?, vec![]); assert_eq!(parent_func_no_cycle(v("3"))?, vec![v("2")]); assert_eq!(parent_func_no_cycle(v("7"))?, vec![v("6")]); Ok(()) } /// Quickly create a Vertex. fn v(name: impl ToString) -> Vertex { Vertex::copy_from(name.to_string().as_bytes()) } }
{ let parent_func = |n: Vertex| -> Result<Vec<Vertex>> { Ok(vec![n, v("1"), v("2")]) }; let parent_func_no_cycle = break_parent_func_cycle(parent_func); assert_eq!(parent_func_no_cycle(v("A"))?, vec![v("1"), v("2")]); assert_eq!(parent_func_no_cycle(v("1"))?, vec![v("2")]); assert_eq!(parent_func_no_cycle(v("2"))?, vec![]); Ok(()) }
identifier_body
object_header.rs
//! A generic header for every Git object. use object_type::ObjectType; use object_type; use reader::Reader; use std::str::FromStr; use error::GitError; use error::GitError::CorruptObject; #[deriving(PartialEq, Show, Clone)] pub struct ObjectHeader { pub typ: ObjectType, pub length: uint } impl ObjectHeader { pub fn encode(&self) -> Vec<u8> { let mut buff = Vec::new(); buff.push_all(format!("{} ", self.typ.to_text()).into_bytes().as_slice()); buff.push_all(format!("{}", self.length).into_bytes().as_slice()); buff.push(0x00); buff } } pub fn decode(bytes: &[u8]) -> Result<ObjectHeader, GitError>
{ let mut reader = Reader::from_data(bytes); let typ = try!(object_type::from_text(reader.take_string_while(|c| *c != 32).unwrap_or(""))); reader.skip(1); let length: uint = try!( FromStr::from_str(reader.take_string_while(|c| *c != 0).unwrap_or("")) .ok_or(CorruptObject("invalid header length".into_cow())) ); Ok(ObjectHeader { typ: typ, length: length }) }
identifier_body
object_header.rs
//! A generic header for every Git object. use object_type::ObjectType; use object_type; use reader::Reader; use std::str::FromStr; use error::GitError; use error::GitError::CorruptObject; #[deriving(PartialEq, Show, Clone)] pub struct ObjectHeader { pub typ: ObjectType, pub length: uint } impl ObjectHeader { pub fn encode(&self) -> Vec<u8> { let mut buff = Vec::new(); buff.push_all(format!("{} ", self.typ.to_text()).into_bytes().as_slice()); buff.push_all(format!("{}", self.length).into_bytes().as_slice()); buff.push(0x00); buff } } pub fn decode(bytes: &[u8]) -> Result<ObjectHeader, GitError> { let mut reader = Reader::from_data(bytes); let typ = try!(object_type::from_text(reader.take_string_while(|c| *c!= 32).unwrap_or("")));
reader.skip(1); let length: uint = try!( FromStr::from_str(reader.take_string_while(|c| *c!= 0).unwrap_or("")) .ok_or(CorruptObject("invalid header length".into_cow())) ); Ok(ObjectHeader { typ: typ, length: length }) }
random_line_split
object_header.rs
//! A generic header for every Git object. use object_type::ObjectType; use object_type; use reader::Reader; use std::str::FromStr; use error::GitError; use error::GitError::CorruptObject; #[deriving(PartialEq, Show, Clone)] pub struct ObjectHeader { pub typ: ObjectType, pub length: uint } impl ObjectHeader { pub fn
(&self) -> Vec<u8> { let mut buff = Vec::new(); buff.push_all(format!("{} ", self.typ.to_text()).into_bytes().as_slice()); buff.push_all(format!("{}", self.length).into_bytes().as_slice()); buff.push(0x00); buff } } pub fn decode(bytes: &[u8]) -> Result<ObjectHeader, GitError> { let mut reader = Reader::from_data(bytes); let typ = try!(object_type::from_text(reader.take_string_while(|c| *c!= 32).unwrap_or(""))); reader.skip(1); let length: uint = try!( FromStr::from_str(reader.take_string_while(|c| *c!= 0).unwrap_or("")) .ok_or(CorruptObject("invalid header length".into_cow())) ); Ok(ObjectHeader { typ: typ, length: length }) }
encode
identifier_name
error.rs
/* Error type based on the error type from es-rs: * * Copyright 2015-2018 Ben Ashford * * 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::http::transport::BuildError; use serde_json; use std::error; use std::fmt; use std::io; /// An error within the client. /// /// Errors that can occur include IO and parsing errors, as well as specific /// errors from Elasticsearch and internal errors from this library #[derive(Debug)] pub enum Error { /// An error building the client Build(BuildError), /// A general error from this library Lib(String), /// HTTP library error Http(reqwest::Error), /// IO error Io(io::Error), /// JSON error Json(serde_json::error::Error), } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err) } } impl From<reqwest::Error> for Error { fn from(err: reqwest::Error) -> Error { Error::Http(err) } } impl From<serde_json::error::Error> for Error { fn from(err: serde_json::error::Error) -> Error { Error::Json(err) } } impl From<url::ParseError> for Error { fn from(err: url::ParseError) -> Error
} impl From<BuildError> for Error { fn from(err: BuildError) -> Error { Error::Build(err) } } impl error::Error for Error { #[allow(warnings)] fn description(&self) -> &str { match *self { Error::Build(ref err) => err.description(), Error::Lib(ref err) => err, Error::Http(ref err) => err.description(), Error::Io(ref err) => err.description(), Error::Json(ref err) => err.description(), } } fn cause(&self) -> Option<&dyn error::Error> { match *self { Error::Build(ref err) => Some(err as &dyn error::Error), Error::Lib(_) => None, Error::Http(ref err) => Some(err as &dyn error::Error), Error::Io(ref err) => Some(err as &dyn error::Error), Error::Json(ref err) => Some(err as &dyn error::Error), } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::Build(ref err) => fmt::Display::fmt(err, f), Error::Lib(ref s) => fmt::Display::fmt(s, f), Error::Http(ref err) => fmt::Display::fmt(err, f), Error::Io(ref err) => fmt::Display::fmt(err, f), Error::Json(ref err) => fmt::Display::fmt(err, f), } } }
{ Error::Lib(err.to_string()) }
identifier_body
error.rs
/* Error type based on the error type from es-rs: * * Copyright 2015-2018 Ben Ashford * * 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::http::transport::BuildError; use serde_json; use std::error; use std::fmt; use std::io; /// An error within the client. /// /// Errors that can occur include IO and parsing errors, as well as specific /// errors from Elasticsearch and internal errors from this library #[derive(Debug)] pub enum Error { /// An error building the client Build(BuildError), /// A general error from this library Lib(String), /// HTTP library error Http(reqwest::Error), /// IO error Io(io::Error), /// JSON error Json(serde_json::error::Error), } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err) } } impl From<reqwest::Error> for Error { fn
(err: reqwest::Error) -> Error { Error::Http(err) } } impl From<serde_json::error::Error> for Error { fn from(err: serde_json::error::Error) -> Error { Error::Json(err) } } impl From<url::ParseError> for Error { fn from(err: url::ParseError) -> Error { Error::Lib(err.to_string()) } } impl From<BuildError> for Error { fn from(err: BuildError) -> Error { Error::Build(err) } } impl error::Error for Error { #[allow(warnings)] fn description(&self) -> &str { match *self { Error::Build(ref err) => err.description(), Error::Lib(ref err) => err, Error::Http(ref err) => err.description(), Error::Io(ref err) => err.description(), Error::Json(ref err) => err.description(), } } fn cause(&self) -> Option<&dyn error::Error> { match *self { Error::Build(ref err) => Some(err as &dyn error::Error), Error::Lib(_) => None, Error::Http(ref err) => Some(err as &dyn error::Error), Error::Io(ref err) => Some(err as &dyn error::Error), Error::Json(ref err) => Some(err as &dyn error::Error), } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::Build(ref err) => fmt::Display::fmt(err, f), Error::Lib(ref s) => fmt::Display::fmt(s, f), Error::Http(ref err) => fmt::Display::fmt(err, f), Error::Io(ref err) => fmt::Display::fmt(err, f), Error::Json(ref err) => fmt::Display::fmt(err, f), } } }
from
identifier_name
error.rs
/* Error type based on the error type from es-rs: * * Copyright 2015-2018 Ben Ashford * * 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::http::transport::BuildError; use serde_json; use std::error; use std::fmt; use std::io; /// An error within the client. /// /// Errors that can occur include IO and parsing errors, as well as specific /// errors from Elasticsearch and internal errors from this library #[derive(Debug)] pub enum Error { /// An error building the client Build(BuildError),
Lib(String), /// HTTP library error Http(reqwest::Error), /// IO error Io(io::Error), /// JSON error Json(serde_json::error::Error), } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err) } } impl From<reqwest::Error> for Error { fn from(err: reqwest::Error) -> Error { Error::Http(err) } } impl From<serde_json::error::Error> for Error { fn from(err: serde_json::error::Error) -> Error { Error::Json(err) } } impl From<url::ParseError> for Error { fn from(err: url::ParseError) -> Error { Error::Lib(err.to_string()) } } impl From<BuildError> for Error { fn from(err: BuildError) -> Error { Error::Build(err) } } impl error::Error for Error { #[allow(warnings)] fn description(&self) -> &str { match *self { Error::Build(ref err) => err.description(), Error::Lib(ref err) => err, Error::Http(ref err) => err.description(), Error::Io(ref err) => err.description(), Error::Json(ref err) => err.description(), } } fn cause(&self) -> Option<&dyn error::Error> { match *self { Error::Build(ref err) => Some(err as &dyn error::Error), Error::Lib(_) => None, Error::Http(ref err) => Some(err as &dyn error::Error), Error::Io(ref err) => Some(err as &dyn error::Error), Error::Json(ref err) => Some(err as &dyn error::Error), } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::Build(ref err) => fmt::Display::fmt(err, f), Error::Lib(ref s) => fmt::Display::fmt(s, f), Error::Http(ref err) => fmt::Display::fmt(err, f), Error::Io(ref err) => fmt::Display::fmt(err, f), Error::Json(ref err) => fmt::Display::fmt(err, f), } } }
/// A general error from this library
random_line_split
defs.rs
//! Various definitions of types, constants, traint,... related to network use core::fmt::{ Binary, Octal, LowerHex, UpperHex, Debug, Display, Formatter, Error }; use core::str::FromStr; use vec::Vec; use num::PrimInt; use net::Packet; /// Type of the ether_type pub type EtherType = u16; /// Type that represent a protocol id pub type ProtocolIdType = u8; /// Type that represent a port pub type PortType = u16; #[derive(Clone)] /// Ethernet layer part of the rule pub struct EthernetRule { pub ether_type: EtherType, pub hw_in: Option<HwAddr>, } #[derive(Clone)] /// Network layer part of the rule pub struct NetworkRule { pub protocol_id: ProtocolIdType, pub ip_in: Option<IpAddr>, } #[derive(Clone)] /// Transport layer part of the rule pub struct TransportRule { pub port: PortType, } #[derive(Clone)] /// Represent a rule that a packet must match to be enqueued in a connexion pub struct Rule { pub eth_rule: Option<EthernetRule>, pub net_rule: Option<NetworkRule>, pub tspt_rule: Option<TransportRule>, } /// Trait implemented by hardware interfaces pub trait Device { /// Periodically called by the network thread to let the interface /// refresh its rx/tx buffers,... fn refresh(&mut self); /// Transmit a packet via the interface fn tx_packet(&mut self, pkt: Packet); } /// Network integer representation /// /// This type stores an integer using network's endianness and let the user /// manipulates it using host's endianness. #[repr(C, packed)] #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] pub struct Int<T: PrimInt + Clone>(T); impl<T> Int<T> where T: PrimInt + Clone { /// Construct from an integer represented using network's endianness pub fn from_net(i: T) -> Self { Int(i) } /// Construct from an integer represented using host's endianness pub fn from_host(i: T) -> Self { Int(i.to_be()) } /// Returns the contained integer using host's endianness pub fn as_host(&self) -> T { T::from_be(self.0.clone()) } /// Returns the contained integer using network's endianness pub fn as_net(&self) -> T { self.0.clone() } } impl<T> Binary for Int<T> where T: PrimInt + Clone + Binary { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } impl<T> Octal for Int<T> where T: PrimInt + Clone + Octal { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } impl<T> LowerHex for Int<T> where T: PrimInt + Clone + LowerHex { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } impl<T> UpperHex for Int<T> where T: PrimInt + Clone + UpperHex { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } impl<T> Debug for Int<T> where T: PrimInt + Clone + Debug { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } impl<T> Display for Int<T> where T: PrimInt + Clone + Display { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } const COUNT_HWADDR_BYTES: usize = 6; #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] /// An IP address, either V4 or V6 pub enum IpAddr { /// An IPv4 address V4(Ipv4Addr), /// An IPv6 address V6(Ipv6Addr) } #[repr(C, packed)] #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] /// An IPv4 address pub struct Ipv4Addr { a: u8, b: u8, c: u8, d: u8, } impl Ipv4Addr { /// Creates a new IPv4 address /// /// The result will represent the IP address `a`.`b`.`c`.`d` pub fn new(a: u8, b: u8, c: u8, d: u8) -> Self { Ipv4Addr { a: a, b: b, c: c, d: d, } } } impl Display for Ipv4Addr { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { f.write_fmt(format_args!("{}.{}.{}.{}", self.a, self.b, self.c, self.d)) } } #[repr(C, packed)] #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] /// An IPv6 address pub struct Ipv6Addr { a: Int<u16>, b: Int<u16>, c: Int<u16>, d: Int<u16>, e: Int<u16>, f: Int<u16>, g: Int<u16>, h: Int<u16>, } impl Ipv6Addr { /// Creates a new IPv6 address /// /// The result will represent the IP address `a`:`b`:`c`:`d`:`e`:`f`:`g`:`h` pub fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr { Ipv6Addr { a: Int::from_host(a), b: Int::from_host(b), c: Int::from_host(c), d: Int::from_host(d), e: Int::from_host(e), f: Int::from_host(f), g: Int::from_host(g), h: Int::from_host(h), } } } impl Display for Ipv6Addr { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { f.write_fmt(format_args!("{}:{}:{}:{}:{}:{}:{}:{}", self.a, self.b, self.c, self.d, self.e, self.f, self.g, self.h)) } } #[repr(C, packed)] #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] /// A MAC address pub struct HwAddr { bytes: [u8; COUNT_HWADDR_BYTES], } impl HwAddr { /// Create an empty hardware address (i.e., 00:00:00:00:00:00) pub fn empty() -> Self { HwAddr { bytes: [0; COUNT_HWADDR_BYTES], } } /// Create a broadcast hardware address (i.e., FF:FF:FF:FF:FF:FF) pub fn broadcast() -> Self { HwAddr { bytes: [0xFF; COUNT_HWADDR_BYTES], } } /// Is the current hardware address a broadcast /// address (i.e., FF:FF:FF:FF:FF:FF) pub fn is_broadcast(&self) -> bool { *self == Self::broadcast() } /// Create an hardware address from bytes. /// /// This method is unsafe because the slice *MUST* contain at least 6 /// elements. pub unsafe fn from_bytes(bytes: &[u8]) -> Self { let mut ret = Self::empty(); ret.bytes[0] = bytes[0]; ret.bytes[1] = bytes[1]; ret.bytes[2] = bytes[2]; ret.bytes[3] = bytes[3]; ret.bytes[4] = bytes[4]; ret.bytes[5] = bytes[5]; ret } #[inline] /// Returns the internal representation of an hardware address pub fn as_bytes(&self) -> &[u8] { &self.bytes[..] } } impl FromStr for HwAddr { type Err = (); /// Convert a string with format XX:XX:XX:XX:XX:XX to an hardware address fn from_str(s: &str) -> Result<Self, Self::Err> { let split: Vec<&str> = s.split(':').collect(); if split.len()!= COUNT_HWADDR_BYTES
let mut ret = Self::empty(); for (i, b) in split.iter().enumerate() { let bytes = b.as_bytes(); if bytes.len()!= 2 { return Err(()) } let d1 = try!(b.char_at(0).to_digit(16).ok_or(())) * 16; let d2 = try!(b.char_at(1).to_digit(16).ok_or(())); ret.bytes[i] = d1 as u8 + d2 as u8; } Ok(ret) } } impl Display for HwAddr { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { f.write_fmt(format_args!("{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", self.bytes[0], self.bytes[1], self.bytes[2], self.bytes[3], self.bytes[4], self.bytes[5])) } }
{ return Err(()) }
conditional_block
defs.rs
//! Various definitions of types, constants, traint,... related to network use core::fmt::{ Binary, Octal, LowerHex, UpperHex, Debug, Display, Formatter, Error }; use core::str::FromStr; use vec::Vec; use num::PrimInt; use net::Packet; /// Type of the ether_type pub type EtherType = u16; /// Type that represent a protocol id pub type ProtocolIdType = u8; /// Type that represent a port pub type PortType = u16; #[derive(Clone)] /// Ethernet layer part of the rule pub struct EthernetRule { pub ether_type: EtherType, pub hw_in: Option<HwAddr>, } #[derive(Clone)] /// Network layer part of the rule pub struct NetworkRule { pub protocol_id: ProtocolIdType, pub ip_in: Option<IpAddr>, } #[derive(Clone)] /// Transport layer part of the rule pub struct TransportRule { pub port: PortType, } #[derive(Clone)] /// Represent a rule that a packet must match to be enqueued in a connexion pub struct Rule { pub eth_rule: Option<EthernetRule>, pub net_rule: Option<NetworkRule>, pub tspt_rule: Option<TransportRule>, } /// Trait implemented by hardware interfaces pub trait Device { /// Periodically called by the network thread to let the interface /// refresh its rx/tx buffers,... fn refresh(&mut self); /// Transmit a packet via the interface fn tx_packet(&mut self, pkt: Packet); } /// Network integer representation /// /// This type stores an integer using network's endianness and let the user /// manipulates it using host's endianness. #[repr(C, packed)] #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] pub struct Int<T: PrimInt + Clone>(T); impl<T> Int<T> where T: PrimInt + Clone { /// Construct from an integer represented using network's endianness pub fn from_net(i: T) -> Self { Int(i) }
/// Construct from an integer represented using host's endianness pub fn from_host(i: T) -> Self { Int(i.to_be()) } /// Returns the contained integer using host's endianness pub fn as_host(&self) -> T { T::from_be(self.0.clone()) } /// Returns the contained integer using network's endianness pub fn as_net(&self) -> T { self.0.clone() } } impl<T> Binary for Int<T> where T: PrimInt + Clone + Binary { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } impl<T> Octal for Int<T> where T: PrimInt + Clone + Octal { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } impl<T> LowerHex for Int<T> where T: PrimInt + Clone + LowerHex { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } impl<T> UpperHex for Int<T> where T: PrimInt + Clone + UpperHex { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } impl<T> Debug for Int<T> where T: PrimInt + Clone + Debug { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } impl<T> Display for Int<T> where T: PrimInt + Clone + Display { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } const COUNT_HWADDR_BYTES: usize = 6; #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] /// An IP address, either V4 or V6 pub enum IpAddr { /// An IPv4 address V4(Ipv4Addr), /// An IPv6 address V6(Ipv6Addr) } #[repr(C, packed)] #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] /// An IPv4 address pub struct Ipv4Addr { a: u8, b: u8, c: u8, d: u8, } impl Ipv4Addr { /// Creates a new IPv4 address /// /// The result will represent the IP address `a`.`b`.`c`.`d` pub fn new(a: u8, b: u8, c: u8, d: u8) -> Self { Ipv4Addr { a: a, b: b, c: c, d: d, } } } impl Display for Ipv4Addr { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { f.write_fmt(format_args!("{}.{}.{}.{}", self.a, self.b, self.c, self.d)) } } #[repr(C, packed)] #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] /// An IPv6 address pub struct Ipv6Addr { a: Int<u16>, b: Int<u16>, c: Int<u16>, d: Int<u16>, e: Int<u16>, f: Int<u16>, g: Int<u16>, h: Int<u16>, } impl Ipv6Addr { /// Creates a new IPv6 address /// /// The result will represent the IP address `a`:`b`:`c`:`d`:`e`:`f`:`g`:`h` pub fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr { Ipv6Addr { a: Int::from_host(a), b: Int::from_host(b), c: Int::from_host(c), d: Int::from_host(d), e: Int::from_host(e), f: Int::from_host(f), g: Int::from_host(g), h: Int::from_host(h), } } } impl Display for Ipv6Addr { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { f.write_fmt(format_args!("{}:{}:{}:{}:{}:{}:{}:{}", self.a, self.b, self.c, self.d, self.e, self.f, self.g, self.h)) } } #[repr(C, packed)] #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] /// A MAC address pub struct HwAddr { bytes: [u8; COUNT_HWADDR_BYTES], } impl HwAddr { /// Create an empty hardware address (i.e., 00:00:00:00:00:00) pub fn empty() -> Self { HwAddr { bytes: [0; COUNT_HWADDR_BYTES], } } /// Create a broadcast hardware address (i.e., FF:FF:FF:FF:FF:FF) pub fn broadcast() -> Self { HwAddr { bytes: [0xFF; COUNT_HWADDR_BYTES], } } /// Is the current hardware address a broadcast /// address (i.e., FF:FF:FF:FF:FF:FF) pub fn is_broadcast(&self) -> bool { *self == Self::broadcast() } /// Create an hardware address from bytes. /// /// This method is unsafe because the slice *MUST* contain at least 6 /// elements. pub unsafe fn from_bytes(bytes: &[u8]) -> Self { let mut ret = Self::empty(); ret.bytes[0] = bytes[0]; ret.bytes[1] = bytes[1]; ret.bytes[2] = bytes[2]; ret.bytes[3] = bytes[3]; ret.bytes[4] = bytes[4]; ret.bytes[5] = bytes[5]; ret } #[inline] /// Returns the internal representation of an hardware address pub fn as_bytes(&self) -> &[u8] { &self.bytes[..] } } impl FromStr for HwAddr { type Err = (); /// Convert a string with format XX:XX:XX:XX:XX:XX to an hardware address fn from_str(s: &str) -> Result<Self, Self::Err> { let split: Vec<&str> = s.split(':').collect(); if split.len()!= COUNT_HWADDR_BYTES { return Err(()) } let mut ret = Self::empty(); for (i, b) in split.iter().enumerate() { let bytes = b.as_bytes(); if bytes.len()!= 2 { return Err(()) } let d1 = try!(b.char_at(0).to_digit(16).ok_or(())) * 16; let d2 = try!(b.char_at(1).to_digit(16).ok_or(())); ret.bytes[i] = d1 as u8 + d2 as u8; } Ok(ret) } } impl Display for HwAddr { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { f.write_fmt(format_args!("{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", self.bytes[0], self.bytes[1], self.bytes[2], self.bytes[3], self.bytes[4], self.bytes[5])) } }
random_line_split
defs.rs
//! Various definitions of types, constants, traint,... related to network use core::fmt::{ Binary, Octal, LowerHex, UpperHex, Debug, Display, Formatter, Error }; use core::str::FromStr; use vec::Vec; use num::PrimInt; use net::Packet; /// Type of the ether_type pub type EtherType = u16; /// Type that represent a protocol id pub type ProtocolIdType = u8; /// Type that represent a port pub type PortType = u16; #[derive(Clone)] /// Ethernet layer part of the rule pub struct EthernetRule { pub ether_type: EtherType, pub hw_in: Option<HwAddr>, } #[derive(Clone)] /// Network layer part of the rule pub struct NetworkRule { pub protocol_id: ProtocolIdType, pub ip_in: Option<IpAddr>, } #[derive(Clone)] /// Transport layer part of the rule pub struct TransportRule { pub port: PortType, } #[derive(Clone)] /// Represent a rule that a packet must match to be enqueued in a connexion pub struct Rule { pub eth_rule: Option<EthernetRule>, pub net_rule: Option<NetworkRule>, pub tspt_rule: Option<TransportRule>, } /// Trait implemented by hardware interfaces pub trait Device { /// Periodically called by the network thread to let the interface /// refresh its rx/tx buffers,... fn refresh(&mut self); /// Transmit a packet via the interface fn tx_packet(&mut self, pkt: Packet); } /// Network integer representation /// /// This type stores an integer using network's endianness and let the user /// manipulates it using host's endianness. #[repr(C, packed)] #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] pub struct Int<T: PrimInt + Clone>(T); impl<T> Int<T> where T: PrimInt + Clone { /// Construct from an integer represented using network's endianness pub fn from_net(i: T) -> Self { Int(i) } /// Construct from an integer represented using host's endianness pub fn from_host(i: T) -> Self { Int(i.to_be()) } /// Returns the contained integer using host's endianness pub fn as_host(&self) -> T { T::from_be(self.0.clone()) } /// Returns the contained integer using network's endianness pub fn as_net(&self) -> T { self.0.clone() } } impl<T> Binary for Int<T> where T: PrimInt + Clone + Binary { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } impl<T> Octal for Int<T> where T: PrimInt + Clone + Octal { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } impl<T> LowerHex for Int<T> where T: PrimInt + Clone + LowerHex { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } impl<T> UpperHex for Int<T> where T: PrimInt + Clone + UpperHex { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } impl<T> Debug for Int<T> where T: PrimInt + Clone + Debug { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } impl<T> Display for Int<T> where T: PrimInt + Clone + Display { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { self.as_host().fmt(f) } } const COUNT_HWADDR_BYTES: usize = 6; #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] /// An IP address, either V4 or V6 pub enum IpAddr { /// An IPv4 address V4(Ipv4Addr), /// An IPv6 address V6(Ipv6Addr) } #[repr(C, packed)] #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] /// An IPv4 address pub struct Ipv4Addr { a: u8, b: u8, c: u8, d: u8, } impl Ipv4Addr { /// Creates a new IPv4 address /// /// The result will represent the IP address `a`.`b`.`c`.`d` pub fn new(a: u8, b: u8, c: u8, d: u8) -> Self { Ipv4Addr { a: a, b: b, c: c, d: d, } } } impl Display for Ipv4Addr { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { f.write_fmt(format_args!("{}.{}.{}.{}", self.a, self.b, self.c, self.d)) } } #[repr(C, packed)] #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] /// An IPv6 address pub struct Ipv6Addr { a: Int<u16>, b: Int<u16>, c: Int<u16>, d: Int<u16>, e: Int<u16>, f: Int<u16>, g: Int<u16>, h: Int<u16>, } impl Ipv6Addr { /// Creates a new IPv6 address /// /// The result will represent the IP address `a`:`b`:`c`:`d`:`e`:`f`:`g`:`h` pub fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr { Ipv6Addr { a: Int::from_host(a), b: Int::from_host(b), c: Int::from_host(c), d: Int::from_host(d), e: Int::from_host(e), f: Int::from_host(f), g: Int::from_host(g), h: Int::from_host(h), } } } impl Display for Ipv6Addr { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { f.write_fmt(format_args!("{}:{}:{}:{}:{}:{}:{}:{}", self.a, self.b, self.c, self.d, self.e, self.f, self.g, self.h)) } } #[repr(C, packed)] #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] /// A MAC address pub struct HwAddr { bytes: [u8; COUNT_HWADDR_BYTES], } impl HwAddr { /// Create an empty hardware address (i.e., 00:00:00:00:00:00) pub fn empty() -> Self { HwAddr { bytes: [0; COUNT_HWADDR_BYTES], } } /// Create a broadcast hardware address (i.e., FF:FF:FF:FF:FF:FF) pub fn broadcast() -> Self { HwAddr { bytes: [0xFF; COUNT_HWADDR_BYTES], } } /// Is the current hardware address a broadcast /// address (i.e., FF:FF:FF:FF:FF:FF) pub fn
(&self) -> bool { *self == Self::broadcast() } /// Create an hardware address from bytes. /// /// This method is unsafe because the slice *MUST* contain at least 6 /// elements. pub unsafe fn from_bytes(bytes: &[u8]) -> Self { let mut ret = Self::empty(); ret.bytes[0] = bytes[0]; ret.bytes[1] = bytes[1]; ret.bytes[2] = bytes[2]; ret.bytes[3] = bytes[3]; ret.bytes[4] = bytes[4]; ret.bytes[5] = bytes[5]; ret } #[inline] /// Returns the internal representation of an hardware address pub fn as_bytes(&self) -> &[u8] { &self.bytes[..] } } impl FromStr for HwAddr { type Err = (); /// Convert a string with format XX:XX:XX:XX:XX:XX to an hardware address fn from_str(s: &str) -> Result<Self, Self::Err> { let split: Vec<&str> = s.split(':').collect(); if split.len()!= COUNT_HWADDR_BYTES { return Err(()) } let mut ret = Self::empty(); for (i, b) in split.iter().enumerate() { let bytes = b.as_bytes(); if bytes.len()!= 2 { return Err(()) } let d1 = try!(b.char_at(0).to_digit(16).ok_or(())) * 16; let d2 = try!(b.char_at(1).to_digit(16).ok_or(())); ret.bytes[i] = d1 as u8 + d2 as u8; } Ok(ret) } } impl Display for HwAddr { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { f.write_fmt(format_args!("{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", self.bytes[0], self.bytes[1], self.bytes[2], self.bytes[3], self.bytes[4], self.bytes[5])) } }
is_broadcast
identifier_name
htmlselectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLSelectElementDerived, HTMLFieldSetElementDerived}; use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement; use dom::bindings::js::{JSRef, Temporary}; use dom::document::Document; use dom::element::{AttributeHandlers, Element}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use util::str::DOMString; use string_cache::Atom; use std::borrow::ToOwned; #[dom_struct] pub struct HTMLSelectElement { htmlelement: HTMLElement } impl HTMLSelectElementDerived for EventTarget { fn is_htmlselectelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement))) } } impl HTMLSelectElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLSelectElement { HTMLSelectElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLSelectElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLSelectElement> { let element = HTMLSelectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap) } } impl<'a> HTMLSelectElementMethods for JSRef<'a, HTMLSelectElement> { fn Validity(self) -> Temporary<ValidityState> { let window = window_from_node(self).root(); ValidityState::new(window.r()) } // Note: this function currently only exists for test_union.html. fn Add(self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // https://www.whatwg.org/html/#dom-fe-disabled make_bool_getter!(Disabled); // https://www.whatwg.org/html/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-select-type fn Type(self) -> DOMString { let elem: JSRef<Element> = ElementCast::from_ref(self); if elem.has_attribute(&atom!("multiple")) { "select-multiple".to_owned() } else { "select-one".to_owned() } } } impl<'a> VirtualMethods for JSRef<'a, HTMLSelectElement> { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, attr: JSRef<Attr>) { if let Some(ref s) = self.super_type() { s.after_set_attr(attr); } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(true); node.set_enabled_state(false); }, _ => () } } fn before_remove_attr(&self, attr: JSRef<Attr>) { if let Some(ref s) = self.super_type() { s.before_remove_attr(attr); } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(false); node.set_enabled_state(true); node.check_ancestors_disabled_state_for_form_control(); }, _ => () } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } let node: JSRef<Node> = NodeCast::from_ref(*self); node.check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(tree_in_doc); } let node: JSRef<Node> = NodeCast::from_ref(*self); if node.ancestors().any(|ancestor| ancestor.root().r().is_htmlfieldsetelement()) { node.check_ancestors_disabled_state_for_form_control(); } else
} }
{ node.check_disabled_attribute(); }
conditional_block
htmlselectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLSelectElementDerived, HTMLFieldSetElementDerived}; use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement; use dom::bindings::js::{JSRef, Temporary}; use dom::document::Document; use dom::element::{AttributeHandlers, Element}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use util::str::DOMString; use string_cache::Atom; use std::borrow::ToOwned; #[dom_struct] pub struct HTMLSelectElement { htmlelement: HTMLElement } impl HTMLSelectElementDerived for EventTarget { fn is_htmlselectelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement))) } } impl HTMLSelectElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLSelectElement { HTMLSelectElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLSelectElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLSelectElement> { let element = HTMLSelectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap) } } impl<'a> HTMLSelectElementMethods for JSRef<'a, HTMLSelectElement> { fn Validity(self) -> Temporary<ValidityState> { let window = window_from_node(self).root(); ValidityState::new(window.r()) } // Note: this function currently only exists for test_union.html. fn Add(self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // https://www.whatwg.org/html/#dom-fe-disabled make_bool_getter!(Disabled); // https://www.whatwg.org/html/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-select-type fn Type(self) -> DOMString { let elem: JSRef<Element> = ElementCast::from_ref(self); if elem.has_attribute(&atom!("multiple")) { "select-multiple".to_owned() } else { "select-one".to_owned() } } } impl<'a> VirtualMethods for JSRef<'a, HTMLSelectElement> { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) }
fn after_set_attr(&self, attr: JSRef<Attr>) { if let Some(ref s) = self.super_type() { s.after_set_attr(attr); } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(true); node.set_enabled_state(false); }, _ => () } } fn before_remove_attr(&self, attr: JSRef<Attr>) { if let Some(ref s) = self.super_type() { s.before_remove_attr(attr); } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(false); node.set_enabled_state(true); node.check_ancestors_disabled_state_for_form_control(); }, _ => () } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } let node: JSRef<Node> = NodeCast::from_ref(*self); node.check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(tree_in_doc); } let node: JSRef<Node> = NodeCast::from_ref(*self); if node.ancestors().any(|ancestor| ancestor.root().r().is_htmlfieldsetelement()) { node.check_ancestors_disabled_state_for_form_control(); } else { node.check_disabled_attribute(); } } }
random_line_split
htmlselectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLSelectElementDerived, HTMLFieldSetElementDerived}; use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement; use dom::bindings::js::{JSRef, Temporary}; use dom::document::Document; use dom::element::{AttributeHandlers, Element}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use util::str::DOMString; use string_cache::Atom; use std::borrow::ToOwned; #[dom_struct] pub struct HTMLSelectElement { htmlelement: HTMLElement } impl HTMLSelectElementDerived for EventTarget { fn is_htmlselectelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement))) } } impl HTMLSelectElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLSelectElement { HTMLSelectElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLSelectElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn
(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLSelectElement> { let element = HTMLSelectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap) } } impl<'a> HTMLSelectElementMethods for JSRef<'a, HTMLSelectElement> { fn Validity(self) -> Temporary<ValidityState> { let window = window_from_node(self).root(); ValidityState::new(window.r()) } // Note: this function currently only exists for test_union.html. fn Add(self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // https://www.whatwg.org/html/#dom-fe-disabled make_bool_getter!(Disabled); // https://www.whatwg.org/html/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-select-type fn Type(self) -> DOMString { let elem: JSRef<Element> = ElementCast::from_ref(self); if elem.has_attribute(&atom!("multiple")) { "select-multiple".to_owned() } else { "select-one".to_owned() } } } impl<'a> VirtualMethods for JSRef<'a, HTMLSelectElement> { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, attr: JSRef<Attr>) { if let Some(ref s) = self.super_type() { s.after_set_attr(attr); } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(true); node.set_enabled_state(false); }, _ => () } } fn before_remove_attr(&self, attr: JSRef<Attr>) { if let Some(ref s) = self.super_type() { s.before_remove_attr(attr); } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(false); node.set_enabled_state(true); node.check_ancestors_disabled_state_for_form_control(); }, _ => () } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } let node: JSRef<Node> = NodeCast::from_ref(*self); node.check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(tree_in_doc); } let node: JSRef<Node> = NodeCast::from_ref(*self); if node.ancestors().any(|ancestor| ancestor.root().r().is_htmlfieldsetelement()) { node.check_ancestors_disabled_state_for_form_control(); } else { node.check_disabled_attribute(); } } }
new
identifier_name
build.rs
extern crate cc; use std::path::{ PathBuf, Path }; use std::process::Command; struct Perl { bin: String, } impl Perl { fn new() -> Perl { Perl { bin: std::env::var("PERL").unwrap_or("perl".to_owned()), } } fn cfg(&self, key: &str) -> String { let out = Command::new(&self.bin) .arg("-MConfig") .arg("-e") .arg(format!("print $Config::Config{{{}}}", key)) .output() .unwrap(); String::from_utf8(out.stdout).unwrap() } fn run(&self, script: &str) { let status = Command::new(&self.bin) .arg(script) .status() .unwrap(); assert!(status.success()); } fn path_core(&self) -> PathBuf { let archlib = self.cfg("archlibexp"); Path::new(&archlib).join("CORE") } } fn build(perl: &Perl) { let mut cc = cc::Build::new(); let ccflags = std::env::var("LIBPERL_CCFLAGS").unwrap_or_else(|_e| { perl.cfg("ccflags") }); for flag in ccflags.split_whitespace() { cc.flag(flag); } cc.flag("-g"); cc.flag("-finline-functions"); cc.include(&perl.path_core()); let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR is set"); cc.file(Path::new(&out_dir).join("perl_sys.c")); cc.compile("libperlsys.a"); } fn main() { let perl = Perl::new(); perl.run("build/regen.pl"); build(&perl); if perl.cfg("usemultiplicity") == "define"
if perl.cfg("useshrplib") == "true" { println!("cargo:rustc-cfg=perl_useshrplib"); // Make sure ld links to libperl that matches current perl interpreter, instead of whatever // is libperl version exists in default linker search path. $archlibexp/CORE is hard-coded // installation path for default perl so this ought to be enough in most cases. println!("cargo:rustc-link-search=native={}", perl.path_core().to_str().unwrap()); } }
{ println!("cargo:rustc-cfg=perl_multiplicity"); }
conditional_block
build.rs
extern crate cc; use std::path::{ PathBuf, Path }; use std::process::Command; struct Perl { bin: String, } impl Perl { fn new() -> Perl { Perl { bin: std::env::var("PERL").unwrap_or("perl".to_owned()), } } fn cfg(&self, key: &str) -> String { let out = Command::new(&self.bin) .arg("-MConfig") .arg("-e") .arg(format!("print $Config::Config{{{}}}", key)) .output() .unwrap(); String::from_utf8(out.stdout).unwrap() } fn run(&self, script: &str) { let status = Command::new(&self.bin) .arg(script) .status() .unwrap(); assert!(status.success()); } fn
(&self) -> PathBuf { let archlib = self.cfg("archlibexp"); Path::new(&archlib).join("CORE") } } fn build(perl: &Perl) { let mut cc = cc::Build::new(); let ccflags = std::env::var("LIBPERL_CCFLAGS").unwrap_or_else(|_e| { perl.cfg("ccflags") }); for flag in ccflags.split_whitespace() { cc.flag(flag); } cc.flag("-g"); cc.flag("-finline-functions"); cc.include(&perl.path_core()); let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR is set"); cc.file(Path::new(&out_dir).join("perl_sys.c")); cc.compile("libperlsys.a"); } fn main() { let perl = Perl::new(); perl.run("build/regen.pl"); build(&perl); if perl.cfg("usemultiplicity") == "define" { println!("cargo:rustc-cfg=perl_multiplicity"); } if perl.cfg("useshrplib") == "true" { println!("cargo:rustc-cfg=perl_useshrplib"); // Make sure ld links to libperl that matches current perl interpreter, instead of whatever // is libperl version exists in default linker search path. $archlibexp/CORE is hard-coded // installation path for default perl so this ought to be enough in most cases. println!("cargo:rustc-link-search=native={}", perl.path_core().to_str().unwrap()); } }
path_core
identifier_name
build.rs
extern crate cc; use std::path::{ PathBuf, Path }; use std::process::Command; struct Perl { bin: String, } impl Perl { fn new() -> Perl { Perl { bin: std::env::var("PERL").unwrap_or("perl".to_owned()), } } fn cfg(&self, key: &str) -> String { let out = Command::new(&self.bin) .arg("-MConfig") .arg("-e") .arg(format!("print $Config::Config{{{}}}", key)) .output() .unwrap(); String::from_utf8(out.stdout).unwrap() } fn run(&self, script: &str) { let status = Command::new(&self.bin) .arg(script) .status() .unwrap(); assert!(status.success()); } fn path_core(&self) -> PathBuf { let archlib = self.cfg("archlibexp"); Path::new(&archlib).join("CORE") } } fn build(perl: &Perl) { let mut cc = cc::Build::new(); let ccflags = std::env::var("LIBPERL_CCFLAGS").unwrap_or_else(|_e| { perl.cfg("ccflags") }); for flag in ccflags.split_whitespace() { cc.flag(flag); } cc.flag("-g"); cc.flag("-finline-functions"); cc.include(&perl.path_core()); let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR is set"); cc.file(Path::new(&out_dir).join("perl_sys.c")); cc.compile("libperlsys.a"); } fn main() { let perl = Perl::new(); perl.run("build/regen.pl"); build(&perl); if perl.cfg("usemultiplicity") == "define" { println!("cargo:rustc-cfg=perl_multiplicity"); } if perl.cfg("useshrplib") == "true" { println!("cargo:rustc-cfg=perl_useshrplib"); // Make sure ld links to libperl that matches current perl interpreter, instead of whatever
// is libperl version exists in default linker search path. $archlibexp/CORE is hard-coded // installation path for default perl so this ought to be enough in most cases. println!("cargo:rustc-link-search=native={}", perl.path_core().to_str().unwrap()); } }
random_line_split
build.rs
extern crate cc; use std::path::{ PathBuf, Path }; use std::process::Command; struct Perl { bin: String, } impl Perl { fn new() -> Perl { Perl { bin: std::env::var("PERL").unwrap_or("perl".to_owned()), } } fn cfg(&self, key: &str) -> String { let out = Command::new(&self.bin) .arg("-MConfig") .arg("-e") .arg(format!("print $Config::Config{{{}}}", key)) .output() .unwrap(); String::from_utf8(out.stdout).unwrap() } fn run(&self, script: &str) { let status = Command::new(&self.bin) .arg(script) .status() .unwrap(); assert!(status.success()); } fn path_core(&self) -> PathBuf { let archlib = self.cfg("archlibexp"); Path::new(&archlib).join("CORE") } } fn build(perl: &Perl) { let mut cc = cc::Build::new(); let ccflags = std::env::var("LIBPERL_CCFLAGS").unwrap_or_else(|_e| { perl.cfg("ccflags") }); for flag in ccflags.split_whitespace() { cc.flag(flag); } cc.flag("-g"); cc.flag("-finline-functions"); cc.include(&perl.path_core()); let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR is set"); cc.file(Path::new(&out_dir).join("perl_sys.c")); cc.compile("libperlsys.a"); } fn main()
{ let perl = Perl::new(); perl.run("build/regen.pl"); build(&perl); if perl.cfg("usemultiplicity") == "define" { println!("cargo:rustc-cfg=perl_multiplicity"); } if perl.cfg("useshrplib") == "true" { println!("cargo:rustc-cfg=perl_useshrplib"); // Make sure ld links to libperl that matches current perl interpreter, instead of whatever // is libperl version exists in default linker search path. $archlibexp/CORE is hard-coded // installation path for default perl so this ought to be enough in most cases. println!("cargo:rustc-link-search=native={}", perl.path_core().to_str().unwrap()); } }
identifier_body
request_redraw_threaded.rs
use std::{thread, time}; use simple_logger::SimpleLogger; use winit::{ event::{Event, WindowEvent}, event_loop::{ControlFlow, EventLoop}, window::WindowBuilder, }; fn
() { SimpleLogger::new().init().unwrap(); let event_loop = EventLoop::new(); let window = WindowBuilder::new() .with_title("A fantastic window!") .build(&event_loop) .unwrap(); thread::spawn(move || loop { thread::sleep(time::Duration::from_secs(1)); window.request_redraw(); }); event_loop.run(move |event, _, control_flow| { println!("{:?}", event); *control_flow = ControlFlow::Wait; match event { Event::WindowEvent { event,.. } => match event { WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, _ => (), }, Event::RedrawRequested(_) => { println!("\nredrawing!\n"); } _ => (), } }); }
main
identifier_name
request_redraw_threaded.rs
use std::{thread, time}; use simple_logger::SimpleLogger; use winit::{ event::{Event, WindowEvent}, event_loop::{ControlFlow, EventLoop}, window::WindowBuilder, }; fn main() { SimpleLogger::new().init().unwrap(); let event_loop = EventLoop::new(); let window = WindowBuilder::new() .with_title("A fantastic window!") .build(&event_loop) .unwrap(); thread::spawn(move || loop { thread::sleep(time::Duration::from_secs(1)); window.request_redraw(); }); event_loop.run(move |event, _, control_flow| { println!("{:?}", event); *control_flow = ControlFlow::Wait; match event { Event::WindowEvent { event,.. } => match event { WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, _ => (), }, Event::RedrawRequested(_) => { println!("\nredrawing!\n"); }
} }); }
_ => (),
random_line_split
request_redraw_threaded.rs
use std::{thread, time}; use simple_logger::SimpleLogger; use winit::{ event::{Event, WindowEvent}, event_loop::{ControlFlow, EventLoop}, window::WindowBuilder, }; fn main()
Event::WindowEvent { event,.. } => match event { WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, _ => (), }, Event::RedrawRequested(_) => { println!("\nredrawing!\n"); } _ => (), } }); }
{ SimpleLogger::new().init().unwrap(); let event_loop = EventLoop::new(); let window = WindowBuilder::new() .with_title("A fantastic window!") .build(&event_loop) .unwrap(); thread::spawn(move || loop { thread::sleep(time::Duration::from_secs(1)); window.request_redraw(); }); event_loop.run(move |event, _, control_flow| { println!("{:?}", event); *control_flow = ControlFlow::Wait; match event {
identifier_body
main.rs
extern crate hyper; extern crate iron; extern crate router; extern crate handlebars_iron as hbsi; extern crate rustc_serialize; extern crate persistent; extern crate urlencoded; extern crate traitobject; #[macro_use] extern crate mime; extern crate mysql; extern crate crypto; extern crate rand; extern crate iron_login; #[macro_use] extern crate log; extern crate log4rs; extern crate time; extern crate chrono; #[macro_use] extern crate lazy_static; extern crate pulldown_cmark; extern crate regex; extern crate ammonia; extern crate rss; extern crate cookie; extern crate oven; extern crate url; extern crate mount; extern crate staticfile; extern crate form_checker; mod base; mod handlers; mod route; use iron::Chain; use hbsi::{HandlebarsEngine, DirectorySource}; use persistent::Read; use base::config::Config; use base::db::MyPool; use mount::Mount; use staticfile::Static; use std::path::Path; fn main()
mount.mount("/", chain); mount.mount("/static/", Static::new(Path::new("static"))); let listen = config.get("listen").as_str().unwrap(); iron::Iron::new(mount).http(listen).unwrap(); }
{ // init logging log4rs::init_file("log4rs.yaml", Default::default()).unwrap(); let mut chain = Chain::new(route::gen_router()); let config = Config::new(); chain.link_before(Read::<Config>::one(config.clone())); let my_pool = MyPool::new(&config); chain.link_before(Read::<MyPool>::one(my_pool)); let cookie_sign_key = config.get("cookie_sign_key").as_str().unwrap().as_bytes().to_owned(); chain.link_around(iron_login::LoginManager::new(cookie_sign_key)); let mut hbse = HandlebarsEngine::new(); hbse.add(Box::new(DirectorySource::new("templates/", ".hbs"))); hbse.reload().unwrap(); chain.link_after(hbse); let mut mount = Mount::new();
identifier_body
main.rs
extern crate hyper; extern crate iron; extern crate router; extern crate handlebars_iron as hbsi; extern crate rustc_serialize; extern crate persistent; extern crate urlencoded; extern crate traitobject; #[macro_use] extern crate mime; extern crate mysql; extern crate crypto; extern crate rand; extern crate iron_login; #[macro_use] extern crate log; extern crate log4rs; extern crate time; extern crate chrono; #[macro_use] extern crate lazy_static; extern crate pulldown_cmark; extern crate regex; extern crate ammonia; extern crate rss; extern crate cookie; extern crate oven; extern crate url; extern crate mount; extern crate staticfile; extern crate form_checker; mod base; mod handlers; mod route; use iron::Chain; use hbsi::{HandlebarsEngine, DirectorySource}; use persistent::Read; use base::config::Config; use base::db::MyPool; use mount::Mount; use staticfile::Static; use std::path::Path; fn
() { // init logging log4rs::init_file("log4rs.yaml", Default::default()).unwrap(); let mut chain = Chain::new(route::gen_router()); let config = Config::new(); chain.link_before(Read::<Config>::one(config.clone())); let my_pool = MyPool::new(&config); chain.link_before(Read::<MyPool>::one(my_pool)); let cookie_sign_key = config.get("cookie_sign_key").as_str().unwrap().as_bytes().to_owned(); chain.link_around(iron_login::LoginManager::new(cookie_sign_key)); let mut hbse = HandlebarsEngine::new(); hbse.add(Box::new(DirectorySource::new("templates/", ".hbs"))); hbse.reload().unwrap(); chain.link_after(hbse); let mut mount = Mount::new(); mount.mount("/", chain); mount.mount("/static/", Static::new(Path::new("static"))); let listen = config.get("listen").as_str().unwrap(); iron::Iron::new(mount).http(listen).unwrap(); }
main
identifier_name
main.rs
extern crate hyper; extern crate iron; extern crate router; extern crate handlebars_iron as hbsi; extern crate rustc_serialize; extern crate persistent; extern crate urlencoded; extern crate traitobject; #[macro_use] extern crate mime; extern crate mysql; extern crate crypto; extern crate rand; extern crate iron_login; #[macro_use] extern crate log;
extern crate pulldown_cmark; extern crate regex; extern crate ammonia; extern crate rss; extern crate cookie; extern crate oven; extern crate url; extern crate mount; extern crate staticfile; extern crate form_checker; mod base; mod handlers; mod route; use iron::Chain; use hbsi::{HandlebarsEngine, DirectorySource}; use persistent::Read; use base::config::Config; use base::db::MyPool; use mount::Mount; use staticfile::Static; use std::path::Path; fn main() { // init logging log4rs::init_file("log4rs.yaml", Default::default()).unwrap(); let mut chain = Chain::new(route::gen_router()); let config = Config::new(); chain.link_before(Read::<Config>::one(config.clone())); let my_pool = MyPool::new(&config); chain.link_before(Read::<MyPool>::one(my_pool)); let cookie_sign_key = config.get("cookie_sign_key").as_str().unwrap().as_bytes().to_owned(); chain.link_around(iron_login::LoginManager::new(cookie_sign_key)); let mut hbse = HandlebarsEngine::new(); hbse.add(Box::new(DirectorySource::new("templates/", ".hbs"))); hbse.reload().unwrap(); chain.link_after(hbse); let mut mount = Mount::new(); mount.mount("/", chain); mount.mount("/static/", Static::new(Path::new("static"))); let listen = config.get("listen").as_str().unwrap(); iron::Iron::new(mount).http(listen).unwrap(); }
extern crate log4rs; extern crate time; extern crate chrono; #[macro_use] extern crate lazy_static;
random_line_split
vrstageparameters.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::VRStageParametersBinding; use crate::dom::bindings::codegen::Bindings::VRStageParametersBinding::VRStageParametersMethods; use crate::dom::bindings::num::Finite; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; use js::jsapi::{Heap, JSContext, JSObject}; use js::typedarray::{CreateWith, Float32Array}; use std::ptr; use std::ptr::NonNull; use webvr_traits::WebVRStageParameters; #[dom_struct] pub struct VRStageParameters { reflector_: Reflector, #[ignore_malloc_size_of = "Defined in rust-webvr"] parameters: DomRefCell<WebVRStageParameters>, transform: Heap<*mut JSObject>, } unsafe_no_jsmanaged_fields!(WebVRStageParameters); impl VRStageParameters { fn new_inherited(parameters: WebVRStageParameters) -> VRStageParameters { VRStageParameters { reflector_: Reflector::new(), parameters: DomRefCell::new(parameters), transform: Heap::default(), } } #[allow(unsafe_code)] pub fn new( parameters: WebVRStageParameters, global: &GlobalScope, ) -> DomRoot<VRStageParameters> { let cx = global.get_cx(); rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); unsafe { let _ = Float32Array::create( cx, CreateWith::Slice(&parameters.sitting_to_standing_transform), array.handle_mut(), ); } let stage_parameters = reflect_dom_object( Box::new(VRStageParameters::new_inherited(parameters)), global, VRStageParametersBinding::Wrap, ); stage_parameters.transform.set(array.get()); stage_parameters } #[allow(unsafe_code)] pub fn update(&self, parameters: &WebVRStageParameters) { unsafe { let cx = self.global().get_cx(); typedarray!(in(cx) let array: Float32Array = self.transform.get()); if let Ok(mut array) = array
} *self.parameters.borrow_mut() = parameters.clone(); } } impl VRStageParametersMethods for VRStageParameters { #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform unsafe fn SittingToStandingTransform(&self, _cx: *mut JSContext) -> NonNull<JSObject> { NonNull::new_unchecked(self.transform.get()) } // https://w3c.github.io/webvr/#dom-vrstageparameters-sizex fn SizeX(&self) -> Finite<f32> { Finite::wrap(self.parameters.borrow().size_x) } // https://w3c.github.io/webvr/#dom-vrstageparameters-sizez fn SizeZ(&self) -> Finite<f32> { Finite::wrap(self.parameters.borrow().size_z) } }
{ array.update(&parameters.sitting_to_standing_transform); }
conditional_block
vrstageparameters.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::VRStageParametersBinding; use crate::dom::bindings::codegen::Bindings::VRStageParametersBinding::VRStageParametersMethods; use crate::dom::bindings::num::Finite; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; use js::jsapi::{Heap, JSContext, JSObject}; use js::typedarray::{CreateWith, Float32Array}; use std::ptr; use std::ptr::NonNull; use webvr_traits::WebVRStageParameters; #[dom_struct] pub struct VRStageParameters { reflector_: Reflector, #[ignore_malloc_size_of = "Defined in rust-webvr"] parameters: DomRefCell<WebVRStageParameters>, transform: Heap<*mut JSObject>, } unsafe_no_jsmanaged_fields!(WebVRStageParameters); impl VRStageParameters { fn new_inherited(parameters: WebVRStageParameters) -> VRStageParameters { VRStageParameters { reflector_: Reflector::new(), parameters: DomRefCell::new(parameters), transform: Heap::default(), } } #[allow(unsafe_code)] pub fn new( parameters: WebVRStageParameters, global: &GlobalScope, ) -> DomRoot<VRStageParameters> { let cx = global.get_cx(); rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); unsafe { let _ = Float32Array::create( cx, CreateWith::Slice(&parameters.sitting_to_standing_transform), array.handle_mut(), ); } let stage_parameters = reflect_dom_object( Box::new(VRStageParameters::new_inherited(parameters)), global, VRStageParametersBinding::Wrap, ); stage_parameters.transform.set(array.get()); stage_parameters } #[allow(unsafe_code)] pub fn
(&self, parameters: &WebVRStageParameters) { unsafe { let cx = self.global().get_cx(); typedarray!(in(cx) let array: Float32Array = self.transform.get()); if let Ok(mut array) = array { array.update(&parameters.sitting_to_standing_transform); } } *self.parameters.borrow_mut() = parameters.clone(); } } impl VRStageParametersMethods for VRStageParameters { #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform unsafe fn SittingToStandingTransform(&self, _cx: *mut JSContext) -> NonNull<JSObject> { NonNull::new_unchecked(self.transform.get()) } // https://w3c.github.io/webvr/#dom-vrstageparameters-sizex fn SizeX(&self) -> Finite<f32> { Finite::wrap(self.parameters.borrow().size_x) } // https://w3c.github.io/webvr/#dom-vrstageparameters-sizez fn SizeZ(&self) -> Finite<f32> { Finite::wrap(self.parameters.borrow().size_z) } }
update
identifier_name
vrstageparameters.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::VRStageParametersBinding; use crate::dom::bindings::codegen::Bindings::VRStageParametersBinding::VRStageParametersMethods; use crate::dom::bindings::num::Finite; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; use js::jsapi::{Heap, JSContext, JSObject}; use js::typedarray::{CreateWith, Float32Array}; use std::ptr; use std::ptr::NonNull; use webvr_traits::WebVRStageParameters;
pub struct VRStageParameters { reflector_: Reflector, #[ignore_malloc_size_of = "Defined in rust-webvr"] parameters: DomRefCell<WebVRStageParameters>, transform: Heap<*mut JSObject>, } unsafe_no_jsmanaged_fields!(WebVRStageParameters); impl VRStageParameters { fn new_inherited(parameters: WebVRStageParameters) -> VRStageParameters { VRStageParameters { reflector_: Reflector::new(), parameters: DomRefCell::new(parameters), transform: Heap::default(), } } #[allow(unsafe_code)] pub fn new( parameters: WebVRStageParameters, global: &GlobalScope, ) -> DomRoot<VRStageParameters> { let cx = global.get_cx(); rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); unsafe { let _ = Float32Array::create( cx, CreateWith::Slice(&parameters.sitting_to_standing_transform), array.handle_mut(), ); } let stage_parameters = reflect_dom_object( Box::new(VRStageParameters::new_inherited(parameters)), global, VRStageParametersBinding::Wrap, ); stage_parameters.transform.set(array.get()); stage_parameters } #[allow(unsafe_code)] pub fn update(&self, parameters: &WebVRStageParameters) { unsafe { let cx = self.global().get_cx(); typedarray!(in(cx) let array: Float32Array = self.transform.get()); if let Ok(mut array) = array { array.update(&parameters.sitting_to_standing_transform); } } *self.parameters.borrow_mut() = parameters.clone(); } } impl VRStageParametersMethods for VRStageParameters { #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform unsafe fn SittingToStandingTransform(&self, _cx: *mut JSContext) -> NonNull<JSObject> { NonNull::new_unchecked(self.transform.get()) } // https://w3c.github.io/webvr/#dom-vrstageparameters-sizex fn SizeX(&self) -> Finite<f32> { Finite::wrap(self.parameters.borrow().size_x) } // https://w3c.github.io/webvr/#dom-vrstageparameters-sizez fn SizeZ(&self) -> Finite<f32> { Finite::wrap(self.parameters.borrow().size_z) } }
#[dom_struct]
random_line_split
vrstageparameters.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::VRStageParametersBinding; use crate::dom::bindings::codegen::Bindings::VRStageParametersBinding::VRStageParametersMethods; use crate::dom::bindings::num::Finite; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; use js::jsapi::{Heap, JSContext, JSObject}; use js::typedarray::{CreateWith, Float32Array}; use std::ptr; use std::ptr::NonNull; use webvr_traits::WebVRStageParameters; #[dom_struct] pub struct VRStageParameters { reflector_: Reflector, #[ignore_malloc_size_of = "Defined in rust-webvr"] parameters: DomRefCell<WebVRStageParameters>, transform: Heap<*mut JSObject>, } unsafe_no_jsmanaged_fields!(WebVRStageParameters); impl VRStageParameters { fn new_inherited(parameters: WebVRStageParameters) -> VRStageParameters { VRStageParameters { reflector_: Reflector::new(), parameters: DomRefCell::new(parameters), transform: Heap::default(), } } #[allow(unsafe_code)] pub fn new( parameters: WebVRStageParameters, global: &GlobalScope, ) -> DomRoot<VRStageParameters>
} #[allow(unsafe_code)] pub fn update(&self, parameters: &WebVRStageParameters) { unsafe { let cx = self.global().get_cx(); typedarray!(in(cx) let array: Float32Array = self.transform.get()); if let Ok(mut array) = array { array.update(&parameters.sitting_to_standing_transform); } } *self.parameters.borrow_mut() = parameters.clone(); } } impl VRStageParametersMethods for VRStageParameters { #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform unsafe fn SittingToStandingTransform(&self, _cx: *mut JSContext) -> NonNull<JSObject> { NonNull::new_unchecked(self.transform.get()) } // https://w3c.github.io/webvr/#dom-vrstageparameters-sizex fn SizeX(&self) -> Finite<f32> { Finite::wrap(self.parameters.borrow().size_x) } // https://w3c.github.io/webvr/#dom-vrstageparameters-sizez fn SizeZ(&self) -> Finite<f32> { Finite::wrap(self.parameters.borrow().size_z) } }
{ let cx = global.get_cx(); rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); unsafe { let _ = Float32Array::create( cx, CreateWith::Slice(&parameters.sitting_to_standing_transform), array.handle_mut(), ); } let stage_parameters = reflect_dom_object( Box::new(VRStageParameters::new_inherited(parameters)), global, VRStageParametersBinding::Wrap, ); stage_parameters.transform.set(array.get()); stage_parameters
identifier_body
intersection_two.rs
use docset::DocSet; use query::Scorer; use DocId; use Score; use SkipResult; /// Creates a `DocSet` that iterator through the intersection of two `DocSet`s. pub struct IntersectionTwoTerms<TDocSet> { left: TDocSet, right: TDocSet } impl<TDocSet: DocSet> IntersectionTwoTerms<TDocSet> { pub fn new(left: TDocSet, right: TDocSet) -> IntersectionTwoTerms<TDocSet> { IntersectionTwoTerms { left, right } } } impl<TDocSet: DocSet> DocSet for IntersectionTwoTerms<TDocSet> { fn advance(&mut self) -> bool { let (left, right) = (&mut self.left, &mut self.right); if!left.advance() { return false;
let mut candidate = left.doc(); loop { match right.skip_next(candidate) { SkipResult::Reached => { return true; } SkipResult::End => { return false; } SkipResult::OverStep => { candidate = right.doc(); } } match left.skip_next(candidate) { SkipResult::Reached => { return true; } SkipResult::End => { return false; } SkipResult::OverStep => { candidate = left.doc(); } } } } fn doc(&self) -> DocId { self.left.doc() } fn size_hint(&self) -> u32 { self.left.size_hint().min(self.right.size_hint()) } } impl<TScorer: Scorer> Scorer for IntersectionTwoTerms<TScorer> { fn score(&mut self) -> Score { self.left.score() + self.right.score() } }
}
random_line_split
intersection_two.rs
use docset::DocSet; use query::Scorer; use DocId; use Score; use SkipResult; /// Creates a `DocSet` that iterator through the intersection of two `DocSet`s. pub struct IntersectionTwoTerms<TDocSet> { left: TDocSet, right: TDocSet } impl<TDocSet: DocSet> IntersectionTwoTerms<TDocSet> { pub fn new(left: TDocSet, right: TDocSet) -> IntersectionTwoTerms<TDocSet> { IntersectionTwoTerms { left, right } } } impl<TDocSet: DocSet> DocSet for IntersectionTwoTerms<TDocSet> { fn
(&mut self) -> bool { let (left, right) = (&mut self.left, &mut self.right); if!left.advance() { return false; } let mut candidate = left.doc(); loop { match right.skip_next(candidate) { SkipResult::Reached => { return true; } SkipResult::End => { return false; } SkipResult::OverStep => { candidate = right.doc(); } } match left.skip_next(candidate) { SkipResult::Reached => { return true; } SkipResult::End => { return false; } SkipResult::OverStep => { candidate = left.doc(); } } } } fn doc(&self) -> DocId { self.left.doc() } fn size_hint(&self) -> u32 { self.left.size_hint().min(self.right.size_hint()) } } impl<TScorer: Scorer> Scorer for IntersectionTwoTerms<TScorer> { fn score(&mut self) -> Score { self.left.score() + self.right.score() } }
advance
identifier_name
intersection_two.rs
use docset::DocSet; use query::Scorer; use DocId; use Score; use SkipResult; /// Creates a `DocSet` that iterator through the intersection of two `DocSet`s. pub struct IntersectionTwoTerms<TDocSet> { left: TDocSet, right: TDocSet } impl<TDocSet: DocSet> IntersectionTwoTerms<TDocSet> { pub fn new(left: TDocSet, right: TDocSet) -> IntersectionTwoTerms<TDocSet> { IntersectionTwoTerms { left, right } } } impl<TDocSet: DocSet> DocSet for IntersectionTwoTerms<TDocSet> { fn advance(&mut self) -> bool { let (left, right) = (&mut self.left, &mut self.right); if!left.advance() { return false; } let mut candidate = left.doc(); loop { match right.skip_next(candidate) { SkipResult::Reached => { return true; } SkipResult::End => { return false; } SkipResult::OverStep => { candidate = right.doc(); } } match left.skip_next(candidate) { SkipResult::Reached =>
SkipResult::End => { return false; } SkipResult::OverStep => { candidate = left.doc(); } } } } fn doc(&self) -> DocId { self.left.doc() } fn size_hint(&self) -> u32 { self.left.size_hint().min(self.right.size_hint()) } } impl<TScorer: Scorer> Scorer for IntersectionTwoTerms<TScorer> { fn score(&mut self) -> Score { self.left.score() + self.right.score() } }
{ return true; }
conditional_block
intersection_two.rs
use docset::DocSet; use query::Scorer; use DocId; use Score; use SkipResult; /// Creates a `DocSet` that iterator through the intersection of two `DocSet`s. pub struct IntersectionTwoTerms<TDocSet> { left: TDocSet, right: TDocSet } impl<TDocSet: DocSet> IntersectionTwoTerms<TDocSet> { pub fn new(left: TDocSet, right: TDocSet) -> IntersectionTwoTerms<TDocSet> { IntersectionTwoTerms { left, right } } } impl<TDocSet: DocSet> DocSet for IntersectionTwoTerms<TDocSet> { fn advance(&mut self) -> bool
return true; } SkipResult::End => { return false; } SkipResult::OverStep => { candidate = left.doc(); } } } } fn doc(&self) -> DocId { self.left.doc() } fn size_hint(&self) -> u32 { self.left.size_hint().min(self.right.size_hint()) } } impl<TScorer: Scorer> Scorer for IntersectionTwoTerms<TScorer> { fn score(&mut self) -> Score { self.left.score() + self.right.score() } }
{ let (left, right) = (&mut self.left, &mut self.right); if !left.advance() { return false; } let mut candidate = left.doc(); loop { match right.skip_next(candidate) { SkipResult::Reached => { return true; } SkipResult::End => { return false; } SkipResult::OverStep => { candidate = right.doc(); } } match left.skip_next(candidate) { SkipResult::Reached => {
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ // Make |cargo bench| work. #![cfg_attr(feature = "bench", feature(test))] #[macro_use] extern crate bitflags; #[macro_use] extern crate cssparser; #[macro_use] extern crate derive_more; extern crate fxhash; #[macro_use] extern crate log;
extern crate smallvec; extern crate to_shmem; #[macro_use] extern crate to_shmem_derive; pub mod attr; pub mod bloom; mod builder; pub mod context; pub mod matching; mod nth_index_cache; pub mod parser; pub mod sink; mod tree; pub mod visitor; pub use crate::nth_index_cache::NthIndexCache; pub use crate::parser::{Parser, SelectorImpl, SelectorList}; pub use crate::tree::{Element, OpaqueElement};
extern crate phf; extern crate precomputed_hash; extern crate servo_arc;
random_line_split
actor.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/. */ /// General actor system infrastructure. use devtools_traits::PreciseTime; use rustc_serialize::json; use std::any::Any; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::mem::replace; use std::net::TcpStream; use std::sync::{Arc, Mutex}; #[derive(PartialEq)] pub enum ActorMessageStatus { Processed, Ignored, } /// A common trait for all devtools actors that encompasses an immutable name /// and the ability to process messages that are directed to particular actors. /// TODO: ensure the name is immutable pub trait Actor: Any + ActorAsAny { fn handle_message(&self, registry: &ActorRegistry, msg_type: &str, msg: &json::Object, stream: &mut TcpStream) -> Result<ActorMessageStatus, ()>; fn name(&self) -> String; } trait ActorAsAny { fn actor_as_any(&self) -> &Any; fn actor_as_any_mut(&mut self) -> &mut Any; } impl<T: Actor> ActorAsAny for T { fn actor_as_any(&self) -> &Any { self } fn actor_as_any_mut(&mut self) -> &mut Any { self } } /// A list of known, owned actors. pub struct ActorRegistry { actors: HashMap<String, Box<Actor + Send>>, new_actors: RefCell<Vec<Box<Actor + Send>>>, old_actors: RefCell<Vec<String>>, script_actors: RefCell<HashMap<String, String>>, shareable: Option<Arc<Mutex<ActorRegistry>>>, next: Cell<u32>, start_stamp: PreciseTime, } impl ActorRegistry { /// Create an empty registry. pub fn new() -> ActorRegistry { ActorRegistry { actors: HashMap::new(), new_actors: RefCell::new(vec!()), old_actors: RefCell::new(vec!()), script_actors: RefCell::new(HashMap::new()), shareable: None, next: Cell::new(0), start_stamp: PreciseTime::now(), } } /// Creating shareable registry pub fn create_shareable(self) -> Arc<Mutex<ActorRegistry>> { if let Some(shareable) = self.shareable { return shareable; } let shareable = Arc::new(Mutex::new(self)); { let mut lock = shareable.lock(); let registry = lock.as_mut().unwrap(); registry.shareable = Some(shareable.clone()); } shareable } /// Get shareable registry through threads pub fn shareable(&self) -> Arc<Mutex<ActorRegistry>> { self.shareable.as_ref().unwrap().clone() } /// Get start stamp when registry was started pub fn start_stamp(&self) -> PreciseTime { self.start_stamp.clone() } pub fn register_script_actor(&self, script_id: String, actor: String) { println!("registering {} ({})", actor, script_id); let mut script_actors = self.script_actors.borrow_mut(); script_actors.insert(script_id, actor); } pub fn script_to_actor(&self, script_id: String) -> String { if script_id.is_empty() { return "".to_owned(); } self.script_actors.borrow().get(&script_id).unwrap().clone() } pub fn script_actor_registered(&self, script_id: String) -> bool { self.script_actors.borrow().contains_key(&script_id) } pub fn actor_to_script(&self, actor: String) -> String { for (key, value) in &*self.script_actors.borrow() { println!("checking {}", value); if *value == actor { return key.to_owned(); } } panic!("couldn't find actor named {}", actor) } /// Create a unique name based on a monotonically increasing suffix pub fn new_name(&self, prefix: &str) -> String { let suffix = self.next.get(); self.next.set(suffix + 1); format!("{}{}", prefix, suffix) } /// Add an actor to the registry of known actors that can receive messages. pub fn register(&mut self, actor: Box<Actor + Send>) { self.actors.insert(actor.name(), actor); } pub fn register_later(&self, actor: Box<Actor + Send>) { let mut actors = self.new_actors.borrow_mut(); actors.push(actor); }
/// Find an actor by registered name pub fn find_mut<'a, T: Any>(&'a mut self, name: &str) -> &'a mut T { let actor = self.actors.get_mut(name).unwrap(); actor.actor_as_any_mut().downcast_mut::<T>().unwrap() } /// Attempt to process a message as directed by its `to` property. If the actor is not /// found or does not indicate that it knew how to process the message, ignore the failure. pub fn handle_message(&mut self, msg: &json::Object, stream: &mut TcpStream) -> Result<(), ()> { let to = msg.get("to").unwrap().as_string().unwrap(); match self.actors.get(to) { None => println!("message received for unknown actor \"{}\"", to), Some(actor) => { let msg_type = msg.get("type").unwrap().as_string().unwrap(); if try!(actor.handle_message(self, msg_type, msg, stream)) != ActorMessageStatus::Processed { println!("unexpected message type \"{}\" found for actor \"{}\"", msg_type, to); } } } let new_actors = replace(&mut *self.new_actors.borrow_mut(), vec!()); for actor in new_actors.into_iter() { self.actors.insert(actor.name().to_owned(), actor); } let old_actors = replace(&mut *self.old_actors.borrow_mut(), vec!()); for name in old_actors { self.drop_actor(name); } Ok(()) } pub fn drop_actor(&mut self, name: String) { self.actors.remove(&name); } pub fn drop_actor_later(&self, name: String) { let mut actors = self.old_actors.borrow_mut(); actors.push(name); } }
/// Find an actor by registered name pub fn find<'a, T: Any>(&'a self, name: &str) -> &'a T { let actor = self.actors.get(name).unwrap(); actor.actor_as_any().downcast_ref::<T>().unwrap() }
random_line_split
actor.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/. */ /// General actor system infrastructure. use devtools_traits::PreciseTime; use rustc_serialize::json; use std::any::Any; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::mem::replace; use std::net::TcpStream; use std::sync::{Arc, Mutex}; #[derive(PartialEq)] pub enum ActorMessageStatus { Processed, Ignored, } /// A common trait for all devtools actors that encompasses an immutable name /// and the ability to process messages that are directed to particular actors. /// TODO: ensure the name is immutable pub trait Actor: Any + ActorAsAny { fn handle_message(&self, registry: &ActorRegistry, msg_type: &str, msg: &json::Object, stream: &mut TcpStream) -> Result<ActorMessageStatus, ()>; fn name(&self) -> String; } trait ActorAsAny { fn actor_as_any(&self) -> &Any; fn actor_as_any_mut(&mut self) -> &mut Any; } impl<T: Actor> ActorAsAny for T { fn actor_as_any(&self) -> &Any { self } fn actor_as_any_mut(&mut self) -> &mut Any { self } } /// A list of known, owned actors. pub struct
{ actors: HashMap<String, Box<Actor + Send>>, new_actors: RefCell<Vec<Box<Actor + Send>>>, old_actors: RefCell<Vec<String>>, script_actors: RefCell<HashMap<String, String>>, shareable: Option<Arc<Mutex<ActorRegistry>>>, next: Cell<u32>, start_stamp: PreciseTime, } impl ActorRegistry { /// Create an empty registry. pub fn new() -> ActorRegistry { ActorRegistry { actors: HashMap::new(), new_actors: RefCell::new(vec!()), old_actors: RefCell::new(vec!()), script_actors: RefCell::new(HashMap::new()), shareable: None, next: Cell::new(0), start_stamp: PreciseTime::now(), } } /// Creating shareable registry pub fn create_shareable(self) -> Arc<Mutex<ActorRegistry>> { if let Some(shareable) = self.shareable { return shareable; } let shareable = Arc::new(Mutex::new(self)); { let mut lock = shareable.lock(); let registry = lock.as_mut().unwrap(); registry.shareable = Some(shareable.clone()); } shareable } /// Get shareable registry through threads pub fn shareable(&self) -> Arc<Mutex<ActorRegistry>> { self.shareable.as_ref().unwrap().clone() } /// Get start stamp when registry was started pub fn start_stamp(&self) -> PreciseTime { self.start_stamp.clone() } pub fn register_script_actor(&self, script_id: String, actor: String) { println!("registering {} ({})", actor, script_id); let mut script_actors = self.script_actors.borrow_mut(); script_actors.insert(script_id, actor); } pub fn script_to_actor(&self, script_id: String) -> String { if script_id.is_empty() { return "".to_owned(); } self.script_actors.borrow().get(&script_id).unwrap().clone() } pub fn script_actor_registered(&self, script_id: String) -> bool { self.script_actors.borrow().contains_key(&script_id) } pub fn actor_to_script(&self, actor: String) -> String { for (key, value) in &*self.script_actors.borrow() { println!("checking {}", value); if *value == actor { return key.to_owned(); } } panic!("couldn't find actor named {}", actor) } /// Create a unique name based on a monotonically increasing suffix pub fn new_name(&self, prefix: &str) -> String { let suffix = self.next.get(); self.next.set(suffix + 1); format!("{}{}", prefix, suffix) } /// Add an actor to the registry of known actors that can receive messages. pub fn register(&mut self, actor: Box<Actor + Send>) { self.actors.insert(actor.name(), actor); } pub fn register_later(&self, actor: Box<Actor + Send>) { let mut actors = self.new_actors.borrow_mut(); actors.push(actor); } /// Find an actor by registered name pub fn find<'a, T: Any>(&'a self, name: &str) -> &'a T { let actor = self.actors.get(name).unwrap(); actor.actor_as_any().downcast_ref::<T>().unwrap() } /// Find an actor by registered name pub fn find_mut<'a, T: Any>(&'a mut self, name: &str) -> &'a mut T { let actor = self.actors.get_mut(name).unwrap(); actor.actor_as_any_mut().downcast_mut::<T>().unwrap() } /// Attempt to process a message as directed by its `to` property. If the actor is not /// found or does not indicate that it knew how to process the message, ignore the failure. pub fn handle_message(&mut self, msg: &json::Object, stream: &mut TcpStream) -> Result<(), ()> { let to = msg.get("to").unwrap().as_string().unwrap(); match self.actors.get(to) { None => println!("message received for unknown actor \"{}\"", to), Some(actor) => { let msg_type = msg.get("type").unwrap().as_string().unwrap(); if try!(actor.handle_message(self, msg_type, msg, stream)) != ActorMessageStatus::Processed { println!("unexpected message type \"{}\" found for actor \"{}\"", msg_type, to); } } } let new_actors = replace(&mut *self.new_actors.borrow_mut(), vec!()); for actor in new_actors.into_iter() { self.actors.insert(actor.name().to_owned(), actor); } let old_actors = replace(&mut *self.old_actors.borrow_mut(), vec!()); for name in old_actors { self.drop_actor(name); } Ok(()) } pub fn drop_actor(&mut self, name: String) { self.actors.remove(&name); } pub fn drop_actor_later(&self, name: String) { let mut actors = self.old_actors.borrow_mut(); actors.push(name); } }
ActorRegistry
identifier_name
actor.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/. */ /// General actor system infrastructure. use devtools_traits::PreciseTime; use rustc_serialize::json; use std::any::Any; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::mem::replace; use std::net::TcpStream; use std::sync::{Arc, Mutex}; #[derive(PartialEq)] pub enum ActorMessageStatus { Processed, Ignored, } /// A common trait for all devtools actors that encompasses an immutable name /// and the ability to process messages that are directed to particular actors. /// TODO: ensure the name is immutable pub trait Actor: Any + ActorAsAny { fn handle_message(&self, registry: &ActorRegistry, msg_type: &str, msg: &json::Object, stream: &mut TcpStream) -> Result<ActorMessageStatus, ()>; fn name(&self) -> String; } trait ActorAsAny { fn actor_as_any(&self) -> &Any; fn actor_as_any_mut(&mut self) -> &mut Any; } impl<T: Actor> ActorAsAny for T { fn actor_as_any(&self) -> &Any { self } fn actor_as_any_mut(&mut self) -> &mut Any { self } } /// A list of known, owned actors. pub struct ActorRegistry { actors: HashMap<String, Box<Actor + Send>>, new_actors: RefCell<Vec<Box<Actor + Send>>>, old_actors: RefCell<Vec<String>>, script_actors: RefCell<HashMap<String, String>>, shareable: Option<Arc<Mutex<ActorRegistry>>>, next: Cell<u32>, start_stamp: PreciseTime, } impl ActorRegistry { /// Create an empty registry. pub fn new() -> ActorRegistry { ActorRegistry { actors: HashMap::new(), new_actors: RefCell::new(vec!()), old_actors: RefCell::new(vec!()), script_actors: RefCell::new(HashMap::new()), shareable: None, next: Cell::new(0), start_stamp: PreciseTime::now(), } } /// Creating shareable registry pub fn create_shareable(self) -> Arc<Mutex<ActorRegistry>> { if let Some(shareable) = self.shareable { return shareable; } let shareable = Arc::new(Mutex::new(self)); { let mut lock = shareable.lock(); let registry = lock.as_mut().unwrap(); registry.shareable = Some(shareable.clone()); } shareable } /// Get shareable registry through threads pub fn shareable(&self) -> Arc<Mutex<ActorRegistry>> { self.shareable.as_ref().unwrap().clone() } /// Get start stamp when registry was started pub fn start_stamp(&self) -> PreciseTime { self.start_stamp.clone() } pub fn register_script_actor(&self, script_id: String, actor: String) { println!("registering {} ({})", actor, script_id); let mut script_actors = self.script_actors.borrow_mut(); script_actors.insert(script_id, actor); } pub fn script_to_actor(&self, script_id: String) -> String { if script_id.is_empty() { return "".to_owned(); } self.script_actors.borrow().get(&script_id).unwrap().clone() } pub fn script_actor_registered(&self, script_id: String) -> bool { self.script_actors.borrow().contains_key(&script_id) } pub fn actor_to_script(&self, actor: String) -> String { for (key, value) in &*self.script_actors.borrow() { println!("checking {}", value); if *value == actor { return key.to_owned(); } } panic!("couldn't find actor named {}", actor) } /// Create a unique name based on a monotonically increasing suffix pub fn new_name(&self, prefix: &str) -> String { let suffix = self.next.get(); self.next.set(suffix + 1); format!("{}{}", prefix, suffix) } /// Add an actor to the registry of known actors that can receive messages. pub fn register(&mut self, actor: Box<Actor + Send>) { self.actors.insert(actor.name(), actor); } pub fn register_later(&self, actor: Box<Actor + Send>) { let mut actors = self.new_actors.borrow_mut(); actors.push(actor); } /// Find an actor by registered name pub fn find<'a, T: Any>(&'a self, name: &str) -> &'a T { let actor = self.actors.get(name).unwrap(); actor.actor_as_any().downcast_ref::<T>().unwrap() } /// Find an actor by registered name pub fn find_mut<'a, T: Any>(&'a mut self, name: &str) -> &'a mut T { let actor = self.actors.get_mut(name).unwrap(); actor.actor_as_any_mut().downcast_mut::<T>().unwrap() } /// Attempt to process a message as directed by its `to` property. If the actor is not /// found or does not indicate that it knew how to process the message, ignore the failure. pub fn handle_message(&mut self, msg: &json::Object, stream: &mut TcpStream) -> Result<(), ()> { let to = msg.get("to").unwrap().as_string().unwrap(); match self.actors.get(to) { None => println!("message received for unknown actor \"{}\"", to), Some(actor) => { let msg_type = msg.get("type").unwrap().as_string().unwrap(); if try!(actor.handle_message(self, msg_type, msg, stream)) != ActorMessageStatus::Processed { println!("unexpected message type \"{}\" found for actor \"{}\"", msg_type, to); } } } let new_actors = replace(&mut *self.new_actors.borrow_mut(), vec!()); for actor in new_actors.into_iter() { self.actors.insert(actor.name().to_owned(), actor); } let old_actors = replace(&mut *self.old_actors.borrow_mut(), vec!()); for name in old_actors { self.drop_actor(name); } Ok(()) } pub fn drop_actor(&mut self, name: String)
pub fn drop_actor_later(&self, name: String) { let mut actors = self.old_actors.borrow_mut(); actors.push(name); } }
{ self.actors.remove(&name); }
identifier_body
pow.rs
use libtww::std::ops::Mul; use {One, CheckedMul}; /// Raises a value to the power of exp, using exponentiation by squaring. /// /// # Example /// /// ```rust /// use num_traits::pow; /// /// assert_eq!(pow(2i8, 4), 16); /// assert_eq!(pow(6u8, 3), 216); /// ``` #[inline] pub fn pow<T: Clone + One + Mul<T, Output = T>>(mut base: T, mut exp: usize) -> T { if exp == 0 { return T::one(); } while exp & 1 == 0 { base = base.clone() * base; exp >>= 1; } if exp == 1 { return base; } let mut acc = base.clone(); while exp > 1 { exp >>= 1; base = base.clone() * base; if exp & 1 == 1 { acc = acc * base.clone(); } } acc } /// Raises a value to the power of exp, returning `None` if an overflow occurred. /// /// Otherwise same as the `pow` function. /// /// # Example /// /// ```rust /// use num_traits::checked_pow; /// /// assert_eq!(checked_pow(2i8, 4), Some(16)); /// assert_eq!(checked_pow(7i8, 8), None); /// assert_eq!(checked_pow(7u32, 8), Some(5_764_801)); /// ``` #[inline] pub fn
<T: Clone + One + CheckedMul>(mut base: T, mut exp: usize) -> Option<T> { if exp == 0 { return Some(T::one()); } macro_rules! optry { ( $ expr : expr ) => { if let Some(val) = $expr { val } else { return None } } } while exp & 1 == 0 { base = optry!(base.checked_mul(&base)); exp >>= 1; } if exp == 1 { return Some(base); } let mut acc = base.clone(); while exp > 1 { exp >>= 1; base = optry!(base.checked_mul(&base)); if exp & 1 == 1 { acc = optry!(acc.checked_mul(&base)); } } Some(acc) }
checked_pow
identifier_name
pow.rs
use libtww::std::ops::Mul; use {One, CheckedMul}; /// Raises a value to the power of exp, using exponentiation by squaring. /// /// # Example /// /// ```rust /// use num_traits::pow; /// /// assert_eq!(pow(2i8, 4), 16); /// assert_eq!(pow(6u8, 3), 216); /// ``` #[inline] pub fn pow<T: Clone + One + Mul<T, Output = T>>(mut base: T, mut exp: usize) -> T { if exp == 0 { return T::one(); } while exp & 1 == 0 { base = base.clone() * base; exp >>= 1; } if exp == 1 { return base; } let mut acc = base.clone(); while exp > 1 { exp >>= 1; base = base.clone() * base; if exp & 1 == 1 { acc = acc * base.clone(); } } acc } /// Raises a value to the power of exp, returning `None` if an overflow occurred. /// /// Otherwise same as the `pow` function. /// /// # Example /// /// ```rust /// use num_traits::checked_pow; /// /// assert_eq!(checked_pow(2i8, 4), Some(16)); /// assert_eq!(checked_pow(7i8, 8), None); /// assert_eq!(checked_pow(7u32, 8), Some(5_764_801)); /// ``` #[inline] pub fn checked_pow<T: Clone + One + CheckedMul>(mut base: T, mut exp: usize) -> Option<T> { if exp == 0 { return Some(T::one()); } macro_rules! optry { ( $ expr : expr ) => { if let Some(val) = $expr { val } else { return None } } } while exp & 1 == 0 { base = optry!(base.checked_mul(&base)); exp >>= 1; } if exp == 1
let mut acc = base.clone(); while exp > 1 { exp >>= 1; base = optry!(base.checked_mul(&base)); if exp & 1 == 1 { acc = optry!(acc.checked_mul(&base)); } } Some(acc) }
{ return Some(base); }
conditional_block
pow.rs
use libtww::std::ops::Mul; use {One, CheckedMul}; /// Raises a value to the power of exp, using exponentiation by squaring. /// /// # Example /// /// ```rust /// use num_traits::pow; /// /// assert_eq!(pow(2i8, 4), 16); /// assert_eq!(pow(6u8, 3), 216); /// ``` #[inline] pub fn pow<T: Clone + One + Mul<T, Output = T>>(mut base: T, mut exp: usize) -> T { if exp == 0 { return T::one(); } while exp & 1 == 0 { base = base.clone() * base; exp >>= 1; } if exp == 1 { return base; } let mut acc = base.clone(); while exp > 1 { exp >>= 1; base = base.clone() * base; if exp & 1 == 1 { acc = acc * base.clone(); } } acc } /// Raises a value to the power of exp, returning `None` if an overflow occurred. /// /// Otherwise same as the `pow` function. /// /// # Example /// /// ```rust /// use num_traits::checked_pow; /// /// assert_eq!(checked_pow(2i8, 4), Some(16)); /// assert_eq!(checked_pow(7i8, 8), None); /// assert_eq!(checked_pow(7u32, 8), Some(5_764_801)); /// ``` #[inline] pub fn checked_pow<T: Clone + One + CheckedMul>(mut base: T, mut exp: usize) -> Option<T> { if exp == 0 { return Some(T::one()); } macro_rules! optry { ( $ expr : expr ) => { if let Some(val) = $expr { val } else { return None } } } while exp & 1 == 0 { base = optry!(base.checked_mul(&base)); exp >>= 1; } if exp == 1 { return Some(base); } let mut acc = base.clone(); while exp > 1 { exp >>= 1; base = optry!(base.checked_mul(&base)); if exp & 1 == 1 { acc = optry!(acc.checked_mul(&base)); } }
}
Some(acc)
random_line_split
pow.rs
use libtww::std::ops::Mul; use {One, CheckedMul}; /// Raises a value to the power of exp, using exponentiation by squaring. /// /// # Example /// /// ```rust /// use num_traits::pow; /// /// assert_eq!(pow(2i8, 4), 16); /// assert_eq!(pow(6u8, 3), 216); /// ``` #[inline] pub fn pow<T: Clone + One + Mul<T, Output = T>>(mut base: T, mut exp: usize) -> T { if exp == 0 { return T::one(); } while exp & 1 == 0 { base = base.clone() * base; exp >>= 1; } if exp == 1 { return base; } let mut acc = base.clone(); while exp > 1 { exp >>= 1; base = base.clone() * base; if exp & 1 == 1 { acc = acc * base.clone(); } } acc } /// Raises a value to the power of exp, returning `None` if an overflow occurred. /// /// Otherwise same as the `pow` function. /// /// # Example /// /// ```rust /// use num_traits::checked_pow; /// /// assert_eq!(checked_pow(2i8, 4), Some(16)); /// assert_eq!(checked_pow(7i8, 8), None); /// assert_eq!(checked_pow(7u32, 8), Some(5_764_801)); /// ``` #[inline] pub fn checked_pow<T: Clone + One + CheckedMul>(mut base: T, mut exp: usize) -> Option<T>
while exp > 1 { exp >>= 1; base = optry!(base.checked_mul(&base)); if exp & 1 == 1 { acc = optry!(acc.checked_mul(&base)); } } Some(acc) }
{ if exp == 0 { return Some(T::one()); } macro_rules! optry { ( $ expr : expr ) => { if let Some(val) = $expr { val } else { return None } } } while exp & 1 == 0 { base = optry!(base.checked_mul(&base)); exp >>= 1; } if exp == 1 { return Some(base); } let mut acc = base.clone();
identifier_body
verify.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(globs, phase, macro_rules)] extern crate syntax; extern crate rustc; #[phase(link)] extern crate regex; #[phase(link, plugin)] extern crate log; #[phase(plugin)] extern crate regex_macros; use std::collections::HashMap; use std::io::File; use syntax::parse; use syntax::parse::lexer; use rustc::driver::{session, config}; use syntax::ast; use syntax::ast::Name; use syntax::parse::token::*; use syntax::parse::lexer::TokenAndSpan; fn parse_token_list(file: &str) -> HashMap<String, Token> { fn id() -> Token { IDENT(ast::Ident { name: Name(0), ctxt: 0, }, false) } let mut res = HashMap::new(); res.insert("-1".to_string(), EOF); for line in file.split('\n') { let eq = match line.trim().rfind('=') { Some(val) => val, None => continue }; let val = line.slice_to(eq); let num = line.slice_from(eq + 1); let tok = match val { "SHR" => BINOP(SHR), "DOLLAR" => DOLLAR, "LT" => LT, "STAR" => BINOP(STAR), "FLOAT_SUFFIX" => id(), "INT_SUFFIX" => id(), "SHL" => BINOP(SHL), "LBRACE" => LBRACE, "RARROW" => RARROW, "LIT_STR" => LIT_STR(Name(0)), "DOTDOT" => DOTDOT, "MOD_SEP" => MOD_SEP, "DOTDOTDOT" => DOTDOTDOT, "NOT" => NOT, "AND" => BINOP(AND), "LPAREN" => LPAREN, "ANDAND" => ANDAND, "AT" => AT, "LBRACKET" => LBRACKET, "LIT_STR_RAW" => LIT_STR_RAW(Name(0), 0), "RPAREN" => RPAREN, "SLASH" => BINOP(SLASH), "COMMA" => COMMA, "LIFETIME" => LIFETIME(ast::Ident { name: Name(0), ctxt: 0 }), "CARET" => BINOP(CARET), "TILDE" => TILDE, "IDENT" => id(), "PLUS" => BINOP(PLUS), "LIT_CHAR" => LIT_CHAR(Name(0)), "LIT_BYTE" => LIT_BYTE(Name(0)), "EQ" => EQ, "RBRACKET" => RBRACKET, "COMMENT" => COMMENT, "DOC_COMMENT" => DOC_COMMENT(Name(0)), "DOT" => DOT, "EQEQ" => EQEQ, "NE" => NE, "GE" => GE, "PERCENT" => BINOP(PERCENT), "RBRACE" => RBRACE, "BINOP" => BINOP(PLUS), "POUND" => POUND, "OROR" => OROR, "LIT_INTEGER" => LIT_INTEGER(Name(0)), "BINOPEQ" => BINOPEQ(PLUS), "LIT_FLOAT" => LIT_FLOAT(Name(0)), "WHITESPACE" => WS, "UNDERSCORE" => UNDERSCORE, "MINUS" => BINOP(MINUS), "SEMI" => SEMI, "COLON" => COLON, "FAT_ARROW" => FAT_ARROW, "OR" => BINOP(OR), "GT" => GT, "LE" => LE, "LIT_BINARY" => LIT_BINARY(Name(0)), "LIT_BINARY_RAW" => LIT_BINARY_RAW(Name(0), 0), _ => continue }; res.insert(num.to_string(), tok); } debug!("Token map: {}", res); res } fn str_to_binop(s: &str) -> BinOp { match s { "+" => PLUS, "/" => SLASH, "-" => MINUS, "*" => STAR, "%" => PERCENT, "^" => CARET, "&" => AND, "|" => OR, "<<" => SHL, ">>" => SHR, _ => fail!("Bad binop str `{}`", s) } } /// Assuming a string/binary literal, strip out the leading/trailing /// hashes and surrounding quotes/raw/binary prefix. fn fix(mut lit: &str) -> ast::Name { if lit.char_at(0) == 'r' { if lit.char_at(1) == 'b' { lit = lit.slice_from(2) } else { lit = lit.slice_from(1); } } else if lit.char_at(0) == 'b' { lit = lit.slice_from(1); } let leading_hashes = count(lit); // +1/-1 to adjust for single quotes parse::token::intern(lit.slice(leading_hashes + 1, lit.len() - leading_hashes - 1)) } /// Assuming a char/byte literal, strip the 'b' prefix and the single quotes. fn fixchar(mut lit: &str) -> ast::Name { if lit.char_at(0) == 'b' { lit = lit.slice_from(1); } parse::token::intern(lit.slice(1, lit.len() - 1)) } fn count(lit: &str) -> uint { lit.chars().take_while(|c| *c == '#').count() } fn parse_antlr_token(s: &str, tokens: &HashMap<String, Token>) -> TokenAndSpan { let re = regex!( r"\[@(?P<seq>\d+),(?P<start>\d+):(?P<end>\d+)='(?P<content>.+?)',<(?P<toknum>-?\d+)>,\d+:\d+]" ); let m = re.captures(s).expect(format!("The regex didn't match {}", s).as_slice()); let start = m.name("start"); let end = m.name("end"); let toknum = m.name("toknum"); let content = m.name("content"); let proto_tok = tokens.find_equiv(&toknum).expect(format!("didn't find token {} in the map", toknum).as_slice()); let nm = parse::token::intern(content); debug!("What we got: content (`{}`), proto: {}", content, proto_tok); let real_tok = match *proto_tok { BINOP(..) => BINOP(str_to_binop(content)), BINOPEQ(..) => BINOPEQ(str_to_binop(content.slice_to(content.len() - 1))), LIT_STR(..) => LIT_STR(fix(content)), LIT_STR_RAW(..) => LIT_STR_RAW(fix(content), count(content)), LIT_CHAR(..) => LIT_CHAR(fixchar(content)), LIT_BYTE(..) => LIT_BYTE(fixchar(content)), DOC_COMMENT(..) => DOC_COMMENT(nm), LIT_INTEGER(..) => LIT_INTEGER(nm), LIT_FLOAT(..) => LIT_FLOAT(nm), LIT_BINARY(..) => LIT_BINARY(nm), LIT_BINARY_RAW(..) => LIT_BINARY_RAW(fix(content), count(content)), IDENT(..) => IDENT(ast::Ident { name: nm, ctxt: 0 }, true), LIFETIME(..) => LIFETIME(ast::Ident { name: nm, ctxt: 0 }), ref t => t.clone() }; let offset = if real_tok == EOF { 1 } else { 0 }; let sp = syntax::codemap::Span { lo: syntax::codemap::BytePos(from_str::<u32>(start).unwrap() - offset), hi: syntax::codemap::BytePos(from_str::<u32>(end).unwrap() + 1), expn_info: None }; TokenAndSpan { tok: real_tok, sp: sp } } fn tok_cmp(a: &Token, b: &Token) -> bool
fn main() { fn next(r: &mut lexer::StringReader) -> TokenAndSpan { use syntax::parse::lexer::Reader; r.next_token() } let args = std::os::args(); let mut token_file = File::open(&Path::new(args.get(2).as_slice())); let token_map = parse_token_list(token_file.read_to_string().unwrap().as_slice()); let mut stdin = std::io::stdin(); let mut antlr_tokens = stdin.lines().map(|l| parse_antlr_token(l.unwrap().as_slice().trim(), &token_map)); let code = File::open(&Path::new(args.get(1).as_slice())).unwrap().read_to_string().unwrap(); let options = config::basic_options(); let session = session::build_session(options, None, syntax::diagnostics::registry::Registry::new([])); let filemap = parse::string_to_filemap(&session.parse_sess, code, String::from_str("<n/a>")); let mut lexer = lexer::StringReader::new(session.diagnostic(), filemap); for antlr_tok in antlr_tokens { let rustc_tok = next(&mut lexer); if rustc_tok.tok == EOF && antlr_tok.tok == EOF { continue } assert!(rustc_tok.sp == antlr_tok.sp, "{} and {} have different spans", rustc_tok, antlr_tok); macro_rules! matches ( ( $($x:pat),+ ) => ( match rustc_tok.tok { $($x => match antlr_tok.tok { $x => { if!tok_cmp(&rustc_tok.tok, &antlr_tok.tok) { // FIXME #15677: needs more robust escaping in // antlr warn!("Different names for {} and {}", rustc_tok, antlr_tok); } } _ => fail!("{} is not {}", antlr_tok, rustc_tok) },)* ref c => assert!(c == &antlr_tok.tok, "{} is not {}", rustc_tok, antlr_tok) } ) ) matches!(LIT_BYTE(..), LIT_CHAR(..), LIT_INTEGER(..), LIT_FLOAT(..), LIT_STR(..), LIT_STR_RAW(..), LIT_BINARY(..), LIT_BINARY_RAW(..), IDENT(..), LIFETIME(..), INTERPOLATED(..), DOC_COMMENT(..), SHEBANG(..) ); } }
{ match a { &IDENT(id, _) => match b { &IDENT(id2, _) => id == id2, _ => false }, _ => a == b } }
identifier_body
verify.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(globs, phase, macro_rules)] extern crate syntax; extern crate rustc; #[phase(link)] extern crate regex; #[phase(link, plugin)] extern crate log; #[phase(plugin)] extern crate regex_macros; use std::collections::HashMap; use std::io::File; use syntax::parse; use syntax::parse::lexer; use rustc::driver::{session, config}; use syntax::ast; use syntax::ast::Name; use syntax::parse::token::*; use syntax::parse::lexer::TokenAndSpan; fn parse_token_list(file: &str) -> HashMap<String, Token> { fn id() -> Token { IDENT(ast::Ident { name: Name(0), ctxt: 0, }, false) } let mut res = HashMap::new(); res.insert("-1".to_string(), EOF); for line in file.split('\n') { let eq = match line.trim().rfind('=') { Some(val) => val, None => continue }; let val = line.slice_to(eq); let num = line.slice_from(eq + 1); let tok = match val { "SHR" => BINOP(SHR), "DOLLAR" => DOLLAR, "LT" => LT, "STAR" => BINOP(STAR), "FLOAT_SUFFIX" => id(), "INT_SUFFIX" => id(), "SHL" => BINOP(SHL), "LBRACE" => LBRACE, "RARROW" => RARROW, "LIT_STR" => LIT_STR(Name(0)), "DOTDOT" => DOTDOT, "MOD_SEP" => MOD_SEP, "DOTDOTDOT" => DOTDOTDOT, "NOT" => NOT, "AND" => BINOP(AND), "LPAREN" => LPAREN, "ANDAND" => ANDAND, "AT" => AT, "LBRACKET" => LBRACKET, "LIT_STR_RAW" => LIT_STR_RAW(Name(0), 0), "RPAREN" => RPAREN, "SLASH" => BINOP(SLASH), "COMMA" => COMMA, "LIFETIME" => LIFETIME(ast::Ident { name: Name(0), ctxt: 0 }), "CARET" => BINOP(CARET), "TILDE" => TILDE, "IDENT" => id(), "PLUS" => BINOP(PLUS), "LIT_CHAR" => LIT_CHAR(Name(0)), "LIT_BYTE" => LIT_BYTE(Name(0)), "EQ" => EQ, "RBRACKET" => RBRACKET, "COMMENT" => COMMENT, "DOC_COMMENT" => DOC_COMMENT(Name(0)), "DOT" => DOT, "EQEQ" => EQEQ, "NE" => NE, "GE" => GE, "PERCENT" => BINOP(PERCENT), "RBRACE" => RBRACE, "BINOP" => BINOP(PLUS), "POUND" => POUND, "OROR" => OROR, "LIT_INTEGER" => LIT_INTEGER(Name(0)), "BINOPEQ" => BINOPEQ(PLUS), "LIT_FLOAT" => LIT_FLOAT(Name(0)), "WHITESPACE" => WS, "UNDERSCORE" => UNDERSCORE, "MINUS" => BINOP(MINUS), "SEMI" => SEMI, "COLON" => COLON, "FAT_ARROW" => FAT_ARROW, "OR" => BINOP(OR), "GT" => GT, "LE" => LE, "LIT_BINARY" => LIT_BINARY(Name(0)), "LIT_BINARY_RAW" => LIT_BINARY_RAW(Name(0), 0), _ => continue }; res.insert(num.to_string(), tok); } debug!("Token map: {}", res); res } fn str_to_binop(s: &str) -> BinOp { match s { "+" => PLUS, "/" => SLASH, "-" => MINUS, "*" => STAR, "%" => PERCENT, "^" => CARET, "&" => AND, "|" => OR, "<<" => SHL, ">>" => SHR, _ => fail!("Bad binop str `{}`", s) } } /// Assuming a string/binary literal, strip out the leading/trailing /// hashes and surrounding quotes/raw/binary prefix. fn fix(mut lit: &str) -> ast::Name { if lit.char_at(0) == 'r' { if lit.char_at(1) == 'b' { lit = lit.slice_from(2) } else { lit = lit.slice_from(1); } } else if lit.char_at(0) == 'b' { lit = lit.slice_from(1); } let leading_hashes = count(lit); // +1/-1 to adjust for single quotes parse::token::intern(lit.slice(leading_hashes + 1, lit.len() - leading_hashes - 1)) } /// Assuming a char/byte literal, strip the 'b' prefix and the single quotes. fn fixchar(mut lit: &str) -> ast::Name { if lit.char_at(0) == 'b' { lit = lit.slice_from(1); } parse::token::intern(lit.slice(1, lit.len() - 1)) } fn count(lit: &str) -> uint { lit.chars().take_while(|c| *c == '#').count() } fn parse_antlr_token(s: &str, tokens: &HashMap<String, Token>) -> TokenAndSpan { let re = regex!( r"\[@(?P<seq>\d+),(?P<start>\d+):(?P<end>\d+)='(?P<content>.+?)',<(?P<toknum>-?\d+)>,\d+:\d+]" ); let m = re.captures(s).expect(format!("The regex didn't match {}", s).as_slice()); let start = m.name("start"); let end = m.name("end"); let toknum = m.name("toknum"); let content = m.name("content");
debug!("What we got: content (`{}`), proto: {}", content, proto_tok); let real_tok = match *proto_tok { BINOP(..) => BINOP(str_to_binop(content)), BINOPEQ(..) => BINOPEQ(str_to_binop(content.slice_to(content.len() - 1))), LIT_STR(..) => LIT_STR(fix(content)), LIT_STR_RAW(..) => LIT_STR_RAW(fix(content), count(content)), LIT_CHAR(..) => LIT_CHAR(fixchar(content)), LIT_BYTE(..) => LIT_BYTE(fixchar(content)), DOC_COMMENT(..) => DOC_COMMENT(nm), LIT_INTEGER(..) => LIT_INTEGER(nm), LIT_FLOAT(..) => LIT_FLOAT(nm), LIT_BINARY(..) => LIT_BINARY(nm), LIT_BINARY_RAW(..) => LIT_BINARY_RAW(fix(content), count(content)), IDENT(..) => IDENT(ast::Ident { name: nm, ctxt: 0 }, true), LIFETIME(..) => LIFETIME(ast::Ident { name: nm, ctxt: 0 }), ref t => t.clone() }; let offset = if real_tok == EOF { 1 } else { 0 }; let sp = syntax::codemap::Span { lo: syntax::codemap::BytePos(from_str::<u32>(start).unwrap() - offset), hi: syntax::codemap::BytePos(from_str::<u32>(end).unwrap() + 1), expn_info: None }; TokenAndSpan { tok: real_tok, sp: sp } } fn tok_cmp(a: &Token, b: &Token) -> bool { match a { &IDENT(id, _) => match b { &IDENT(id2, _) => id == id2, _ => false }, _ => a == b } } fn main() { fn next(r: &mut lexer::StringReader) -> TokenAndSpan { use syntax::parse::lexer::Reader; r.next_token() } let args = std::os::args(); let mut token_file = File::open(&Path::new(args.get(2).as_slice())); let token_map = parse_token_list(token_file.read_to_string().unwrap().as_slice()); let mut stdin = std::io::stdin(); let mut antlr_tokens = stdin.lines().map(|l| parse_antlr_token(l.unwrap().as_slice().trim(), &token_map)); let code = File::open(&Path::new(args.get(1).as_slice())).unwrap().read_to_string().unwrap(); let options = config::basic_options(); let session = session::build_session(options, None, syntax::diagnostics::registry::Registry::new([])); let filemap = parse::string_to_filemap(&session.parse_sess, code, String::from_str("<n/a>")); let mut lexer = lexer::StringReader::new(session.diagnostic(), filemap); for antlr_tok in antlr_tokens { let rustc_tok = next(&mut lexer); if rustc_tok.tok == EOF && antlr_tok.tok == EOF { continue } assert!(rustc_tok.sp == antlr_tok.sp, "{} and {} have different spans", rustc_tok, antlr_tok); macro_rules! matches ( ( $($x:pat),+ ) => ( match rustc_tok.tok { $($x => match antlr_tok.tok { $x => { if!tok_cmp(&rustc_tok.tok, &antlr_tok.tok) { // FIXME #15677: needs more robust escaping in // antlr warn!("Different names for {} and {}", rustc_tok, antlr_tok); } } _ => fail!("{} is not {}", antlr_tok, rustc_tok) },)* ref c => assert!(c == &antlr_tok.tok, "{} is not {}", rustc_tok, antlr_tok) } ) ) matches!(LIT_BYTE(..), LIT_CHAR(..), LIT_INTEGER(..), LIT_FLOAT(..), LIT_STR(..), LIT_STR_RAW(..), LIT_BINARY(..), LIT_BINARY_RAW(..), IDENT(..), LIFETIME(..), INTERPOLATED(..), DOC_COMMENT(..), SHEBANG(..) ); } }
let proto_tok = tokens.find_equiv(&toknum).expect(format!("didn't find token {} in the map", toknum).as_slice()); let nm = parse::token::intern(content);
random_line_split
verify.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(globs, phase, macro_rules)] extern crate syntax; extern crate rustc; #[phase(link)] extern crate regex; #[phase(link, plugin)] extern crate log; #[phase(plugin)] extern crate regex_macros; use std::collections::HashMap; use std::io::File; use syntax::parse; use syntax::parse::lexer; use rustc::driver::{session, config}; use syntax::ast; use syntax::ast::Name; use syntax::parse::token::*; use syntax::parse::lexer::TokenAndSpan; fn parse_token_list(file: &str) -> HashMap<String, Token> { fn id() -> Token { IDENT(ast::Ident { name: Name(0), ctxt: 0, }, false) } let mut res = HashMap::new(); res.insert("-1".to_string(), EOF); for line in file.split('\n') { let eq = match line.trim().rfind('=') { Some(val) => val, None => continue }; let val = line.slice_to(eq); let num = line.slice_from(eq + 1); let tok = match val { "SHR" => BINOP(SHR), "DOLLAR" => DOLLAR, "LT" => LT, "STAR" => BINOP(STAR), "FLOAT_SUFFIX" => id(), "INT_SUFFIX" => id(), "SHL" => BINOP(SHL), "LBRACE" => LBRACE, "RARROW" => RARROW, "LIT_STR" => LIT_STR(Name(0)), "DOTDOT" => DOTDOT, "MOD_SEP" => MOD_SEP, "DOTDOTDOT" => DOTDOTDOT, "NOT" => NOT, "AND" => BINOP(AND), "LPAREN" => LPAREN, "ANDAND" => ANDAND, "AT" => AT, "LBRACKET" => LBRACKET, "LIT_STR_RAW" => LIT_STR_RAW(Name(0), 0), "RPAREN" => RPAREN, "SLASH" => BINOP(SLASH), "COMMA" => COMMA, "LIFETIME" => LIFETIME(ast::Ident { name: Name(0), ctxt: 0 }), "CARET" => BINOP(CARET), "TILDE" => TILDE, "IDENT" => id(), "PLUS" => BINOP(PLUS), "LIT_CHAR" => LIT_CHAR(Name(0)), "LIT_BYTE" => LIT_BYTE(Name(0)), "EQ" => EQ, "RBRACKET" => RBRACKET, "COMMENT" => COMMENT, "DOC_COMMENT" => DOC_COMMENT(Name(0)), "DOT" => DOT, "EQEQ" => EQEQ, "NE" => NE, "GE" => GE, "PERCENT" => BINOP(PERCENT), "RBRACE" => RBRACE, "BINOP" => BINOP(PLUS), "POUND" => POUND, "OROR" => OROR, "LIT_INTEGER" => LIT_INTEGER(Name(0)), "BINOPEQ" => BINOPEQ(PLUS), "LIT_FLOAT" => LIT_FLOAT(Name(0)), "WHITESPACE" => WS, "UNDERSCORE" => UNDERSCORE, "MINUS" => BINOP(MINUS), "SEMI" => SEMI, "COLON" => COLON, "FAT_ARROW" => FAT_ARROW, "OR" => BINOP(OR), "GT" => GT, "LE" => LE, "LIT_BINARY" => LIT_BINARY(Name(0)), "LIT_BINARY_RAW" => LIT_BINARY_RAW(Name(0), 0), _ => continue }; res.insert(num.to_string(), tok); } debug!("Token map: {}", res); res } fn str_to_binop(s: &str) -> BinOp { match s { "+" => PLUS, "/" => SLASH, "-" => MINUS, "*" => STAR, "%" => PERCENT, "^" => CARET, "&" => AND, "|" => OR, "<<" => SHL, ">>" => SHR, _ => fail!("Bad binop str `{}`", s) } } /// Assuming a string/binary literal, strip out the leading/trailing /// hashes and surrounding quotes/raw/binary prefix. fn fix(mut lit: &str) -> ast::Name { if lit.char_at(0) == 'r' { if lit.char_at(1) == 'b' { lit = lit.slice_from(2) } else { lit = lit.slice_from(1); } } else if lit.char_at(0) == 'b' { lit = lit.slice_from(1); } let leading_hashes = count(lit); // +1/-1 to adjust for single quotes parse::token::intern(lit.slice(leading_hashes + 1, lit.len() - leading_hashes - 1)) } /// Assuming a char/byte literal, strip the 'b' prefix and the single quotes. fn fixchar(mut lit: &str) -> ast::Name { if lit.char_at(0) == 'b' { lit = lit.slice_from(1); } parse::token::intern(lit.slice(1, lit.len() - 1)) } fn count(lit: &str) -> uint { lit.chars().take_while(|c| *c == '#').count() } fn parse_antlr_token(s: &str, tokens: &HashMap<String, Token>) -> TokenAndSpan { let re = regex!( r"\[@(?P<seq>\d+),(?P<start>\d+):(?P<end>\d+)='(?P<content>.+?)',<(?P<toknum>-?\d+)>,\d+:\d+]" ); let m = re.captures(s).expect(format!("The regex didn't match {}", s).as_slice()); let start = m.name("start"); let end = m.name("end"); let toknum = m.name("toknum"); let content = m.name("content"); let proto_tok = tokens.find_equiv(&toknum).expect(format!("didn't find token {} in the map", toknum).as_slice()); let nm = parse::token::intern(content); debug!("What we got: content (`{}`), proto: {}", content, proto_tok); let real_tok = match *proto_tok { BINOP(..) => BINOP(str_to_binop(content)), BINOPEQ(..) => BINOPEQ(str_to_binop(content.slice_to(content.len() - 1))), LIT_STR(..) => LIT_STR(fix(content)), LIT_STR_RAW(..) => LIT_STR_RAW(fix(content), count(content)), LIT_CHAR(..) => LIT_CHAR(fixchar(content)), LIT_BYTE(..) => LIT_BYTE(fixchar(content)), DOC_COMMENT(..) => DOC_COMMENT(nm), LIT_INTEGER(..) => LIT_INTEGER(nm), LIT_FLOAT(..) => LIT_FLOAT(nm), LIT_BINARY(..) => LIT_BINARY(nm), LIT_BINARY_RAW(..) => LIT_BINARY_RAW(fix(content), count(content)), IDENT(..) => IDENT(ast::Ident { name: nm, ctxt: 0 }, true), LIFETIME(..) => LIFETIME(ast::Ident { name: nm, ctxt: 0 }), ref t => t.clone() }; let offset = if real_tok == EOF { 1 } else { 0 }; let sp = syntax::codemap::Span { lo: syntax::codemap::BytePos(from_str::<u32>(start).unwrap() - offset), hi: syntax::codemap::BytePos(from_str::<u32>(end).unwrap() + 1), expn_info: None }; TokenAndSpan { tok: real_tok, sp: sp } } fn
(a: &Token, b: &Token) -> bool { match a { &IDENT(id, _) => match b { &IDENT(id2, _) => id == id2, _ => false }, _ => a == b } } fn main() { fn next(r: &mut lexer::StringReader) -> TokenAndSpan { use syntax::parse::lexer::Reader; r.next_token() } let args = std::os::args(); let mut token_file = File::open(&Path::new(args.get(2).as_slice())); let token_map = parse_token_list(token_file.read_to_string().unwrap().as_slice()); let mut stdin = std::io::stdin(); let mut antlr_tokens = stdin.lines().map(|l| parse_antlr_token(l.unwrap().as_slice().trim(), &token_map)); let code = File::open(&Path::new(args.get(1).as_slice())).unwrap().read_to_string().unwrap(); let options = config::basic_options(); let session = session::build_session(options, None, syntax::diagnostics::registry::Registry::new([])); let filemap = parse::string_to_filemap(&session.parse_sess, code, String::from_str("<n/a>")); let mut lexer = lexer::StringReader::new(session.diagnostic(), filemap); for antlr_tok in antlr_tokens { let rustc_tok = next(&mut lexer); if rustc_tok.tok == EOF && antlr_tok.tok == EOF { continue } assert!(rustc_tok.sp == antlr_tok.sp, "{} and {} have different spans", rustc_tok, antlr_tok); macro_rules! matches ( ( $($x:pat),+ ) => ( match rustc_tok.tok { $($x => match antlr_tok.tok { $x => { if!tok_cmp(&rustc_tok.tok, &antlr_tok.tok) { // FIXME #15677: needs more robust escaping in // antlr warn!("Different names for {} and {}", rustc_tok, antlr_tok); } } _ => fail!("{} is not {}", antlr_tok, rustc_tok) },)* ref c => assert!(c == &antlr_tok.tok, "{} is not {}", rustc_tok, antlr_tok) } ) ) matches!(LIT_BYTE(..), LIT_CHAR(..), LIT_INTEGER(..), LIT_FLOAT(..), LIT_STR(..), LIT_STR_RAW(..), LIT_BINARY(..), LIT_BINARY_RAW(..), IDENT(..), LIFETIME(..), INTERPOLATED(..), DOC_COMMENT(..), SHEBANG(..) ); } }
tok_cmp
identifier_name
sparse.rs
use std::fmt; use std::ops::Deref; use std::slice; /// A sparse set used for representing ordered NFA states. /// /// This supports constant time addition and membership testing. Clearing an /// entire set can also be done in constant time. Iteration yields elements /// in the order in which they were inserted. /// /// The data structure is based on: https://research.swtch.com/sparse /// Note though that we don't actually use uninitialized memory. We generally /// reuse allocations, so the initial allocation cost is bareable. However, /// its other properties listed above are extremely useful. #[derive(Clone)] pub struct SparseSet { /// Dense contains the instruction pointers in the order in which they /// were inserted. dense: Vec<usize>, /// Sparse maps instruction pointers to their location in dense. /// /// An instruction pointer is in the set if and only if /// sparse[ip] < dense.len() && ip == dense[sparse[ip]]. sparse: Box<[usize]>, } impl SparseSet { pub fn new(size: usize) -> SparseSet { SparseSet { dense: Vec::with_capacity(size), sparse: vec![0; size].into_boxed_slice(), } } pub fn len(&self) -> usize { self.dense.len() } pub fn is_empty(&self) -> bool { self.dense.is_empty() } pub fn capacity(&self) -> usize { self.dense.capacity() } pub fn insert(&mut self, value: usize) { let i = self.len(); assert!(i < self.capacity()); self.dense.push(value); self.sparse[value] = i; } pub fn contains(&self, value: usize) -> bool { let i = self.sparse[value]; self.dense.get(i) == Some(&value) } pub fn clear(&mut self)
} impl fmt::Debug for SparseSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "SparseSet({:?})", self.dense) } } impl Deref for SparseSet { type Target = [usize]; fn deref(&self) -> &Self::Target { &self.dense } } impl<'a> IntoIterator for &'a SparseSet { type Item = &'a usize; type IntoIter = slice::Iter<'a, usize>; fn into_iter(self) -> Self::IntoIter { self.iter() } }
{ self.dense.clear(); }
identifier_body
sparse.rs
use std::fmt; use std::ops::Deref; use std::slice; /// A sparse set used for representing ordered NFA states. /// /// This supports constant time addition and membership testing. Clearing an /// entire set can also be done in constant time. Iteration yields elements /// in the order in which they were inserted. /// /// The data structure is based on: https://research.swtch.com/sparse /// Note though that we don't actually use uninitialized memory. We generally /// reuse allocations, so the initial allocation cost is bareable. However, /// its other properties listed above are extremely useful. #[derive(Clone)] pub struct SparseSet { /// Dense contains the instruction pointers in the order in which they /// were inserted. dense: Vec<usize>, /// Sparse maps instruction pointers to their location in dense. /// /// An instruction pointer is in the set if and only if /// sparse[ip] < dense.len() && ip == dense[sparse[ip]]. sparse: Box<[usize]>, } impl SparseSet { pub fn new(size: usize) -> SparseSet {
sparse: vec![0; size].into_boxed_slice(), } } pub fn len(&self) -> usize { self.dense.len() } pub fn is_empty(&self) -> bool { self.dense.is_empty() } pub fn capacity(&self) -> usize { self.dense.capacity() } pub fn insert(&mut self, value: usize) { let i = self.len(); assert!(i < self.capacity()); self.dense.push(value); self.sparse[value] = i; } pub fn contains(&self, value: usize) -> bool { let i = self.sparse[value]; self.dense.get(i) == Some(&value) } pub fn clear(&mut self) { self.dense.clear(); } } impl fmt::Debug for SparseSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "SparseSet({:?})", self.dense) } } impl Deref for SparseSet { type Target = [usize]; fn deref(&self) -> &Self::Target { &self.dense } } impl<'a> IntoIterator for &'a SparseSet { type Item = &'a usize; type IntoIter = slice::Iter<'a, usize>; fn into_iter(self) -> Self::IntoIter { self.iter() } }
SparseSet { dense: Vec::with_capacity(size),
random_line_split
sparse.rs
use std::fmt; use std::ops::Deref; use std::slice; /// A sparse set used for representing ordered NFA states. /// /// This supports constant time addition and membership testing. Clearing an /// entire set can also be done in constant time. Iteration yields elements /// in the order in which they were inserted. /// /// The data structure is based on: https://research.swtch.com/sparse /// Note though that we don't actually use uninitialized memory. We generally /// reuse allocations, so the initial allocation cost is bareable. However, /// its other properties listed above are extremely useful. #[derive(Clone)] pub struct SparseSet { /// Dense contains the instruction pointers in the order in which they /// were inserted. dense: Vec<usize>, /// Sparse maps instruction pointers to their location in dense. /// /// An instruction pointer is in the set if and only if /// sparse[ip] < dense.len() && ip == dense[sparse[ip]]. sparse: Box<[usize]>, } impl SparseSet { pub fn new(size: usize) -> SparseSet { SparseSet { dense: Vec::with_capacity(size), sparse: vec![0; size].into_boxed_slice(), } } pub fn len(&self) -> usize { self.dense.len() } pub fn is_empty(&self) -> bool { self.dense.is_empty() } pub fn capacity(&self) -> usize { self.dense.capacity() } pub fn
(&mut self, value: usize) { let i = self.len(); assert!(i < self.capacity()); self.dense.push(value); self.sparse[value] = i; } pub fn contains(&self, value: usize) -> bool { let i = self.sparse[value]; self.dense.get(i) == Some(&value) } pub fn clear(&mut self) { self.dense.clear(); } } impl fmt::Debug for SparseSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "SparseSet({:?})", self.dense) } } impl Deref for SparseSet { type Target = [usize]; fn deref(&self) -> &Self::Target { &self.dense } } impl<'a> IntoIterator for &'a SparseSet { type Item = &'a usize; type IntoIter = slice::Iter<'a, usize>; fn into_iter(self) -> Self::IntoIter { self.iter() } }
insert
identifier_name
is_power_of_2.rs
use malachite_base::num::arithmetic::traits::IsPowerOf2; use Rational; impl IsPowerOf2 for Rational { /// Determines whether a `Rational` is an integer power of 2. /// /// # Worst-case complexity /// $T(n) = O(n)$ /// /// $M(n) = O(1)$ /// /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`. /// /// # Examples /// ``` /// extern crate malachite_base; /// extern crate malachite_q; /// /// use malachite_base::num::arithmetic::traits::IsPowerOf2; /// use malachite_q::Rational; /// /// assert_eq!(Rational::from(0x80).is_power_of_2(), true); /// assert_eq!(Rational::from_signeds(1, 8).is_power_of_2(), true); /// assert_eq!(Rational::from_signeds(-1, 8).is_power_of_2(), false); /// assert_eq!(Rational::from_signeds(22, 7).is_power_of_2(), false); /// ``` fn is_power_of_2(&self) -> bool
}
{ self.sign && (self.denominator == 1u32 && self.numerator.is_power_of_2() || self.numerator == 1u32 && self.denominator.is_power_of_2()) }
identifier_body
is_power_of_2.rs
use malachite_base::num::arithmetic::traits::IsPowerOf2; use Rational; impl IsPowerOf2 for Rational { /// Determines whether a `Rational` is an integer power of 2. /// /// # Worst-case complexity /// $T(n) = O(n)$ /// /// $M(n) = O(1)$ /// /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`. /// /// # Examples /// ``` /// extern crate malachite_base; /// extern crate malachite_q; /// /// use malachite_base::num::arithmetic::traits::IsPowerOf2; /// use malachite_q::Rational; /// /// assert_eq!(Rational::from(0x80).is_power_of_2(), true); /// assert_eq!(Rational::from_signeds(1, 8).is_power_of_2(), true); /// assert_eq!(Rational::from_signeds(-1, 8).is_power_of_2(), false); /// assert_eq!(Rational::from_signeds(22, 7).is_power_of_2(), false); /// ``` fn is_power_of_2(&self) -> bool { self.sign
&& (self.denominator == 1u32 && self.numerator.is_power_of_2() || self.numerator == 1u32 && self.denominator.is_power_of_2()) } }
random_line_split
is_power_of_2.rs
use malachite_base::num::arithmetic::traits::IsPowerOf2; use Rational; impl IsPowerOf2 for Rational { /// Determines whether a `Rational` is an integer power of 2. /// /// # Worst-case complexity /// $T(n) = O(n)$ /// /// $M(n) = O(1)$ /// /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`. /// /// # Examples /// ``` /// extern crate malachite_base; /// extern crate malachite_q; /// /// use malachite_base::num::arithmetic::traits::IsPowerOf2; /// use malachite_q::Rational; /// /// assert_eq!(Rational::from(0x80).is_power_of_2(), true); /// assert_eq!(Rational::from_signeds(1, 8).is_power_of_2(), true); /// assert_eq!(Rational::from_signeds(-1, 8).is_power_of_2(), false); /// assert_eq!(Rational::from_signeds(22, 7).is_power_of_2(), false); /// ``` fn
(&self) -> bool { self.sign && (self.denominator == 1u32 && self.numerator.is_power_of_2() || self.numerator == 1u32 && self.denominator.is_power_of_2()) } }
is_power_of_2
identifier_name
mimetype.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::MimeTypeBinding::MimeTypeMethods; use dom::bindings::js::Root; use dom::bindings::reflector::Reflector; use dom::bindings::str::DOMString; use dom::plugin::Plugin; use dom_struct::dom_struct; #[dom_struct] pub struct MimeType { reflector_: Reflector, } impl MimeTypeMethods for MimeType { // https://html.spec.whatwg.org/multipage/#dom-mimetype-type fn Type(&self) -> DOMString
// https://html.spec.whatwg.org/multipage/#dom-mimetype-description fn Description(&self) -> DOMString { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-mimetype-suffixes fn Suffixes(&self) -> DOMString { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-mimetype-enabledplugin fn EnabledPlugin(&self) -> Root<Plugin> { unreachable!() } }
{ unreachable!() }
identifier_body
mimetype.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::MimeTypeBinding::MimeTypeMethods; use dom::bindings::js::Root; use dom::bindings::reflector::Reflector; use dom::bindings::str::DOMString; use dom::plugin::Plugin; use dom_struct::dom_struct; #[dom_struct] pub struct MimeType { reflector_: Reflector, } impl MimeTypeMethods for MimeType { // https://html.spec.whatwg.org/multipage/#dom-mimetype-type fn Type(&self) -> DOMString { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-mimetype-description fn Description(&self) -> DOMString { unreachable!()
fn Suffixes(&self) -> DOMString { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-mimetype-enabledplugin fn EnabledPlugin(&self) -> Root<Plugin> { unreachable!() } }
} // https://html.spec.whatwg.org/multipage/#dom-mimetype-suffixes
random_line_split
mimetype.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::MimeTypeBinding::MimeTypeMethods; use dom::bindings::js::Root; use dom::bindings::reflector::Reflector; use dom::bindings::str::DOMString; use dom::plugin::Plugin; use dom_struct::dom_struct; #[dom_struct] pub struct
{ reflector_: Reflector, } impl MimeTypeMethods for MimeType { // https://html.spec.whatwg.org/multipage/#dom-mimetype-type fn Type(&self) -> DOMString { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-mimetype-description fn Description(&self) -> DOMString { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-mimetype-suffixes fn Suffixes(&self) -> DOMString { unreachable!() } // https://html.spec.whatwg.org/multipage/#dom-mimetype-enabledplugin fn EnabledPlugin(&self) -> Root<Plugin> { unreachable!() } }
MimeType
identifier_name
util.rs
// This file is part of rss. // // Copyright © 2015-2017 The rust-syndication Developers // // This program is free software; you can redistribute it and/or modify // it under the terms of the MIT License and/or Apache 2.0 License. use std::collections::HashMap; use std::io::BufRead; use std::str; use quick_xml::events::Event; use quick_xml::events::attributes::Attributes; use quick_xml::Reader; use error::Error; use extension::{Extension, ExtensionMap}; pub fn extension_name(element_name: &[u8]) -> Option<(&[u8], &[u8])> { let mut split = element_name.splitn(2, |b| *b == b':'); match split.next() { Some(b"") | None => None, Some(ns) => split.next().map(|name| (ns, name)), } } pub fn parse_extension<R>( reader: &mut Reader<R>, atts: Attributes, ns: &[u8], name: &[u8], extensions: &mut ExtensionMap, ) -> Result<(), Error> where R: BufRead, { let ns = str::from_utf8(ns)?; let name = str::from_utf8(name)?; let ext = parse_extension_element(reader, atts)?; if!extensions.contains_key(ns) { extensions.insert(ns.to_string(), HashMap::new()); } let map = match extensions.get_mut(ns) { Some(map) => map, None => unreachable!(), }; if!map.contains_key(name) { map.insert(name.to_string(), Vec::new()); } let items = match map.get_mut(name) { Some(items) => items, None => unreachable!(), }; items.push(ext); Ok(()) } fn parse_extension_element<R: BufRead>( reader: &mut Reader<R>, mut atts: Attributes, ) -> Result<Extension, Error> {
} let items = match extension.children.get_mut(name) { Some(items) => items, None => unreachable!(), }; items.push(ext); } Event::CData(element) => { extension.value = Some(reader.decode(&element).into_owned()); } Event::Text(element) => { extension.value = Some(element.unescape_and_decode(reader)?); } Event::End(element) => { extension.name = reader.decode(element.name()).into_owned(); break; } Event::Eof => return Err(Error::Eof), _ => {} } buf.clear(); } Ok(extension) } pub fn remove_extension_values( map: &mut HashMap<String, Vec<Extension>>, key: &str, ) -> Option<Vec<String>> { map.remove(key).map(|v| { v.into_iter() .filter_map(|ext| ext.value) .collect::<Vec<_>>() }) } pub fn remove_extension_value( map: &mut HashMap<String, Vec<Extension>>, key: &str, ) -> Option<String> { map.remove(key) .map(|mut v| v.remove(0)) .and_then(|ext| ext.value) }
let mut extension = Extension::default(); let mut buf = Vec::new(); for attr in atts.with_checks(false) { if let Ok(attr) = attr { let key = str::from_utf8(attr.key)?; let value = attr.unescape_and_decode_value(reader)?; extension.attrs.insert(key.to_string(), value); } } loop { match reader.read_event(&mut buf)? { Event::Start(element) => { let ext = parse_extension_element(reader, element.attributes())?; let name = str::from_utf8(element.local_name())?; if !extension.children.contains_key(name) { extension.children.insert(name.to_string(), Vec::new());
identifier_body
util.rs
// This file is part of rss. // // Copyright © 2015-2017 The rust-syndication Developers // // This program is free software; you can redistribute it and/or modify // it under the terms of the MIT License and/or Apache 2.0 License. use std::collections::HashMap; use std::io::BufRead; use std::str; use quick_xml::events::Event; use quick_xml::events::attributes::Attributes; use quick_xml::Reader; use error::Error; use extension::{Extension, ExtensionMap}; pub fn extension_name(element_name: &[u8]) -> Option<(&[u8], &[u8])> { let mut split = element_name.splitn(2, |b| *b == b':'); match split.next() { Some(b"") | None => None, Some(ns) => split.next().map(|name| (ns, name)), } } pub fn parse_extension<R>( reader: &mut Reader<R>, atts: Attributes, ns: &[u8], name: &[u8], extensions: &mut ExtensionMap, ) -> Result<(), Error> where R: BufRead, { let ns = str::from_utf8(ns)?; let name = str::from_utf8(name)?; let ext = parse_extension_element(reader, atts)?; if!extensions.contains_key(ns) { extensions.insert(ns.to_string(), HashMap::new()); } let map = match extensions.get_mut(ns) { Some(map) => map, None => unreachable!(), }; if!map.contains_key(name) { map.insert(name.to_string(), Vec::new()); } let items = match map.get_mut(name) { Some(items) => items, None => unreachable!(), }; items.push(ext); Ok(()) } fn parse_extension_element<R: BufRead>( reader: &mut Reader<R>, mut atts: Attributes, ) -> Result<Extension, Error> { let mut extension = Extension::default(); let mut buf = Vec::new(); for attr in atts.with_checks(false) { if let Ok(attr) = attr { let key = str::from_utf8(attr.key)?; let value = attr.unescape_and_decode_value(reader)?; extension.attrs.insert(key.to_string(), value); } } loop { match reader.read_event(&mut buf)? { Event::Start(element) => { let ext = parse_extension_element(reader, element.attributes())?; let name = str::from_utf8(element.local_name())?; if!extension.children.contains_key(name) { extension.children.insert(name.to_string(), Vec::new()); } let items = match extension.children.get_mut(name) { Some(items) => items, None => unreachable!(), }; items.push(ext); } Event::CData(element) => { extension.value = Some(reader.decode(&element).into_owned()); } Event::Text(element) => { extension.value = Some(element.unescape_and_decode(reader)?); } Event::End(element) => { extension.name = reader.decode(element.name()).into_owned(); break; } Event::Eof => return Err(Error::Eof), _ => {} } buf.clear(); } Ok(extension) } pub fn remove_extension_values( map: &mut HashMap<String, Vec<Extension>>, key: &str, ) -> Option<Vec<String>> { map.remove(key).map(|v| { v.into_iter() .filter_map(|ext| ext.value) .collect::<Vec<_>>() }) } pub fn r
map: &mut HashMap<String, Vec<Extension>>, key: &str, ) -> Option<String> { map.remove(key) .map(|mut v| v.remove(0)) .and_then(|ext| ext.value) }
emove_extension_value(
identifier_name
util.rs
// This file is part of rss. // // Copyright © 2015-2017 The rust-syndication Developers // // This program is free software; you can redistribute it and/or modify // it under the terms of the MIT License and/or Apache 2.0 License. use std::collections::HashMap; use std::io::BufRead; use std::str; use quick_xml::events::Event; use quick_xml::events::attributes::Attributes; use quick_xml::Reader; use error::Error; use extension::{Extension, ExtensionMap}; pub fn extension_name(element_name: &[u8]) -> Option<(&[u8], &[u8])> { let mut split = element_name.splitn(2, |b| *b == b':'); match split.next() { Some(b"") | None => None, Some(ns) => split.next().map(|name| (ns, name)), } } pub fn parse_extension<R>( reader: &mut Reader<R>, atts: Attributes, ns: &[u8], name: &[u8], extensions: &mut ExtensionMap, ) -> Result<(), Error> where R: BufRead, { let ns = str::from_utf8(ns)?; let name = str::from_utf8(name)?; let ext = parse_extension_element(reader, atts)?; if!extensions.contains_key(ns) { extensions.insert(ns.to_string(), HashMap::new()); } let map = match extensions.get_mut(ns) { Some(map) => map, None => unreachable!(), }; if!map.contains_key(name) { map.insert(name.to_string(), Vec::new()); } let items = match map.get_mut(name) { Some(items) => items, None => unreachable!(), }; items.push(ext); Ok(()) } fn parse_extension_element<R: BufRead>( reader: &mut Reader<R>, mut atts: Attributes, ) -> Result<Extension, Error> { let mut extension = Extension::default(); let mut buf = Vec::new(); for attr in atts.with_checks(false) { if let Ok(attr) = attr {
} loop { match reader.read_event(&mut buf)? { Event::Start(element) => { let ext = parse_extension_element(reader, element.attributes())?; let name = str::from_utf8(element.local_name())?; if!extension.children.contains_key(name) { extension.children.insert(name.to_string(), Vec::new()); } let items = match extension.children.get_mut(name) { Some(items) => items, None => unreachable!(), }; items.push(ext); } Event::CData(element) => { extension.value = Some(reader.decode(&element).into_owned()); } Event::Text(element) => { extension.value = Some(element.unescape_and_decode(reader)?); } Event::End(element) => { extension.name = reader.decode(element.name()).into_owned(); break; } Event::Eof => return Err(Error::Eof), _ => {} } buf.clear(); } Ok(extension) } pub fn remove_extension_values( map: &mut HashMap<String, Vec<Extension>>, key: &str, ) -> Option<Vec<String>> { map.remove(key).map(|v| { v.into_iter() .filter_map(|ext| ext.value) .collect::<Vec<_>>() }) } pub fn remove_extension_value( map: &mut HashMap<String, Vec<Extension>>, key: &str, ) -> Option<String> { map.remove(key) .map(|mut v| v.remove(0)) .and_then(|ext| ext.value) }
let key = str::from_utf8(attr.key)?; let value = attr.unescape_and_decode_value(reader)?; extension.attrs.insert(key.to_string(), value); }
conditional_block
util.rs
// This file is part of rss. // // Copyright © 2015-2017 The rust-syndication Developers // // This program is free software; you can redistribute it and/or modify // it under the terms of the MIT License and/or Apache 2.0 License. use std::collections::HashMap; use std::io::BufRead; use std::str; use quick_xml::events::Event; use quick_xml::events::attributes::Attributes; use quick_xml::Reader; use error::Error; use extension::{Extension, ExtensionMap}; pub fn extension_name(element_name: &[u8]) -> Option<(&[u8], &[u8])> { let mut split = element_name.splitn(2, |b| *b == b':'); match split.next() { Some(b"") | None => None, Some(ns) => split.next().map(|name| (ns, name)), } } pub fn parse_extension<R>( reader: &mut Reader<R>, atts: Attributes, ns: &[u8], name: &[u8], extensions: &mut ExtensionMap, ) -> Result<(), Error> where R: BufRead, { let ns = str::from_utf8(ns)?; let name = str::from_utf8(name)?; let ext = parse_extension_element(reader, atts)?; if!extensions.contains_key(ns) { extensions.insert(ns.to_string(), HashMap::new()); } let map = match extensions.get_mut(ns) { Some(map) => map, None => unreachable!(), }; if!map.contains_key(name) { map.insert(name.to_string(), Vec::new()); } let items = match map.get_mut(name) { Some(items) => items, None => unreachable!(), }; items.push(ext); Ok(())
fn parse_extension_element<R: BufRead>( reader: &mut Reader<R>, mut atts: Attributes, ) -> Result<Extension, Error> { let mut extension = Extension::default(); let mut buf = Vec::new(); for attr in atts.with_checks(false) { if let Ok(attr) = attr { let key = str::from_utf8(attr.key)?; let value = attr.unescape_and_decode_value(reader)?; extension.attrs.insert(key.to_string(), value); } } loop { match reader.read_event(&mut buf)? { Event::Start(element) => { let ext = parse_extension_element(reader, element.attributes())?; let name = str::from_utf8(element.local_name())?; if!extension.children.contains_key(name) { extension.children.insert(name.to_string(), Vec::new()); } let items = match extension.children.get_mut(name) { Some(items) => items, None => unreachable!(), }; items.push(ext); } Event::CData(element) => { extension.value = Some(reader.decode(&element).into_owned()); } Event::Text(element) => { extension.value = Some(element.unescape_and_decode(reader)?); } Event::End(element) => { extension.name = reader.decode(element.name()).into_owned(); break; } Event::Eof => return Err(Error::Eof), _ => {} } buf.clear(); } Ok(extension) } pub fn remove_extension_values( map: &mut HashMap<String, Vec<Extension>>, key: &str, ) -> Option<Vec<String>> { map.remove(key).map(|v| { v.into_iter() .filter_map(|ext| ext.value) .collect::<Vec<_>>() }) } pub fn remove_extension_value( map: &mut HashMap<String, Vec<Extension>>, key: &str, ) -> Option<String> { map.remove(key) .map(|mut v| v.remove(0)) .and_then(|ext| ext.value) }
}
random_line_split
enum-doc-bitfield.rs
/* automatically generated by rust-bindgen */ #![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals
/// Document field with three slashes pub const VAR_A: B = B(0); } impl B { /// Document field with preceeding star pub const VAR_B: B = B(1); } impl B { /// Document field with preceeding exclamation pub const VAR_C: B = B(2); } impl B { ///< Document field with following star pub const VAR_D: B = B(3); } impl B { ///< Document field with following exclamation pub const VAR_E: B = B(4); } impl B { /// Document field with preceeding star, with a loong long multiline /// comment. /// /// Very interesting documentation, definitely. pub const VAR_F: B = B(5); } impl ::std::ops::BitOr<B> for B { type Output = Self; #[inline] fn bitor(self, other: Self) -> Self { B(self.0 | other.0) } } impl ::std::ops::BitOrAssign for B { #[inline] fn bitor_assign(&mut self, rhs: B) { self.0 |= rhs.0; } } impl ::std::ops::BitAnd<B> for B { type Output = Self; #[inline] fn bitand(self, other: Self) -> Self { B(self.0 & other.0) } } impl ::std::ops::BitAndAssign for B { #[inline] fn bitand_assign(&mut self, rhs: B) { self.0 &= rhs.0; } } #[repr(transparent)] /// Document enum #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub struct B(pub u32);
)] impl B {
random_line_split
enum-doc-bitfield.rs
/* automatically generated by rust-bindgen */ #![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] impl B { /// Document field with three slashes pub const VAR_A: B = B(0); } impl B { /// Document field with preceeding star pub const VAR_B: B = B(1); } impl B { /// Document field with preceeding exclamation pub const VAR_C: B = B(2); } impl B { ///< Document field with following star pub const VAR_D: B = B(3); } impl B { ///< Document field with following exclamation pub const VAR_E: B = B(4); } impl B { /// Document field with preceeding star, with a loong long multiline /// comment. /// /// Very interesting documentation, definitely. pub const VAR_F: B = B(5); } impl ::std::ops::BitOr<B> for B { type Output = Self; #[inline] fn bitor(self, other: Self) -> Self { B(self.0 | other.0) } } impl ::std::ops::BitOrAssign for B { #[inline] fn bitor_assign(&mut self, rhs: B) { self.0 |= rhs.0; } } impl ::std::ops::BitAnd<B> for B { type Output = Self; #[inline] fn
(self, other: Self) -> Self { B(self.0 & other.0) } } impl ::std::ops::BitAndAssign for B { #[inline] fn bitand_assign(&mut self, rhs: B) { self.0 &= rhs.0; } } #[repr(transparent)] /// Document enum #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub struct B(pub u32);
bitand
identifier_name
enum-doc-bitfield.rs
/* automatically generated by rust-bindgen */ #![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] impl B { /// Document field with three slashes pub const VAR_A: B = B(0); } impl B { /// Document field with preceeding star pub const VAR_B: B = B(1); } impl B { /// Document field with preceeding exclamation pub const VAR_C: B = B(2); } impl B { ///< Document field with following star pub const VAR_D: B = B(3); } impl B { ///< Document field with following exclamation pub const VAR_E: B = B(4); } impl B { /// Document field with preceeding star, with a loong long multiline /// comment. /// /// Very interesting documentation, definitely. pub const VAR_F: B = B(5); } impl ::std::ops::BitOr<B> for B { type Output = Self; #[inline] fn bitor(self, other: Self) -> Self
} impl ::std::ops::BitOrAssign for B { #[inline] fn bitor_assign(&mut self, rhs: B) { self.0 |= rhs.0; } } impl ::std::ops::BitAnd<B> for B { type Output = Self; #[inline] fn bitand(self, other: Self) -> Self { B(self.0 & other.0) } } impl ::std::ops::BitAndAssign for B { #[inline] fn bitand_assign(&mut self, rhs: B) { self.0 &= rhs.0; } } #[repr(transparent)] /// Document enum #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub struct B(pub u32);
{ B(self.0 | other.0) }
identifier_body
main.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/. */ #![feature(env, os, start)] #[cfg(target_os="android")] extern crate libc; extern crate servo; extern crate time; extern crate util; extern crate net; #[cfg(not(test))] extern crate "glutin_app" as app; #[cfg(not(test))] extern crate compositing; #[cfg(target_os="android")] #[macro_use] extern crate android_glue; #[cfg(target_os="android")] use libc::c_int; #[cfg(not(test))] use util::opts; #[cfg(not(test))] use net::resource_task; #[cfg(not(test))] use servo::Browser; #[cfg(not(test))] use compositing::windowing::WindowEvent; #[cfg(target_os="android")] use std::borrow::ToOwned; #[cfg(not(test))] struct
{ browser: Browser, } #[cfg(target_os="android")] android_start!(main); #[cfg(target_os="android")] fn get_args() -> Vec<String> { vec![ "servo".to_owned(), "http://en.wikipedia.org/wiki/Rust".to_owned() ] } #[cfg(not(target_os="android"))] fn get_args() -> Vec<String> { use std::env; env::args().collect() } #[cfg(target_os="android")] struct FilePtr(*mut libc::types::common::c95::FILE); #[cfg(target_os="android")] unsafe impl Send for FilePtr {} #[cfg(target_os="android")] fn redirect_output(file_no: c_int) { use libc::funcs::posix88::unistd::{pipe, dup2}; use libc::funcs::posix88::stdio::fdopen; use libc::funcs::c95::stdio::fgets; use util::task::spawn_named; use std::mem; use std::ffi::CString; use std::str::from_utf8; unsafe { let mut pipes: [c_int; 2] = [ 0, 0 ]; pipe(pipes.as_mut_ptr()); dup2(pipes[1], file_no); let mode = CString::from_slice("r".as_bytes()); let input_file = FilePtr(fdopen(pipes[0], mode.as_ptr())); spawn_named("android-logger".to_owned(), move || { loop { let mut read_buffer: [u8; 1024] = mem::zeroed(); let FilePtr(input_file) = input_file; fgets(read_buffer.as_mut_ptr() as *mut i8, read_buffer.len() as i32, input_file); let cs = CString::from_slice(&read_buffer); match from_utf8(cs.as_bytes()) { Ok(s) => android_glue::write_log(s), _ => {} } } }); } } #[cfg(target_os="android")] fn setup_logging() { use libc::consts::os::posix88::{STDERR_FILENO, STDOUT_FILENO}; //os::setenv("RUST_LOG", "servo,gfx,msg,util,layers,js,std,rt,extra"); redirect_output(STDERR_FILENO); redirect_output(STDOUT_FILENO); } #[cfg(not(target_os="android"))] fn setup_logging() { } fn main() { if opts::from_cmdline_args(&*get_args()) { setup_logging(); resource_task::global_init(); let window = if opts::get().headless { None } else { Some(app::create_window()) }; let mut browser = BrowserWrapper { browser: Browser::new(window.clone()), }; match window { None => {} Some(ref window) => { unsafe { window.set_nested_event_loop_listener(&mut browser); } } } browser.browser.handle_event(WindowEvent::InitializeCompositing); loop { let should_continue = match window { None => browser.browser.handle_event(WindowEvent::Idle), Some(ref window) => { let event = window.wait_events(); browser.browser.handle_event(event) } }; if!should_continue { break } }; match window { None => {} Some(ref window) => { unsafe { window.remove_nested_event_loop_listener(); } } } let BrowserWrapper { browser } = browser; browser.shutdown(); } } impl app::NestedEventLoopListener for BrowserWrapper { fn handle_event_from_nested_event_loop(&mut self, event: WindowEvent) -> bool { let is_resize = match event { WindowEvent::Resize(..) => true, _ => false, }; if!self.browser.handle_event(event) { return false } if is_resize { self.browser.repaint_synchronously() } true } }
BrowserWrapper
identifier_name
main.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/. */ #![feature(env, os, start)] #[cfg(target_os="android")] extern crate libc; extern crate servo; extern crate time; extern crate util; extern crate net; #[cfg(not(test))] extern crate "glutin_app" as app; #[cfg(not(test))] extern crate compositing; #[cfg(target_os="android")] #[macro_use] extern crate android_glue; #[cfg(target_os="android")] use libc::c_int; #[cfg(not(test))] use util::opts; #[cfg(not(test))] use net::resource_task; #[cfg(not(test))] use servo::Browser; #[cfg(not(test))] use compositing::windowing::WindowEvent; #[cfg(target_os="android")] use std::borrow::ToOwned; #[cfg(not(test))] struct BrowserWrapper { browser: Browser, } #[cfg(target_os="android")] android_start!(main); #[cfg(target_os="android")] fn get_args() -> Vec<String> { vec![ "servo".to_owned(), "http://en.wikipedia.org/wiki/Rust".to_owned() ] } #[cfg(not(target_os="android"))] fn get_args() -> Vec<String> { use std::env; env::args().collect() } #[cfg(target_os="android")] struct FilePtr(*mut libc::types::common::c95::FILE); #[cfg(target_os="android")] unsafe impl Send for FilePtr {} #[cfg(target_os="android")] fn redirect_output(file_no: c_int) { use libc::funcs::posix88::unistd::{pipe, dup2}; use libc::funcs::posix88::stdio::fdopen; use libc::funcs::c95::stdio::fgets; use util::task::spawn_named; use std::mem; use std::ffi::CString; use std::str::from_utf8; unsafe { let mut pipes: [c_int; 2] = [ 0, 0 ]; pipe(pipes.as_mut_ptr()); dup2(pipes[1], file_no); let mode = CString::from_slice("r".as_bytes()); let input_file = FilePtr(fdopen(pipes[0], mode.as_ptr())); spawn_named("android-logger".to_owned(), move || { loop { let mut read_buffer: [u8; 1024] = mem::zeroed(); let FilePtr(input_file) = input_file; fgets(read_buffer.as_mut_ptr() as *mut i8, read_buffer.len() as i32, input_file); let cs = CString::from_slice(&read_buffer); match from_utf8(cs.as_bytes()) { Ok(s) => android_glue::write_log(s), _ => {} } } }); } } #[cfg(target_os="android")] fn setup_logging() { use libc::consts::os::posix88::{STDERR_FILENO, STDOUT_FILENO}; //os::setenv("RUST_LOG", "servo,gfx,msg,util,layers,js,std,rt,extra"); redirect_output(STDERR_FILENO); redirect_output(STDOUT_FILENO);
} #[cfg(not(target_os="android"))] fn setup_logging() { } fn main() { if opts::from_cmdline_args(&*get_args()) { setup_logging(); resource_task::global_init(); let window = if opts::get().headless { None } else { Some(app::create_window()) }; let mut browser = BrowserWrapper { browser: Browser::new(window.clone()), }; match window { None => {} Some(ref window) => { unsafe { window.set_nested_event_loop_listener(&mut browser); } } } browser.browser.handle_event(WindowEvent::InitializeCompositing); loop { let should_continue = match window { None => browser.browser.handle_event(WindowEvent::Idle), Some(ref window) => { let event = window.wait_events(); browser.browser.handle_event(event) } }; if!should_continue { break } }; match window { None => {} Some(ref window) => { unsafe { window.remove_nested_event_loop_listener(); } } } let BrowserWrapper { browser } = browser; browser.shutdown(); } } impl app::NestedEventLoopListener for BrowserWrapper { fn handle_event_from_nested_event_loop(&mut self, event: WindowEvent) -> bool { let is_resize = match event { WindowEvent::Resize(..) => true, _ => false, }; if!self.browser.handle_event(event) { return false } if is_resize { self.browser.repaint_synchronously() } true } }
random_line_split
main.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/. */ #![feature(env, os, start)] #[cfg(target_os="android")] extern crate libc; extern crate servo; extern crate time; extern crate util; extern crate net; #[cfg(not(test))] extern crate "glutin_app" as app; #[cfg(not(test))] extern crate compositing; #[cfg(target_os="android")] #[macro_use] extern crate android_glue; #[cfg(target_os="android")] use libc::c_int; #[cfg(not(test))] use util::opts; #[cfg(not(test))] use net::resource_task; #[cfg(not(test))] use servo::Browser; #[cfg(not(test))] use compositing::windowing::WindowEvent; #[cfg(target_os="android")] use std::borrow::ToOwned; #[cfg(not(test))] struct BrowserWrapper { browser: Browser, } #[cfg(target_os="android")] android_start!(main); #[cfg(target_os="android")] fn get_args() -> Vec<String> { vec![ "servo".to_owned(), "http://en.wikipedia.org/wiki/Rust".to_owned() ] } #[cfg(not(target_os="android"))] fn get_args() -> Vec<String> { use std::env; env::args().collect() } #[cfg(target_os="android")] struct FilePtr(*mut libc::types::common::c95::FILE); #[cfg(target_os="android")] unsafe impl Send for FilePtr {} #[cfg(target_os="android")] fn redirect_output(file_no: c_int) { use libc::funcs::posix88::unistd::{pipe, dup2}; use libc::funcs::posix88::stdio::fdopen; use libc::funcs::c95::stdio::fgets; use util::task::spawn_named; use std::mem; use std::ffi::CString; use std::str::from_utf8; unsafe { let mut pipes: [c_int; 2] = [ 0, 0 ]; pipe(pipes.as_mut_ptr()); dup2(pipes[1], file_no); let mode = CString::from_slice("r".as_bytes()); let input_file = FilePtr(fdopen(pipes[0], mode.as_ptr())); spawn_named("android-logger".to_owned(), move || { loop { let mut read_buffer: [u8; 1024] = mem::zeroed(); let FilePtr(input_file) = input_file; fgets(read_buffer.as_mut_ptr() as *mut i8, read_buffer.len() as i32, input_file); let cs = CString::from_slice(&read_buffer); match from_utf8(cs.as_bytes()) { Ok(s) => android_glue::write_log(s), _ => {} } } }); } } #[cfg(target_os="android")] fn setup_logging() { use libc::consts::os::posix88::{STDERR_FILENO, STDOUT_FILENO}; //os::setenv("RUST_LOG", "servo,gfx,msg,util,layers,js,std,rt,extra"); redirect_output(STDERR_FILENO); redirect_output(STDOUT_FILENO); } #[cfg(not(target_os="android"))] fn setup_logging() { } fn main() { if opts::from_cmdline_args(&*get_args()) { setup_logging(); resource_task::global_init(); let window = if opts::get().headless { None } else { Some(app::create_window()) }; let mut browser = BrowserWrapper { browser: Browser::new(window.clone()), }; match window { None => {} Some(ref window) => { unsafe { window.set_nested_event_loop_listener(&mut browser); } } } browser.browser.handle_event(WindowEvent::InitializeCompositing); loop { let should_continue = match window { None => browser.browser.handle_event(WindowEvent::Idle), Some(ref window) => { let event = window.wait_events(); browser.browser.handle_event(event) } }; if!should_continue { break } }; match window { None => {} Some(ref window) => { unsafe { window.remove_nested_event_loop_listener(); } } } let BrowserWrapper { browser } = browser; browser.shutdown(); } } impl app::NestedEventLoopListener for BrowserWrapper { fn handle_event_from_nested_event_loop(&mut self, event: WindowEvent) -> bool
}
{ let is_resize = match event { WindowEvent::Resize(..) => true, _ => false, }; if !self.browser.handle_event(event) { return false } if is_resize { self.browser.repaint_synchronously() } true }
identifier_body
regex_route.rs
use util::*; use hyper::status::StatusCode; use hyper::client::Response; fn with_path<F>(path: &str, f: F) where F: FnOnce(&mut Response) { run_example("regex_route", |port| { let url = format!("http://localhost:{}{}", port, path); let ref mut res = response_for(&url); f(res) }) } #[test] fn with_param()
#[test] fn ignores_query() { with_path("/hello/world?foo=bar", |res| { let s = read_body_to_string(res); assert_eq!(s, "Hello world"); }) } #[test] // FIXME? // Rym: I would expect this to 404, but its behavior is somewhat // expected when compared to the regex provided. To get my expected // behaviour, you'd need to append `$` to the regex in the example. // This seems like it might be a bit of a footgun. fn fallthrough_too_many_params() { with_path("/hello/beautiful/world", |res| { let s = read_body_to_string(res); assert_eq!(s, "Hello beautiful"); }) } #[test] fn fallthrough_with_no_match() { with_path("/", |res| { assert_eq!(res.status, StatusCode::NotFound); }) }
{ with_path("/hello/world", |res| { let s = read_body_to_string(res); assert_eq!(s, "Hello world"); }) }
identifier_body
regex_route.rs
use util::*; use hyper::status::StatusCode; use hyper::client::Response; fn with_path<F>(path: &str, f: F) where F: FnOnce(&mut Response) { run_example("regex_route", |port| { let url = format!("http://localhost:{}{}", port, path); let ref mut res = response_for(&url); f(res) }) } #[test] fn with_param() { with_path("/hello/world", |res| { let s = read_body_to_string(res); assert_eq!(s, "Hello world"); }) } #[test] fn ignores_query() { with_path("/hello/world?foo=bar", |res| { let s = read_body_to_string(res); assert_eq!(s, "Hello world"); }) } #[test] // FIXME?
// This seems like it might be a bit of a footgun. fn fallthrough_too_many_params() { with_path("/hello/beautiful/world", |res| { let s = read_body_to_string(res); assert_eq!(s, "Hello beautiful"); }) } #[test] fn fallthrough_with_no_match() { with_path("/", |res| { assert_eq!(res.status, StatusCode::NotFound); }) }
// Rym: I would expect this to 404, but its behavior is somewhat // expected when compared to the regex provided. To get my expected // behaviour, you'd need to append `$` to the regex in the example.
random_line_split
regex_route.rs
use util::*; use hyper::status::StatusCode; use hyper::client::Response; fn
<F>(path: &str, f: F) where F: FnOnce(&mut Response) { run_example("regex_route", |port| { let url = format!("http://localhost:{}{}", port, path); let ref mut res = response_for(&url); f(res) }) } #[test] fn with_param() { with_path("/hello/world", |res| { let s = read_body_to_string(res); assert_eq!(s, "Hello world"); }) } #[test] fn ignores_query() { with_path("/hello/world?foo=bar", |res| { let s = read_body_to_string(res); assert_eq!(s, "Hello world"); }) } #[test] // FIXME? // Rym: I would expect this to 404, but its behavior is somewhat // expected when compared to the regex provided. To get my expected // behaviour, you'd need to append `$` to the regex in the example. // This seems like it might be a bit of a footgun. fn fallthrough_too_many_params() { with_path("/hello/beautiful/world", |res| { let s = read_body_to_string(res); assert_eq!(s, "Hello beautiful"); }) } #[test] fn fallthrough_with_no_match() { with_path("/", |res| { assert_eq!(res.status, StatusCode::NotFound); }) }
with_path
identifier_name
routing_graph.rs
use crate::database::{Database, DeviceGlobalsData,}; use std::collections::{HashSet, HashMap}; use std::convert::TryInto; use crate::bba::idstring::*; use crate::bba::idxset::*; use crate::bba::tiletype::{Neighbour, BranchSide, TileTypes}; use crate::sites::*; use crate::wires::*; use crate::pip_classes::classify_pip; // A tile type from the interchange format perspective // this is not the same as a database tile type; because the Oxide graph can have // more than one tile at a grid location whereas the interchange grid is one tile // per location #[derive(Clone, Eq, PartialEq, Hash)] pub struct TileTypeKey { pub tile_types: Vec<String>, } impl TileTypeKey { pub fn new() -> TileTypeKey { TileTypeKey { tile_types: Vec::new() } } } pub struct IcTileType { pub key: TileTypeKey, pub wires: IndexedMap<IdString, IcWire>, pub pips: Vec<IcPip>, pub site_types: Vec<Site>, // TODO: constants, sites, etc } impl IcTileType { pub fn new(key: TileTypeKey, family: &str, db: &mut Database) -> IcTileType { let mut site_types = Vec::new(); for tt in key.tile_types.iter() { site_types.extend(build_sites(&tt, &db.tile_bitdb(family, &tt).db)); } IcTileType { key: key, wires: IndexedMap::new(), pips: Vec::new(), site_types: site_types, } } pub fn wire(&mut self, name: IdString) -> usize { self.wires.add(&name, IcWire::new(name)) } pub fn add_pip(&mut self, sub_tile: usize, src: IdString, dst: IdString, tmg_idx: usize) { let src_idx = self.wire(src); let dst_idx = self.wire(dst); self.pips.push(IcPip { src_wire: src_idx, dst_wire: dst_idx, sub_tile: sub_tile, pseudo_cells: Vec::new(), tmg_idx: tmg_idx, }); } pub fn add_ppip(&mut self, sub_tile: usize, src: IdString, dst: IdString, tmg_idx: usize, pseudo_cells: Vec<IcPseudoCell>) { let src_idx = self.wire(src); let dst_idx = self.wire(dst); self.pips.push(IcPip { src_wire: src_idx, dst_wire: dst_idx, sub_tile: sub_tile, pseudo_cells: pseudo_cells, tmg_idx: tmg_idx, }); } } pub struct IcWire { pub name: IdString, } impl IcWire { pub fn new(name: IdString) -> IcWire { IcWire { name: name, } } } pub struct IcPseudoCell { pub bel: IdString, pub pins: Vec<IdString>, } pub struct IcPip { pub src_wire: usize, pub dst_wire: usize, pub sub_tile: usize, pub pseudo_cells: Vec<IcPseudoCell>, pub tmg_idx: usize, } // A tile instance pub struct IcTileInst { pub name: IdString, pub x: u32, pub y: u32, pub type_idx: usize, pub key: TileTypeKey, // mapping between wires and nodes wire_to_node: HashMap<IdString, usize>, } impl IcTileInst { pub fn new(ids: &mut IdStringDB, x: u32, y: u32) -> IcTileInst { IcTileInst { name: ids.id(&format!("R{}C{}", y, x)), x: x, y: y, type_idx: 0, key: TileTypeKey::new(), wire_to_node: HashMap::new(), } } } // A reference to a tile wire #[derive(Clone, Hash, Eq, PartialEq)] pub struct IcWireRef { pub tile_name: IdString, pub wire_name: IdString, } pub const WIRE_TYPE_GENERAL: u32 = 0; pub const WIRE_TYPE_SPECIAL: u32 = 1; pub const WIRE_TYPE_GLOBAL: u32 = 2; // A node instance pub struct IcNode { // list of tile wires in the node pub wires: HashSet<IcWireRef>, pub root_wire: IcWireRef, pub wire_type: u32, } impl IcNode { pub fn new(root_wire: IcWireRef, wire_type: u32) -> IcNode { IcNode { wires: [root_wire.clone()].iter().cloned().collect(), root_wire: root_wire, wire_type: wire_type, } } } // The overall routing resource graph pub struct IcGraph { pub tile_types: IndexedMap<TileTypeKey, IcTileType>, pub tiles: Vec<IcTileInst>, pub nodes: Vec<IcNode>, pub width: u32, pub height: u32, pub pip_timings: IndexedSet<String>, } impl IcGraph { pub fn new(ids: &mut IdStringDB, width: u32, height: u32) -> IcGraph { IcGraph { tile_types: IndexedMap::new(), tiles: (0..width*height).map(|i| IcTileInst::new(ids, i%width, i/width)).collect(), nodes: Vec::new(), width: width, height: height, pip_timings: IndexedSet::new(), } } pub fn tile_idx(&self, x: u32, y: u32) -> usize { assert!(x < self.width); assert!(y < self.height); ((y * self.width) + x) as usize } pub fn tile_at(&mut self, x: u32, y: u32) -> &mut IcTileInst { let idx = self.tile_idx(x, y); &mut self.tiles[idx] } pub fn type_at(&mut self, x: u32, y: u32) -> &mut IcTileType { let idx = self.tile_at(x, y).type_idx; self.tile_types.value_mut(idx) } pub fn map_node(&mut self, ids: &IdStringDB, root_x: u32, root_y: u32, root_wire: IdString, wire_x: u32, wire_y: u32, wire: IdString) { // Make sure wire exists in both tiles self.type_at(root_x, root_y).wire(root_wire); self.type_at(wire_x, wire_y).wire(wire); // Update wire-node mapping let root_tile_idx = self.tile_idx(root_x, root_y); let node_idx = match self.tiles[root_tile_idx].wire_to_node.get(&root_wire) { Some(i) => *i, None => { let idx = self.nodes.len(); let wire_name_str = ids.str(root_wire); let wire_type = if wire_name_str.starts_with("H0") || wire_name_str.starts_with("V0") { WIRE_TYPE_GENERAL } else if wire_name_str.starts_with("HPBX") || wire_name_str.starts_with("VPSX0") || wire_name_str.starts_with("HPRX0") { WIRE_TYPE_GLOBAL } else { WIRE_TYPE_SPECIAL }; self.nodes.push(IcNode::new(IcWireRef { tile_name: self.tiles[root_tile_idx].name, wire_name: root_wire }, wire_type)); self.tiles[root_tile_idx].wire_to_node.insert(root_wire, idx); idx } }; let wire_tile_idx = self.tile_idx(wire_x, wire_y); self.nodes[node_idx].wires.insert(IcWireRef {tile_name: self.tiles[wire_tile_idx].name, wire_name: wire }); self.tiles[wire_tile_idx].wire_to_node.insert(wire, node_idx); } } pub struct GraphBuilder<'a> { g: IcGraph, ids: &'a mut IdStringDB, chip: &'a Chip, glb: DeviceGlobalsData, db: &'a mut Database, tiletypes_by_xy: HashMap<(u32, u32), TileTypeKey>, orig_tts: TileTypes, } impl <'a> GraphBuilder<'a> { fn new(ids: &'a mut IdStringDB, chip: &'a Chip, db: &'a mut Database) -> GraphBuilder<'a> { let mut width = 0; let mut height = 0; let mut tiletypes_by_xy = HashMap::new(); for t in chip.tiles.iter() { tiletypes_by_xy.entry((t.x, t.y)).or_insert(TileTypeKey::new()).tile_types.push(t.tiletype.to_string()); width = std::cmp::max(width, t.x + 1); height = std::cmp::max(height, t.y + 1); } for v in tiletypes_by_xy.values_mut() { v.tile_types.sort(); }
GraphBuilder { g: IcGraph::new(ids, width, height), ids: ids, chip: chip, glb: globals.clone(), db: db, tiletypes_by_xy: tiletypes_by_xy, // the original tiletypes from the database orig_tts: orig_tts, } } fn get_pip_tmg_class(from_wire: &str, to_wire: &str) -> String { let (src_rel, src_name) = Neighbour::parse_wire(from_wire); let (dst_rel, dst_name) = Neighbour::parse_wire(to_wire); let (src_x, src_y) = match src_rel { Some(Neighbour::RelXY { rel_x: x, rel_y: y }) => (x, y), _ => (0, 0) }; let (dst_x, dst_y) = match dst_rel { Some(Neighbour::RelXY { rel_x: x, rel_y: y }) => (x, y), _ => (0, 0) }; classify_pip(src_x, src_y, src_name, dst_x, dst_y, dst_name) .unwrap_or("".into()) } fn setup_tiletypes(&mut self) { for t in self.g.tiles.iter_mut() { let key = self.tiletypes_by_xy.get(&(t.x, t.y)).unwrap(); t.key = key.clone(); t.type_idx = self.g.tile_types.add(key, IcTileType::new(key.clone(), &self.chip.family, self.db)); } let mut pip_timings = IndexedSet::new(); for (key, lt) in self.g.tile_types.iter_mut() { // setup wires for site pins let site_wires : Vec<String> = lt.site_types.iter().map(|s| s.pins.iter()).flatten().map(|p| p.tile_wire.clone()).collect(); for w in site_wires { lt.wire(self.ids.id(&w)); } for (sub_tile, tt) in key.tile_types.iter().enumerate() { // setup wires for all sub-tile-types let tt_data = self.orig_tts.get(tt).unwrap(); for wire in tt_data.wire_ids.iter() { lt.wire(*wire); } // setup pips, both fixed and not // TODO: skip site wires and pips and deal with these later let tdb = &self.db.tile_bitdb(&self.chip.family, tt).db; for (to_wire, pips) in tdb.pips.iter() { for pip in pips.iter() { if is_site_wire(tt, &pip.from_wire) && is_site_wire(tt, to_wire) { continue; } if to_wire.contains("CIBMUX") && pip.from_wire.contains("CIBMUX") && to_wire.chars().rev().nth(1).unwrap()!= pip.from_wire.chars().rev().nth(1).unwrap() { // Don't use CIBMUX other than straight-through // This avoids issues with having to carefully set CIBMUX for unused pins so they float high correctly, see // https://github.com/YosysHQ/nextpnr/blob/24ae205f20f0e1a0326e48002ab14d5bacfca1ef/nexus/fasm.cc#L272-L286 continue; } let tmg_cls = Self::get_pip_tmg_class(&pip.from_wire, to_wire); let tmg_idx = pip_timings.add(&tmg_cls); lt.add_pip(sub_tile, self.ids.id(&pip.from_wire), self.ids.id(to_wire), tmg_idx); } } for (to_wire, conns) in tdb.conns.iter() { for conn in conns.iter() { if is_site_wire(tt, &conn.from_wire) && is_site_wire(tt, to_wire) { continue; } lt.add_pip(sub_tile, self.ids.id(&conn.from_wire), self.ids.id(to_wire), 0); } } } if lt.site_types.iter().find(|s| s.site_type == "PLC").is_some() { let gnd_wire = self.ids.id("G:GND"); lt.wire(gnd_wire); let sub_tile = key.tile_types.iter().position(|x| &x[..] == "PLC").unwrap(); for i in 0..8 { // Create pseudo-ground drivers for LUT outputs lt.add_ppip(sub_tile, gnd_wire, self.ids.id(&format!("JF{}", i)), 0, vec![ IcPseudoCell { bel: self.ids.id(&format!("SLICE{}_LUT{}", &"ABCD"[(i/2)..(i/2)+1], i%2)), pins: vec![self.ids.id("F")], } ]); // Create LUT route-through PIPs for j in &["A", "B", "C", "D"] { lt.add_ppip(sub_tile, self.ids.id(&format!("J{}{}", j, i)), self.ids.id(&format!("JF{}", i)), 0, vec![ IcPseudoCell { bel: self.ids.id(&format!("SLICE{}_LUT{}", &"ABCD"[(i/2)..(i/2)+1], i%2)), pins: vec![self.ids.id(j), self.ids.id("F")], } ]); } } } } self.g.pip_timings = pip_timings; } // Convert a neighbour to a coordinate pub fn neighbour_tile(&self, x: u32, y: u32, n: &Neighbour) -> Option<(u32, u32)> { let conv_tuple = |(x, y)| (x as u32, y as u32); match n { Neighbour::RelXY { rel_x, rel_y } => { let nx = (x as i32) + rel_x; let ny = (y as i32) + rel_y; if nx >= 0 && ny >= 0 && (nx as u32) < self.g.width && (ny as u32) < self.g.height { Some((nx as u32, ny as u32)) } else { None } } Neighbour::Global => { // FIXME: current interchange format assumption that (0, 0) is empty Some((1, 1)) } Neighbour::Branch => { let branch_col = self.glb.branch_sink_to_origin(x as usize).unwrap(); Some((branch_col.try_into().unwrap(), y)) } Neighbour::BranchDriver { side } => { let offset: i32 = match side { BranchSide::Right => 2, BranchSide::Left => -2, }; let branch_col = self .glb .branch_sink_to_origin((x as i32 + offset) as usize) .unwrap(); Some((branch_col.try_into().unwrap(), y)) } Neighbour::Spine => Some(conv_tuple(self.glb.spine_sink_to_origin(x as usize, y as usize).unwrap())), Neighbour::HRow => Some(conv_tuple(self.glb.hrow_sink_to_origin(x as usize, y as usize).unwrap())), _ => None } } fn setup_wire2node(&mut self) { for ((x, y), key) in self.tiletypes_by_xy.iter() { for tt in key.tile_types.iter() { for wire in self.orig_tts.get(tt).unwrap().wires.iter() { let (neigh, base_wire) = Neighbour::parse_wire(wire); if let Some(neigh) = neigh { // it's a neighbour wire, map to the base tile if let Some((root_x, root_y)) = self.neighbour_tile(*x, *y, &neigh) { let base_wire_id = self.ids.id(base_wire); let wire_id = self.ids.id(wire); self.g.map_node(self.ids, root_x, root_y, base_wire_id, *x, *y, wire_id); } } else { // root node, map to itself let base_wire_id = self.ids.id(base_wire); self.g.map_node(self.ids, *x, *y, base_wire_id, *x, *y, base_wire_id); } } } } } pub fn run(ids: &'a mut IdStringDB, chip: &'a Chip, db: &'a mut Database) -> IcGraph { let mut builder = GraphBuilder::new(ids, chip, db
let orig_tts = TileTypes::new(db, ids, &chip.family, &[&chip.device]); let globals = db.device_globals(&chip.family, &chip.device);
random_line_split
routing_graph.rs
crate::database::{Database, DeviceGlobalsData,}; use std::collections::{HashSet, HashMap}; use std::convert::TryInto; use crate::bba::idstring::*; use crate::bba::idxset::*; use crate::bba::tiletype::{Neighbour, BranchSide, TileTypes}; use crate::sites::*; use crate::wires::*; use crate::pip_classes::classify_pip; // A tile type from the interchange format perspective // this is not the same as a database tile type; because the Oxide graph can have // more than one tile at a grid location whereas the interchange grid is one tile // per location #[derive(Clone, Eq, PartialEq, Hash)] pub struct TileTypeKey { pub tile_types: Vec<String>, } impl TileTypeKey { pub fn new() -> TileTypeKey { TileTypeKey { tile_types: Vec::new() } } } pub struct IcTileType { pub key: TileTypeKey, pub wires: IndexedMap<IdString, IcWire>, pub pips: Vec<IcPip>, pub site_types: Vec<Site>, // TODO: constants, sites, etc } impl IcTileType { pub fn new(key: TileTypeKey, family: &str, db: &mut Database) -> IcTileType { let mut site_types = Vec::new(); for tt in key.tile_types.iter() { site_types.extend(build_sites(&tt, &db.tile_bitdb(family, &tt).db)); } IcTileType { key: key, wires: IndexedMap::new(), pips: Vec::new(), site_types: site_types, } } pub fn wire(&mut self, name: IdString) -> usize { self.wires.add(&name, IcWire::new(name)) } pub fn add_pip(&mut self, sub_tile: usize, src: IdString, dst: IdString, tmg_idx: usize) { let src_idx = self.wire(src); let dst_idx = self.wire(dst); self.pips.push(IcPip { src_wire: src_idx, dst_wire: dst_idx, sub_tile: sub_tile, pseudo_cells: Vec::new(), tmg_idx: tmg_idx, }); } pub fn add_ppip(&mut self, sub_tile: usize, src: IdString, dst: IdString, tmg_idx: usize, pseudo_cells: Vec<IcPseudoCell>) { let src_idx = self.wire(src); let dst_idx = self.wire(dst); self.pips.push(IcPip { src_wire: src_idx, dst_wire: dst_idx, sub_tile: sub_tile, pseudo_cells: pseudo_cells, tmg_idx: tmg_idx, }); } } pub struct IcWire { pub name: IdString, } impl IcWire { pub fn new(name: IdString) -> IcWire { IcWire { name: name, } } } pub struct IcPseudoCell { pub bel: IdString, pub pins: Vec<IdString>, } pub struct IcPip { pub src_wire: usize, pub dst_wire: usize, pub sub_tile: usize, pub pseudo_cells: Vec<IcPseudoCell>, pub tmg_idx: usize, } // A tile instance pub struct IcTileInst { pub name: IdString, pub x: u32, pub y: u32, pub type_idx: usize, pub key: TileTypeKey, // mapping between wires and nodes wire_to_node: HashMap<IdString, usize>, } impl IcTileInst { pub fn new(ids: &mut IdStringDB, x: u32, y: u32) -> IcTileInst { IcTileInst { name: ids.id(&format!("R{}C{}", y, x)), x: x, y: y, type_idx: 0, key: TileTypeKey::new(), wire_to_node: HashMap::new(), } } } // A reference to a tile wire #[derive(Clone, Hash, Eq, PartialEq)] pub struct IcWireRef { pub tile_name: IdString, pub wire_name: IdString, } pub const WIRE_TYPE_GENERAL: u32 = 0; pub const WIRE_TYPE_SPECIAL: u32 = 1; pub const WIRE_TYPE_GLOBAL: u32 = 2; // A node instance pub struct IcNode { // list of tile wires in the node pub wires: HashSet<IcWireRef>, pub root_wire: IcWireRef, pub wire_type: u32, } impl IcNode { pub fn new(root_wire: IcWireRef, wire_type: u32) -> IcNode { IcNode { wires: [root_wire.clone()].iter().cloned().collect(), root_wire: root_wire, wire_type: wire_type, } } } // The overall routing resource graph pub struct IcGraph { pub tile_types: IndexedMap<TileTypeKey, IcTileType>, pub tiles: Vec<IcTileInst>, pub nodes: Vec<IcNode>, pub width: u32, pub height: u32, pub pip_timings: IndexedSet<String>, } impl IcGraph { pub fn new(ids: &mut IdStringDB, width: u32, height: u32) -> IcGraph { IcGraph { tile_types: IndexedMap::new(), tiles: (0..width*height).map(|i| IcTileInst::new(ids, i%width, i/width)).collect(), nodes: Vec::new(), width: width, height: height, pip_timings: IndexedSet::new(), } } pub fn tile_idx(&self, x: u32, y: u32) -> usize { assert!(x < self.width); assert!(y < self.height); ((y * self.width) + x) as usize } pub fn tile_at(&mut self, x: u32, y: u32) -> &mut IcTileInst { let idx = self.tile_idx(x, y); &mut self.tiles[idx] } pub fn type_at(&mut self, x: u32, y: u32) -> &mut IcTileType { let idx = self.tile_at(x, y).type_idx; self.tile_types.value_mut(idx) } pub fn map_node(&mut self, ids: &IdStringDB, root_x: u32, root_y: u32, root_wire: IdString, wire_x: u32, wire_y: u32, wire: IdString) { // Make sure wire exists in both tiles self.type_at(root_x, root_y).wire(root_wire); self.type_at(wire_x, wire_y).wire(wire); // Update wire-node mapping let root_tile_idx = self.tile_idx(root_x, root_y); let node_idx = match self.tiles[root_tile_idx].wire_to_node.get(&root_wire) { Some(i) => *i, None => { let idx = self.nodes.len(); let wire_name_str = ids.str(root_wire); let wire_type = if wire_name_str.starts_with("H0") || wire_name_str.starts_with("V0") { WIRE_TYPE_GENERAL } else if wire_name_str.starts_with("HPBX") || wire_name_str.starts_with("VPSX0") || wire_name_str.starts_with("HPRX0") { WIRE_TYPE_GLOBAL } else { WIRE_TYPE_SPECIAL }; self.nodes.push(IcNode::new(IcWireRef { tile_name: self.tiles[root_tile_idx].name, wire_name: root_wire }, wire_type)); self.tiles[root_tile_idx].wire_to_node.insert(root_wire, idx); idx } }; let wire_tile_idx = self.tile_idx(wire_x, wire_y); self.nodes[node_idx].wires.insert(IcWireRef {tile_name: self.tiles[wire_tile_idx].name, wire_name: wire }); self.tiles[wire_tile_idx].wire_to_node.insert(wire, node_idx); } } pub struct GraphBuilder<'a> { g: IcGraph, ids: &'a mut IdStringDB, chip: &'a Chip, glb: DeviceGlobalsData, db: &'a mut Database, tiletypes_by_xy: HashMap<(u32, u32), TileTypeKey>, orig_tts: TileTypes, } impl <'a> GraphBuilder<'a> { fn new(ids: &'a mut IdStringDB, chip: &'a Chip, db: &'a mut Database) -> GraphBuilder<'a> { let mut width = 0; let mut height = 0; let mut tiletypes_by_xy = HashMap::new(); for t in chip.tiles.iter() { tiletypes_by_xy.entry((t.x, t.y)).or_insert(TileTypeKey::new()).tile_types.push(t.tiletype.to_string()); width = std::cmp::max(width, t.x + 1); height = std::cmp::max(height, t.y + 1); } for v in tiletypes_by_xy.values_mut() { v.tile_types.sort(); } let orig_tts = TileTypes::new(db, ids, &chip.family, &[&chip.device]); let globals = db.device_globals(&chip.family, &chip.device); GraphBuilder { g: IcGraph::new(ids, width, height), ids: ids, chip: chip, glb: globals.clone(), db: db, tiletypes_by_xy: tiletypes_by_xy, // the original tiletypes from the database orig_tts: orig_tts, } } fn
(from_wire: &str, to_wire: &str) -> String { let (src_rel, src_name) = Neighbour::parse_wire(from_wire); let (dst_rel, dst_name) = Neighbour::parse_wire(to_wire); let (src_x, src_y) = match src_rel { Some(Neighbour::RelXY { rel_x: x, rel_y: y }) => (x, y), _ => (0, 0) }; let (dst_x, dst_y) = match dst_rel { Some(Neighbour::RelXY { rel_x: x, rel_y: y }) => (x, y), _ => (0, 0) }; classify_pip(src_x, src_y, src_name, dst_x, dst_y, dst_name) .unwrap_or("".into()) } fn setup_tiletypes(&mut self) { for t in self.g.tiles.iter_mut() { let key = self.tiletypes_by_xy.get(&(t.x, t.y)).unwrap(); t.key = key.clone(); t.type_idx = self.g.tile_types.add(key, IcTileType::new(key.clone(), &self.chip.family, self.db)); } let mut pip_timings = IndexedSet::new(); for (key, lt) in self.g.tile_types.iter_mut() { // setup wires for site pins let site_wires : Vec<String> = lt.site_types.iter().map(|s| s.pins.iter()).flatten().map(|p| p.tile_wire.clone()).collect(); for w in site_wires { lt.wire(self.ids.id(&w)); } for (sub_tile, tt) in key.tile_types.iter().enumerate() { // setup wires for all sub-tile-types let tt_data = self.orig_tts.get(tt).unwrap(); for wire in tt_data.wire_ids.iter() { lt.wire(*wire); } // setup pips, both fixed and not // TODO: skip site wires and pips and deal with these later let tdb = &self.db.tile_bitdb(&self.chip.family, tt).db; for (to_wire, pips) in tdb.pips.iter() { for pip in pips.iter() { if is_site_wire(tt, &pip.from_wire) && is_site_wire(tt, to_wire) { continue; } if to_wire.contains("CIBMUX") && pip.from_wire.contains("CIBMUX") && to_wire.chars().rev().nth(1).unwrap()!= pip.from_wire.chars().rev().nth(1).unwrap() { // Don't use CIBMUX other than straight-through // This avoids issues with having to carefully set CIBMUX for unused pins so they float high correctly, see // https://github.com/YosysHQ/nextpnr/blob/24ae205f20f0e1a0326e48002ab14d5bacfca1ef/nexus/fasm.cc#L272-L286 continue; } let tmg_cls = Self::get_pip_tmg_class(&pip.from_wire, to_wire); let tmg_idx = pip_timings.add(&tmg_cls); lt.add_pip(sub_tile, self.ids.id(&pip.from_wire), self.ids.id(to_wire), tmg_idx); } } for (to_wire, conns) in tdb.conns.iter() { for conn in conns.iter() { if is_site_wire(tt, &conn.from_wire) && is_site_wire(tt, to_wire) { continue; } lt.add_pip(sub_tile, self.ids.id(&conn.from_wire), self.ids.id(to_wire), 0); } } } if lt.site_types.iter().find(|s| s.site_type == "PLC").is_some() { let gnd_wire = self.ids.id("G:GND"); lt.wire(gnd_wire); let sub_tile = key.tile_types.iter().position(|x| &x[..] == "PLC").unwrap(); for i in 0..8 { // Create pseudo-ground drivers for LUT outputs lt.add_ppip(sub_tile, gnd_wire, self.ids.id(&format!("JF{}", i)), 0, vec![ IcPseudoCell { bel: self.ids.id(&format!("SLICE{}_LUT{}", &"ABCD"[(i/2)..(i/2)+1], i%2)), pins: vec![self.ids.id("F")], } ]); // Create LUT route-through PIPs for j in &["A", "B", "C", "D"] { lt.add_ppip(sub_tile, self.ids.id(&format!("J{}{}", j, i)), self.ids.id(&format!("JF{}", i)), 0, vec![ IcPseudoCell { bel: self.ids.id(&format!("SLICE{}_LUT{}", &"ABCD"[(i/2)..(i/2)+1], i%2)), pins: vec![self.ids.id(j), self.ids.id("F")], } ]); } } } } self.g.pip_timings = pip_timings; } // Convert a neighbour to a coordinate pub fn neighbour_tile(&self, x: u32, y: u32, n: &Neighbour) -> Option<(u32, u32)> { let conv_tuple = |(x, y)| (x as u32, y as u32); match n { Neighbour::RelXY { rel_x, rel_y } => { let nx = (x as i32) + rel_x; let ny = (y as i32) + rel_y; if nx >= 0 && ny >= 0 && (nx as u32) < self.g.width && (ny as u32) < self.g.height { Some((nx as u32, ny as u32)) } else { None } } Neighbour::Global => { // FIXME: current interchange format assumption that (0, 0) is empty Some((1, 1)) } Neighbour::Branch => { let branch_col = self.glb.branch_sink_to_origin(x as usize).unwrap(); Some((branch_col.try_into().unwrap(), y)) } Neighbour::BranchDriver { side } => { let offset: i32 = match side { BranchSide::Right => 2, BranchSide::Left => -2, }; let branch_col = self .glb .branch_sink_to_origin((x as i32 + offset) as usize) .unwrap(); Some((branch_col.try_into().unwrap(), y)) } Neighbour::Spine => Some(conv_tuple(self.glb.spine_sink_to_origin(x as usize, y as usize).unwrap())), Neighbour::HRow => Some(conv_tuple(self.glb.hrow_sink_to_origin(x as usize, y as usize).unwrap())), _ => None } } fn setup_wire2node(&mut self) { for ((x, y), key) in self.tiletypes_by_xy.iter() { for tt in key.tile_types.iter() { for wire in self.orig_tts.get(tt).unwrap().wires.iter() { let (neigh, base_wire) = Neighbour::parse_wire(wire); if let Some(neigh) = neigh { // it's a neighbour wire, map to the base tile if let Some((root_x, root_y)) = self.neighbour_tile(*x, *y, &neigh) { let base_wire_id = self.ids.id(base_wire); let wire_id = self.ids.id(wire); self.g.map_node(self.ids, root_x, root_y, base_wire_id, *x, *y, wire_id); } } else { // root node, map to itself let base_wire_id = self.ids.id(base_wire); self.g.map_node(self.ids, *x, *y, base_wire_id, *x, *y, base_wire_id); } } } } } pub fn run(ids: &'a mut IdStringDB, chip: &'a Chip, db: &'a mut Database) -> IcGraph { let mut builder = GraphBuilder::new(ids, chip
get_pip_tmg_class
identifier_name
routing_graph.rs
crate::database::{Database, DeviceGlobalsData,}; use std::collections::{HashSet, HashMap}; use std::convert::TryInto; use crate::bba::idstring::*; use crate::bba::idxset::*; use crate::bba::tiletype::{Neighbour, BranchSide, TileTypes}; use crate::sites::*; use crate::wires::*; use crate::pip_classes::classify_pip; // A tile type from the interchange format perspective // this is not the same as a database tile type; because the Oxide graph can have // more than one tile at a grid location whereas the interchange grid is one tile // per location #[derive(Clone, Eq, PartialEq, Hash)] pub struct TileTypeKey { pub tile_types: Vec<String>, } impl TileTypeKey { pub fn new() -> TileTypeKey { TileTypeKey { tile_types: Vec::new() } } } pub struct IcTileType { pub key: TileTypeKey, pub wires: IndexedMap<IdString, IcWire>, pub pips: Vec<IcPip>, pub site_types: Vec<Site>, // TODO: constants, sites, etc } impl IcTileType { pub fn new(key: TileTypeKey, family: &str, db: &mut Database) -> IcTileType { let mut site_types = Vec::new(); for tt in key.tile_types.iter() { site_types.extend(build_sites(&tt, &db.tile_bitdb(family, &tt).db)); } IcTileType { key: key, wires: IndexedMap::new(), pips: Vec::new(), site_types: site_types, } } pub fn wire(&mut self, name: IdString) -> usize { self.wires.add(&name, IcWire::new(name)) } pub fn add_pip(&mut self, sub_tile: usize, src: IdString, dst: IdString, tmg_idx: usize) { let src_idx = self.wire(src); let dst_idx = self.wire(dst); self.pips.push(IcPip { src_wire: src_idx, dst_wire: dst_idx, sub_tile: sub_tile, pseudo_cells: Vec::new(), tmg_idx: tmg_idx, }); } pub fn add_ppip(&mut self, sub_tile: usize, src: IdString, dst: IdString, tmg_idx: usize, pseudo_cells: Vec<IcPseudoCell>) { let src_idx = self.wire(src); let dst_idx = self.wire(dst); self.pips.push(IcPip { src_wire: src_idx, dst_wire: dst_idx, sub_tile: sub_tile, pseudo_cells: pseudo_cells, tmg_idx: tmg_idx, }); } } pub struct IcWire { pub name: IdString, } impl IcWire { pub fn new(name: IdString) -> IcWire { IcWire { name: name, } } } pub struct IcPseudoCell { pub bel: IdString, pub pins: Vec<IdString>, } pub struct IcPip { pub src_wire: usize, pub dst_wire: usize, pub sub_tile: usize, pub pseudo_cells: Vec<IcPseudoCell>, pub tmg_idx: usize, } // A tile instance pub struct IcTileInst { pub name: IdString, pub x: u32, pub y: u32, pub type_idx: usize, pub key: TileTypeKey, // mapping between wires and nodes wire_to_node: HashMap<IdString, usize>, } impl IcTileInst { pub fn new(ids: &mut IdStringDB, x: u32, y: u32) -> IcTileInst { IcTileInst { name: ids.id(&format!("R{}C{}", y, x)), x: x, y: y, type_idx: 0, key: TileTypeKey::new(), wire_to_node: HashMap::new(), } } } // A reference to a tile wire #[derive(Clone, Hash, Eq, PartialEq)] pub struct IcWireRef { pub tile_name: IdString, pub wire_name: IdString, } pub const WIRE_TYPE_GENERAL: u32 = 0; pub const WIRE_TYPE_SPECIAL: u32 = 1; pub const WIRE_TYPE_GLOBAL: u32 = 2; // A node instance pub struct IcNode { // list of tile wires in the node pub wires: HashSet<IcWireRef>, pub root_wire: IcWireRef, pub wire_type: u32, } impl IcNode { pub fn new(root_wire: IcWireRef, wire_type: u32) -> IcNode { IcNode { wires: [root_wire.clone()].iter().cloned().collect(), root_wire: root_wire, wire_type: wire_type, } } } // The overall routing resource graph pub struct IcGraph { pub tile_types: IndexedMap<TileTypeKey, IcTileType>, pub tiles: Vec<IcTileInst>, pub nodes: Vec<IcNode>, pub width: u32, pub height: u32, pub pip_timings: IndexedSet<String>, } impl IcGraph { pub fn new(ids: &mut IdStringDB, width: u32, height: u32) -> IcGraph { IcGraph { tile_types: IndexedMap::new(), tiles: (0..width*height).map(|i| IcTileInst::new(ids, i%width, i/width)).collect(), nodes: Vec::new(), width: width, height: height, pip_timings: IndexedSet::new(), } } pub fn tile_idx(&self, x: u32, y: u32) -> usize
pub fn tile_at(&mut self, x: u32, y: u32) -> &mut IcTileInst { let idx = self.tile_idx(x, y); &mut self.tiles[idx] } pub fn type_at(&mut self, x: u32, y: u32) -> &mut IcTileType { let idx = self.tile_at(x, y).type_idx; self.tile_types.value_mut(idx) } pub fn map_node(&mut self, ids: &IdStringDB, root_x: u32, root_y: u32, root_wire: IdString, wire_x: u32, wire_y: u32, wire: IdString) { // Make sure wire exists in both tiles self.type_at(root_x, root_y).wire(root_wire); self.type_at(wire_x, wire_y).wire(wire); // Update wire-node mapping let root_tile_idx = self.tile_idx(root_x, root_y); let node_idx = match self.tiles[root_tile_idx].wire_to_node.get(&root_wire) { Some(i) => *i, None => { let idx = self.nodes.len(); let wire_name_str = ids.str(root_wire); let wire_type = if wire_name_str.starts_with("H0") || wire_name_str.starts_with("V0") { WIRE_TYPE_GENERAL } else if wire_name_str.starts_with("HPBX") || wire_name_str.starts_with("VPSX0") || wire_name_str.starts_with("HPRX0") { WIRE_TYPE_GLOBAL } else { WIRE_TYPE_SPECIAL }; self.nodes.push(IcNode::new(IcWireRef { tile_name: self.tiles[root_tile_idx].name, wire_name: root_wire }, wire_type)); self.tiles[root_tile_idx].wire_to_node.insert(root_wire, idx); idx } }; let wire_tile_idx = self.tile_idx(wire_x, wire_y); self.nodes[node_idx].wires.insert(IcWireRef {tile_name: self.tiles[wire_tile_idx].name, wire_name: wire }); self.tiles[wire_tile_idx].wire_to_node.insert(wire, node_idx); } } pub struct GraphBuilder<'a> { g: IcGraph, ids: &'a mut IdStringDB, chip: &'a Chip, glb: DeviceGlobalsData, db: &'a mut Database, tiletypes_by_xy: HashMap<(u32, u32), TileTypeKey>, orig_tts: TileTypes, } impl <'a> GraphBuilder<'a> { fn new(ids: &'a mut IdStringDB, chip: &'a Chip, db: &'a mut Database) -> GraphBuilder<'a> { let mut width = 0; let mut height = 0; let mut tiletypes_by_xy = HashMap::new(); for t in chip.tiles.iter() { tiletypes_by_xy.entry((t.x, t.y)).or_insert(TileTypeKey::new()).tile_types.push(t.tiletype.to_string()); width = std::cmp::max(width, t.x + 1); height = std::cmp::max(height, t.y + 1); } for v in tiletypes_by_xy.values_mut() { v.tile_types.sort(); } let orig_tts = TileTypes::new(db, ids, &chip.family, &[&chip.device]); let globals = db.device_globals(&chip.family, &chip.device); GraphBuilder { g: IcGraph::new(ids, width, height), ids: ids, chip: chip, glb: globals.clone(), db: db, tiletypes_by_xy: tiletypes_by_xy, // the original tiletypes from the database orig_tts: orig_tts, } } fn get_pip_tmg_class(from_wire: &str, to_wire: &str) -> String { let (src_rel, src_name) = Neighbour::parse_wire(from_wire); let (dst_rel, dst_name) = Neighbour::parse_wire(to_wire); let (src_x, src_y) = match src_rel { Some(Neighbour::RelXY { rel_x: x, rel_y: y }) => (x, y), _ => (0, 0) }; let (dst_x, dst_y) = match dst_rel { Some(Neighbour::RelXY { rel_x: x, rel_y: y }) => (x, y), _ => (0, 0) }; classify_pip(src_x, src_y, src_name, dst_x, dst_y, dst_name) .unwrap_or("".into()) } fn setup_tiletypes(&mut self) { for t in self.g.tiles.iter_mut() { let key = self.tiletypes_by_xy.get(&(t.x, t.y)).unwrap(); t.key = key.clone(); t.type_idx = self.g.tile_types.add(key, IcTileType::new(key.clone(), &self.chip.family, self.db)); } let mut pip_timings = IndexedSet::new(); for (key, lt) in self.g.tile_types.iter_mut() { // setup wires for site pins let site_wires : Vec<String> = lt.site_types.iter().map(|s| s.pins.iter()).flatten().map(|p| p.tile_wire.clone()).collect(); for w in site_wires { lt.wire(self.ids.id(&w)); } for (sub_tile, tt) in key.tile_types.iter().enumerate() { // setup wires for all sub-tile-types let tt_data = self.orig_tts.get(tt).unwrap(); for wire in tt_data.wire_ids.iter() { lt.wire(*wire); } // setup pips, both fixed and not // TODO: skip site wires and pips and deal with these later let tdb = &self.db.tile_bitdb(&self.chip.family, tt).db; for (to_wire, pips) in tdb.pips.iter() { for pip in pips.iter() { if is_site_wire(tt, &pip.from_wire) && is_site_wire(tt, to_wire) { continue; } if to_wire.contains("CIBMUX") && pip.from_wire.contains("CIBMUX") && to_wire.chars().rev().nth(1).unwrap()!= pip.from_wire.chars().rev().nth(1).unwrap() { // Don't use CIBMUX other than straight-through // This avoids issues with having to carefully set CIBMUX for unused pins so they float high correctly, see // https://github.com/YosysHQ/nextpnr/blob/24ae205f20f0e1a0326e48002ab14d5bacfca1ef/nexus/fasm.cc#L272-L286 continue; } let tmg_cls = Self::get_pip_tmg_class(&pip.from_wire, to_wire); let tmg_idx = pip_timings.add(&tmg_cls); lt.add_pip(sub_tile, self.ids.id(&pip.from_wire), self.ids.id(to_wire), tmg_idx); } } for (to_wire, conns) in tdb.conns.iter() { for conn in conns.iter() { if is_site_wire(tt, &conn.from_wire) && is_site_wire(tt, to_wire) { continue; } lt.add_pip(sub_tile, self.ids.id(&conn.from_wire), self.ids.id(to_wire), 0); } } } if lt.site_types.iter().find(|s| s.site_type == "PLC").is_some() { let gnd_wire = self.ids.id("G:GND"); lt.wire(gnd_wire); let sub_tile = key.tile_types.iter().position(|x| &x[..] == "PLC").unwrap(); for i in 0..8 { // Create pseudo-ground drivers for LUT outputs lt.add_ppip(sub_tile, gnd_wire, self.ids.id(&format!("JF{}", i)), 0, vec![ IcPseudoCell { bel: self.ids.id(&format!("SLICE{}_LUT{}", &"ABCD"[(i/2)..(i/2)+1], i%2)), pins: vec![self.ids.id("F")], } ]); // Create LUT route-through PIPs for j in &["A", "B", "C", "D"] { lt.add_ppip(sub_tile, self.ids.id(&format!("J{}{}", j, i)), self.ids.id(&format!("JF{}", i)), 0, vec![ IcPseudoCell { bel: self.ids.id(&format!("SLICE{}_LUT{}", &"ABCD"[(i/2)..(i/2)+1], i%2)), pins: vec![self.ids.id(j), self.ids.id("F")], } ]); } } } } self.g.pip_timings = pip_timings; } // Convert a neighbour to a coordinate pub fn neighbour_tile(&self, x: u32, y: u32, n: &Neighbour) -> Option<(u32, u32)> { let conv_tuple = |(x, y)| (x as u32, y as u32); match n { Neighbour::RelXY { rel_x, rel_y } => { let nx = (x as i32) + rel_x; let ny = (y as i32) + rel_y; if nx >= 0 && ny >= 0 && (nx as u32) < self.g.width && (ny as u32) < self.g.height { Some((nx as u32, ny as u32)) } else { None } } Neighbour::Global => { // FIXME: current interchange format assumption that (0, 0) is empty Some((1, 1)) } Neighbour::Branch => { let branch_col = self.glb.branch_sink_to_origin(x as usize).unwrap(); Some((branch_col.try_into().unwrap(), y)) } Neighbour::BranchDriver { side } => { let offset: i32 = match side { BranchSide::Right => 2, BranchSide::Left => -2, }; let branch_col = self .glb .branch_sink_to_origin((x as i32 + offset) as usize) .unwrap(); Some((branch_col.try_into().unwrap(), y)) } Neighbour::Spine => Some(conv_tuple(self.glb.spine_sink_to_origin(x as usize, y as usize).unwrap())), Neighbour::HRow => Some(conv_tuple(self.glb.hrow_sink_to_origin(x as usize, y as usize).unwrap())), _ => None } } fn setup_wire2node(&mut self) { for ((x, y), key) in self.tiletypes_by_xy.iter() { for tt in key.tile_types.iter() { for wire in self.orig_tts.get(tt).unwrap().wires.iter() { let (neigh, base_wire) = Neighbour::parse_wire(wire); if let Some(neigh) = neigh { // it's a neighbour wire, map to the base tile if let Some((root_x, root_y)) = self.neighbour_tile(*x, *y, &neigh) { let base_wire_id = self.ids.id(base_wire); let wire_id = self.ids.id(wire); self.g.map_node(self.ids, root_x, root_y, base_wire_id, *x, *y, wire_id); } } else { // root node, map to itself let base_wire_id = self.ids.id(base_wire); self.g.map_node(self.ids, *x, *y, base_wire_id, *x, *y, base_wire_id); } } } } } pub fn run(ids: &'a mut IdStringDB, chip: &'a Chip, db: &'a mut Database) -> IcGraph { let mut builder = GraphBuilder::new(ids, chip
{ assert!(x < self.width); assert!(y < self.height); ((y * self.width) + x) as usize }
identifier_body
dompoint.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap}; use dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::DOMPointReadOnlyMethods; use dom::bindings::error::Fallible; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::dompointreadonly::{DOMPointReadOnly, DOMPointWriteMethods}; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; // http://dev.w3.org/fxtf/geometry/Overview.html#dompoint #[dom_struct] pub struct DOMPoint { point: DOMPointReadOnly, } impl DOMPoint { fn new_inherited(x: f64, y: f64, z: f64, w: f64) -> DOMPoint { DOMPoint { point: DOMPointReadOnly::new_inherited(x, y, z, w), } } pub fn new(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> DomRoot<DOMPoint> { reflect_dom_object(Box::new(DOMPoint::new_inherited(x, y, z, w)), global, Wrap) } pub fn Constructor(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> Fallible<DomRoot<DOMPoint>> { Ok(DOMPoint::new(global, x, y, z, w)) } pub fn new_from_init(global: &GlobalScope, p: &DOMPointInit) -> DomRoot<DOMPoint> { DOMPoint::new(global, p.x, p.y, p.z, p.w) } } impl DOMPointMethods for DOMPoint { // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x fn X(&self) -> f64 { self.point.X() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x fn SetX(&self, value: f64) { self.point.SetX(value); } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-y fn Y(&self) -> f64 { self.point.Y() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-y fn
(&self, value: f64) { self.point.SetY(value); } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z fn Z(&self) -> f64 { self.point.Z() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z fn SetZ(&self, value: f64) { self.point.SetZ(value); } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w fn W(&self) -> f64 { self.point.W() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w fn SetW(&self, value: f64) { self.point.SetW(value); } }
SetY
identifier_name
dompoint.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap}; use dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::DOMPointReadOnlyMethods; use dom::bindings::error::Fallible; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::dompointreadonly::{DOMPointReadOnly, DOMPointWriteMethods}; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; // http://dev.w3.org/fxtf/geometry/Overview.html#dompoint #[dom_struct] pub struct DOMPoint { point: DOMPointReadOnly, } impl DOMPoint { fn new_inherited(x: f64, y: f64, z: f64, w: f64) -> DOMPoint { DOMPoint { point: DOMPointReadOnly::new_inherited(x, y, z, w), } } pub fn new(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> DomRoot<DOMPoint> { reflect_dom_object(Box::new(DOMPoint::new_inherited(x, y, z, w)), global, Wrap) } pub fn Constructor(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> Fallible<DomRoot<DOMPoint>> { Ok(DOMPoint::new(global, x, y, z, w)) } pub fn new_from_init(global: &GlobalScope, p: &DOMPointInit) -> DomRoot<DOMPoint> { DOMPoint::new(global, p.x, p.y, p.z, p.w) } } impl DOMPointMethods for DOMPoint { // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x fn X(&self) -> f64 { self.point.X() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x fn SetX(&self, value: f64) { self.point.SetX(value); } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-y fn Y(&self) -> f64 { self.point.Y() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-y fn SetY(&self, value: f64) { self.point.SetY(value); } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z fn Z(&self) -> f64 { self.point.Z() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z fn SetZ(&self, value: f64) { self.point.SetZ(value); } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w fn W(&self) -> f64
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w fn SetW(&self, value: f64) { self.point.SetW(value); } }
{ self.point.W() }
identifier_body
dompoint.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap}; use dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::DOMPointReadOnlyMethods; use dom::bindings::error::Fallible; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::dompointreadonly::{DOMPointReadOnly, DOMPointWriteMethods}; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; // http://dev.w3.org/fxtf/geometry/Overview.html#dompoint #[dom_struct] pub struct DOMPoint { point: DOMPointReadOnly, } impl DOMPoint { fn new_inherited(x: f64, y: f64, z: f64, w: f64) -> DOMPoint { DOMPoint { point: DOMPointReadOnly::new_inherited(x, y, z, w), } } pub fn new(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> DomRoot<DOMPoint> { reflect_dom_object(Box::new(DOMPoint::new_inherited(x, y, z, w)), global, Wrap) } pub fn Constructor(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> Fallible<DomRoot<DOMPoint>> { Ok(DOMPoint::new(global, x, y, z, w)) } pub fn new_from_init(global: &GlobalScope, p: &DOMPointInit) -> DomRoot<DOMPoint> { DOMPoint::new(global, p.x, p.y, p.z, p.w) } } impl DOMPointMethods for DOMPoint { // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x fn X(&self) -> f64 { self.point.X() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x fn SetX(&self, value: f64) { self.point.SetX(value); } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-y fn Y(&self) -> f64 { self.point.Y() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-y fn SetY(&self, value: f64) { self.point.SetY(value); } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z fn Z(&self) -> f64 {
fn SetZ(&self, value: f64) { self.point.SetZ(value); } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w fn W(&self) -> f64 { self.point.W() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w fn SetW(&self, value: f64) { self.point.SetW(value); } }
self.point.Z() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z
random_line_split
session.rs
use std::future::Future; use std::pin::Pin; use std::sync::{atomic, Arc}; use std::task::{Context, Poll}; use crate::core; use futures::channel::oneshot; use futures::future; use futures::FutureExt; use parking_lot::Mutex; use slab::Slab; use crate::server_utils::cors::Origin; use crate::server_utils::hosts::Host; use crate::server_utils::reactor::TaskExecutor; use crate::server_utils::session::{SessionId, SessionStats}; use crate::server_utils::Pattern; use crate::ws; use crate::error; use crate::metadata; /// Middleware to intercept server requests. /// You can either terminate the request (by returning a response) /// or just proceed with standard JSON-RPC handling. pub trait RequestMiddleware: Send + Sync +'static { /// Process a request and decide what to do next. fn process(&self, req: &ws::Request) -> MiddlewareAction; } impl<F> RequestMiddleware for F where F: Fn(&ws::Request) -> Option<ws::Response> + Send + Sync +'static, { fn process(&self, req: &ws::Request) -> MiddlewareAction { (*self)(req).into() } } /// Request middleware action #[derive(Debug)] pub enum MiddlewareAction { /// Proceed with standard JSON-RPC behaviour. Proceed, /// Terminate the request and return a response. Respond { /// Response to return response: ws::Response, /// Should origin be validated before returning the response? validate_origin: bool, /// Should hosts be validated before returning the response? validate_hosts: bool, }, } impl MiddlewareAction { fn should_verify_origin(&self) -> bool { use self::MiddlewareAction::*; match *self { Proceed => true, Respond { validate_origin,.. } => validate_origin, } } fn should_verify_hosts(&self) -> bool { use self::MiddlewareAction::*; match *self { Proceed => true, Respond { validate_hosts,.. } => validate_hosts, } } } impl From<Option<ws::Response>> for MiddlewareAction { fn from(opt: Option<ws::Response>) -> Self { match opt { Some(res) => MiddlewareAction::Respond { response: res, validate_origin: true, validate_hosts: true, }, None => MiddlewareAction::Proceed, } } } // the slab is only inserted into when live. type TaskSlab = Mutex<Slab<Option<oneshot::Sender<()>>>>; // future for checking session liveness. // this returns `NotReady` until the session it corresponds to is dropped. #[derive(Debug)] struct LivenessPoll { task_slab: Arc<TaskSlab>, slab_handle: usize, rx: oneshot::Receiver<()>, } impl LivenessPoll { fn create(task_slab: Arc<TaskSlab>) -> Self { const INITIAL_SIZE: usize = 4; let (index, rx) = { let mut task_slab = task_slab.lock(); if task_slab.len() == task_slab.capacity() { // grow the size if necessary. // we don't expect this to get so big as to overflow. let reserve = ::std::cmp::max(task_slab.capacity(), INITIAL_SIZE); task_slab.reserve_exact(reserve); } let (tx, rx) = oneshot::channel(); let index = task_slab.insert(Some(tx)); (index, rx) }; LivenessPoll { task_slab, slab_handle: index, rx, } } } impl Future for LivenessPoll { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = Pin::into_inner(self); // if the future resolves ok then we've been signalled to return. // it should never be cancelled, but if it was the session definitely // isn't live. match Pin::new(&mut this.rx).poll(cx) { Poll::Ready(_) => Poll::Ready(()), Poll::Pending => Poll::Pending, } } } impl Drop for LivenessPoll { fn drop(&mut self) { // remove the entry from the slab if it hasn't been destroyed yet. self.task_slab.lock().remove(self.slab_handle); } } pub struct Session<M: core::Metadata, S: core::Middleware<M>> { active: Arc<atomic::AtomicBool>, context: metadata::RequestContext, handler: Arc<core::MetaIoHandler<M, S>>, meta_extractor: Arc<dyn metadata::MetaExtractor<M>>, allowed_origins: Option<Vec<Origin>>, allowed_hosts: Option<Vec<Host>>, request_middleware: Option<Arc<dyn RequestMiddleware>>, stats: Option<Arc<dyn SessionStats>>, metadata: Option<M>, executor: TaskExecutor, task_slab: Arc<TaskSlab>, } impl<M: core::Metadata, S: core::Middleware<M>> Drop for Session<M, S> { fn drop(&mut self) { self.active.store(false, atomic::Ordering::SeqCst); if let Some(stats) = self.stats.as_ref() { stats.close_session(self.context.session_id) } // signal to all still-live tasks that the session has been dropped. for (_index, task) in self.task_slab.lock().iter_mut() { if let Some(task) = task.take() { let _ = task.send(()); } } } } impl<M: core::Metadata, S: core::Middleware<M>> Session<M, S> { fn read_origin<'a>(&self, req: &'a ws::Request) -> Option<&'a [u8]> {
if!header_is_allowed(&self.allowed_origins, origin) { warn!( "Blocked connection to WebSockets server from untrusted origin: {:?}", origin.and_then(|s| std::str::from_utf8(s).ok()), ); Some(forbidden("URL Blocked", "Connection Origin has been rejected.")) } else { None } } fn verify_host(&self, req: &ws::Request) -> Option<ws::Response> { let host = req.header("host").map(|x| &x[..]); if!header_is_allowed(&self.allowed_hosts, host) { warn!( "Blocked connection to WebSockets server with untrusted host: {:?}", host.and_then(|s| std::str::from_utf8(s).ok()), ); Some(forbidden("URL Blocked", "Connection Host has been rejected.")) } else { None } } } impl<M: core::Metadata, S: core::Middleware<M>> ws::Handler for Session<M, S> where S::Future: Unpin, S::CallFuture: Unpin, { fn on_request(&mut self, req: &ws::Request) -> ws::Result<ws::Response> { // Run middleware let action = if let Some(ref middleware) = self.request_middleware { middleware.process(req) } else { MiddlewareAction::Proceed }; let origin = self.read_origin(req); if action.should_verify_origin() { // Verify request origin. if let Some(response) = self.verify_origin(origin) { return Ok(response); } } if action.should_verify_hosts() { // Verify host header. if let Some(response) = self.verify_host(req) { return Ok(response); } } self.context.origin = origin .and_then(|origin| ::std::str::from_utf8(origin).ok()) .map(Into::into); self.context.protocols = req .protocols() .ok() .map(|protos| protos.into_iter().map(Into::into).collect()) .unwrap_or_else(Vec::new); self.metadata = Some(self.meta_extractor.extract(&self.context)); match action { MiddlewareAction::Proceed => ws::Response::from_request(req).map(|mut res| { if let Some(protocol) = self.context.protocols.get(0) { res.set_protocol(protocol); } res }), MiddlewareAction::Respond { response,.. } => Ok(response), } } fn on_message(&mut self, msg: ws::Message) -> ws::Result<()> { let req = msg.as_text()?; let out = self.context.out.clone(); let metadata = self .metadata .clone() .expect("Metadata is always set in on_request; qed"); // TODO: creation requires allocating a `oneshot` channel and acquiring a // mutex. we could alternatively do this lazily upon first poll if // it becomes a bottleneck. let poll_liveness = LivenessPoll::create(self.task_slab.clone()); let active_lock = self.active.clone(); let response = self.handler.handle_request(req, metadata); let future = response.map(move |response| { if!active_lock.load(atomic::Ordering::SeqCst) { return; } if let Some(result) = response { let res = out.send(result); match res { Err(error::Error::ConnectionClosed) => { active_lock.store(false, atomic::Ordering::SeqCst); } Err(e) => { warn!("Error while sending response: {:?}", e); } _ => {} } } }); let future = future::select(future, poll_liveness); self.executor.spawn(future); Ok(()) } } pub struct Factory<M: core::Metadata, S: core::Middleware<M>> { session_id: SessionId, handler: Arc<core::MetaIoHandler<M, S>>, meta_extractor: Arc<dyn metadata::MetaExtractor<M>>, allowed_origins: Option<Vec<Origin>>, allowed_hosts: Option<Vec<Host>>, request_middleware: Option<Arc<dyn RequestMiddleware>>, stats: Option<Arc<dyn SessionStats>>, executor: TaskExecutor, } impl<M: core::Metadata, S: core::Middleware<M>> Factory<M, S> { pub fn new( handler: Arc<core::MetaIoHandler<M, S>>, meta_extractor: Arc<dyn metadata::MetaExtractor<M>>, allowed_origins: Option<Vec<Origin>>, allowed_hosts: Option<Vec<Host>>, request_middleware: Option<Arc<dyn RequestMiddleware>>, stats: Option<Arc<dyn SessionStats>>, executor: TaskExecutor, ) -> Self { Factory { session_id: 0, handler, meta_extractor, allowed_origins, allowed_hosts, request_middleware, stats, executor, } } } impl<M: core::Metadata, S: core::Middleware<M>> ws::Factory for Factory<M, S> where S::Future: Unpin, S::CallFuture: Unpin, { type Handler = Session<M, S>; fn connection_made(&mut self, sender: ws::Sender) -> Self::Handler { self.session_id += 1; if let Some(executor) = self.stats.as_ref() { executor.open_session(self.session_id) } let active = Arc::new(atomic::AtomicBool::new(true)); Session { active: active.clone(), context: metadata::RequestContext { session_id: self.session_id, origin: None, protocols: Vec::new(), out: metadata::Sender::new(sender, active), executor: self.executor.clone(), }, handler: self.handler.clone(), meta_extractor: self.meta_extractor.clone(), allowed_origins: self.allowed_origins.clone(), allowed_hosts: self.allowed_hosts.clone(), stats: self.stats.clone(), request_middleware: self.request_middleware.clone(), metadata: None, executor: self.executor.clone(), task_slab: Arc::new(Mutex::new(Slab::with_capacity(0))), } } } fn header_is_allowed<T>(allowed: &Option<Vec<T>>, header: Option<&[u8]>) -> bool where T: Pattern, { let header = header.map(std::str::from_utf8); match (header, allowed.as_ref()) { // Always allow if Origin/Host is not specified (None, _) => true, // Always allow if Origin/Host validation is disabled (_, None) => true, // Validate Origin (Some(Ok(val)), Some(values)) => { for v in values { if v.matches(val) { return true; } } false } // Disallow in other cases _ => false, } } fn forbidden(title: &str, message: &str) -> ws::Response { let mut forbidden = ws::Response::new(403, "Forbidden", format!("{}\n{}\n", title, message).into_bytes()); { let headers = forbidden.headers_mut(); headers.push(("Connection".to_owned(), b"close".to_vec())); } forbidden }
req.header("origin").map(|x| &x[..]) } fn verify_origin(&self, origin: Option<&[u8]>) -> Option<ws::Response> {
random_line_split
session.rs
use std::future::Future; use std::pin::Pin; use std::sync::{atomic, Arc}; use std::task::{Context, Poll}; use crate::core; use futures::channel::oneshot; use futures::future; use futures::FutureExt; use parking_lot::Mutex; use slab::Slab; use crate::server_utils::cors::Origin; use crate::server_utils::hosts::Host; use crate::server_utils::reactor::TaskExecutor; use crate::server_utils::session::{SessionId, SessionStats}; use crate::server_utils::Pattern; use crate::ws; use crate::error; use crate::metadata; /// Middleware to intercept server requests. /// You can either terminate the request (by returning a response) /// or just proceed with standard JSON-RPC handling. pub trait RequestMiddleware: Send + Sync +'static { /// Process a request and decide what to do next. fn process(&self, req: &ws::Request) -> MiddlewareAction; } impl<F> RequestMiddleware for F where F: Fn(&ws::Request) -> Option<ws::Response> + Send + Sync +'static, { fn process(&self, req: &ws::Request) -> MiddlewareAction { (*self)(req).into() } } /// Request middleware action #[derive(Debug)] pub enum MiddlewareAction { /// Proceed with standard JSON-RPC behaviour. Proceed, /// Terminate the request and return a response. Respond { /// Response to return response: ws::Response, /// Should origin be validated before returning the response? validate_origin: bool, /// Should hosts be validated before returning the response? validate_hosts: bool, }, } impl MiddlewareAction { fn should_verify_origin(&self) -> bool { use self::MiddlewareAction::*; match *self { Proceed => true, Respond { validate_origin,.. } => validate_origin, } } fn should_verify_hosts(&self) -> bool { use self::MiddlewareAction::*; match *self { Proceed => true, Respond { validate_hosts,.. } => validate_hosts, } } } impl From<Option<ws::Response>> for MiddlewareAction { fn from(opt: Option<ws::Response>) -> Self { match opt { Some(res) => MiddlewareAction::Respond { response: res, validate_origin: true, validate_hosts: true, }, None => MiddlewareAction::Proceed, } } } // the slab is only inserted into when live. type TaskSlab = Mutex<Slab<Option<oneshot::Sender<()>>>>; // future for checking session liveness. // this returns `NotReady` until the session it corresponds to is dropped. #[derive(Debug)] struct LivenessPoll { task_slab: Arc<TaskSlab>, slab_handle: usize, rx: oneshot::Receiver<()>, } impl LivenessPoll { fn create(task_slab: Arc<TaskSlab>) -> Self { const INITIAL_SIZE: usize = 4; let (index, rx) = { let mut task_slab = task_slab.lock(); if task_slab.len() == task_slab.capacity() { // grow the size if necessary. // we don't expect this to get so big as to overflow. let reserve = ::std::cmp::max(task_slab.capacity(), INITIAL_SIZE); task_slab.reserve_exact(reserve); } let (tx, rx) = oneshot::channel(); let index = task_slab.insert(Some(tx)); (index, rx) }; LivenessPoll { task_slab, slab_handle: index, rx, } } } impl Future for LivenessPoll { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = Pin::into_inner(self); // if the future resolves ok then we've been signalled to return. // it should never be cancelled, but if it was the session definitely // isn't live. match Pin::new(&mut this.rx).poll(cx) { Poll::Ready(_) => Poll::Ready(()), Poll::Pending => Poll::Pending, } } } impl Drop for LivenessPoll { fn drop(&mut self) { // remove the entry from the slab if it hasn't been destroyed yet. self.task_slab.lock().remove(self.slab_handle); } } pub struct Session<M: core::Metadata, S: core::Middleware<M>> { active: Arc<atomic::AtomicBool>, context: metadata::RequestContext, handler: Arc<core::MetaIoHandler<M, S>>, meta_extractor: Arc<dyn metadata::MetaExtractor<M>>, allowed_origins: Option<Vec<Origin>>, allowed_hosts: Option<Vec<Host>>, request_middleware: Option<Arc<dyn RequestMiddleware>>, stats: Option<Arc<dyn SessionStats>>, metadata: Option<M>, executor: TaskExecutor, task_slab: Arc<TaskSlab>, } impl<M: core::Metadata, S: core::Middleware<M>> Drop for Session<M, S> { fn drop(&mut self) { self.active.store(false, atomic::Ordering::SeqCst); if let Some(stats) = self.stats.as_ref() { stats.close_session(self.context.session_id) } // signal to all still-live tasks that the session has been dropped. for (_index, task) in self.task_slab.lock().iter_mut() { if let Some(task) = task.take() { let _ = task.send(()); } } } } impl<M: core::Metadata, S: core::Middleware<M>> Session<M, S> { fn read_origin<'a>(&self, req: &'a ws::Request) -> Option<&'a [u8]> { req.header("origin").map(|x| &x[..]) } fn verify_origin(&self, origin: Option<&[u8]>) -> Option<ws::Response> { if!header_is_allowed(&self.allowed_origins, origin) { warn!( "Blocked connection to WebSockets server from untrusted origin: {:?}", origin.and_then(|s| std::str::from_utf8(s).ok()), ); Some(forbidden("URL Blocked", "Connection Origin has been rejected.")) } else { None } } fn
(&self, req: &ws::Request) -> Option<ws::Response> { let host = req.header("host").map(|x| &x[..]); if!header_is_allowed(&self.allowed_hosts, host) { warn!( "Blocked connection to WebSockets server with untrusted host: {:?}", host.and_then(|s| std::str::from_utf8(s).ok()), ); Some(forbidden("URL Blocked", "Connection Host has been rejected.")) } else { None } } } impl<M: core::Metadata, S: core::Middleware<M>> ws::Handler for Session<M, S> where S::Future: Unpin, S::CallFuture: Unpin, { fn on_request(&mut self, req: &ws::Request) -> ws::Result<ws::Response> { // Run middleware let action = if let Some(ref middleware) = self.request_middleware { middleware.process(req) } else { MiddlewareAction::Proceed }; let origin = self.read_origin(req); if action.should_verify_origin() { // Verify request origin. if let Some(response) = self.verify_origin(origin) { return Ok(response); } } if action.should_verify_hosts() { // Verify host header. if let Some(response) = self.verify_host(req) { return Ok(response); } } self.context.origin = origin .and_then(|origin| ::std::str::from_utf8(origin).ok()) .map(Into::into); self.context.protocols = req .protocols() .ok() .map(|protos| protos.into_iter().map(Into::into).collect()) .unwrap_or_else(Vec::new); self.metadata = Some(self.meta_extractor.extract(&self.context)); match action { MiddlewareAction::Proceed => ws::Response::from_request(req).map(|mut res| { if let Some(protocol) = self.context.protocols.get(0) { res.set_protocol(protocol); } res }), MiddlewareAction::Respond { response,.. } => Ok(response), } } fn on_message(&mut self, msg: ws::Message) -> ws::Result<()> { let req = msg.as_text()?; let out = self.context.out.clone(); let metadata = self .metadata .clone() .expect("Metadata is always set in on_request; qed"); // TODO: creation requires allocating a `oneshot` channel and acquiring a // mutex. we could alternatively do this lazily upon first poll if // it becomes a bottleneck. let poll_liveness = LivenessPoll::create(self.task_slab.clone()); let active_lock = self.active.clone(); let response = self.handler.handle_request(req, metadata); let future = response.map(move |response| { if!active_lock.load(atomic::Ordering::SeqCst) { return; } if let Some(result) = response { let res = out.send(result); match res { Err(error::Error::ConnectionClosed) => { active_lock.store(false, atomic::Ordering::SeqCst); } Err(e) => { warn!("Error while sending response: {:?}", e); } _ => {} } } }); let future = future::select(future, poll_liveness); self.executor.spawn(future); Ok(()) } } pub struct Factory<M: core::Metadata, S: core::Middleware<M>> { session_id: SessionId, handler: Arc<core::MetaIoHandler<M, S>>, meta_extractor: Arc<dyn metadata::MetaExtractor<M>>, allowed_origins: Option<Vec<Origin>>, allowed_hosts: Option<Vec<Host>>, request_middleware: Option<Arc<dyn RequestMiddleware>>, stats: Option<Arc<dyn SessionStats>>, executor: TaskExecutor, } impl<M: core::Metadata, S: core::Middleware<M>> Factory<M, S> { pub fn new( handler: Arc<core::MetaIoHandler<M, S>>, meta_extractor: Arc<dyn metadata::MetaExtractor<M>>, allowed_origins: Option<Vec<Origin>>, allowed_hosts: Option<Vec<Host>>, request_middleware: Option<Arc<dyn RequestMiddleware>>, stats: Option<Arc<dyn SessionStats>>, executor: TaskExecutor, ) -> Self { Factory { session_id: 0, handler, meta_extractor, allowed_origins, allowed_hosts, request_middleware, stats, executor, } } } impl<M: core::Metadata, S: core::Middleware<M>> ws::Factory for Factory<M, S> where S::Future: Unpin, S::CallFuture: Unpin, { type Handler = Session<M, S>; fn connection_made(&mut self, sender: ws::Sender) -> Self::Handler { self.session_id += 1; if let Some(executor) = self.stats.as_ref() { executor.open_session(self.session_id) } let active = Arc::new(atomic::AtomicBool::new(true)); Session { active: active.clone(), context: metadata::RequestContext { session_id: self.session_id, origin: None, protocols: Vec::new(), out: metadata::Sender::new(sender, active), executor: self.executor.clone(), }, handler: self.handler.clone(), meta_extractor: self.meta_extractor.clone(), allowed_origins: self.allowed_origins.clone(), allowed_hosts: self.allowed_hosts.clone(), stats: self.stats.clone(), request_middleware: self.request_middleware.clone(), metadata: None, executor: self.executor.clone(), task_slab: Arc::new(Mutex::new(Slab::with_capacity(0))), } } } fn header_is_allowed<T>(allowed: &Option<Vec<T>>, header: Option<&[u8]>) -> bool where T: Pattern, { let header = header.map(std::str::from_utf8); match (header, allowed.as_ref()) { // Always allow if Origin/Host is not specified (None, _) => true, // Always allow if Origin/Host validation is disabled (_, None) => true, // Validate Origin (Some(Ok(val)), Some(values)) => { for v in values { if v.matches(val) { return true; } } false } // Disallow in other cases _ => false, } } fn forbidden(title: &str, message: &str) -> ws::Response { let mut forbidden = ws::Response::new(403, "Forbidden", format!("{}\n{}\n", title, message).into_bytes()); { let headers = forbidden.headers_mut(); headers.push(("Connection".to_owned(), b"close".to_vec())); } forbidden }
verify_host
identifier_name
session.rs
use std::future::Future; use std::pin::Pin; use std::sync::{atomic, Arc}; use std::task::{Context, Poll}; use crate::core; use futures::channel::oneshot; use futures::future; use futures::FutureExt; use parking_lot::Mutex; use slab::Slab; use crate::server_utils::cors::Origin; use crate::server_utils::hosts::Host; use crate::server_utils::reactor::TaskExecutor; use crate::server_utils::session::{SessionId, SessionStats}; use crate::server_utils::Pattern; use crate::ws; use crate::error; use crate::metadata; /// Middleware to intercept server requests. /// You can either terminate the request (by returning a response) /// or just proceed with standard JSON-RPC handling. pub trait RequestMiddleware: Send + Sync +'static { /// Process a request and decide what to do next. fn process(&self, req: &ws::Request) -> MiddlewareAction; } impl<F> RequestMiddleware for F where F: Fn(&ws::Request) -> Option<ws::Response> + Send + Sync +'static, { fn process(&self, req: &ws::Request) -> MiddlewareAction { (*self)(req).into() } } /// Request middleware action #[derive(Debug)] pub enum MiddlewareAction { /// Proceed with standard JSON-RPC behaviour. Proceed, /// Terminate the request and return a response. Respond { /// Response to return response: ws::Response, /// Should origin be validated before returning the response? validate_origin: bool, /// Should hosts be validated before returning the response? validate_hosts: bool, }, } impl MiddlewareAction { fn should_verify_origin(&self) -> bool { use self::MiddlewareAction::*; match *self { Proceed => true, Respond { validate_origin,.. } => validate_origin, } } fn should_verify_hosts(&self) -> bool { use self::MiddlewareAction::*; match *self { Proceed => true, Respond { validate_hosts,.. } => validate_hosts, } } } impl From<Option<ws::Response>> for MiddlewareAction { fn from(opt: Option<ws::Response>) -> Self { match opt { Some(res) => MiddlewareAction::Respond { response: res, validate_origin: true, validate_hosts: true, }, None => MiddlewareAction::Proceed, } } } // the slab is only inserted into when live. type TaskSlab = Mutex<Slab<Option<oneshot::Sender<()>>>>; // future for checking session liveness. // this returns `NotReady` until the session it corresponds to is dropped. #[derive(Debug)] struct LivenessPoll { task_slab: Arc<TaskSlab>, slab_handle: usize, rx: oneshot::Receiver<()>, } impl LivenessPoll { fn create(task_slab: Arc<TaskSlab>) -> Self { const INITIAL_SIZE: usize = 4; let (index, rx) = { let mut task_slab = task_slab.lock(); if task_slab.len() == task_slab.capacity() { // grow the size if necessary. // we don't expect this to get so big as to overflow. let reserve = ::std::cmp::max(task_slab.capacity(), INITIAL_SIZE); task_slab.reserve_exact(reserve); } let (tx, rx) = oneshot::channel(); let index = task_slab.insert(Some(tx)); (index, rx) }; LivenessPoll { task_slab, slab_handle: index, rx, } } } impl Future for LivenessPoll { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = Pin::into_inner(self); // if the future resolves ok then we've been signalled to return. // it should never be cancelled, but if it was the session definitely // isn't live. match Pin::new(&mut this.rx).poll(cx) { Poll::Ready(_) => Poll::Ready(()), Poll::Pending => Poll::Pending, } } } impl Drop for LivenessPoll { fn drop(&mut self) { // remove the entry from the slab if it hasn't been destroyed yet. self.task_slab.lock().remove(self.slab_handle); } } pub struct Session<M: core::Metadata, S: core::Middleware<M>> { active: Arc<atomic::AtomicBool>, context: metadata::RequestContext, handler: Arc<core::MetaIoHandler<M, S>>, meta_extractor: Arc<dyn metadata::MetaExtractor<M>>, allowed_origins: Option<Vec<Origin>>, allowed_hosts: Option<Vec<Host>>, request_middleware: Option<Arc<dyn RequestMiddleware>>, stats: Option<Arc<dyn SessionStats>>, metadata: Option<M>, executor: TaskExecutor, task_slab: Arc<TaskSlab>, } impl<M: core::Metadata, S: core::Middleware<M>> Drop for Session<M, S> { fn drop(&mut self) { self.active.store(false, atomic::Ordering::SeqCst); if let Some(stats) = self.stats.as_ref() { stats.close_session(self.context.session_id) } // signal to all still-live tasks that the session has been dropped. for (_index, task) in self.task_slab.lock().iter_mut() { if let Some(task) = task.take() { let _ = task.send(()); } } } } impl<M: core::Metadata, S: core::Middleware<M>> Session<M, S> { fn read_origin<'a>(&self, req: &'a ws::Request) -> Option<&'a [u8]> { req.header("origin").map(|x| &x[..]) } fn verify_origin(&self, origin: Option<&[u8]>) -> Option<ws::Response> { if!header_is_allowed(&self.allowed_origins, origin) { warn!( "Blocked connection to WebSockets server from untrusted origin: {:?}", origin.and_then(|s| std::str::from_utf8(s).ok()), ); Some(forbidden("URL Blocked", "Connection Origin has been rejected.")) } else { None } } fn verify_host(&self, req: &ws::Request) -> Option<ws::Response> { let host = req.header("host").map(|x| &x[..]); if!header_is_allowed(&self.allowed_hosts, host) { warn!( "Blocked connection to WebSockets server with untrusted host: {:?}", host.and_then(|s| std::str::from_utf8(s).ok()), ); Some(forbidden("URL Blocked", "Connection Host has been rejected.")) } else { None } } } impl<M: core::Metadata, S: core::Middleware<M>> ws::Handler for Session<M, S> where S::Future: Unpin, S::CallFuture: Unpin, { fn on_request(&mut self, req: &ws::Request) -> ws::Result<ws::Response> { // Run middleware let action = if let Some(ref middleware) = self.request_middleware { middleware.process(req) } else { MiddlewareAction::Proceed }; let origin = self.read_origin(req); if action.should_verify_origin() { // Verify request origin. if let Some(response) = self.verify_origin(origin) { return Ok(response); } } if action.should_verify_hosts() { // Verify host header. if let Some(response) = self.verify_host(req) { return Ok(response); } } self.context.origin = origin .and_then(|origin| ::std::str::from_utf8(origin).ok()) .map(Into::into); self.context.protocols = req .protocols() .ok() .map(|protos| protos.into_iter().map(Into::into).collect()) .unwrap_or_else(Vec::new); self.metadata = Some(self.meta_extractor.extract(&self.context)); match action { MiddlewareAction::Proceed => ws::Response::from_request(req).map(|mut res| { if let Some(protocol) = self.context.protocols.get(0) { res.set_protocol(protocol); } res }), MiddlewareAction::Respond { response,.. } => Ok(response), } } fn on_message(&mut self, msg: ws::Message) -> ws::Result<()> { let req = msg.as_text()?; let out = self.context.out.clone(); let metadata = self .metadata .clone() .expect("Metadata is always set in on_request; qed"); // TODO: creation requires allocating a `oneshot` channel and acquiring a // mutex. we could alternatively do this lazily upon first poll if // it becomes a bottleneck. let poll_liveness = LivenessPoll::create(self.task_slab.clone()); let active_lock = self.active.clone(); let response = self.handler.handle_request(req, metadata); let future = response.map(move |response| { if!active_lock.load(atomic::Ordering::SeqCst) { return; } if let Some(result) = response { let res = out.send(result); match res { Err(error::Error::ConnectionClosed) => { active_lock.store(false, atomic::Ordering::SeqCst); } Err(e) => { warn!("Error while sending response: {:?}", e); } _ => {} } } }); let future = future::select(future, poll_liveness); self.executor.spawn(future); Ok(()) } } pub struct Factory<M: core::Metadata, S: core::Middleware<M>> { session_id: SessionId, handler: Arc<core::MetaIoHandler<M, S>>, meta_extractor: Arc<dyn metadata::MetaExtractor<M>>, allowed_origins: Option<Vec<Origin>>, allowed_hosts: Option<Vec<Host>>, request_middleware: Option<Arc<dyn RequestMiddleware>>, stats: Option<Arc<dyn SessionStats>>, executor: TaskExecutor, } impl<M: core::Metadata, S: core::Middleware<M>> Factory<M, S> { pub fn new( handler: Arc<core::MetaIoHandler<M, S>>, meta_extractor: Arc<dyn metadata::MetaExtractor<M>>, allowed_origins: Option<Vec<Origin>>, allowed_hosts: Option<Vec<Host>>, request_middleware: Option<Arc<dyn RequestMiddleware>>, stats: Option<Arc<dyn SessionStats>>, executor: TaskExecutor, ) -> Self { Factory { session_id: 0, handler, meta_extractor, allowed_origins, allowed_hosts, request_middleware, stats, executor, } } } impl<M: core::Metadata, S: core::Middleware<M>> ws::Factory for Factory<M, S> where S::Future: Unpin, S::CallFuture: Unpin, { type Handler = Session<M, S>; fn connection_made(&mut self, sender: ws::Sender) -> Self::Handler { self.session_id += 1; if let Some(executor) = self.stats.as_ref() { executor.open_session(self.session_id) } let active = Arc::new(atomic::AtomicBool::new(true)); Session { active: active.clone(), context: metadata::RequestContext { session_id: self.session_id, origin: None, protocols: Vec::new(), out: metadata::Sender::new(sender, active), executor: self.executor.clone(), }, handler: self.handler.clone(), meta_extractor: self.meta_extractor.clone(), allowed_origins: self.allowed_origins.clone(), allowed_hosts: self.allowed_hosts.clone(), stats: self.stats.clone(), request_middleware: self.request_middleware.clone(), metadata: None, executor: self.executor.clone(), task_slab: Arc::new(Mutex::new(Slab::with_capacity(0))), } } } fn header_is_allowed<T>(allowed: &Option<Vec<T>>, header: Option<&[u8]>) -> bool where T: Pattern, { let header = header.map(std::str::from_utf8); match (header, allowed.as_ref()) { // Always allow if Origin/Host is not specified (None, _) => true, // Always allow if Origin/Host validation is disabled (_, None) => true, // Validate Origin (Some(Ok(val)), Some(values)) =>
// Disallow in other cases _ => false, } } fn forbidden(title: &str, message: &str) -> ws::Response { let mut forbidden = ws::Response::new(403, "Forbidden", format!("{}\n{}\n", title, message).into_bytes()); { let headers = forbidden.headers_mut(); headers.push(("Connection".to_owned(), b"close".to_vec())); } forbidden }
{ for v in values { if v.matches(val) { return true; } } false }
conditional_block
session.rs
use std::future::Future; use std::pin::Pin; use std::sync::{atomic, Arc}; use std::task::{Context, Poll}; use crate::core; use futures::channel::oneshot; use futures::future; use futures::FutureExt; use parking_lot::Mutex; use slab::Slab; use crate::server_utils::cors::Origin; use crate::server_utils::hosts::Host; use crate::server_utils::reactor::TaskExecutor; use crate::server_utils::session::{SessionId, SessionStats}; use crate::server_utils::Pattern; use crate::ws; use crate::error; use crate::metadata; /// Middleware to intercept server requests. /// You can either terminate the request (by returning a response) /// or just proceed with standard JSON-RPC handling. pub trait RequestMiddleware: Send + Sync +'static { /// Process a request and decide what to do next. fn process(&self, req: &ws::Request) -> MiddlewareAction; } impl<F> RequestMiddleware for F where F: Fn(&ws::Request) -> Option<ws::Response> + Send + Sync +'static, { fn process(&self, req: &ws::Request) -> MiddlewareAction { (*self)(req).into() } } /// Request middleware action #[derive(Debug)] pub enum MiddlewareAction { /// Proceed with standard JSON-RPC behaviour. Proceed, /// Terminate the request and return a response. Respond { /// Response to return response: ws::Response, /// Should origin be validated before returning the response? validate_origin: bool, /// Should hosts be validated before returning the response? validate_hosts: bool, }, } impl MiddlewareAction { fn should_verify_origin(&self) -> bool { use self::MiddlewareAction::*; match *self { Proceed => true, Respond { validate_origin,.. } => validate_origin, } } fn should_verify_hosts(&self) -> bool { use self::MiddlewareAction::*; match *self { Proceed => true, Respond { validate_hosts,.. } => validate_hosts, } } } impl From<Option<ws::Response>> for MiddlewareAction { fn from(opt: Option<ws::Response>) -> Self { match opt { Some(res) => MiddlewareAction::Respond { response: res, validate_origin: true, validate_hosts: true, }, None => MiddlewareAction::Proceed, } } } // the slab is only inserted into when live. type TaskSlab = Mutex<Slab<Option<oneshot::Sender<()>>>>; // future for checking session liveness. // this returns `NotReady` until the session it corresponds to is dropped. #[derive(Debug)] struct LivenessPoll { task_slab: Arc<TaskSlab>, slab_handle: usize, rx: oneshot::Receiver<()>, } impl LivenessPoll { fn create(task_slab: Arc<TaskSlab>) -> Self { const INITIAL_SIZE: usize = 4; let (index, rx) = { let mut task_slab = task_slab.lock(); if task_slab.len() == task_slab.capacity() { // grow the size if necessary. // we don't expect this to get so big as to overflow. let reserve = ::std::cmp::max(task_slab.capacity(), INITIAL_SIZE); task_slab.reserve_exact(reserve); } let (tx, rx) = oneshot::channel(); let index = task_slab.insert(Some(tx)); (index, rx) }; LivenessPoll { task_slab, slab_handle: index, rx, } } } impl Future for LivenessPoll { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = Pin::into_inner(self); // if the future resolves ok then we've been signalled to return. // it should never be cancelled, but if it was the session definitely // isn't live. match Pin::new(&mut this.rx).poll(cx) { Poll::Ready(_) => Poll::Ready(()), Poll::Pending => Poll::Pending, } } } impl Drop for LivenessPoll { fn drop(&mut self) { // remove the entry from the slab if it hasn't been destroyed yet. self.task_slab.lock().remove(self.slab_handle); } } pub struct Session<M: core::Metadata, S: core::Middleware<M>> { active: Arc<atomic::AtomicBool>, context: metadata::RequestContext, handler: Arc<core::MetaIoHandler<M, S>>, meta_extractor: Arc<dyn metadata::MetaExtractor<M>>, allowed_origins: Option<Vec<Origin>>, allowed_hosts: Option<Vec<Host>>, request_middleware: Option<Arc<dyn RequestMiddleware>>, stats: Option<Arc<dyn SessionStats>>, metadata: Option<M>, executor: TaskExecutor, task_slab: Arc<TaskSlab>, } impl<M: core::Metadata, S: core::Middleware<M>> Drop for Session<M, S> { fn drop(&mut self) { self.active.store(false, atomic::Ordering::SeqCst); if let Some(stats) = self.stats.as_ref() { stats.close_session(self.context.session_id) } // signal to all still-live tasks that the session has been dropped. for (_index, task) in self.task_slab.lock().iter_mut() { if let Some(task) = task.take() { let _ = task.send(()); } } } } impl<M: core::Metadata, S: core::Middleware<M>> Session<M, S> { fn read_origin<'a>(&self, req: &'a ws::Request) -> Option<&'a [u8]> { req.header("origin").map(|x| &x[..]) } fn verify_origin(&self, origin: Option<&[u8]>) -> Option<ws::Response> { if!header_is_allowed(&self.allowed_origins, origin) { warn!( "Blocked connection to WebSockets server from untrusted origin: {:?}", origin.and_then(|s| std::str::from_utf8(s).ok()), ); Some(forbidden("URL Blocked", "Connection Origin has been rejected.")) } else { None } } fn verify_host(&self, req: &ws::Request) -> Option<ws::Response> { let host = req.header("host").map(|x| &x[..]); if!header_is_allowed(&self.allowed_hosts, host) { warn!( "Blocked connection to WebSockets server with untrusted host: {:?}", host.and_then(|s| std::str::from_utf8(s).ok()), ); Some(forbidden("URL Blocked", "Connection Host has been rejected.")) } else { None } } } impl<M: core::Metadata, S: core::Middleware<M>> ws::Handler for Session<M, S> where S::Future: Unpin, S::CallFuture: Unpin, { fn on_request(&mut self, req: &ws::Request) -> ws::Result<ws::Response> { // Run middleware let action = if let Some(ref middleware) = self.request_middleware { middleware.process(req) } else { MiddlewareAction::Proceed }; let origin = self.read_origin(req); if action.should_verify_origin() { // Verify request origin. if let Some(response) = self.verify_origin(origin) { return Ok(response); } } if action.should_verify_hosts() { // Verify host header. if let Some(response) = self.verify_host(req) { return Ok(response); } } self.context.origin = origin .and_then(|origin| ::std::str::from_utf8(origin).ok()) .map(Into::into); self.context.protocols = req .protocols() .ok() .map(|protos| protos.into_iter().map(Into::into).collect()) .unwrap_or_else(Vec::new); self.metadata = Some(self.meta_extractor.extract(&self.context)); match action { MiddlewareAction::Proceed => ws::Response::from_request(req).map(|mut res| { if let Some(protocol) = self.context.protocols.get(0) { res.set_protocol(protocol); } res }), MiddlewareAction::Respond { response,.. } => Ok(response), } } fn on_message(&mut self, msg: ws::Message) -> ws::Result<()> { let req = msg.as_text()?; let out = self.context.out.clone(); let metadata = self .metadata .clone() .expect("Metadata is always set in on_request; qed"); // TODO: creation requires allocating a `oneshot` channel and acquiring a // mutex. we could alternatively do this lazily upon first poll if // it becomes a bottleneck. let poll_liveness = LivenessPoll::create(self.task_slab.clone()); let active_lock = self.active.clone(); let response = self.handler.handle_request(req, metadata); let future = response.map(move |response| { if!active_lock.load(atomic::Ordering::SeqCst) { return; } if let Some(result) = response { let res = out.send(result); match res { Err(error::Error::ConnectionClosed) => { active_lock.store(false, atomic::Ordering::SeqCst); } Err(e) => { warn!("Error while sending response: {:?}", e); } _ => {} } } }); let future = future::select(future, poll_liveness); self.executor.spawn(future); Ok(()) } } pub struct Factory<M: core::Metadata, S: core::Middleware<M>> { session_id: SessionId, handler: Arc<core::MetaIoHandler<M, S>>, meta_extractor: Arc<dyn metadata::MetaExtractor<M>>, allowed_origins: Option<Vec<Origin>>, allowed_hosts: Option<Vec<Host>>, request_middleware: Option<Arc<dyn RequestMiddleware>>, stats: Option<Arc<dyn SessionStats>>, executor: TaskExecutor, } impl<M: core::Metadata, S: core::Middleware<M>> Factory<M, S> { pub fn new( handler: Arc<core::MetaIoHandler<M, S>>, meta_extractor: Arc<dyn metadata::MetaExtractor<M>>, allowed_origins: Option<Vec<Origin>>, allowed_hosts: Option<Vec<Host>>, request_middleware: Option<Arc<dyn RequestMiddleware>>, stats: Option<Arc<dyn SessionStats>>, executor: TaskExecutor, ) -> Self { Factory { session_id: 0, handler, meta_extractor, allowed_origins, allowed_hosts, request_middleware, stats, executor, } } } impl<M: core::Metadata, S: core::Middleware<M>> ws::Factory for Factory<M, S> where S::Future: Unpin, S::CallFuture: Unpin, { type Handler = Session<M, S>; fn connection_made(&mut self, sender: ws::Sender) -> Self::Handler { self.session_id += 1; if let Some(executor) = self.stats.as_ref() { executor.open_session(self.session_id) } let active = Arc::new(atomic::AtomicBool::new(true)); Session { active: active.clone(), context: metadata::RequestContext { session_id: self.session_id, origin: None, protocols: Vec::new(), out: metadata::Sender::new(sender, active), executor: self.executor.clone(), }, handler: self.handler.clone(), meta_extractor: self.meta_extractor.clone(), allowed_origins: self.allowed_origins.clone(), allowed_hosts: self.allowed_hosts.clone(), stats: self.stats.clone(), request_middleware: self.request_middleware.clone(), metadata: None, executor: self.executor.clone(), task_slab: Arc::new(Mutex::new(Slab::with_capacity(0))), } } } fn header_is_allowed<T>(allowed: &Option<Vec<T>>, header: Option<&[u8]>) -> bool where T: Pattern, { let header = header.map(std::str::from_utf8); match (header, allowed.as_ref()) { // Always allow if Origin/Host is not specified (None, _) => true, // Always allow if Origin/Host validation is disabled (_, None) => true, // Validate Origin (Some(Ok(val)), Some(values)) => { for v in values { if v.matches(val) { return true; } } false } // Disallow in other cases _ => false, } } fn forbidden(title: &str, message: &str) -> ws::Response
{ let mut forbidden = ws::Response::new(403, "Forbidden", format!("{}\n{}\n", title, message).into_bytes()); { let headers = forbidden.headers_mut(); headers.push(("Connection".to_owned(), b"close".to_vec())); } forbidden }
identifier_body
mod.rs
use std::fs; use std::path; use std::io::Read; use serialize::json; use valico::json_schema; fn visit_specs<F>(dir: &path::Path, cb: F) where F: Fn(&path::Path, json::Json) { let contents = fs::read_dir(dir).ok().unwrap(); for entry in contents { let path = entry.unwrap().path(); match fs::File::open(&path) { Err(_) => continue, Ok(mut file) => { let metadata = file.metadata().unwrap(); if metadata.is_file() { let mut content = String::new(); file.read_to_string(&mut content).ok().unwrap(); let json: json::Json = content.parse().unwrap(); cb(&path, json); } } } } } #[test] fn test_suite() { let mut content = String::new(); fs::File::open(&path::Path::new("tests/schema/schema.json")).ok().unwrap() .read_to_string(&mut content).ok().unwrap();
let spec_set = spec_set.as_array().unwrap(); let exceptions: Vec<(String, String)> = vec![ ("maxLength.json".to_string(), "two supplementary Unicode code points is long enough".to_string()), ("minLength.json".to_string(), "one supplementary Unicode code point is not long enough".to_string()), ("refRemote.json".to_string(), "remote ref invalid".to_string()), ("refRemote.json".to_string(), "remote fragment invalid".to_string()), ("refRemote.json".to_string(), "ref within ref invalid".to_string()), ("refRemote.json".to_string(), "changed scope ref invalid".to_string()), ]; for spec in spec_set.iter() { let spec = spec.as_object().unwrap(); let mut scope = json_schema::Scope::new(); scope.compile(json_v4_schema.clone(), true).ok().unwrap(); let schema = match scope.compile_and_return(spec.get("schema").unwrap().clone(), false) { Ok(schema) => schema, Err(err) => panic!("Error in schema {} {}: {:?}", path.file_name().unwrap().to_str().unwrap(), spec.get("description").unwrap().as_string().unwrap(), err ) }; let tests = spec.get("tests").unwrap().as_array().unwrap(); for test in tests.iter() { let test = test.as_object().unwrap(); let description = test.get("description").unwrap().as_string().unwrap(); let data = test.get("data").unwrap(); let valid = test.get("valid").unwrap().as_boolean().unwrap(); let state = schema.validate(&data); if state.is_valid()!= valid { if!&exceptions[..].contains(&(path.file_name().unwrap().to_str().unwrap().to_string(), description.to_string())) { panic!("Failure: \"{}\" in {}", path.file_name().unwrap().to_str().unwrap(), description.to_string()); } } else { println!("test json_schema::test_suite -> {}.. ok", description); } } } }) }
let json_v4_schema: json::Json = content.parse().unwrap(); visit_specs(&path::Path::new("tests/schema/JSON-Schema-Test-Suite/tests/draft4"), |path, spec_set: json::Json| {
random_line_split
mod.rs
use std::fs; use std::path; use std::io::Read; use serialize::json; use valico::json_schema; fn visit_specs<F>(dir: &path::Path, cb: F) where F: Fn(&path::Path, json::Json) { let contents = fs::read_dir(dir).ok().unwrap(); for entry in contents { let path = entry.unwrap().path(); match fs::File::open(&path) { Err(_) => continue, Ok(mut file) => { let metadata = file.metadata().unwrap(); if metadata.is_file() { let mut content = String::new(); file.read_to_string(&mut content).ok().unwrap(); let json: json::Json = content.parse().unwrap(); cb(&path, json); } } } } } #[test] fn
() { let mut content = String::new(); fs::File::open(&path::Path::new("tests/schema/schema.json")).ok().unwrap() .read_to_string(&mut content).ok().unwrap(); let json_v4_schema: json::Json = content.parse().unwrap(); visit_specs(&path::Path::new("tests/schema/JSON-Schema-Test-Suite/tests/draft4"), |path, spec_set: json::Json| { let spec_set = spec_set.as_array().unwrap(); let exceptions: Vec<(String, String)> = vec![ ("maxLength.json".to_string(), "two supplementary Unicode code points is long enough".to_string()), ("minLength.json".to_string(), "one supplementary Unicode code point is not long enough".to_string()), ("refRemote.json".to_string(), "remote ref invalid".to_string()), ("refRemote.json".to_string(), "remote fragment invalid".to_string()), ("refRemote.json".to_string(), "ref within ref invalid".to_string()), ("refRemote.json".to_string(), "changed scope ref invalid".to_string()), ]; for spec in spec_set.iter() { let spec = spec.as_object().unwrap(); let mut scope = json_schema::Scope::new(); scope.compile(json_v4_schema.clone(), true).ok().unwrap(); let schema = match scope.compile_and_return(spec.get("schema").unwrap().clone(), false) { Ok(schema) => schema, Err(err) => panic!("Error in schema {} {}: {:?}", path.file_name().unwrap().to_str().unwrap(), spec.get("description").unwrap().as_string().unwrap(), err ) }; let tests = spec.get("tests").unwrap().as_array().unwrap(); for test in tests.iter() { let test = test.as_object().unwrap(); let description = test.get("description").unwrap().as_string().unwrap(); let data = test.get("data").unwrap(); let valid = test.get("valid").unwrap().as_boolean().unwrap(); let state = schema.validate(&data); if state.is_valid()!= valid { if!&exceptions[..].contains(&(path.file_name().unwrap().to_str().unwrap().to_string(), description.to_string())) { panic!("Failure: \"{}\" in {}", path.file_name().unwrap().to_str().unwrap(), description.to_string()); } } else { println!("test json_schema::test_suite -> {}.. ok", description); } } } }) }
test_suite
identifier_name
mod.rs
use std::fs; use std::path; use std::io::Read; use serialize::json; use valico::json_schema; fn visit_specs<F>(dir: &path::Path, cb: F) where F: Fn(&path::Path, json::Json)
#[test] fn test_suite() { let mut content = String::new(); fs::File::open(&path::Path::new("tests/schema/schema.json")).ok().unwrap() .read_to_string(&mut content).ok().unwrap(); let json_v4_schema: json::Json = content.parse().unwrap(); visit_specs(&path::Path::new("tests/schema/JSON-Schema-Test-Suite/tests/draft4"), |path, spec_set: json::Json| { let spec_set = spec_set.as_array().unwrap(); let exceptions: Vec<(String, String)> = vec![ ("maxLength.json".to_string(), "two supplementary Unicode code points is long enough".to_string()), ("minLength.json".to_string(), "one supplementary Unicode code point is not long enough".to_string()), ("refRemote.json".to_string(), "remote ref invalid".to_string()), ("refRemote.json".to_string(), "remote fragment invalid".to_string()), ("refRemote.json".to_string(), "ref within ref invalid".to_string()), ("refRemote.json".to_string(), "changed scope ref invalid".to_string()), ]; for spec in spec_set.iter() { let spec = spec.as_object().unwrap(); let mut scope = json_schema::Scope::new(); scope.compile(json_v4_schema.clone(), true).ok().unwrap(); let schema = match scope.compile_and_return(spec.get("schema").unwrap().clone(), false) { Ok(schema) => schema, Err(err) => panic!("Error in schema {} {}: {:?}", path.file_name().unwrap().to_str().unwrap(), spec.get("description").unwrap().as_string().unwrap(), err ) }; let tests = spec.get("tests").unwrap().as_array().unwrap(); for test in tests.iter() { let test = test.as_object().unwrap(); let description = test.get("description").unwrap().as_string().unwrap(); let data = test.get("data").unwrap(); let valid = test.get("valid").unwrap().as_boolean().unwrap(); let state = schema.validate(&data); if state.is_valid()!= valid { if!&exceptions[..].contains(&(path.file_name().unwrap().to_str().unwrap().to_string(), description.to_string())) { panic!("Failure: \"{}\" in {}", path.file_name().unwrap().to_str().unwrap(), description.to_string()); } } else { println!("test json_schema::test_suite -> {}.. ok", description); } } } }) }
{ let contents = fs::read_dir(dir).ok().unwrap(); for entry in contents { let path = entry.unwrap().path(); match fs::File::open(&path) { Err(_) => continue, Ok(mut file) => { let metadata = file.metadata().unwrap(); if metadata.is_file() { let mut content = String::new(); file.read_to_string(&mut content).ok().unwrap(); let json: json::Json = content.parse().unwrap(); cb(&path, json); } } } } }
identifier_body
cliente.rs
use std::cmp::{Ordering, min}; use std::fs::File; use std::io::{BufWriter, Write, Read}; use chrono::{DateTime, NaiveDateTime, Utc}; use serializable::Serializable; use serializable::SerializeError; use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian}; #[derive(Debug, Clone)] pub struct Cliente { pub codigo: u32, pub nome: String, // 50 bytes of utf-8 in the file pub data_nascimento: DateTime<Utc>, } impl PartialEq for Cliente { fn eq(&self, other: &Cliente) -> bool { self.codigo == other.codigo } } impl PartialOrd for Cliente { fn partial_cmp(&self, other: &Cliente) -> Option<Ordering> { Some(self.codigo.cmp(&other.codigo)) } } impl Serializable for Cliente { fn
(&self, file: &mut File) -> Result<(), SerializeError> { let mut file = BufWriter::new(file); if self.codigo == 3763629520 { println!("entra aqui arrombado"); } file.write_u32::<BigEndian>(self.codigo)?; let bytes = self.nome.as_bytes(); let boundary = min(50, bytes.len()); let diff = 50 - boundary; file.write_all(&bytes[..boundary])?; for _ in 0..diff { file.write_u8(0)?; } file.write_i64::<BigEndian>(self.data_nascimento.timestamp())?; Ok(()) } fn deserialize(file: &mut File) -> Result<Cliente, SerializeError> { let codigo = file.read_u32::<BigEndian>()?; let mut nome = [0; 50]; file.read_exact(&mut nome)?; let nul_pos = nome.iter().position(|&c| c == b'\0').unwrap_or(nome.len()); let nome = String::from_utf8(nome[..nul_pos].to_vec())?; let data_nascimento = file.read_i64::<BigEndian>()?; let data_nascimento = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(data_nascimento, 0), Utc); Ok(Cliente {codigo, nome, data_nascimento}) } }
serialize
identifier_name
cliente.rs
use std::cmp::{Ordering, min}; use std::fs::File; use std::io::{BufWriter, Write, Read}; use chrono::{DateTime, NaiveDateTime, Utc}; use serializable::Serializable; use serializable::SerializeError; use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian}; #[derive(Debug, Clone)] pub struct Cliente { pub codigo: u32, pub nome: String, // 50 bytes of utf-8 in the file pub data_nascimento: DateTime<Utc>, } impl PartialEq for Cliente { fn eq(&self, other: &Cliente) -> bool { self.codigo == other.codigo } } impl PartialOrd for Cliente { fn partial_cmp(&self, other: &Cliente) -> Option<Ordering> { Some(self.codigo.cmp(&other.codigo)) } } impl Serializable for Cliente { fn serialize(&self, file: &mut File) -> Result<(), SerializeError> { let mut file = BufWriter::new(file); if self.codigo == 3763629520 { println!("entra aqui arrombado"); } file.write_u32::<BigEndian>(self.codigo)?; let bytes = self.nome.as_bytes(); let boundary = min(50, bytes.len()); let diff = 50 - boundary; file.write_all(&bytes[..boundary])?; for _ in 0..diff { file.write_u8(0)?; } file.write_i64::<BigEndian>(self.data_nascimento.timestamp())?; Ok(()) } fn deserialize(file: &mut File) -> Result<Cliente, SerializeError>
}
{ let codigo = file.read_u32::<BigEndian>()?; let mut nome = [0; 50]; file.read_exact(&mut nome)?; let nul_pos = nome.iter().position(|&c| c == b'\0').unwrap_or(nome.len()); let nome = String::from_utf8(nome[..nul_pos].to_vec())?; let data_nascimento = file.read_i64::<BigEndian>()?; let data_nascimento = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(data_nascimento, 0), Utc); Ok(Cliente {codigo, nome, data_nascimento}) }
identifier_body
cliente.rs
use std::cmp::{Ordering, min}; use std::fs::File; use std::io::{BufWriter, Write, Read}; use chrono::{DateTime, NaiveDateTime, Utc}; use serializable::Serializable; use serializable::SerializeError; use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian}; #[derive(Debug, Clone)] pub struct Cliente { pub codigo: u32, pub nome: String, // 50 bytes of utf-8 in the file pub data_nascimento: DateTime<Utc>, } impl PartialEq for Cliente { fn eq(&self, other: &Cliente) -> bool { self.codigo == other.codigo } } impl PartialOrd for Cliente { fn partial_cmp(&self, other: &Cliente) -> Option<Ordering> { Some(self.codigo.cmp(&other.codigo)) } } impl Serializable for Cliente { fn serialize(&self, file: &mut File) -> Result<(), SerializeError> { let mut file = BufWriter::new(file); if self.codigo == 3763629520
file.write_u32::<BigEndian>(self.codigo)?; let bytes = self.nome.as_bytes(); let boundary = min(50, bytes.len()); let diff = 50 - boundary; file.write_all(&bytes[..boundary])?; for _ in 0..diff { file.write_u8(0)?; } file.write_i64::<BigEndian>(self.data_nascimento.timestamp())?; Ok(()) } fn deserialize(file: &mut File) -> Result<Cliente, SerializeError> { let codigo = file.read_u32::<BigEndian>()?; let mut nome = [0; 50]; file.read_exact(&mut nome)?; let nul_pos = nome.iter().position(|&c| c == b'\0').unwrap_or(nome.len()); let nome = String::from_utf8(nome[..nul_pos].to_vec())?; let data_nascimento = file.read_i64::<BigEndian>()?; let data_nascimento = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(data_nascimento, 0), Utc); Ok(Cliente {codigo, nome, data_nascimento}) } }
{ println!("entra aqui arrombado"); }
conditional_block
cliente.rs
use std::cmp::{Ordering, min}; use std::fs::File; use std::io::{BufWriter, Write, Read}; use chrono::{DateTime, NaiveDateTime, Utc}; use serializable::Serializable; use serializable::SerializeError; use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian}; #[derive(Debug, Clone)] pub struct Cliente { pub codigo: u32, pub nome: String, // 50 bytes of utf-8 in the file pub data_nascimento: DateTime<Utc>, } impl PartialEq for Cliente { fn eq(&self, other: &Cliente) -> bool { self.codigo == other.codigo } } impl PartialOrd for Cliente { fn partial_cmp(&self, other: &Cliente) -> Option<Ordering> { Some(self.codigo.cmp(&other.codigo)) } } impl Serializable for Cliente { fn serialize(&self, file: &mut File) -> Result<(), SerializeError> { let mut file = BufWriter::new(file); if self.codigo == 3763629520 { println!("entra aqui arrombado"); } file.write_u32::<BigEndian>(self.codigo)?; let bytes = self.nome.as_bytes();
let boundary = min(50, bytes.len()); let diff = 50 - boundary; file.write_all(&bytes[..boundary])?; for _ in 0..diff { file.write_u8(0)?; } file.write_i64::<BigEndian>(self.data_nascimento.timestamp())?; Ok(()) } fn deserialize(file: &mut File) -> Result<Cliente, SerializeError> { let codigo = file.read_u32::<BigEndian>()?; let mut nome = [0; 50]; file.read_exact(&mut nome)?; let nul_pos = nome.iter().position(|&c| c == b'\0').unwrap_or(nome.len()); let nome = String::from_utf8(nome[..nul_pos].to_vec())?; let data_nascimento = file.read_i64::<BigEndian>()?; let data_nascimento = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(data_nascimento, 0), Utc); Ok(Cliente {codigo, nome, data_nascimento}) } }
random_line_split
main.rs
use binaryninja::architecture::Architecture; use binaryninja::binaryview::{BinaryViewBase, BinaryViewExt}; // Standalone executables need to provide a main function for rustc // Plugins should refer to `binaryninja::command::*` for the various registration callbacks. fn main() { // This loads all the core architecture, platform, etc plugins // Standalone executables probably need to call this, but plugins do not println!("Loading plugins...");
println!("Loading binary..."); let bv = binaryninja::open_view("/bin/cat").expect("Couldn't open `/bin/cat`"); println!("Filename: `{}`", bv.metadata().filename()); println!("File size: `{:#x}`", bv.len()); println!("Function count: {}", bv.functions().len()); for func in &bv.functions() { println!(" `{}`:", func.symbol().full_name()); for basic_block in &func.basic_blocks() { // TODO : This is intended to be refactored to be more nice to work with soon(TM) for addr in basic_block.as_ref() { print!(" {} ", addr); match func.arch().instruction_text( bv.read_buffer(addr, func.arch().max_instr_len()) .unwrap() .get_data(), addr, ) { Some((_, tokens)) => { tokens .iter() .for_each(|token| print!("{}", token.text().as_str())); println!("") } _ => (), } } } } // Important! Standalone executables need to call shutdown or they will hang forever binaryninja::headless::shutdown(); }
binaryninja::headless::init(); // Your code here...
random_line_split
main.rs
use binaryninja::architecture::Architecture; use binaryninja::binaryview::{BinaryViewBase, BinaryViewExt}; // Standalone executables need to provide a main function for rustc // Plugins should refer to `binaryninja::command::*` for the various registration callbacks. fn main()
match func.arch().instruction_text( bv.read_buffer(addr, func.arch().max_instr_len()) .unwrap() .get_data(), addr, ) { Some((_, tokens)) => { tokens .iter() .for_each(|token| print!("{}", token.text().as_str())); println!("") } _ => (), } } } } // Important! Standalone executables need to call shutdown or they will hang forever binaryninja::headless::shutdown(); }
{ // This loads all the core architecture, platform, etc plugins // Standalone executables probably need to call this, but plugins do not println!("Loading plugins..."); binaryninja::headless::init(); // Your code here... println!("Loading binary..."); let bv = binaryninja::open_view("/bin/cat").expect("Couldn't open `/bin/cat`"); println!("Filename: `{}`", bv.metadata().filename()); println!("File size: `{:#x}`", bv.len()); println!("Function count: {}", bv.functions().len()); for func in &bv.functions() { println!(" `{}`:", func.symbol().full_name()); for basic_block in &func.basic_blocks() { // TODO : This is intended to be refactored to be more nice to work with soon(TM) for addr in basic_block.as_ref() { print!(" {} ", addr);
identifier_body
main.rs
use binaryninja::architecture::Architecture; use binaryninja::binaryview::{BinaryViewBase, BinaryViewExt}; // Standalone executables need to provide a main function for rustc // Plugins should refer to `binaryninja::command::*` for the various registration callbacks. fn
() { // This loads all the core architecture, platform, etc plugins // Standalone executables probably need to call this, but plugins do not println!("Loading plugins..."); binaryninja::headless::init(); // Your code here... println!("Loading binary..."); let bv = binaryninja::open_view("/bin/cat").expect("Couldn't open `/bin/cat`"); println!("Filename: `{}`", bv.metadata().filename()); println!("File size: `{:#x}`", bv.len()); println!("Function count: {}", bv.functions().len()); for func in &bv.functions() { println!(" `{}`:", func.symbol().full_name()); for basic_block in &func.basic_blocks() { // TODO : This is intended to be refactored to be more nice to work with soon(TM) for addr in basic_block.as_ref() { print!(" {} ", addr); match func.arch().instruction_text( bv.read_buffer(addr, func.arch().max_instr_len()) .unwrap() .get_data(), addr, ) { Some((_, tokens)) => { tokens .iter() .for_each(|token| print!("{}", token.text().as_str())); println!("") } _ => (), } } } } // Important! Standalone executables need to call shutdown or they will hang forever binaryninja::headless::shutdown(); }
main
identifier_name
main.rs
use binaryninja::architecture::Architecture; use binaryninja::binaryview::{BinaryViewBase, BinaryViewExt}; // Standalone executables need to provide a main function for rustc // Plugins should refer to `binaryninja::command::*` for the various registration callbacks. fn main() { // This loads all the core architecture, platform, etc plugins // Standalone executables probably need to call this, but plugins do not println!("Loading plugins..."); binaryninja::headless::init(); // Your code here... println!("Loading binary..."); let bv = binaryninja::open_view("/bin/cat").expect("Couldn't open `/bin/cat`"); println!("Filename: `{}`", bv.metadata().filename()); println!("File size: `{:#x}`", bv.len()); println!("Function count: {}", bv.functions().len()); for func in &bv.functions() { println!(" `{}`:", func.symbol().full_name()); for basic_block in &func.basic_blocks() { // TODO : This is intended to be refactored to be more nice to work with soon(TM) for addr in basic_block.as_ref() { print!(" {} ", addr); match func.arch().instruction_text( bv.read_buffer(addr, func.arch().max_instr_len()) .unwrap() .get_data(), addr, ) { Some((_, tokens)) =>
_ => (), } } } } // Important! Standalone executables need to call shutdown or they will hang forever binaryninja::headless::shutdown(); }
{ tokens .iter() .for_each(|token| print!("{}", token.text().as_str())); println!("") }
conditional_block
split.rs
// #![ warn( missing_docs ) ] // #![ warn( missing_debug_implementations ) ] use former::Former; /// /// Either delimeter or delimeted with the slice on its string. /// #[ derive( Debug ) ] pub struct Split< 'a > { string : &'a str, typ : SplitType, } impl< 'a > From< Split< 'a > > for String { fn from( src : Split ) -> Self { src.string.into() } } /// /// Either delimeter or delimeted /// #[ derive( Debug ) ] pub enum SplitType { /// Substring of the original string with text inbetween delimeters. Delimeted, /// Delimeter. Delimeter, } /// /// Split iterator. /// #[ derive( Debug ) ] pub struct SplitIterator< 'a > { iterator : std::iter::Peekable< std::str::Split< 'a, &'a str > >, counter : i32, delimeter : &'a str, } // impl< 'a > SplitIterator< 'a > { fn new( src : &'a str, delimeter : &'a str ) -> Self { let counter = 0; // let delimeter = delimeter.clone(); let delimeter_slice = unsafe { let slice = core::slice::from_raw_parts( delimeter.as_ptr(), delimeter.len() ); core::str::from_utf8_unchecked( slice ) }; let iterator = src.split( delimeter_slice ).peekable(); Self { iterator,
} // impl< 'a > Iterator for SplitIterator< 'a > { type Item = Split< 'a >; fn next( &mut self ) -> Option< Self::Item > { self.counter += 1; if self.counter % 2 == 1 { let next = self.iterator.next(); if let Some( next ) = next { Some( Split { string : next, typ : SplitType::Delimeted } ) } else { None } } else { if self.iterator.peek().is_none() { self.iterator.next(); return None; } Some( Split { string : self.delimeter, typ : SplitType::Delimeter } ) // Some( Split::Delimeter( self.delimeter.clone() ) ) } } } /// /// Options of function split. /// #[ derive( Debug ) ] #[ derive( Former ) ] #[ form_after( fn split( self ) -> SplitIterator< 'a > ) ] pub struct SplitOptions< 'a > { #[ default( "" ) ] src : &'a str, #[ default( "" ) ] delimeter : &'a str, #[ default( true ) ] preserving_empty : bool, #[ default( true ) ] preserving_delimeters : bool, // #[ method ] // fn split( self ) -> SplitIterator< 'a > // where // Self : Sized, // { // SplitIterator::new( self.src(), self.delimeter() ) // } // result : HashMap< Box< str >, Box< str > >, } /// /// Adapter for Split Options. /// pub trait SplitOptionsAdapter< 'a > { /// A string to split. fn src( &self ) -> &'a str; /// A delimeter to split string. fn delimeter( &self ) -> &'a str; /// Preserving or dropping empty splits. fn preserving_empty( &self ) -> bool; /// Preserving or dropping delimeters. fn preserving_delimeters( &self ) -> bool; /// Do splitting. fn split( self ) -> SplitIterator< 'a > where Self : Sized, { SplitIterator::new( self.src(), self.delimeter() ) } } // impl< 'a > SplitOptionsAdapter< 'a > for SplitOptions< 'a > { fn src( &self ) -> &'a str { self.src } fn delimeter( &self ) -> &'a str { self.delimeter } fn preserving_empty( &self ) -> bool { self.preserving_empty } fn preserving_delimeters( &self ) -> bool { self.preserving_delimeters } } /// /// Function to split a string. /// /// It produces former. To convert former into options and run algorithm of splitting call `form()`. /// /// # Sample /// ``` /// let iter = wstring_tools::string::split() /// .src( "abc def" ) /// .delimeter( " " ) /// .form(); /// ``` pub fn split< 'a >() -> SplitOptionsFormer< 'a > { SplitOptions::former() }
delimeter, counter, } }
random_line_split
split.rs
// #![ warn( missing_docs ) ] // #![ warn( missing_debug_implementations ) ] use former::Former; /// /// Either delimeter or delimeted with the slice on its string. /// #[ derive( Debug ) ] pub struct Split< 'a > { string : &'a str, typ : SplitType, } impl< 'a > From< Split< 'a > > for String { fn from( src : Split ) -> Self { src.string.into() } } /// /// Either delimeter or delimeted /// #[ derive( Debug ) ] pub enum SplitType { /// Substring of the original string with text inbetween delimeters. Delimeted, /// Delimeter. Delimeter, } /// /// Split iterator. /// #[ derive( Debug ) ] pub struct SplitIterator< 'a > { iterator : std::iter::Peekable< std::str::Split< 'a, &'a str > >, counter : i32, delimeter : &'a str, } // impl< 'a > SplitIterator< 'a > { fn new( src : &'a str, delimeter : &'a str ) -> Self { let counter = 0; // let delimeter = delimeter.clone(); let delimeter_slice = unsafe { let slice = core::slice::from_raw_parts( delimeter.as_ptr(), delimeter.len() ); core::str::from_utf8_unchecked( slice ) }; let iterator = src.split( delimeter_slice ).peekable(); Self { iterator, delimeter, counter, } } } // impl< 'a > Iterator for SplitIterator< 'a > { type Item = Split< 'a >; fn next( &mut self ) -> Option< Self::Item > { self.counter += 1; if self.counter % 2 == 1 { let next = self.iterator.next(); if let Some( next ) = next { Some( Split { string : next, typ : SplitType::Delimeted } ) } else { None } } else { if self.iterator.peek().is_none()
Some( Split { string : self.delimeter, typ : SplitType::Delimeter } ) // Some( Split::Delimeter( self.delimeter.clone() ) ) } } } /// /// Options of function split. /// #[ derive( Debug ) ] #[ derive( Former ) ] #[ form_after( fn split( self ) -> SplitIterator< 'a > ) ] pub struct SplitOptions< 'a > { #[ default( "" ) ] src : &'a str, #[ default( "" ) ] delimeter : &'a str, #[ default( true ) ] preserving_empty : bool, #[ default( true ) ] preserving_delimeters : bool, // #[ method ] // fn split( self ) -> SplitIterator< 'a > // where // Self : Sized, // { // SplitIterator::new( self.src(), self.delimeter() ) // } // result : HashMap< Box< str >, Box< str > >, } /// /// Adapter for Split Options. /// pub trait SplitOptionsAdapter< 'a > { /// A string to split. fn src( &self ) -> &'a str; /// A delimeter to split string. fn delimeter( &self ) -> &'a str; /// Preserving or dropping empty splits. fn preserving_empty( &self ) -> bool; /// Preserving or dropping delimeters. fn preserving_delimeters( &self ) -> bool; /// Do splitting. fn split( self ) -> SplitIterator< 'a > where Self : Sized, { SplitIterator::new( self.src(), self.delimeter() ) } } // impl< 'a > SplitOptionsAdapter< 'a > for SplitOptions< 'a > { fn src( &self ) -> &'a str { self.src } fn delimeter( &self ) -> &'a str { self.delimeter } fn preserving_empty( &self ) -> bool { self.preserving_empty } fn preserving_delimeters( &self ) -> bool { self.preserving_delimeters } } /// /// Function to split a string. /// /// It produces former. To convert former into options and run algorithm of splitting call `form()`. /// /// # Sample /// ``` /// let iter = wstring_tools::string::split() /// .src( "abc def" ) /// .delimeter( " " ) /// .form(); /// ``` pub fn split< 'a >() -> SplitOptionsFormer< 'a > { SplitOptions::former() }
{ self.iterator.next(); return None; }
conditional_block
split.rs
// #![ warn( missing_docs ) ] // #![ warn( missing_debug_implementations ) ] use former::Former; /// /// Either delimeter or delimeted with the slice on its string. /// #[ derive( Debug ) ] pub struct Split< 'a > { string : &'a str, typ : SplitType, } impl< 'a > From< Split< 'a > > for String { fn from( src : Split ) -> Self
} /// /// Either delimeter or delimeted /// #[ derive( Debug ) ] pub enum SplitType { /// Substring of the original string with text inbetween delimeters. Delimeted, /// Delimeter. Delimeter, } /// /// Split iterator. /// #[ derive( Debug ) ] pub struct SplitIterator< 'a > { iterator : std::iter::Peekable< std::str::Split< 'a, &'a str > >, counter : i32, delimeter : &'a str, } // impl< 'a > SplitIterator< 'a > { fn new( src : &'a str, delimeter : &'a str ) -> Self { let counter = 0; // let delimeter = delimeter.clone(); let delimeter_slice = unsafe { let slice = core::slice::from_raw_parts( delimeter.as_ptr(), delimeter.len() ); core::str::from_utf8_unchecked( slice ) }; let iterator = src.split( delimeter_slice ).peekable(); Self { iterator, delimeter, counter, } } } // impl< 'a > Iterator for SplitIterator< 'a > { type Item = Split< 'a >; fn next( &mut self ) -> Option< Self::Item > { self.counter += 1; if self.counter % 2 == 1 { let next = self.iterator.next(); if let Some( next ) = next { Some( Split { string : next, typ : SplitType::Delimeted } ) } else { None } } else { if self.iterator.peek().is_none() { self.iterator.next(); return None; } Some( Split { string : self.delimeter, typ : SplitType::Delimeter } ) // Some( Split::Delimeter( self.delimeter.clone() ) ) } } } /// /// Options of function split. /// #[ derive( Debug ) ] #[ derive( Former ) ] #[ form_after( fn split( self ) -> SplitIterator< 'a > ) ] pub struct SplitOptions< 'a > { #[ default( "" ) ] src : &'a str, #[ default( "" ) ] delimeter : &'a str, #[ default( true ) ] preserving_empty : bool, #[ default( true ) ] preserving_delimeters : bool, // #[ method ] // fn split( self ) -> SplitIterator< 'a > // where // Self : Sized, // { // SplitIterator::new( self.src(), self.delimeter() ) // } // result : HashMap< Box< str >, Box< str > >, } /// /// Adapter for Split Options. /// pub trait SplitOptionsAdapter< 'a > { /// A string to split. fn src( &self ) -> &'a str; /// A delimeter to split string. fn delimeter( &self ) -> &'a str; /// Preserving or dropping empty splits. fn preserving_empty( &self ) -> bool; /// Preserving or dropping delimeters. fn preserving_delimeters( &self ) -> bool; /// Do splitting. fn split( self ) -> SplitIterator< 'a > where Self : Sized, { SplitIterator::new( self.src(), self.delimeter() ) } } // impl< 'a > SplitOptionsAdapter< 'a > for SplitOptions< 'a > { fn src( &self ) -> &'a str { self.src } fn delimeter( &self ) -> &'a str { self.delimeter } fn preserving_empty( &self ) -> bool { self.preserving_empty } fn preserving_delimeters( &self ) -> bool { self.preserving_delimeters } } /// /// Function to split a string. /// /// It produces former. To convert former into options and run algorithm of splitting call `form()`. /// /// # Sample /// ``` /// let iter = wstring_tools::string::split() /// .src( "abc def" ) /// .delimeter( " " ) /// .form(); /// ``` pub fn split< 'a >() -> SplitOptionsFormer< 'a > { SplitOptions::former() }
{ src.string.into() }
identifier_body
split.rs
// #![ warn( missing_docs ) ] // #![ warn( missing_debug_implementations ) ] use former::Former; /// /// Either delimeter or delimeted with the slice on its string. /// #[ derive( Debug ) ] pub struct Split< 'a > { string : &'a str, typ : SplitType, } impl< 'a > From< Split< 'a > > for String { fn from( src : Split ) -> Self { src.string.into() } } /// /// Either delimeter or delimeted /// #[ derive( Debug ) ] pub enum SplitType { /// Substring of the original string with text inbetween delimeters. Delimeted, /// Delimeter. Delimeter, } /// /// Split iterator. /// #[ derive( Debug ) ] pub struct SplitIterator< 'a > { iterator : std::iter::Peekable< std::str::Split< 'a, &'a str > >, counter : i32, delimeter : &'a str, } // impl< 'a > SplitIterator< 'a > { fn new( src : &'a str, delimeter : &'a str ) -> Self { let counter = 0; // let delimeter = delimeter.clone(); let delimeter_slice = unsafe { let slice = core::slice::from_raw_parts( delimeter.as_ptr(), delimeter.len() ); core::str::from_utf8_unchecked( slice ) }; let iterator = src.split( delimeter_slice ).peekable(); Self { iterator, delimeter, counter, } } } // impl< 'a > Iterator for SplitIterator< 'a > { type Item = Split< 'a >; fn next( &mut self ) -> Option< Self::Item > { self.counter += 1; if self.counter % 2 == 1 { let next = self.iterator.next(); if let Some( next ) = next { Some( Split { string : next, typ : SplitType::Delimeted } ) } else { None } } else { if self.iterator.peek().is_none() { self.iterator.next(); return None; } Some( Split { string : self.delimeter, typ : SplitType::Delimeter } ) // Some( Split::Delimeter( self.delimeter.clone() ) ) } } } /// /// Options of function split. /// #[ derive( Debug ) ] #[ derive( Former ) ] #[ form_after( fn split( self ) -> SplitIterator< 'a > ) ] pub struct SplitOptions< 'a > { #[ default( "" ) ] src : &'a str, #[ default( "" ) ] delimeter : &'a str, #[ default( true ) ] preserving_empty : bool, #[ default( true ) ] preserving_delimeters : bool, // #[ method ] // fn split( self ) -> SplitIterator< 'a > // where // Self : Sized, // { // SplitIterator::new( self.src(), self.delimeter() ) // } // result : HashMap< Box< str >, Box< str > >, } /// /// Adapter for Split Options. /// pub trait SplitOptionsAdapter< 'a > { /// A string to split. fn src( &self ) -> &'a str; /// A delimeter to split string. fn delimeter( &self ) -> &'a str; /// Preserving or dropping empty splits. fn preserving_empty( &self ) -> bool; /// Preserving or dropping delimeters. fn preserving_delimeters( &self ) -> bool; /// Do splitting. fn split( self ) -> SplitIterator< 'a > where Self : Sized, { SplitIterator::new( self.src(), self.delimeter() ) } } // impl< 'a > SplitOptionsAdapter< 'a > for SplitOptions< 'a > { fn src( &self ) -> &'a str { self.src } fn
( &self ) -> &'a str { self.delimeter } fn preserving_empty( &self ) -> bool { self.preserving_empty } fn preserving_delimeters( &self ) -> bool { self.preserving_delimeters } } /// /// Function to split a string. /// /// It produces former. To convert former into options and run algorithm of splitting call `form()`. /// /// # Sample /// ``` /// let iter = wstring_tools::string::split() /// .src( "abc def" ) /// .delimeter( " " ) /// .form(); /// ``` pub fn split< 'a >() -> SplitOptionsFormer< 'a > { SplitOptions::former() }
delimeter
identifier_name
sha1nexte.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn sha1nexte_1() { run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 56, 200, 207], OperandSize::Dword) } fn sha1nexte_2()
fn sha1nexte_3() { run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 56, 200, 226], OperandSize::Qword) } fn sha1nexte_4() { run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM1)), operand2: Some(IndirectDisplaced(RSI, 580853945, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 56, 200, 142, 185, 32, 159, 34], OperandSize::Qword) }
{ run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(EDI, Two, 1878744270, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 56, 200, 20, 125, 206, 92, 251, 111], OperandSize::Dword) }
identifier_body
sha1nexte.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn sha1nexte_1() { run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 56, 200, 207], OperandSize::Dword) } fn
() { run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(EDI, Two, 1878744270, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 56, 200, 20, 125, 206, 92, 251, 111], OperandSize::Dword) } fn sha1nexte_3() { run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 56, 200, 226], OperandSize::Qword) } fn sha1nexte_4() { run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM1)), operand2: Some(IndirectDisplaced(RSI, 580853945, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 56, 200, 142, 185, 32, 159, 34], OperandSize::Qword) }
sha1nexte_2
identifier_name
sha1nexte.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn sha1nexte_1() { run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 56, 200, 207], OperandSize::Dword) } fn sha1nexte_2() { run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(EDI, Two, 1878744270, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 56, 200, 20, 125, 206, 92, 251, 111], OperandSize::Dword) } fn sha1nexte_3() { run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 56, 200, 226], OperandSize::Qword) } fn sha1nexte_4() { run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM1)), operand2: Some(IndirectDisplaced(RSI, 580853945, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 56, 200, 142, 185, 32, 159, 34], OperandSize::Qword)
}
random_line_split
insertion.rs
// Copyright 2020 Johannes Köster. // Licensed under the GNU GPLv3 license (https://opensource.org/licenses/GPL-3.0) // This file may not be copied, modified, or distributed // except according to those terms. use std::cell::RefCell; use std::cmp; use std::rc::Rc; use std::sync::Arc; use anyhow::Result; use bio::stats::pairhmm::EmissionParameters; use bio::stats::LogProb; use bio_types::genome::{self, AbstractInterval, AbstractLocus}; use crate::estimation::alignment_properties::AlignmentProperties; use crate::reference; use crate::variants::evidence::realignment::pairhmm::{ReadEmission, RefBaseEmission}; use crate::variants::evidence::realignment::{Realignable, Realigner}; use crate::variants::sampling_bias::{ReadSamplingBias, SamplingBias}; use crate::variants::types::{AlleleSupport, MultiLocus, PairedEndEvidence, SingleLocus, Variant}; use crate::{default_emission, default_ref_base_emission}; pub(crate) struct Insertion<R: Realigner> { locus: MultiLocus, ins_seq: Rc<Vec<u8>>, realigner: RefCell<R>, } impl<R: Realigner> Insertion<R> { pub(crate) fn new(locus: genome::Locus, ins_seq: Vec<u8>, realigner: R) -> Self { Insertion { locus: MultiLocus::new(vec![SingleLocus::new(genome::Interval::new( locus.contig().to_owned(), locus.pos()..locus.pos() + 1, ))]), ins_seq: Rc::new(ins_seq), realigner: RefCell::new(realigner), } } pub(crate) fn locus(&self) -> &SingleLocus { &self.locus[0] } } impl<'a, R: Realigner> Realignable<'a> for Insertion<R> { type EmissionParams = InsertionEmissionParams<'a>; fn alt_emission_params( &self, read_emission_params: Rc<ReadEmission<'a>>, ref_buffer: Arc<reference::Buffer>, _: &genome::Interval, ref_window: usize, ) -> Result<Vec<InsertionEmissionParams<'a>>> { let l = self.ins_seq.len() as usize; let start = self.locus().range().start as usize; let ref_seq = ref_buffer.seq(self.locus().contig())?; let ref_seq_len = ref_seq.len(); Ok(vec![InsertionEmissionParams { ref_seq, ref_offset: start.saturating_sub(ref_window), ref_end: cmp::min(start + l + ref_window, ref_seq_len), ins_start: start, ins_len: l, ins_end: start + l, ins_seq: Rc::clone(&self.ins_seq), read_emission: read_emission_params, }]) } } impl<R: Realigner> SamplingBias for Insertion<R> { fn feasible_bases(&self, read_len: u64, alignment_properties: &AlignmentProperties) -> u64 { if let Some(len) = self.enclosable_len() { if len < (alignment_properties.max_ins_cigar_len as u64) { return read_len; } } (read_len as f64 * alignment_properties.frac_max_softclip) as u64 } fn enclosable_len(&self) -> Option<u64> { Some(self.ins_seq.len() as u64) } } impl<R: Realigner> ReadSamplingBias for Insertion<R> {} impl<R: Realigner> Variant for Insertion<R> { type Evidence = PairedEndEvidence; type Loci = MultiLocus; fn is_valid_evidence( &self, evidence: &Self::Evidence, _: &AlignmentProperties, ) -> Option<Vec<usize>> { if match evidence { PairedEndEvidence::SingleEnd(read) =>!self.locus().overlap(read, true).is_none(), PairedEndEvidence::PairedEnd { left, right } => {
} { Some(vec![0]) } else { None } } /// Return variant loci. fn loci(&self) -> &Self::Loci { &self.locus } /// Calculate probability for alt and reference allele. fn allele_support( &self, evidence: &Self::Evidence, _alignment_properties: &AlignmentProperties, ) -> Result<Option<AlleleSupport>> { match evidence { PairedEndEvidence::SingleEnd(record) => Ok(Some( self.realigner .borrow_mut() .allele_support(record, self.locus.iter(), self)?, )), PairedEndEvidence::PairedEnd { left, right } => { let left_support = self.realigner .borrow_mut() .allele_support(left, self.locus.iter(), self)?; let right_support = self.realigner .borrow_mut() .allele_support(right, self.locus.iter(), self)?; let mut support = left_support; support.merge(&right_support); Ok(Some(support)) } } } fn prob_sample_alt( &self, evidence: &Self::Evidence, alignment_properties: &AlignmentProperties, ) -> LogProb { match evidence { PairedEndEvidence::PairedEnd { left, right } => { // METHOD: we do not require the fragment to enclose the variant. // Hence, we treat both reads independently. (self .prob_sample_alt_read(left.seq().len() as u64, alignment_properties) .ln_one_minus_exp() + self .prob_sample_alt_read(right.seq().len() as u64, alignment_properties) .ln_one_minus_exp()) .ln_one_minus_exp() } PairedEndEvidence::SingleEnd(read) => { self.prob_sample_alt_read(read.seq().len() as u64, alignment_properties) } } } } /// Emission parameters for PairHMM over insertion allele. pub(crate) struct InsertionEmissionParams<'a> { ref_seq: Arc<Vec<u8>>, ref_offset: usize, ref_end: usize, ins_start: usize, ins_end: usize, ins_len: usize, ins_seq: Rc<Vec<u8>>, read_emission: Rc<ReadEmission<'a>>, } impl<'a> RefBaseEmission for InsertionEmissionParams<'a> { #[inline] fn ref_base(&self, i: usize) -> u8 { let i_ = i + self.ref_offset; if i_ <= self.ins_start { self.ref_seq[i_] } else if i_ > self.ins_end { self.ref_seq[i_ - self.ins_len] } else { self.ins_seq[i_ - (self.ins_start + 1)] } } default_ref_base_emission!(); } impl<'a> EmissionParameters for InsertionEmissionParams<'a> { default_emission!(); #[inline] fn len_x(&self) -> usize { self.ref_end - self.ref_offset + self.ins_len } }
!self.locus().overlap(left, true).is_none() || !self.locus().overlap(right, true).is_none() }
conditional_block
insertion.rs
// Copyright 2020 Johannes Köster. // Licensed under the GNU GPLv3 license (https://opensource.org/licenses/GPL-3.0) // This file may not be copied, modified, or distributed // except according to those terms. use std::cell::RefCell; use std::cmp; use std::rc::Rc; use std::sync::Arc; use anyhow::Result; use bio::stats::pairhmm::EmissionParameters; use bio::stats::LogProb; use bio_types::genome::{self, AbstractInterval, AbstractLocus}; use crate::estimation::alignment_properties::AlignmentProperties; use crate::reference; use crate::variants::evidence::realignment::pairhmm::{ReadEmission, RefBaseEmission}; use crate::variants::evidence::realignment::{Realignable, Realigner}; use crate::variants::sampling_bias::{ReadSamplingBias, SamplingBias}; use crate::variants::types::{AlleleSupport, MultiLocus, PairedEndEvidence, SingleLocus, Variant}; use crate::{default_emission, default_ref_base_emission}; pub(crate) struct Insertion<R: Realigner> { locus: MultiLocus, ins_seq: Rc<Vec<u8>>, realigner: RefCell<R>, } impl<R: Realigner> Insertion<R> { pub(crate) fn new(locus: genome::Locus, ins_seq: Vec<u8>, realigner: R) -> Self { Insertion { locus: MultiLocus::new(vec![SingleLocus::new(genome::Interval::new( locus.contig().to_owned(), locus.pos()..locus.pos() + 1, ))]), ins_seq: Rc::new(ins_seq), realigner: RefCell::new(realigner), } } pub(crate) fn locus(&self) -> &SingleLocus { &self.locus[0] } } impl<'a, R: Realigner> Realignable<'a> for Insertion<R> { type EmissionParams = InsertionEmissionParams<'a>; fn alt_emission_params( &self, read_emission_params: Rc<ReadEmission<'a>>, ref_buffer: Arc<reference::Buffer>, _: &genome::Interval, ref_window: usize, ) -> Result<Vec<InsertionEmissionParams<'a>>> { let l = self.ins_seq.len() as usize; let start = self.locus().range().start as usize; let ref_seq = ref_buffer.seq(self.locus().contig())?; let ref_seq_len = ref_seq.len(); Ok(vec![InsertionEmissionParams { ref_seq, ref_offset: start.saturating_sub(ref_window), ref_end: cmp::min(start + l + ref_window, ref_seq_len), ins_start: start, ins_len: l, ins_end: start + l, ins_seq: Rc::clone(&self.ins_seq), read_emission: read_emission_params, }]) } } impl<R: Realigner> SamplingBias for Insertion<R> { fn feasible_bases(&self, read_len: u64, alignment_properties: &AlignmentProperties) -> u64 { if let Some(len) = self.enclosable_len() { if len < (alignment_properties.max_ins_cigar_len as u64) { return read_len; } } (read_len as f64 * alignment_properties.frac_max_softclip) as u64
} } impl<R: Realigner> ReadSamplingBias for Insertion<R> {} impl<R: Realigner> Variant for Insertion<R> { type Evidence = PairedEndEvidence; type Loci = MultiLocus; fn is_valid_evidence( &self, evidence: &Self::Evidence, _: &AlignmentProperties, ) -> Option<Vec<usize>> { if match evidence { PairedEndEvidence::SingleEnd(read) =>!self.locus().overlap(read, true).is_none(), PairedEndEvidence::PairedEnd { left, right } => { !self.locus().overlap(left, true).is_none() ||!self.locus().overlap(right, true).is_none() } } { Some(vec![0]) } else { None } } /// Return variant loci. fn loci(&self) -> &Self::Loci { &self.locus } /// Calculate probability for alt and reference allele. fn allele_support( &self, evidence: &Self::Evidence, _alignment_properties: &AlignmentProperties, ) -> Result<Option<AlleleSupport>> { match evidence { PairedEndEvidence::SingleEnd(record) => Ok(Some( self.realigner .borrow_mut() .allele_support(record, self.locus.iter(), self)?, )), PairedEndEvidence::PairedEnd { left, right } => { let left_support = self.realigner .borrow_mut() .allele_support(left, self.locus.iter(), self)?; let right_support = self.realigner .borrow_mut() .allele_support(right, self.locus.iter(), self)?; let mut support = left_support; support.merge(&right_support); Ok(Some(support)) } } } fn prob_sample_alt( &self, evidence: &Self::Evidence, alignment_properties: &AlignmentProperties, ) -> LogProb { match evidence { PairedEndEvidence::PairedEnd { left, right } => { // METHOD: we do not require the fragment to enclose the variant. // Hence, we treat both reads independently. (self .prob_sample_alt_read(left.seq().len() as u64, alignment_properties) .ln_one_minus_exp() + self .prob_sample_alt_read(right.seq().len() as u64, alignment_properties) .ln_one_minus_exp()) .ln_one_minus_exp() } PairedEndEvidence::SingleEnd(read) => { self.prob_sample_alt_read(read.seq().len() as u64, alignment_properties) } } } } /// Emission parameters for PairHMM over insertion allele. pub(crate) struct InsertionEmissionParams<'a> { ref_seq: Arc<Vec<u8>>, ref_offset: usize, ref_end: usize, ins_start: usize, ins_end: usize, ins_len: usize, ins_seq: Rc<Vec<u8>>, read_emission: Rc<ReadEmission<'a>>, } impl<'a> RefBaseEmission for InsertionEmissionParams<'a> { #[inline] fn ref_base(&self, i: usize) -> u8 { let i_ = i + self.ref_offset; if i_ <= self.ins_start { self.ref_seq[i_] } else if i_ > self.ins_end { self.ref_seq[i_ - self.ins_len] } else { self.ins_seq[i_ - (self.ins_start + 1)] } } default_ref_base_emission!(); } impl<'a> EmissionParameters for InsertionEmissionParams<'a> { default_emission!(); #[inline] fn len_x(&self) -> usize { self.ref_end - self.ref_offset + self.ins_len } }
} fn enclosable_len(&self) -> Option<u64> { Some(self.ins_seq.len() as u64)
random_line_split