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
cabi_powerpc.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use libc::c_uint; use llvm; use llvm::{Integer, Pointer, Float, Double, Struct, Array}; use llvm::{StructRetAttribute, ZExtAttribute}; use trans::cabi::{FnType, ArgType}; use trans::context::CrateContext; use trans::type_::Type; use std::cmp; fn align_up_to(off: uint, a: uint) -> uint { return (off + a - 1u) / a * a; } fn align(off: uint, ty: Type) -> uint { let a = ty_align(ty); return align_up_to(off, a); } fn ty_align(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { 1 } else { let str_tys = ty.field_types(); str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t))) } } Array => { let elt = ty.element_type(); ty_align(elt) } _ => panic!("ty_size: unhandled type") } } fn ty_size(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { let str_tys = ty.field_types(); str_tys.iter().fold(0, |s, t| s + ty_size(*t)) } else { let str_tys = ty.field_types(); let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t)); align(size, ty) } } Array => { let len = ty.array_length(); let elt = ty.element_type(); let eltsz = ty_size(elt); len * eltsz } _ => panic!("ty_size: unhandled type") } } fn classify_ret_ty(ccx: &CrateContext, ty: Type) -> ArgType { if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else { ArgType::indirect(ty, Some(StructRetAttribute)) } } fn classify_arg_ty(ccx: &CrateContext, ty: Type, offset: &mut uint) -> ArgType { let orig_offset = *offset; let size = ty_size(ty) * 8; let mut align = ty_align(ty); align = cmp::min(cmp::max(align, 4), 8); *offset = align_up_to(*offset, align); *offset += align_up_to(size, align * 8) / 8; if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else { ArgType::direct( ty, Some(struct_ty(ccx, ty)), padding_ty(ccx, align, orig_offset), None ) } } fn is_reg_ty(ty: Type) -> bool { return match ty.kind() { Integer | Pointer | Float | Double => true, _ => false }; } fn padding_ty(ccx: &CrateContext, align: uint, offset: uint) -> Option<Type> { if ((align - 1 ) & offset) > 0 { Some(Type::i32(ccx)) } else { None } } fn coerce_to_int(ccx: &CrateContext, size: uint) -> Vec<Type> { let int_ty = Type::i32(ccx); let mut args = Vec::new(); let mut n = size / 32; while n > 0 { args.push(int_ty); n -= 1; } let r = size % 32; if r > 0 { unsafe { args.push(Type::from_ref(llvm::LLVMIntTypeInContext(ccx.llcx(), r as c_uint))); } }
Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false) } pub fn compute_abi_info(ccx: &CrateContext, atys: &[Type], rty: Type, ret_def: bool) -> FnType { let ret_ty = if ret_def { classify_ret_ty(ccx, rty) } else { ArgType::direct(Type::void(ccx), None, None, None) }; let sret = ret_ty.is_indirect(); let mut arg_tys = Vec::new(); let mut offset = if sret { 4 } else { 0 }; for aty in atys.iter() { let ty = classify_arg_ty(ccx, *aty, &mut offset); arg_tys.push(ty); }; return FnType { arg_tys: arg_tys, ret_ty: ret_ty, }; }
args } fn struct_ty(ccx: &CrateContext, ty: Type) -> Type { let size = ty_size(ty) * 8;
random_line_split
cabi_powerpc.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use libc::c_uint; use llvm; use llvm::{Integer, Pointer, Float, Double, Struct, Array}; use llvm::{StructRetAttribute, ZExtAttribute}; use trans::cabi::{FnType, ArgType}; use trans::context::CrateContext; use trans::type_::Type; use std::cmp; fn align_up_to(off: uint, a: uint) -> uint { return (off + a - 1u) / a * a; } fn align(off: uint, ty: Type) -> uint { let a = ty_align(ty); return align_up_to(off, a); } fn ty_align(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { 1 } else { let str_tys = ty.field_types(); str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t))) } } Array => { let elt = ty.element_type(); ty_align(elt) } _ => panic!("ty_size: unhandled type") } } fn ty_size(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { let str_tys = ty.field_types(); str_tys.iter().fold(0, |s, t| s + ty_size(*t)) } else { let str_tys = ty.field_types(); let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t)); align(size, ty) } } Array => { let len = ty.array_length(); let elt = ty.element_type(); let eltsz = ty_size(elt); len * eltsz } _ => panic!("ty_size: unhandled type") } } fn classify_ret_ty(ccx: &CrateContext, ty: Type) -> ArgType { if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else { ArgType::indirect(ty, Some(StructRetAttribute)) } } fn classify_arg_ty(ccx: &CrateContext, ty: Type, offset: &mut uint) -> ArgType { let orig_offset = *offset; let size = ty_size(ty) * 8; let mut align = ty_align(ty); align = cmp::min(cmp::max(align, 4), 8); *offset = align_up_to(*offset, align); *offset += align_up_to(size, align * 8) / 8; if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else
} fn is_reg_ty(ty: Type) -> bool { return match ty.kind() { Integer | Pointer | Float | Double => true, _ => false }; } fn padding_ty(ccx: &CrateContext, align: uint, offset: uint) -> Option<Type> { if ((align - 1 ) & offset) > 0 { Some(Type::i32(ccx)) } else { None } } fn coerce_to_int(ccx: &CrateContext, size: uint) -> Vec<Type> { let int_ty = Type::i32(ccx); let mut args = Vec::new(); let mut n = size / 32; while n > 0 { args.push(int_ty); n -= 1; } let r = size % 32; if r > 0 { unsafe { args.push(Type::from_ref(llvm::LLVMIntTypeInContext(ccx.llcx(), r as c_uint))); } } args } fn struct_ty(ccx: &CrateContext, ty: Type) -> Type { let size = ty_size(ty) * 8; Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false) } pub fn compute_abi_info(ccx: &CrateContext, atys: &[Type], rty: Type, ret_def: bool) -> FnType { let ret_ty = if ret_def { classify_ret_ty(ccx, rty) } else { ArgType::direct(Type::void(ccx), None, None, None) }; let sret = ret_ty.is_indirect(); let mut arg_tys = Vec::new(); let mut offset = if sret { 4 } else { 0 }; for aty in atys.iter() { let ty = classify_arg_ty(ccx, *aty, &mut offset); arg_tys.push(ty); }; return FnType { arg_tys: arg_tys, ret_ty: ret_ty, }; }
{ ArgType::direct( ty, Some(struct_ty(ccx, ty)), padding_ty(ccx, align, orig_offset), None ) }
conditional_block
type-ascription-precedence.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Operator precedence of type ascription // Type ascription has very high precedence, the same as operator `as` #![feature(type_ascription)] use std::ops::*; struct S; struct Z; impl Add<Z> for S { type Output = S; fn add(self, _rhs: Z) -> S { panic!() } } impl Mul<Z> for S { type Output = S; fn mul(self, _rhs: Z) -> S { panic!() } } impl Neg for S { type Output = Z; fn
(self) -> Z { panic!() } } impl Deref for S { type Target = Z; fn deref(&self) -> &Z { panic!() } } fn main() { &S: &S; // OK (&S): &S; // OK &(S: &S); //~ ERROR mismatched types *S: Z; // OK (*S): Z; // OK *(S: Z); //~ ERROR mismatched types //~^ ERROR type `Z` cannot be dereferenced -S: Z; // OK (-S): Z; // OK -(S: Z); //~ ERROR mismatched types //~^ ERROR cannot apply unary operator `-` to type `Z` S + Z: Z; // OK S + (Z: Z); // OK (S + Z): Z; //~ ERROR mismatched types S * Z: Z; // OK S * (Z: Z); // OK (S * Z): Z; //~ ERROR mismatched types S.. S: S; // OK S.. (S: S); // OK (S.. S): S; //~ ERROR mismatched types }
neg
identifier_name
type-ascription-precedence.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Operator precedence of type ascription // Type ascription has very high precedence, the same as operator `as` #![feature(type_ascription)] use std::ops::*; struct S; struct Z; impl Add<Z> for S { type Output = S; fn add(self, _rhs: Z) -> S { panic!() } } impl Mul<Z> for S { type Output = S; fn mul(self, _rhs: Z) -> S { panic!() } } impl Neg for S { type Output = Z; fn neg(self) -> Z { panic!() } } impl Deref for S { type Target = Z; fn deref(&self) -> &Z
} fn main() { &S: &S; // OK (&S): &S; // OK &(S: &S); //~ ERROR mismatched types *S: Z; // OK (*S): Z; // OK *(S: Z); //~ ERROR mismatched types //~^ ERROR type `Z` cannot be dereferenced -S: Z; // OK (-S): Z; // OK -(S: Z); //~ ERROR mismatched types //~^ ERROR cannot apply unary operator `-` to type `Z` S + Z: Z; // OK S + (Z: Z); // OK (S + Z): Z; //~ ERROR mismatched types S * Z: Z; // OK S * (Z: Z); // OK (S * Z): Z; //~ ERROR mismatched types S.. S: S; // OK S.. (S: S); // OK (S.. S): S; //~ ERROR mismatched types }
{ panic!() }
identifier_body
type-ascription-precedence.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
#![feature(type_ascription)] use std::ops::*; struct S; struct Z; impl Add<Z> for S { type Output = S; fn add(self, _rhs: Z) -> S { panic!() } } impl Mul<Z> for S { type Output = S; fn mul(self, _rhs: Z) -> S { panic!() } } impl Neg for S { type Output = Z; fn neg(self) -> Z { panic!() } } impl Deref for S { type Target = Z; fn deref(&self) -> &Z { panic!() } } fn main() { &S: &S; // OK (&S): &S; // OK &(S: &S); //~ ERROR mismatched types *S: Z; // OK (*S): Z; // OK *(S: Z); //~ ERROR mismatched types //~^ ERROR type `Z` cannot be dereferenced -S: Z; // OK (-S): Z; // OK -(S: Z); //~ ERROR mismatched types //~^ ERROR cannot apply unary operator `-` to type `Z` S + Z: Z; // OK S + (Z: Z); // OK (S + Z): Z; //~ ERROR mismatched types S * Z: Z; // OK S * (Z: Z); // OK (S * Z): Z; //~ ERROR mismatched types S.. S: S; // OK S.. (S: S); // OK (S.. S): S; //~ ERROR mismatched types }
// Operator precedence of type ascription // Type ascription has very high precedence, the same as operator `as`
random_line_split
types.rs
use vecmath::{self, vec2_sub, vec2_len}; pub type Scalar = f64; /// [width, height] pub type Extent = vecmath::Vector2<Scalar>; /// [x, y] pub type Position = vecmath::Vector2<Scalar>; pub type Velocity = vecmath::Vector2<Scalar>; use transition::Transition; /// Points on screen. Usually they correspond to pixels, but might not on a /// `HiDPI` display pub type Pt = Scalar; /// Represents a shape used for collision detection #[derive(Debug, Clone, PartialEq)] pub enum CollisionShape { Square, Circle, } /// A game object which knows a few things about itself #[derive(Debug, Clone, PartialEq)] pub struct Object { pub pos: Position, pub half_size: Pt, pub shape: CollisionShape, } impl Object { pub fn left(&self) -> Scalar { self.pos[0] - self.half_size } pub fn right(&self) -> Scalar { self.pos[0] + self.half_size } pub fn top(&self) -> Scalar { self.pos[1] - self.half_size } pub fn bottom(&self) -> Scalar { self.pos[1] + self.half_size } /// Returns true if both objects intersect pub fn intersects(&self, other: &Object) -> bool { match (&self.shape, &other.shape) { (&CollisionShape::Circle, &CollisionShape::Circle) =>
_ => { self.left() <= other.right() && self.right() >= other.left() && self.top() <= other.bottom() && self.bottom() >= other.top() } } } } #[derive(Debug, Clone, PartialEq)] pub enum ObstacleKind { /// Enables a temporary attractive force AttractiveForceSwitch, /// Causes all other obstacles to hide themselves for a while InvisibiltySwitch, /// Kills the player Deadly, } /// An obstacle the hunter can collide with #[derive(Debug, Clone, PartialEq)] pub struct Obstacle { pub kind: ObstacleKind, pub object: Object, pub velocity: Velocity, } #[derive(Debug, Clone, PartialEq)] pub struct Hunter { pub object: Object, pub force: Scalar, pub velocity: Velocity, } /// It maintains the state of the game and expects to be updated with /// time-delta information to compute the next state. /// /// Please note that the coordinates used in the playing field start at 0 /// and grow #[derive(Debug, Clone, PartialEq)] pub struct State { /// The playing field pub field: Extent, /// The player's character pub hunter: Hunter, /// Hunted the player's character pub prey: Object, /// Obstacles the hunter must avoid to prevent game-over pub obstacles: Vec<Obstacle>, /// score of the current game pub score: u32, /// multiply prey score with the given value pub score_coeff: Scalar, /// transition between opaque and invisible obstacles pub obstacle_opacity: Transition, /// transition between no attracting force and maximum one pub attracting_force: Transition, /// Last delta-time during update pub last_dt: f64, }
{ vec2_len(vec2_sub(self.pos, other.pos)) <= self.half_size + other.half_size }
conditional_block
types.rs
use vecmath::{self, vec2_sub, vec2_len}; pub type Scalar = f64; /// [width, height] pub type Extent = vecmath::Vector2<Scalar>; /// [x, y] pub type Position = vecmath::Vector2<Scalar>; pub type Velocity = vecmath::Vector2<Scalar>; use transition::Transition; /// Points on screen. Usually they correspond to pixels, but might not on a /// `HiDPI` display pub type Pt = Scalar; /// Represents a shape used for collision detection #[derive(Debug, Clone, PartialEq)] pub enum CollisionShape { Square, Circle, } /// A game object which knows a few things about itself #[derive(Debug, Clone, PartialEq)] pub struct Object { pub pos: Position, pub half_size: Pt, pub shape: CollisionShape, } impl Object { pub fn left(&self) -> Scalar { self.pos[0] - self.half_size } pub fn right(&self) -> Scalar { self.pos[0] + self.half_size } pub fn top(&self) -> Scalar { self.pos[1] - self.half_size } pub fn bottom(&self) -> Scalar { self.pos[1] + self.half_size } /// Returns true if both objects intersect pub fn intersects(&self, other: &Object) -> bool { match (&self.shape, &other.shape) { (&CollisionShape::Circle, &CollisionShape::Circle) => { vec2_len(vec2_sub(self.pos, other.pos)) <= self.half_size + other.half_size } _ => { self.left() <= other.right() && self.right() >= other.left() && self.top() <= other.bottom() && self.bottom() >= other.top() } } } } #[derive(Debug, Clone, PartialEq)] pub enum
{ /// Enables a temporary attractive force AttractiveForceSwitch, /// Causes all other obstacles to hide themselves for a while InvisibiltySwitch, /// Kills the player Deadly, } /// An obstacle the hunter can collide with #[derive(Debug, Clone, PartialEq)] pub struct Obstacle { pub kind: ObstacleKind, pub object: Object, pub velocity: Velocity, } #[derive(Debug, Clone, PartialEq)] pub struct Hunter { pub object: Object, pub force: Scalar, pub velocity: Velocity, } /// It maintains the state of the game and expects to be updated with /// time-delta information to compute the next state. /// /// Please note that the coordinates used in the playing field start at 0 /// and grow #[derive(Debug, Clone, PartialEq)] pub struct State { /// The playing field pub field: Extent, /// The player's character pub hunter: Hunter, /// Hunted the player's character pub prey: Object, /// Obstacles the hunter must avoid to prevent game-over pub obstacles: Vec<Obstacle>, /// score of the current game pub score: u32, /// multiply prey score with the given value pub score_coeff: Scalar, /// transition between opaque and invisible obstacles pub obstacle_opacity: Transition, /// transition between no attracting force and maximum one pub attracting_force: Transition, /// Last delta-time during update pub last_dt: f64, }
ObstacleKind
identifier_name
types.rs
use vecmath::{self, vec2_sub, vec2_len}; pub type Scalar = f64; /// [width, height] pub type Extent = vecmath::Vector2<Scalar>; /// [x, y] pub type Position = vecmath::Vector2<Scalar>; pub type Velocity = vecmath::Vector2<Scalar>; use transition::Transition; /// Points on screen. Usually they correspond to pixels, but might not on a /// `HiDPI` display pub type Pt = Scalar; /// Represents a shape used for collision detection #[derive(Debug, Clone, PartialEq)] pub enum CollisionShape { Square, Circle, } /// A game object which knows a few things about itself #[derive(Debug, Clone, PartialEq)] pub struct Object { pub pos: Position, pub half_size: Pt, pub shape: CollisionShape, } impl Object { pub fn left(&self) -> Scalar { self.pos[0] - self.half_size } pub fn right(&self) -> Scalar { self.pos[0] + self.half_size
pub fn top(&self) -> Scalar { self.pos[1] - self.half_size } pub fn bottom(&self) -> Scalar { self.pos[1] + self.half_size } /// Returns true if both objects intersect pub fn intersects(&self, other: &Object) -> bool { match (&self.shape, &other.shape) { (&CollisionShape::Circle, &CollisionShape::Circle) => { vec2_len(vec2_sub(self.pos, other.pos)) <= self.half_size + other.half_size } _ => { self.left() <= other.right() && self.right() >= other.left() && self.top() <= other.bottom() && self.bottom() >= other.top() } } } } #[derive(Debug, Clone, PartialEq)] pub enum ObstacleKind { /// Enables a temporary attractive force AttractiveForceSwitch, /// Causes all other obstacles to hide themselves for a while InvisibiltySwitch, /// Kills the player Deadly, } /// An obstacle the hunter can collide with #[derive(Debug, Clone, PartialEq)] pub struct Obstacle { pub kind: ObstacleKind, pub object: Object, pub velocity: Velocity, } #[derive(Debug, Clone, PartialEq)] pub struct Hunter { pub object: Object, pub force: Scalar, pub velocity: Velocity, } /// It maintains the state of the game and expects to be updated with /// time-delta information to compute the next state. /// /// Please note that the coordinates used in the playing field start at 0 /// and grow #[derive(Debug, Clone, PartialEq)] pub struct State { /// The playing field pub field: Extent, /// The player's character pub hunter: Hunter, /// Hunted the player's character pub prey: Object, /// Obstacles the hunter must avoid to prevent game-over pub obstacles: Vec<Obstacle>, /// score of the current game pub score: u32, /// multiply prey score with the given value pub score_coeff: Scalar, /// transition between opaque and invisible obstacles pub obstacle_opacity: Transition, /// transition between no attracting force and maximum one pub attracting_force: Transition, /// Last delta-time during update pub last_dt: f64, }
}
random_line_split
lib.rs
)] grammar ); pub mod infix; mod layout; mod str_suffix; mod token; fn new_ident<Id>(type_cache: &TypeCache<Id, ArcType<Id>>, name: Id) -> TypedIdent<Id> { TypedIdent { name: name, typ: type_cache.hole(), } } type LalrpopError<'input> = lalrpop_util::ParseError<BytePos, BorrowedToken<'input>, Spanned<Error, BytePos>>; /// Shrink hidden spans to fit the visible expressions and flatten singleton blocks. fn shrink_hidden_spans<Id: std::fmt::Debug>(mut expr: SpannedExpr<Id>) -> SpannedExpr<Id> { match expr.value { Expr::Infix { rhs: ref last,.. } | Expr::IfElse(_, _, ref last) | Expr::TypeBindings(_, ref last) | Expr::Do(Do { body: ref last,.. }) => { expr.span = Span::new(expr.span.start(), last.span.end()) } Expr::LetBindings(_, ref last) => expr.span = Span::new(expr.span.start(), last.span.end()), Expr::Lambda(ref lambda) => { expr.span = Span::new(expr.span.start(), lambda.body.span.end()) } Expr::Block(ref mut exprs) => match exprs { [] => (), [e] => { return std::mem::take(e); } _ => expr.span = Span::new(expr.span.start(), exprs.last().unwrap().span.end()), }, Expr::Match(_, ref alts) => { if let Some(last_alt) = alts.last() { let end = last_alt.expr.span.end(); expr.span = Span::new(expr.span.start(), end); } } Expr::Annotated(..) | Expr::App {.. } | Expr::Ident(_) | Expr::Literal(_) | Expr::Projection(_, _, _) | Expr::Array(_) | Expr::Record {.. } | Expr::Tuple {.. } | Expr::MacroExpansion {.. } | Expr::Error(..) => (), } expr } fn transform_errors<'a, Iter>( source_span: Span<BytePos>, errors: Iter, ) -> Errors<Spanned<Error, BytePos>> where Iter: IntoIterator<Item = LalrpopError<'a>>, { errors .into_iter() .map(|err| Error::from_lalrpop(source_span, err)) .collect() } struct Expected<'a>(&'a [String]); impl<'a> fmt::Display for Expected<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.0.len() { 0 => (), 1 => write!(f, "\nExpected ")?, _ => write!(f, "\nExpected one of ")?, } for (i, token) in self.0.iter().enumerate() { let sep = match i { 0 => "", i if i + 1 < self.0.len() => ",", _ => " or", }; write!(f, "{} {}", sep, token)?; } Ok(()) } } quick_error! { #[derive(Debug, Eq, PartialEq, Hash, Clone)] pub enum Error { Token(err: TokenizeError) { display("{}", err) from() } Layout(err: LayoutError) { display("{}", err) from() } InvalidToken { display("Invalid token") } UnexpectedToken(token: Token<String>, expected: Vec<String>) { display("Unexpected token: {}{}", token, Expected(&expected)) } UnexpectedEof(expected: Vec<String>) { display("Unexpected end of file{}", Expected(&expected)) } ExtraToken(token: Token<String>) { display("Extra token: {}", token) } Infix(err: InfixError) { display("{}", err) from() } Message(msg: String) { display("{}", msg) from() } } } impl AsDiagnostic for Error { fn as_diagnostic( &self, _map: &base::source::CodeMap, ) -> codespan_reporting::diagnostic::Diagnostic<source::FileId> { codespan_reporting::diagnostic::Diagnostic::error().with_message(self.to_string()) } } /// LALRPOP currently has an unnecessary set of `"` around each expected token fn remove_extra_quotes(tokens: &mut [String]) { for token in tokens { if token.starts_with('"') && token.ends_with('"') { token.remove(0); token.pop(); } } } impl Error { fn from_lalrpop(source_span: Span<BytePos>, err: LalrpopError) -> Spanned<Error, BytePos> { use lalrpop_util::ParseError::*; match err { InvalidToken { location } => pos::spanned2(location, location, Error::InvalidToken), UnrecognizedToken { token: (lpos, token, rpos), mut expected, } => { remove_extra_quotes(&mut expected); pos::spanned2( lpos, rpos, Error::UnexpectedToken(token.map(|s| s.into()), expected), ) } UnrecognizedEOF { location, mut expected, } => { // LALRPOP will use `Default::default()` as the location if it is unable to find // one. This is not correct for codespan as that represents "nil" so we must grab // the end from the current source instead let location = if location == BytePos::default() { source_span.end() } else { location }; remove_extra_quotes(&mut expected); pos::spanned2(location, location, Error::UnexpectedEof(expected))
ExtraToken { token: (lpos, token, rpos), } => pos::spanned2(lpos, rpos, Error::ExtraToken(token.map(|s| s.into()))), User { error } => error, } } } #[derive(Debug)] pub enum FieldExpr<'ast, Id> { Type( BaseMetadata<'ast>, Spanned<Id, BytePos>, Option<ArcType<Id>>, ), Value( BaseMetadata<'ast>, Spanned<Id, BytePos>, Option<SpannedExpr<'ast, Id>>, ), } pub enum Variant<'ast, Id> { Gadt(Sp<Id>, AstType<'ast, Id>), Simple(Sp<Id>, Vec<AstType<'ast, Id>>), } // Hack around LALRPOP's limited type syntax type MutIdentEnv<'env, Id> = &'env mut dyn IdentEnv<Ident = Id>; type ErrorEnv<'err, 'input> = &'err mut Errors<LalrpopError<'input>>; type Slice<T> = [T]; trait TempVec<'ast, Id>: Sized { fn select<'a>(vecs: &'a mut TempVecs<'ast, Id>) -> &'a mut Vec<Self>; } macro_rules! impl_temp_vec { ($( $ty: ty => $field: ident),* $(,)?) => { #[doc(hidden)] pub struct TempVecs<'ast, Id> { $( $field: Vec<$ty>, )* } #[doc(hidden)] #[derive(Debug)] pub struct TempVecStart<T>(usize, PhantomData<T>); impl<'ast, Id> TempVecs<'ast, Id> { fn new() -> Self { TempVecs { $( $field: Vec::new(), )* } } fn start<T>(&mut self) -> TempVecStart<T> where T: TempVec<'ast, Id>, { TempVecStart(T::select(self).len(), PhantomData) } fn select<T>(&mut self) -> &mut Vec<T> where T: TempVec<'ast, Id>, { T::select(self) } fn drain<'a, T>(&'a mut self, start: TempVecStart<T>) -> impl DoubleEndedIterator<Item = T> + 'a where T: TempVec<'ast, Id> + 'a, { T::select(self).drain(start.0..) } fn drain_n<'a, T>(&'a mut self, n: usize) -> impl DoubleEndedIterator<Item = T> + 'a where T: TempVec<'ast, Id> + 'a, { let vec = T::select(self); let start = vec.len() - n; vec.drain(start..) } } $( impl<'ast, Id> TempVec<'ast, Id> for $ty { fn select<'a>(vecs: &'a mut TempVecs<'ast, Id>) -> &'a mut Vec<Self> { &mut vecs.$field } } )* }; } impl_temp_vec! { SpannedExpr<'ast, Id> => exprs, SpannedPattern<'ast, Id> => patterns, ast::PatternField<'ast, Id> => pattern_field, ast::ExprField<'ast, Id, ArcType<Id>> => expr_field_types, ast::ExprField<'ast, Id, SpannedExpr<'ast, Id>> => expr_field_exprs, ast::TypeBinding<'ast, Id> => type_bindings, ValueBinding<'ast, Id> => value_bindings, ast::Do<'ast, Id> => do_exprs, ast::Alternative<'ast, Id> => alts, ast::Argument<ast::SpannedIdent<Id>> => args, FieldExpr<'ast, Id> => field_expr, ast::InnerAstType<'ast, Id> => types, AstType<'ast, Id> => type_ptrs, Generic<Id> => generics, Field<Spanned<Id, BytePos>, AstType<'ast, Id>> => type_fields, Field<Spanned<Id, BytePos>, Alias<Id, AstType<'ast, Id>>> => type_type_fields, Either<Field<Spanned<Id, BytePos>, Alias<Id, AstType<'ast, Id>>>, Field<Spanned<Id, BytePos>, AstType<'ast, Id>>> => either_type_fields, } pub type ParseErrors = Errors<Spanned<Error, BytePos>>; pub trait ParserSource { fn src(&self) -> &str; fn start_index(&self) -> BytePos; fn span(&self) -> Span<BytePos> { let start = self.start_index(); Span::new(start, start + ByteOffset::from(self.src().len() as i64)) } } impl<'a, S> ParserSource for &'a S where S:?Sized + ParserSource, { fn src(&self) -> &str { (**self).src() } fn start_index(&self) -> BytePos { (**self).start_index() } } impl ParserSource for str { fn src(&self) -> &str { self } fn start_index(&self) -> BytePos { BytePos::from(1) } } impl ParserSource for source::FileMap { fn src(&self) -> &str { source::FileMap::source(self) } fn start_index(&self) -> BytePos { source::Source::span(self).start() } } pub fn parse_partial_root_expr<Id, S>( symbols: &mut dyn IdentEnv<Ident = Id>, type_cache: &TypeCache<Id, ArcType<Id>>, input: &S, ) -> Result<RootExpr<Id>, (Option<RootExpr<Id>>, ParseErrors)> where Id: Clone + AsRef<str> + std::fmt::Debug, S:?Sized + ParserSource, { mk_ast_arena!(arena); parse_partial_expr((*arena).borrow(), symbols, type_cache, input) .map_err(|(expr, err)| { ( expr.map(|expr| RootExpr::new(arena.clone(), arena.alloc(expr))), err, ) }) .map(|expr| RootExpr::new(arena.clone(), arena.alloc(expr))) } pub fn parse_partial_expr<'ast, Id, S>( arena: ast::ArenaRef<'_, 'ast, Id>, symbols: &mut dyn IdentEnv<Ident = Id>, type_cache: &TypeCache<Id, ArcType<Id>>, input: &S, ) -> Result<SpannedExpr<'ast, Id>, (Option<SpannedExpr<'ast, Id>>, ParseErrors)> where Id: Clone + AsRef<str> + std::fmt::Debug, S:?Sized + ParserSource, { parse_with(input, &mut |parse_errors, layout| { grammar::TopExprParser::new().parse( &input, type_cache, arena, symbols, parse_errors, &mut TempVecs::new(), layout, ) }) } pub fn parse_expr<'ast>( arena: ast::ArenaRef<'_, 'ast, Symbol>, symbols: &mut dyn IdentEnv<Ident = Symbol>, type_cache: &TypeCache<Symbol, ArcType>, input: &str, ) -> Result<SpannedExpr<'ast, Symbol>, ParseErrors> { parse_partial_expr(arena, symbols, type_cache, input).map_err(|t| t.1) } #[derive(Debug, PartialEq)] pub enum ReplLine<'ast, Id> { Expr(SpannedExpr<'ast, Id>), Let(&'ast mut ValueBinding<'ast, Id>), } pub fn parse_partial_repl_line<'ast, Id, S>( arena: ast::ArenaRef<'_, 'ast, Id>, symbols: &mut dyn IdentEnv<Ident = Id>, input: &S, ) -> Result<Option<ReplLine<'ast, Id>>, (Option<ReplLine<'ast, Id>>, ParseErrors)> where Id: Clone + Eq + Hash + AsRef<str> + ::std::fmt::Debug, S:?Sized + ParserSource, { parse_with(input, &mut |parse_errors, layout| { let type_cache = TypeCache::default(); grammar::ReplLineParser::new() .parse( &input, &type_cache, arena, symbols, parse_errors, &mut TempVecs::new(), layout, ) .map(|o| o.map(|b| *b)) }) .map_err(|(opt, err)| (opt.and_then(|opt| opt), err)) } fn parse_with<'ast, 'input, S, T>( input: &'input S, parse: &mut dyn FnMut( ErrorEnv<'_, 'input>, Layout<'input, &mut Tokenizer<'input>>, ) -> Result< T, lalrpop_util::ParseError<BytePos, Token<&'input str>, Spanned<Error, BytePos>>, >, ) -> Result<T, (Option<T>, ParseErrors)> where S:?Sized + ParserSource, { let mut tokenizer = Tokenizer::new(input); let layout = Layout::new(&mut tokenizer); let mut parse_errors = Errors::new(); let result = parse(&mut parse_errors, layout); let mut all_errors = transform_errors(input.span(), parse_errors); all_errors.extend(tokenizer.errors.drain(..).map(|sp_error| { pos::spanned2( sp_error.span.start().absolute, sp_error.span.end().absolute, sp_error.value.into(), ) })); match result { Ok(value) => { if all_errors.has_errors() { Err((Some(value), all_errors)) } else { Ok(value) } } Err(err) => { all_errors.push(Error::from_lalrpop(input.span(), err)); Err((None, all_errors)) } } } pub fn reparse_infix<'ast, Id>( arena: ast::ArenaRef<'_, 'ast, Id>, metadata: &FnvMap<Id, Arc<Metadata>>, symbols: &dyn IdentEnv<Ident = Id>, expr: &mut SpannedExpr<'ast, Id>, ) -> Result<(), ParseErrors> where Id: Clone + Eq + Hash + AsRef<str> + ::std::fmt::Debug, { use crate::base::ast::{is_operator_char, walk_pattern, Pattern, Visitor}; let mut errors = Errors::new(); struct CheckInfix<'b, Id> where Id: 'b, { metadata: &'b FnvMap<Id, Arc<Metadata>>, errors: &'b mut Errors<Spanned<Error, BytePos>>, op_table: &'b mut OpTable<Id>, } impl<'b, Id> CheckInfix<'b, Id> where Id: Clone + Eq + Hash + AsRef<str>, { fn insert_infix(&mut self, id: &Id, span: Span<BytePos>) { match self .metadata .get(id) .and_then(|meta| meta.get_attribute("infix")) { Some(infix_attribute) => { fn parse_infix(s: &str) -> Result<OpMeta, InfixError> { let mut iter = s.splitn(2, ","); let fixity = match iter.next().ok_or(InfixError::InvalidFixity)?.trim() { "left" => Fixity::Left, "right" => Fixity::Right, _ => { return Err(InfixError::InvalidFixity); } }; let precedence = iter .next() .and_then(|s| s.trim().parse().ok()) .and_then(|precedence| { if precedence >= 0 { Some(precedence) } else { None } }) .ok_or(InfixError::InvalidPrecedence)?; Ok(OpMeta { fixity, precedence }) } match parse_infix(infix_attribute) { Ok(op_meta) => { self.op_table.operators.insert(id.clone(), op_meta); } Err(err) => { self.errors.push(pos::spanned(span, err.into())); } } } None => { if id.as_ref().starts_with(is_operator_char) {
}
random_line_split
lib.rs
grammar ); pub mod infix; mod layout; mod str_suffix; mod token; fn new_ident<Id>(type_cache: &TypeCache<Id, ArcType<Id>>, name: Id) -> TypedIdent<Id> { TypedIdent { name: name, typ: type_cache.hole(), } } type LalrpopError<'input> = lalrpop_util::ParseError<BytePos, BorrowedToken<'input>, Spanned<Error, BytePos>>; /// Shrink hidden spans to fit the visible expressions and flatten singleton blocks. fn shrink_hidden_spans<Id: std::fmt::Debug>(mut expr: SpannedExpr<Id>) -> SpannedExpr<Id> { match expr.value { Expr::Infix { rhs: ref last,.. } | Expr::IfElse(_, _, ref last) | Expr::TypeBindings(_, ref last) | Expr::Do(Do { body: ref last,.. }) => { expr.span = Span::new(expr.span.start(), last.span.end()) } Expr::LetBindings(_, ref last) => expr.span = Span::new(expr.span.start(), last.span.end()), Expr::Lambda(ref lambda) => { expr.span = Span::new(expr.span.start(), lambda.body.span.end()) } Expr::Block(ref mut exprs) => match exprs { [] => (), [e] => { return std::mem::take(e); } _ => expr.span = Span::new(expr.span.start(), exprs.last().unwrap().span.end()), }, Expr::Match(_, ref alts) => { if let Some(last_alt) = alts.last() { let end = last_alt.expr.span.end(); expr.span = Span::new(expr.span.start(), end); } } Expr::Annotated(..) | Expr::App {.. } | Expr::Ident(_) | Expr::Literal(_) | Expr::Projection(_, _, _) | Expr::Array(_) | Expr::Record {.. } | Expr::Tuple {.. } | Expr::MacroExpansion {.. } | Expr::Error(..) => (), } expr } fn transform_errors<'a, Iter>( source_span: Span<BytePos>, errors: Iter, ) -> Errors<Spanned<Error, BytePos>> where Iter: IntoIterator<Item = LalrpopError<'a>>, { errors .into_iter() .map(|err| Error::from_lalrpop(source_span, err)) .collect() } struct Expected<'a>(&'a [String]); impl<'a> fmt::Display for Expected<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.0.len() { 0 => (), 1 => write!(f, "\nExpected ")?, _ => write!(f, "\nExpected one of ")?, } for (i, token) in self.0.iter().enumerate() { let sep = match i { 0 => "", i if i + 1 < self.0.len() => ",", _ => " or", }; write!(f, "{} {}", sep, token)?; } Ok(()) } } quick_error! { #[derive(Debug, Eq, PartialEq, Hash, Clone)] pub enum Error { Token(err: TokenizeError) { display("{}", err) from() } Layout(err: LayoutError) { display("{}", err) from() } InvalidToken { display("Invalid token") } UnexpectedToken(token: Token<String>, expected: Vec<String>) { display("Unexpected token: {}{}", token, Expected(&expected)) } UnexpectedEof(expected: Vec<String>) { display("Unexpected end of file{}", Expected(&expected)) } ExtraToken(token: Token<String>) { display("Extra token: {}", token) } Infix(err: InfixError) { display("{}", err) from() } Message(msg: String) { display("{}", msg) from() } } } impl AsDiagnostic for Error { fn as_diagnostic( &self, _map: &base::source::CodeMap, ) -> codespan_reporting::diagnostic::Diagnostic<source::FileId> { codespan_reporting::diagnostic::Diagnostic::error().with_message(self.to_string()) } } /// LALRPOP currently has an unnecessary set of `"` around each expected token fn remove_extra_quotes(tokens: &mut [String]) { for token in tokens { if token.starts_with('"') && token.ends_with('"') { token.remove(0); token.pop(); } } } impl Error { fn from_lalrpop(source_span: Span<BytePos>, err: LalrpopError) -> Spanned<Error, BytePos> { use lalrpop_util::ParseError::*; match err { InvalidToken { location } => pos::spanned2(location, location, Error::InvalidToken), UnrecognizedToken { token: (lpos, token, rpos), mut expected, } => { remove_extra_quotes(&mut expected); pos::spanned2( lpos, rpos, Error::UnexpectedToken(token.map(|s| s.into()), expected), ) } UnrecognizedEOF { location, mut expected, } => { // LALRPOP will use `Default::default()` as the location if it is unable to find // one. This is not correct for codespan as that represents "nil" so we must grab // the end from the current source instead let location = if location == BytePos::default() { source_span.end() } else { location }; remove_extra_quotes(&mut expected); pos::spanned2(location, location, Error::UnexpectedEof(expected)) } ExtraToken { token: (lpos, token, rpos), } => pos::spanned2(lpos, rpos, Error::ExtraToken(token.map(|s| s.into()))), User { error } => error, } } } #[derive(Debug)] pub enum FieldExpr<'ast, Id> { Type( BaseMetadata<'ast>, Spanned<Id, BytePos>, Option<ArcType<Id>>, ), Value( BaseMetadata<'ast>, Spanned<Id, BytePos>, Option<SpannedExpr<'ast, Id>>, ), } pub enum Variant<'ast, Id> { Gadt(Sp<Id>, AstType<'ast, Id>), Simple(Sp<Id>, Vec<AstType<'ast, Id>>), } // Hack around LALRPOP's limited type syntax type MutIdentEnv<'env, Id> = &'env mut dyn IdentEnv<Ident = Id>; type ErrorEnv<'err, 'input> = &'err mut Errors<LalrpopError<'input>>; type Slice<T> = [T]; trait TempVec<'ast, Id>: Sized { fn select<'a>(vecs: &'a mut TempVecs<'ast, Id>) -> &'a mut Vec<Self>; } macro_rules! impl_temp_vec { ($( $ty: ty => $field: ident),* $(,)?) => { #[doc(hidden)] pub struct TempVecs<'ast, Id> { $( $field: Vec<$ty>, )* } #[doc(hidden)] #[derive(Debug)] pub struct TempVecStart<T>(usize, PhantomData<T>); impl<'ast, Id> TempVecs<'ast, Id> { fn new() -> Self { TempVecs { $( $field: Vec::new(), )* } } fn start<T>(&mut self) -> TempVecStart<T> where T: TempVec<'ast, Id>, { TempVecStart(T::select(self).len(), PhantomData) } fn select<T>(&mut self) -> &mut Vec<T> where T: TempVec<'ast, Id>, { T::select(self) } fn drain<'a, T>(&'a mut self, start: TempVecStart<T>) -> impl DoubleEndedIterator<Item = T> + 'a where T: TempVec<'ast, Id> + 'a, { T::select(self).drain(start.0..) } fn drain_n<'a, T>(&'a mut self, n: usize) -> impl DoubleEndedIterator<Item = T> + 'a where T: TempVec<'ast, Id> + 'a, { let vec = T::select(self); let start = vec.len() - n; vec.drain(start..) } } $( impl<'ast, Id> TempVec<'ast, Id> for $ty { fn select<'a>(vecs: &'a mut TempVecs<'ast, Id>) -> &'a mut Vec<Self> { &mut vecs.$field } } )* }; } impl_temp_vec! { SpannedExpr<'ast, Id> => exprs, SpannedPattern<'ast, Id> => patterns, ast::PatternField<'ast, Id> => pattern_field, ast::ExprField<'ast, Id, ArcType<Id>> => expr_field_types, ast::ExprField<'ast, Id, SpannedExpr<'ast, Id>> => expr_field_exprs, ast::TypeBinding<'ast, Id> => type_bindings, ValueBinding<'ast, Id> => value_bindings, ast::Do<'ast, Id> => do_exprs, ast::Alternative<'ast, Id> => alts, ast::Argument<ast::SpannedIdent<Id>> => args, FieldExpr<'ast, Id> => field_expr, ast::InnerAstType<'ast, Id> => types, AstType<'ast, Id> => type_ptrs, Generic<Id> => generics, Field<Spanned<Id, BytePos>, AstType<'ast, Id>> => type_fields, Field<Spanned<Id, BytePos>, Alias<Id, AstType<'ast, Id>>> => type_type_fields, Either<Field<Spanned<Id, BytePos>, Alias<Id, AstType<'ast, Id>>>, Field<Spanned<Id, BytePos>, AstType<'ast, Id>>> => either_type_fields, } pub type ParseErrors = Errors<Spanned<Error, BytePos>>; pub trait ParserSource { fn src(&self) -> &str; fn start_index(&self) -> BytePos; fn span(&self) -> Span<BytePos> { let start = self.start_index(); Span::new(start, start + ByteOffset::from(self.src().len() as i64)) } } impl<'a, S> ParserSource for &'a S where S:?Sized + ParserSource, { fn src(&self) -> &str { (**self).src() } fn start_index(&self) -> BytePos { (**self).start_index() } } impl ParserSource for str { fn src(&self) -> &str { self } fn start_index(&self) -> BytePos { BytePos::from(1) } } impl ParserSource for source::FileMap { fn src(&self) -> &str { source::FileMap::source(self) } fn start_index(&self) -> BytePos { source::Source::span(self).start() } } pub fn parse_partial_root_expr<Id, S>( symbols: &mut dyn IdentEnv<Ident = Id>, type_cache: &TypeCache<Id, ArcType<Id>>, input: &S, ) -> Result<RootExpr<Id>, (Option<RootExpr<Id>>, ParseErrors)> where Id: Clone + AsRef<str> + std::fmt::Debug, S:?Sized + ParserSource, { mk_ast_arena!(arena); parse_partial_expr((*arena).borrow(), symbols, type_cache, input) .map_err(|(expr, err)| { ( expr.map(|expr| RootExpr::new(arena.clone(), arena.alloc(expr))), err, ) }) .map(|expr| RootExpr::new(arena.clone(), arena.alloc(expr))) } pub fn parse_partial_expr<'ast, Id, S>( arena: ast::ArenaRef<'_, 'ast, Id>, symbols: &mut dyn IdentEnv<Ident = Id>, type_cache: &TypeCache<Id, ArcType<Id>>, input: &S, ) -> Result<SpannedExpr<'ast, Id>, (Option<SpannedExpr<'ast, Id>>, ParseErrors)> where Id: Clone + AsRef<str> + std::fmt::Debug, S:?Sized + ParserSource, { parse_with(input, &mut |parse_errors, layout| { grammar::TopExprParser::new().parse( &input, type_cache, arena, symbols, parse_errors, &mut TempVecs::new(), layout, ) }) } pub fn parse_expr<'ast>( arena: ast::ArenaRef<'_, 'ast, Symbol>, symbols: &mut dyn IdentEnv<Ident = Symbol>, type_cache: &TypeCache<Symbol, ArcType>, input: &str, ) -> Result<SpannedExpr<'ast, Symbol>, ParseErrors> { parse_partial_expr(arena, symbols, type_cache, input).map_err(|t| t.1) } #[derive(Debug, PartialEq)] pub enum ReplLine<'ast, Id> { Expr(SpannedExpr<'ast, Id>), Let(&'ast mut ValueBinding<'ast, Id>), } pub fn parse_partial_repl_line<'ast, Id, S>( arena: ast::ArenaRef<'_, 'ast, Id>, symbols: &mut dyn IdentEnv<Ident = Id>, input: &S, ) -> Result<Option<ReplLine<'ast, Id>>, (Option<ReplLine<'ast, Id>>, ParseErrors)> where Id: Clone + Eq + Hash + AsRef<str> + ::std::fmt::Debug, S:?Sized + ParserSource, { parse_with(input, &mut |parse_errors, layout| { let type_cache = TypeCache::default(); grammar::ReplLineParser::new() .parse( &input, &type_cache, arena, symbols, parse_errors, &mut TempVecs::new(), layout, ) .map(|o| o.map(|b| *b)) }) .map_err(|(opt, err)| (opt.and_then(|opt| opt), err)) } fn parse_with<'ast, 'input, S, T>( input: &'input S, parse: &mut dyn FnMut( ErrorEnv<'_, 'input>, Layout<'input, &mut Tokenizer<'input>>, ) -> Result< T, lalrpop_util::ParseError<BytePos, Token<&'input str>, Spanned<Error, BytePos>>, >, ) -> Result<T, (Option<T>, ParseErrors)> where S:?Sized + ParserSource, { let mut tokenizer = Tokenizer::new(input); let layout = Layout::new(&mut tokenizer); let mut parse_errors = Errors::new(); let result = parse(&mut parse_errors, layout); let mut all_errors = transform_errors(input.span(), parse_errors); all_errors.extend(tokenizer.errors.drain(..).map(|sp_error| { pos::spanned2( sp_error.span.start().absolute, sp_error.span.end().absolute, sp_error.value.into(), ) })); match result { Ok(value) => { if all_errors.has_errors() { Err((Some(value), all_errors)) } else { Ok(value) } } Err(err) => { all_errors.push(Error::from_lalrpop(input.span(), err)); Err((None, all_errors)) } } } pub fn reparse_infix<'ast, Id>( arena: ast::ArenaRef<'_, 'ast, Id>, metadata: &FnvMap<Id, Arc<Metadata>>, symbols: &dyn IdentEnv<Ident = Id>, expr: &mut SpannedExpr<'ast, Id>, ) -> Result<(), ParseErrors> where Id: Clone + Eq + Hash + AsRef<str> + ::std::fmt::Debug, { use crate::base::ast::{is_operator_char, walk_pattern, Pattern, Visitor}; let mut errors = Errors::new(); struct CheckInfix<'b, Id> where Id: 'b, { metadata: &'b FnvMap<Id, Arc<Metadata>>, errors: &'b mut Errors<Spanned<Error, BytePos>>, op_table: &'b mut OpTable<Id>, } impl<'b, Id> CheckInfix<'b, Id> where Id: Clone + Eq + Hash + AsRef<str>, { fn insert_infix(&mut self, id: &Id, span: Span<BytePos>) { match self .metadata .get(id) .and_then(|meta| meta.get_attribute("infix")) { Some(infix_attribute) => { fn parse_infix(s: &str) -> Result<OpMeta, InfixError>
Ok(OpMeta { fixity, precedence }) } match parse_infix(infix_attribute) { Ok(op_meta) => { self.op_table.operators.insert(id.clone(), op_meta); } Err(err) => { self.errors.push(pos::spanned(span, err.into())); } } } None => { if id.as_ref().starts_with(is_operator_char) {
{ let mut iter = s.splitn(2, ","); let fixity = match iter.next().ok_or(InfixError::InvalidFixity)?.trim() { "left" => Fixity::Left, "right" => Fixity::Right, _ => { return Err(InfixError::InvalidFixity); } }; let precedence = iter .next() .and_then(|s| s.trim().parse().ok()) .and_then(|precedence| { if precedence >= 0 { Some(precedence) } else { None } }) .ok_or(InfixError::InvalidPrecedence)?;
identifier_body
lib.rs
grammar ); pub mod infix; mod layout; mod str_suffix; mod token; fn new_ident<Id>(type_cache: &TypeCache<Id, ArcType<Id>>, name: Id) -> TypedIdent<Id> { TypedIdent { name: name, typ: type_cache.hole(), } } type LalrpopError<'input> = lalrpop_util::ParseError<BytePos, BorrowedToken<'input>, Spanned<Error, BytePos>>; /// Shrink hidden spans to fit the visible expressions and flatten singleton blocks. fn shrink_hidden_spans<Id: std::fmt::Debug>(mut expr: SpannedExpr<Id>) -> SpannedExpr<Id> { match expr.value { Expr::Infix { rhs: ref last,.. } | Expr::IfElse(_, _, ref last) | Expr::TypeBindings(_, ref last) | Expr::Do(Do { body: ref last,.. }) => { expr.span = Span::new(expr.span.start(), last.span.end()) } Expr::LetBindings(_, ref last) => expr.span = Span::new(expr.span.start(), last.span.end()), Expr::Lambda(ref lambda) => { expr.span = Span::new(expr.span.start(), lambda.body.span.end()) } Expr::Block(ref mut exprs) => match exprs { [] => (), [e] => { return std::mem::take(e); } _ => expr.span = Span::new(expr.span.start(), exprs.last().unwrap().span.end()), }, Expr::Match(_, ref alts) => { if let Some(last_alt) = alts.last() { let end = last_alt.expr.span.end(); expr.span = Span::new(expr.span.start(), end); } } Expr::Annotated(..) | Expr::App {.. } | Expr::Ident(_) | Expr::Literal(_) | Expr::Projection(_, _, _) | Expr::Array(_) | Expr::Record {.. } | Expr::Tuple {.. } | Expr::MacroExpansion {.. } | Expr::Error(..) => (), } expr } fn transform_errors<'a, Iter>( source_span: Span<BytePos>, errors: Iter, ) -> Errors<Spanned<Error, BytePos>> where Iter: IntoIterator<Item = LalrpopError<'a>>, { errors .into_iter() .map(|err| Error::from_lalrpop(source_span, err)) .collect() } struct Expected<'a>(&'a [String]); impl<'a> fmt::Display for Expected<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.0.len() { 0 => (), 1 => write!(f, "\nExpected ")?, _ => write!(f, "\nExpected one of ")?, } for (i, token) in self.0.iter().enumerate() { let sep = match i { 0 => "", i if i + 1 < self.0.len() => ",", _ => " or", }; write!(f, "{} {}", sep, token)?; } Ok(()) } } quick_error! { #[derive(Debug, Eq, PartialEq, Hash, Clone)] pub enum Error { Token(err: TokenizeError) { display("{}", err) from() } Layout(err: LayoutError) { display("{}", err) from() } InvalidToken { display("Invalid token") } UnexpectedToken(token: Token<String>, expected: Vec<String>) { display("Unexpected token: {}{}", token, Expected(&expected)) } UnexpectedEof(expected: Vec<String>) { display("Unexpected end of file{}", Expected(&expected)) } ExtraToken(token: Token<String>) { display("Extra token: {}", token) } Infix(err: InfixError) { display("{}", err) from() } Message(msg: String) { display("{}", msg) from() } } } impl AsDiagnostic for Error { fn as_diagnostic( &self, _map: &base::source::CodeMap, ) -> codespan_reporting::diagnostic::Diagnostic<source::FileId> { codespan_reporting::diagnostic::Diagnostic::error().with_message(self.to_string()) } } /// LALRPOP currently has an unnecessary set of `"` around each expected token fn remove_extra_quotes(tokens: &mut [String]) { for token in tokens { if token.starts_with('"') && token.ends_with('"') { token.remove(0); token.pop(); } } } impl Error { fn from_lalrpop(source_span: Span<BytePos>, err: LalrpopError) -> Spanned<Error, BytePos> { use lalrpop_util::ParseError::*; match err { InvalidToken { location } => pos::spanned2(location, location, Error::InvalidToken), UnrecognizedToken { token: (lpos, token, rpos), mut expected, } => { remove_extra_quotes(&mut expected); pos::spanned2( lpos, rpos, Error::UnexpectedToken(token.map(|s| s.into()), expected), ) } UnrecognizedEOF { location, mut expected, } =>
ExtraToken { token: (lpos, token, rpos), } => pos::spanned2(lpos, rpos, Error::ExtraToken(token.map(|s| s.into()))), User { error } => error, } } } #[derive(Debug)] pub enum FieldExpr<'ast, Id> { Type( BaseMetadata<'ast>, Spanned<Id, BytePos>, Option<ArcType<Id>>, ), Value( BaseMetadata<'ast>, Spanned<Id, BytePos>, Option<SpannedExpr<'ast, Id>>, ), } pub enum Variant<'ast, Id> { Gadt(Sp<Id>, AstType<'ast, Id>), Simple(Sp<Id>, Vec<AstType<'ast, Id>>), } // Hack around LALRPOP's limited type syntax type MutIdentEnv<'env, Id> = &'env mut dyn IdentEnv<Ident = Id>; type ErrorEnv<'err, 'input> = &'err mut Errors<LalrpopError<'input>>; type Slice<T> = [T]; trait TempVec<'ast, Id>: Sized { fn select<'a>(vecs: &'a mut TempVecs<'ast, Id>) -> &'a mut Vec<Self>; } macro_rules! impl_temp_vec { ($( $ty: ty => $field: ident),* $(,)?) => { #[doc(hidden)] pub struct TempVecs<'ast, Id> { $( $field: Vec<$ty>, )* } #[doc(hidden)] #[derive(Debug)] pub struct TempVecStart<T>(usize, PhantomData<T>); impl<'ast, Id> TempVecs<'ast, Id> { fn new() -> Self { TempVecs { $( $field: Vec::new(), )* } } fn start<T>(&mut self) -> TempVecStart<T> where T: TempVec<'ast, Id>, { TempVecStart(T::select(self).len(), PhantomData) } fn select<T>(&mut self) -> &mut Vec<T> where T: TempVec<'ast, Id>, { T::select(self) } fn drain<'a, T>(&'a mut self, start: TempVecStart<T>) -> impl DoubleEndedIterator<Item = T> + 'a where T: TempVec<'ast, Id> + 'a, { T::select(self).drain(start.0..) } fn drain_n<'a, T>(&'a mut self, n: usize) -> impl DoubleEndedIterator<Item = T> + 'a where T: TempVec<'ast, Id> + 'a, { let vec = T::select(self); let start = vec.len() - n; vec.drain(start..) } } $( impl<'ast, Id> TempVec<'ast, Id> for $ty { fn select<'a>(vecs: &'a mut TempVecs<'ast, Id>) -> &'a mut Vec<Self> { &mut vecs.$field } } )* }; } impl_temp_vec! { SpannedExpr<'ast, Id> => exprs, SpannedPattern<'ast, Id> => patterns, ast::PatternField<'ast, Id> => pattern_field, ast::ExprField<'ast, Id, ArcType<Id>> => expr_field_types, ast::ExprField<'ast, Id, SpannedExpr<'ast, Id>> => expr_field_exprs, ast::TypeBinding<'ast, Id> => type_bindings, ValueBinding<'ast, Id> => value_bindings, ast::Do<'ast, Id> => do_exprs, ast::Alternative<'ast, Id> => alts, ast::Argument<ast::SpannedIdent<Id>> => args, FieldExpr<'ast, Id> => field_expr, ast::InnerAstType<'ast, Id> => types, AstType<'ast, Id> => type_ptrs, Generic<Id> => generics, Field<Spanned<Id, BytePos>, AstType<'ast, Id>> => type_fields, Field<Spanned<Id, BytePos>, Alias<Id, AstType<'ast, Id>>> => type_type_fields, Either<Field<Spanned<Id, BytePos>, Alias<Id, AstType<'ast, Id>>>, Field<Spanned<Id, BytePos>, AstType<'ast, Id>>> => either_type_fields, } pub type ParseErrors = Errors<Spanned<Error, BytePos>>; pub trait ParserSource { fn src(&self) -> &str; fn start_index(&self) -> BytePos; fn span(&self) -> Span<BytePos> { let start = self.start_index(); Span::new(start, start + ByteOffset::from(self.src().len() as i64)) } } impl<'a, S> ParserSource for &'a S where S:?Sized + ParserSource, { fn src(&self) -> &str { (**self).src() } fn start_index(&self) -> BytePos { (**self).start_index() } } impl ParserSource for str { fn src(&self) -> &str { self } fn start_index(&self) -> BytePos { BytePos::from(1) } } impl ParserSource for source::FileMap { fn src(&self) -> &str { source::FileMap::source(self) } fn start_index(&self) -> BytePos { source::Source::span(self).start() } } pub fn parse_partial_root_expr<Id, S>( symbols: &mut dyn IdentEnv<Ident = Id>, type_cache: &TypeCache<Id, ArcType<Id>>, input: &S, ) -> Result<RootExpr<Id>, (Option<RootExpr<Id>>, ParseErrors)> where Id: Clone + AsRef<str> + std::fmt::Debug, S:?Sized + ParserSource, { mk_ast_arena!(arena); parse_partial_expr((*arena).borrow(), symbols, type_cache, input) .map_err(|(expr, err)| { ( expr.map(|expr| RootExpr::new(arena.clone(), arena.alloc(expr))), err, ) }) .map(|expr| RootExpr::new(arena.clone(), arena.alloc(expr))) } pub fn parse_partial_expr<'ast, Id, S>( arena: ast::ArenaRef<'_, 'ast, Id>, symbols: &mut dyn IdentEnv<Ident = Id>, type_cache: &TypeCache<Id, ArcType<Id>>, input: &S, ) -> Result<SpannedExpr<'ast, Id>, (Option<SpannedExpr<'ast, Id>>, ParseErrors)> where Id: Clone + AsRef<str> + std::fmt::Debug, S:?Sized + ParserSource, { parse_with(input, &mut |parse_errors, layout| { grammar::TopExprParser::new().parse( &input, type_cache, arena, symbols, parse_errors, &mut TempVecs::new(), layout, ) }) } pub fn parse_expr<'ast>( arena: ast::ArenaRef<'_, 'ast, Symbol>, symbols: &mut dyn IdentEnv<Ident = Symbol>, type_cache: &TypeCache<Symbol, ArcType>, input: &str, ) -> Result<SpannedExpr<'ast, Symbol>, ParseErrors> { parse_partial_expr(arena, symbols, type_cache, input).map_err(|t| t.1) } #[derive(Debug, PartialEq)] pub enum ReplLine<'ast, Id> { Expr(SpannedExpr<'ast, Id>), Let(&'ast mut ValueBinding<'ast, Id>), } pub fn parse_partial_repl_line<'ast, Id, S>( arena: ast::ArenaRef<'_, 'ast, Id>, symbols: &mut dyn IdentEnv<Ident = Id>, input: &S, ) -> Result<Option<ReplLine<'ast, Id>>, (Option<ReplLine<'ast, Id>>, ParseErrors)> where Id: Clone + Eq + Hash + AsRef<str> + ::std::fmt::Debug, S:?Sized + ParserSource, { parse_with(input, &mut |parse_errors, layout| { let type_cache = TypeCache::default(); grammar::ReplLineParser::new() .parse( &input, &type_cache, arena, symbols, parse_errors, &mut TempVecs::new(), layout, ) .map(|o| o.map(|b| *b)) }) .map_err(|(opt, err)| (opt.and_then(|opt| opt), err)) } fn parse_with<'ast, 'input, S, T>( input: &'input S, parse: &mut dyn FnMut( ErrorEnv<'_, 'input>, Layout<'input, &mut Tokenizer<'input>>, ) -> Result< T, lalrpop_util::ParseError<BytePos, Token<&'input str>, Spanned<Error, BytePos>>, >, ) -> Result<T, (Option<T>, ParseErrors)> where S:?Sized + ParserSource, { let mut tokenizer = Tokenizer::new(input); let layout = Layout::new(&mut tokenizer); let mut parse_errors = Errors::new(); let result = parse(&mut parse_errors, layout); let mut all_errors = transform_errors(input.span(), parse_errors); all_errors.extend(tokenizer.errors.drain(..).map(|sp_error| { pos::spanned2( sp_error.span.start().absolute, sp_error.span.end().absolute, sp_error.value.into(), ) })); match result { Ok(value) => { if all_errors.has_errors() { Err((Some(value), all_errors)) } else { Ok(value) } } Err(err) => { all_errors.push(Error::from_lalrpop(input.span(), err)); Err((None, all_errors)) } } } pub fn reparse_infix<'ast, Id>( arena: ast::ArenaRef<'_, 'ast, Id>, metadata: &FnvMap<Id, Arc<Metadata>>, symbols: &dyn IdentEnv<Ident = Id>, expr: &mut SpannedExpr<'ast, Id>, ) -> Result<(), ParseErrors> where Id: Clone + Eq + Hash + AsRef<str> + ::std::fmt::Debug, { use crate::base::ast::{is_operator_char, walk_pattern, Pattern, Visitor}; let mut errors = Errors::new(); struct CheckInfix<'b, Id> where Id: 'b, { metadata: &'b FnvMap<Id, Arc<Metadata>>, errors: &'b mut Errors<Spanned<Error, BytePos>>, op_table: &'b mut OpTable<Id>, } impl<'b, Id> CheckInfix<'b, Id> where Id: Clone + Eq + Hash + AsRef<str>, { fn insert_infix(&mut self, id: &Id, span: Span<BytePos>) { match self .metadata .get(id) .and_then(|meta| meta.get_attribute("infix")) { Some(infix_attribute) => { fn parse_infix(s: &str) -> Result<OpMeta, InfixError> { let mut iter = s.splitn(2, ","); let fixity = match iter.next().ok_or(InfixError::InvalidFixity)?.trim() { "left" => Fixity::Left, "right" => Fixity::Right, _ => { return Err(InfixError::InvalidFixity); } }; let precedence = iter .next() .and_then(|s| s.trim().parse().ok()) .and_then(|precedence| { if precedence >= 0 { Some(precedence) } else { None } }) .ok_or(InfixError::InvalidPrecedence)?; Ok(OpMeta { fixity, precedence }) } match parse_infix(infix_attribute) { Ok(op_meta) => { self.op_table.operators.insert(id.clone(), op_meta); } Err(err) => { self.errors.push(pos::spanned(span, err.into())); } } } None => { if id.as_ref().starts_with(is_operator_char) {
{ // LALRPOP will use `Default::default()` as the location if it is unable to find // one. This is not correct for codespan as that represents "nil" so we must grab // the end from the current source instead let location = if location == BytePos::default() { source_span.end() } else { location }; remove_extra_quotes(&mut expected); pos::spanned2(location, location, Error::UnexpectedEof(expected)) }
conditional_block
lib.rs
grammar ); pub mod infix; mod layout; mod str_suffix; mod token; fn new_ident<Id>(type_cache: &TypeCache<Id, ArcType<Id>>, name: Id) -> TypedIdent<Id> { TypedIdent { name: name, typ: type_cache.hole(), } } type LalrpopError<'input> = lalrpop_util::ParseError<BytePos, BorrowedToken<'input>, Spanned<Error, BytePos>>; /// Shrink hidden spans to fit the visible expressions and flatten singleton blocks. fn shrink_hidden_spans<Id: std::fmt::Debug>(mut expr: SpannedExpr<Id>) -> SpannedExpr<Id> { match expr.value { Expr::Infix { rhs: ref last,.. } | Expr::IfElse(_, _, ref last) | Expr::TypeBindings(_, ref last) | Expr::Do(Do { body: ref last,.. }) => { expr.span = Span::new(expr.span.start(), last.span.end()) } Expr::LetBindings(_, ref last) => expr.span = Span::new(expr.span.start(), last.span.end()), Expr::Lambda(ref lambda) => { expr.span = Span::new(expr.span.start(), lambda.body.span.end()) } Expr::Block(ref mut exprs) => match exprs { [] => (), [e] => { return std::mem::take(e); } _ => expr.span = Span::new(expr.span.start(), exprs.last().unwrap().span.end()), }, Expr::Match(_, ref alts) => { if let Some(last_alt) = alts.last() { let end = last_alt.expr.span.end(); expr.span = Span::new(expr.span.start(), end); } } Expr::Annotated(..) | Expr::App {.. } | Expr::Ident(_) | Expr::Literal(_) | Expr::Projection(_, _, _) | Expr::Array(_) | Expr::Record {.. } | Expr::Tuple {.. } | Expr::MacroExpansion {.. } | Expr::Error(..) => (), } expr } fn
<'a, Iter>( source_span: Span<BytePos>, errors: Iter, ) -> Errors<Spanned<Error, BytePos>> where Iter: IntoIterator<Item = LalrpopError<'a>>, { errors .into_iter() .map(|err| Error::from_lalrpop(source_span, err)) .collect() } struct Expected<'a>(&'a [String]); impl<'a> fmt::Display for Expected<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.0.len() { 0 => (), 1 => write!(f, "\nExpected ")?, _ => write!(f, "\nExpected one of ")?, } for (i, token) in self.0.iter().enumerate() { let sep = match i { 0 => "", i if i + 1 < self.0.len() => ",", _ => " or", }; write!(f, "{} {}", sep, token)?; } Ok(()) } } quick_error! { #[derive(Debug, Eq, PartialEq, Hash, Clone)] pub enum Error { Token(err: TokenizeError) { display("{}", err) from() } Layout(err: LayoutError) { display("{}", err) from() } InvalidToken { display("Invalid token") } UnexpectedToken(token: Token<String>, expected: Vec<String>) { display("Unexpected token: {}{}", token, Expected(&expected)) } UnexpectedEof(expected: Vec<String>) { display("Unexpected end of file{}", Expected(&expected)) } ExtraToken(token: Token<String>) { display("Extra token: {}", token) } Infix(err: InfixError) { display("{}", err) from() } Message(msg: String) { display("{}", msg) from() } } } impl AsDiagnostic for Error { fn as_diagnostic( &self, _map: &base::source::CodeMap, ) -> codespan_reporting::diagnostic::Diagnostic<source::FileId> { codespan_reporting::diagnostic::Diagnostic::error().with_message(self.to_string()) } } /// LALRPOP currently has an unnecessary set of `"` around each expected token fn remove_extra_quotes(tokens: &mut [String]) { for token in tokens { if token.starts_with('"') && token.ends_with('"') { token.remove(0); token.pop(); } } } impl Error { fn from_lalrpop(source_span: Span<BytePos>, err: LalrpopError) -> Spanned<Error, BytePos> { use lalrpop_util::ParseError::*; match err { InvalidToken { location } => pos::spanned2(location, location, Error::InvalidToken), UnrecognizedToken { token: (lpos, token, rpos), mut expected, } => { remove_extra_quotes(&mut expected); pos::spanned2( lpos, rpos, Error::UnexpectedToken(token.map(|s| s.into()), expected), ) } UnrecognizedEOF { location, mut expected, } => { // LALRPOP will use `Default::default()` as the location if it is unable to find // one. This is not correct for codespan as that represents "nil" so we must grab // the end from the current source instead let location = if location == BytePos::default() { source_span.end() } else { location }; remove_extra_quotes(&mut expected); pos::spanned2(location, location, Error::UnexpectedEof(expected)) } ExtraToken { token: (lpos, token, rpos), } => pos::spanned2(lpos, rpos, Error::ExtraToken(token.map(|s| s.into()))), User { error } => error, } } } #[derive(Debug)] pub enum FieldExpr<'ast, Id> { Type( BaseMetadata<'ast>, Spanned<Id, BytePos>, Option<ArcType<Id>>, ), Value( BaseMetadata<'ast>, Spanned<Id, BytePos>, Option<SpannedExpr<'ast, Id>>, ), } pub enum Variant<'ast, Id> { Gadt(Sp<Id>, AstType<'ast, Id>), Simple(Sp<Id>, Vec<AstType<'ast, Id>>), } // Hack around LALRPOP's limited type syntax type MutIdentEnv<'env, Id> = &'env mut dyn IdentEnv<Ident = Id>; type ErrorEnv<'err, 'input> = &'err mut Errors<LalrpopError<'input>>; type Slice<T> = [T]; trait TempVec<'ast, Id>: Sized { fn select<'a>(vecs: &'a mut TempVecs<'ast, Id>) -> &'a mut Vec<Self>; } macro_rules! impl_temp_vec { ($( $ty: ty => $field: ident),* $(,)?) => { #[doc(hidden)] pub struct TempVecs<'ast, Id> { $( $field: Vec<$ty>, )* } #[doc(hidden)] #[derive(Debug)] pub struct TempVecStart<T>(usize, PhantomData<T>); impl<'ast, Id> TempVecs<'ast, Id> { fn new() -> Self { TempVecs { $( $field: Vec::new(), )* } } fn start<T>(&mut self) -> TempVecStart<T> where T: TempVec<'ast, Id>, { TempVecStart(T::select(self).len(), PhantomData) } fn select<T>(&mut self) -> &mut Vec<T> where T: TempVec<'ast, Id>, { T::select(self) } fn drain<'a, T>(&'a mut self, start: TempVecStart<T>) -> impl DoubleEndedIterator<Item = T> + 'a where T: TempVec<'ast, Id> + 'a, { T::select(self).drain(start.0..) } fn drain_n<'a, T>(&'a mut self, n: usize) -> impl DoubleEndedIterator<Item = T> + 'a where T: TempVec<'ast, Id> + 'a, { let vec = T::select(self); let start = vec.len() - n; vec.drain(start..) } } $( impl<'ast, Id> TempVec<'ast, Id> for $ty { fn select<'a>(vecs: &'a mut TempVecs<'ast, Id>) -> &'a mut Vec<Self> { &mut vecs.$field } } )* }; } impl_temp_vec! { SpannedExpr<'ast, Id> => exprs, SpannedPattern<'ast, Id> => patterns, ast::PatternField<'ast, Id> => pattern_field, ast::ExprField<'ast, Id, ArcType<Id>> => expr_field_types, ast::ExprField<'ast, Id, SpannedExpr<'ast, Id>> => expr_field_exprs, ast::TypeBinding<'ast, Id> => type_bindings, ValueBinding<'ast, Id> => value_bindings, ast::Do<'ast, Id> => do_exprs, ast::Alternative<'ast, Id> => alts, ast::Argument<ast::SpannedIdent<Id>> => args, FieldExpr<'ast, Id> => field_expr, ast::InnerAstType<'ast, Id> => types, AstType<'ast, Id> => type_ptrs, Generic<Id> => generics, Field<Spanned<Id, BytePos>, AstType<'ast, Id>> => type_fields, Field<Spanned<Id, BytePos>, Alias<Id, AstType<'ast, Id>>> => type_type_fields, Either<Field<Spanned<Id, BytePos>, Alias<Id, AstType<'ast, Id>>>, Field<Spanned<Id, BytePos>, AstType<'ast, Id>>> => either_type_fields, } pub type ParseErrors = Errors<Spanned<Error, BytePos>>; pub trait ParserSource { fn src(&self) -> &str; fn start_index(&self) -> BytePos; fn span(&self) -> Span<BytePos> { let start = self.start_index(); Span::new(start, start + ByteOffset::from(self.src().len() as i64)) } } impl<'a, S> ParserSource for &'a S where S:?Sized + ParserSource, { fn src(&self) -> &str { (**self).src() } fn start_index(&self) -> BytePos { (**self).start_index() } } impl ParserSource for str { fn src(&self) -> &str { self } fn start_index(&self) -> BytePos { BytePos::from(1) } } impl ParserSource for source::FileMap { fn src(&self) -> &str { source::FileMap::source(self) } fn start_index(&self) -> BytePos { source::Source::span(self).start() } } pub fn parse_partial_root_expr<Id, S>( symbols: &mut dyn IdentEnv<Ident = Id>, type_cache: &TypeCache<Id, ArcType<Id>>, input: &S, ) -> Result<RootExpr<Id>, (Option<RootExpr<Id>>, ParseErrors)> where Id: Clone + AsRef<str> + std::fmt::Debug, S:?Sized + ParserSource, { mk_ast_arena!(arena); parse_partial_expr((*arena).borrow(), symbols, type_cache, input) .map_err(|(expr, err)| { ( expr.map(|expr| RootExpr::new(arena.clone(), arena.alloc(expr))), err, ) }) .map(|expr| RootExpr::new(arena.clone(), arena.alloc(expr))) } pub fn parse_partial_expr<'ast, Id, S>( arena: ast::ArenaRef<'_, 'ast, Id>, symbols: &mut dyn IdentEnv<Ident = Id>, type_cache: &TypeCache<Id, ArcType<Id>>, input: &S, ) -> Result<SpannedExpr<'ast, Id>, (Option<SpannedExpr<'ast, Id>>, ParseErrors)> where Id: Clone + AsRef<str> + std::fmt::Debug, S:?Sized + ParserSource, { parse_with(input, &mut |parse_errors, layout| { grammar::TopExprParser::new().parse( &input, type_cache, arena, symbols, parse_errors, &mut TempVecs::new(), layout, ) }) } pub fn parse_expr<'ast>( arena: ast::ArenaRef<'_, 'ast, Symbol>, symbols: &mut dyn IdentEnv<Ident = Symbol>, type_cache: &TypeCache<Symbol, ArcType>, input: &str, ) -> Result<SpannedExpr<'ast, Symbol>, ParseErrors> { parse_partial_expr(arena, symbols, type_cache, input).map_err(|t| t.1) } #[derive(Debug, PartialEq)] pub enum ReplLine<'ast, Id> { Expr(SpannedExpr<'ast, Id>), Let(&'ast mut ValueBinding<'ast, Id>), } pub fn parse_partial_repl_line<'ast, Id, S>( arena: ast::ArenaRef<'_, 'ast, Id>, symbols: &mut dyn IdentEnv<Ident = Id>, input: &S, ) -> Result<Option<ReplLine<'ast, Id>>, (Option<ReplLine<'ast, Id>>, ParseErrors)> where Id: Clone + Eq + Hash + AsRef<str> + ::std::fmt::Debug, S:?Sized + ParserSource, { parse_with(input, &mut |parse_errors, layout| { let type_cache = TypeCache::default(); grammar::ReplLineParser::new() .parse( &input, &type_cache, arena, symbols, parse_errors, &mut TempVecs::new(), layout, ) .map(|o| o.map(|b| *b)) }) .map_err(|(opt, err)| (opt.and_then(|opt| opt), err)) } fn parse_with<'ast, 'input, S, T>( input: &'input S, parse: &mut dyn FnMut( ErrorEnv<'_, 'input>, Layout<'input, &mut Tokenizer<'input>>, ) -> Result< T, lalrpop_util::ParseError<BytePos, Token<&'input str>, Spanned<Error, BytePos>>, >, ) -> Result<T, (Option<T>, ParseErrors)> where S:?Sized + ParserSource, { let mut tokenizer = Tokenizer::new(input); let layout = Layout::new(&mut tokenizer); let mut parse_errors = Errors::new(); let result = parse(&mut parse_errors, layout); let mut all_errors = transform_errors(input.span(), parse_errors); all_errors.extend(tokenizer.errors.drain(..).map(|sp_error| { pos::spanned2( sp_error.span.start().absolute, sp_error.span.end().absolute, sp_error.value.into(), ) })); match result { Ok(value) => { if all_errors.has_errors() { Err((Some(value), all_errors)) } else { Ok(value) } } Err(err) => { all_errors.push(Error::from_lalrpop(input.span(), err)); Err((None, all_errors)) } } } pub fn reparse_infix<'ast, Id>( arena: ast::ArenaRef<'_, 'ast, Id>, metadata: &FnvMap<Id, Arc<Metadata>>, symbols: &dyn IdentEnv<Ident = Id>, expr: &mut SpannedExpr<'ast, Id>, ) -> Result<(), ParseErrors> where Id: Clone + Eq + Hash + AsRef<str> + ::std::fmt::Debug, { use crate::base::ast::{is_operator_char, walk_pattern, Pattern, Visitor}; let mut errors = Errors::new(); struct CheckInfix<'b, Id> where Id: 'b, { metadata: &'b FnvMap<Id, Arc<Metadata>>, errors: &'b mut Errors<Spanned<Error, BytePos>>, op_table: &'b mut OpTable<Id>, } impl<'b, Id> CheckInfix<'b, Id> where Id: Clone + Eq + Hash + AsRef<str>, { fn insert_infix(&mut self, id: &Id, span: Span<BytePos>) { match self .metadata .get(id) .and_then(|meta| meta.get_attribute("infix")) { Some(infix_attribute) => { fn parse_infix(s: &str) -> Result<OpMeta, InfixError> { let mut iter = s.splitn(2, ","); let fixity = match iter.next().ok_or(InfixError::InvalidFixity)?.trim() { "left" => Fixity::Left, "right" => Fixity::Right, _ => { return Err(InfixError::InvalidFixity); } }; let precedence = iter .next() .and_then(|s| s.trim().parse().ok()) .and_then(|precedence| { if precedence >= 0 { Some(precedence) } else { None } }) .ok_or(InfixError::InvalidPrecedence)?; Ok(OpMeta { fixity, precedence }) } match parse_infix(infix_attribute) { Ok(op_meta) => { self.op_table.operators.insert(id.clone(), op_meta); } Err(err) => { self.errors.push(pos::spanned(span, err.into())); } } } None => { if id.as_ref().starts_with(is_operator_char) {
transform_errors
identifier_name
issue-4252.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
// xfail-test trait X { fn call(&self); } struct Y; struct Z<T> { x: T } impl X for Y { fn call(&self) { } } impl<T: X> Drop for Z<T> { fn drop(&mut self) { self.x.call(); // Adding this statement causes an ICE. } } fn main() { let y = Y; let _z = Z{x: y}; }
random_line_split
issue-4252.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-test trait X { fn call(&self); } struct Y; struct Z<T> { x: T } impl X for Y { fn call(&self) { } } impl<T: X> Drop for Z<T> { fn drop(&mut self) { self.x.call(); // Adding this statement causes an ICE. } } fn
() { let y = Y; let _z = Z{x: y}; }
main
identifier_name
issue-4252.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-test trait X { fn call(&self); } struct Y; struct Z<T> { x: T } impl X for Y { fn call(&self)
} impl<T: X> Drop for Z<T> { fn drop(&mut self) { self.x.call(); // Adding this statement causes an ICE. } } fn main() { let y = Y; let _z = Z{x: y}; }
{ }
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/. */ #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[macro_use] extern crate num_derive; #[macro_use] extern crate serde; pub mod resources; use crossbeam_channel::{Receiver, Sender}; use ipc_channel::ipc::IpcSender; use keyboard_types::KeyboardEvent; use msg::constellation_msg::{InputMethodType, PipelineId, TopLevelBrowsingContextId}; use servo_url::ServoUrl; use std::fmt::{Debug, Error, Formatter}; use webrender_api::units::{DeviceIntPoint, DeviceIntSize}; pub use webxr_api::MainThreadWaker as EventLoopWaker; /// A cursor for the window. This is different from a CSS cursor (see /// `CursorKind`) in that it has no `Auto` value. #[repr(u8)] #[derive(Clone, Copy, Deserialize, Eq, FromPrimitive, PartialEq, Serialize)] pub enum Cursor { None, Default, Pointer, ContextMenu, Help, Progress, Wait, Cell, Crosshair, Text, VerticalText, Alias, Copy, Move, NoDrop, NotAllowed, Grab, Grabbing, EResize, NResize, NeResize, NwResize, SResize, SeResize, SwResize, WResize, EwResize, NsResize, NeswResize, NwseResize, ColResize, RowResize, AllScroll, ZoomIn, ZoomOut, } /// Sends messages to the embedder. pub struct EmbedderProxy { pub sender: Sender<(Option<TopLevelBrowsingContextId>, EmbedderMsg)>, pub event_loop_waker: Box<dyn EventLoopWaker>, }
pub fn send(&self, msg: (Option<TopLevelBrowsingContextId>, EmbedderMsg)) { // Send a message and kick the OS event loop awake. if let Err(err) = self.sender.send(msg) { warn!("Failed to send response ({:?}).", err); } self.event_loop_waker.wake(); } } impl Clone for EmbedderProxy { fn clone(&self) -> EmbedderProxy { EmbedderProxy { sender: self.sender.clone(), event_loop_waker: self.event_loop_waker.clone(), } } } /// The port that the embedder receives messages on. pub struct EmbedderReceiver { pub receiver: Receiver<(Option<TopLevelBrowsingContextId>, EmbedderMsg)>, } impl EmbedderReceiver { pub fn try_recv_embedder_msg( &mut self, ) -> Option<(Option<TopLevelBrowsingContextId>, EmbedderMsg)> { self.receiver.try_recv().ok() } pub fn recv_embedder_msg(&mut self) -> (Option<TopLevelBrowsingContextId>, EmbedderMsg) { self.receiver.recv().unwrap() } } #[derive(Deserialize, Serialize)] pub enum ContextMenuResult { Dismissed, Ignored, Selected(usize), } #[derive(Deserialize, Serialize)] pub enum PromptDefinition { /// Show a message. Alert(String, IpcSender<()>), /// Ask a Ok/Cancel question. OkCancel(String, IpcSender<PromptResult>), /// Ask a Yes/No question. YesNo(String, IpcSender<PromptResult>), /// Ask the user to enter text. Input(String, String, IpcSender<Option<String>>), } #[derive(Deserialize, PartialEq, Serialize)] pub enum PromptOrigin { /// Prompt is triggered from content (window.prompt/alert/confirm/…). /// Prompt message is unknown. Untrusted, /// Prompt is triggered from Servo (ask for permission, show error,…). Trusted, } #[derive(Deserialize, PartialEq, Serialize)] pub enum PromptResult { /// Prompt was closed by clicking on the primary button (ok/yes) Primary, /// Prompt was closed by clicking on the secondary button (cancel/no) Secondary, /// Prompt was dismissed Dismissed, } #[derive(Deserialize, Serialize)] pub enum EmbedderMsg { /// A status message to be displayed by the browser chrome. Status(Option<String>), /// Alerts the embedder that the current page has changed its title. ChangePageTitle(Option<String>), /// Move the window to a point MoveTo(DeviceIntPoint), /// Resize the window to size ResizeTo(DeviceIntSize), /// Show dialog to user Prompt(PromptDefinition, PromptOrigin), /// Show a context menu to the user ShowContextMenu(IpcSender<ContextMenuResult>, Option<String>, Vec<String>), /// Whether or not to allow a pipeline to load a url. AllowNavigationRequest(PipelineId, ServoUrl), /// Whether or not to allow script to open a new tab/browser AllowOpeningBrowser(IpcSender<bool>), /// A new browser was created by script BrowserCreated(TopLevelBrowsingContextId), /// Wether or not to unload a document AllowUnload(IpcSender<bool>), /// Sends an unconsumed key event back to the embedder. Keyboard(KeyboardEvent), /// Gets system clipboard contents GetClipboardContents(IpcSender<String>), /// Sets system clipboard contents SetClipboardContents(String), /// Changes the cursor. SetCursor(Cursor), /// A favicon was detected NewFavicon(ServoUrl), /// <head> tag finished parsing HeadParsed, /// The history state has changed. HistoryChanged(Vec<ServoUrl>, usize), /// Enter or exit fullscreen SetFullscreenState(bool), /// The load of a page has begun LoadStart, /// The load of a page has completed LoadComplete, /// A browser is to be closed CloseBrowser, /// A pipeline panicked. First string is the reason, second one is the backtrace. Panic(String, Option<String>), /// Open dialog to select bluetooth device. GetSelectedBluetoothDevice(Vec<String>, IpcSender<Option<String>>), /// Open file dialog to select files. Set boolean flag to true allows to select multiple files. SelectFiles(Vec<FilterPattern>, bool, IpcSender<Option<Vec<String>>>), /// Open interface to request permission specified by prompt. PromptPermission(PermissionPrompt, IpcSender<PermissionRequest>), /// Request to present an IME to the user when an editable element is focused. ShowIME(InputMethodType), /// Request to hide the IME when the editable element is blurred. HideIME, /// Servo has shut down Shutdown, /// Report a complete sampled profile ReportProfile(Vec<u8>), /// Notifies the embedder about media session events /// (i.e. when there is metadata for the active media session, playback state changes...). MediaSessionEvent(MediaSessionEvent), /// Report the status of Devtools Server OnDevtoolsStarted(Result<u16, ()>), } impl Debug for EmbedderMsg { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { match *self { EmbedderMsg::Status(..) => write!(f, "Status"), EmbedderMsg::ChangePageTitle(..) => write!(f, "ChangePageTitle"), EmbedderMsg::MoveTo(..) => write!(f, "MoveTo"), EmbedderMsg::ResizeTo(..) => write!(f, "ResizeTo"), EmbedderMsg::Prompt(..) => write!(f, "Prompt"), EmbedderMsg::AllowUnload(..) => write!(f, "AllowUnload"), EmbedderMsg::AllowNavigationRequest(..) => write!(f, "AllowNavigationRequest"), EmbedderMsg::Keyboard(..) => write!(f, "Keyboard"), EmbedderMsg::GetClipboardContents(..) => write!(f, "GetClipboardContents"), EmbedderMsg::SetClipboardContents(..) => write!(f, "SetClipboardContents"), EmbedderMsg::SetCursor(..) => write!(f, "SetCursor"), EmbedderMsg::NewFavicon(..) => write!(f, "NewFavicon"), EmbedderMsg::HeadParsed => write!(f, "HeadParsed"), EmbedderMsg::CloseBrowser => write!(f, "CloseBrowser"), EmbedderMsg::HistoryChanged(..) => write!(f, "HistoryChanged"), EmbedderMsg::SetFullscreenState(..) => write!(f, "SetFullscreenState"), EmbedderMsg::LoadStart => write!(f, "LoadStart"), EmbedderMsg::LoadComplete => write!(f, "LoadComplete"), EmbedderMsg::Panic(..) => write!(f, "Panic"), EmbedderMsg::GetSelectedBluetoothDevice(..) => write!(f, "GetSelectedBluetoothDevice"), EmbedderMsg::SelectFiles(..) => write!(f, "SelectFiles"), EmbedderMsg::PromptPermission(..) => write!(f, "PromptPermission"), EmbedderMsg::ShowIME(..) => write!(f, "ShowIME"), EmbedderMsg::HideIME => write!(f, "HideIME"), EmbedderMsg::Shutdown => write!(f, "Shutdown"), EmbedderMsg::AllowOpeningBrowser(..) => write!(f, "AllowOpeningBrowser"), EmbedderMsg::BrowserCreated(..) => write!(f, "BrowserCreated"), EmbedderMsg::ReportProfile(..) => write!(f, "ReportProfile"), EmbedderMsg::MediaSessionEvent(..) => write!(f, "MediaSessionEvent"), EmbedderMsg::OnDevtoolsStarted(..) => write!(f, "OnDevtoolsStarted"), EmbedderMsg::ShowContextMenu(..) => write!(f, "ShowContextMenu"), } } } /// Filter for file selection; /// the `String` content is expected to be extension (e.g, "doc", without the prefixing ".") #[derive(Clone, Debug, Deserialize, Serialize)] pub struct FilterPattern(pub String); /// https://w3c.github.io/mediasession/#mediametadata #[derive(Clone, Debug, Deserialize, Serialize)] pub struct MediaMetadata { /// Title pub title: String, /// Artist pub artist: String, /// Album pub album: String, } impl MediaMetadata { pub fn new(title: String) -> Self { Self { title, artist: "".to_owned(), album: "".to_owned(), } } } /// https://w3c.github.io/mediasession/#enumdef-mediasessionplaybackstate #[repr(i32)] #[derive(Clone, Debug, Deserialize, Serialize)] pub enum MediaSessionPlaybackState { /// The browsing context does not specify whether it’s playing or paused. None_ = 1, /// The browsing context is currently playing media and it can be paused. Playing, /// The browsing context has paused media and it can be resumed. Paused, } /// https://w3c.github.io/mediasession/#dictdef-mediapositionstate #[derive(Clone, Debug, Deserialize, Serialize)] pub struct MediaPositionState { pub duration: f64, pub playback_rate: f64, pub position: f64, } impl MediaPositionState { pub fn new(duration: f64, playback_rate: f64, position: f64) -> Self { Self { duration, playback_rate, position, } } } /// Type of events sent from script to the embedder about the media session. #[derive(Clone, Debug, Deserialize, Serialize)] pub enum MediaSessionEvent { /// Indicates that the media metadata is available. SetMetadata(MediaMetadata), /// Indicates that the playback state has changed. PlaybackStateChange(MediaSessionPlaybackState), /// Indicates that the position state is set. SetPositionState(MediaPositionState), } /// Enum with variants that match the DOM PermissionName enum #[derive(Clone, Debug, Deserialize, Serialize)] pub enum PermissionName { Geolocation, Notifications, Push, Midi, Camera, Microphone, Speaker, DeviceInfo, BackgroundSync, Bluetooth, PersistentStorage, } /// Information required to display a permission prompt #[derive(Clone, Debug, Deserialize, Serialize)] pub enum PermissionPrompt { Insecure(PermissionName), Request(PermissionName), } /// Status for prompting user for permission. #[derive(Clone, Debug, Deserialize, Serialize)] pub enum PermissionRequest { Granted, Denied, }
impl EmbedderProxy {
random_line_split
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/. */ #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[macro_use] extern crate num_derive; #[macro_use] extern crate serde; pub mod resources; use crossbeam_channel::{Receiver, Sender}; use ipc_channel::ipc::IpcSender; use keyboard_types::KeyboardEvent; use msg::constellation_msg::{InputMethodType, PipelineId, TopLevelBrowsingContextId}; use servo_url::ServoUrl; use std::fmt::{Debug, Error, Formatter}; use webrender_api::units::{DeviceIntPoint, DeviceIntSize}; pub use webxr_api::MainThreadWaker as EventLoopWaker; /// A cursor for the window. This is different from a CSS cursor (see /// `CursorKind`) in that it has no `Auto` value. #[repr(u8)] #[derive(Clone, Copy, Deserialize, Eq, FromPrimitive, PartialEq, Serialize)] pub enum Cursor { None, Default, Pointer, ContextMenu, Help, Progress, Wait, Cell, Crosshair, Text, VerticalText, Alias, Copy, Move, NoDrop, NotAllowed, Grab, Grabbing, EResize, NResize, NeResize, NwResize, SResize, SeResize, SwResize, WResize, EwResize, NsResize, NeswResize, NwseResize, ColResize, RowResize, AllScroll, ZoomIn, ZoomOut, } /// Sends messages to the embedder. pub struct EmbedderProxy { pub sender: Sender<(Option<TopLevelBrowsingContextId>, EmbedderMsg)>, pub event_loop_waker: Box<dyn EventLoopWaker>, } impl EmbedderProxy { pub fn send(&self, msg: (Option<TopLevelBrowsingContextId>, EmbedderMsg)) { // Send a message and kick the OS event loop awake. if let Err(err) = self.sender.send(msg) { warn!("Failed to send response ({:?}).", err); } self.event_loop_waker.wake(); } } impl Clone for EmbedderProxy { fn clone(&self) -> EmbedderProxy { EmbedderProxy { sender: self.sender.clone(), event_loop_waker: self.event_loop_waker.clone(), } } } /// The port that the embedder receives messages on. pub struct EmbedderReceiver { pub receiver: Receiver<(Option<TopLevelBrowsingContextId>, EmbedderMsg)>, } impl EmbedderReceiver { pub fn try_recv_embedder_msg( &mut self, ) -> Option<(Option<TopLevelBrowsingContextId>, EmbedderMsg)> { self.receiver.try_recv().ok() } pub fn recv_embedder_msg(&mut self) -> (Option<TopLevelBrowsingContextId>, EmbedderMsg) { self.receiver.recv().unwrap() } } #[derive(Deserialize, Serialize)] pub enum ContextMenuResult { Dismissed, Ignored, Selected(usize), } #[derive(Deserialize, Serialize)] pub enum PromptDefinition { /// Show a message. Alert(String, IpcSender<()>), /// Ask a Ok/Cancel question. OkCancel(String, IpcSender<PromptResult>), /// Ask a Yes/No question. YesNo(String, IpcSender<PromptResult>), /// Ask the user to enter text. Input(String, String, IpcSender<Option<String>>), } #[derive(Deserialize, PartialEq, Serialize)] pub enum PromptOrigin { /// Prompt is triggered from content (window.prompt/alert/confirm/…). /// Prompt message is unknown. Untrusted, /// Prompt is triggered from Servo (ask for permission, show error,…). Trusted, } #[derive(Deserialize, PartialEq, Serialize)] pub enum PromptResult { /// Prompt was closed by clicking on the primary button (ok/yes) Primary, /// Prompt was closed by clicking on the secondary button (cancel/no) Secondary, /// Prompt was dismissed Dismissed, } #[derive(Deserialize, Serialize)] pub enum EmbedderMsg { /// A status message to be displayed by the browser chrome. Status(Option<String>), /// Alerts the embedder that the current page has changed its title. ChangePageTitle(Option<String>), /// Move the window to a point MoveTo(DeviceIntPoint), /// Resize the window to size ResizeTo(DeviceIntSize), /// Show dialog to user Prompt(PromptDefinition, PromptOrigin), /// Show a context menu to the user ShowContextMenu(IpcSender<ContextMenuResult>, Option<String>, Vec<String>), /// Whether or not to allow a pipeline to load a url. AllowNavigationRequest(PipelineId, ServoUrl), /// Whether or not to allow script to open a new tab/browser AllowOpeningBrowser(IpcSender<bool>), /// A new browser was created by script BrowserCreated(TopLevelBrowsingContextId), /// Wether or not to unload a document AllowUnload(IpcSender<bool>), /// Sends an unconsumed key event back to the embedder. Keyboard(KeyboardEvent), /// Gets system clipboard contents GetClipboardContents(IpcSender<String>), /// Sets system clipboard contents SetClipboardContents(String), /// Changes the cursor. SetCursor(Cursor), /// A favicon was detected NewFavicon(ServoUrl), /// <head> tag finished parsing HeadParsed, /// The history state has changed. HistoryChanged(Vec<ServoUrl>, usize), /// Enter or exit fullscreen SetFullscreenState(bool), /// The load of a page has begun LoadStart, /// The load of a page has completed LoadComplete, /// A browser is to be closed CloseBrowser, /// A pipeline panicked. First string is the reason, second one is the backtrace. Panic(String, Option<String>), /// Open dialog to select bluetooth device. GetSelectedBluetoothDevice(Vec<String>, IpcSender<Option<String>>), /// Open file dialog to select files. Set boolean flag to true allows to select multiple files. SelectFiles(Vec<FilterPattern>, bool, IpcSender<Option<Vec<String>>>), /// Open interface to request permission specified by prompt. PromptPermission(PermissionPrompt, IpcSender<PermissionRequest>), /// Request to present an IME to the user when an editable element is focused. ShowIME(InputMethodType), /// Request to hide the IME when the editable element is blurred. HideIME, /// Servo has shut down Shutdown, /// Report a complete sampled profile ReportProfile(Vec<u8>), /// Notifies the embedder about media session events /// (i.e. when there is metadata for the active media session, playback state changes...). MediaSessionEvent(MediaSessionEvent), /// Report the status of Devtools Server OnDevtoolsStarted(Result<u16, ()>), } impl Debug for EmbedderMsg { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { match *self { EmbedderMsg::Status(..) => write!(f, "Status"), EmbedderMsg::ChangePageTitle(..) => write!(f, "ChangePageTitle"), EmbedderMsg::MoveTo(..) => write!(f, "MoveTo"), EmbedderMsg::ResizeTo(..) => write!(f, "ResizeTo"), EmbedderMsg::Prompt(..) => write!(f, "Prompt"), EmbedderMsg::AllowUnload(..) => write!(f, "AllowUnload"), EmbedderMsg::AllowNavigationRequest(..) => write!(f, "AllowNavigationRequest"), EmbedderMsg::Keyboard(..) => write!(f, "Keyboard"), EmbedderMsg::GetClipboardContents(..) => write!(f, "GetClipboardContents"), EmbedderMsg::SetClipboardContents(..) => write!(f, "SetClipboardContents"), EmbedderMsg::SetCursor(..) => write!(f, "SetCursor"), EmbedderMsg::NewFavicon(..) => write!(f, "NewFavicon"), EmbedderMsg::HeadParsed => write!(f, "HeadParsed"), EmbedderMsg::CloseBrowser => write!(f, "CloseBrowser"), EmbedderMsg::HistoryChanged(..) => write!(f, "HistoryChanged"), EmbedderMsg::SetFullscreenState(..) => write!(f, "SetFullscreenState"), EmbedderMsg::LoadStart => write!(f, "LoadStart"), EmbedderMsg::LoadComplete => write!(f, "LoadComplete"), EmbedderMsg::Panic(..) => write!(f, "Panic"), EmbedderMsg::GetSelectedBluetoothDevice(..) => write!(f, "GetSelectedBluetoothDevice"), EmbedderMsg::SelectFiles(..) => write!(f, "SelectFiles"), EmbedderMsg::PromptPermission(..) => write!(f, "PromptPermission"), EmbedderMsg::ShowIME(..) => write!(f, "ShowIME"), EmbedderMsg::HideIME => write!(f, "HideIME"), EmbedderMsg::Shutdown => write!(f, "Shutdown"), EmbedderMsg::AllowOpeningBrowser(..) => write!(f, "AllowOpeningBrowser"), EmbedderMsg::BrowserCreated(..) => write!(f, "BrowserCreated"), EmbedderMsg::ReportProfile(..) => write!(f, "ReportProfile"), EmbedderMsg::MediaSessionEvent(..) => write!(f, "MediaSessionEvent"), EmbedderMsg::OnDevtoolsStarted(..) => write!(f, "OnDevtoolsStarted"), EmbedderMsg::ShowContextMenu(..) => write!(f, "ShowContextMenu"), } } } /// Filter for file selection; /// the `String` content is expected to be extension (e.g, "doc", without the prefixing ".") #[derive(Clone, Debug, Deserialize, Serialize)] pub struct FilterPattern(pub String); /// https://w3c.github.io/mediasession/#mediametadata #[derive(Clone, Debug, Deserialize, Serialize)] pub struct MediaMetadata { /// Title pub title: String, /// Artist pub artist: String, /// Album pub album: String, } impl MediaMetadata { pub fn new(title: String) -> Self { Self { title, artist: "".to_owned(), album: "".to_owned(), } } } /// https://w3c.github.io/mediasession/#enumdef-mediasessionplaybackstate #[repr(i32)] #[derive(Clone, Debug, Deserialize, Serialize)] pub enum MediaSessionPlaybackState { /// The browsing context does not specify whether it’s playing or paused. None_ = 1, /// The browsing context is currently playing media and it can be paused. Playing, /// The browsing context has paused media and it can be resumed. Paused, } /// https://w3c.github.io/mediasession/#dictdef-mediapositionstate #[derive(Clone, Debug, Deserialize, Serialize)] pub struct MediaP
pub duration: f64, pub playback_rate: f64, pub position: f64, } impl MediaPositionState { pub fn new(duration: f64, playback_rate: f64, position: f64) -> Self { Self { duration, playback_rate, position, } } } /// Type of events sent from script to the embedder about the media session. #[derive(Clone, Debug, Deserialize, Serialize)] pub enum MediaSessionEvent { /// Indicates that the media metadata is available. SetMetadata(MediaMetadata), /// Indicates that the playback state has changed. PlaybackStateChange(MediaSessionPlaybackState), /// Indicates that the position state is set. SetPositionState(MediaPositionState), } /// Enum with variants that match the DOM PermissionName enum #[derive(Clone, Debug, Deserialize, Serialize)] pub enum PermissionName { Geolocation, Notifications, Push, Midi, Camera, Microphone, Speaker, DeviceInfo, BackgroundSync, Bluetooth, PersistentStorage, } /// Information required to display a permission prompt #[derive(Clone, Debug, Deserialize, Serialize)] pub enum PermissionPrompt { Insecure(PermissionName), Request(PermissionName), } /// Status for prompting user for permission. #[derive(Clone, Debug, Deserialize, Serialize)] pub enum PermissionRequest { Granted, Denied, }
ositionState {
identifier_name
isr.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]> // // 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. //! This file is not part of zinc crate, it is linked separately, alongside the //! ISRs for the platform. #![allow(missing_docs)] #[cfg(feature = "cpu_cortex-m0")] #[path="cortex_m0/isr.rs"] pub mod isr_cortex_m0;
#[path="cortex_m3/isr.rs"] pub mod isr_cortex_m4; #[cfg(feature = "mcu_lpc17xx")] #[path="lpc17xx/isr.rs"] pub mod isr_lpc17xx; #[cfg(feature = "mcu_k20")] #[path="k20/isr.rs"] pub mod isr_k20; #[cfg(feature = "mcu_tiva_c")] #[path="tiva_c/isr.rs"] pub mod isr_tiva_c;
#[cfg(feature = "cpu_cortex-m3")] #[path="cortex_m3/isr.rs"] pub mod isr_cortex_m3; #[cfg(feature = "cpu_cortex-m4")]
random_line_split
gamestate.rs
extern crate rand; use std::fmt; use rand::{Rng, SeedableRng, XorShiftRng}; pub const GRID_HEIGHT: i16 = 1000; pub const GRID_WIDTH: i16 = 400; pub const BLOCK_SIZE: i16 = 1; pub const WINDOW_HEIGHT: i16 = GRID_HEIGHT * BLOCK_SIZE; pub const WINDOW_WIDTH: i16 = GRID_WIDTH * BLOCK_SIZE; pub const RAIN_SPARSENESS: i16 = 5; pub const X: bool = true; pub const o: bool = false; #[derive(Eq, PartialEq, Clone)] pub struct Loc { pub x: i16, pub y: i16, } pub struct Map { pub map: Box<[[bool; GRID_HEIGHT as usize]; GRID_WIDTH as usize]>, } pub struct GameState { pub particles: Vec<Loc>, pub obstacles: Vec<Loc>, pub indexes_to_remove: Vec<usize>, pub map: Map, // 2D array to check occupancy pub max_x: i16, pub max_y: i16, pub rng: XorShiftRng, } impl fmt::Debug for GameState { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { writeln!(f, "GameState {{").ok(); writeln!(f, " num particles = {}", self.particles.len()).ok(); writeln!(f, " num obstacles = {}", self.obstacles.len()).ok(); writeln!(f, "}}") } } impl Map { fn is_occupied(&self, x: i16, y: i16) -> bool { // not valid is not occupied to allow particles to leave the grid if!GameState::is_valid(x, y) { false } else { unsafe { *self.map.get_unchecked(x as usize).get_unchecked(y as usize) } } } fn get_neighbours( &mut self, x: i16, y: i16, ) -> (bool, bool, bool, bool, bool, bool, bool, bool) { ( self.is_occupied(x - 1, y - 1), self.is_occupied(x, y - 1), self.is_occupied(x + 1, y - 1), self.is_occupied(x - 1, y), self.is_occupied(x + 1, y), self.is_occupied(x - 1, y + 1), self.is_occupied(x, y + 1), self.is_occupied(x - 1, y + 1), ) } fn add_coord_map(&mut self, x: i16, y: i16) { self.map[x as usize][y as usize] = true; } fn remove_coord_map(&mut self, x: i16, y: i16) { self.map[x as usize][y as usize] = false; } fn new() -> Map { // casting a vector of bools into a 2d array of bools unsafely // to avoid using unstable box_syntax // code taken from: //https://gist.github.com/anonymous/62f21e4fb7a13867891c let mut v: Vec<bool> = Vec::with_capacity(GRID_HEIGHT as usize * GRID_WIDTH as usize); for _ in 0..(GRID_HEIGHT as usize * GRID_WIDTH as usize) { v.push(false); } let v_slice = v.into_boxed_slice(); let boxed_array = unsafe { let v_raw: *const [bool] = ::std::mem::transmute(v_slice); let v_raw: *const [[bool; GRID_HEIGHT as usize]; GRID_WIDTH as usize] = v_raw as *const _; ::std::mem::transmute(v_raw) }; Map { map: boxed_array } } } impl GameState { // check if point in inside the grid pub fn
(x: i16, y: i16) -> bool { !(x < 0 || x >= GRID_WIDTH || y < 0 || y >= GRID_HEIGHT) } pub fn update(&mut self) { // MAIN LOGIC for (index, particle) in self.particles.iter_mut().enumerate() { let (x, y) = (particle.x, particle.y); let neighbours = self.map.get_neighbours(x, y); let (x_new, y_new) = match neighbours { // 1-2-3 above 4-5 sides 6-7-8 below (_, _, _, _, _, _, o, _) => (x, y + 1), //fall straight down if possible (_, X, _, o, X, _, X, _) => (x - 1, y), //move sideways if only one path (_, X, _, X, o, _, X, _) => (x + 1, y), //... // deterministic choice of path both left and right are free (_, X, _, o, o, _, X, _) => (if y & 2 == 0 { x - 1 } else { x + 1 }, y), // [_,o,_, X,X, X,X,X] => ( x, y-1 ), //boiling sand // random choice of path both left and right are free // [_,X,_, o,o, _,X,_] => ( if self.rng.gen::<i16>()&2 == 0 {x-1} else {x+1}, y ), _ => continue, }; if Self::is_valid(x_new, y_new) { self.map.remove_coord_map(x, y); self.map.add_coord_map(x_new, y_new); *particle = Loc { x: x_new, y: y_new }; } else { self.map.map[x as usize][y as usize] = false; self.indexes_to_remove.push(index); //prepare list of particles to remove } } // must use.rev(), otherwise you can't remove the last element for index in self.indexes_to_remove.iter().rev() { self.particles.swap_remove(*index); } self.indexes_to_remove.clear(); } //end update pub fn rain(&mut self) { for x in (GRID_WIDTH / 20)..19 * (GRID_WIDTH / 20) { if!self.map.is_occupied(x, 0) && self.rng.gen::<i16>() & RAIN_SPARSENESS == 0 { self.particles.push(Loc { x: x, y: 0 }); self.map.add_coord_map(x, 0); } } } fn remove_indices_in_rect( items: &mut Vec<Loc>, indexes_to_remove: &mut Vec<usize>, ul: Loc, lr: Loc, ) { for (index, p) in items.iter().enumerate() { if p.x >= ul.x && p.y >= ul.y && p.x < lr.x && p.y < lr.y { indexes_to_remove.push(index); } } for index in indexes_to_remove.iter().rev() { items.swap_remove(*index); } indexes_to_remove.clear(); } fn add_particle(&mut self, x: i16, y: i16) { self.map.add_coord_map(x, y); let loc = Loc { x: x, y: y }; self.particles.push(loc); } fn add_obstacle(&mut self, x: i16, y: i16) { self.map.add_coord_map(x, y); let loc = Loc { x: x, y: y }; self.obstacles.push(loc); } pub fn remove_square(&mut self, ux: i16, uy: i16, dx: i16, dy: i16) { if Self::is_valid(ux, uy) && Self::is_valid(ux + dx, uy + dy) { for x in ux..ux + dx { for y in uy..uy + dy { self.map.remove_coord_map(x, y); } } let ul = Loc { x: ux, y: uy }; let lr = Loc { x: ux + dx, y: uy + dy, }; Self::remove_indices_in_rect( &mut self.obstacles, &mut self.indexes_to_remove, ul.clone(), lr.clone(), ); Self::remove_indices_in_rect(&mut self.particles, &mut self.indexes_to_remove, ul, lr); } } pub fn paint_square_obstacles(&mut self, ux: i16, uy: i16, dx: i16, dy: i16) { //if Self::is_valid(ux + dx, uy + dy) { if Self::is_valid(ux, uy) && Self::is_valid(ux + dx, uy + dy) { for x in ux..ux + dx { for y in uy..uy + dy { if!self.map.is_occupied(x, y) { self.map.add_coord_map(x, y); self.add_obstacle(x, y); } } } } } pub fn new() -> GameState { GameState { particles: Vec::with_capacity(10_000), obstacles: Vec::with_capacity(10_000), indexes_to_remove: Vec::with_capacity(1000), map: Map::new(), max_x: GRID_WIDTH, max_y: GRID_HEIGHT, rng: SeedableRng::from_seed([1, 2, 3, 4]), } } } //end impl GameState
is_valid
identifier_name
gamestate.rs
extern crate rand; use std::fmt; use rand::{Rng, SeedableRng, XorShiftRng}; pub const GRID_HEIGHT: i16 = 1000; pub const GRID_WIDTH: i16 = 400; pub const BLOCK_SIZE: i16 = 1; pub const WINDOW_HEIGHT: i16 = GRID_HEIGHT * BLOCK_SIZE; pub const WINDOW_WIDTH: i16 = GRID_WIDTH * BLOCK_SIZE; pub const RAIN_SPARSENESS: i16 = 5; pub const X: bool = true; pub const o: bool = false; #[derive(Eq, PartialEq, Clone)] pub struct Loc { pub x: i16, pub y: i16, } pub struct Map { pub map: Box<[[bool; GRID_HEIGHT as usize]; GRID_WIDTH as usize]>, } pub struct GameState { pub particles: Vec<Loc>, pub obstacles: Vec<Loc>, pub indexes_to_remove: Vec<usize>, pub map: Map, // 2D array to check occupancy pub max_x: i16, pub max_y: i16, pub rng: XorShiftRng, } impl fmt::Debug for GameState { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { writeln!(f, "GameState {{").ok(); writeln!(f, " num particles = {}", self.particles.len()).ok(); writeln!(f, " num obstacles = {}", self.obstacles.len()).ok(); writeln!(f, "}}") } } impl Map { fn is_occupied(&self, x: i16, y: i16) -> bool { // not valid is not occupied to allow particles to leave the grid if!GameState::is_valid(x, y) { false } else { unsafe { *self.map.get_unchecked(x as usize).get_unchecked(y as usize) } } } fn get_neighbours( &mut self, x: i16, y: i16, ) -> (bool, bool, bool, bool, bool, bool, bool, bool) { ( self.is_occupied(x - 1, y - 1), self.is_occupied(x, y - 1), self.is_occupied(x + 1, y - 1), self.is_occupied(x - 1, y), self.is_occupied(x + 1, y), self.is_occupied(x - 1, y + 1), self.is_occupied(x, y + 1), self.is_occupied(x - 1, y + 1), ) } fn add_coord_map(&mut self, x: i16, y: i16) { self.map[x as usize][y as usize] = true; } fn remove_coord_map(&mut self, x: i16, y: i16) { self.map[x as usize][y as usize] = false; } fn new() -> Map { // casting a vector of bools into a 2d array of bools unsafely // to avoid using unstable box_syntax // code taken from: //https://gist.github.com/anonymous/62f21e4fb7a13867891c let mut v: Vec<bool> = Vec::with_capacity(GRID_HEIGHT as usize * GRID_WIDTH as usize); for _ in 0..(GRID_HEIGHT as usize * GRID_WIDTH as usize) { v.push(false); } let v_slice = v.into_boxed_slice(); let boxed_array = unsafe { let v_raw: *const [bool] = ::std::mem::transmute(v_slice); let v_raw: *const [[bool; GRID_HEIGHT as usize]; GRID_WIDTH as usize] = v_raw as *const _; ::std::mem::transmute(v_raw) }; Map { map: boxed_array } } } impl GameState { // check if point in inside the grid pub fn is_valid(x: i16, y: i16) -> bool { !(x < 0 || x >= GRID_WIDTH || y < 0 || y >= GRID_HEIGHT) } pub fn update(&mut self) { // MAIN LOGIC for (index, particle) in self.particles.iter_mut().enumerate() { let (x, y) = (particle.x, particle.y); let neighbours = self.map.get_neighbours(x, y); let (x_new, y_new) = match neighbours { // 1-2-3 above 4-5 sides 6-7-8 below (_, _, _, _, _, _, o, _) => (x, y + 1), //fall straight down if possible (_, X, _, o, X, _, X, _) => (x - 1, y), //move sideways if only one path (_, X, _, X, o, _, X, _) => (x + 1, y), //... // deterministic choice of path both left and right are free (_, X, _, o, o, _, X, _) => (if y & 2 == 0 { x - 1 } else { x + 1 }, y), // [_,o,_, X,X, X,X,X] => ( x, y-1 ), //boiling sand // random choice of path both left and right are free // [_,X,_, o,o, _,X,_] => ( if self.rng.gen::<i16>()&2 == 0 {x-1} else {x+1}, y ), _ => continue, }; if Self::is_valid(x_new, y_new) { self.map.remove_coord_map(x, y); self.map.add_coord_map(x_new, y_new); *particle = Loc { x: x_new, y: y_new }; } else { self.map.map[x as usize][y as usize] = false; self.indexes_to_remove.push(index); //prepare list of particles to remove } } // must use.rev(), otherwise you can't remove the last element for index in self.indexes_to_remove.iter().rev() { self.particles.swap_remove(*index); } self.indexes_to_remove.clear(); } //end update pub fn rain(&mut self) { for x in (GRID_WIDTH / 20)..19 * (GRID_WIDTH / 20) { if!self.map.is_occupied(x, 0) && self.rng.gen::<i16>() & RAIN_SPARSENESS == 0 { self.particles.push(Loc { x: x, y: 0 }); self.map.add_coord_map(x, 0); } } } fn remove_indices_in_rect( items: &mut Vec<Loc>, indexes_to_remove: &mut Vec<usize>, ul: Loc, lr: Loc, ) { for (index, p) in items.iter().enumerate() { if p.x >= ul.x && p.y >= ul.y && p.x < lr.x && p.y < lr.y { indexes_to_remove.push(index); } } for index in indexes_to_remove.iter().rev() { items.swap_remove(*index); } indexes_to_remove.clear(); } fn add_particle(&mut self, x: i16, y: i16) { self.map.add_coord_map(x, y); let loc = Loc { x: x, y: y }; self.particles.push(loc); } fn add_obstacle(&mut self, x: i16, y: i16) { self.map.add_coord_map(x, y); let loc = Loc { x: x, y: y }; self.obstacles.push(loc); } pub fn remove_square(&mut self, ux: i16, uy: i16, dx: i16, dy: i16) { if Self::is_valid(ux, uy) && Self::is_valid(ux + dx, uy + dy)
} pub fn paint_square_obstacles(&mut self, ux: i16, uy: i16, dx: i16, dy: i16) { //if Self::is_valid(ux + dx, uy + dy) { if Self::is_valid(ux, uy) && Self::is_valid(ux + dx, uy + dy) { for x in ux..ux + dx { for y in uy..uy + dy { if!self.map.is_occupied(x, y) { self.map.add_coord_map(x, y); self.add_obstacle(x, y); } } } } } pub fn new() -> GameState { GameState { particles: Vec::with_capacity(10_000), obstacles: Vec::with_capacity(10_000), indexes_to_remove: Vec::with_capacity(1000), map: Map::new(), max_x: GRID_WIDTH, max_y: GRID_HEIGHT, rng: SeedableRng::from_seed([1, 2, 3, 4]), } } } //end impl GameState
{ for x in ux..ux + dx { for y in uy..uy + dy { self.map.remove_coord_map(x, y); } } let ul = Loc { x: ux, y: uy }; let lr = Loc { x: ux + dx, y: uy + dy, }; Self::remove_indices_in_rect( &mut self.obstacles, &mut self.indexes_to_remove, ul.clone(), lr.clone(), ); Self::remove_indices_in_rect(&mut self.particles, &mut self.indexes_to_remove, ul, lr); }
conditional_block
gamestate.rs
extern crate rand; use std::fmt; use rand::{Rng, SeedableRng, XorShiftRng}; pub const GRID_HEIGHT: i16 = 1000; pub const GRID_WIDTH: i16 = 400; pub const BLOCK_SIZE: i16 = 1; pub const WINDOW_HEIGHT: i16 = GRID_HEIGHT * BLOCK_SIZE; pub const WINDOW_WIDTH: i16 = GRID_WIDTH * BLOCK_SIZE; pub const RAIN_SPARSENESS: i16 = 5; pub const X: bool = true; pub const o: bool = false; #[derive(Eq, PartialEq, Clone)] pub struct Loc { pub x: i16, pub y: i16, } pub struct Map { pub map: Box<[[bool; GRID_HEIGHT as usize]; GRID_WIDTH as usize]>, } pub struct GameState { pub particles: Vec<Loc>, pub obstacles: Vec<Loc>, pub indexes_to_remove: Vec<usize>, pub map: Map, // 2D array to check occupancy pub max_x: i16, pub max_y: i16, pub rng: XorShiftRng, } impl fmt::Debug for GameState { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { writeln!(f, "GameState {{").ok(); writeln!(f, " num particles = {}", self.particles.len()).ok(); writeln!(f, " num obstacles = {}", self.obstacles.len()).ok(); writeln!(f, "}}") } } impl Map { fn is_occupied(&self, x: i16, y: i16) -> bool { // not valid is not occupied to allow particles to leave the grid if!GameState::is_valid(x, y) { false } else { unsafe { *self.map.get_unchecked(x as usize).get_unchecked(y as usize) } } } fn get_neighbours( &mut self, x: i16, y: i16, ) -> (bool, bool, bool, bool, bool, bool, bool, bool) { ( self.is_occupied(x - 1, y - 1), self.is_occupied(x, y - 1), self.is_occupied(x + 1, y - 1), self.is_occupied(x - 1, y), self.is_occupied(x + 1, y), self.is_occupied(x - 1, y + 1), self.is_occupied(x, y + 1), self.is_occupied(x - 1, y + 1), ) } fn add_coord_map(&mut self, x: i16, y: i16) { self.map[x as usize][y as usize] = true; } fn remove_coord_map(&mut self, x: i16, y: i16)
fn new() -> Map { // casting a vector of bools into a 2d array of bools unsafely // to avoid using unstable box_syntax // code taken from: //https://gist.github.com/anonymous/62f21e4fb7a13867891c let mut v: Vec<bool> = Vec::with_capacity(GRID_HEIGHT as usize * GRID_WIDTH as usize); for _ in 0..(GRID_HEIGHT as usize * GRID_WIDTH as usize) { v.push(false); } let v_slice = v.into_boxed_slice(); let boxed_array = unsafe { let v_raw: *const [bool] = ::std::mem::transmute(v_slice); let v_raw: *const [[bool; GRID_HEIGHT as usize]; GRID_WIDTH as usize] = v_raw as *const _; ::std::mem::transmute(v_raw) }; Map { map: boxed_array } } } impl GameState { // check if point in inside the grid pub fn is_valid(x: i16, y: i16) -> bool { !(x < 0 || x >= GRID_WIDTH || y < 0 || y >= GRID_HEIGHT) } pub fn update(&mut self) { // MAIN LOGIC for (index, particle) in self.particles.iter_mut().enumerate() { let (x, y) = (particle.x, particle.y); let neighbours = self.map.get_neighbours(x, y); let (x_new, y_new) = match neighbours { // 1-2-3 above 4-5 sides 6-7-8 below (_, _, _, _, _, _, o, _) => (x, y + 1), //fall straight down if possible (_, X, _, o, X, _, X, _) => (x - 1, y), //move sideways if only one path (_, X, _, X, o, _, X, _) => (x + 1, y), //... // deterministic choice of path both left and right are free (_, X, _, o, o, _, X, _) => (if y & 2 == 0 { x - 1 } else { x + 1 }, y), // [_,o,_, X,X, X,X,X] => ( x, y-1 ), //boiling sand // random choice of path both left and right are free // [_,X,_, o,o, _,X,_] => ( if self.rng.gen::<i16>()&2 == 0 {x-1} else {x+1}, y ), _ => continue, }; if Self::is_valid(x_new, y_new) { self.map.remove_coord_map(x, y); self.map.add_coord_map(x_new, y_new); *particle = Loc { x: x_new, y: y_new }; } else { self.map.map[x as usize][y as usize] = false; self.indexes_to_remove.push(index); //prepare list of particles to remove } } // must use.rev(), otherwise you can't remove the last element for index in self.indexes_to_remove.iter().rev() { self.particles.swap_remove(*index); } self.indexes_to_remove.clear(); } //end update pub fn rain(&mut self) { for x in (GRID_WIDTH / 20)..19 * (GRID_WIDTH / 20) { if!self.map.is_occupied(x, 0) && self.rng.gen::<i16>() & RAIN_SPARSENESS == 0 { self.particles.push(Loc { x: x, y: 0 }); self.map.add_coord_map(x, 0); } } } fn remove_indices_in_rect( items: &mut Vec<Loc>, indexes_to_remove: &mut Vec<usize>, ul: Loc, lr: Loc, ) { for (index, p) in items.iter().enumerate() { if p.x >= ul.x && p.y >= ul.y && p.x < lr.x && p.y < lr.y { indexes_to_remove.push(index); } } for index in indexes_to_remove.iter().rev() { items.swap_remove(*index); } indexes_to_remove.clear(); } fn add_particle(&mut self, x: i16, y: i16) { self.map.add_coord_map(x, y); let loc = Loc { x: x, y: y }; self.particles.push(loc); } fn add_obstacle(&mut self, x: i16, y: i16) { self.map.add_coord_map(x, y); let loc = Loc { x: x, y: y }; self.obstacles.push(loc); } pub fn remove_square(&mut self, ux: i16, uy: i16, dx: i16, dy: i16) { if Self::is_valid(ux, uy) && Self::is_valid(ux + dx, uy + dy) { for x in ux..ux + dx { for y in uy..uy + dy { self.map.remove_coord_map(x, y); } } let ul = Loc { x: ux, y: uy }; let lr = Loc { x: ux + dx, y: uy + dy, }; Self::remove_indices_in_rect( &mut self.obstacles, &mut self.indexes_to_remove, ul.clone(), lr.clone(), ); Self::remove_indices_in_rect(&mut self.particles, &mut self.indexes_to_remove, ul, lr); } } pub fn paint_square_obstacles(&mut self, ux: i16, uy: i16, dx: i16, dy: i16) { //if Self::is_valid(ux + dx, uy + dy) { if Self::is_valid(ux, uy) && Self::is_valid(ux + dx, uy + dy) { for x in ux..ux + dx { for y in uy..uy + dy { if!self.map.is_occupied(x, y) { self.map.add_coord_map(x, y); self.add_obstacle(x, y); } } } } } pub fn new() -> GameState { GameState { particles: Vec::with_capacity(10_000), obstacles: Vec::with_capacity(10_000), indexes_to_remove: Vec::with_capacity(1000), map: Map::new(), max_x: GRID_WIDTH, max_y: GRID_HEIGHT, rng: SeedableRng::from_seed([1, 2, 3, 4]), } } } //end impl GameState
{ self.map[x as usize][y as usize] = false; }
identifier_body
gamestate.rs
extern crate rand; use std::fmt; use rand::{Rng, SeedableRng, XorShiftRng}; pub const GRID_HEIGHT: i16 = 1000; pub const GRID_WIDTH: i16 = 400; pub const BLOCK_SIZE: i16 = 1; pub const WINDOW_HEIGHT: i16 = GRID_HEIGHT * BLOCK_SIZE; pub const WINDOW_WIDTH: i16 = GRID_WIDTH * BLOCK_SIZE; pub const RAIN_SPARSENESS: i16 = 5; pub const X: bool = true; pub const o: bool = false; #[derive(Eq, PartialEq, Clone)] pub struct Loc { pub x: i16, pub y: i16, } pub struct Map { pub map: Box<[[bool; GRID_HEIGHT as usize]; GRID_WIDTH as usize]>, } pub struct GameState { pub particles: Vec<Loc>, pub obstacles: Vec<Loc>, pub indexes_to_remove: Vec<usize>, pub map: Map, // 2D array to check occupancy pub max_x: i16, pub max_y: i16, pub rng: XorShiftRng, } impl fmt::Debug for GameState { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { writeln!(f, "GameState {{").ok(); writeln!(f, " num particles = {}", self.particles.len()).ok(); writeln!(f, " num obstacles = {}", self.obstacles.len()).ok(); writeln!(f, "}}") } } impl Map { fn is_occupied(&self, x: i16, y: i16) -> bool { // not valid is not occupied to allow particles to leave the grid if!GameState::is_valid(x, y) { false } else { unsafe { *self.map.get_unchecked(x as usize).get_unchecked(y as usize) } } } fn get_neighbours( &mut self, x: i16, y: i16, ) -> (bool, bool, bool, bool, bool, bool, bool, bool) { ( self.is_occupied(x - 1, y - 1), self.is_occupied(x, y - 1), self.is_occupied(x + 1, y - 1), self.is_occupied(x - 1, y), self.is_occupied(x + 1, y), self.is_occupied(x - 1, y + 1), self.is_occupied(x, y + 1), self.is_occupied(x - 1, y + 1), ) } fn add_coord_map(&mut self, x: i16, y: i16) { self.map[x as usize][y as usize] = true; } fn remove_coord_map(&mut self, x: i16, y: i16) { self.map[x as usize][y as usize] = false; } fn new() -> Map { // casting a vector of bools into a 2d array of bools unsafely // to avoid using unstable box_syntax // code taken from: //https://gist.github.com/anonymous/62f21e4fb7a13867891c let mut v: Vec<bool> = Vec::with_capacity(GRID_HEIGHT as usize * GRID_WIDTH as usize); for _ in 0..(GRID_HEIGHT as usize * GRID_WIDTH as usize) { v.push(false); } let v_slice = v.into_boxed_slice(); let boxed_array = unsafe { let v_raw: *const [bool] = ::std::mem::transmute(v_slice); let v_raw: *const [[bool; GRID_HEIGHT as usize]; GRID_WIDTH as usize] = v_raw as *const _; ::std::mem::transmute(v_raw) }; Map { map: boxed_array } } } impl GameState { // check if point in inside the grid pub fn is_valid(x: i16, y: i16) -> bool { !(x < 0 || x >= GRID_WIDTH || y < 0 || y >= GRID_HEIGHT) } pub fn update(&mut self) {
let neighbours = self.map.get_neighbours(x, y); let (x_new, y_new) = match neighbours { // 1-2-3 above 4-5 sides 6-7-8 below (_, _, _, _, _, _, o, _) => (x, y + 1), //fall straight down if possible (_, X, _, o, X, _, X, _) => (x - 1, y), //move sideways if only one path (_, X, _, X, o, _, X, _) => (x + 1, y), //... // deterministic choice of path both left and right are free (_, X, _, o, o, _, X, _) => (if y & 2 == 0 { x - 1 } else { x + 1 }, y), // [_,o,_, X,X, X,X,X] => ( x, y-1 ), //boiling sand // random choice of path both left and right are free // [_,X,_, o,o, _,X,_] => ( if self.rng.gen::<i16>()&2 == 0 {x-1} else {x+1}, y ), _ => continue, }; if Self::is_valid(x_new, y_new) { self.map.remove_coord_map(x, y); self.map.add_coord_map(x_new, y_new); *particle = Loc { x: x_new, y: y_new }; } else { self.map.map[x as usize][y as usize] = false; self.indexes_to_remove.push(index); //prepare list of particles to remove } } // must use.rev(), otherwise you can't remove the last element for index in self.indexes_to_remove.iter().rev() { self.particles.swap_remove(*index); } self.indexes_to_remove.clear(); } //end update pub fn rain(&mut self) { for x in (GRID_WIDTH / 20)..19 * (GRID_WIDTH / 20) { if!self.map.is_occupied(x, 0) && self.rng.gen::<i16>() & RAIN_SPARSENESS == 0 { self.particles.push(Loc { x: x, y: 0 }); self.map.add_coord_map(x, 0); } } } fn remove_indices_in_rect( items: &mut Vec<Loc>, indexes_to_remove: &mut Vec<usize>, ul: Loc, lr: Loc, ) { for (index, p) in items.iter().enumerate() { if p.x >= ul.x && p.y >= ul.y && p.x < lr.x && p.y < lr.y { indexes_to_remove.push(index); } } for index in indexes_to_remove.iter().rev() { items.swap_remove(*index); } indexes_to_remove.clear(); } fn add_particle(&mut self, x: i16, y: i16) { self.map.add_coord_map(x, y); let loc = Loc { x: x, y: y }; self.particles.push(loc); } fn add_obstacle(&mut self, x: i16, y: i16) { self.map.add_coord_map(x, y); let loc = Loc { x: x, y: y }; self.obstacles.push(loc); } pub fn remove_square(&mut self, ux: i16, uy: i16, dx: i16, dy: i16) { if Self::is_valid(ux, uy) && Self::is_valid(ux + dx, uy + dy) { for x in ux..ux + dx { for y in uy..uy + dy { self.map.remove_coord_map(x, y); } } let ul = Loc { x: ux, y: uy }; let lr = Loc { x: ux + dx, y: uy + dy, }; Self::remove_indices_in_rect( &mut self.obstacles, &mut self.indexes_to_remove, ul.clone(), lr.clone(), ); Self::remove_indices_in_rect(&mut self.particles, &mut self.indexes_to_remove, ul, lr); } } pub fn paint_square_obstacles(&mut self, ux: i16, uy: i16, dx: i16, dy: i16) { //if Self::is_valid(ux + dx, uy + dy) { if Self::is_valid(ux, uy) && Self::is_valid(ux + dx, uy + dy) { for x in ux..ux + dx { for y in uy..uy + dy { if!self.map.is_occupied(x, y) { self.map.add_coord_map(x, y); self.add_obstacle(x, y); } } } } } pub fn new() -> GameState { GameState { particles: Vec::with_capacity(10_000), obstacles: Vec::with_capacity(10_000), indexes_to_remove: Vec::with_capacity(1000), map: Map::new(), max_x: GRID_WIDTH, max_y: GRID_HEIGHT, rng: SeedableRng::from_seed([1, 2, 3, 4]), } } } //end impl GameState
// MAIN LOGIC for (index, particle) in self.particles.iter_mut().enumerate() { let (x, y) = (particle.x, particle.y);
random_line_split
lib.rs
//! # Fixerio API Wrapper //! //! http://fixer.io //! //! ## Usage //! Add the following to `Cargo.toml`: //! //! ```rust,ignore
//! [dependencies] //! fixerio = "0.1.3" //! ``` //! //! Synchronous example: //! //! ```rust,no_run //! //! extern crate fixerio; //! //! use fixerio::{Config, Currency, SyncApi}; //! //! fn main() { //! let api = SyncApi::new().expect("Error creating API"); //! //! let config = Config::new(Currency::USD); //! let rates = api.get(&config).expect("Error retrieving rates"); //! //! println!("{:?}", rates); //! } //! ``` //! //! Asynchronous example: //! //! ```rust,no_run //! //! extern crate fixerio; //! extern crate tokio_core; //! //! use fixerio::{Config, Currency, AsyncApi}; //! use tokio_core::reactor::Core; //! //! fn main() { //! let mut core = Core::new().expect("Error creating core"); //! let handle = core.handle(); //! //! let api = AsyncApi::new(&handle); //! //! let config = Config::new(Currency::USD); //! let work = api.get(&config); //! //! println!("{:?}", core.run(work).expect("Error retrieving rates")); //! } //! ``` #[macro_use] extern crate serde_derive; extern crate hyper; extern crate tokio_core; extern crate futures; extern crate serde; extern crate serde_json; #[macro_use] extern crate error_chain; mod client; mod exchange; mod future; mod errors; pub use self::client::{AsyncApi, SyncApi, Config}; pub use self::exchange::{Currency, Exchange, Rates}; pub use self::future::FixerioFuture; pub use self::errors::{Error, ErrorKind};
random_line_split
traversal.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 context::{LocalStyleContext, SharedStyleContext, StyleContext}; use dom::OpaqueNode; use gecko::context::StandaloneStyleContext; use gecko::wrapper::GeckoNode; use std::mem; use traversal::{DomTraversalContext, recalc_style_at}; use traversal::RestyleResult; pub struct RecalcStyleOnly<'lc> { context: StandaloneStyleContext<'lc>, root: OpaqueNode, } impl<'lc, 'ln> DomTraversalContext<GeckoNode<'ln>> for RecalcStyleOnly<'lc> { type SharedContext = SharedStyleContext; #[allow(unsafe_code)] fn new<'a>(shared: &'a Self::SharedContext, root: OpaqueNode) -> Self
fn process_preorder(&self, node: GeckoNode<'ln>) -> RestyleResult { // FIXME(pcwalton): Stop allocating here. Ideally this should just be done by the HTML // parser. node.initialize_data(); recalc_style_at(&self.context, self.root, node) } fn process_postorder(&self, _: GeckoNode<'ln>) { unreachable!(); } /// We don't use the post-order traversal for anything. fn needs_postorder_traversal(&self) -> bool { false } fn local_context(&self) -> &LocalStyleContext { self.context.local_context() } }
{ // See the comment in RecalcStyleAndConstructFlows::new for an explanation of why this is // necessary. let shared_lc: &'lc Self::SharedContext = unsafe { mem::transmute(shared) }; RecalcStyleOnly { context: StandaloneStyleContext::new(shared_lc), root: root, } }
identifier_body
traversal.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 context::{LocalStyleContext, SharedStyleContext, StyleContext}; use dom::OpaqueNode; use gecko::context::StandaloneStyleContext; use gecko::wrapper::GeckoNode; use std::mem; use traversal::{DomTraversalContext, recalc_style_at}; use traversal::RestyleResult; pub struct RecalcStyleOnly<'lc> { context: StandaloneStyleContext<'lc>, root: OpaqueNode, } impl<'lc, 'ln> DomTraversalContext<GeckoNode<'ln>> for RecalcStyleOnly<'lc> { type SharedContext = SharedStyleContext; #[allow(unsafe_code)] fn new<'a>(shared: &'a Self::SharedContext, root: OpaqueNode) -> Self { // See the comment in RecalcStyleAndConstructFlows::new for an explanation of why this is // necessary. let shared_lc: &'lc Self::SharedContext = unsafe { mem::transmute(shared) }; RecalcStyleOnly { context: StandaloneStyleContext::new(shared_lc), root: root, } } fn process_preorder(&self, node: GeckoNode<'ln>) -> RestyleResult {
// parser. node.initialize_data(); recalc_style_at(&self.context, self.root, node) } fn process_postorder(&self, _: GeckoNode<'ln>) { unreachable!(); } /// We don't use the post-order traversal for anything. fn needs_postorder_traversal(&self) -> bool { false } fn local_context(&self) -> &LocalStyleContext { self.context.local_context() } }
// FIXME(pcwalton): Stop allocating here. Ideally this should just be done by the HTML
random_line_split
traversal.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 context::{LocalStyleContext, SharedStyleContext, StyleContext}; use dom::OpaqueNode; use gecko::context::StandaloneStyleContext; use gecko::wrapper::GeckoNode; use std::mem; use traversal::{DomTraversalContext, recalc_style_at}; use traversal::RestyleResult; pub struct RecalcStyleOnly<'lc> { context: StandaloneStyleContext<'lc>, root: OpaqueNode, } impl<'lc, 'ln> DomTraversalContext<GeckoNode<'ln>> for RecalcStyleOnly<'lc> { type SharedContext = SharedStyleContext; #[allow(unsafe_code)] fn new<'a>(shared: &'a Self::SharedContext, root: OpaqueNode) -> Self { // See the comment in RecalcStyleAndConstructFlows::new for an explanation of why this is // necessary. let shared_lc: &'lc Self::SharedContext = unsafe { mem::transmute(shared) }; RecalcStyleOnly { context: StandaloneStyleContext::new(shared_lc), root: root, } } fn process_preorder(&self, node: GeckoNode<'ln>) -> RestyleResult { // FIXME(pcwalton): Stop allocating here. Ideally this should just be done by the HTML // parser. node.initialize_data(); recalc_style_at(&self.context, self.root, node) } fn process_postorder(&self, _: GeckoNode<'ln>) { unreachable!(); } /// We don't use the post-order traversal for anything. fn
(&self) -> bool { false } fn local_context(&self) -> &LocalStyleContext { self.context.local_context() } }
needs_postorder_traversal
identifier_name
main.rs
/* * main.rs * This file is part of Oblique_Projection * * Copyright (C) 2017 - Lilith Wynter * * Oblique_Projection is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Oblique_Projection is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Oblique_Projection. If not, see <http://www.gnu.org/licenses/>. */ #[macro_use] extern crate image; extern crate csv; use std::fs::File; use std::path::Path; fn array_to_image(image: &mut Vec<[f64; 2]>) { println!("Creating 2D projection"); let mut image_lengthx: i64 = 0; let mut image_lengthy: i64 = 0; // Find largest point in x and y direction to determine image size for i in image.iter_mut() { if i[0] < 0.0 { if i[0] as i64*-1 > image_lengthx { image_lengthx = i[0] as i64*-1; } } else { if i[0] as i64 > image_lengthx { image_lengthx = i[0] as i64; } } if i[1] < 0.0 { if i[1] as i64 * -1 > image_lengthy { image_lengthy = i[1] as i64*-1; } } else { if i[1] as i64 > image_lengthy { image_lengthy = i[1] as i64; } } } let image = image; let mut done: bool = false; // Have image size a multiple of 10 while!done { let mut changed: bool = false; if image_lengthx%10!= 0 { changed = true; image_lengthx+=1; } if image_lengthy%10!= 0 { changed = true; image_lengthy+=1; } if changed == false { done = true; } } // Double the largest x and y point, so that 0, 0 can be in the center let sizex: u64 = image_lengthx as u64 * 2; let sizey: u64 = image_lengthy as u64 * 2; println!(" image Width: {} Height: {}", sizex, sizey); let mut imgbuffer = image::ImageBuffer::new(sizex as u32, sizey as u32); for (x, y, pixel) in imgbuffer.enumerate_pixels_mut() { let crnt_px: i64 = (x as i64 - sizex as i64 /2) as i64; let crnt_py: i64 = (y as i64 - sizey as i64 /2) as i64; for i in image.iter() { if i[0] as i64 == crnt_px { if i[1] as i64 == crnt_py { // Place white pixel *pixel = image::Luma([255]); } } } } let ref mut fout = File::create(&Path::new("2DVisualisation.png")).unwrap(); let _ = image::ImageLuma8(imgbuffer).save(fout, image::PNG); println!("Projection generated!!"); } fn read_nd_data(file: &str) -> Vec<Vec<f64>> { let mut temp_array_data = Vec::new(); // Read the csv file let mut rdr = csv::Reader::from_file(file).unwrap(); for row in rdr.records().map(|r| r.unwrap()) { let data = row; temp_array_data.push(data); } let mut array_data = Vec::new(); // Change vector from string to f64 for i in 0..temp_array_data.len() { array_data.push(Vec::new()); for j in 0..temp_array_data[i].len() { if temp_array_data[i][j].is_empty() { array_data[i].push(0.0 as f64); } else { array_data[i].push( temp_array_data[i][j].parse::<f64>().unwrap()); } } } array_data } fn oblique_projection_from_nd(file: &str)
temp_data.push(Vec::new()); for j in 0..num_dim-1 { if j%2 == 0 { temp_data[i].push(final_array[i][j] as f64 + 0.5*final_array[i][num_dim-1]*angle.cos() as f64); } else { temp_data[i].push(final_array[i][j] as f64 + 0.5*final_array[i][num_dim-1]*angle.sin() as f64); } } } num_dim-=1; final_array.clear(); final_array = temp_data; } let mut largest_num: f64 = 0.0; for i in 0..final_array.len() { for j in 0..final_array[i].len() { if largest_num < final_array[i][j] { largest_num = final_array[i][j]; } } } // Shrink or grow the results as to stop memory overloads // Results in more resonable image output and size if largest_num > 10000.0 { let mut larger_than_1000: bool = true; while larger_than_1000 { let mut check: bool = false; for i in 0..final_array.len() { for j in 0..final_array[i].len() { if final_array[i][j] > 10000.0 { check = true; } final_array[i][j] /= 10.0; } } if check == false { larger_than_1000 = false; } } } else if largest_num < -10000.0 { let mut smaller_than_10000: bool = true; while smaller_than_10000 { let mut check: bool = false; for i in 0..final_array.len() { for j in 0..final_array[i].len() { if final_array[i][j] < -10000.0 { check = true; } final_array[i][j] *= 10.0; println!("{}", final_array[i][j]); } } if check == false { smaller_than_10000 = false; } } } let mut array_2d: Vec<[f64; 2]> = Vec::new(); // Change array structure for imaging for i in 0..num_points { array_2d.push([final_array[i][0], final_array[i][1]]); } array_to_image(&mut array_2d); } fn main() { oblique_projection_from_nd("./data/DorotheaData.csv"); }
{ // Gather data from specified file let data = read_nd_data(file); // The standard angle in a oblique projection let angle: f64 = 63.4; let mut final_array = data; // Number of points in dataset let num_points = final_array.len(); // Number of dimensions let mut num_dim = final_array[0].len(); // Apply oblique projection to the vector until it is 2 dimensional array while num_dim > 2 { let mut temp_data: Vec<Vec<f64>> = Vec::new(); for i in 0..num_points {
identifier_body
main.rs
/* * main.rs * This file is part of Oblique_Projection * * Copyright (C) 2017 - Lilith Wynter * * Oblique_Projection is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Oblique_Projection is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Oblique_Projection. If not, see <http://www.gnu.org/licenses/>. */ #[macro_use] extern crate image; extern crate csv; use std::fs::File; use std::path::Path; fn array_to_image(image: &mut Vec<[f64; 2]>) { println!("Creating 2D projection"); let mut image_lengthx: i64 = 0; let mut image_lengthy: i64 = 0; // Find largest point in x and y direction to determine image size for i in image.iter_mut() { if i[0] < 0.0 { if i[0] as i64*-1 > image_lengthx { image_lengthx = i[0] as i64*-1; } } else { if i[0] as i64 > image_lengthx { image_lengthx = i[0] as i64; } } if i[1] < 0.0 { if i[1] as i64 * -1 > image_lengthy { image_lengthy = i[1] as i64*-1; } } else { if i[1] as i64 > image_lengthy { image_lengthy = i[1] as i64; } } } let image = image; let mut done: bool = false; // Have image size a multiple of 10 while!done { let mut changed: bool = false; if image_lengthx%10!= 0 { changed = true; image_lengthx+=1; } if image_lengthy%10!= 0 { changed = true; image_lengthy+=1; } if changed == false { done = true; } } // Double the largest x and y point, so that 0, 0 can be in the center let sizex: u64 = image_lengthx as u64 * 2; let sizey: u64 = image_lengthy as u64 * 2; println!(" image Width: {} Height: {}", sizex, sizey); let mut imgbuffer = image::ImageBuffer::new(sizex as u32, sizey as u32); for (x, y, pixel) in imgbuffer.enumerate_pixels_mut() { let crnt_px: i64 = (x as i64 - sizex as i64 /2) as i64; let crnt_py: i64 = (y as i64 - sizey as i64 /2) as i64; for i in image.iter() { if i[0] as i64 == crnt_px { if i[1] as i64 == crnt_py { // Place white pixel *pixel = image::Luma([255]); } } } } let ref mut fout = File::create(&Path::new("2DVisualisation.png")).unwrap(); let _ = image::ImageLuma8(imgbuffer).save(fout, image::PNG); println!("Projection generated!!"); } fn read_nd_data(file: &str) -> Vec<Vec<f64>> { let mut temp_array_data = Vec::new(); // Read the csv file let mut rdr = csv::Reader::from_file(file).unwrap(); for row in rdr.records().map(|r| r.unwrap()) { let data = row; temp_array_data.push(data); } let mut array_data = Vec::new(); // Change vector from string to f64 for i in 0..temp_array_data.len() { array_data.push(Vec::new()); for j in 0..temp_array_data[i].len() { if temp_array_data[i][j].is_empty() { array_data[i].push(0.0 as f64); } else { array_data[i].push( temp_array_data[i][j].parse::<f64>().unwrap()); } } } array_data } fn oblique_projection_from_nd(file: &str) { // Gather data from specified file let data = read_nd_data(file); // The standard angle in a oblique projection let angle: f64 = 63.4; let mut final_array = data; // Number of points in dataset let num_points = final_array.len(); // Number of dimensions let mut num_dim = final_array[0].len(); // Apply oblique projection to the vector until it is 2 dimensional array while num_dim > 2 { let mut temp_data: Vec<Vec<f64>> = Vec::new(); for i in 0..num_points { temp_data.push(Vec::new()); for j in 0..num_dim-1 { if j%2 == 0 { temp_data[i].push(final_array[i][j] as f64 + 0.5*final_array[i][num_dim-1]*angle.cos() as f64); } else { temp_data[i].push(final_array[i][j] as f64 + 0.5*final_array[i][num_dim-1]*angle.sin() as f64); } } } num_dim-=1; final_array.clear(); final_array = temp_data; } let mut largest_num: f64 = 0.0; for i in 0..final_array.len() { for j in 0..final_array[i].len() { if largest_num < final_array[i][j] { largest_num = final_array[i][j]; } } } // Shrink or grow the results as to stop memory overloads // Results in more resonable image output and size if largest_num > 10000.0 { let mut larger_than_1000: bool = true; while larger_than_1000 { let mut check: bool = false; for i in 0..final_array.len() { for j in 0..final_array[i].len() { if final_array[i][j] > 10000.0 { check = true; } final_array[i][j] /= 10.0; } } if check == false { larger_than_1000 = false; } } } else if largest_num < -10000.0 { let mut smaller_than_10000: bool = true; while smaller_than_10000 { let mut check: bool = false; for i in 0..final_array.len() { for j in 0..final_array[i].len() { if final_array[i][j] < -10000.0 { check = true; } final_array[i][j] *= 10.0; println!("{}", final_array[i][j]); } } if check == false { smaller_than_10000 = false; } } } let mut array_2d: Vec<[f64; 2]> = Vec::new(); // Change array structure for imaging for i in 0..num_points { array_2d.push([final_array[i][0], final_array[i][1]]); } array_to_image(&mut array_2d); } fn
() { oblique_projection_from_nd("./data/DorotheaData.csv"); }
main
identifier_name
main.rs
/* * main.rs * This file is part of Oblique_Projection * * Copyright (C) 2017 - Lilith Wynter * * Oblique_Projection is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Oblique_Projection is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Oblique_Projection. If not, see <http://www.gnu.org/licenses/>. */ #[macro_use] extern crate image; extern crate csv; use std::fs::File; use std::path::Path; fn array_to_image(image: &mut Vec<[f64; 2]>) { println!("Creating 2D projection"); let mut image_lengthx: i64 = 0; let mut image_lengthy: i64 = 0; // Find largest point in x and y direction to determine image size for i in image.iter_mut() { if i[0] < 0.0 { if i[0] as i64*-1 > image_lengthx { image_lengthx = i[0] as i64*-1; } } else { if i[0] as i64 > image_lengthx { image_lengthx = i[0] as i64; } } if i[1] < 0.0 { if i[1] as i64 * -1 > image_lengthy { image_lengthy = i[1] as i64*-1; } } else { if i[1] as i64 > image_lengthy { image_lengthy = i[1] as i64; } } } let image = image; let mut done: bool = false; // Have image size a multiple of 10 while!done { let mut changed: bool = false; if image_lengthx%10!= 0 { changed = true; image_lengthx+=1; } if image_lengthy%10!= 0 { changed = true; image_lengthy+=1; } if changed == false { done = true; } } // Double the largest x and y point, so that 0, 0 can be in the center let sizex: u64 = image_lengthx as u64 * 2; let sizey: u64 = image_lengthy as u64 * 2; println!(" image Width: {} Height: {}", sizex, sizey); let mut imgbuffer = image::ImageBuffer::new(sizex as u32, sizey as u32); for (x, y, pixel) in imgbuffer.enumerate_pixels_mut() { let crnt_px: i64 = (x as i64 - sizex as i64 /2) as i64; let crnt_py: i64 = (y as i64 - sizey as i64 /2) as i64; for i in image.iter() { if i[0] as i64 == crnt_px { if i[1] as i64 == crnt_py { // Place white pixel *pixel = image::Luma([255]); } } } } let ref mut fout = File::create(&Path::new("2DVisualisation.png")).unwrap(); let _ = image::ImageLuma8(imgbuffer).save(fout, image::PNG); println!("Projection generated!!"); } fn read_nd_data(file: &str) -> Vec<Vec<f64>> { let mut temp_array_data = Vec::new(); // Read the csv file let mut rdr = csv::Reader::from_file(file).unwrap(); for row in rdr.records().map(|r| r.unwrap()) { let data = row; temp_array_data.push(data); } let mut array_data = Vec::new(); // Change vector from string to f64 for i in 0..temp_array_data.len() { array_data.push(Vec::new()); for j in 0..temp_array_data[i].len() { if temp_array_data[i][j].is_empty() { array_data[i].push(0.0 as f64); } else { array_data[i].push( temp_array_data[i][j].parse::<f64>().unwrap()); } } } array_data } fn oblique_projection_from_nd(file: &str) { // Gather data from specified file let data = read_nd_data(file); // The standard angle in a oblique projection let angle: f64 = 63.4; let mut final_array = data; // Number of points in dataset let num_points = final_array.len(); // Number of dimensions let mut num_dim = final_array[0].len(); // Apply oblique projection to the vector until it is 2 dimensional array while num_dim > 2 { let mut temp_data: Vec<Vec<f64>> = Vec::new(); for i in 0..num_points { temp_data.push(Vec::new()); for j in 0..num_dim-1 { if j%2 == 0 { temp_data[i].push(final_array[i][j] as f64 + 0.5*final_array[i][num_dim-1]*angle.cos() as f64); } else { temp_data[i].push(final_array[i][j] as f64 + 0.5*final_array[i][num_dim-1]*angle.sin() as f64); } } } num_dim-=1; final_array.clear(); final_array = temp_data; } let mut largest_num: f64 = 0.0; for i in 0..final_array.len() { for j in 0..final_array[i].len() { if largest_num < final_array[i][j] { largest_num = final_array[i][j]; } } } // Shrink or grow the results as to stop memory overloads // Results in more resonable image output and size if largest_num > 10000.0 { let mut larger_than_1000: bool = true; while larger_than_1000 { let mut check: bool = false; for i in 0..final_array.len() { for j in 0..final_array[i].len() { if final_array[i][j] > 10000.0 { check = true; } final_array[i][j] /= 10.0; } } if check == false { larger_than_1000 = false; } } } else if largest_num < -10000.0 { let mut smaller_than_10000: bool = true; while smaller_than_10000 { let mut check: bool = false; for i in 0..final_array.len() { for j in 0..final_array[i].len() { if final_array[i][j] < -10000.0 { check = true; } final_array[i][j] *= 10.0; println!("{}", final_array[i][j]); } } if check == false
} } let mut array_2d: Vec<[f64; 2]> = Vec::new(); // Change array structure for imaging for i in 0..num_points { array_2d.push([final_array[i][0], final_array[i][1]]); } array_to_image(&mut array_2d); } fn main() { oblique_projection_from_nd("./data/DorotheaData.csv"); }
{ smaller_than_10000 = false; }
conditional_block
main.rs
/* * main.rs * This file is part of Oblique_Projection * * Copyright (C) 2017 - Lilith Wynter * * Oblique_Projection is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Oblique_Projection is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Oblique_Projection. If not, see <http://www.gnu.org/licenses/>. */ #[macro_use] extern crate image; extern crate csv; use std::fs::File; use std::path::Path; fn array_to_image(image: &mut Vec<[f64; 2]>) { println!("Creating 2D projection"); let mut image_lengthx: i64 = 0; let mut image_lengthy: i64 = 0; // Find largest point in x and y direction to determine image size for i in image.iter_mut() { if i[0] < 0.0 { if i[0] as i64*-1 > image_lengthx { image_lengthx = i[0] as i64*-1; } } else { if i[0] as i64 > image_lengthx { image_lengthx = i[0] as i64; } } if i[1] < 0.0 { if i[1] as i64 * -1 > image_lengthy { image_lengthy = i[1] as i64*-1; } } else { if i[1] as i64 > image_lengthy { image_lengthy = i[1] as i64; } } } let image = image; let mut done: bool = false; // Have image size a multiple of 10 while!done { let mut changed: bool = false; if image_lengthx%10!= 0 { changed = true; image_lengthx+=1; } if image_lengthy%10!= 0 { changed = true; image_lengthy+=1; } if changed == false { done = true; } } // Double the largest x and y point, so that 0, 0 can be in the center let sizex: u64 = image_lengthx as u64 * 2; let sizey: u64 = image_lengthy as u64 * 2; println!(" image Width: {} Height: {}", sizex, sizey); let mut imgbuffer = image::ImageBuffer::new(sizex as u32, sizey as u32); for (x, y, pixel) in imgbuffer.enumerate_pixels_mut() { let crnt_px: i64 = (x as i64 - sizex as i64 /2) as i64; let crnt_py: i64 = (y as i64 - sizey as i64 /2) as i64; for i in image.iter() { if i[0] as i64 == crnt_px { if i[1] as i64 == crnt_py { // Place white pixel *pixel = image::Luma([255]); } } } } let ref mut fout = File::create(&Path::new("2DVisualisation.png")).unwrap(); let _ = image::ImageLuma8(imgbuffer).save(fout, image::PNG); println!("Projection generated!!"); } fn read_nd_data(file: &str) -> Vec<Vec<f64>> { let mut temp_array_data = Vec::new(); // Read the csv file let mut rdr = csv::Reader::from_file(file).unwrap(); for row in rdr.records().map(|r| r.unwrap()) { let data = row; temp_array_data.push(data); } let mut array_data = Vec::new(); // Change vector from string to f64 for i in 0..temp_array_data.len() { array_data.push(Vec::new()); for j in 0..temp_array_data[i].len() { if temp_array_data[i][j].is_empty() { array_data[i].push(0.0 as f64); } else { array_data[i].push( temp_array_data[i][j].parse::<f64>().unwrap()); } } } array_data } fn oblique_projection_from_nd(file: &str) { // Gather data from specified file let data = read_nd_data(file); // The standard angle in a oblique projection let angle: f64 = 63.4; let mut final_array = data; // Number of points in dataset let num_points = final_array.len(); // Number of dimensions let mut num_dim = final_array[0].len(); // Apply oblique projection to the vector until it is 2 dimensional array while num_dim > 2 { let mut temp_data: Vec<Vec<f64>> = Vec::new(); for i in 0..num_points { temp_data.push(Vec::new()); for j in 0..num_dim-1 { if j%2 == 0 { temp_data[i].push(final_array[i][j] as f64 + 0.5*final_array[i][num_dim-1]*angle.cos() as f64); } else { temp_data[i].push(final_array[i][j] as f64 + 0.5*final_array[i][num_dim-1]*angle.sin() as f64); } } } num_dim-=1; final_array.clear(); final_array = temp_data; } let mut largest_num: f64 = 0.0; for i in 0..final_array.len() { for j in 0..final_array[i].len() { if largest_num < final_array[i][j] { largest_num = final_array[i][j]; } } } // Shrink or grow the results as to stop memory overloads // Results in more resonable image output and size if largest_num > 10000.0 { let mut larger_than_1000: bool = true; while larger_than_1000 { let mut check: bool = false; for i in 0..final_array.len() { for j in 0..final_array[i].len() { if final_array[i][j] > 10000.0 { check = true; } final_array[i][j] /= 10.0; } } if check == false { larger_than_1000 = false; } } } else if largest_num < -10000.0 { let mut smaller_than_10000: bool = true; while smaller_than_10000 { let mut check: bool = false; for i in 0..final_array.len() { for j in 0..final_array[i].len() { if final_array[i][j] < -10000.0 { check = true; } final_array[i][j] *= 10.0; println!("{}", final_array[i][j]); } } if check == false { smaller_than_10000 = false; } } } let mut array_2d: Vec<[f64; 2]> = Vec::new(); // Change array structure for imaging for i in 0..num_points { array_2d.push([final_array[i][0], final_array[i][1]]); } array_to_image(&mut array_2d);
oblique_projection_from_nd("./data/DorotheaData.csv"); }
} fn main() {
random_line_split
mod.rs
//! Utilities for handling shell surfaces with the `wlr_layer_shell` protocol //! //! This interface should be suitable for the implementation of many desktop shell components, //! and a broad number of other applications that interact with the desktop. //! //! ### Initialization //! //! To initialize this handler, simple use the [`wlr_layer_shell_init`] function provided in this module. //! You need to provide a closure that will be invoked whenever some action is required from you, //! are represented by the [`LayerShellRequest`] enum. //! //! ```no_run //! # extern crate wayland_server; //! # //! use smithay::wayland::shell::wlr_layer::{wlr_layer_shell_init, LayerShellRequest}; //! //! # let mut display = wayland_server::Display::new(); //! let (shell_state, _) = wlr_layer_shell_init( //! &mut display, //! // your implementation //! |event: LayerShellRequest, dispatch_data| { /* handle the shell requests here */ }, //! None // put a logger if you want //! ); //! //! // You're now ready to go! //! ``` use std::{ cell::RefCell, rc::Rc, sync::{Arc, Mutex}, }; use wayland_protocols::wlr::unstable::layer_shell::v1::server::{zwlr_layer_shell_v1, zwlr_layer_surface_v1}; use wayland_server::{ protocol::{wl_output::WlOutput, wl_surface}, DispatchData, Display, Filter, Global, Main, }; use crate::{ utils::{DeadResource, Logical, Size}, wayland::{ compositor::{self, Cacheable}, Serial, SERIAL_COUNTER, }, }; mod handlers; mod types; pub use types::{Anchor, ExclusiveZone, KeyboardInteractivity, Layer, Margins}; /// The role of a wlr_layer_shell_surface pub const LAYER_SURFACE_ROLE: &str = "zwlr_layer_surface_v1"; /// Attributes for layer surface #[derive(Debug)] pub struct LayerSurfaceAttributes { surface: zwlr_layer_surface_v1::ZwlrLayerSurfaceV1, /// Defines if the surface has received at least one /// layer_surface.ack_configure from the client pub configured: bool, /// The serial of the last acked configure pub configure_serial: Option<Serial>, /// Holds the state if the surface has sent the initial /// configure event to the client. It is expected that /// during the first commit a initial /// configure event is sent to the client pub initial_configure_sent: bool, /// Holds the configures the server has sent out /// to the client waiting to be acknowledged by /// the client. All pending configures that are older /// than the acknowledged one will be discarded during /// processing layer_surface.ack_configure. pending_configures: Vec<LayerSurfaceConfigure>, /// Holds the pending state as set by the server. pub server_pending: Option<LayerSurfaceState>, /// Holds the last server_pending state that has been acknowledged /// by the client. This state should be cloned to the current /// during a commit. pub last_acked: Option<LayerSurfaceState>, /// Holds the current state of the layer after a successful /// commit. pub current: LayerSurfaceState, } impl LayerSurfaceAttributes { fn new(surface: zwlr_layer_surface_v1::ZwlrLayerSurfaceV1) -> Self { Self { surface, configured: false, configure_serial: None, initial_configure_sent: false, pending_configures: Vec::new(), server_pending: None, last_acked: None, current: Default::default(), } } fn ack_configure(&mut self, serial: Serial) -> Option<LayerSurfaceConfigure> { let configure = self .pending_configures .iter() .find(|configure| configure.serial == serial) .cloned()?; self.last_acked = Some(configure.state.clone()); self.configured = true; self.configure_serial = Some(serial); self.pending_configures.retain(|c| c.serial > serial); Some(configure) } } /// State of a layer surface #[derive(Debug, Default, Clone, PartialEq)] pub struct LayerSurfaceState { /// The suggested size of the surface pub size: Option<Size<i32, Logical>>, } /// Represents the client pending state #[derive(Debug, Default, Clone, Copy)] pub struct LayerSurfaceCachedState { /// The size requested by the client pub size: Size<i32, Logical>, /// Anchor bitflags, describing how the layers surface should be positioned and sized pub anchor: Anchor, /// Descripton of exclusive zone pub exclusive_zone: ExclusiveZone, /// Describes distance from the anchor point of the output pub margin: Margins, /// Describes how keyboard events are delivered to this surface pub keyboard_interactivity: KeyboardInteractivity, /// The layer that the surface is rendered on pub layer: Layer, } impl Cacheable for LayerSurfaceCachedState { fn commit(&mut self) -> Self { *self } fn merge_into(self, into: &mut Self) { *into = self; } } /// Shell global state /// /// This state allows you to retrieve a list of surfaces /// currently known to the shell global. #[derive(Debug)] pub struct
{ known_layers: Vec<LayerSurface>, } impl LayerShellState { /// Access all the shell surfaces known by this handler pub fn layer_surfaces(&self) -> &[LayerSurface] { &self.known_layers[..] } } #[derive(Clone)] struct ShellUserData { _log: ::slog::Logger, user_impl: Rc<RefCell<dyn FnMut(LayerShellRequest, DispatchData<'_>)>>, shell_state: Arc<Mutex<LayerShellState>>, } /// Create a new `wlr_layer_shell` globals pub fn wlr_layer_shell_init<L, Impl>( display: &mut Display, implementation: Impl, logger: L, ) -> ( Arc<Mutex<LayerShellState>>, Global<zwlr_layer_shell_v1::ZwlrLayerShellV1>, ) where L: Into<Option<::slog::Logger>>, Impl: FnMut(LayerShellRequest, DispatchData<'_>) +'static, { let log = crate::slog_or_fallback(logger); let shell_state = Arc::new(Mutex::new(LayerShellState { known_layers: Vec::new(), })); let shell_data = ShellUserData { _log: log.new(slog::o!("smithay_module" => "layer_shell_handler")), user_impl: Rc::new(RefCell::new(implementation)), shell_state: shell_state.clone(), }; let layer_shell_global = display.create_global( 4, Filter::new( move |(shell, _version): (Main<zwlr_layer_shell_v1::ZwlrLayerShellV1>, _), _, _ddata| { shell.quick_assign(self::handlers::layer_shell_implementation); shell.as_ref().user_data().set({ let shell_data = shell_data.clone(); move || shell_data }); }, ), ); (shell_state, layer_shell_global) } /// A handle to a layer surface #[derive(Debug, Clone)] pub struct LayerSurface { wl_surface: wl_surface::WlSurface, shell_surface: zwlr_layer_surface_v1::ZwlrLayerSurfaceV1, } impl std::cmp::PartialEq for LayerSurface { fn eq(&self, other: &Self) -> bool { self.alive() && other.alive() && self.wl_surface == other.wl_surface } } impl LayerSurface { /// Is the layer surface referred by this handle still alive? pub fn alive(&self) -> bool { self.shell_surface.as_ref().is_alive() && self.wl_surface.as_ref().is_alive() } /// Gets the current pending state for a configure /// /// Returns `Some` if either no initial configure has been sent or /// the `server_pending` is `Some` and different from the last pending /// configure or `last_acked` if there is no pending /// /// Returns `None` if either no `server_pending` or the pending /// has already been sent to the client or the pending is equal /// to the `last_acked` fn get_pending_state(&self, attributes: &mut LayerSurfaceAttributes) -> Option<LayerSurfaceState> { if!attributes.initial_configure_sent { return Some(attributes.server_pending.take().unwrap_or_default()); } let server_pending = match attributes.server_pending.take() { Some(state) => state, None => { return None; } }; let last_state = attributes .pending_configures .last() .map(|c| &c.state) .or(attributes.last_acked.as_ref()); if let Some(state) = last_state { if state == &server_pending { return None; } } Some(server_pending) } /// Send a configure event to this layer surface to suggest it a new configuration /// /// The serial of this configure will be tracked waiting for the client to ACK it. /// /// You can manipulate the state that will be sent to the client with the [`with_pending_state`](#method.with_pending_state) /// method. pub fn send_configure(&self) { if let Some(surface) = self.get_surface() { let configure = compositor::with_states(surface, |states| { let mut attributes = states .data_map .get::<Mutex<LayerSurfaceAttributes>>() .unwrap() .lock() .unwrap(); if let Some(pending) = self.get_pending_state(&mut *attributes) { let configure = LayerSurfaceConfigure { serial: SERIAL_COUNTER.next_serial(), state: pending, }; attributes.pending_configures.push(configure.clone()); attributes.initial_configure_sent = true; Some(configure) } else { None } }) .unwrap_or(None); // send surface configure if let Some(configure) = configure { let (width, height) = configure.state.size.unwrap_or_default().into(); let serial = configure.serial; self.shell_surface .configure(serial.into(), width as u32, height as u32); } } } /// Make sure this surface was configured /// /// Returns `true` if it was, if not, returns `false` and raise /// a protocol error to the associated layer surface. Also returns `false` /// if the surface is already destroyed. pub fn ensure_configured(&self) -> bool { if!self.alive() { return false; } let configured = compositor::with_states(&self.wl_surface, |states| { states .data_map .get::<Mutex<LayerSurfaceAttributes>>() .unwrap() .lock() .unwrap() .configured }) .unwrap(); if!configured { self.shell_surface.as_ref().post_error( zwlr_layer_shell_v1::Error::AlreadyConstructed as u32, "layer_surface has never been configured".into(), ); } configured } /// Send a "close" event to the client pub fn send_close(&self) { self.shell_surface.closed() } /// Access the underlying `wl_surface` of this layer surface /// /// Returns `None` if the layer surface actually no longer exists. pub fn get_surface(&self) -> Option<&wl_surface::WlSurface> { if self.alive() { Some(&self.wl_surface) } else { None } } /// Allows the pending state of this layer to /// be manipulated. /// /// This should be used to inform the client about size and state changes, /// for example after a resize request from the client. /// /// The state will be sent to the client when calling [`send_configure`](#method.send_configure). pub fn with_pending_state<F, T>(&self, f: F) -> Result<T, DeadResource> where F: FnOnce(&mut LayerSurfaceState) -> T, { if!self.alive() { return Err(DeadResource); } Ok(compositor::with_states(&self.wl_surface, |states| { let mut attributes = states .data_map .get::<Mutex<LayerSurfaceAttributes>>() .unwrap() .lock() .unwrap(); if attributes.server_pending.is_none() { attributes.server_pending = Some(attributes.current.clone()); } let server_pending = attributes.server_pending.as_mut().unwrap(); f(server_pending) }) .unwrap()) } /// Gets a copy of the current state of this layer /// /// Returns `None` if the underlying surface has been /// destroyed pub fn current_state(&self) -> Option<LayerSurfaceState> { if!self.alive() { return None; } Some( compositor::with_states(&self.wl_surface, |states| { let attributes = states .data_map .get::<Mutex<LayerSurfaceAttributes>>() .unwrap() .lock() .unwrap(); attributes.current.clone() }) .unwrap(), ) } } /// A configure message for layer surfaces #[derive(Debug, Clone)] pub struct LayerSurfaceConfigure { /// The state associated with this configure pub state: LayerSurfaceState, /// A serial number to track ACK from the client /// /// This should be an ever increasing number, as the ACK-ing /// from a client for a serial will validate all pending lower /// serials. pub serial: Serial, } /// Events generated by layer shell surfaces /// /// Depending on what you want to do, you might ignore some of them #[derive(Debug)] pub enum LayerShellRequest { /// A new layer surface was created /// /// You likely need to send a [`LayerSurfaceConfigure`] to the surface, to hint the /// client as to how its layer surface should be sized. NewLayerSurface { /// the surface surface: LayerSurface, /// The output that the layer will be displayed on /// /// None means that the compositor should decide which output to use, /// Generally this will be the one that the user most recently interacted with output: Option<WlOutput>, /// This values indicate on which layer a surface should be rendered on layer: Layer, /// namespace that defines the purpose of the layer surface namespace: String, }, /// A surface has acknowledged a configure serial. AckConfigure { /// The surface. surface: wl_surface::WlSurface, /// The configure serial. configure: LayerSurfaceConfigure, }, }
LayerShellState
identifier_name
mod.rs
//! Utilities for handling shell surfaces with the `wlr_layer_shell` protocol //! //! This interface should be suitable for the implementation of many desktop shell components, //! and a broad number of other applications that interact with the desktop. //! //! ### Initialization //! //! To initialize this handler, simple use the [`wlr_layer_shell_init`] function provided in this module. //! You need to provide a closure that will be invoked whenever some action is required from you, //! are represented by the [`LayerShellRequest`] enum. //! //! ```no_run //! # extern crate wayland_server; //! # //! use smithay::wayland::shell::wlr_layer::{wlr_layer_shell_init, LayerShellRequest}; //! //! # let mut display = wayland_server::Display::new(); //! let (shell_state, _) = wlr_layer_shell_init( //! &mut display, //! // your implementation //! |event: LayerShellRequest, dispatch_data| { /* handle the shell requests here */ }, //! None // put a logger if you want //! ); //! //! // You're now ready to go! //! ``` use std::{ cell::RefCell, rc::Rc, sync::{Arc, Mutex}, }; use wayland_protocols::wlr::unstable::layer_shell::v1::server::{zwlr_layer_shell_v1, zwlr_layer_surface_v1}; use wayland_server::{ protocol::{wl_output::WlOutput, wl_surface}, DispatchData, Display, Filter, Global, Main, }; use crate::{ utils::{DeadResource, Logical, Size}, wayland::{ compositor::{self, Cacheable}, Serial, SERIAL_COUNTER, }, }; mod handlers; mod types; pub use types::{Anchor, ExclusiveZone, KeyboardInteractivity, Layer, Margins}; /// The role of a wlr_layer_shell_surface pub const LAYER_SURFACE_ROLE: &str = "zwlr_layer_surface_v1"; /// Attributes for layer surface #[derive(Debug)] pub struct LayerSurfaceAttributes { surface: zwlr_layer_surface_v1::ZwlrLayerSurfaceV1, /// Defines if the surface has received at least one /// layer_surface.ack_configure from the client pub configured: bool, /// The serial of the last acked configure pub configure_serial: Option<Serial>, /// Holds the state if the surface has sent the initial /// configure event to the client. It is expected that /// during the first commit a initial /// configure event is sent to the client pub initial_configure_sent: bool, /// Holds the configures the server has sent out /// to the client waiting to be acknowledged by /// the client. All pending configures that are older /// than the acknowledged one will be discarded during /// processing layer_surface.ack_configure. pending_configures: Vec<LayerSurfaceConfigure>, /// Holds the pending state as set by the server. pub server_pending: Option<LayerSurfaceState>, /// Holds the last server_pending state that has been acknowledged /// by the client. This state should be cloned to the current /// during a commit. pub last_acked: Option<LayerSurfaceState>, /// Holds the current state of the layer after a successful /// commit. pub current: LayerSurfaceState, } impl LayerSurfaceAttributes { fn new(surface: zwlr_layer_surface_v1::ZwlrLayerSurfaceV1) -> Self { Self { surface, configured: false, configure_serial: None, initial_configure_sent: false, pending_configures: Vec::new(), server_pending: None, last_acked: None, current: Default::default(), } } fn ack_configure(&mut self, serial: Serial) -> Option<LayerSurfaceConfigure> { let configure = self .pending_configures .iter() .find(|configure| configure.serial == serial) .cloned()?; self.last_acked = Some(configure.state.clone()); self.configured = true; self.configure_serial = Some(serial); self.pending_configures.retain(|c| c.serial > serial); Some(configure) } } /// State of a layer surface #[derive(Debug, Default, Clone, PartialEq)] pub struct LayerSurfaceState { /// The suggested size of the surface pub size: Option<Size<i32, Logical>>, } /// Represents the client pending state #[derive(Debug, Default, Clone, Copy)] pub struct LayerSurfaceCachedState { /// The size requested by the client pub size: Size<i32, Logical>, /// Anchor bitflags, describing how the layers surface should be positioned and sized pub anchor: Anchor, /// Descripton of exclusive zone pub exclusive_zone: ExclusiveZone, /// Describes distance from the anchor point of the output pub margin: Margins, /// Describes how keyboard events are delivered to this surface pub keyboard_interactivity: KeyboardInteractivity, /// The layer that the surface is rendered on pub layer: Layer, } impl Cacheable for LayerSurfaceCachedState { fn commit(&mut self) -> Self { *self } fn merge_into(self, into: &mut Self) { *into = self; } } /// Shell global state /// /// This state allows you to retrieve a list of surfaces /// currently known to the shell global. #[derive(Debug)] pub struct LayerShellState { known_layers: Vec<LayerSurface>, } impl LayerShellState { /// Access all the shell surfaces known by this handler pub fn layer_surfaces(&self) -> &[LayerSurface] { &self.known_layers[..] } } #[derive(Clone)] struct ShellUserData { _log: ::slog::Logger, user_impl: Rc<RefCell<dyn FnMut(LayerShellRequest, DispatchData<'_>)>>, shell_state: Arc<Mutex<LayerShellState>>, } /// Create a new `wlr_layer_shell` globals pub fn wlr_layer_shell_init<L, Impl>( display: &mut Display, implementation: Impl, logger: L, ) -> ( Arc<Mutex<LayerShellState>>, Global<zwlr_layer_shell_v1::ZwlrLayerShellV1>, ) where L: Into<Option<::slog::Logger>>, Impl: FnMut(LayerShellRequest, DispatchData<'_>) +'static, { let log = crate::slog_or_fallback(logger); let shell_state = Arc::new(Mutex::new(LayerShellState { known_layers: Vec::new(), })); let shell_data = ShellUserData { _log: log.new(slog::o!("smithay_module" => "layer_shell_handler")), user_impl: Rc::new(RefCell::new(implementation)), shell_state: shell_state.clone(), }; let layer_shell_global = display.create_global( 4, Filter::new( move |(shell, _version): (Main<zwlr_layer_shell_v1::ZwlrLayerShellV1>, _), _, _ddata| { shell.quick_assign(self::handlers::layer_shell_implementation); shell.as_ref().user_data().set({ let shell_data = shell_data.clone(); move || shell_data }); }, ), ); (shell_state, layer_shell_global) } /// A handle to a layer surface #[derive(Debug, Clone)] pub struct LayerSurface { wl_surface: wl_surface::WlSurface, shell_surface: zwlr_layer_surface_v1::ZwlrLayerSurfaceV1, } impl std::cmp::PartialEq for LayerSurface { fn eq(&self, other: &Self) -> bool { self.alive() && other.alive() && self.wl_surface == other.wl_surface } } impl LayerSurface { /// Is the layer surface referred by this handle still alive? pub fn alive(&self) -> bool { self.shell_surface.as_ref().is_alive() && self.wl_surface.as_ref().is_alive() } /// Gets the current pending state for a configure /// /// Returns `Some` if either no initial configure has been sent or /// the `server_pending` is `Some` and different from the last pending /// configure or `last_acked` if there is no pending /// /// Returns `None` if either no `server_pending` or the pending /// has already been sent to the client or the pending is equal /// to the `last_acked` fn get_pending_state(&self, attributes: &mut LayerSurfaceAttributes) -> Option<LayerSurfaceState> { if!attributes.initial_configure_sent { return Some(attributes.server_pending.take().unwrap_or_default()); } let server_pending = match attributes.server_pending.take() { Some(state) => state, None => { return None; } }; let last_state = attributes .pending_configures .last() .map(|c| &c.state) .or(attributes.last_acked.as_ref()); if let Some(state) = last_state { if state == &server_pending { return None; } } Some(server_pending) } /// Send a configure event to this layer surface to suggest it a new configuration /// /// The serial of this configure will be tracked waiting for the client to ACK it. /// /// You can manipulate the state that will be sent to the client with the [`with_pending_state`](#method.with_pending_state) /// method. pub fn send_configure(&self) { if let Some(surface) = self.get_surface() { let configure = compositor::with_states(surface, |states| { let mut attributes = states .data_map .get::<Mutex<LayerSurfaceAttributes>>() .unwrap() .lock() .unwrap(); if let Some(pending) = self.get_pending_state(&mut *attributes) { let configure = LayerSurfaceConfigure { serial: SERIAL_COUNTER.next_serial(), state: pending, }; attributes.pending_configures.push(configure.clone()); attributes.initial_configure_sent = true; Some(configure) } else { None } }) .unwrap_or(None); // send surface configure if let Some(configure) = configure { let (width, height) = configure.state.size.unwrap_or_default().into(); let serial = configure.serial; self.shell_surface .configure(serial.into(), width as u32, height as u32); } } } /// Make sure this surface was configured /// /// Returns `true` if it was, if not, returns `false` and raise /// a protocol error to the associated layer surface. Also returns `false` /// if the surface is already destroyed. pub fn ensure_configured(&self) -> bool { if!self.alive() { return false; } let configured = compositor::with_states(&self.wl_surface, |states| { states .data_map .get::<Mutex<LayerSurfaceAttributes>>() .unwrap() .lock() .unwrap() .configured }) .unwrap(); if!configured { self.shell_surface.as_ref().post_error( zwlr_layer_shell_v1::Error::AlreadyConstructed as u32, "layer_surface has never been configured".into(), ); } configured } /// Send a "close" event to the client pub fn send_close(&self) { self.shell_surface.closed() } /// Access the underlying `wl_surface` of this layer surface /// /// Returns `None` if the layer surface actually no longer exists. pub fn get_surface(&self) -> Option<&wl_surface::WlSurface> { if self.alive() { Some(&self.wl_surface) } else { None } } /// Allows the pending state of this layer to /// be manipulated. /// /// This should be used to inform the client about size and state changes, /// for example after a resize request from the client. /// /// The state will be sent to the client when calling [`send_configure`](#method.send_configure). pub fn with_pending_state<F, T>(&self, f: F) -> Result<T, DeadResource> where F: FnOnce(&mut LayerSurfaceState) -> T, { if!self.alive()
Ok(compositor::with_states(&self.wl_surface, |states| { let mut attributes = states .data_map .get::<Mutex<LayerSurfaceAttributes>>() .unwrap() .lock() .unwrap(); if attributes.server_pending.is_none() { attributes.server_pending = Some(attributes.current.clone()); } let server_pending = attributes.server_pending.as_mut().unwrap(); f(server_pending) }) .unwrap()) } /// Gets a copy of the current state of this layer /// /// Returns `None` if the underlying surface has been /// destroyed pub fn current_state(&self) -> Option<LayerSurfaceState> { if!self.alive() { return None; } Some( compositor::with_states(&self.wl_surface, |states| { let attributes = states .data_map .get::<Mutex<LayerSurfaceAttributes>>() .unwrap() .lock() .unwrap(); attributes.current.clone() }) .unwrap(), ) } } /// A configure message for layer surfaces #[derive(Debug, Clone)] pub struct LayerSurfaceConfigure { /// The state associated with this configure pub state: LayerSurfaceState, /// A serial number to track ACK from the client /// /// This should be an ever increasing number, as the ACK-ing /// from a client for a serial will validate all pending lower /// serials. pub serial: Serial, } /// Events generated by layer shell surfaces /// /// Depending on what you want to do, you might ignore some of them #[derive(Debug)] pub enum LayerShellRequest { /// A new layer surface was created /// /// You likely need to send a [`LayerSurfaceConfigure`] to the surface, to hint the /// client as to how its layer surface should be sized. NewLayerSurface { /// the surface surface: LayerSurface, /// The output that the layer will be displayed on /// /// None means that the compositor should decide which output to use, /// Generally this will be the one that the user most recently interacted with output: Option<WlOutput>, /// This values indicate on which layer a surface should be rendered on layer: Layer, /// namespace that defines the purpose of the layer surface namespace: String, }, /// A surface has acknowledged a configure serial. AckConfigure { /// The surface. surface: wl_surface::WlSurface, /// The configure serial. configure: LayerSurfaceConfigure, }, }
{ return Err(DeadResource); }
conditional_block
mod.rs
//! Utilities for handling shell surfaces with the `wlr_layer_shell` protocol //! //! This interface should be suitable for the implementation of many desktop shell components, //! and a broad number of other applications that interact with the desktop. //! //! ### Initialization //! //! To initialize this handler, simple use the [`wlr_layer_shell_init`] function provided in this module. //! You need to provide a closure that will be invoked whenever some action is required from you, //! are represented by the [`LayerShellRequest`] enum. //! //! ```no_run //! # extern crate wayland_server; //! # //! use smithay::wayland::shell::wlr_layer::{wlr_layer_shell_init, LayerShellRequest}; //! //! # let mut display = wayland_server::Display::new(); //! let (shell_state, _) = wlr_layer_shell_init( //! &mut display, //! // your implementation //! |event: LayerShellRequest, dispatch_data| { /* handle the shell requests here */ }, //! None // put a logger if you want //! ); //! //! // You're now ready to go! //! ``` use std::{ cell::RefCell, rc::Rc, sync::{Arc, Mutex}, }; use wayland_protocols::wlr::unstable::layer_shell::v1::server::{zwlr_layer_shell_v1, zwlr_layer_surface_v1}; use wayland_server::{ protocol::{wl_output::WlOutput, wl_surface}, DispatchData, Display, Filter, Global, Main, }; use crate::{ utils::{DeadResource, Logical, Size}, wayland::{ compositor::{self, Cacheable},
}, }; mod handlers; mod types; pub use types::{Anchor, ExclusiveZone, KeyboardInteractivity, Layer, Margins}; /// The role of a wlr_layer_shell_surface pub const LAYER_SURFACE_ROLE: &str = "zwlr_layer_surface_v1"; /// Attributes for layer surface #[derive(Debug)] pub struct LayerSurfaceAttributes { surface: zwlr_layer_surface_v1::ZwlrLayerSurfaceV1, /// Defines if the surface has received at least one /// layer_surface.ack_configure from the client pub configured: bool, /// The serial of the last acked configure pub configure_serial: Option<Serial>, /// Holds the state if the surface has sent the initial /// configure event to the client. It is expected that /// during the first commit a initial /// configure event is sent to the client pub initial_configure_sent: bool, /// Holds the configures the server has sent out /// to the client waiting to be acknowledged by /// the client. All pending configures that are older /// than the acknowledged one will be discarded during /// processing layer_surface.ack_configure. pending_configures: Vec<LayerSurfaceConfigure>, /// Holds the pending state as set by the server. pub server_pending: Option<LayerSurfaceState>, /// Holds the last server_pending state that has been acknowledged /// by the client. This state should be cloned to the current /// during a commit. pub last_acked: Option<LayerSurfaceState>, /// Holds the current state of the layer after a successful /// commit. pub current: LayerSurfaceState, } impl LayerSurfaceAttributes { fn new(surface: zwlr_layer_surface_v1::ZwlrLayerSurfaceV1) -> Self { Self { surface, configured: false, configure_serial: None, initial_configure_sent: false, pending_configures: Vec::new(), server_pending: None, last_acked: None, current: Default::default(), } } fn ack_configure(&mut self, serial: Serial) -> Option<LayerSurfaceConfigure> { let configure = self .pending_configures .iter() .find(|configure| configure.serial == serial) .cloned()?; self.last_acked = Some(configure.state.clone()); self.configured = true; self.configure_serial = Some(serial); self.pending_configures.retain(|c| c.serial > serial); Some(configure) } } /// State of a layer surface #[derive(Debug, Default, Clone, PartialEq)] pub struct LayerSurfaceState { /// The suggested size of the surface pub size: Option<Size<i32, Logical>>, } /// Represents the client pending state #[derive(Debug, Default, Clone, Copy)] pub struct LayerSurfaceCachedState { /// The size requested by the client pub size: Size<i32, Logical>, /// Anchor bitflags, describing how the layers surface should be positioned and sized pub anchor: Anchor, /// Descripton of exclusive zone pub exclusive_zone: ExclusiveZone, /// Describes distance from the anchor point of the output pub margin: Margins, /// Describes how keyboard events are delivered to this surface pub keyboard_interactivity: KeyboardInteractivity, /// The layer that the surface is rendered on pub layer: Layer, } impl Cacheable for LayerSurfaceCachedState { fn commit(&mut self) -> Self { *self } fn merge_into(self, into: &mut Self) { *into = self; } } /// Shell global state /// /// This state allows you to retrieve a list of surfaces /// currently known to the shell global. #[derive(Debug)] pub struct LayerShellState { known_layers: Vec<LayerSurface>, } impl LayerShellState { /// Access all the shell surfaces known by this handler pub fn layer_surfaces(&self) -> &[LayerSurface] { &self.known_layers[..] } } #[derive(Clone)] struct ShellUserData { _log: ::slog::Logger, user_impl: Rc<RefCell<dyn FnMut(LayerShellRequest, DispatchData<'_>)>>, shell_state: Arc<Mutex<LayerShellState>>, } /// Create a new `wlr_layer_shell` globals pub fn wlr_layer_shell_init<L, Impl>( display: &mut Display, implementation: Impl, logger: L, ) -> ( Arc<Mutex<LayerShellState>>, Global<zwlr_layer_shell_v1::ZwlrLayerShellV1>, ) where L: Into<Option<::slog::Logger>>, Impl: FnMut(LayerShellRequest, DispatchData<'_>) +'static, { let log = crate::slog_or_fallback(logger); let shell_state = Arc::new(Mutex::new(LayerShellState { known_layers: Vec::new(), })); let shell_data = ShellUserData { _log: log.new(slog::o!("smithay_module" => "layer_shell_handler")), user_impl: Rc::new(RefCell::new(implementation)), shell_state: shell_state.clone(), }; let layer_shell_global = display.create_global( 4, Filter::new( move |(shell, _version): (Main<zwlr_layer_shell_v1::ZwlrLayerShellV1>, _), _, _ddata| { shell.quick_assign(self::handlers::layer_shell_implementation); shell.as_ref().user_data().set({ let shell_data = shell_data.clone(); move || shell_data }); }, ), ); (shell_state, layer_shell_global) } /// A handle to a layer surface #[derive(Debug, Clone)] pub struct LayerSurface { wl_surface: wl_surface::WlSurface, shell_surface: zwlr_layer_surface_v1::ZwlrLayerSurfaceV1, } impl std::cmp::PartialEq for LayerSurface { fn eq(&self, other: &Self) -> bool { self.alive() && other.alive() && self.wl_surface == other.wl_surface } } impl LayerSurface { /// Is the layer surface referred by this handle still alive? pub fn alive(&self) -> bool { self.shell_surface.as_ref().is_alive() && self.wl_surface.as_ref().is_alive() } /// Gets the current pending state for a configure /// /// Returns `Some` if either no initial configure has been sent or /// the `server_pending` is `Some` and different from the last pending /// configure or `last_acked` if there is no pending /// /// Returns `None` if either no `server_pending` or the pending /// has already been sent to the client or the pending is equal /// to the `last_acked` fn get_pending_state(&self, attributes: &mut LayerSurfaceAttributes) -> Option<LayerSurfaceState> { if!attributes.initial_configure_sent { return Some(attributes.server_pending.take().unwrap_or_default()); } let server_pending = match attributes.server_pending.take() { Some(state) => state, None => { return None; } }; let last_state = attributes .pending_configures .last() .map(|c| &c.state) .or(attributes.last_acked.as_ref()); if let Some(state) = last_state { if state == &server_pending { return None; } } Some(server_pending) } /// Send a configure event to this layer surface to suggest it a new configuration /// /// The serial of this configure will be tracked waiting for the client to ACK it. /// /// You can manipulate the state that will be sent to the client with the [`with_pending_state`](#method.with_pending_state) /// method. pub fn send_configure(&self) { if let Some(surface) = self.get_surface() { let configure = compositor::with_states(surface, |states| { let mut attributes = states .data_map .get::<Mutex<LayerSurfaceAttributes>>() .unwrap() .lock() .unwrap(); if let Some(pending) = self.get_pending_state(&mut *attributes) { let configure = LayerSurfaceConfigure { serial: SERIAL_COUNTER.next_serial(), state: pending, }; attributes.pending_configures.push(configure.clone()); attributes.initial_configure_sent = true; Some(configure) } else { None } }) .unwrap_or(None); // send surface configure if let Some(configure) = configure { let (width, height) = configure.state.size.unwrap_or_default().into(); let serial = configure.serial; self.shell_surface .configure(serial.into(), width as u32, height as u32); } } } /// Make sure this surface was configured /// /// Returns `true` if it was, if not, returns `false` and raise /// a protocol error to the associated layer surface. Also returns `false` /// if the surface is already destroyed. pub fn ensure_configured(&self) -> bool { if!self.alive() { return false; } let configured = compositor::with_states(&self.wl_surface, |states| { states .data_map .get::<Mutex<LayerSurfaceAttributes>>() .unwrap() .lock() .unwrap() .configured }) .unwrap(); if!configured { self.shell_surface.as_ref().post_error( zwlr_layer_shell_v1::Error::AlreadyConstructed as u32, "layer_surface has never been configured".into(), ); } configured } /// Send a "close" event to the client pub fn send_close(&self) { self.shell_surface.closed() } /// Access the underlying `wl_surface` of this layer surface /// /// Returns `None` if the layer surface actually no longer exists. pub fn get_surface(&self) -> Option<&wl_surface::WlSurface> { if self.alive() { Some(&self.wl_surface) } else { None } } /// Allows the pending state of this layer to /// be manipulated. /// /// This should be used to inform the client about size and state changes, /// for example after a resize request from the client. /// /// The state will be sent to the client when calling [`send_configure`](#method.send_configure). pub fn with_pending_state<F, T>(&self, f: F) -> Result<T, DeadResource> where F: FnOnce(&mut LayerSurfaceState) -> T, { if!self.alive() { return Err(DeadResource); } Ok(compositor::with_states(&self.wl_surface, |states| { let mut attributes = states .data_map .get::<Mutex<LayerSurfaceAttributes>>() .unwrap() .lock() .unwrap(); if attributes.server_pending.is_none() { attributes.server_pending = Some(attributes.current.clone()); } let server_pending = attributes.server_pending.as_mut().unwrap(); f(server_pending) }) .unwrap()) } /// Gets a copy of the current state of this layer /// /// Returns `None` if the underlying surface has been /// destroyed pub fn current_state(&self) -> Option<LayerSurfaceState> { if!self.alive() { return None; } Some( compositor::with_states(&self.wl_surface, |states| { let attributes = states .data_map .get::<Mutex<LayerSurfaceAttributes>>() .unwrap() .lock() .unwrap(); attributes.current.clone() }) .unwrap(), ) } } /// A configure message for layer surfaces #[derive(Debug, Clone)] pub struct LayerSurfaceConfigure { /// The state associated with this configure pub state: LayerSurfaceState, /// A serial number to track ACK from the client /// /// This should be an ever increasing number, as the ACK-ing /// from a client for a serial will validate all pending lower /// serials. pub serial: Serial, } /// Events generated by layer shell surfaces /// /// Depending on what you want to do, you might ignore some of them #[derive(Debug)] pub enum LayerShellRequest { /// A new layer surface was created /// /// You likely need to send a [`LayerSurfaceConfigure`] to the surface, to hint the /// client as to how its layer surface should be sized. NewLayerSurface { /// the surface surface: LayerSurface, /// The output that the layer will be displayed on /// /// None means that the compositor should decide which output to use, /// Generally this will be the one that the user most recently interacted with output: Option<WlOutput>, /// This values indicate on which layer a surface should be rendered on layer: Layer, /// namespace that defines the purpose of the layer surface namespace: String, }, /// A surface has acknowledged a configure serial. AckConfigure { /// The surface. surface: wl_surface::WlSurface, /// The configure serial. configure: LayerSurfaceConfigure, }, }
Serial, SERIAL_COUNTER,
random_line_split
mod.rs
//! Utilities for handling shell surfaces with the `wlr_layer_shell` protocol //! //! This interface should be suitable for the implementation of many desktop shell components, //! and a broad number of other applications that interact with the desktop. //! //! ### Initialization //! //! To initialize this handler, simple use the [`wlr_layer_shell_init`] function provided in this module. //! You need to provide a closure that will be invoked whenever some action is required from you, //! are represented by the [`LayerShellRequest`] enum. //! //! ```no_run //! # extern crate wayland_server; //! # //! use smithay::wayland::shell::wlr_layer::{wlr_layer_shell_init, LayerShellRequest}; //! //! # let mut display = wayland_server::Display::new(); //! let (shell_state, _) = wlr_layer_shell_init( //! &mut display, //! // your implementation //! |event: LayerShellRequest, dispatch_data| { /* handle the shell requests here */ }, //! None // put a logger if you want //! ); //! //! // You're now ready to go! //! ``` use std::{ cell::RefCell, rc::Rc, sync::{Arc, Mutex}, }; use wayland_protocols::wlr::unstable::layer_shell::v1::server::{zwlr_layer_shell_v1, zwlr_layer_surface_v1}; use wayland_server::{ protocol::{wl_output::WlOutput, wl_surface}, DispatchData, Display, Filter, Global, Main, }; use crate::{ utils::{DeadResource, Logical, Size}, wayland::{ compositor::{self, Cacheable}, Serial, SERIAL_COUNTER, }, }; mod handlers; mod types; pub use types::{Anchor, ExclusiveZone, KeyboardInteractivity, Layer, Margins}; /// The role of a wlr_layer_shell_surface pub const LAYER_SURFACE_ROLE: &str = "zwlr_layer_surface_v1"; /// Attributes for layer surface #[derive(Debug)] pub struct LayerSurfaceAttributes { surface: zwlr_layer_surface_v1::ZwlrLayerSurfaceV1, /// Defines if the surface has received at least one /// layer_surface.ack_configure from the client pub configured: bool, /// The serial of the last acked configure pub configure_serial: Option<Serial>, /// Holds the state if the surface has sent the initial /// configure event to the client. It is expected that /// during the first commit a initial /// configure event is sent to the client pub initial_configure_sent: bool, /// Holds the configures the server has sent out /// to the client waiting to be acknowledged by /// the client. All pending configures that are older /// than the acknowledged one will be discarded during /// processing layer_surface.ack_configure. pending_configures: Vec<LayerSurfaceConfigure>, /// Holds the pending state as set by the server. pub server_pending: Option<LayerSurfaceState>, /// Holds the last server_pending state that has been acknowledged /// by the client. This state should be cloned to the current /// during a commit. pub last_acked: Option<LayerSurfaceState>, /// Holds the current state of the layer after a successful /// commit. pub current: LayerSurfaceState, } impl LayerSurfaceAttributes { fn new(surface: zwlr_layer_surface_v1::ZwlrLayerSurfaceV1) -> Self { Self { surface, configured: false, configure_serial: None, initial_configure_sent: false, pending_configures: Vec::new(), server_pending: None, last_acked: None, current: Default::default(), } } fn ack_configure(&mut self, serial: Serial) -> Option<LayerSurfaceConfigure> { let configure = self .pending_configures .iter() .find(|configure| configure.serial == serial) .cloned()?; self.last_acked = Some(configure.state.clone()); self.configured = true; self.configure_serial = Some(serial); self.pending_configures.retain(|c| c.serial > serial); Some(configure) } } /// State of a layer surface #[derive(Debug, Default, Clone, PartialEq)] pub struct LayerSurfaceState { /// The suggested size of the surface pub size: Option<Size<i32, Logical>>, } /// Represents the client pending state #[derive(Debug, Default, Clone, Copy)] pub struct LayerSurfaceCachedState { /// The size requested by the client pub size: Size<i32, Logical>, /// Anchor bitflags, describing how the layers surface should be positioned and sized pub anchor: Anchor, /// Descripton of exclusive zone pub exclusive_zone: ExclusiveZone, /// Describes distance from the anchor point of the output pub margin: Margins, /// Describes how keyboard events are delivered to this surface pub keyboard_interactivity: KeyboardInteractivity, /// The layer that the surface is rendered on pub layer: Layer, } impl Cacheable for LayerSurfaceCachedState { fn commit(&mut self) -> Self
fn merge_into(self, into: &mut Self) { *into = self; } } /// Shell global state /// /// This state allows you to retrieve a list of surfaces /// currently known to the shell global. #[derive(Debug)] pub struct LayerShellState { known_layers: Vec<LayerSurface>, } impl LayerShellState { /// Access all the shell surfaces known by this handler pub fn layer_surfaces(&self) -> &[LayerSurface] { &self.known_layers[..] } } #[derive(Clone)] struct ShellUserData { _log: ::slog::Logger, user_impl: Rc<RefCell<dyn FnMut(LayerShellRequest, DispatchData<'_>)>>, shell_state: Arc<Mutex<LayerShellState>>, } /// Create a new `wlr_layer_shell` globals pub fn wlr_layer_shell_init<L, Impl>( display: &mut Display, implementation: Impl, logger: L, ) -> ( Arc<Mutex<LayerShellState>>, Global<zwlr_layer_shell_v1::ZwlrLayerShellV1>, ) where L: Into<Option<::slog::Logger>>, Impl: FnMut(LayerShellRequest, DispatchData<'_>) +'static, { let log = crate::slog_or_fallback(logger); let shell_state = Arc::new(Mutex::new(LayerShellState { known_layers: Vec::new(), })); let shell_data = ShellUserData { _log: log.new(slog::o!("smithay_module" => "layer_shell_handler")), user_impl: Rc::new(RefCell::new(implementation)), shell_state: shell_state.clone(), }; let layer_shell_global = display.create_global( 4, Filter::new( move |(shell, _version): (Main<zwlr_layer_shell_v1::ZwlrLayerShellV1>, _), _, _ddata| { shell.quick_assign(self::handlers::layer_shell_implementation); shell.as_ref().user_data().set({ let shell_data = shell_data.clone(); move || shell_data }); }, ), ); (shell_state, layer_shell_global) } /// A handle to a layer surface #[derive(Debug, Clone)] pub struct LayerSurface { wl_surface: wl_surface::WlSurface, shell_surface: zwlr_layer_surface_v1::ZwlrLayerSurfaceV1, } impl std::cmp::PartialEq for LayerSurface { fn eq(&self, other: &Self) -> bool { self.alive() && other.alive() && self.wl_surface == other.wl_surface } } impl LayerSurface { /// Is the layer surface referred by this handle still alive? pub fn alive(&self) -> bool { self.shell_surface.as_ref().is_alive() && self.wl_surface.as_ref().is_alive() } /// Gets the current pending state for a configure /// /// Returns `Some` if either no initial configure has been sent or /// the `server_pending` is `Some` and different from the last pending /// configure or `last_acked` if there is no pending /// /// Returns `None` if either no `server_pending` or the pending /// has already been sent to the client or the pending is equal /// to the `last_acked` fn get_pending_state(&self, attributes: &mut LayerSurfaceAttributes) -> Option<LayerSurfaceState> { if!attributes.initial_configure_sent { return Some(attributes.server_pending.take().unwrap_or_default()); } let server_pending = match attributes.server_pending.take() { Some(state) => state, None => { return None; } }; let last_state = attributes .pending_configures .last() .map(|c| &c.state) .or(attributes.last_acked.as_ref()); if let Some(state) = last_state { if state == &server_pending { return None; } } Some(server_pending) } /// Send a configure event to this layer surface to suggest it a new configuration /// /// The serial of this configure will be tracked waiting for the client to ACK it. /// /// You can manipulate the state that will be sent to the client with the [`with_pending_state`](#method.with_pending_state) /// method. pub fn send_configure(&self) { if let Some(surface) = self.get_surface() { let configure = compositor::with_states(surface, |states| { let mut attributes = states .data_map .get::<Mutex<LayerSurfaceAttributes>>() .unwrap() .lock() .unwrap(); if let Some(pending) = self.get_pending_state(&mut *attributes) { let configure = LayerSurfaceConfigure { serial: SERIAL_COUNTER.next_serial(), state: pending, }; attributes.pending_configures.push(configure.clone()); attributes.initial_configure_sent = true; Some(configure) } else { None } }) .unwrap_or(None); // send surface configure if let Some(configure) = configure { let (width, height) = configure.state.size.unwrap_or_default().into(); let serial = configure.serial; self.shell_surface .configure(serial.into(), width as u32, height as u32); } } } /// Make sure this surface was configured /// /// Returns `true` if it was, if not, returns `false` and raise /// a protocol error to the associated layer surface. Also returns `false` /// if the surface is already destroyed. pub fn ensure_configured(&self) -> bool { if!self.alive() { return false; } let configured = compositor::with_states(&self.wl_surface, |states| { states .data_map .get::<Mutex<LayerSurfaceAttributes>>() .unwrap() .lock() .unwrap() .configured }) .unwrap(); if!configured { self.shell_surface.as_ref().post_error( zwlr_layer_shell_v1::Error::AlreadyConstructed as u32, "layer_surface has never been configured".into(), ); } configured } /// Send a "close" event to the client pub fn send_close(&self) { self.shell_surface.closed() } /// Access the underlying `wl_surface` of this layer surface /// /// Returns `None` if the layer surface actually no longer exists. pub fn get_surface(&self) -> Option<&wl_surface::WlSurface> { if self.alive() { Some(&self.wl_surface) } else { None } } /// Allows the pending state of this layer to /// be manipulated. /// /// This should be used to inform the client about size and state changes, /// for example after a resize request from the client. /// /// The state will be sent to the client when calling [`send_configure`](#method.send_configure). pub fn with_pending_state<F, T>(&self, f: F) -> Result<T, DeadResource> where F: FnOnce(&mut LayerSurfaceState) -> T, { if!self.alive() { return Err(DeadResource); } Ok(compositor::with_states(&self.wl_surface, |states| { let mut attributes = states .data_map .get::<Mutex<LayerSurfaceAttributes>>() .unwrap() .lock() .unwrap(); if attributes.server_pending.is_none() { attributes.server_pending = Some(attributes.current.clone()); } let server_pending = attributes.server_pending.as_mut().unwrap(); f(server_pending) }) .unwrap()) } /// Gets a copy of the current state of this layer /// /// Returns `None` if the underlying surface has been /// destroyed pub fn current_state(&self) -> Option<LayerSurfaceState> { if!self.alive() { return None; } Some( compositor::with_states(&self.wl_surface, |states| { let attributes = states .data_map .get::<Mutex<LayerSurfaceAttributes>>() .unwrap() .lock() .unwrap(); attributes.current.clone() }) .unwrap(), ) } } /// A configure message for layer surfaces #[derive(Debug, Clone)] pub struct LayerSurfaceConfigure { /// The state associated with this configure pub state: LayerSurfaceState, /// A serial number to track ACK from the client /// /// This should be an ever increasing number, as the ACK-ing /// from a client for a serial will validate all pending lower /// serials. pub serial: Serial, } /// Events generated by layer shell surfaces /// /// Depending on what you want to do, you might ignore some of them #[derive(Debug)] pub enum LayerShellRequest { /// A new layer surface was created /// /// You likely need to send a [`LayerSurfaceConfigure`] to the surface, to hint the /// client as to how its layer surface should be sized. NewLayerSurface { /// the surface surface: LayerSurface, /// The output that the layer will be displayed on /// /// None means that the compositor should decide which output to use, /// Generally this will be the one that the user most recently interacted with output: Option<WlOutput>, /// This values indicate on which layer a surface should be rendered on layer: Layer, /// namespace that defines the purpose of the layer surface namespace: String, }, /// A surface has acknowledged a configure serial. AckConfigure { /// The surface. surface: wl_surface::WlSurface, /// The configure serial. configure: LayerSurfaceConfigure, }, }
{ *self }
identifier_body
http_server.rs
use std::thread; use actix_web::{middleware, web, App, HttpRequest, HttpServer, Responder}; use prometheus::{Encoder, TextEncoder}; pub fn start_http_server( addr: std::net::SocketAddr, ) -> (thread::JoinHandle<()>, actix_rt::System, actix_web::dev::Server) { let (tx, rx) = std::sync::mpsc::channel(); let (tx_http, rx_http) = std::sync::mpsc::channel(); let join_handle = thread::spawn(move || { let system = actix_rt::System::new("http_server"); let server = HttpServer::new(move || { App::new() .wrap(middleware::Logger::default()) .wrap(middleware::DefaultHeaders::new().header("Access-Control-Allow-Origin", "*")) .service(web::resource("/api/metrics").to(metrics)) }) .disable_signals() .bind(addr) .unwrap() .run(); tx.send(actix_rt::System::current()).unwrap(); tx_http.send(server).unwrap(); system.run().unwrap(); debug!("http server shutdown"); }); let system = rx.recv().unwrap();
async fn metrics(_req: HttpRequest) -> impl Responder { let metric_families = prometheus::gather(); let encoder = TextEncoder::new(); let mut buffer = Vec::new(); let encode_result = encoder.encode(&metric_families, &mut buffer); match encode_result { Ok(_) => {} Err(e) => error!("[E02011] Error encoding metrics: {}", e), } String::from_utf8(buffer).unwrap() }
let server = rx_http.recv().unwrap(); (join_handle, system, server) }
random_line_split
http_server.rs
use std::thread; use actix_web::{middleware, web, App, HttpRequest, HttpServer, Responder}; use prometheus::{Encoder, TextEncoder}; pub fn start_http_server( addr: std::net::SocketAddr, ) -> (thread::JoinHandle<()>, actix_rt::System, actix_web::dev::Server) { let (tx, rx) = std::sync::mpsc::channel(); let (tx_http, rx_http) = std::sync::mpsc::channel(); let join_handle = thread::spawn(move || { let system = actix_rt::System::new("http_server"); let server = HttpServer::new(move || { App::new() .wrap(middleware::Logger::default()) .wrap(middleware::DefaultHeaders::new().header("Access-Control-Allow-Origin", "*")) .service(web::resource("/api/metrics").to(metrics)) }) .disable_signals() .bind(addr) .unwrap() .run(); tx.send(actix_rt::System::current()).unwrap(); tx_http.send(server).unwrap(); system.run().unwrap(); debug!("http server shutdown"); }); let system = rx.recv().unwrap(); let server = rx_http.recv().unwrap(); (join_handle, system, server) } async fn
(_req: HttpRequest) -> impl Responder { let metric_families = prometheus::gather(); let encoder = TextEncoder::new(); let mut buffer = Vec::new(); let encode_result = encoder.encode(&metric_families, &mut buffer); match encode_result { Ok(_) => {} Err(e) => error!("[E02011] Error encoding metrics: {}", e), } String::from_utf8(buffer).unwrap() }
metrics
identifier_name
http_server.rs
use std::thread; use actix_web::{middleware, web, App, HttpRequest, HttpServer, Responder}; use prometheus::{Encoder, TextEncoder}; pub fn start_http_server( addr: std::net::SocketAddr, ) -> (thread::JoinHandle<()>, actix_rt::System, actix_web::dev::Server)
system.run().unwrap(); debug!("http server shutdown"); }); let system = rx.recv().unwrap(); let server = rx_http.recv().unwrap(); (join_handle, system, server) } async fn metrics(_req: HttpRequest) -> impl Responder { let metric_families = prometheus::gather(); let encoder = TextEncoder::new(); let mut buffer = Vec::new(); let encode_result = encoder.encode(&metric_families, &mut buffer); match encode_result { Ok(_) => {} Err(e) => error!("[E02011] Error encoding metrics: {}", e), } String::from_utf8(buffer).unwrap() }
{ let (tx, rx) = std::sync::mpsc::channel(); let (tx_http, rx_http) = std::sync::mpsc::channel(); let join_handle = thread::spawn(move || { let system = actix_rt::System::new("http_server"); let server = HttpServer::new(move || { App::new() .wrap(middleware::Logger::default()) .wrap(middleware::DefaultHeaders::new().header("Access-Control-Allow-Origin", "*")) .service(web::resource("/api/metrics").to(metrics)) }) .disable_signals() .bind(addr) .unwrap() .run(); tx.send(actix_rt::System::current()).unwrap(); tx_http.send(server).unwrap();
identifier_body
message.rs
// Rust Bitcoin Library // Written in 2014 by // Andrew Poelstra <[email protected]> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. // // You should have received a copy of the CC0 Public Domain Dedication // along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // //! # Network message //! //! This module defines the `Message` traits which are used //! for (de)serializing Bitcoin objects for transmission on the network. It //! also defines (de)serialization routines for many primitives. //! use std::iter; use std::io::Cursor; use std::sync::mpsc::Sender; use blockdata::block; use blockdata::transaction; use network::address::Address; use network::message_network; use network::message_blockdata; use network::encodable::{ConsensusDecodable, ConsensusEncodable}; use network::encodable::CheckedData; use network::serialize::{serialize, RawDecoder, SimpleEncoder, SimpleDecoder}; use util::{self, propagate_err}; /// Serializer for command string #[derive(PartialEq, Eq, Clone, Debug)] pub struct CommandString(pub String); impl<S: SimpleEncoder> ConsensusEncodable<S> for CommandString { #[inline] fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { use std::intrinsics::copy_nonoverlapping; use std::mem; let &CommandString(ref inner_str) = self; let mut rawbytes = [0u8; 12]; unsafe { copy_nonoverlapping(inner_str.as_bytes().as_ptr(), rawbytes.as_mut_ptr(), mem::size_of::<[u8; 12]>()); } rawbytes.consensus_encode(s) } } impl<D: SimpleDecoder> ConsensusDecodable<D> for CommandString { #[inline] fn consensus_decode(d: &mut D) -> Result<CommandString, D::Error> { let rawbytes: [u8; 12] = try!(ConsensusDecodable::consensus_decode(d)); let rv = iter::FromIterator::from_iter(rawbytes.iter().filter_map(|&u| if u > 0 { Some(u as char) } else { None })); Ok(CommandString(rv)) } } /// A Network message pub struct RawNetworkMessage { /// Magic bytes to identify the network these messages are meant for pub magic: u32, /// The actual message data pub payload: NetworkMessage } /// A response from the peer-connected socket pub enum SocketResponse { /// A message was received MessageReceived(NetworkMessage), /// An error occured and the socket needs to close ConnectionFailed(util::Error, Sender<()>) } #[derive(Clone, PartialEq, Eq, Debug)] /// A Network message payload. Proper documentation is available on the Bitcoin /// wiki https://en.bitcoin.it/wiki/Protocol_specification pub enum NetworkMessage { /// `version` Version(message_network::VersionMessage), /// `verack` Verack, /// `addr` Addr(Vec<(u32, Address)>), /// `inv` Inv(Vec<message_blockdata::Inventory>), /// `getdata` GetData(Vec<message_blockdata::Inventory>), /// `notfound` NotFound(Vec<message_blockdata::Inventory>), /// `getblocks` GetBlocks(message_blockdata::GetBlocksMessage), /// `getheaders` GetHeaders(message_blockdata::GetHeadersMessage), /// tx Tx(transaction::Transaction), /// `block` Block(block::Block), /// `headers` Headers(Vec<block::LoneBlockHeader>), // TODO: getaddr, // TODO: mempool, // TODO: checkorder, // TODO: submitorder, // TODO: reply, /// `ping` Ping(u64), /// `pong` Pong(u64) // TODO: reject, // TODO: bloom filtering // TODO: alert } impl RawNetworkMessage { fn command(&self) -> String { match self.payload { NetworkMessage::Version(_) => "version", NetworkMessage::Verack => "verack", NetworkMessage::Addr(_) => "addr", NetworkMessage::Inv(_) => "inv", NetworkMessage::GetData(_) => "getdata", NetworkMessage::NotFound(_) => "notfound", NetworkMessage::GetBlocks(_) => "getblocks", NetworkMessage::GetHeaders(_) => "getheaders", NetworkMessage::Tx(_) => "tx", NetworkMessage::Block(_) => "block", NetworkMessage::Headers(_) => "headers", NetworkMessage::Ping(_) => "ping", NetworkMessage::Pong(_) => "pong", }.to_string() } } impl<S: SimpleEncoder> ConsensusEncodable<S> for RawNetworkMessage { fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { try!(self.magic.consensus_encode(s)); try!(CommandString(self.command()).consensus_encode(s)); try!(CheckedData(match self.payload { NetworkMessage::Version(ref dat) => serialize(dat), NetworkMessage::Verack => Ok(vec![]), NetworkMessage::Addr(ref dat) => serialize(dat), NetworkMessage::Inv(ref dat) => serialize(dat), NetworkMessage::GetData(ref dat) => serialize(dat), NetworkMessage::NotFound(ref dat) => serialize(dat), NetworkMessage::GetBlocks(ref dat) => serialize(dat), NetworkMessage::GetHeaders(ref dat) => serialize(dat), NetworkMessage::Tx(ref dat) => serialize(dat), NetworkMessage::Block(ref dat) => serialize(dat), NetworkMessage::Headers(ref dat) => serialize(dat), NetworkMessage::Ping(ref dat) => serialize(dat), NetworkMessage::Pong(ref dat) => serialize(dat), }.unwrap()).consensus_encode(s)); Ok(()) } } // TODO: restriction on D::Error is so that `propagate_err` will work; // is there a more generic way to handle this? impl<D: SimpleDecoder<Error=util::Error>> ConsensusDecodable<D> for RawNetworkMessage { fn consensus_decode(d: &mut D) -> Result<RawNetworkMessage, D::Error>
cmd => return Err(d.error(format!("unrecognized network command `{}`", cmd))) }; Ok(RawNetworkMessage { magic: magic, payload: payload }) } } #[cfg(test)] mod test { use super::{RawNetworkMessage, NetworkMessage, CommandString}; use network::serialize::{deserialize, serialize}; #[test] fn serialize_commandstring_test() { let cs = CommandString("Andrew".to_string()); assert_eq!(serialize(&cs).ok(), Some(vec![0x41u8, 0x6e, 0x64, 0x72, 0x65, 0x77, 0, 0, 0, 0, 0, 0])); } #[test] fn deserialize_commandstring_test() { let cs: Result<CommandString, _> = deserialize(&[0x41u8, 0x6e, 0x64, 0x72, 0x65, 0x77, 0, 0, 0, 0, 0, 0]); assert!(cs.is_ok()); assert_eq!(cs.unwrap(), CommandString("Andrew".to_string())); let short_cs: Result<CommandString, _> = deserialize(&[0x41u8, 0x6e, 0x64, 0x72, 0x65, 0x77, 0, 0, 0, 0, 0]); assert!(short_cs.is_err()); } #[test] fn serialize_verack_test() { assert_eq!(serialize(&RawNetworkMessage { magic: 0xd9b4bef9, payload: NetworkMessage::Verack }).ok(), Some(vec![0xf9, 0xbe, 0xb4, 0xd9, 0x76, 0x65, 0x72, 0x61, 0x63, 0x6B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5d, 0xf6, 0xe0, 0xe2])); } #[test] fn serialize_ping_test() { assert_eq!(serialize(&RawNetworkMessage { magic: 0xd9b4bef9, payload: NetworkMessage::Ping(100) }).ok(), Some(vec![0xf9, 0xbe, 0xb4, 0xd9, 0x70, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x24, 0x67, 0xf1, 0x1d, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])); } }
{ let magic = try!(ConsensusDecodable::consensus_decode(d)); let CommandString(cmd): CommandString= try!(ConsensusDecodable::consensus_decode(d)); let CheckedData(raw_payload): CheckedData = try!(ConsensusDecodable::consensus_decode(d)); let mut mem_d = RawDecoder::new(Cursor::new(raw_payload)); let payload = match &cmd[..] { "version" => NetworkMessage::Version(try!(propagate_err("version".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "verack" => NetworkMessage::Verack, "addr" => NetworkMessage::Addr(try!(propagate_err("addr".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "inv" => NetworkMessage::Inv(try!(propagate_err("inv".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "getdata" => NetworkMessage::GetData(try!(propagate_err("getdata".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "notfound" => NetworkMessage::NotFound(try!(propagate_err("notfound".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "getblocks" => NetworkMessage::GetBlocks(try!(propagate_err("getblocks".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "getheaders" => NetworkMessage::GetHeaders(try!(propagate_err("getheaders".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "block" => NetworkMessage::Block(try!(propagate_err("block".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "headers" => NetworkMessage::Headers(try!(propagate_err("headers".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "ping" => NetworkMessage::Ping(try!(propagate_err("ping".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "pong" => NetworkMessage::Ping(try!(propagate_err("pong".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "tx" => NetworkMessage::Tx(try!(propagate_err("tx".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))),
identifier_body
message.rs
// Rust Bitcoin Library // Written in 2014 by // Andrew Poelstra <[email protected]> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. // // You should have received a copy of the CC0 Public Domain Dedication // along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // //! # Network message //! //! This module defines the `Message` traits which are used //! for (de)serializing Bitcoin objects for transmission on the network. It //! also defines (de)serialization routines for many primitives. //! use std::iter; use std::io::Cursor; use std::sync::mpsc::Sender; use blockdata::block; use blockdata::transaction; use network::address::Address; use network::message_network; use network::message_blockdata; use network::encodable::{ConsensusDecodable, ConsensusEncodable}; use network::encodable::CheckedData; use network::serialize::{serialize, RawDecoder, SimpleEncoder, SimpleDecoder}; use util::{self, propagate_err}; /// Serializer for command string #[derive(PartialEq, Eq, Clone, Debug)] pub struct CommandString(pub String); impl<S: SimpleEncoder> ConsensusEncodable<S> for CommandString { #[inline] fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { use std::intrinsics::copy_nonoverlapping; use std::mem; let &CommandString(ref inner_str) = self; let mut rawbytes = [0u8; 12]; unsafe { copy_nonoverlapping(inner_str.as_bytes().as_ptr(), rawbytes.as_mut_ptr(), mem::size_of::<[u8; 12]>()); } rawbytes.consensus_encode(s) } } impl<D: SimpleDecoder> ConsensusDecodable<D> for CommandString { #[inline] fn consensus_decode(d: &mut D) -> Result<CommandString, D::Error> { let rawbytes: [u8; 12] = try!(ConsensusDecodable::consensus_decode(d)); let rv = iter::FromIterator::from_iter(rawbytes.iter().filter_map(|&u| if u > 0 { Some(u as char) } else { None })); Ok(CommandString(rv)) } } /// A Network message pub struct RawNetworkMessage { /// Magic bytes to identify the network these messages are meant for pub magic: u32, /// The actual message data pub payload: NetworkMessage } /// A response from the peer-connected socket pub enum SocketResponse { /// A message was received MessageReceived(NetworkMessage), /// An error occured and the socket needs to close ConnectionFailed(util::Error, Sender<()>) } #[derive(Clone, PartialEq, Eq, Debug)]
/// `verack` Verack, /// `addr` Addr(Vec<(u32, Address)>), /// `inv` Inv(Vec<message_blockdata::Inventory>), /// `getdata` GetData(Vec<message_blockdata::Inventory>), /// `notfound` NotFound(Vec<message_blockdata::Inventory>), /// `getblocks` GetBlocks(message_blockdata::GetBlocksMessage), /// `getheaders` GetHeaders(message_blockdata::GetHeadersMessage), /// tx Tx(transaction::Transaction), /// `block` Block(block::Block), /// `headers` Headers(Vec<block::LoneBlockHeader>), // TODO: getaddr, // TODO: mempool, // TODO: checkorder, // TODO: submitorder, // TODO: reply, /// `ping` Ping(u64), /// `pong` Pong(u64) // TODO: reject, // TODO: bloom filtering // TODO: alert } impl RawNetworkMessage { fn command(&self) -> String { match self.payload { NetworkMessage::Version(_) => "version", NetworkMessage::Verack => "verack", NetworkMessage::Addr(_) => "addr", NetworkMessage::Inv(_) => "inv", NetworkMessage::GetData(_) => "getdata", NetworkMessage::NotFound(_) => "notfound", NetworkMessage::GetBlocks(_) => "getblocks", NetworkMessage::GetHeaders(_) => "getheaders", NetworkMessage::Tx(_) => "tx", NetworkMessage::Block(_) => "block", NetworkMessage::Headers(_) => "headers", NetworkMessage::Ping(_) => "ping", NetworkMessage::Pong(_) => "pong", }.to_string() } } impl<S: SimpleEncoder> ConsensusEncodable<S> for RawNetworkMessage { fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { try!(self.magic.consensus_encode(s)); try!(CommandString(self.command()).consensus_encode(s)); try!(CheckedData(match self.payload { NetworkMessage::Version(ref dat) => serialize(dat), NetworkMessage::Verack => Ok(vec![]), NetworkMessage::Addr(ref dat) => serialize(dat), NetworkMessage::Inv(ref dat) => serialize(dat), NetworkMessage::GetData(ref dat) => serialize(dat), NetworkMessage::NotFound(ref dat) => serialize(dat), NetworkMessage::GetBlocks(ref dat) => serialize(dat), NetworkMessage::GetHeaders(ref dat) => serialize(dat), NetworkMessage::Tx(ref dat) => serialize(dat), NetworkMessage::Block(ref dat) => serialize(dat), NetworkMessage::Headers(ref dat) => serialize(dat), NetworkMessage::Ping(ref dat) => serialize(dat), NetworkMessage::Pong(ref dat) => serialize(dat), }.unwrap()).consensus_encode(s)); Ok(()) } } // TODO: restriction on D::Error is so that `propagate_err` will work; // is there a more generic way to handle this? impl<D: SimpleDecoder<Error=util::Error>> ConsensusDecodable<D> for RawNetworkMessage { fn consensus_decode(d: &mut D) -> Result<RawNetworkMessage, D::Error> { let magic = try!(ConsensusDecodable::consensus_decode(d)); let CommandString(cmd): CommandString= try!(ConsensusDecodable::consensus_decode(d)); let CheckedData(raw_payload): CheckedData = try!(ConsensusDecodable::consensus_decode(d)); let mut mem_d = RawDecoder::new(Cursor::new(raw_payload)); let payload = match &cmd[..] { "version" => NetworkMessage::Version(try!(propagate_err("version".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "verack" => NetworkMessage::Verack, "addr" => NetworkMessage::Addr(try!(propagate_err("addr".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "inv" => NetworkMessage::Inv(try!(propagate_err("inv".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "getdata" => NetworkMessage::GetData(try!(propagate_err("getdata".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "notfound" => NetworkMessage::NotFound(try!(propagate_err("notfound".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "getblocks" => NetworkMessage::GetBlocks(try!(propagate_err("getblocks".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "getheaders" => NetworkMessage::GetHeaders(try!(propagate_err("getheaders".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "block" => NetworkMessage::Block(try!(propagate_err("block".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "headers" => NetworkMessage::Headers(try!(propagate_err("headers".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "ping" => NetworkMessage::Ping(try!(propagate_err("ping".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "pong" => NetworkMessage::Ping(try!(propagate_err("pong".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "tx" => NetworkMessage::Tx(try!(propagate_err("tx".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), cmd => return Err(d.error(format!("unrecognized network command `{}`", cmd))) }; Ok(RawNetworkMessage { magic: magic, payload: payload }) } } #[cfg(test)] mod test { use super::{RawNetworkMessage, NetworkMessage, CommandString}; use network::serialize::{deserialize, serialize}; #[test] fn serialize_commandstring_test() { let cs = CommandString("Andrew".to_string()); assert_eq!(serialize(&cs).ok(), Some(vec![0x41u8, 0x6e, 0x64, 0x72, 0x65, 0x77, 0, 0, 0, 0, 0, 0])); } #[test] fn deserialize_commandstring_test() { let cs: Result<CommandString, _> = deserialize(&[0x41u8, 0x6e, 0x64, 0x72, 0x65, 0x77, 0, 0, 0, 0, 0, 0]); assert!(cs.is_ok()); assert_eq!(cs.unwrap(), CommandString("Andrew".to_string())); let short_cs: Result<CommandString, _> = deserialize(&[0x41u8, 0x6e, 0x64, 0x72, 0x65, 0x77, 0, 0, 0, 0, 0]); assert!(short_cs.is_err()); } #[test] fn serialize_verack_test() { assert_eq!(serialize(&RawNetworkMessage { magic: 0xd9b4bef9, payload: NetworkMessage::Verack }).ok(), Some(vec![0xf9, 0xbe, 0xb4, 0xd9, 0x76, 0x65, 0x72, 0x61, 0x63, 0x6B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5d, 0xf6, 0xe0, 0xe2])); } #[test] fn serialize_ping_test() { assert_eq!(serialize(&RawNetworkMessage { magic: 0xd9b4bef9, payload: NetworkMessage::Ping(100) }).ok(), Some(vec![0xf9, 0xbe, 0xb4, 0xd9, 0x70, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x24, 0x67, 0xf1, 0x1d, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])); } }
/// A Network message payload. Proper documentation is available on the Bitcoin /// wiki https://en.bitcoin.it/wiki/Protocol_specification pub enum NetworkMessage { /// `version` Version(message_network::VersionMessage),
random_line_split
message.rs
// Rust Bitcoin Library // Written in 2014 by // Andrew Poelstra <[email protected]> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. // // You should have received a copy of the CC0 Public Domain Dedication // along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // //! # Network message //! //! This module defines the `Message` traits which are used //! for (de)serializing Bitcoin objects for transmission on the network. It //! also defines (de)serialization routines for many primitives. //! use std::iter; use std::io::Cursor; use std::sync::mpsc::Sender; use blockdata::block; use blockdata::transaction; use network::address::Address; use network::message_network; use network::message_blockdata; use network::encodable::{ConsensusDecodable, ConsensusEncodable}; use network::encodable::CheckedData; use network::serialize::{serialize, RawDecoder, SimpleEncoder, SimpleDecoder}; use util::{self, propagate_err}; /// Serializer for command string #[derive(PartialEq, Eq, Clone, Debug)] pub struct CommandString(pub String); impl<S: SimpleEncoder> ConsensusEncodable<S> for CommandString { #[inline] fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { use std::intrinsics::copy_nonoverlapping; use std::mem; let &CommandString(ref inner_str) = self; let mut rawbytes = [0u8; 12]; unsafe { copy_nonoverlapping(inner_str.as_bytes().as_ptr(), rawbytes.as_mut_ptr(), mem::size_of::<[u8; 12]>()); } rawbytes.consensus_encode(s) } } impl<D: SimpleDecoder> ConsensusDecodable<D> for CommandString { #[inline] fn consensus_decode(d: &mut D) -> Result<CommandString, D::Error> { let rawbytes: [u8; 12] = try!(ConsensusDecodable::consensus_decode(d)); let rv = iter::FromIterator::from_iter(rawbytes.iter().filter_map(|&u| if u > 0 { Some(u as char) } else { None })); Ok(CommandString(rv)) } } /// A Network message pub struct RawNetworkMessage { /// Magic bytes to identify the network these messages are meant for pub magic: u32, /// The actual message data pub payload: NetworkMessage } /// A response from the peer-connected socket pub enum SocketResponse { /// A message was received MessageReceived(NetworkMessage), /// An error occured and the socket needs to close ConnectionFailed(util::Error, Sender<()>) } #[derive(Clone, PartialEq, Eq, Debug)] /// A Network message payload. Proper documentation is available on the Bitcoin /// wiki https://en.bitcoin.it/wiki/Protocol_specification pub enum NetworkMessage { /// `version` Version(message_network::VersionMessage), /// `verack` Verack, /// `addr` Addr(Vec<(u32, Address)>), /// `inv` Inv(Vec<message_blockdata::Inventory>), /// `getdata` GetData(Vec<message_blockdata::Inventory>), /// `notfound` NotFound(Vec<message_blockdata::Inventory>), /// `getblocks` GetBlocks(message_blockdata::GetBlocksMessage), /// `getheaders` GetHeaders(message_blockdata::GetHeadersMessage), /// tx Tx(transaction::Transaction), /// `block` Block(block::Block), /// `headers` Headers(Vec<block::LoneBlockHeader>), // TODO: getaddr, // TODO: mempool, // TODO: checkorder, // TODO: submitorder, // TODO: reply, /// `ping` Ping(u64), /// `pong` Pong(u64) // TODO: reject, // TODO: bloom filtering // TODO: alert } impl RawNetworkMessage { fn command(&self) -> String { match self.payload { NetworkMessage::Version(_) => "version", NetworkMessage::Verack => "verack", NetworkMessage::Addr(_) => "addr", NetworkMessage::Inv(_) => "inv", NetworkMessage::GetData(_) => "getdata", NetworkMessage::NotFound(_) => "notfound", NetworkMessage::GetBlocks(_) => "getblocks", NetworkMessage::GetHeaders(_) => "getheaders", NetworkMessage::Tx(_) => "tx", NetworkMessage::Block(_) => "block", NetworkMessage::Headers(_) => "headers", NetworkMessage::Ping(_) => "ping", NetworkMessage::Pong(_) => "pong", }.to_string() } } impl<S: SimpleEncoder> ConsensusEncodable<S> for RawNetworkMessage { fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { try!(self.magic.consensus_encode(s)); try!(CommandString(self.command()).consensus_encode(s)); try!(CheckedData(match self.payload { NetworkMessage::Version(ref dat) => serialize(dat), NetworkMessage::Verack => Ok(vec![]), NetworkMessage::Addr(ref dat) => serialize(dat), NetworkMessage::Inv(ref dat) => serialize(dat), NetworkMessage::GetData(ref dat) => serialize(dat), NetworkMessage::NotFound(ref dat) => serialize(dat), NetworkMessage::GetBlocks(ref dat) => serialize(dat), NetworkMessage::GetHeaders(ref dat) => serialize(dat), NetworkMessage::Tx(ref dat) => serialize(dat), NetworkMessage::Block(ref dat) => serialize(dat), NetworkMessage::Headers(ref dat) => serialize(dat), NetworkMessage::Ping(ref dat) => serialize(dat), NetworkMessage::Pong(ref dat) => serialize(dat), }.unwrap()).consensus_encode(s)); Ok(()) } } // TODO: restriction on D::Error is so that `propagate_err` will work; // is there a more generic way to handle this? impl<D: SimpleDecoder<Error=util::Error>> ConsensusDecodable<D> for RawNetworkMessage { fn
(d: &mut D) -> Result<RawNetworkMessage, D::Error> { let magic = try!(ConsensusDecodable::consensus_decode(d)); let CommandString(cmd): CommandString= try!(ConsensusDecodable::consensus_decode(d)); let CheckedData(raw_payload): CheckedData = try!(ConsensusDecodable::consensus_decode(d)); let mut mem_d = RawDecoder::new(Cursor::new(raw_payload)); let payload = match &cmd[..] { "version" => NetworkMessage::Version(try!(propagate_err("version".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "verack" => NetworkMessage::Verack, "addr" => NetworkMessage::Addr(try!(propagate_err("addr".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "inv" => NetworkMessage::Inv(try!(propagate_err("inv".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "getdata" => NetworkMessage::GetData(try!(propagate_err("getdata".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "notfound" => NetworkMessage::NotFound(try!(propagate_err("notfound".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "getblocks" => NetworkMessage::GetBlocks(try!(propagate_err("getblocks".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "getheaders" => NetworkMessage::GetHeaders(try!(propagate_err("getheaders".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "block" => NetworkMessage::Block(try!(propagate_err("block".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "headers" => NetworkMessage::Headers(try!(propagate_err("headers".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "ping" => NetworkMessage::Ping(try!(propagate_err("ping".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "pong" => NetworkMessage::Ping(try!(propagate_err("pong".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), "tx" => NetworkMessage::Tx(try!(propagate_err("tx".to_string(), ConsensusDecodable::consensus_decode(&mut mem_d)))), cmd => return Err(d.error(format!("unrecognized network command `{}`", cmd))) }; Ok(RawNetworkMessage { magic: magic, payload: payload }) } } #[cfg(test)] mod test { use super::{RawNetworkMessage, NetworkMessage, CommandString}; use network::serialize::{deserialize, serialize}; #[test] fn serialize_commandstring_test() { let cs = CommandString("Andrew".to_string()); assert_eq!(serialize(&cs).ok(), Some(vec![0x41u8, 0x6e, 0x64, 0x72, 0x65, 0x77, 0, 0, 0, 0, 0, 0])); } #[test] fn deserialize_commandstring_test() { let cs: Result<CommandString, _> = deserialize(&[0x41u8, 0x6e, 0x64, 0x72, 0x65, 0x77, 0, 0, 0, 0, 0, 0]); assert!(cs.is_ok()); assert_eq!(cs.unwrap(), CommandString("Andrew".to_string())); let short_cs: Result<CommandString, _> = deserialize(&[0x41u8, 0x6e, 0x64, 0x72, 0x65, 0x77, 0, 0, 0, 0, 0]); assert!(short_cs.is_err()); } #[test] fn serialize_verack_test() { assert_eq!(serialize(&RawNetworkMessage { magic: 0xd9b4bef9, payload: NetworkMessage::Verack }).ok(), Some(vec![0xf9, 0xbe, 0xb4, 0xd9, 0x76, 0x65, 0x72, 0x61, 0x63, 0x6B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5d, 0xf6, 0xe0, 0xe2])); } #[test] fn serialize_ping_test() { assert_eq!(serialize(&RawNetworkMessage { magic: 0xd9b4bef9, payload: NetworkMessage::Ping(100) }).ok(), Some(vec![0xf9, 0xbe, 0xb4, 0xd9, 0x70, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x24, 0x67, 0xf1, 0x1d, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])); } }
consensus_decode
identifier_name
event.rs
use crate::Token; use super::Ready; pub type SysEvent = Event; #[derive(Debug, Clone)] pub struct Event { token: Token, readiness: Ready, } impl Event { pub(crate) fn new(readiness: Ready, token: Token) -> Event { Event { token, readiness } } pub fn token(&self) -> Token { self.token } pub fn is_readable(&self) -> bool { self.readiness.is_readable() } pub fn is_writable(&self) -> bool { self.readiness.is_writable() } pub fn is_error(&self) -> bool { self.readiness.is_error()
} pub fn is_priority(&self) -> bool { self.readiness.is_priority() } pub fn is_aio(&self) -> bool { self.readiness.is_aio() } pub fn is_lio(&self) -> bool { self.readiness.is_lio() } }
} pub fn is_hup(&self) -> bool { self.readiness.is_hup()
random_line_split
event.rs
use crate::Token; use super::Ready; pub type SysEvent = Event; #[derive(Debug, Clone)] pub struct Event { token: Token, readiness: Ready, } impl Event { pub(crate) fn new(readiness: Ready, token: Token) -> Event { Event { token, readiness } } pub fn token(&self) -> Token { self.token } pub fn
(&self) -> bool { self.readiness.is_readable() } pub fn is_writable(&self) -> bool { self.readiness.is_writable() } pub fn is_error(&self) -> bool { self.readiness.is_error() } pub fn is_hup(&self) -> bool { self.readiness.is_hup() } pub fn is_priority(&self) -> bool { self.readiness.is_priority() } pub fn is_aio(&self) -> bool { self.readiness.is_aio() } pub fn is_lio(&self) -> bool { self.readiness.is_lio() } }
is_readable
identifier_name
from_json.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Coversion from json. use standard::*; use bigint::uint::*; #[macro_export] macro_rules! xjson { ( $x:expr ) => { FromJson::from_json($x)
pub trait FromJson { /// Convert a JSON value to an instance of this type. fn from_json(json: &Json) -> Self; } impl FromJson for U256 { fn from_json(json: &Json) -> Self { match *json { Json::String(ref s) => { if s.len() >= 2 && &s[0..2] == "0x" { FromStr::from_str(&s[2..]).unwrap_or_else(|_| Default::default()) } else { Uint::from_dec_str(s).unwrap_or_else(|_| Default::default()) } }, Json::U64(u) => From::from(u), Json::I64(i) => From::from(i as u64), _ => Uint::zero(), } } }
} } /// Trait allowing conversion from a JSON value.
random_line_split
from_json.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Coversion from json. use standard::*; use bigint::uint::*; #[macro_export] macro_rules! xjson { ( $x:expr ) => { FromJson::from_json($x) } } /// Trait allowing conversion from a JSON value. pub trait FromJson { /// Convert a JSON value to an instance of this type. fn from_json(json: &Json) -> Self; } impl FromJson for U256 { fn from_json(json: &Json) -> Self
}
{ match *json { Json::String(ref s) => { if s.len() >= 2 && &s[0..2] == "0x" { FromStr::from_str(&s[2..]).unwrap_or_else(|_| Default::default()) } else { Uint::from_dec_str(s).unwrap_or_else(|_| Default::default()) } }, Json::U64(u) => From::from(u), Json::I64(i) => From::from(i as u64), _ => Uint::zero(), } }
identifier_body
from_json.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Coversion from json. use standard::*; use bigint::uint::*; #[macro_export] macro_rules! xjson { ( $x:expr ) => { FromJson::from_json($x) } } /// Trait allowing conversion from a JSON value. pub trait FromJson { /// Convert a JSON value to an instance of this type. fn from_json(json: &Json) -> Self; } impl FromJson for U256 { fn
(json: &Json) -> Self { match *json { Json::String(ref s) => { if s.len() >= 2 && &s[0..2] == "0x" { FromStr::from_str(&s[2..]).unwrap_or_else(|_| Default::default()) } else { Uint::from_dec_str(s).unwrap_or_else(|_| Default::default()) } }, Json::U64(u) => From::from(u), Json::I64(i) => From::from(i as u64), _ => Uint::zero(), } } }
from_json
identifier_name
util.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::sync::Arc; use cpython::*; use cpython_ext::{ExtractInner, PyPath, PyPathBuf, ResultPyErrExt}; use edenapi::{Progress, ProgressCallback, ResponseMeta}; use edenapi_types::TreeAttributes; use pyrevisionstore::{mutabledeltastore, mutablehistorystore}; use revisionstore::{HgIdMutableDeltaStore, HgIdMutableHistoryStore}; use types::{HgId, Key, RepoPathBuf}; pub fn to_path(py: Python, name: &PyPath) -> PyResult<RepoPathBuf> { name.to_repo_path() .map_pyerr(py) .map(|path| path.to_owned()) } pub fn to_hgid(py: Python, hgid: &PyBytes) -> HgId { let mut bytes = [0u8; 20]; bytes.copy_from_slice(&hgid.data(py)[0..20]); HgId::from(&bytes) } pub fn to_tree_attrs(py: Python, attrs: &PyDict) -> PyResult<TreeAttributes> { let mut attributes = TreeAttributes::default(); attributes.manifest_blob = attrs .get_item(py, "manifest_blob") .map(|v| v.extract::<bool>(py)) .transpose()? .unwrap_or(attributes.manifest_blob); attributes.parents = attrs .get_item(py, "parents") .map(|v| v.extract::<bool>(py)) .transpose()? .unwrap_or(attributes.parents); attributes.child_metadata = attrs .get_item(py, "child_metadata") .map(|v| v.extract::<bool>(py)) .transpose()? .unwrap_or(attributes.child_metadata); Ok(attributes) } pub fn to_hgids(py: Python, hgids: impl IntoIterator<Item = PyBytes>) -> Vec<HgId> { hgids.into_iter().map(|hgid| to_hgid(py, &hgid)).collect() } pub fn to_key(py: Python, path: &PyPath, hgid: &PyBytes) -> PyResult<Key> { let hgid = to_hgid(py, hgid); let path = to_path(py, path)?; Ok(Key::new(path, hgid)) } pub fn
<'a>( py: Python, keys: impl IntoIterator<Item = &'a (PyPathBuf, PyBytes)>, ) -> PyResult<Vec<Key>> { keys.into_iter() .map(|(path, hgid)| to_key(py, path, hgid)) .collect() } pub fn wrap_callback(callback: PyObject) -> ProgressCallback { Box::new(move |progress: Progress| { let gil = Python::acquire_gil(); let py = gil.python(); let _ = callback.call(py, progress.as_tuple(), None); }) } pub fn as_deltastore(py: Python, store: PyObject) -> PyResult<Arc<dyn HgIdMutableDeltaStore>> { Ok(store.extract::<mutabledeltastore>(py)?.extract_inner(py)) } pub fn as_historystore(py: Python, store: PyObject) -> PyResult<Arc<dyn HgIdMutableHistoryStore>> { Ok(store.extract::<mutablehistorystore>(py)?.extract_inner(py)) } pub fn meta_to_dict(py: Python, meta: &ResponseMeta) -> PyResult<PyDict> { let dict = PyDict::new(py); dict.set_item(py, "version", format!("{:?}", &meta.version))?; dict.set_item(py, "status", meta.status.as_u16())?; dict.set_item(py, "server", &meta.server)?; dict.set_item(py, "request_id", &meta.request_id)?; dict.set_item(py, "tw_task_handle", &meta.tw_task_handle)?; dict.set_item(py, "tw_task_version", &meta.tw_task_version)?; dict.set_item(py, "tw_canary_id", &meta.tw_canary_id)?; dict.set_item(py, "server_load", &meta.server_load)?; dict.set_item(py, "content_length", &meta.content_length)?; Ok(dict) }
to_keys
identifier_name
util.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::sync::Arc; use cpython::*; use cpython_ext::{ExtractInner, PyPath, PyPathBuf, ResultPyErrExt}; use edenapi::{Progress, ProgressCallback, ResponseMeta}; use edenapi_types::TreeAttributes; use pyrevisionstore::{mutabledeltastore, mutablehistorystore}; use revisionstore::{HgIdMutableDeltaStore, HgIdMutableHistoryStore}; use types::{HgId, Key, RepoPathBuf}; pub fn to_path(py: Python, name: &PyPath) -> PyResult<RepoPathBuf> { name.to_repo_path() .map_pyerr(py) .map(|path| path.to_owned()) } pub fn to_hgid(py: Python, hgid: &PyBytes) -> HgId { let mut bytes = [0u8; 20]; bytes.copy_from_slice(&hgid.data(py)[0..20]); HgId::from(&bytes) } pub fn to_tree_attrs(py: Python, attrs: &PyDict) -> PyResult<TreeAttributes> { let mut attributes = TreeAttributes::default(); attributes.manifest_blob = attrs .get_item(py, "manifest_blob") .map(|v| v.extract::<bool>(py)) .transpose()? .unwrap_or(attributes.manifest_blob); attributes.parents = attrs .get_item(py, "parents") .map(|v| v.extract::<bool>(py)) .transpose()? .unwrap_or(attributes.parents); attributes.child_metadata = attrs .get_item(py, "child_metadata") .map(|v| v.extract::<bool>(py)) .transpose()? .unwrap_or(attributes.child_metadata); Ok(attributes) } pub fn to_hgids(py: Python, hgids: impl IntoIterator<Item = PyBytes>) -> Vec<HgId> { hgids.into_iter().map(|hgid| to_hgid(py, &hgid)).collect() } pub fn to_key(py: Python, path: &PyPath, hgid: &PyBytes) -> PyResult<Key> { let hgid = to_hgid(py, hgid); let path = to_path(py, path)?; Ok(Key::new(path, hgid)) } pub fn to_keys<'a>( py: Python, keys: impl IntoIterator<Item = &'a (PyPathBuf, PyBytes)>, ) -> PyResult<Vec<Key>> { keys.into_iter() .map(|(path, hgid)| to_key(py, path, hgid)) .collect() } pub fn wrap_callback(callback: PyObject) -> ProgressCallback
pub fn as_deltastore(py: Python, store: PyObject) -> PyResult<Arc<dyn HgIdMutableDeltaStore>> { Ok(store.extract::<mutabledeltastore>(py)?.extract_inner(py)) } pub fn as_historystore(py: Python, store: PyObject) -> PyResult<Arc<dyn HgIdMutableHistoryStore>> { Ok(store.extract::<mutablehistorystore>(py)?.extract_inner(py)) } pub fn meta_to_dict(py: Python, meta: &ResponseMeta) -> PyResult<PyDict> { let dict = PyDict::new(py); dict.set_item(py, "version", format!("{:?}", &meta.version))?; dict.set_item(py, "status", meta.status.as_u16())?; dict.set_item(py, "server", &meta.server)?; dict.set_item(py, "request_id", &meta.request_id)?; dict.set_item(py, "tw_task_handle", &meta.tw_task_handle)?; dict.set_item(py, "tw_task_version", &meta.tw_task_version)?; dict.set_item(py, "tw_canary_id", &meta.tw_canary_id)?; dict.set_item(py, "server_load", &meta.server_load)?; dict.set_item(py, "content_length", &meta.content_length)?; Ok(dict) }
{ Box::new(move |progress: Progress| { let gil = Python::acquire_gil(); let py = gil.python(); let _ = callback.call(py, progress.as_tuple(), None); }) }
identifier_body
util.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::sync::Arc; use cpython::*; use cpython_ext::{ExtractInner, PyPath, PyPathBuf, ResultPyErrExt}; use edenapi::{Progress, ProgressCallback, ResponseMeta}; use edenapi_types::TreeAttributes; use pyrevisionstore::{mutabledeltastore, mutablehistorystore}; use revisionstore::{HgIdMutableDeltaStore, HgIdMutableHistoryStore}; use types::{HgId, Key, RepoPathBuf}; pub fn to_path(py: Python, name: &PyPath) -> PyResult<RepoPathBuf> { name.to_repo_path() .map_pyerr(py) .map(|path| path.to_owned()) } pub fn to_hgid(py: Python, hgid: &PyBytes) -> HgId { let mut bytes = [0u8; 20]; bytes.copy_from_slice(&hgid.data(py)[0..20]); HgId::from(&bytes) } pub fn to_tree_attrs(py: Python, attrs: &PyDict) -> PyResult<TreeAttributes> { let mut attributes = TreeAttributes::default(); attributes.manifest_blob = attrs .get_item(py, "manifest_blob") .map(|v| v.extract::<bool>(py)) .transpose()? .unwrap_or(attributes.manifest_blob); attributes.parents = attrs
.transpose()? .unwrap_or(attributes.parents); attributes.child_metadata = attrs .get_item(py, "child_metadata") .map(|v| v.extract::<bool>(py)) .transpose()? .unwrap_or(attributes.child_metadata); Ok(attributes) } pub fn to_hgids(py: Python, hgids: impl IntoIterator<Item = PyBytes>) -> Vec<HgId> { hgids.into_iter().map(|hgid| to_hgid(py, &hgid)).collect() } pub fn to_key(py: Python, path: &PyPath, hgid: &PyBytes) -> PyResult<Key> { let hgid = to_hgid(py, hgid); let path = to_path(py, path)?; Ok(Key::new(path, hgid)) } pub fn to_keys<'a>( py: Python, keys: impl IntoIterator<Item = &'a (PyPathBuf, PyBytes)>, ) -> PyResult<Vec<Key>> { keys.into_iter() .map(|(path, hgid)| to_key(py, path, hgid)) .collect() } pub fn wrap_callback(callback: PyObject) -> ProgressCallback { Box::new(move |progress: Progress| { let gil = Python::acquire_gil(); let py = gil.python(); let _ = callback.call(py, progress.as_tuple(), None); }) } pub fn as_deltastore(py: Python, store: PyObject) -> PyResult<Arc<dyn HgIdMutableDeltaStore>> { Ok(store.extract::<mutabledeltastore>(py)?.extract_inner(py)) } pub fn as_historystore(py: Python, store: PyObject) -> PyResult<Arc<dyn HgIdMutableHistoryStore>> { Ok(store.extract::<mutablehistorystore>(py)?.extract_inner(py)) } pub fn meta_to_dict(py: Python, meta: &ResponseMeta) -> PyResult<PyDict> { let dict = PyDict::new(py); dict.set_item(py, "version", format!("{:?}", &meta.version))?; dict.set_item(py, "status", meta.status.as_u16())?; dict.set_item(py, "server", &meta.server)?; dict.set_item(py, "request_id", &meta.request_id)?; dict.set_item(py, "tw_task_handle", &meta.tw_task_handle)?; dict.set_item(py, "tw_task_version", &meta.tw_task_version)?; dict.set_item(py, "tw_canary_id", &meta.tw_canary_id)?; dict.set_item(py, "server_load", &meta.server_load)?; dict.set_item(py, "content_length", &meta.content_length)?; Ok(dict) }
.get_item(py, "parents") .map(|v| v.extract::<bool>(py))
random_line_split
global_gen.rs
// Copyright 2013-2014 The gl-rs developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use registry::{Registry, Ns}; use std::io; #[allow(missing_copy_implementations)] pub struct GlobalGenerator; impl super::Generator for GlobalGenerator { fn write<W>(&self, registry: &Registry, ns: Ns, dest: &mut W) -> io::Result<()> where W: io::Write { try!(write_header(dest)); try!(write_metaloadfn(dest)); try!(write_type_aliases(&ns, dest)); try!(write_enums(registry, dest)); try!(write_fns(registry, dest)); try!(write_fnptr_struct_def(dest)); try!(write_ptrs(registry, dest)); try!(write_fn_mods(registry, &ns, dest)); try!(write_panicking_fns(&ns, dest)); try!(write_load_fn(registry, dest)); Ok(()) } } /// Creates a `__gl_imports` module which contains all the external symbols that we need for the /// bindings. fn write_header<W>(dest: &mut W) -> io::Result<()> where W: io::Write { writeln!(dest, r#" mod __gl_imports {{ extern crate gl_common; extern crate libc; pub use std::mem; }} "#) } /// Creates the metaloadfn function for fallbacks fn write_metaloadfn<W>(dest: &mut W) -> io::Result<()> where W: io::Write { writeln!(dest, r#" fn metaloadfn<F>(mut loadfn: F, symbol: &str, fallbacks: &[&str]) -> *const __gl_imports::libc::c_void where F: FnMut(&str) -> *const __gl_imports::libc::c_void {{ let mut ptr = loadfn(symbol); if ptr.is_null() {{ for &sym in fallbacks.iter() {{ ptr = loadfn(sym); if!ptr.is_null() {{ break; }} }} }} ptr }} "#) } /// Creates a `types` module which contains all the type aliases. /// /// See also `generators::gen_type_aliases`. fn write_type_aliases<W>(ns: &Ns, dest: &mut W) -> io::Result<()> where W: io::Write { try!(writeln!(dest, r#" pub mod types {{ #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(dead_code)] #![allow(missing_copy_implementations)] "#)); try!(super::gen_type_aliases(ns, dest)); writeln!(dest, " }} ") } /// Creates all the `<enum>` elements at the root of the bindings. fn write_enums<W>(registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write { for e in registry.enum_iter() { try!(super::gen_enum_item(e, "types::", dest)); } Ok(()) } /// Creates the functions corresponding to the GL commands. /// /// The function calls the corresponding function pointer stored in the `storage` module created /// by `write_ptrs`. fn write_fns<W>(registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write { for c in registry.cmd_iter() { if let Some(v) = registry.aliases.get(&c.proto.ident) { try!(writeln!(dest, "/// Fallbacks: {}", v.connect(", "))); } try!(writeln!(dest, "#[allow(non_snake_case, unused_variables, dead_code)] #[inline] pub unsafe fn {name}({params}) -> {return_suffix} {{ \ __gl_imports::mem::transmute::<_, extern \"system\" fn({typed_params}) -> {return_suffix}>\ (storage::{name}.f)({idents}) \ }}", name = c.proto.ident, params = super::gen_parameters(c, true, true).connect(", "), typed_params = super::gen_parameters(c, false, true).connect(", "), return_suffix = super::gen_return_type(c), idents = super::gen_parameters(c, true, false).connect(", "), )); } Ok(()) } /// Creates a `FnPtr` structure which contains the store for a single binding. fn write_fnptr_struct_def<W>(dest: &mut W) -> io::Result<()> where W: io::Write { writeln!(dest, " #[allow(missing_copy_implementations)] pub struct FnPtr {{ /// The function pointer that will be used when calling the function. f: *const __gl_imports::libc::c_void, /// True if the pointer points to a real function, false if points to a `panic!` fn. is_loaded: bool, }} impl FnPtr {{ /// Creates a `FnPtr` from a load attempt. pub fn new(ptr: *const __gl_imports::libc::c_void) -> FnPtr {{ if ptr.is_null() {{ FnPtr {{ f: missing_fn_panic as *const __gl_imports::libc::c_void, is_loaded: false }} }} else {{ FnPtr {{ f: ptr, is_loaded: true }} }} }} }} ") } /// Creates a `storage` module which contains a static `FnPtr` per GL command in the registry. fn write_ptrs<W>(registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write { try!(writeln!(dest, "mod storage {{ #![allow(non_snake_case)] use super::__gl_imports::libc; use super::FnPtr;")); for c in registry.cmd_iter() { try!(writeln!(dest, "pub static mut {name}: FnPtr = FnPtr {{ f: super::missing_fn_panic as *const libc::c_void, is_loaded: false }};", name = c.proto.ident )); } writeln!(dest, "}}") } /// Creates one module for each GL command. /// /// Each module contains `is_loaded` and `load_with` which interact with the `storage` module /// created by `write_ptrs`. fn write_fn_mods<W>(registry: &Registry, ns: &Ns, dest: &mut W) -> io::Result<()> where W: io::Write
pub fn is_loaded() -> bool {{ unsafe {{ storage::{fnname}.is_loaded }} }} #[allow(dead_code)] pub fn load_with<F>(loadfn: F) where F: FnMut(&str) -> *const super::__gl_imports::libc::c_void {{ unsafe {{ storage::{fnname} = FnPtr::new(metaloadfn(loadfn, "{symbol}", {fallbacks})) }} }} }} "##, fnname = fnname, fallbacks = fallbacks, symbol = symbol)); } Ok(()) } /// Creates a `missing_fn_panic` function. /// /// This function is the mock that is called if the real function could not be called. fn write_panicking_fns<W>(ns: &Ns, dest: &mut W) -> io::Result<()> where W: io::Write { writeln!(dest, "#[inline(never)] fn missing_fn_panic() ->! {{ panic!(\"{ns} function was not loaded\") }} ", ns = ns) } /// Creates the `load_with` function. /// /// The function calls `load_with` in each module created by `write_fn_mods`. fn write_load_fn<W>(registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write { try!(writeln!(dest, " /// Load each OpenGL symbol using a custom load function. This allows for the /// use of functions like `glfwGetProcAddress` or `SDL_GL_GetProcAddress`. /// ~~~ignore /// gl::load_with(|s| glfw.get_proc_address(s)); /// ~~~ #[allow(dead_code)] pub fn load_with<F>(mut loadfn: F) where F: FnMut(&str) -> *const __gl_imports::libc::c_void {{ ")); for c in registry.cmd_iter() { try!(writeln!(dest, "{cmd_name}::load_with(|s| loadfn(s));", cmd_name = &c.proto.ident[..])); } writeln!(dest, " }} /// Load each OpenGL symbol using a custom load function. /// /// ~~~ignore /// gl::load(&glfw); /// ~~~ #[allow(dead_code)] pub fn load<T: __gl_imports::gl_common::GlFunctionsSource>(loader: &T) {{ load_with(|name| loader.get_proc_addr(name)); }} ") }
{ for c in registry.cmd_iter() { let fallbacks = match registry.aliases.get(&c.proto.ident) { Some(v) => { let names = v.iter().map(|name| format!("\"{}\"", super::gen_symbol_name(ns, &name[..]))).collect::<Vec<_>>(); format!("&[{}]", names.connect(", ")) }, None => "&[]".to_string(), }; let fnname = &c.proto.ident[..]; let symbol = super::gen_symbol_name(ns, &c.proto.ident[..]); let symbol = &symbol[..]; try!(writeln!(dest, r##" #[allow(non_snake_case)] pub mod {fnname} {{ use super::{{storage, metaloadfn}}; use super::FnPtr; #[inline] #[allow(dead_code)]
identifier_body
global_gen.rs
// Copyright 2013-2014 The gl-rs developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use registry::{Registry, Ns}; use std::io; #[allow(missing_copy_implementations)] pub struct GlobalGenerator; impl super::Generator for GlobalGenerator { fn write<W>(&self, registry: &Registry, ns: Ns, dest: &mut W) -> io::Result<()> where W: io::Write { try!(write_header(dest)); try!(write_metaloadfn(dest)); try!(write_type_aliases(&ns, dest)); try!(write_enums(registry, dest)); try!(write_fns(registry, dest)); try!(write_fnptr_struct_def(dest)); try!(write_ptrs(registry, dest)); try!(write_fn_mods(registry, &ns, dest)); try!(write_panicking_fns(&ns, dest)); try!(write_load_fn(registry, dest)); Ok(()) } } /// Creates a `__gl_imports` module which contains all the external symbols that we need for the /// bindings. fn write_header<W>(dest: &mut W) -> io::Result<()> where W: io::Write { writeln!(dest, r#" mod __gl_imports {{ extern crate gl_common; extern crate libc; pub use std::mem; }} "#) } /// Creates the metaloadfn function for fallbacks fn write_metaloadfn<W>(dest: &mut W) -> io::Result<()> where W: io::Write { writeln!(dest, r#" fn metaloadfn<F>(mut loadfn: F, symbol: &str, fallbacks: &[&str]) -> *const __gl_imports::libc::c_void where F: FnMut(&str) -> *const __gl_imports::libc::c_void {{ let mut ptr = loadfn(symbol); if ptr.is_null() {{ for &sym in fallbacks.iter() {{ ptr = loadfn(sym); if!ptr.is_null() {{ break; }} }} }} ptr }} "#) } /// Creates a `types` module which contains all the type aliases. /// /// See also `generators::gen_type_aliases`. fn write_type_aliases<W>(ns: &Ns, dest: &mut W) -> io::Result<()> where W: io::Write { try!(writeln!(dest, r#" pub mod types {{ #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(dead_code)] #![allow(missing_copy_implementations)] "#)); try!(super::gen_type_aliases(ns, dest));
} /// Creates all the `<enum>` elements at the root of the bindings. fn write_enums<W>(registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write { for e in registry.enum_iter() { try!(super::gen_enum_item(e, "types::", dest)); } Ok(()) } /// Creates the functions corresponding to the GL commands. /// /// The function calls the corresponding function pointer stored in the `storage` module created /// by `write_ptrs`. fn write_fns<W>(registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write { for c in registry.cmd_iter() { if let Some(v) = registry.aliases.get(&c.proto.ident) { try!(writeln!(dest, "/// Fallbacks: {}", v.connect(", "))); } try!(writeln!(dest, "#[allow(non_snake_case, unused_variables, dead_code)] #[inline] pub unsafe fn {name}({params}) -> {return_suffix} {{ \ __gl_imports::mem::transmute::<_, extern \"system\" fn({typed_params}) -> {return_suffix}>\ (storage::{name}.f)({idents}) \ }}", name = c.proto.ident, params = super::gen_parameters(c, true, true).connect(", "), typed_params = super::gen_parameters(c, false, true).connect(", "), return_suffix = super::gen_return_type(c), idents = super::gen_parameters(c, true, false).connect(", "), )); } Ok(()) } /// Creates a `FnPtr` structure which contains the store for a single binding. fn write_fnptr_struct_def<W>(dest: &mut W) -> io::Result<()> where W: io::Write { writeln!(dest, " #[allow(missing_copy_implementations)] pub struct FnPtr {{ /// The function pointer that will be used when calling the function. f: *const __gl_imports::libc::c_void, /// True if the pointer points to a real function, false if points to a `panic!` fn. is_loaded: bool, }} impl FnPtr {{ /// Creates a `FnPtr` from a load attempt. pub fn new(ptr: *const __gl_imports::libc::c_void) -> FnPtr {{ if ptr.is_null() {{ FnPtr {{ f: missing_fn_panic as *const __gl_imports::libc::c_void, is_loaded: false }} }} else {{ FnPtr {{ f: ptr, is_loaded: true }} }} }} }} ") } /// Creates a `storage` module which contains a static `FnPtr` per GL command in the registry. fn write_ptrs<W>(registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write { try!(writeln!(dest, "mod storage {{ #![allow(non_snake_case)] use super::__gl_imports::libc; use super::FnPtr;")); for c in registry.cmd_iter() { try!(writeln!(dest, "pub static mut {name}: FnPtr = FnPtr {{ f: super::missing_fn_panic as *const libc::c_void, is_loaded: false }};", name = c.proto.ident )); } writeln!(dest, "}}") } /// Creates one module for each GL command. /// /// Each module contains `is_loaded` and `load_with` which interact with the `storage` module /// created by `write_ptrs`. fn write_fn_mods<W>(registry: &Registry, ns: &Ns, dest: &mut W) -> io::Result<()> where W: io::Write { for c in registry.cmd_iter() { let fallbacks = match registry.aliases.get(&c.proto.ident) { Some(v) => { let names = v.iter().map(|name| format!("\"{}\"", super::gen_symbol_name(ns, &name[..]))).collect::<Vec<_>>(); format!("&[{}]", names.connect(", ")) }, None => "&[]".to_string(), }; let fnname = &c.proto.ident[..]; let symbol = super::gen_symbol_name(ns, &c.proto.ident[..]); let symbol = &symbol[..]; try!(writeln!(dest, r##" #[allow(non_snake_case)] pub mod {fnname} {{ use super::{{storage, metaloadfn}}; use super::FnPtr; #[inline] #[allow(dead_code)] pub fn is_loaded() -> bool {{ unsafe {{ storage::{fnname}.is_loaded }} }} #[allow(dead_code)] pub fn load_with<F>(loadfn: F) where F: FnMut(&str) -> *const super::__gl_imports::libc::c_void {{ unsafe {{ storage::{fnname} = FnPtr::new(metaloadfn(loadfn, "{symbol}", {fallbacks})) }} }} }} "##, fnname = fnname, fallbacks = fallbacks, symbol = symbol)); } Ok(()) } /// Creates a `missing_fn_panic` function. /// /// This function is the mock that is called if the real function could not be called. fn write_panicking_fns<W>(ns: &Ns, dest: &mut W) -> io::Result<()> where W: io::Write { writeln!(dest, "#[inline(never)] fn missing_fn_panic() ->! {{ panic!(\"{ns} function was not loaded\") }} ", ns = ns) } /// Creates the `load_with` function. /// /// The function calls `load_with` in each module created by `write_fn_mods`. fn write_load_fn<W>(registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write { try!(writeln!(dest, " /// Load each OpenGL symbol using a custom load function. This allows for the /// use of functions like `glfwGetProcAddress` or `SDL_GL_GetProcAddress`. /// ~~~ignore /// gl::load_with(|s| glfw.get_proc_address(s)); /// ~~~ #[allow(dead_code)] pub fn load_with<F>(mut loadfn: F) where F: FnMut(&str) -> *const __gl_imports::libc::c_void {{ ")); for c in registry.cmd_iter() { try!(writeln!(dest, "{cmd_name}::load_with(|s| loadfn(s));", cmd_name = &c.proto.ident[..])); } writeln!(dest, " }} /// Load each OpenGL symbol using a custom load function. /// /// ~~~ignore /// gl::load(&glfw); /// ~~~ #[allow(dead_code)] pub fn load<T: __gl_imports::gl_common::GlFunctionsSource>(loader: &T) {{ load_with(|name| loader.get_proc_addr(name)); }} ") }
writeln!(dest, " }} ")
random_line_split
global_gen.rs
// Copyright 2013-2014 The gl-rs developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use registry::{Registry, Ns}; use std::io; #[allow(missing_copy_implementations)] pub struct GlobalGenerator; impl super::Generator for GlobalGenerator { fn write<W>(&self, registry: &Registry, ns: Ns, dest: &mut W) -> io::Result<()> where W: io::Write { try!(write_header(dest)); try!(write_metaloadfn(dest)); try!(write_type_aliases(&ns, dest)); try!(write_enums(registry, dest)); try!(write_fns(registry, dest)); try!(write_fnptr_struct_def(dest)); try!(write_ptrs(registry, dest)); try!(write_fn_mods(registry, &ns, dest)); try!(write_panicking_fns(&ns, dest)); try!(write_load_fn(registry, dest)); Ok(()) } } /// Creates a `__gl_imports` module which contains all the external symbols that we need for the /// bindings. fn write_header<W>(dest: &mut W) -> io::Result<()> where W: io::Write { writeln!(dest, r#" mod __gl_imports {{ extern crate gl_common; extern crate libc; pub use std::mem; }} "#) } /// Creates the metaloadfn function for fallbacks fn write_metaloadfn<W>(dest: &mut W) -> io::Result<()> where W: io::Write { writeln!(dest, r#" fn metaloadfn<F>(mut loadfn: F, symbol: &str, fallbacks: &[&str]) -> *const __gl_imports::libc::c_void where F: FnMut(&str) -> *const __gl_imports::libc::c_void {{ let mut ptr = loadfn(symbol); if ptr.is_null() {{ for &sym in fallbacks.iter() {{ ptr = loadfn(sym); if!ptr.is_null() {{ break; }} }} }} ptr }} "#) } /// Creates a `types` module which contains all the type aliases. /// /// See also `generators::gen_type_aliases`. fn write_type_aliases<W>(ns: &Ns, dest: &mut W) -> io::Result<()> where W: io::Write { try!(writeln!(dest, r#" pub mod types {{ #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(dead_code)] #![allow(missing_copy_implementations)] "#)); try!(super::gen_type_aliases(ns, dest)); writeln!(dest, " }} ") } /// Creates all the `<enum>` elements at the root of the bindings. fn write_enums<W>(registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write { for e in registry.enum_iter() { try!(super::gen_enum_item(e, "types::", dest)); } Ok(()) } /// Creates the functions corresponding to the GL commands. /// /// The function calls the corresponding function pointer stored in the `storage` module created /// by `write_ptrs`. fn write_fns<W>(registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write { for c in registry.cmd_iter() { if let Some(v) = registry.aliases.get(&c.proto.ident) { try!(writeln!(dest, "/// Fallbacks: {}", v.connect(", "))); } try!(writeln!(dest, "#[allow(non_snake_case, unused_variables, dead_code)] #[inline] pub unsafe fn {name}({params}) -> {return_suffix} {{ \ __gl_imports::mem::transmute::<_, extern \"system\" fn({typed_params}) -> {return_suffix}>\ (storage::{name}.f)({idents}) \ }}", name = c.proto.ident, params = super::gen_parameters(c, true, true).connect(", "), typed_params = super::gen_parameters(c, false, true).connect(", "), return_suffix = super::gen_return_type(c), idents = super::gen_parameters(c, true, false).connect(", "), )); } Ok(()) } /// Creates a `FnPtr` structure which contains the store for a single binding. fn write_fnptr_struct_def<W>(dest: &mut W) -> io::Result<()> where W: io::Write { writeln!(dest, " #[allow(missing_copy_implementations)] pub struct FnPtr {{ /// The function pointer that will be used when calling the function. f: *const __gl_imports::libc::c_void, /// True if the pointer points to a real function, false if points to a `panic!` fn. is_loaded: bool, }} impl FnPtr {{ /// Creates a `FnPtr` from a load attempt. pub fn new(ptr: *const __gl_imports::libc::c_void) -> FnPtr {{ if ptr.is_null() {{ FnPtr {{ f: missing_fn_panic as *const __gl_imports::libc::c_void, is_loaded: false }} }} else {{ FnPtr {{ f: ptr, is_loaded: true }} }} }} }} ") } /// Creates a `storage` module which contains a static `FnPtr` per GL command in the registry. fn write_ptrs<W>(registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write { try!(writeln!(dest, "mod storage {{ #![allow(non_snake_case)] use super::__gl_imports::libc; use super::FnPtr;")); for c in registry.cmd_iter() { try!(writeln!(dest, "pub static mut {name}: FnPtr = FnPtr {{ f: super::missing_fn_panic as *const libc::c_void, is_loaded: false }};", name = c.proto.ident )); } writeln!(dest, "}}") } /// Creates one module for each GL command. /// /// Each module contains `is_loaded` and `load_with` which interact with the `storage` module /// created by `write_ptrs`. fn write_fn_mods<W>(registry: &Registry, ns: &Ns, dest: &mut W) -> io::Result<()> where W: io::Write { for c in registry.cmd_iter() { let fallbacks = match registry.aliases.get(&c.proto.ident) { Some(v) => { let names = v.iter().map(|name| format!("\"{}\"", super::gen_symbol_name(ns, &name[..]))).collect::<Vec<_>>(); format!("&[{}]", names.connect(", ")) }, None => "&[]".to_string(), }; let fnname = &c.proto.ident[..]; let symbol = super::gen_symbol_name(ns, &c.proto.ident[..]); let symbol = &symbol[..]; try!(writeln!(dest, r##" #[allow(non_snake_case)] pub mod {fnname} {{ use super::{{storage, metaloadfn}}; use super::FnPtr; #[inline] #[allow(dead_code)] pub fn is_loaded() -> bool {{ unsafe {{ storage::{fnname}.is_loaded }} }} #[allow(dead_code)] pub fn load_with<F>(loadfn: F) where F: FnMut(&str) -> *const super::__gl_imports::libc::c_void {{ unsafe {{ storage::{fnname} = FnPtr::new(metaloadfn(loadfn, "{symbol}", {fallbacks})) }} }} }} "##, fnname = fnname, fallbacks = fallbacks, symbol = symbol)); } Ok(()) } /// Creates a `missing_fn_panic` function. /// /// This function is the mock that is called if the real function could not be called. fn
<W>(ns: &Ns, dest: &mut W) -> io::Result<()> where W: io::Write { writeln!(dest, "#[inline(never)] fn missing_fn_panic() ->! {{ panic!(\"{ns} function was not loaded\") }} ", ns = ns) } /// Creates the `load_with` function. /// /// The function calls `load_with` in each module created by `write_fn_mods`. fn write_load_fn<W>(registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write { try!(writeln!(dest, " /// Load each OpenGL symbol using a custom load function. This allows for the /// use of functions like `glfwGetProcAddress` or `SDL_GL_GetProcAddress`. /// ~~~ignore /// gl::load_with(|s| glfw.get_proc_address(s)); /// ~~~ #[allow(dead_code)] pub fn load_with<F>(mut loadfn: F) where F: FnMut(&str) -> *const __gl_imports::libc::c_void {{ ")); for c in registry.cmd_iter() { try!(writeln!(dest, "{cmd_name}::load_with(|s| loadfn(s));", cmd_name = &c.proto.ident[..])); } writeln!(dest, " }} /// Load each OpenGL symbol using a custom load function. /// /// ~~~ignore /// gl::load(&glfw); /// ~~~ #[allow(dead_code)] pub fn load<T: __gl_imports::gl_common::GlFunctionsSource>(loader: &T) {{ load_with(|name| loader.get_proc_addr(name)); }} ") }
write_panicking_fns
identifier_name
serial.rs
//! Serde integration support. use std::fmt; use std::marker::PhantomData; use serde::de::{Error, Unexpected, Visitor}; use serde::*; fn i64_to_u64<'d, V: Visitor<'d>, E: Error>(v: V, n: i64) -> Result<V::Value, E> { if n >= 0 { v.visit_u64(n as u64) } else { Err(E::invalid_value(Unexpected::Signed(n), &v)) } } /// Ignore deserialization errors and revert to default. pub fn ignore_errors<'d, T: Deserialize<'d> + Default, D: Deserializer<'d>>( d: D, ) -> Result<T, D::Error> { use serde_json::Value; let v = Value::deserialize(d)?; Ok(T::deserialize(v).ok().unwrap_or_default()) } /// Deserialize a maybe-string ID into a u64. pub fn deserialize_id<'d, D: Deserializer<'d>>(d: D) -> Result<u64, D::Error> { struct IdVisitor; impl<'d> Visitor<'d> for IdVisitor { type Value = u64; fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "a u64 or parseable string") } fn visit_i64<E: Error>(self, v: i64) -> Result<u64, E> { i64_to_u64(self, v) } fn visit_u64<E: Error>(self, v: u64) -> Result<u64, E> { Ok(v) } fn visit_str<E: Error>(self, v: &str) -> Result<u64, E> { v.parse::<u64>() .map_err(|_| E::invalid_value(Unexpected::Str(v), &self)) } } d.deserialize_any(IdVisitor) } /// Deserialize a maybe-string discriminator into a u16. /// Also enforces 0 <= N <= 9999. #[allow(unused_comparisons)] pub fn
<'d, D: Deserializer<'d>>(d: D) -> Result<Option<u16>, D::Error> { macro_rules! check { ($self:ident, $v:ident, $wrong:expr) => { if $v >= 0 && $v <= 9999 { Ok(Some($v as u16)) } else { Err(E::invalid_value($wrong, &$self)) } }; } struct DiscrimVisitor; impl<'d> Visitor<'d> for DiscrimVisitor { type Value = Option<u16>; fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "a u16 in [0, 9999] or parseable string") } fn visit_i64<E: Error>(self, v: i64) -> Result<Self::Value, E> { check!(self, v, Unexpected::Signed(v)) } fn visit_u64<E: Error>(self, v: u64) -> Result<Self::Value, E> { check!(self, v, Unexpected::Unsigned(v)) } fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> { v.parse::<u16>() .map_err(|_| E::invalid_value(Unexpected::Str(v), &self)) .and_then(|v| self.visit_u16(v)) } } d.deserialize_any(DiscrimVisitor) } pub fn deserialize_discrim<'d, D: Deserializer<'d>>(d: D) -> Result<u16, D::Error> { match deserialize_discrim_opt(d) { Ok(Some(result)) => Ok(result), Err(e) => Err(e), Ok(None) => Err(D::Error::missing_field("discriminator")), } } /// Deserialize a single-field struct like a newtype struct. macro_rules! serial_single_field { ($typ:ident as $field:ident: $inner:path) => { impl ::serde::Serialize for $typ { fn serialize<S: ::serde::ser::Serializer>( &self, s: S, ) -> ::std::result::Result<S::Ok, S::Error> { self.$field.serialize(s) } } impl<'d> ::serde::Deserialize<'d> for $typ { fn deserialize<D: ::serde::de::Deserializer<'d>>( d: D, ) -> ::std::result::Result<$typ, D::Error> { <$inner as ::serde::de::Deserialize>::deserialize(d).map(|v| $typ { $field: v }) } } }; } /// Special support for the oddly complex `ReactionEmoji`. pub mod reaction_emoji { use super::*; use model::{EmojiId, ReactionEmoji}; #[derive(Serialize)] struct EmojiSer<'s> { name: &'s str, id: Option<EmojiId>, } #[derive(Deserialize)] struct EmojiDe { name: String, id: Option<EmojiId>, } pub fn serialize<S: Serializer>(v: &ReactionEmoji, s: S) -> Result<S::Ok, S::Error> { (match *v { ReactionEmoji::Unicode(ref name) => EmojiSer { name: name, id: None, }, ReactionEmoji::Custom { ref name, id } => EmojiSer { name: name, id: Some(id), }, }) .serialize(s) } pub fn deserialize<'d, D: Deserializer<'d>>(d: D) -> Result<ReactionEmoji, D::Error> { Ok(match EmojiDe::deserialize(d)? { EmojiDe { name, id: None } => ReactionEmoji::Unicode(name), EmojiDe { name, id: Some(id) } => ReactionEmoji::Custom { name: name, id: id }, }) } } /// Support for named enums. pub mod named { use super::*; pub trait NamedEnum: Sized { fn name(&self) -> &'static str; fn from_name(name: &str) -> Option<Self>; fn typename() -> &'static str; } pub fn serialize<T: NamedEnum, S: Serializer>(v: &T, s: S) -> Result<S::Ok, S::Error> { v.name().serialize(s) } pub fn deserialize<'d, T: NamedEnum, D: Deserializer<'d>>(d: D) -> Result<T, D::Error> { struct NameVisitor<T>(PhantomData<T>); impl<'d, T: NamedEnum> Visitor<'d> for NameVisitor<T> { type Value = T; fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "a valid {} name", T::typename()) } fn visit_str<E: Error>(self, v: &str) -> Result<T, E> { T::from_name(v).ok_or_else(|| E::invalid_value(Unexpected::Str(v), &self)) } } d.deserialize_any(NameVisitor(PhantomData)) } } macro_rules! serial_names { ($typ:ident; $($entry:ident, $value:expr;)*) => { impl $typ { pub fn name(&self) -> &'static str { match *self { $($typ::$entry => $value,)* } } pub fn from_name(name: &str) -> Option<Self> { match name { $($value => Some($typ::$entry),)* _ => None, } } } impl ::serial::named::NamedEnum for $typ { fn name(&self) -> &'static str { self.name() } fn from_name(name: &str) -> Option<Self> { Self::from_name(name) } fn typename() -> &'static str { stringify!($typ) } } } } /// Support for numeric enums. pub mod numeric { use super::*; pub trait NumericEnum: Sized { fn num(&self) -> u64; fn from_num(num: u64) -> Option<Self>; fn typename() -> &'static str; } pub fn serialize<T: NumericEnum, S: Serializer>(v: &T, s: S) -> Result<S::Ok, S::Error> { v.num().serialize(s) } pub fn deserialize<'d, T: NumericEnum, D: Deserializer<'d>>(d: D) -> Result<T, D::Error> { struct NumVisitor<T>(PhantomData<T>); impl<'d, T: NumericEnum> Visitor<'d> for NumVisitor<T> { type Value = T; fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "a valid {} number", T::typename()) } fn visit_i64<E: Error>(self, v: i64) -> Result<T, E> { i64_to_u64(self, v) } fn visit_u64<E: Error>(self, v: u64) -> Result<T, E> { T::from_num(v).ok_or_else(|| E::invalid_value(Unexpected::Unsigned(v), &self)) } } d.deserialize_any(NumVisitor(PhantomData)) } } macro_rules! serial_numbers { ($typ:ident; $($entry:ident, $value:expr;)*) => { impl $typ { pub fn num(&self) -> u64 { match *self { $($typ::$entry => $value,)* } } pub fn from_num(num: u64) -> Option<Self> { match num { $($value => Some($typ::$entry),)* _ => None, } } } impl ::serial::numeric::NumericEnum for $typ { fn num(&self) -> u64 { self.num() } fn from_num(num: u64) -> Option<Self> { Self::from_num(num) } fn typename() -> &'static str { stringify!($typ) } } } } /// Support for using "named" or "numeric" as the default ser/de impl. macro_rules! serial_use_mapping { ($typ:ident, $which:ident) => { impl ::serde::Serialize for $typ { #[inline] fn serialize<S: ::serde::ser::Serializer>( &self, s: S, ) -> ::std::result::Result<S::Ok, S::Error> { ::serial::$which::serialize(self, s) } } impl<'d> ::serde::Deserialize<'d> for $typ { #[inline] fn deserialize<D: ::serde::de::Deserializer<'d>>( d: D, ) -> ::std::result::Result<$typ, D::Error> { ::serial::$which::deserialize(d) } } }; }
deserialize_discrim_opt
identifier_name
serial.rs
//! Serde integration support. use std::fmt; use std::marker::PhantomData; use serde::de::{Error, Unexpected, Visitor}; use serde::*; fn i64_to_u64<'d, V: Visitor<'d>, E: Error>(v: V, n: i64) -> Result<V::Value, E> { if n >= 0 { v.visit_u64(n as u64) } else { Err(E::invalid_value(Unexpected::Signed(n), &v)) } } /// Ignore deserialization errors and revert to default. pub fn ignore_errors<'d, T: Deserialize<'d> + Default, D: Deserializer<'d>>( d: D, ) -> Result<T, D::Error> { use serde_json::Value; let v = Value::deserialize(d)?; Ok(T::deserialize(v).ok().unwrap_or_default()) } /// Deserialize a maybe-string ID into a u64. pub fn deserialize_id<'d, D: Deserializer<'d>>(d: D) -> Result<u64, D::Error> { struct IdVisitor; impl<'d> Visitor<'d> for IdVisitor { type Value = u64; fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "a u64 or parseable string") } fn visit_i64<E: Error>(self, v: i64) -> Result<u64, E> { i64_to_u64(self, v) } fn visit_u64<E: Error>(self, v: u64) -> Result<u64, E> { Ok(v) } fn visit_str<E: Error>(self, v: &str) -> Result<u64, E> { v.parse::<u64>() .map_err(|_| E::invalid_value(Unexpected::Str(v), &self)) } } d.deserialize_any(IdVisitor) } /// Deserialize a maybe-string discriminator into a u16. /// Also enforces 0 <= N <= 9999. #[allow(unused_comparisons)] pub fn deserialize_discrim_opt<'d, D: Deserializer<'d>>(d: D) -> Result<Option<u16>, D::Error> { macro_rules! check { ($self:ident, $v:ident, $wrong:expr) => { if $v >= 0 && $v <= 9999 { Ok(Some($v as u16)) } else { Err(E::invalid_value($wrong, &$self)) } }; } struct DiscrimVisitor; impl<'d> Visitor<'d> for DiscrimVisitor { type Value = Option<u16>; fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "a u16 in [0, 9999] or parseable string") } fn visit_i64<E: Error>(self, v: i64) -> Result<Self::Value, E> { check!(self, v, Unexpected::Signed(v)) } fn visit_u64<E: Error>(self, v: u64) -> Result<Self::Value, E> { check!(self, v, Unexpected::Unsigned(v)) } fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> { v.parse::<u16>() .map_err(|_| E::invalid_value(Unexpected::Str(v), &self)) .and_then(|v| self.visit_u16(v)) } } d.deserialize_any(DiscrimVisitor) } pub fn deserialize_discrim<'d, D: Deserializer<'d>>(d: D) -> Result<u16, D::Error> { match deserialize_discrim_opt(d) { Ok(Some(result)) => Ok(result), Err(e) => Err(e), Ok(None) => Err(D::Error::missing_field("discriminator")), } } /// Deserialize a single-field struct like a newtype struct. macro_rules! serial_single_field { ($typ:ident as $field:ident: $inner:path) => { impl ::serde::Serialize for $typ { fn serialize<S: ::serde::ser::Serializer>( &self, s: S, ) -> ::std::result::Result<S::Ok, S::Error> { self.$field.serialize(s) } } impl<'d> ::serde::Deserialize<'d> for $typ { fn deserialize<D: ::serde::de::Deserializer<'d>>( d: D, ) -> ::std::result::Result<$typ, D::Error> { <$inner as ::serde::de::Deserialize>::deserialize(d).map(|v| $typ { $field: v }) } } }; } /// Special support for the oddly complex `ReactionEmoji`. pub mod reaction_emoji { use super::*; use model::{EmojiId, ReactionEmoji}; #[derive(Serialize)] struct EmojiSer<'s> { name: &'s str, id: Option<EmojiId>, } #[derive(Deserialize)] struct EmojiDe { name: String, id: Option<EmojiId>, } pub fn serialize<S: Serializer>(v: &ReactionEmoji, s: S) -> Result<S::Ok, S::Error> { (match *v { ReactionEmoji::Unicode(ref name) => EmojiSer { name: name, id: None, }, ReactionEmoji::Custom { ref name, id } => EmojiSer { name: name, id: Some(id), }, }) .serialize(s) } pub fn deserialize<'d, D: Deserializer<'d>>(d: D) -> Result<ReactionEmoji, D::Error> { Ok(match EmojiDe::deserialize(d)? { EmojiDe { name, id: None } => ReactionEmoji::Unicode(name), EmojiDe { name, id: Some(id) } => ReactionEmoji::Custom { name: name, id: id }, }) } } /// Support for named enums. pub mod named { use super::*; pub trait NamedEnum: Sized { fn name(&self) -> &'static str; fn from_name(name: &str) -> Option<Self>; fn typename() -> &'static str; } pub fn serialize<T: NamedEnum, S: Serializer>(v: &T, s: S) -> Result<S::Ok, S::Error>
pub fn deserialize<'d, T: NamedEnum, D: Deserializer<'d>>(d: D) -> Result<T, D::Error> { struct NameVisitor<T>(PhantomData<T>); impl<'d, T: NamedEnum> Visitor<'d> for NameVisitor<T> { type Value = T; fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "a valid {} name", T::typename()) } fn visit_str<E: Error>(self, v: &str) -> Result<T, E> { T::from_name(v).ok_or_else(|| E::invalid_value(Unexpected::Str(v), &self)) } } d.deserialize_any(NameVisitor(PhantomData)) } } macro_rules! serial_names { ($typ:ident; $($entry:ident, $value:expr;)*) => { impl $typ { pub fn name(&self) -> &'static str { match *self { $($typ::$entry => $value,)* } } pub fn from_name(name: &str) -> Option<Self> { match name { $($value => Some($typ::$entry),)* _ => None, } } } impl ::serial::named::NamedEnum for $typ { fn name(&self) -> &'static str { self.name() } fn from_name(name: &str) -> Option<Self> { Self::from_name(name) } fn typename() -> &'static str { stringify!($typ) } } } } /// Support for numeric enums. pub mod numeric { use super::*; pub trait NumericEnum: Sized { fn num(&self) -> u64; fn from_num(num: u64) -> Option<Self>; fn typename() -> &'static str; } pub fn serialize<T: NumericEnum, S: Serializer>(v: &T, s: S) -> Result<S::Ok, S::Error> { v.num().serialize(s) } pub fn deserialize<'d, T: NumericEnum, D: Deserializer<'d>>(d: D) -> Result<T, D::Error> { struct NumVisitor<T>(PhantomData<T>); impl<'d, T: NumericEnum> Visitor<'d> for NumVisitor<T> { type Value = T; fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "a valid {} number", T::typename()) } fn visit_i64<E: Error>(self, v: i64) -> Result<T, E> { i64_to_u64(self, v) } fn visit_u64<E: Error>(self, v: u64) -> Result<T, E> { T::from_num(v).ok_or_else(|| E::invalid_value(Unexpected::Unsigned(v), &self)) } } d.deserialize_any(NumVisitor(PhantomData)) } } macro_rules! serial_numbers { ($typ:ident; $($entry:ident, $value:expr;)*) => { impl $typ { pub fn num(&self) -> u64 { match *self { $($typ::$entry => $value,)* } } pub fn from_num(num: u64) -> Option<Self> { match num { $($value => Some($typ::$entry),)* _ => None, } } } impl ::serial::numeric::NumericEnum for $typ { fn num(&self) -> u64 { self.num() } fn from_num(num: u64) -> Option<Self> { Self::from_num(num) } fn typename() -> &'static str { stringify!($typ) } } } } /// Support for using "named" or "numeric" as the default ser/de impl. macro_rules! serial_use_mapping { ($typ:ident, $which:ident) => { impl ::serde::Serialize for $typ { #[inline] fn serialize<S: ::serde::ser::Serializer>( &self, s: S, ) -> ::std::result::Result<S::Ok, S::Error> { ::serial::$which::serialize(self, s) } } impl<'d> ::serde::Deserialize<'d> for $typ { #[inline] fn deserialize<D: ::serde::de::Deserializer<'d>>( d: D, ) -> ::std::result::Result<$typ, D::Error> { ::serial::$which::deserialize(d) } } }; }
{ v.name().serialize(s) }
identifier_body
serial.rs
//! Serde integration support. use std::fmt; use std::marker::PhantomData; use serde::de::{Error, Unexpected, Visitor}; use serde::*; fn i64_to_u64<'d, V: Visitor<'d>, E: Error>(v: V, n: i64) -> Result<V::Value, E> { if n >= 0 { v.visit_u64(n as u64) } else { Err(E::invalid_value(Unexpected::Signed(n), &v)) } } /// Ignore deserialization errors and revert to default. pub fn ignore_errors<'d, T: Deserialize<'d> + Default, D: Deserializer<'d>>( d: D, ) -> Result<T, D::Error> { use serde_json::Value; let v = Value::deserialize(d)?; Ok(T::deserialize(v).ok().unwrap_or_default()) } /// Deserialize a maybe-string ID into a u64. pub fn deserialize_id<'d, D: Deserializer<'d>>(d: D) -> Result<u64, D::Error> { struct IdVisitor; impl<'d> Visitor<'d> for IdVisitor { type Value = u64; fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "a u64 or parseable string") } fn visit_i64<E: Error>(self, v: i64) -> Result<u64, E> { i64_to_u64(self, v) } fn visit_u64<E: Error>(self, v: u64) -> Result<u64, E> { Ok(v) } fn visit_str<E: Error>(self, v: &str) -> Result<u64, E> { v.parse::<u64>() .map_err(|_| E::invalid_value(Unexpected::Str(v), &self)) } } d.deserialize_any(IdVisitor) } /// Deserialize a maybe-string discriminator into a u16. /// Also enforces 0 <= N <= 9999. #[allow(unused_comparisons)] pub fn deserialize_discrim_opt<'d, D: Deserializer<'d>>(d: D) -> Result<Option<u16>, D::Error> { macro_rules! check { ($self:ident, $v:ident, $wrong:expr) => { if $v >= 0 && $v <= 9999 { Ok(Some($v as u16)) } else { Err(E::invalid_value($wrong, &$self)) } }; } struct DiscrimVisitor; impl<'d> Visitor<'d> for DiscrimVisitor { type Value = Option<u16>; fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "a u16 in [0, 9999] or parseable string") } fn visit_i64<E: Error>(self, v: i64) -> Result<Self::Value, E> { check!(self, v, Unexpected::Signed(v)) } fn visit_u64<E: Error>(self, v: u64) -> Result<Self::Value, E> { check!(self, v, Unexpected::Unsigned(v)) } fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> { v.parse::<u16>() .map_err(|_| E::invalid_value(Unexpected::Str(v), &self)) .and_then(|v| self.visit_u16(v)) } } d.deserialize_any(DiscrimVisitor) } pub fn deserialize_discrim<'d, D: Deserializer<'d>>(d: D) -> Result<u16, D::Error> { match deserialize_discrim_opt(d) { Ok(Some(result)) => Ok(result), Err(e) => Err(e), Ok(None) => Err(D::Error::missing_field("discriminator")), } } /// Deserialize a single-field struct like a newtype struct. macro_rules! serial_single_field { ($typ:ident as $field:ident: $inner:path) => { impl ::serde::Serialize for $typ { fn serialize<S: ::serde::ser::Serializer>( &self, s: S, ) -> ::std::result::Result<S::Ok, S::Error> { self.$field.serialize(s) } } impl<'d> ::serde::Deserialize<'d> for $typ { fn deserialize<D: ::serde::de::Deserializer<'d>>( d: D, ) -> ::std::result::Result<$typ, D::Error> { <$inner as ::serde::de::Deserialize>::deserialize(d).map(|v| $typ { $field: v }) } } }; } /// Special support for the oddly complex `ReactionEmoji`. pub mod reaction_emoji { use super::*; use model::{EmojiId, ReactionEmoji}; #[derive(Serialize)] struct EmojiSer<'s> { name: &'s str, id: Option<EmojiId>, } #[derive(Deserialize)] struct EmojiDe { name: String, id: Option<EmojiId>, } pub fn serialize<S: Serializer>(v: &ReactionEmoji, s: S) -> Result<S::Ok, S::Error> { (match *v { ReactionEmoji::Unicode(ref name) => EmojiSer { name: name, id: None, }, ReactionEmoji::Custom { ref name, id } => EmojiSer { name: name, id: Some(id), }, }) .serialize(s) } pub fn deserialize<'d, D: Deserializer<'d>>(d: D) -> Result<ReactionEmoji, D::Error> { Ok(match EmojiDe::deserialize(d)? { EmojiDe { name, id: None } => ReactionEmoji::Unicode(name), EmojiDe { name, id: Some(id) } => ReactionEmoji::Custom { name: name, id: id }, }) } } /// Support for named enums. pub mod named { use super::*; pub trait NamedEnum: Sized { fn name(&self) -> &'static str; fn from_name(name: &str) -> Option<Self>; fn typename() -> &'static str; } pub fn serialize<T: NamedEnum, S: Serializer>(v: &T, s: S) -> Result<S::Ok, S::Error> { v.name().serialize(s) } pub fn deserialize<'d, T: NamedEnum, D: Deserializer<'d>>(d: D) -> Result<T, D::Error> { struct NameVisitor<T>(PhantomData<T>); impl<'d, T: NamedEnum> Visitor<'d> for NameVisitor<T> { type Value = T; fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "a valid {} name", T::typename()) } fn visit_str<E: Error>(self, v: &str) -> Result<T, E> { T::from_name(v).ok_or_else(|| E::invalid_value(Unexpected::Str(v), &self)) } } d.deserialize_any(NameVisitor(PhantomData)) } } macro_rules! serial_names { ($typ:ident; $($entry:ident, $value:expr;)*) => { impl $typ { pub fn name(&self) -> &'static str { match *self { $($typ::$entry => $value,)* } } pub fn from_name(name: &str) -> Option<Self> { match name { $($value => Some($typ::$entry),)* _ => None, } } } impl ::serial::named::NamedEnum for $typ { fn name(&self) -> &'static str { self.name() }
fn from_name(name: &str) -> Option<Self> { Self::from_name(name) } fn typename() -> &'static str { stringify!($typ) } } } } /// Support for numeric enums. pub mod numeric { use super::*; pub trait NumericEnum: Sized { fn num(&self) -> u64; fn from_num(num: u64) -> Option<Self>; fn typename() -> &'static str; } pub fn serialize<T: NumericEnum, S: Serializer>(v: &T, s: S) -> Result<S::Ok, S::Error> { v.num().serialize(s) } pub fn deserialize<'d, T: NumericEnum, D: Deserializer<'d>>(d: D) -> Result<T, D::Error> { struct NumVisitor<T>(PhantomData<T>); impl<'d, T: NumericEnum> Visitor<'d> for NumVisitor<T> { type Value = T; fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "a valid {} number", T::typename()) } fn visit_i64<E: Error>(self, v: i64) -> Result<T, E> { i64_to_u64(self, v) } fn visit_u64<E: Error>(self, v: u64) -> Result<T, E> { T::from_num(v).ok_or_else(|| E::invalid_value(Unexpected::Unsigned(v), &self)) } } d.deserialize_any(NumVisitor(PhantomData)) } } macro_rules! serial_numbers { ($typ:ident; $($entry:ident, $value:expr;)*) => { impl $typ { pub fn num(&self) -> u64 { match *self { $($typ::$entry => $value,)* } } pub fn from_num(num: u64) -> Option<Self> { match num { $($value => Some($typ::$entry),)* _ => None, } } } impl ::serial::numeric::NumericEnum for $typ { fn num(&self) -> u64 { self.num() } fn from_num(num: u64) -> Option<Self> { Self::from_num(num) } fn typename() -> &'static str { stringify!($typ) } } } } /// Support for using "named" or "numeric" as the default ser/de impl. macro_rules! serial_use_mapping { ($typ:ident, $which:ident) => { impl ::serde::Serialize for $typ { #[inline] fn serialize<S: ::serde::ser::Serializer>( &self, s: S, ) -> ::std::result::Result<S::Ok, S::Error> { ::serial::$which::serialize(self, s) } } impl<'d> ::serde::Deserialize<'d> for $typ { #[inline] fn deserialize<D: ::serde::de::Deserializer<'d>>( d: D, ) -> ::std::result::Result<$typ, D::Error> { ::serial::$which::deserialize(d) } } }; }
random_line_split
handleapi.rs
// Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms. //! handleapi include file use shared::minwindef::{BOOL, DWORD, LPDWORD, LPHANDLE}; use um::winnt::HANDLE; pub const INVALID_HANDLE_VALUE: HANDLE = -1isize as HANDLE; extern "system" { pub fn CloseHandle( hObject: HANDLE, ) -> BOOL; pub fn DuplicateHandle( hSourceProcessHandle: HANDLE, hSourceHandle: HANDLE, hTargetProcessHandle: HANDLE, lpTargetHandle: LPHANDLE, dwDesiredAccess: DWORD, bInheritHandle: BOOL, dwOptions: DWORD, ) -> BOOL; pub fn CompareObjectHandles( hFirstObjectHandle: HANDLE, hSecondObjectHandle: HANDLE, ) -> BOOL;
pub fn GetHandleInformation( hObject: HANDLE, lpdwFlags: LPDWORD, ) -> BOOL; pub fn SetHandleInformation( hObject: HANDLE, dwMask: DWORD, dwFlags: DWORD, ) -> BOOL; }
random_line_split
color_chooser_dialog.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use FFIWidget; use cast::{GTK_WINDOW}; use glib::translate::ToGlibPtr; struct_Widget!(ColorChooserDialog); impl ColorChooserDialog {
None => ::std::ptr::null_mut() } ) }; if tmp_pointer.is_null() { None } else { Some(::FFIWidget::wrap_widget(tmp_pointer)) } } } impl_drop!(ColorChooserDialog); impl_TraitWidget!(ColorChooserDialog); impl ::ContainerTrait for ColorChooserDialog {} impl ::BinTrait for ColorChooserDialog {} impl ::WindowTrait for ColorChooserDialog {} impl ::DialogTrait for ColorChooserDialog {} impl ::ColorChooserTrait for ColorChooserDialog {}
pub fn new(title: &str, parent: Option<&::Window>) -> Option<ColorChooserDialog> { let tmp_pointer = unsafe { ffi::gtk_color_chooser_dialog_new(title.to_glib_none().0, match parent { Some(ref p) => GTK_WINDOW(p.unwrap_widget()),
random_line_split
color_chooser_dialog.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use FFIWidget; use cast::{GTK_WINDOW}; use glib::translate::ToGlibPtr; struct_Widget!(ColorChooserDialog); impl ColorChooserDialog { pub fn new(title: &str, parent: Option<&::Window>) -> Option<ColorChooserDialog>
} impl_drop!(ColorChooserDialog); impl_TraitWidget!(ColorChooserDialog); impl ::ContainerTrait for ColorChooserDialog {} impl ::BinTrait for ColorChooserDialog {} impl ::WindowTrait for ColorChooserDialog {} impl ::DialogTrait for ColorChooserDialog {} impl ::ColorChooserTrait for ColorChooserDialog {}
{ let tmp_pointer = unsafe { ffi::gtk_color_chooser_dialog_new(title.to_glib_none().0, match parent { Some(ref p) => GTK_WINDOW(p.unwrap_widget()), None => ::std::ptr::null_mut() } ) }; if tmp_pointer.is_null() { None } else { Some(::FFIWidget::wrap_widget(tmp_pointer)) } }
identifier_body
color_chooser_dialog.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use FFIWidget; use cast::{GTK_WINDOW}; use glib::translate::ToGlibPtr; struct_Widget!(ColorChooserDialog); impl ColorChooserDialog { pub fn new(title: &str, parent: Option<&::Window>) -> Option<ColorChooserDialog> { let tmp_pointer = unsafe { ffi::gtk_color_chooser_dialog_new(title.to_glib_none().0, match parent { Some(ref p) => GTK_WINDOW(p.unwrap_widget()), None => ::std::ptr::null_mut() } ) }; if tmp_pointer.is_null()
else { Some(::FFIWidget::wrap_widget(tmp_pointer)) } } } impl_drop!(ColorChooserDialog); impl_TraitWidget!(ColorChooserDialog); impl ::ContainerTrait for ColorChooserDialog {} impl ::BinTrait for ColorChooserDialog {} impl ::WindowTrait for ColorChooserDialog {} impl ::DialogTrait for ColorChooserDialog {} impl ::ColorChooserTrait for ColorChooserDialog {}
{ None }
conditional_block
color_chooser_dialog.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use FFIWidget; use cast::{GTK_WINDOW}; use glib::translate::ToGlibPtr; struct_Widget!(ColorChooserDialog); impl ColorChooserDialog { pub fn
(title: &str, parent: Option<&::Window>) -> Option<ColorChooserDialog> { let tmp_pointer = unsafe { ffi::gtk_color_chooser_dialog_new(title.to_glib_none().0, match parent { Some(ref p) => GTK_WINDOW(p.unwrap_widget()), None => ::std::ptr::null_mut() } ) }; if tmp_pointer.is_null() { None } else { Some(::FFIWidget::wrap_widget(tmp_pointer)) } } } impl_drop!(ColorChooserDialog); impl_TraitWidget!(ColorChooserDialog); impl ::ContainerTrait for ColorChooserDialog {} impl ::BinTrait for ColorChooserDialog {} impl ::WindowTrait for ColorChooserDialog {} impl ::DialogTrait for ColorChooserDialog {} impl ::ColorChooserTrait for ColorChooserDialog {}
new
identifier_name
audio.rs
use super::error::Error; use ao; use earwax::{Earwax, Timestamp, LogLevel}; use std::sync::{Once, ONCE_INIT}; static START: Once = ONCE_INIT; /// Type for audio streaming audio that hides the details of earwax and ao-rs handling. pub struct Audio { earwax: Earwax, driver: ao::Driver, format: ao::Format,
device: ao::Device, } impl Audio { /// Tries to initialize a new stream for the given URL. pub fn new(url: &str) -> Result<Self, Error> { // #[cfg(not(debug_assertions))] START.call_once(|| { Earwax::set_log_level(LogLevel::Error); }); let earwax = try!(Earwax::new(url)); let driver = try!(ao::Driver::new()); let format = ao::Format::new(); let device = try!(ao::Device::new(&driver, &format, None)); Ok(Audio { earwax: earwax, driver: driver, format: format, device: device, }) } /// Plays the next chunk of the stream to the default audio device. /// # Returns /// If playback was successful (at getting next stream chunk), the value returned /// is a tuple where the first element is the current timestamp, and the second /// element is the total timestamp. pub fn play(&mut self) -> Result<(Timestamp, Timestamp), ()> { let duration = self.earwax.info().duration; if let Some(chunk) = self.earwax.spit() { self.device.play(chunk.data); Ok((chunk.time, duration)) } else { Err(()) } } /// Plays all the chunks remaining in the stream to the default audio the device. pub fn play_all(&mut self) { while let Some(chunk) = self.earwax.spit() { self.device.play(chunk.data); } } }
random_line_split
audio.rs
use super::error::Error; use ao; use earwax::{Earwax, Timestamp, LogLevel}; use std::sync::{Once, ONCE_INIT}; static START: Once = ONCE_INIT; /// Type for audio streaming audio that hides the details of earwax and ao-rs handling. pub struct Audio { earwax: Earwax, driver: ao::Driver, format: ao::Format, device: ao::Device, } impl Audio { /// Tries to initialize a new stream for the given URL. pub fn new(url: &str) -> Result<Self, Error>
/// Plays the next chunk of the stream to the default audio device. /// # Returns /// If playback was successful (at getting next stream chunk), the value returned /// is a tuple where the first element is the current timestamp, and the second /// element is the total timestamp. pub fn play(&mut self) -> Result<(Timestamp, Timestamp), ()> { let duration = self.earwax.info().duration; if let Some(chunk) = self.earwax.spit() { self.device.play(chunk.data); Ok((chunk.time, duration)) } else { Err(()) } } /// Plays all the chunks remaining in the stream to the default audio the device. pub fn play_all(&mut self) { while let Some(chunk) = self.earwax.spit() { self.device.play(chunk.data); } } }
{ // #[cfg(not(debug_assertions))] START.call_once(|| { Earwax::set_log_level(LogLevel::Error); }); let earwax = try!(Earwax::new(url)); let driver = try!(ao::Driver::new()); let format = ao::Format::new(); let device = try!(ao::Device::new(&driver, &format, None)); Ok(Audio { earwax: earwax, driver: driver, format: format, device: device, }) }
identifier_body
audio.rs
use super::error::Error; use ao; use earwax::{Earwax, Timestamp, LogLevel}; use std::sync::{Once, ONCE_INIT}; static START: Once = ONCE_INIT; /// Type for audio streaming audio that hides the details of earwax and ao-rs handling. pub struct Audio { earwax: Earwax, driver: ao::Driver, format: ao::Format, device: ao::Device, } impl Audio { /// Tries to initialize a new stream for the given URL. pub fn new(url: &str) -> Result<Self, Error> { // #[cfg(not(debug_assertions))] START.call_once(|| { Earwax::set_log_level(LogLevel::Error); }); let earwax = try!(Earwax::new(url)); let driver = try!(ao::Driver::new()); let format = ao::Format::new(); let device = try!(ao::Device::new(&driver, &format, None)); Ok(Audio { earwax: earwax, driver: driver, format: format, device: device, }) } /// Plays the next chunk of the stream to the default audio device. /// # Returns /// If playback was successful (at getting next stream chunk), the value returned /// is a tuple where the first element is the current timestamp, and the second /// element is the total timestamp. pub fn play(&mut self) -> Result<(Timestamp, Timestamp), ()> { let duration = self.earwax.info().duration; if let Some(chunk) = self.earwax.spit()
else { Err(()) } } /// Plays all the chunks remaining in the stream to the default audio the device. pub fn play_all(&mut self) { while let Some(chunk) = self.earwax.spit() { self.device.play(chunk.data); } } }
{ self.device.play(chunk.data); Ok((chunk.time, duration)) }
conditional_block
audio.rs
use super::error::Error; use ao; use earwax::{Earwax, Timestamp, LogLevel}; use std::sync::{Once, ONCE_INIT}; static START: Once = ONCE_INIT; /// Type for audio streaming audio that hides the details of earwax and ao-rs handling. pub struct Audio { earwax: Earwax, driver: ao::Driver, format: ao::Format, device: ao::Device, } impl Audio { /// Tries to initialize a new stream for the given URL. pub fn
(url: &str) -> Result<Self, Error> { // #[cfg(not(debug_assertions))] START.call_once(|| { Earwax::set_log_level(LogLevel::Error); }); let earwax = try!(Earwax::new(url)); let driver = try!(ao::Driver::new()); let format = ao::Format::new(); let device = try!(ao::Device::new(&driver, &format, None)); Ok(Audio { earwax: earwax, driver: driver, format: format, device: device, }) } /// Plays the next chunk of the stream to the default audio device. /// # Returns /// If playback was successful (at getting next stream chunk), the value returned /// is a tuple where the first element is the current timestamp, and the second /// element is the total timestamp. pub fn play(&mut self) -> Result<(Timestamp, Timestamp), ()> { let duration = self.earwax.info().duration; if let Some(chunk) = self.earwax.spit() { self.device.play(chunk.data); Ok((chunk.time, duration)) } else { Err(()) } } /// Plays all the chunks remaining in the stream to the default audio the device. pub fn play_all(&mut self) { while let Some(chunk) = self.earwax.spit() { self.device.play(chunk.data); } } }
new
identifier_name
cssstylesheet.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding; use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding::CSSStyleSheetMethods; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; use crate::dom::bindings::str::DOMString; use crate::dom::cssrulelist::{CSSRuleList, RulesSource}; use crate::dom::element::Element; use crate::dom::stylesheet::StyleSheet; use crate::dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use std::cell::Cell; use style::shared_lock::SharedRwLock; use style::stylesheets::Stylesheet as StyleStyleSheet; #[dom_struct] pub struct CSSStyleSheet { stylesheet: StyleSheet, owner: Dom<Element>, rulelist: MutNullableDom<CSSRuleList>, #[ignore_malloc_size_of = "Arc"] style_stylesheet: Arc<StyleStyleSheet>, origin_clean: Cell<bool>, } impl CSSStyleSheet { fn new_inherited( owner: &Element, type_: DOMString, href: Option<DOMString>, title: Option<DOMString>, stylesheet: Arc<StyleStyleSheet>, ) -> CSSStyleSheet { CSSStyleSheet { stylesheet: StyleSheet::new_inherited(type_, href, title), owner: Dom::from_ref(owner), rulelist: MutNullableDom::new(None), style_stylesheet: stylesheet, origin_clean: Cell::new(true), } } #[allow(unrooted_must_root)] pub fn new( window: &Window, owner: &Element, type_: DOMString, href: Option<DOMString>, title: Option<DOMString>, stylesheet: Arc<StyleStyleSheet>, ) -> DomRoot<CSSStyleSheet> { reflect_dom_object( Box::new(CSSStyleSheet::new_inherited( owner, type_, href, title, stylesheet, )), window, CSSStyleSheetBinding::Wrap, ) } fn rulelist(&self) -> DomRoot<CSSRuleList> { self.rulelist.or_init(|| { let rules = self.style_stylesheet.contents.rules.clone(); CSSRuleList::new(self.global().as_window(), self, RulesSource::Rules(rules)) }) } pub fn disabled(&self) -> bool { self.style_stylesheet.disabled() } pub fn set_disabled(&self, disabled: bool) { if self.style_stylesheet.set_disabled(disabled) { self.global() .as_window() .Document() .invalidate_stylesheets(); } } pub fn shared_lock(&self) -> &SharedRwLock { &self.style_stylesheet.shared_lock } pub fn style_stylesheet(&self) -> &StyleStyleSheet { &self.style_stylesheet } pub fn set_origin_clean(&self, origin_clean: bool) { self.origin_clean.set(origin_clean); } } impl CSSStyleSheetMethods for CSSStyleSheet { // https://drafts.csswg.org/cssom/#dom-cssstylesheet-cssrules fn GetCssRules(&self) -> Fallible<DomRoot<CSSRuleList>> { if!self.origin_clean.get()
Ok(self.rulelist()) } // https://drafts.csswg.org/cssom/#dom-cssstylesheet-insertrule fn InsertRule(&self, rule: DOMString, index: u32) -> Fallible<u32> { if!self.origin_clean.get() { return Err(Error::Security); } self.rulelist() .insert_rule(&rule, index, /* nested */ false) } // https://drafts.csswg.org/cssom/#dom-cssstylesheet-deleterule fn DeleteRule(&self, index: u32) -> ErrorResult { if!self.origin_clean.get() { return Err(Error::Security); } self.rulelist().remove_rule(index) } }
{ return Err(Error::Security); }
conditional_block
cssstylesheet.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::root::{Dom, DomRoot, MutNullableDom}; use crate::dom::bindings::str::DOMString; use crate::dom::cssrulelist::{CSSRuleList, RulesSource}; use crate::dom::element::Element; use crate::dom::stylesheet::StyleSheet; use crate::dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use std::cell::Cell; use style::shared_lock::SharedRwLock; use style::stylesheets::Stylesheet as StyleStyleSheet; #[dom_struct] pub struct CSSStyleSheet { stylesheet: StyleSheet, owner: Dom<Element>, rulelist: MutNullableDom<CSSRuleList>, #[ignore_malloc_size_of = "Arc"] style_stylesheet: Arc<StyleStyleSheet>, origin_clean: Cell<bool>, } impl CSSStyleSheet { fn new_inherited( owner: &Element, type_: DOMString, href: Option<DOMString>, title: Option<DOMString>, stylesheet: Arc<StyleStyleSheet>, ) -> CSSStyleSheet { CSSStyleSheet { stylesheet: StyleSheet::new_inherited(type_, href, title), owner: Dom::from_ref(owner), rulelist: MutNullableDom::new(None), style_stylesheet: stylesheet, origin_clean: Cell::new(true), } } #[allow(unrooted_must_root)] pub fn new( window: &Window, owner: &Element, type_: DOMString, href: Option<DOMString>, title: Option<DOMString>, stylesheet: Arc<StyleStyleSheet>, ) -> DomRoot<CSSStyleSheet> { reflect_dom_object( Box::new(CSSStyleSheet::new_inherited( owner, type_, href, title, stylesheet, )), window, CSSStyleSheetBinding::Wrap, ) } fn rulelist(&self) -> DomRoot<CSSRuleList> { self.rulelist.or_init(|| { let rules = self.style_stylesheet.contents.rules.clone(); CSSRuleList::new(self.global().as_window(), self, RulesSource::Rules(rules)) }) } pub fn disabled(&self) -> bool { self.style_stylesheet.disabled() } pub fn set_disabled(&self, disabled: bool) { if self.style_stylesheet.set_disabled(disabled) { self.global() .as_window() .Document() .invalidate_stylesheets(); } } pub fn shared_lock(&self) -> &SharedRwLock { &self.style_stylesheet.shared_lock } pub fn style_stylesheet(&self) -> &StyleStyleSheet { &self.style_stylesheet } pub fn set_origin_clean(&self, origin_clean: bool) { self.origin_clean.set(origin_clean); } } impl CSSStyleSheetMethods for CSSStyleSheet { // https://drafts.csswg.org/cssom/#dom-cssstylesheet-cssrules fn GetCssRules(&self) -> Fallible<DomRoot<CSSRuleList>> { if!self.origin_clean.get() { return Err(Error::Security); } Ok(self.rulelist()) } // https://drafts.csswg.org/cssom/#dom-cssstylesheet-insertrule fn InsertRule(&self, rule: DOMString, index: u32) -> Fallible<u32> { if!self.origin_clean.get() { return Err(Error::Security); } self.rulelist() .insert_rule(&rule, index, /* nested */ false) } // https://drafts.csswg.org/cssom/#dom-cssstylesheet-deleterule fn DeleteRule(&self, index: u32) -> ErrorResult { if!self.origin_clean.get() { return Err(Error::Security); } self.rulelist().remove_rule(index) } }
use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding; use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding::CSSStyleSheetMethods; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
random_line_split
cssstylesheet.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding; use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding::CSSStyleSheetMethods; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; use crate::dom::bindings::str::DOMString; use crate::dom::cssrulelist::{CSSRuleList, RulesSource}; use crate::dom::element::Element; use crate::dom::stylesheet::StyleSheet; use crate::dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use std::cell::Cell; use style::shared_lock::SharedRwLock; use style::stylesheets::Stylesheet as StyleStyleSheet; #[dom_struct] pub struct CSSStyleSheet { stylesheet: StyleSheet, owner: Dom<Element>, rulelist: MutNullableDom<CSSRuleList>, #[ignore_malloc_size_of = "Arc"] style_stylesheet: Arc<StyleStyleSheet>, origin_clean: Cell<bool>, } impl CSSStyleSheet { fn new_inherited( owner: &Element, type_: DOMString, href: Option<DOMString>, title: Option<DOMString>, stylesheet: Arc<StyleStyleSheet>, ) -> CSSStyleSheet { CSSStyleSheet { stylesheet: StyleSheet::new_inherited(type_, href, title), owner: Dom::from_ref(owner), rulelist: MutNullableDom::new(None), style_stylesheet: stylesheet, origin_clean: Cell::new(true), } } #[allow(unrooted_must_root)] pub fn new( window: &Window, owner: &Element, type_: DOMString, href: Option<DOMString>, title: Option<DOMString>, stylesheet: Arc<StyleStyleSheet>, ) -> DomRoot<CSSStyleSheet> { reflect_dom_object( Box::new(CSSStyleSheet::new_inherited( owner, type_, href, title, stylesheet, )), window, CSSStyleSheetBinding::Wrap, ) } fn rulelist(&self) -> DomRoot<CSSRuleList> { self.rulelist.or_init(|| { let rules = self.style_stylesheet.contents.rules.clone(); CSSRuleList::new(self.global().as_window(), self, RulesSource::Rules(rules)) }) } pub fn disabled(&self) -> bool { self.style_stylesheet.disabled() } pub fn set_disabled(&self, disabled: bool) { if self.style_stylesheet.set_disabled(disabled) { self.global() .as_window() .Document() .invalidate_stylesheets(); } } pub fn shared_lock(&self) -> &SharedRwLock { &self.style_stylesheet.shared_lock } pub fn style_stylesheet(&self) -> &StyleStyleSheet { &self.style_stylesheet } pub fn set_origin_clean(&self, origin_clean: bool) { self.origin_clean.set(origin_clean); } } impl CSSStyleSheetMethods for CSSStyleSheet { // https://drafts.csswg.org/cssom/#dom-cssstylesheet-cssrules fn
(&self) -> Fallible<DomRoot<CSSRuleList>> { if!self.origin_clean.get() { return Err(Error::Security); } Ok(self.rulelist()) } // https://drafts.csswg.org/cssom/#dom-cssstylesheet-insertrule fn InsertRule(&self, rule: DOMString, index: u32) -> Fallible<u32> { if!self.origin_clean.get() { return Err(Error::Security); } self.rulelist() .insert_rule(&rule, index, /* nested */ false) } // https://drafts.csswg.org/cssom/#dom-cssstylesheet-deleterule fn DeleteRule(&self, index: u32) -> ErrorResult { if!self.origin_clean.get() { return Err(Error::Security); } self.rulelist().remove_rule(index) } }
GetCssRules
identifier_name
cssstylesheet.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding; use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding::CSSStyleSheetMethods; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; use crate::dom::bindings::str::DOMString; use crate::dom::cssrulelist::{CSSRuleList, RulesSource}; use crate::dom::element::Element; use crate::dom::stylesheet::StyleSheet; use crate::dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use std::cell::Cell; use style::shared_lock::SharedRwLock; use style::stylesheets::Stylesheet as StyleStyleSheet; #[dom_struct] pub struct CSSStyleSheet { stylesheet: StyleSheet, owner: Dom<Element>, rulelist: MutNullableDom<CSSRuleList>, #[ignore_malloc_size_of = "Arc"] style_stylesheet: Arc<StyleStyleSheet>, origin_clean: Cell<bool>, } impl CSSStyleSheet { fn new_inherited( owner: &Element, type_: DOMString, href: Option<DOMString>, title: Option<DOMString>, stylesheet: Arc<StyleStyleSheet>, ) -> CSSStyleSheet { CSSStyleSheet { stylesheet: StyleSheet::new_inherited(type_, href, title), owner: Dom::from_ref(owner), rulelist: MutNullableDom::new(None), style_stylesheet: stylesheet, origin_clean: Cell::new(true), } } #[allow(unrooted_must_root)] pub fn new( window: &Window, owner: &Element, type_: DOMString, href: Option<DOMString>, title: Option<DOMString>, stylesheet: Arc<StyleStyleSheet>, ) -> DomRoot<CSSStyleSheet> { reflect_dom_object( Box::new(CSSStyleSheet::new_inherited( owner, type_, href, title, stylesheet, )), window, CSSStyleSheetBinding::Wrap, ) } fn rulelist(&self) -> DomRoot<CSSRuleList> { self.rulelist.or_init(|| { let rules = self.style_stylesheet.contents.rules.clone(); CSSRuleList::new(self.global().as_window(), self, RulesSource::Rules(rules)) }) } pub fn disabled(&self) -> bool { self.style_stylesheet.disabled() } pub fn set_disabled(&self, disabled: bool) { if self.style_stylesheet.set_disabled(disabled) { self.global() .as_window() .Document() .invalidate_stylesheets(); } } pub fn shared_lock(&self) -> &SharedRwLock { &self.style_stylesheet.shared_lock } pub fn style_stylesheet(&self) -> &StyleStyleSheet { &self.style_stylesheet } pub fn set_origin_clean(&self, origin_clean: bool) { self.origin_clean.set(origin_clean); } } impl CSSStyleSheetMethods for CSSStyleSheet { // https://drafts.csswg.org/cssom/#dom-cssstylesheet-cssrules fn GetCssRules(&self) -> Fallible<DomRoot<CSSRuleList>> { if!self.origin_clean.get() { return Err(Error::Security); } Ok(self.rulelist()) } // https://drafts.csswg.org/cssom/#dom-cssstylesheet-insertrule fn InsertRule(&self, rule: DOMString, index: u32) -> Fallible<u32> { if!self.origin_clean.get() { return Err(Error::Security); } self.rulelist() .insert_rule(&rule, index, /* nested */ false) } // https://drafts.csswg.org/cssom/#dom-cssstylesheet-deleterule fn DeleteRule(&self, index: u32) -> ErrorResult
}
{ if !self.origin_clean.get() { return Err(Error::Security); } self.rulelist().remove_rule(index) }
identifier_body
test_generation_xflow_to_es5.rs
extern crate env_logger; extern crate ratel; use ratel::parser;
mod common; use crate::common::load_doc; // partof: TST-artifact-generation-xflow // #[test] fn test_load_basic_page_document() { let _ = env_logger::try_init(); let xflow = load_doc::<XFlowDocument>("resource/docs/xflow/flows/branch_boolean_condition.json"); let s_es5 = xflow_to_es5::output_es5(&xflow); let s_es = xflow_to_es5::output(&xflow); let _ = parser::parse(s_es5.to_string()).expect("Must compile"); let _ = parser::parse(s_es.to_string()).expect("Must compile"); // //XXX: A little more assurance would be nice here assert_ne!(s_es, ""); // println!("JS! {}", s_es5); println!("JS LATEST! {}", s_es); }
extern crate gears; use gears::structure::xflow::*; use gears::generation::xflow_to_es5;
random_line_split
test_generation_xflow_to_es5.rs
extern crate env_logger; extern crate ratel; use ratel::parser; extern crate gears; use gears::structure::xflow::*; use gears::generation::xflow_to_es5; mod common; use crate::common::load_doc; // partof: TST-artifact-generation-xflow // #[test] fn
() { let _ = env_logger::try_init(); let xflow = load_doc::<XFlowDocument>("resource/docs/xflow/flows/branch_boolean_condition.json"); let s_es5 = xflow_to_es5::output_es5(&xflow); let s_es = xflow_to_es5::output(&xflow); let _ = parser::parse(s_es5.to_string()).expect("Must compile"); let _ = parser::parse(s_es.to_string()).expect("Must compile"); // //XXX: A little more assurance would be nice here assert_ne!(s_es, ""); // println!("JS! {}", s_es5); println!("JS LATEST! {}", s_es); }
test_load_basic_page_document
identifier_name
test_generation_xflow_to_es5.rs
extern crate env_logger; extern crate ratel; use ratel::parser; extern crate gears; use gears::structure::xflow::*; use gears::generation::xflow_to_es5; mod common; use crate::common::load_doc; // partof: TST-artifact-generation-xflow // #[test] fn test_load_basic_page_document()
{ let _ = env_logger::try_init(); let xflow = load_doc::<XFlowDocument>("resource/docs/xflow/flows/branch_boolean_condition.json"); let s_es5 = xflow_to_es5::output_es5(&xflow); let s_es = xflow_to_es5::output(&xflow); let _ = parser::parse(s_es5.to_string()).expect("Must compile"); let _ = parser::parse(s_es.to_string()).expect("Must compile"); // //XXX: A little more assurance would be nice here assert_ne!(s_es, ""); // println!("JS! {}", s_es5); println!("JS LATEST! {}", s_es); }
identifier_body
ntcc.rs
// Copyright 2014 Pierre Talbot (IRCAM) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. pub use self::ntcc::*; grammar! ntcc{ // #![debug_api] ntcc = spacing expression expression = expression2 -> (^) expression2 = sum / par / tell / next / async / rep / unless / let_in / skip_kw sum = pick_kw or? when sum_body* end_kw? sum_body = or when
par_body = oror expression tell = store_kw left_arrow constraint next = next_kw expression async = async_kw expression rep = rep_kw expression unless = unless_kw entailed_by next when = when_kw entails right_arrow expression entails = store_kw entail constraint entailed_by = constraint entail store_kw constraint = constraint_operand comparison constraint_operand constraint_operand = integer / var_ident comparison = le / neq / lt / ge / gt / eq spacing = [" \n\t"]* -> (^) let_in = let_kw var_decl in_kw expression var_decl = var_ident eq_bind var_range var_range = range / domain domain = dom_kw var_ident // max x.. 10 / min x.. max y / 0..10 range = range_bound dotdot range_bound range_bound = integer / min_bound / max_bound min_bound = min_kw var_ident max_bound = max_kw var_ident integer = ["0-9"]+ spacing -> (^) var_ident =!["0-9"] ["a-zA-Z0-9_"]+ spacing -> (^) pick_kw = "pick" spacing when_kw = "when" spacing store_kw = "store" spacing skip_kw = "skip" spacing let_kw = "let" spacing in_kw = "in" spacing dom_kw = "dom" spacing min_kw = "min" spacing max_kw = "max" spacing end_kw = "end" spacing par_kw = "par" spacing next_kw = "next" spacing async_kw = "async" spacing rep_kw = "rep" spacing unless_kw = "unless" spacing or = "|" spacing oror = "||" spacing entail = "|=" spacing lt = "<" spacing le = "<=" spacing gt = ">" spacing ge = ">=" spacing eq = "==" spacing neq = "<>" spacing right_arrow = "->" spacing left_arrow = "<-" spacing dotdot = ".." spacing eq_bind = "=" spacing }
par = par_kw oror? expression par_body* end_kw?
random_line_split
mod.rs
//! Abstracts out the APIs necessary to `Runtime` for integrating the blocking //! pool. When the `blocking` feature flag is **not** enabled, these APIs are //! shells. This isolates the complexity of dealing with conditional //! compilation. mod pool; pub(crate) use pool::{spawn_blocking, BlockingPool, Mandatory, Spawner, Task}; cfg_fs! { pub(crate) use pool::spawn_mandatory_blocking; } mod schedule; mod shutdown; mod task; pub(crate) use schedule::NoopSchedule; pub(crate) use task::BlockingTask; use crate::runtime::Builder; pub(crate) fn create_blocking_pool(builder: &Builder, thread_cap: usize) -> BlockingPool
/* cfg_not_blocking_impl! { use crate::runtime::Builder; use std::time::Duration; #[derive(Debug, Clone)] pub(crate) struct BlockingPool {} pub(crate) use BlockingPool as Spawner; pub(crate) fn create_blocking_pool(_builder: &Builder, _thread_cap: usize) -> BlockingPool { BlockingPool {} } impl BlockingPool { pub(crate) fn spawner(&self) -> &BlockingPool { self } pub(crate) fn shutdown(&mut self, _duration: Option<Duration>) { } } } */
{ BlockingPool::new(builder, thread_cap) }
identifier_body
mod.rs
//! Abstracts out the APIs necessary to `Runtime` for integrating the blocking //! pool. When the `blocking` feature flag is **not** enabled, these APIs are //! shells. This isolates the complexity of dealing with conditional //! compilation. mod pool; pub(crate) use pool::{spawn_blocking, BlockingPool, Mandatory, Spawner, Task}; cfg_fs! { pub(crate) use pool::spawn_mandatory_blocking; } mod schedule; mod shutdown; mod task; pub(crate) use schedule::NoopSchedule; pub(crate) use task::BlockingTask; use crate::runtime::Builder; pub(crate) fn
(builder: &Builder, thread_cap: usize) -> BlockingPool { BlockingPool::new(builder, thread_cap) } /* cfg_not_blocking_impl! { use crate::runtime::Builder; use std::time::Duration; #[derive(Debug, Clone)] pub(crate) struct BlockingPool {} pub(crate) use BlockingPool as Spawner; pub(crate) fn create_blocking_pool(_builder: &Builder, _thread_cap: usize) -> BlockingPool { BlockingPool {} } impl BlockingPool { pub(crate) fn spawner(&self) -> &BlockingPool { self } pub(crate) fn shutdown(&mut self, _duration: Option<Duration>) { } } } */
create_blocking_pool
identifier_name
mod.rs
//! Abstracts out the APIs necessary to `Runtime` for integrating the blocking //! pool. When the `blocking` feature flag is **not** enabled, these APIs are //! shells. This isolates the complexity of dealing with conditional //! compilation. mod pool; pub(crate) use pool::{spawn_blocking, BlockingPool, Mandatory, Spawner, Task}; cfg_fs! { pub(crate) use pool::spawn_mandatory_blocking; } mod schedule; mod shutdown;
pub(crate) use task::BlockingTask; use crate::runtime::Builder; pub(crate) fn create_blocking_pool(builder: &Builder, thread_cap: usize) -> BlockingPool { BlockingPool::new(builder, thread_cap) } /* cfg_not_blocking_impl! { use crate::runtime::Builder; use std::time::Duration; #[derive(Debug, Clone)] pub(crate) struct BlockingPool {} pub(crate) use BlockingPool as Spawner; pub(crate) fn create_blocking_pool(_builder: &Builder, _thread_cap: usize) -> BlockingPool { BlockingPool {} } impl BlockingPool { pub(crate) fn spawner(&self) -> &BlockingPool { self } pub(crate) fn shutdown(&mut self, _duration: Option<Duration>) { } } } */
mod task; pub(crate) use schedule::NoopSchedule;
random_line_split
mod.rs
// ColdFire Target // // This file is part of AEx. // Copyright (C) 2017 Jeffrey Sharp // // AEx is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published // by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // AEx is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See // the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with AEx. If not, see <http://www.gnu.org/licenses/>. // Operand Representations //mod index; mod scale; mod data_reg; mod addr_reg; //mod addr_disp; //mod addr_disp_idx; //mod misc_regs; //mod pc_disp; //mod pc_disp_idx; mod modes; //pub use self::index::*; pub use self::scale::*; pub use self::data_reg::*; // mode 0 pub use self::addr_reg::*; // mode 1 //pub use self::addr_disp::*; //pub use self::addr_disp_idx::*; //pub use self::data_reg::*; //pub use self::misc_regs::*; //pub use self::pc_disp::*; //pub use self::pc_disp_idx::*; pub use self::modes::*; // Encoding / Decoding mod decode; mod mnemonics; mod opcodes; mod operand; pub use self::decode::*; pub use self::mnemonics::*; pub use self::opcodes::*; pub use self::operand::*; /// Operation sizes. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] pub enum
{ /// No associated size. Zero, /// Byte Byte, /// Word (2 bytes) Word, /// Longword (4 bytes) Long, /// Single-precision floating-point (4 bytes) Single, /// Double-precision floating-point (8 bytes) Double, }
Size
identifier_name
mod.rs
// ColdFire Target // // This file is part of AEx. // Copyright (C) 2017 Jeffrey Sharp // // AEx is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published // by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // AEx is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See // the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with AEx. If not, see <http://www.gnu.org/licenses/>. // Operand Representations //mod index; mod scale; mod data_reg; mod addr_reg; //mod addr_disp; //mod addr_disp_idx; //mod misc_regs; //mod pc_disp; //mod pc_disp_idx; mod modes; //pub use self::index::*; pub use self::scale::*; pub use self::data_reg::*; // mode 0 pub use self::addr_reg::*; // mode 1 //pub use self::addr_disp::*; //pub use self::addr_disp_idx::*; //pub use self::data_reg::*; //pub use self::misc_regs::*; //pub use self::pc_disp::*; //pub use self::pc_disp_idx::*; pub use self::modes::*; // Encoding / Decoding mod decode; mod mnemonics; mod opcodes; mod operand; pub use self::decode::*;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] pub enum Size { /// No associated size. Zero, /// Byte Byte, /// Word (2 bytes) Word, /// Longword (4 bytes) Long, /// Single-precision floating-point (4 bytes) Single, /// Double-precision floating-point (8 bytes) Double, }
pub use self::mnemonics::*; pub use self::opcodes::*; pub use self::operand::*; /// Operation sizes.
random_line_split
propagate-multiple-requirements.rs
// Test that we propagate *all* requirements to the caller, not just the first // one. #![feature(nll)] fn once<S, T, U, F: FnOnce(S, T) -> U>(f: F, s: S, t: T) -> U
pub fn dangle() -> &'static [i32] { let other_local_arr = [0, 2, 4]; let local_arr = other_local_arr; let mut out: &mut &'static [i32] = &mut (&[1] as _); once(|mut z: &[i32], mut out_val: &mut &[i32]| { // We unfortunately point to the first use in the closure in the error // message z = &local_arr; //~ ERROR *out_val = &local_arr; }, &[] as &[_], &mut *out); *out } fn main() { println!("{:?}", dangle()); }
{ f(s, t) }
identifier_body
propagate-multiple-requirements.rs
// Test that we propagate *all* requirements to the caller, not just the first // one. #![feature(nll)]
pub fn dangle() -> &'static [i32] { let other_local_arr = [0, 2, 4]; let local_arr = other_local_arr; let mut out: &mut &'static [i32] = &mut (&[1] as _); once(|mut z: &[i32], mut out_val: &mut &[i32]| { // We unfortunately point to the first use in the closure in the error // message z = &local_arr; //~ ERROR *out_val = &local_arr; }, &[] as &[_], &mut *out); *out } fn main() { println!("{:?}", dangle()); }
fn once<S, T, U, F: FnOnce(S, T) -> U>(f: F, s: S, t: T) -> U { f(s, t) }
random_line_split
propagate-multiple-requirements.rs
// Test that we propagate *all* requirements to the caller, not just the first // one. #![feature(nll)] fn
<S, T, U, F: FnOnce(S, T) -> U>(f: F, s: S, t: T) -> U { f(s, t) } pub fn dangle() -> &'static [i32] { let other_local_arr = [0, 2, 4]; let local_arr = other_local_arr; let mut out: &mut &'static [i32] = &mut (&[1] as _); once(|mut z: &[i32], mut out_val: &mut &[i32]| { // We unfortunately point to the first use in the closure in the error // message z = &local_arr; //~ ERROR *out_val = &local_arr; }, &[] as &[_], &mut *out); *out } fn main() { println!("{:?}", dangle()); }
once
identifier_name
lang_items.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Detecting language items. // // Language items are items that represent concepts intrinsic to the language // itself. Examples are: // // * Traits that specify "kinds"; e.g. "Sync", "Send". // // * Traits that represent operators; e.g. "Add", "Sub", "Index". // // * Functions called by the compiler itself. pub use self::LangItem::*; use session::Session; use metadata::csearch::each_lang_item; use middle::ty; use middle::weak_lang_items; use util::nodemap::FnvHashMap; use syntax::ast; use syntax::ast_util::local_def; use syntax::attr::AttrMetaMethods; use syntax::codemap::{DUMMY_SP, Span}; use syntax::parse::token::InternedString; use syntax::visit::Visitor; use syntax::visit; use std::iter::Enumerate; use std::slice; // The actual lang items defined come at the end of this file in one handy table. // So you probably just want to nip down to the end. macro_rules! lets_do_this { ( $( $variant:ident, $name:expr, $method:ident; )* ) => { enum_from_u32! { #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub enum LangItem { $($variant,)* } } pub struct LanguageItems { pub items: Vec<Option<ast::DefId>>, pub missing: Vec<LangItem>, } impl LanguageItems { pub fn new() -> LanguageItems { fn foo(_: LangItem) -> Option<ast::DefId> { None } LanguageItems { items: vec!($(foo($variant)),*), missing: Vec::new(), } } pub fn items<'a>(&'a self) -> Enumerate<slice::Iter<'a, Option<ast::DefId>>> { self.items.iter().enumerate() } pub fn item_name(index: usize) -> &'static str { let item: Option<LangItem> = LangItem::from_u32(index as u32); match item { $( Some($variant) => $name, )* None => "???" } } pub fn require(&self, it: LangItem) -> Result<ast::DefId, String> { match self.items[it as usize] { Some(id) => Ok(id), None => { Err(format!("requires `{}` lang_item", LanguageItems::item_name(it as usize))) } } } pub fn require_owned_box(&self) -> Result<ast::DefId, String> { self.require(OwnedBoxLangItem) } pub fn from_builtin_kind(&self, bound: ty::BuiltinBound) -> Result<ast::DefId, String> { match bound { ty::BoundSend => self.require(SendTraitLangItem), ty::BoundSized => self.require(SizedTraitLangItem), ty::BoundCopy => self.require(CopyTraitLangItem), ty::BoundSync => self.require(SyncTraitLangItem), } } pub fn to_builtin_kind(&self, id: ast::DefId) -> Option<ty::BuiltinBound> { if Some(id) == self.send_trait() { Some(ty::BoundSend) } else if Some(id) == self.sized_trait() { Some(ty::BoundSized) } else if Some(id) == self.copy_trait() { Some(ty::BoundCopy) } else if Some(id) == self.sync_trait() { Some(ty::BoundSync) } else { None } } pub fn fn_trait_kind(&self, id: ast::DefId) -> Option<ty::ClosureKind> { let def_id_kinds = [ (self.fn_trait(), ty::FnClosureKind), (self.fn_mut_trait(), ty::FnMutClosureKind), (self.fn_once_trait(), ty::FnOnceClosureKind), ]; for &(opt_def_id, kind) in &def_id_kinds { if Some(id) == opt_def_id { return Some(kind); } } None } $( #[allow(dead_code)] pub fn $method(&self) -> Option<ast::DefId> { self.items[$variant as usize] } )* } struct LanguageItemCollector<'a> { items: LanguageItems, session: &'a Session, item_refs: FnvHashMap<&'static str, usize>, } impl<'a, 'v> Visitor<'v> for LanguageItemCollector<'a> { fn visit_item(&mut self, item: &ast::Item) { if let Some(value) = extract(&item.attrs) { let item_index = self.item_refs.get(&value[..]).cloned(); if let Some(item_index) = item_index { self.collect_item(item_index, local_def(item.id), item.span) } } visit::walk_item(self, item); } } impl<'a> LanguageItemCollector<'a> { pub fn new(session: &'a Session) -> LanguageItemCollector<'a> { let mut item_refs = FnvHashMap(); $( item_refs.insert($name, $variant as usize); )* LanguageItemCollector { session: session, items: LanguageItems::new(), item_refs: item_refs } } pub fn collect_item(&mut self, item_index: usize, item_def_id: ast::DefId, span: Span) { // Check for duplicates. match self.items.items[item_index] { Some(original_def_id) if original_def_id!= item_def_id => { span_err!(self.session, span, E0152, "duplicate entry for `{}`", LanguageItems::item_name(item_index)); } Some(_) | None => { // OK. } } // Matched. self.items.items[item_index] = Some(item_def_id); } pub fn collect_local_language_items(&mut self, krate: &ast::Crate) { visit::walk_crate(self, krate); } pub fn collect_external_language_items(&mut self) { let crate_store = &self.session.cstore; crate_store.iter_crate_data(|crate_number, _crate_metadata| { each_lang_item(crate_store, crate_number, |node_id, item_index| { let def_id = ast::DefId { krate: crate_number, node: node_id }; self.collect_item(item_index, def_id, DUMMY_SP); true }); }) } pub fn collect(&mut self, krate: &ast::Crate) { self.collect_local_language_items(krate); self.collect_external_language_items(); } } pub fn extract(attrs: &[ast::Attribute]) -> Option<InternedString> { for attribute in attrs { match attribute.value_str() { Some(ref value) if attribute.check_name("lang") => { return Some(value.clone()); } _ => {} } } return None; } pub fn collect_language_items(krate: &ast::Crate, session: &Session) -> LanguageItems { let mut collector = LanguageItemCollector::new(session); collector.collect(krate); let LanguageItemCollector { mut items,.. } = collector; weak_lang_items::check_crate(krate, session, &mut items); session.abort_if_errors(); items } // End of the macro } } lets_do_this! { // Variant name, Name, Method name; CharImplItem, "char", char_impl; StrImplItem, "str", str_impl; SliceImplItem, "slice", slice_impl; ConstPtrImplItem, "const_ptr", const_ptr_impl; MutPtrImplItem, "mut_ptr", mut_ptr_impl; I8ImplItem, "i8", i8_impl; I16ImplItem, "i16", i16_impl; I32ImplItem, "i32", i32_impl; I64ImplItem, "i64", i64_impl; IsizeImplItem, "isize", isize_impl; U8ImplItem, "u8", u8_impl; U16ImplItem, "u16", u16_impl; U32ImplItem, "u32", u32_impl; U64ImplItem, "u64", u64_impl; UsizeImplItem, "usize", usize_impl; F32ImplItem, "f32", f32_impl; F64ImplItem, "f64", f64_impl; SendTraitLangItem, "send", send_trait; SizedTraitLangItem, "sized", sized_trait; UnsizeTraitLangItem, "unsize", unsize_trait; CopyTraitLangItem, "copy", copy_trait; SyncTraitLangItem, "sync", sync_trait; DropTraitLangItem, "drop", drop_trait; CoerceUnsizedTraitLangItem, "coerce_unsized", coerce_unsized_trait; AddTraitLangItem, "add", add_trait; SubTraitLangItem, "sub", sub_trait; MulTraitLangItem, "mul", mul_trait; DivTraitLangItem, "div", div_trait; RemTraitLangItem, "rem", rem_trait; NegTraitLangItem, "neg", neg_trait; NotTraitLangItem, "not", not_trait; BitXorTraitLangItem, "bitxor", bitxor_trait;
BitAndTraitLangItem, "bitand", bitand_trait; BitOrTraitLangItem, "bitor", bitor_trait; ShlTraitLangItem, "shl", shl_trait; ShrTraitLangItem, "shr", shr_trait; IndexTraitLangItem, "index", index_trait; IndexMutTraitLangItem, "index_mut", index_mut_trait; RangeStructLangItem, "range", range_struct; RangeFromStructLangItem, "range_from", range_from_struct; RangeToStructLangItem, "range_to", range_to_struct; RangeFullStructLangItem, "range_full", range_full_struct; UnsafeCellTypeLangItem, "unsafe_cell", unsafe_cell_type; DerefTraitLangItem, "deref", deref_trait; DerefMutTraitLangItem, "deref_mut", deref_mut_trait; FnTraitLangItem, "fn", fn_trait; FnMutTraitLangItem, "fn_mut", fn_mut_trait; FnOnceTraitLangItem, "fn_once", fn_once_trait; EqTraitLangItem, "eq", eq_trait; OrdTraitLangItem, "ord", ord_trait; StrEqFnLangItem, "str_eq", str_eq_fn; // A number of panic-related lang items. The `panic` item corresponds to // divide-by-zero and various panic cases with `match`. The // `panic_bounds_check` item is for indexing arrays. // // The `begin_unwind` lang item has a predefined symbol name and is sort of // a "weak lang item" in the sense that a crate is not required to have it // defined to use it, but a final product is required to define it // somewhere. Additionally, there are restrictions on crates that use a weak // lang item, but do not have it defined. PanicFnLangItem, "panic", panic_fn; PanicBoundsCheckFnLangItem, "panic_bounds_check", panic_bounds_check_fn; PanicFmtLangItem, "panic_fmt", panic_fmt; ExchangeMallocFnLangItem, "exchange_malloc", exchange_malloc_fn; ExchangeFreeFnLangItem, "exchange_free", exchange_free_fn; StrDupUniqFnLangItem, "strdup_uniq", strdup_uniq_fn; StartFnLangItem, "start", start_fn; EhPersonalityLangItem, "eh_personality", eh_personality; EhPersonalityCatchLangItem, "eh_personality_catch", eh_personality_catch; MSVCTryFilterLangItem, "msvc_try_filter", msvc_try_filter; ExchangeHeapLangItem, "exchange_heap", exchange_heap; OwnedBoxLangItem, "owned_box", owned_box; PhantomDataItem, "phantom_data", phantom_data; // Deprecated: CovariantTypeItem, "covariant_type", covariant_type; ContravariantTypeItem, "contravariant_type", contravariant_type; InvariantTypeItem, "invariant_type", invariant_type; CovariantLifetimeItem, "covariant_lifetime", covariant_lifetime; ContravariantLifetimeItem, "contravariant_lifetime", contravariant_lifetime; InvariantLifetimeItem, "invariant_lifetime", invariant_lifetime; NoCopyItem, "no_copy_bound", no_copy_bound; NonZeroItem, "non_zero", non_zero; StackExhaustedLangItem, "stack_exhausted", stack_exhausted; DebugTraitLangItem, "debug_trait", debug_trait; }
random_line_split
div.rs
#![feature(core, core_simd)]
#[cfg(test)] mod tests { use core::simd::u32x4; // #[simd] // #[derive(Copy, Clone, Debug)] // #[repr(C)] // pub struct u32x4(pub u32, pub u32, pub u32, pub u32); #[test] fn div_test1() { let x: u32x4 = u32x4( 0, 1, 2, 3 ); let y: u32x4 = u32x4( 2, 2, 2, 2 ); let z: u32x4 = x / y; let result: String = format!("{:?}", z); assert_eq!(result, "u32x4(0, 0, 1, 1)".to_string()); } }
extern crate core;
random_line_split
div.rs
#![feature(core, core_simd)] extern crate core; #[cfg(test)] mod tests { use core::simd::u32x4; // #[simd] // #[derive(Copy, Clone, Debug)] // #[repr(C)] // pub struct u32x4(pub u32, pub u32, pub u32, pub u32); #[test] fn div_test1()
}
{ let x: u32x4 = u32x4( 0, 1, 2, 3 ); let y: u32x4 = u32x4( 2, 2, 2, 2 ); let z: u32x4 = x / y; let result: String = format!("{:?}", z); assert_eq!(result, "u32x4(0, 0, 1, 1)".to_string()); }
identifier_body
div.rs
#![feature(core, core_simd)] extern crate core; #[cfg(test)] mod tests { use core::simd::u32x4; // #[simd] // #[derive(Copy, Clone, Debug)] // #[repr(C)] // pub struct u32x4(pub u32, pub u32, pub u32, pub u32); #[test] fn
() { let x: u32x4 = u32x4( 0, 1, 2, 3 ); let y: u32x4 = u32x4( 2, 2, 2, 2 ); let z: u32x4 = x / y; let result: String = format!("{:?}", z); assert_eq!(result, "u32x4(0, 0, 1, 1)".to_string()); } }
div_test1
identifier_name
str.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::from_str::FromStr; use std::hash::{Hash, sip}; use std::path::BytesContainer; use std::str; #[deriving(Encodable,Clone,Eq,PartialEq)] pub struct ByteString(Vec<u8>); impl ByteString { pub fn new(value: Vec<u8>) -> ByteString { ByteString(value) } pub fn as_str<'a>(&'a self) -> Option<&'a str> { let ByteString(ref vec) = *self; str::from_utf8(vec.as_slice()) } pub fn as_slice<'a>(&'a self) -> &'a [u8] { let ByteString(ref vector) = *self; vector.as_slice() } pub fn len(&self) -> uint { let ByteString(ref vector) = *self; vector.len() } pub fn eq_ignore_case(&self, other: &ByteString) -> bool { // XXXManishearth make this more efficient self.to_lower() == other.to_lower() } pub fn to_lower(&self) -> ByteString { let ByteString(ref vec) = *self; ByteString::new(vec.iter().map(|&x| { if x > 'A' as u8 && x < 'Z' as u8 { x + ('a' as u8) - ('A' as u8) } else { x } }).collect()) } pub fn is_token(&self) -> bool { let ByteString(ref vec) = *self; if vec.len() == 0 { return false; // A token must be at least a single character } vec.iter().all(|&x| { // http://tools.ietf.org/html/rfc2616#section-2.2 match x { 0..31 | 127 => false, // CTLs 40 | 41 | 60 | 62 | 64 | 44 | 59 | 58 | 92 | 34 | 47 | 91 | 93 | 63 | 61 | 123 | 125 | 32 => false, // separators x if x > 127 => false, // non-CHARs _ => true } }) } pub fn
(&self) -> bool { // Classifications of characters necessary for the [CRLF] (SP|HT) rule #[deriving(PartialEq)] enum PreviousCharacter { Other, CR, LF, SPHT // SP or HT } let ByteString(ref vec) = *self; let mut prev = Other; // The previous character vec.iter().all(|&x| { // http://tools.ietf.org/html/rfc2616#section-2.2 match x { 13 => { // CR if prev == Other || prev == SPHT { prev = CR; true } else { false } }, 10 => { // LF if prev == CR { prev = LF; true } else { false } }, 32 => { // SP if prev == LF || prev == SPHT { prev = SPHT; true } else if prev == Other { // Counts as an Other here, since it's not preceded by a CRLF // SP is not a CTL, so it can be used anywhere // though if used immediately after a CR the CR is invalid // We don't change prev since it's already Other true } else { false } }, 9 => { // HT if prev == LF || prev == SPHT { prev = SPHT; true } else { false } }, 0..31 | 127 => false, // CTLs x if x > 127 => false, // non ASCII _ if prev == Other || prev == SPHT => { prev = Other; true }, _ => false // Previous character was a CR/LF but not part of the [CRLF] (SP|HT) rule } }) } } impl Hash for ByteString { fn hash(&self, state: &mut sip::SipState) { let ByteString(ref vec) = *self; vec.hash(state); } } impl FromStr for ByteString { fn from_str(s: &str) -> Option<ByteString> { Some(ByteString::new(s.container_into_owned_bytes())) } }
is_field_value
identifier_name
str.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::from_str::FromStr; use std::hash::{Hash, sip}; use std::path::BytesContainer; use std::str; #[deriving(Encodable,Clone,Eq,PartialEq)] pub struct ByteString(Vec<u8>); impl ByteString { pub fn new(value: Vec<u8>) -> ByteString
pub fn as_str<'a>(&'a self) -> Option<&'a str> { let ByteString(ref vec) = *self; str::from_utf8(vec.as_slice()) } pub fn as_slice<'a>(&'a self) -> &'a [u8] { let ByteString(ref vector) = *self; vector.as_slice() } pub fn len(&self) -> uint { let ByteString(ref vector) = *self; vector.len() } pub fn eq_ignore_case(&self, other: &ByteString) -> bool { // XXXManishearth make this more efficient self.to_lower() == other.to_lower() } pub fn to_lower(&self) -> ByteString { let ByteString(ref vec) = *self; ByteString::new(vec.iter().map(|&x| { if x > 'A' as u8 && x < 'Z' as u8 { x + ('a' as u8) - ('A' as u8) } else { x } }).collect()) } pub fn is_token(&self) -> bool { let ByteString(ref vec) = *self; if vec.len() == 0 { return false; // A token must be at least a single character } vec.iter().all(|&x| { // http://tools.ietf.org/html/rfc2616#section-2.2 match x { 0..31 | 127 => false, // CTLs 40 | 41 | 60 | 62 | 64 | 44 | 59 | 58 | 92 | 34 | 47 | 91 | 93 | 63 | 61 | 123 | 125 | 32 => false, // separators x if x > 127 => false, // non-CHARs _ => true } }) } pub fn is_field_value(&self) -> bool { // Classifications of characters necessary for the [CRLF] (SP|HT) rule #[deriving(PartialEq)] enum PreviousCharacter { Other, CR, LF, SPHT // SP or HT } let ByteString(ref vec) = *self; let mut prev = Other; // The previous character vec.iter().all(|&x| { // http://tools.ietf.org/html/rfc2616#section-2.2 match x { 13 => { // CR if prev == Other || prev == SPHT { prev = CR; true } else { false } }, 10 => { // LF if prev == CR { prev = LF; true } else { false } }, 32 => { // SP if prev == LF || prev == SPHT { prev = SPHT; true } else if prev == Other { // Counts as an Other here, since it's not preceded by a CRLF // SP is not a CTL, so it can be used anywhere // though if used immediately after a CR the CR is invalid // We don't change prev since it's already Other true } else { false } }, 9 => { // HT if prev == LF || prev == SPHT { prev = SPHT; true } else { false } }, 0..31 | 127 => false, // CTLs x if x > 127 => false, // non ASCII _ if prev == Other || prev == SPHT => { prev = Other; true }, _ => false // Previous character was a CR/LF but not part of the [CRLF] (SP|HT) rule } }) } } impl Hash for ByteString { fn hash(&self, state: &mut sip::SipState) { let ByteString(ref vec) = *self; vec.hash(state); } } impl FromStr for ByteString { fn from_str(s: &str) -> Option<ByteString> { Some(ByteString::new(s.container_into_owned_bytes())) } }
{ ByteString(value) }
identifier_body
str.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::from_str::FromStr; use std::hash::{Hash, sip}; use std::path::BytesContainer; use std::str; #[deriving(Encodable,Clone,Eq,PartialEq)] pub struct ByteString(Vec<u8>); impl ByteString { pub fn new(value: Vec<u8>) -> ByteString { ByteString(value) } pub fn as_str<'a>(&'a self) -> Option<&'a str> { let ByteString(ref vec) = *self; str::from_utf8(vec.as_slice()) } pub fn as_slice<'a>(&'a self) -> &'a [u8] { let ByteString(ref vector) = *self; vector.as_slice() } pub fn len(&self) -> uint { let ByteString(ref vector) = *self; vector.len() } pub fn eq_ignore_case(&self, other: &ByteString) -> bool {
pub fn to_lower(&self) -> ByteString { let ByteString(ref vec) = *self; ByteString::new(vec.iter().map(|&x| { if x > 'A' as u8 && x < 'Z' as u8 { x + ('a' as u8) - ('A' as u8) } else { x } }).collect()) } pub fn is_token(&self) -> bool { let ByteString(ref vec) = *self; if vec.len() == 0 { return false; // A token must be at least a single character } vec.iter().all(|&x| { // http://tools.ietf.org/html/rfc2616#section-2.2 match x { 0..31 | 127 => false, // CTLs 40 | 41 | 60 | 62 | 64 | 44 | 59 | 58 | 92 | 34 | 47 | 91 | 93 | 63 | 61 | 123 | 125 | 32 => false, // separators x if x > 127 => false, // non-CHARs _ => true } }) } pub fn is_field_value(&self) -> bool { // Classifications of characters necessary for the [CRLF] (SP|HT) rule #[deriving(PartialEq)] enum PreviousCharacter { Other, CR, LF, SPHT // SP or HT } let ByteString(ref vec) = *self; let mut prev = Other; // The previous character vec.iter().all(|&x| { // http://tools.ietf.org/html/rfc2616#section-2.2 match x { 13 => { // CR if prev == Other || prev == SPHT { prev = CR; true } else { false } }, 10 => { // LF if prev == CR { prev = LF; true } else { false } }, 32 => { // SP if prev == LF || prev == SPHT { prev = SPHT; true } else if prev == Other { // Counts as an Other here, since it's not preceded by a CRLF // SP is not a CTL, so it can be used anywhere // though if used immediately after a CR the CR is invalid // We don't change prev since it's already Other true } else { false } }, 9 => { // HT if prev == LF || prev == SPHT { prev = SPHT; true } else { false } }, 0..31 | 127 => false, // CTLs x if x > 127 => false, // non ASCII _ if prev == Other || prev == SPHT => { prev = Other; true }, _ => false // Previous character was a CR/LF but not part of the [CRLF] (SP|HT) rule } }) } } impl Hash for ByteString { fn hash(&self, state: &mut sip::SipState) { let ByteString(ref vec) = *self; vec.hash(state); } } impl FromStr for ByteString { fn from_str(s: &str) -> Option<ByteString> { Some(ByteString::new(s.container_into_owned_bytes())) } }
// XXXManishearth make this more efficient self.to_lower() == other.to_lower() }
random_line_split
main.rs
#[derive(Debug, Clone)] struct Node { x: usize, y: usize, value: String, } #[derive(Debug, Clone)] struct Edge { edge: bool, node: Option<String>, } #[derive(Debug)] struct Graphadj { nodenums: usize, graphadj: Vec<Vec<Edge>>, } impl Node { fn new(x: usize, y:usize, value: String) -> Self { Node{ x: x, y: y, value: value, } } } impl Edge { fn new() -> Self { Edge { edge: false, node: None } } fn have_edge(value: String) -> Self { Edge { edge: true, node: Some(value) }
impl Graphadj { fn new(nums: usize) -> Self { Graphadj { nodenums: nums, graphadj: vec![vec![Edge::new();nums];nums] } } fn insert_edge(&mut self, v: Node) { match v.x < self.nodenums && v.y < self.nodenums { true => { self.graphadj[v.x][v.y] = Edge::have_edge(v.value.clone()); self.graphadj[v.y][v.x] = Edge::have_edge(v.value); } false => { panic!("your nodeid is bigger than nodenums!") } } } } fn main() { let mut g = Graphadj::new(2); let v1 = Node::new(0, 1,"v1".to_string()); g.insert_edge(v1); println!("{:?}", g); }
} }
random_line_split
main.rs
#[derive(Debug, Clone)] struct Node { x: usize, y: usize, value: String, } #[derive(Debug, Clone)] struct
{ edge: bool, node: Option<String>, } #[derive(Debug)] struct Graphadj { nodenums: usize, graphadj: Vec<Vec<Edge>>, } impl Node { fn new(x: usize, y:usize, value: String) -> Self { Node{ x: x, y: y, value: value, } } } impl Edge { fn new() -> Self { Edge { edge: false, node: None } } fn have_edge(value: String) -> Self { Edge { edge: true, node: Some(value) } } } impl Graphadj { fn new(nums: usize) -> Self { Graphadj { nodenums: nums, graphadj: vec![vec![Edge::new();nums];nums] } } fn insert_edge(&mut self, v: Node) { match v.x < self.nodenums && v.y < self.nodenums { true => { self.graphadj[v.x][v.y] = Edge::have_edge(v.value.clone()); self.graphadj[v.y][v.x] = Edge::have_edge(v.value); } false => { panic!("your nodeid is bigger than nodenums!") } } } } fn main() { let mut g = Graphadj::new(2); let v1 = Node::new(0, 1,"v1".to_string()); g.insert_edge(v1); println!("{:?}", g); }
Edge
identifier_name
main.rs
#[derive(Debug, Clone)] struct Node { x: usize, y: usize, value: String, } #[derive(Debug, Clone)] struct Edge { edge: bool, node: Option<String>, } #[derive(Debug)] struct Graphadj { nodenums: usize, graphadj: Vec<Vec<Edge>>, } impl Node { fn new(x: usize, y:usize, value: String) -> Self { Node{ x: x, y: y, value: value, } } } impl Edge { fn new() -> Self { Edge { edge: false, node: None } } fn have_edge(value: String) -> Self { Edge { edge: true, node: Some(value) } } } impl Graphadj { fn new(nums: usize) -> Self
fn insert_edge(&mut self, v: Node) { match v.x < self.nodenums && v.y < self.nodenums { true => { self.graphadj[v.x][v.y] = Edge::have_edge(v.value.clone()); self.graphadj[v.y][v.x] = Edge::have_edge(v.value); } false => { panic!("your nodeid is bigger than nodenums!") } } } } fn main() { let mut g = Graphadj::new(2); let v1 = Node::new(0, 1,"v1".to_string()); g.insert_edge(v1); println!("{:?}", g); }
{ Graphadj { nodenums: nums, graphadj: vec![vec![Edge::new();nums];nums] } }
identifier_body
main.rs
#[derive(Debug, Clone)] struct Node { x: usize, y: usize, value: String, } #[derive(Debug, Clone)] struct Edge { edge: bool, node: Option<String>, } #[derive(Debug)] struct Graphadj { nodenums: usize, graphadj: Vec<Vec<Edge>>, } impl Node { fn new(x: usize, y:usize, value: String) -> Self { Node{ x: x, y: y, value: value, } } } impl Edge { fn new() -> Self { Edge { edge: false, node: None } } fn have_edge(value: String) -> Self { Edge { edge: true, node: Some(value) } } } impl Graphadj { fn new(nums: usize) -> Self { Graphadj { nodenums: nums, graphadj: vec![vec![Edge::new();nums];nums] } } fn insert_edge(&mut self, v: Node) { match v.x < self.nodenums && v.y < self.nodenums { true => { self.graphadj[v.x][v.y] = Edge::have_edge(v.value.clone()); self.graphadj[v.y][v.x] = Edge::have_edge(v.value); } false =>
} } } fn main() { let mut g = Graphadj::new(2); let v1 = Node::new(0, 1,"v1".to_string()); g.insert_edge(v1); println!("{:?}", g); }
{ panic!("your nodeid is bigger than nodenums!") }
conditional_block
urlsearchparams.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::URLSearchParamsBinding::URLSearchParamsMethods; use crate::dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsWrap; use crate::dom::bindings::codegen::UnionTypes::USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::iterable::Iterable; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::bindings::weakref::MutableWeakRef; use crate::dom::globalscope::GlobalScope; use crate::dom::url::URL; use dom_struct::dom_struct; use url::form_urlencoded; // https://url.spec.whatwg.org/#interface-urlsearchparams #[dom_struct] pub struct URLSearchParams { reflector_: Reflector, // https://url.spec.whatwg.org/#concept-urlsearchparams-list list: DomRefCell<Vec<(String, String)>>, // https://url.spec.whatwg.org/#concept-urlsearchparams-url-object url: MutableWeakRef<URL>, } impl URLSearchParams { fn new_inherited(url: Option<&URL>) -> URLSearchParams { URLSearchParams { reflector_: Reflector::new(), list: DomRefCell::new(url.map_or(Vec::new(), |url| url.query_pairs())), url: MutableWeakRef::new(url), } } pub fn new(global: &GlobalScope, url: Option<&URL>) -> DomRoot<URLSearchParams> { reflect_dom_object( Box::new(URLSearchParams::new_inherited(url)), global, URLSearchParamsWrap, ) } // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams pub fn Constructor( global: &GlobalScope, init: USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString, ) -> Fallible<DomRoot<URLSearchParams>> { // Step 1. let query = URLSearchParams::new(global, None); match init { USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString::USVStringSequenceSequence(init) => { // Step 2. // Step 2-1. if init.iter().any(|pair| pair.len()!= 2) { return Err(Error::Type("Sequence initializer must only contain pair elements.".to_string())); } // Step 2-2. *query.list.borrow_mut() = init.iter().map(|pair| (pair[0].to_string(), pair[1].to_string())).collect::<Vec<_>>(); }, USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString::USVStringUSVStringRecord(init) => { // Step 3. *query.list.borrow_mut() = (*init).iter().map(|(name, value)| (name.to_string(), value.to_string())).collect::<Vec<_>>(); }, USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString::USVString(init) => { // Step 4. let init_bytes = match init.0.chars().next() { Some(first_char) if first_char == '?' => { let (_, other_bytes) = init.0.as_bytes().split_at(1); other_bytes }, _ => init.0.as_bytes(), }; *query.list.borrow_mut() = form_urlencoded::parse(init_bytes).into_owned().collect(); } } // Step 5. Ok(query) } pub fn set_list(&self, list: Vec<(String, String)>) { *self.list.borrow_mut() = list; } } impl URLSearchParamsMethods for URLSearchParams { // https://url.spec.whatwg.org/#dom-urlsearchparams-append fn Append(&self, name: USVString, value: USVString) { // Step 1. self.list.borrow_mut().push((name.0, value.0)); // Step 2. self.update_steps(); } // https://url.spec.whatwg.org/#dom-urlsearchparams-delete fn Delete(&self, name: USVString) { // Step 1. self.list.borrow_mut().retain(|&(ref k, _)| k!= &name.0); // Step 2. self.update_steps(); } // https://url.spec.whatwg.org/#dom-urlsearchparams-get fn Get(&self, name: USVString) -> Option<USVString> { let list = self.list.borrow(); list.iter() .find(|&kv| kv.0 == name.0) .map(|ref kv| USVString(kv.1.clone())) } // https://url.spec.whatwg.org/#dom-urlsearchparams-getall fn GetAll(&self, name: USVString) -> Vec<USVString> { let list = self.list.borrow(); list.iter() .filter_map(|&(ref k, ref v)| { if k == &name.0 { Some(USVString(v.clone())) } else { None } }) .collect() } // https://url.spec.whatwg.org/#dom-urlsearchparams-has fn Has(&self, name: USVString) -> bool { let list = self.list.borrow(); list.iter().any(|&(ref k, _)| k == &name.0) } // https://url.spec.whatwg.org/#dom-urlsearchparams-set fn Set(&self, name: USVString, value: USVString) { { // Step 1. let mut list = self.list.borrow_mut(); let mut index = None; let mut i = 0; list.retain(|&(ref k, _)| { if index.is_none()
else { k!= &name.0 } }); match index { Some(index) => list[index].1 = value.0, None => list.push((name.0, value.0)), // Step 2. }; } // Un-borrow self.list // Step 3. self.update_steps(); } // https://url.spec.whatwg.org/#dom-urlsearchparams-sort fn Sort(&self) { // Step 1. self.list .borrow_mut() .sort_by(|(a, _), (b, _)| a.encode_utf16().cmp(b.encode_utf16())); // Step 2. self.update_steps(); } // https://url.spec.whatwg.org/#stringification-behavior fn Stringifier(&self) -> DOMString { DOMString::from(self.serialize_utf8()) } } impl URLSearchParams { // https://url.spec.whatwg.org/#concept-urlencoded-serializer pub fn serialize_utf8(&self) -> String { let list = self.list.borrow(); form_urlencoded::Serializer::new(String::new()) .extend_pairs(&*list) .finish() } // https://url.spec.whatwg.org/#concept-urlsearchparams-update fn update_steps(&self) { if let Some(url) = self.url.root() { url.set_query_pairs(&self.list.borrow()) } } } impl Iterable for URLSearchParams { type Key = USVString; type Value = USVString; fn get_iterable_length(&self) -> u32 { self.list.borrow().len() as u32 } fn get_value_at_index(&self, n: u32) -> USVString { let value = self.list.borrow()[n as usize].1.clone(); USVString(value) } fn get_key_at_index(&self, n: u32) -> USVString { let key = self.list.borrow()[n as usize].0.clone(); USVString(key) } }
{ if k == &name.0 { index = Some(i); } else { i += 1; } true }
conditional_block
urlsearchparams.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::URLSearchParamsBinding::URLSearchParamsMethods; use crate::dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsWrap; use crate::dom::bindings::codegen::UnionTypes::USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::iterable::Iterable; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::bindings::weakref::MutableWeakRef; use crate::dom::globalscope::GlobalScope; use crate::dom::url::URL; use dom_struct::dom_struct; use url::form_urlencoded; // https://url.spec.whatwg.org/#interface-urlsearchparams #[dom_struct] pub struct URLSearchParams { reflector_: Reflector, // https://url.spec.whatwg.org/#concept-urlsearchparams-list list: DomRefCell<Vec<(String, String)>>, // https://url.spec.whatwg.org/#concept-urlsearchparams-url-object url: MutableWeakRef<URL>, } impl URLSearchParams { fn new_inherited(url: Option<&URL>) -> URLSearchParams { URLSearchParams { reflector_: Reflector::new(), list: DomRefCell::new(url.map_or(Vec::new(), |url| url.query_pairs())), url: MutableWeakRef::new(url), } } pub fn new(global: &GlobalScope, url: Option<&URL>) -> DomRoot<URLSearchParams> { reflect_dom_object( Box::new(URLSearchParams::new_inherited(url)), global, URLSearchParamsWrap, ) } // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams pub fn Constructor( global: &GlobalScope, init: USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString, ) -> Fallible<DomRoot<URLSearchParams>> { // Step 1. let query = URLSearchParams::new(global, None); match init { USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString::USVStringSequenceSequence(init) => { // Step 2. // Step 2-1. if init.iter().any(|pair| pair.len()!= 2) { return Err(Error::Type("Sequence initializer must only contain pair elements.".to_string())); } // Step 2-2. *query.list.borrow_mut() = init.iter().map(|pair| (pair[0].to_string(), pair[1].to_string())).collect::<Vec<_>>(); }, USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString::USVStringUSVStringRecord(init) => { // Step 3. *query.list.borrow_mut() = (*init).iter().map(|(name, value)| (name.to_string(), value.to_string())).collect::<Vec<_>>(); }, USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString::USVString(init) => { // Step 4. let init_bytes = match init.0.chars().next() { Some(first_char) if first_char == '?' => { let (_, other_bytes) = init.0.as_bytes().split_at(1); other_bytes }, _ => init.0.as_bytes(), }; *query.list.borrow_mut() = form_urlencoded::parse(init_bytes).into_owned().collect(); } } // Step 5. Ok(query) } pub fn set_list(&self, list: Vec<(String, String)>) { *self.list.borrow_mut() = list; } } impl URLSearchParamsMethods for URLSearchParams { // https://url.spec.whatwg.org/#dom-urlsearchparams-append fn Append(&self, name: USVString, value: USVString) { // Step 1. self.list.borrow_mut().push((name.0, value.0)); // Step 2. self.update_steps(); } // https://url.spec.whatwg.org/#dom-urlsearchparams-delete fn Delete(&self, name: USVString) { // Step 1. self.list.borrow_mut().retain(|&(ref k, _)| k!= &name.0); // Step 2. self.update_steps(); } // https://url.spec.whatwg.org/#dom-urlsearchparams-get fn Get(&self, name: USVString) -> Option<USVString>
// https://url.spec.whatwg.org/#dom-urlsearchparams-getall fn GetAll(&self, name: USVString) -> Vec<USVString> { let list = self.list.borrow(); list.iter() .filter_map(|&(ref k, ref v)| { if k == &name.0 { Some(USVString(v.clone())) } else { None } }) .collect() } // https://url.spec.whatwg.org/#dom-urlsearchparams-has fn Has(&self, name: USVString) -> bool { let list = self.list.borrow(); list.iter().any(|&(ref k, _)| k == &name.0) } // https://url.spec.whatwg.org/#dom-urlsearchparams-set fn Set(&self, name: USVString, value: USVString) { { // Step 1. let mut list = self.list.borrow_mut(); let mut index = None; let mut i = 0; list.retain(|&(ref k, _)| { if index.is_none() { if k == &name.0 { index = Some(i); } else { i += 1; } true } else { k!= &name.0 } }); match index { Some(index) => list[index].1 = value.0, None => list.push((name.0, value.0)), // Step 2. }; } // Un-borrow self.list // Step 3. self.update_steps(); } // https://url.spec.whatwg.org/#dom-urlsearchparams-sort fn Sort(&self) { // Step 1. self.list .borrow_mut() .sort_by(|(a, _), (b, _)| a.encode_utf16().cmp(b.encode_utf16())); // Step 2. self.update_steps(); } // https://url.spec.whatwg.org/#stringification-behavior fn Stringifier(&self) -> DOMString { DOMString::from(self.serialize_utf8()) } } impl URLSearchParams { // https://url.spec.whatwg.org/#concept-urlencoded-serializer pub fn serialize_utf8(&self) -> String { let list = self.list.borrow(); form_urlencoded::Serializer::new(String::new()) .extend_pairs(&*list) .finish() } // https://url.spec.whatwg.org/#concept-urlsearchparams-update fn update_steps(&self) { if let Some(url) = self.url.root() { url.set_query_pairs(&self.list.borrow()) } } } impl Iterable for URLSearchParams { type Key = USVString; type Value = USVString; fn get_iterable_length(&self) -> u32 { self.list.borrow().len() as u32 } fn get_value_at_index(&self, n: u32) -> USVString { let value = self.list.borrow()[n as usize].1.clone(); USVString(value) } fn get_key_at_index(&self, n: u32) -> USVString { let key = self.list.borrow()[n as usize].0.clone(); USVString(key) } }
{ let list = self.list.borrow(); list.iter() .find(|&kv| kv.0 == name.0) .map(|ref kv| USVString(kv.1.clone())) }
identifier_body
urlsearchparams.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::URLSearchParamsBinding::URLSearchParamsMethods; use crate::dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsWrap; use crate::dom::bindings::codegen::UnionTypes::USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::iterable::Iterable; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::bindings::weakref::MutableWeakRef; use crate::dom::globalscope::GlobalScope; use crate::dom::url::URL; use dom_struct::dom_struct; use url::form_urlencoded; // https://url.spec.whatwg.org/#interface-urlsearchparams #[dom_struct] pub struct URLSearchParams { reflector_: Reflector, // https://url.spec.whatwg.org/#concept-urlsearchparams-list list: DomRefCell<Vec<(String, String)>>, // https://url.spec.whatwg.org/#concept-urlsearchparams-url-object url: MutableWeakRef<URL>, } impl URLSearchParams { fn new_inherited(url: Option<&URL>) -> URLSearchParams { URLSearchParams { reflector_: Reflector::new(), list: DomRefCell::new(url.map_or(Vec::new(), |url| url.query_pairs())), url: MutableWeakRef::new(url), } }
global, URLSearchParamsWrap, ) } // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams pub fn Constructor( global: &GlobalScope, init: USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString, ) -> Fallible<DomRoot<URLSearchParams>> { // Step 1. let query = URLSearchParams::new(global, None); match init { USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString::USVStringSequenceSequence(init) => { // Step 2. // Step 2-1. if init.iter().any(|pair| pair.len()!= 2) { return Err(Error::Type("Sequence initializer must only contain pair elements.".to_string())); } // Step 2-2. *query.list.borrow_mut() = init.iter().map(|pair| (pair[0].to_string(), pair[1].to_string())).collect::<Vec<_>>(); }, USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString::USVStringUSVStringRecord(init) => { // Step 3. *query.list.borrow_mut() = (*init).iter().map(|(name, value)| (name.to_string(), value.to_string())).collect::<Vec<_>>(); }, USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString::USVString(init) => { // Step 4. let init_bytes = match init.0.chars().next() { Some(first_char) if first_char == '?' => { let (_, other_bytes) = init.0.as_bytes().split_at(1); other_bytes }, _ => init.0.as_bytes(), }; *query.list.borrow_mut() = form_urlencoded::parse(init_bytes).into_owned().collect(); } } // Step 5. Ok(query) } pub fn set_list(&self, list: Vec<(String, String)>) { *self.list.borrow_mut() = list; } } impl URLSearchParamsMethods for URLSearchParams { // https://url.spec.whatwg.org/#dom-urlsearchparams-append fn Append(&self, name: USVString, value: USVString) { // Step 1. self.list.borrow_mut().push((name.0, value.0)); // Step 2. self.update_steps(); } // https://url.spec.whatwg.org/#dom-urlsearchparams-delete fn Delete(&self, name: USVString) { // Step 1. self.list.borrow_mut().retain(|&(ref k, _)| k!= &name.0); // Step 2. self.update_steps(); } // https://url.spec.whatwg.org/#dom-urlsearchparams-get fn Get(&self, name: USVString) -> Option<USVString> { let list = self.list.borrow(); list.iter() .find(|&kv| kv.0 == name.0) .map(|ref kv| USVString(kv.1.clone())) } // https://url.spec.whatwg.org/#dom-urlsearchparams-getall fn GetAll(&self, name: USVString) -> Vec<USVString> { let list = self.list.borrow(); list.iter() .filter_map(|&(ref k, ref v)| { if k == &name.0 { Some(USVString(v.clone())) } else { None } }) .collect() } // https://url.spec.whatwg.org/#dom-urlsearchparams-has fn Has(&self, name: USVString) -> bool { let list = self.list.borrow(); list.iter().any(|&(ref k, _)| k == &name.0) } // https://url.spec.whatwg.org/#dom-urlsearchparams-set fn Set(&self, name: USVString, value: USVString) { { // Step 1. let mut list = self.list.borrow_mut(); let mut index = None; let mut i = 0; list.retain(|&(ref k, _)| { if index.is_none() { if k == &name.0 { index = Some(i); } else { i += 1; } true } else { k!= &name.0 } }); match index { Some(index) => list[index].1 = value.0, None => list.push((name.0, value.0)), // Step 2. }; } // Un-borrow self.list // Step 3. self.update_steps(); } // https://url.spec.whatwg.org/#dom-urlsearchparams-sort fn Sort(&self) { // Step 1. self.list .borrow_mut() .sort_by(|(a, _), (b, _)| a.encode_utf16().cmp(b.encode_utf16())); // Step 2. self.update_steps(); } // https://url.spec.whatwg.org/#stringification-behavior fn Stringifier(&self) -> DOMString { DOMString::from(self.serialize_utf8()) } } impl URLSearchParams { // https://url.spec.whatwg.org/#concept-urlencoded-serializer pub fn serialize_utf8(&self) -> String { let list = self.list.borrow(); form_urlencoded::Serializer::new(String::new()) .extend_pairs(&*list) .finish() } // https://url.spec.whatwg.org/#concept-urlsearchparams-update fn update_steps(&self) { if let Some(url) = self.url.root() { url.set_query_pairs(&self.list.borrow()) } } } impl Iterable for URLSearchParams { type Key = USVString; type Value = USVString; fn get_iterable_length(&self) -> u32 { self.list.borrow().len() as u32 } fn get_value_at_index(&self, n: u32) -> USVString { let value = self.list.borrow()[n as usize].1.clone(); USVString(value) } fn get_key_at_index(&self, n: u32) -> USVString { let key = self.list.borrow()[n as usize].0.clone(); USVString(key) } }
pub fn new(global: &GlobalScope, url: Option<&URL>) -> DomRoot<URLSearchParams> { reflect_dom_object( Box::new(URLSearchParams::new_inherited(url)),
random_line_split
urlsearchparams.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::URLSearchParamsBinding::URLSearchParamsMethods; use crate::dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsWrap; use crate::dom::bindings::codegen::UnionTypes::USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::iterable::Iterable; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::bindings::weakref::MutableWeakRef; use crate::dom::globalscope::GlobalScope; use crate::dom::url::URL; use dom_struct::dom_struct; use url::form_urlencoded; // https://url.spec.whatwg.org/#interface-urlsearchparams #[dom_struct] pub struct URLSearchParams { reflector_: Reflector, // https://url.spec.whatwg.org/#concept-urlsearchparams-list list: DomRefCell<Vec<(String, String)>>, // https://url.spec.whatwg.org/#concept-urlsearchparams-url-object url: MutableWeakRef<URL>, } impl URLSearchParams { fn new_inherited(url: Option<&URL>) -> URLSearchParams { URLSearchParams { reflector_: Reflector::new(), list: DomRefCell::new(url.map_or(Vec::new(), |url| url.query_pairs())), url: MutableWeakRef::new(url), } } pub fn new(global: &GlobalScope, url: Option<&URL>) -> DomRoot<URLSearchParams> { reflect_dom_object( Box::new(URLSearchParams::new_inherited(url)), global, URLSearchParamsWrap, ) } // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams pub fn Constructor( global: &GlobalScope, init: USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString, ) -> Fallible<DomRoot<URLSearchParams>> { // Step 1. let query = URLSearchParams::new(global, None); match init { USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString::USVStringSequenceSequence(init) => { // Step 2. // Step 2-1. if init.iter().any(|pair| pair.len()!= 2) { return Err(Error::Type("Sequence initializer must only contain pair elements.".to_string())); } // Step 2-2. *query.list.borrow_mut() = init.iter().map(|pair| (pair[0].to_string(), pair[1].to_string())).collect::<Vec<_>>(); }, USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString::USVStringUSVStringRecord(init) => { // Step 3. *query.list.borrow_mut() = (*init).iter().map(|(name, value)| (name.to_string(), value.to_string())).collect::<Vec<_>>(); }, USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString::USVString(init) => { // Step 4. let init_bytes = match init.0.chars().next() { Some(first_char) if first_char == '?' => { let (_, other_bytes) = init.0.as_bytes().split_at(1); other_bytes }, _ => init.0.as_bytes(), }; *query.list.borrow_mut() = form_urlencoded::parse(init_bytes).into_owned().collect(); } } // Step 5. Ok(query) } pub fn set_list(&self, list: Vec<(String, String)>) { *self.list.borrow_mut() = list; } } impl URLSearchParamsMethods for URLSearchParams { // https://url.spec.whatwg.org/#dom-urlsearchparams-append fn Append(&self, name: USVString, value: USVString) { // Step 1. self.list.borrow_mut().push((name.0, value.0)); // Step 2. self.update_steps(); } // https://url.spec.whatwg.org/#dom-urlsearchparams-delete fn Delete(&self, name: USVString) { // Step 1. self.list.borrow_mut().retain(|&(ref k, _)| k!= &name.0); // Step 2. self.update_steps(); } // https://url.spec.whatwg.org/#dom-urlsearchparams-get fn Get(&self, name: USVString) -> Option<USVString> { let list = self.list.borrow(); list.iter() .find(|&kv| kv.0 == name.0) .map(|ref kv| USVString(kv.1.clone())) } // https://url.spec.whatwg.org/#dom-urlsearchparams-getall fn GetAll(&self, name: USVString) -> Vec<USVString> { let list = self.list.borrow(); list.iter() .filter_map(|&(ref k, ref v)| { if k == &name.0 { Some(USVString(v.clone())) } else { None } }) .collect() } // https://url.spec.whatwg.org/#dom-urlsearchparams-has fn
(&self, name: USVString) -> bool { let list = self.list.borrow(); list.iter().any(|&(ref k, _)| k == &name.0) } // https://url.spec.whatwg.org/#dom-urlsearchparams-set fn Set(&self, name: USVString, value: USVString) { { // Step 1. let mut list = self.list.borrow_mut(); let mut index = None; let mut i = 0; list.retain(|&(ref k, _)| { if index.is_none() { if k == &name.0 { index = Some(i); } else { i += 1; } true } else { k!= &name.0 } }); match index { Some(index) => list[index].1 = value.0, None => list.push((name.0, value.0)), // Step 2. }; } // Un-borrow self.list // Step 3. self.update_steps(); } // https://url.spec.whatwg.org/#dom-urlsearchparams-sort fn Sort(&self) { // Step 1. self.list .borrow_mut() .sort_by(|(a, _), (b, _)| a.encode_utf16().cmp(b.encode_utf16())); // Step 2. self.update_steps(); } // https://url.spec.whatwg.org/#stringification-behavior fn Stringifier(&self) -> DOMString { DOMString::from(self.serialize_utf8()) } } impl URLSearchParams { // https://url.spec.whatwg.org/#concept-urlencoded-serializer pub fn serialize_utf8(&self) -> String { let list = self.list.borrow(); form_urlencoded::Serializer::new(String::new()) .extend_pairs(&*list) .finish() } // https://url.spec.whatwg.org/#concept-urlsearchparams-update fn update_steps(&self) { if let Some(url) = self.url.root() { url.set_query_pairs(&self.list.borrow()) } } } impl Iterable for URLSearchParams { type Key = USVString; type Value = USVString; fn get_iterable_length(&self) -> u32 { self.list.borrow().len() as u32 } fn get_value_at_index(&self, n: u32) -> USVString { let value = self.list.borrow()[n as usize].1.clone(); USVString(value) } fn get_key_at_index(&self, n: u32) -> USVString { let key = self.list.borrow()[n as usize].0.clone(); USVString(key) } }
Has
identifier_name
stream.rs
use libc::c_int; use libc::c_uint; use libc::c_void; use format::format::Format; use format::sample::SampleType; use format::sample::Stream; use format::error::DriverError; use alsa::device::AlsaDevice; use alsa::device::create_error; use alsa::format::AlsaFormat; use alsa::mixer::Params; use alsa::ffi::*; pub struct AlsaStream<S: SampleType> { device: AlsaDevice, sample_rate: usize, buffer: Vec<S> } impl<F: AlsaFormat, S: SampleType<Sample=F>> AlsaStream<S> { pub fn open(device: AlsaDevice) -> Result<Self, DriverError> { let sample_rate = 44100; let params = Params::new().expect("Failed to create hw params"); params.any(&device); params.format(&device, sample_rate, S::CHANNELS as c_uint, F::FORMAT_ID); params.apply(&device); //device.setup(&mut params); let buffer_size = params.buffer_size(); params.free(); return Ok(AlsaStream { device: device, sample_rate: sample_rate as usize, buffer: Vec::new() }); } pub fn get_sample_rate(&self) -> usize { return self.sample_rate; } pub fn wait(&self) -> Result<i32, DriverError> { let mut result = 0; unsafe { result = snd_pcm_wait(self.device.get_pcm(), -1); } if result < 0 { return Err(create_error("snd_pcm_wait", result)); } else { return Ok(result); } } pub fn write_some(&self, data: &[S]) -> Result<usize, DriverError>
pub fn output(&self, data: &[S]) -> Result<usize, DriverError> { let available = data.len(); let mut written: usize = 0; while written < available { let subdata = &data[written..data.len()]; match self.write_some(subdata) { Ok(count) => written += count, Err(err) => return Err(err), } } return Ok(written); } } impl<F: AlsaFormat, S: SampleType<Sample=F>> Stream<S> for AlsaStream<S> { fn push(&mut self, frames: &[S]) { self.output(frames).expect("Failed to output to device"); } }
{ let data_ptr = data.as_ptr() as *const c_void; let frames = data.len() as snd_pcm_uframes_t; let mut size = 0; unsafe { match self.wait() { Ok(status) => size = snd_pcm_writei(self.device.get_pcm(), data_ptr, frames), Err(err) => return Err(err), } } if size < 0 { return Err(create_error("snd_pcm_writei", size as i32)); } else { return Ok(size as usize); } }
identifier_body
stream.rs
use libc::c_int; use libc::c_uint; use libc::c_void; use format::format::Format; use format::sample::SampleType; use format::sample::Stream; use format::error::DriverError; use alsa::device::AlsaDevice; use alsa::device::create_error; use alsa::format::AlsaFormat; use alsa::mixer::Params; use alsa::ffi::*; pub struct AlsaStream<S: SampleType> { device: AlsaDevice, sample_rate: usize, buffer: Vec<S> } impl<F: AlsaFormat, S: SampleType<Sample=F>> AlsaStream<S> { pub fn open(device: AlsaDevice) -> Result<Self, DriverError> { let sample_rate = 44100; let params = Params::new().expect("Failed to create hw params"); params.any(&device); params.format(&device, sample_rate, S::CHANNELS as c_uint, F::FORMAT_ID); params.apply(&device); //device.setup(&mut params); let buffer_size = params.buffer_size(); params.free(); return Ok(AlsaStream { device: device, sample_rate: sample_rate as usize, buffer: Vec::new() }); } pub fn get_sample_rate(&self) -> usize { return self.sample_rate; } pub fn wait(&self) -> Result<i32, DriverError> { let mut result = 0; unsafe { result = snd_pcm_wait(self.device.get_pcm(), -1); } if result < 0 { return Err(create_error("snd_pcm_wait", result)); } else { return Ok(result); } } pub fn write_some(&self, data: &[S]) -> Result<usize, DriverError> { let data_ptr = data.as_ptr() as *const c_void; let frames = data.len() as snd_pcm_uframes_t; let mut size = 0; unsafe { match self.wait() { Ok(status) => size = snd_pcm_writei(self.device.get_pcm(), data_ptr, frames), Err(err) => return Err(err), } } if size < 0 { return Err(create_error("snd_pcm_writei", size as i32)); } else { return Ok(size as usize); } } pub fn output(&self, data: &[S]) -> Result<usize, DriverError> { let available = data.len(); let mut written: usize = 0; while written < available { let subdata = &data[written..data.len()]; match self.write_some(subdata) { Ok(count) => written += count, Err(err) => return Err(err), }
} impl<F: AlsaFormat, S: SampleType<Sample=F>> Stream<S> for AlsaStream<S> { fn push(&mut self, frames: &[S]) { self.output(frames).expect("Failed to output to device"); } }
} return Ok(written); }
random_line_split
stream.rs
use libc::c_int; use libc::c_uint; use libc::c_void; use format::format::Format; use format::sample::SampleType; use format::sample::Stream; use format::error::DriverError; use alsa::device::AlsaDevice; use alsa::device::create_error; use alsa::format::AlsaFormat; use alsa::mixer::Params; use alsa::ffi::*; pub struct AlsaStream<S: SampleType> { device: AlsaDevice, sample_rate: usize, buffer: Vec<S> } impl<F: AlsaFormat, S: SampleType<Sample=F>> AlsaStream<S> { pub fn
(device: AlsaDevice) -> Result<Self, DriverError> { let sample_rate = 44100; let params = Params::new().expect("Failed to create hw params"); params.any(&device); params.format(&device, sample_rate, S::CHANNELS as c_uint, F::FORMAT_ID); params.apply(&device); //device.setup(&mut params); let buffer_size = params.buffer_size(); params.free(); return Ok(AlsaStream { device: device, sample_rate: sample_rate as usize, buffer: Vec::new() }); } pub fn get_sample_rate(&self) -> usize { return self.sample_rate; } pub fn wait(&self) -> Result<i32, DriverError> { let mut result = 0; unsafe { result = snd_pcm_wait(self.device.get_pcm(), -1); } if result < 0 { return Err(create_error("snd_pcm_wait", result)); } else { return Ok(result); } } pub fn write_some(&self, data: &[S]) -> Result<usize, DriverError> { let data_ptr = data.as_ptr() as *const c_void; let frames = data.len() as snd_pcm_uframes_t; let mut size = 0; unsafe { match self.wait() { Ok(status) => size = snd_pcm_writei(self.device.get_pcm(), data_ptr, frames), Err(err) => return Err(err), } } if size < 0 { return Err(create_error("snd_pcm_writei", size as i32)); } else { return Ok(size as usize); } } pub fn output(&self, data: &[S]) -> Result<usize, DriverError> { let available = data.len(); let mut written: usize = 0; while written < available { let subdata = &data[written..data.len()]; match self.write_some(subdata) { Ok(count) => written += count, Err(err) => return Err(err), } } return Ok(written); } } impl<F: AlsaFormat, S: SampleType<Sample=F>> Stream<S> for AlsaStream<S> { fn push(&mut self, frames: &[S]) { self.output(frames).expect("Failed to output to device"); } }
open
identifier_name
bvlist.rs
use bap::high::bitvector::BitVector; use holmes::pg::dyn::values::{ValueT, ToValue}; use holmes::pg::dyn::types::TypeT; use postgres::types::{ToSql, IsNull}; use postgres_array::Array; use holmes::pg::RowIter; use holmes::pg::dyn::{Type, Value}; use bit_vec::BitVec; use std::any::Any; use std::sync::Arc; #[derive(Debug, Clone, Hash, PartialOrd, PartialEq)] pub struct BVList(pub Vec<BitVector>); impl ::std::fmt::Display for BVList { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::result::Result<(), ::std::fmt::Error>
} #[derive(Debug, Clone, Hash, PartialEq)] pub struct BVListType; impl TypeT for BVListType { fn name(&self) -> Option<&'static str> { Some("bvlist") } fn extract(&self, rows: &mut RowIter) -> Option<Value> { let raw: Array<BitVec> = rows.next().unwrap(); Some(Arc::new( BVList(raw.iter().map(|bv| BitVector::new(bv)).collect()), )) } fn repr(&self) -> &'static str { "bit varying[] not null" } typet_boiler!(); } impl ValueT for BVList { fn type_(&self) -> Type { Arc::new(BVListType) } fn get(&self) -> &Any { self as &Any } fn to_sql(&self) -> Vec<&ToSql> { vec![self] } valuet_boiler!(); } impl ToSql for BVList { accepts!(::postgres::types::VARBIT_ARRAY); to_sql_checked!(); fn to_sql( &self, ty: &::postgres::types::Type, out: &mut Vec<u8>, ) -> ::std::result::Result<IsNull, Box<::std::error::Error + Send + Sync>> { let med: Array<&BitVec> = Array::from_vec(self.0.iter().map(|bv| bv.to_bitvec()).collect(), 0); med.to_sql(ty, out) } } impl ToValue for BVList { fn to_value(self) -> Value { Arc::new(self) } }
{ use std::fmt::Debug; self.0.fmt(f) }
identifier_body
bvlist.rs
use bap::high::bitvector::BitVector; use holmes::pg::dyn::values::{ValueT, ToValue}; use holmes::pg::dyn::types::TypeT; use postgres::types::{ToSql, IsNull}; use postgres_array::Array; use holmes::pg::RowIter; use holmes::pg::dyn::{Type, Value}; use bit_vec::BitVec; use std::any::Any; use std::sync::Arc; #[derive(Debug, Clone, Hash, PartialOrd, PartialEq)] pub struct BVList(pub Vec<BitVector>); impl ::std::fmt::Display for BVList { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::result::Result<(), ::std::fmt::Error> { use std::fmt::Debug; self.0.fmt(f) } } #[derive(Debug, Clone, Hash, PartialEq)] pub struct BVListType; impl TypeT for BVListType { fn name(&self) -> Option<&'static str> { Some("bvlist") } fn extract(&self, rows: &mut RowIter) -> Option<Value> { let raw: Array<BitVec> = rows.next().unwrap(); Some(Arc::new( BVList(raw.iter().map(|bv| BitVector::new(bv)).collect()), )) } fn repr(&self) -> &'static str { "bit varying[] not null" } typet_boiler!(); } impl ValueT for BVList { fn type_(&self) -> Type { Arc::new(BVListType) } fn get(&self) -> &Any { self as &Any
vec![self] } valuet_boiler!(); } impl ToSql for BVList { accepts!(::postgres::types::VARBIT_ARRAY); to_sql_checked!(); fn to_sql( &self, ty: &::postgres::types::Type, out: &mut Vec<u8>, ) -> ::std::result::Result<IsNull, Box<::std::error::Error + Send + Sync>> { let med: Array<&BitVec> = Array::from_vec(self.0.iter().map(|bv| bv.to_bitvec()).collect(), 0); med.to_sql(ty, out) } } impl ToValue for BVList { fn to_value(self) -> Value { Arc::new(self) } }
} fn to_sql(&self) -> Vec<&ToSql> {
random_line_split
bvlist.rs
use bap::high::bitvector::BitVector; use holmes::pg::dyn::values::{ValueT, ToValue}; use holmes::pg::dyn::types::TypeT; use postgres::types::{ToSql, IsNull}; use postgres_array::Array; use holmes::pg::RowIter; use holmes::pg::dyn::{Type, Value}; use bit_vec::BitVec; use std::any::Any; use std::sync::Arc; #[derive(Debug, Clone, Hash, PartialOrd, PartialEq)] pub struct BVList(pub Vec<BitVector>); impl ::std::fmt::Display for BVList { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::result::Result<(), ::std::fmt::Error> { use std::fmt::Debug; self.0.fmt(f) } } #[derive(Debug, Clone, Hash, PartialEq)] pub struct BVListType; impl TypeT for BVListType { fn name(&self) -> Option<&'static str> { Some("bvlist") } fn extract(&self, rows: &mut RowIter) -> Option<Value> { let raw: Array<BitVec> = rows.next().unwrap(); Some(Arc::new( BVList(raw.iter().map(|bv| BitVector::new(bv)).collect()), )) } fn repr(&self) -> &'static str { "bit varying[] not null" } typet_boiler!(); } impl ValueT for BVList { fn
(&self) -> Type { Arc::new(BVListType) } fn get(&self) -> &Any { self as &Any } fn to_sql(&self) -> Vec<&ToSql> { vec![self] } valuet_boiler!(); } impl ToSql for BVList { accepts!(::postgres::types::VARBIT_ARRAY); to_sql_checked!(); fn to_sql( &self, ty: &::postgres::types::Type, out: &mut Vec<u8>, ) -> ::std::result::Result<IsNull, Box<::std::error::Error + Send + Sync>> { let med: Array<&BitVec> = Array::from_vec(self.0.iter().map(|bv| bv.to_bitvec()).collect(), 0); med.to_sql(ty, out) } } impl ToValue for BVList { fn to_value(self) -> Value { Arc::new(self) } }
type_
identifier_name