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
combine.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. /////////////////////////////////////////////////////////////////////////// // # Type combining // // There are four type combiners: equate, sub, lub, and glb. Each // implements the trait `Combine` and contains methods for combining // two instances of various things and yielding a new instance. These // combiner methods always yield a `Result<T>`. There is a lot of // common code for these operations, implemented as default methods on // the `Combine` trait. // // Each operation may have side-effects on the inference context, // though these can be unrolled using snapshots. On success, the // LUB/GLB operations return the appropriate bound. The Eq and Sub // operations generally return the first operand. // // ## Contravariance // // When you are relating two things which have a contravariant // relationship, you should use `contratys()` or `contraregions()`, // rather than inversing the order of arguments! This is necessary // because the order of arguments is not relevant for LUB and GLB. It // is also useful to track which value is the "expected" value in // terms of error reporting. use super::bivariate::Bivariate; use super::equate::Equate; use super::glb::Glb; use super::lub::Lub; use super::sub::Sub; use super::{InferCtxt}; use super::{MiscVariable, TypeTrace}; use super::type_variable::{RelationDir, BiTo, EqTo, SubtypeOf, SupertypeOf}; use middle::ty::{TyVar}; use middle::ty::{IntType, UintType}; use middle::ty::{self, Ty}; use middle::ty_fold; use middle::ty_fold::{TypeFolder, TypeFoldable}; use middle::ty_relate::{self, Relate, RelateResult, TypeRelation}; use util::ppaux::Repr; use syntax::ast; use syntax::codemap::Span; #[derive(Clone)] pub struct CombineFields<'a, 'tcx: 'a> { pub infcx: &'a InferCtxt<'a, 'tcx>, pub a_is_expected: bool, pub trace: TypeTrace<'tcx>, } pub fn super_combine_tys<'a,'tcx:'a,R>(infcx: &InferCtxt<'a, 'tcx>, relation: &mut R, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> where R: TypeRelation<'a,'tcx> { let a_is_expected = relation.a_is_expected(); match (&a.sty, &b.sty) { // Relate integral variables to other types (&ty::TyInfer(ty::IntVar(a_id)), &ty::TyInfer(ty::IntVar(b_id))) => { try!(infcx.int_unification_table .borrow_mut() .unify_var_var(a_id, b_id) .map_err(|e| int_unification_error(a_is_expected, e))); Ok(a) } (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyInt(v)) => { unify_integral_variable(infcx, a_is_expected, v_id, IntType(v)) } (&ty::TyInt(v), &ty::TyInfer(ty::IntVar(v_id))) => { unify_integral_variable(infcx,!a_is_expected, v_id, IntType(v)) } (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyUint(v)) => { unify_integral_variable(infcx, a_is_expected, v_id, UintType(v)) } (&ty::TyUint(v), &ty::TyInfer(ty::IntVar(v_id))) => { unify_integral_variable(infcx,!a_is_expected, v_id, UintType(v)) } // Relate floating-point variables to other types (&ty::TyInfer(ty::FloatVar(a_id)), &ty::TyInfer(ty::FloatVar(b_id))) => { try!(infcx.float_unification_table .borrow_mut() .unify_var_var(a_id, b_id) .map_err(|e| float_unification_error(relation.a_is_expected(), e))); Ok(a) } (&ty::TyInfer(ty::FloatVar(v_id)), &ty::TyFloat(v)) => { unify_float_variable(infcx, a_is_expected, v_id, v) } (&ty::TyFloat(v), &ty::TyInfer(ty::FloatVar(v_id))) => { unify_float_variable(infcx,!a_is_expected, v_id, v) } // All other cases of inference are errors (&ty::TyInfer(_), _) | (_, &ty::TyInfer(_)) => { Err(ty::terr_sorts(ty_relate::expected_found(relation, &a, &b))) } _ => { ty_relate::super_relate_tys(relation, a, b) } } } fn unify_integral_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, vid_is_expected: bool, vid: ty::IntVid, val: ty::IntVarValue) -> RelateResult<'tcx, Ty<'tcx>> { try!(infcx .int_unification_table .borrow_mut() .unify_var_value(vid, val) .map_err(|e| int_unification_error(vid_is_expected, e))); match val { IntType(v) => Ok(ty::mk_mach_int(infcx.tcx, v)), UintType(v) => Ok(ty::mk_mach_uint(infcx.tcx, v)), } } fn unify_float_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, vid_is_expected: bool, vid: ty::FloatVid, val: ast::FloatTy) -> RelateResult<'tcx, Ty<'tcx>> { try!(infcx .float_unification_table .borrow_mut() .unify_var_value(vid, val) .map_err(|e| float_unification_error(vid_is_expected, e))); Ok(ty::mk_mach_float(infcx.tcx, val)) } impl<'a, 'tcx> CombineFields<'a, 'tcx> { pub fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.infcx.tcx } pub fn switch_expected(&self) -> CombineFields<'a, 'tcx> { CombineFields { a_is_expected:!self.a_is_expected, ..(*self).clone() } } pub fn equate(&self) -> Equate<'a, 'tcx> { Equate::new(self.clone()) } pub fn bivariate(&self) -> Bivariate<'a, 'tcx> { Bivariate::new(self.clone()) } pub fn sub(&self) -> Sub<'a, 'tcx> { Sub::new(self.clone()) } pub fn lub(&self) -> Lub<'a, 'tcx>
pub fn glb(&self) -> Glb<'a, 'tcx> { Glb::new(self.clone()) } pub fn instantiate(&self, a_ty: Ty<'tcx>, dir: RelationDir, b_vid: ty::TyVid) -> RelateResult<'tcx, ()> { let tcx = self.infcx.tcx; let mut stack = Vec::new(); stack.push((a_ty, dir, b_vid)); loop { // For each turn of the loop, we extract a tuple // // (a_ty, dir, b_vid) // // to relate. Here dir is either SubtypeOf or // SupertypeOf. The idea is that we should ensure that // the type `a_ty` is a subtype or supertype (respectively) of the // type to which `b_vid` is bound. // // If `b_vid` has not yet been instantiated with a type // (which is always true on the first iteration, but not // necessarily true on later iterations), we will first // instantiate `b_vid` with a *generalized* version of // `a_ty`. Generalization introduces other inference // variables wherever subtyping could occur (at time of // this writing, this means replacing free regions with // region variables). let (a_ty, dir, b_vid) = match stack.pop() { None => break, Some(e) => e, }; debug!("instantiate(a_ty={} dir={:?} b_vid={})", a_ty.repr(tcx), dir, b_vid.repr(tcx)); // Check whether `vid` has been instantiated yet. If not, // make a generalized form of `ty` and instantiate with // that. let b_ty = self.infcx.type_variables.borrow().probe(b_vid); let b_ty = match b_ty { Some(t) => t, //...already instantiated. None => { //...not yet instantiated: // Generalize type if necessary. let generalized_ty = try!(match dir { EqTo => self.generalize(a_ty, b_vid, false), BiTo | SupertypeOf | SubtypeOf => self.generalize(a_ty, b_vid, true), }); debug!("instantiate(a_ty={}, dir={:?}, \ b_vid={}, generalized_ty={})", a_ty.repr(tcx), dir, b_vid.repr(tcx), generalized_ty.repr(tcx)); self.infcx.type_variables .borrow_mut() .instantiate_and_push( b_vid, generalized_ty, &mut stack); generalized_ty } }; // The original triple was `(a_ty, dir, b_vid)` -- now we have // resolved `b_vid` to `b_ty`, so apply `(a_ty, dir, b_ty)`: // // FIXME(#16847): This code is non-ideal because all these subtype // relations wind up attributed to the same spans. We need // to associate causes/spans with each of the relations in // the stack to get this right. try!(match dir { BiTo => self.bivariate().relate(&a_ty, &b_ty), EqTo => self.equate().relate(&a_ty, &b_ty), SubtypeOf => self.sub().relate(&a_ty, &b_ty), SupertypeOf => self.sub().relate_with_variance(ty::Contravariant, &a_ty, &b_ty), }); } Ok(()) } /// Attempts to generalize `ty` for the type variable `for_vid`. This checks for cycle -- that /// is, whether the type `ty` references `for_vid`. If `make_region_vars` is true, it will also /// replace all regions with fresh variables. Returns `TyError` in the case of a cycle, `Ok` /// otherwise. fn generalize(&self, ty: Ty<'tcx>, for_vid: ty::TyVid, make_region_vars: bool) -> RelateResult<'tcx, Ty<'tcx>> { let mut generalize = Generalizer { infcx: self.infcx, span: self.trace.origin.span(), for_vid: for_vid, make_region_vars: make_region_vars, cycle_detected: false }; let u = ty.fold_with(&mut generalize); if generalize.cycle_detected { Err(ty::terr_cyclic_ty) } else { Ok(u) } } } struct Generalizer<'cx, 'tcx:'cx> { infcx: &'cx InferCtxt<'cx, 'tcx>, span: Span, for_vid: ty::TyVid, make_region_vars: bool, cycle_detected: bool, } impl<'cx, 'tcx> ty_fold::TypeFolder<'tcx> for Generalizer<'cx, 'tcx> { fn tcx(&self) -> &ty::ctxt<'tcx> { self.infcx.tcx } fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { // Check to see whether the type we are genealizing references // `vid`. At the same time, also update any type variables to // the values that they are bound to. This is needed to truly // check for cycles, but also just makes things readable. // // (In particular, you could have something like `$0 = Box<$1>` // where `$1` has already been instantiated with `Box<$0>`) match t.sty { ty::TyInfer(ty::TyVar(vid)) => { if vid == self.for_vid { self.cycle_detected = true; self.tcx().types.err } else { match self.infcx.type_variables.borrow().probe(vid) { Some(u) => self.fold_ty(u), None => t, } } } _ => { ty_fold::super_fold_ty(self, t) } } } fn fold_region(&mut self, r: ty::Region) -> ty::Region { match r { // Never make variables for regions bound within the type itself. ty::ReLateBound(..) => { return r; } // Early-bound regions should really have been substituted away before // we get to this point. ty::ReEarlyBound(..) => { self.tcx().sess.span_bug( self.span, &format!("Encountered early bound region when generalizing: {}", r.repr(self.tcx()))); } // Always make a fresh region variable for skolemized regions; // the higher-ranked decision procedures rely on this. ty::ReInfer(ty::ReSkolemized(..)) => { } // For anything else, we make a region variable, unless we // are *equating*, in which case it's just wasteful. ty::ReEmpty | ty::ReStatic | ty::ReScope(..) | ty::ReInfer(ty::ReVar(..)) | ty::ReFree(..) => { if!self.make_region_vars { return r; } } } // FIXME: This is non-ideal because we don't give a // very descriptive origin for this region variable. self.infcx.next_region_var(MiscVariable(self.span)) } } pub trait RelateResultCompare<'tcx, T> { fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where F: FnOnce() -> ty::type_err<'tcx>; } impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> { fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where F: FnOnce() -> ty::type_err<'tcx>, { self.clone().and_then(|s| { if s == t { self.clone() } else { Err(f()) } }) } } fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue)) -> ty::type_err<'tcx> { let (a, b) = v; ty::terr_int_mismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b)) } fn float_unification_error<'tcx>(a_is_expected: bool, v: (ast::FloatTy, ast::FloatTy)) -> ty::type_err<'tcx> { let (a, b) = v; ty::terr_float_mismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b)) }
{ Lub::new(self.clone()) }
identifier_body
combine.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. /////////////////////////////////////////////////////////////////////////// // # Type combining // // There are four type combiners: equate, sub, lub, and glb. Each // implements the trait `Combine` and contains methods for combining // two instances of various things and yielding a new instance. These // combiner methods always yield a `Result<T>`. There is a lot of // common code for these operations, implemented as default methods on // the `Combine` trait. // // Each operation may have side-effects on the inference context, // though these can be unrolled using snapshots. On success, the // LUB/GLB operations return the appropriate bound. The Eq and Sub // operations generally return the first operand. // // ## Contravariance // // When you are relating two things which have a contravariant // relationship, you should use `contratys()` or `contraregions()`, // rather than inversing the order of arguments! This is necessary // because the order of arguments is not relevant for LUB and GLB. It // is also useful to track which value is the "expected" value in // terms of error reporting. use super::bivariate::Bivariate; use super::equate::Equate; use super::glb::Glb; use super::lub::Lub; use super::sub::Sub; use super::{InferCtxt}; use super::{MiscVariable, TypeTrace}; use super::type_variable::{RelationDir, BiTo, EqTo, SubtypeOf, SupertypeOf}; use middle::ty::{TyVar}; use middle::ty::{IntType, UintType}; use middle::ty::{self, Ty}; use middle::ty_fold; use middle::ty_fold::{TypeFolder, TypeFoldable}; use middle::ty_relate::{self, Relate, RelateResult, TypeRelation}; use util::ppaux::Repr; use syntax::ast; use syntax::codemap::Span; #[derive(Clone)] pub struct CombineFields<'a, 'tcx: 'a> { pub infcx: &'a InferCtxt<'a, 'tcx>, pub a_is_expected: bool, pub trace: TypeTrace<'tcx>, } pub fn super_combine_tys<'a,'tcx:'a,R>(infcx: &InferCtxt<'a, 'tcx>, relation: &mut R, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> where R: TypeRelation<'a,'tcx> { let a_is_expected = relation.a_is_expected(); match (&a.sty, &b.sty) { // Relate integral variables to other types (&ty::TyInfer(ty::IntVar(a_id)), &ty::TyInfer(ty::IntVar(b_id))) => { try!(infcx.int_unification_table .borrow_mut() .unify_var_var(a_id, b_id) .map_err(|e| int_unification_error(a_is_expected, e))); Ok(a) } (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyInt(v)) => { unify_integral_variable(infcx, a_is_expected, v_id, IntType(v)) } (&ty::TyInt(v), &ty::TyInfer(ty::IntVar(v_id))) => { unify_integral_variable(infcx,!a_is_expected, v_id, IntType(v)) } (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyUint(v)) => { unify_integral_variable(infcx, a_is_expected, v_id, UintType(v)) } (&ty::TyUint(v), &ty::TyInfer(ty::IntVar(v_id))) => { unify_integral_variable(infcx,!a_is_expected, v_id, UintType(v)) } // Relate floating-point variables to other types (&ty::TyInfer(ty::FloatVar(a_id)), &ty::TyInfer(ty::FloatVar(b_id))) => { try!(infcx.float_unification_table .borrow_mut() .unify_var_var(a_id, b_id) .map_err(|e| float_unification_error(relation.a_is_expected(), e))); Ok(a) } (&ty::TyInfer(ty::FloatVar(v_id)), &ty::TyFloat(v)) => { unify_float_variable(infcx, a_is_expected, v_id, v) } (&ty::TyFloat(v), &ty::TyInfer(ty::FloatVar(v_id))) => { unify_float_variable(infcx,!a_is_expected, v_id, v) } // All other cases of inference are errors (&ty::TyInfer(_), _) | (_, &ty::TyInfer(_)) => { Err(ty::terr_sorts(ty_relate::expected_found(relation, &a, &b))) } _ => { ty_relate::super_relate_tys(relation, a, b) } } } fn unify_integral_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, vid_is_expected: bool, vid: ty::IntVid, val: ty::IntVarValue) -> RelateResult<'tcx, Ty<'tcx>> { try!(infcx .int_unification_table .borrow_mut() .unify_var_value(vid, val) .map_err(|e| int_unification_error(vid_is_expected, e))); match val { IntType(v) => Ok(ty::mk_mach_int(infcx.tcx, v)), UintType(v) => Ok(ty::mk_mach_uint(infcx.tcx, v)), } } fn unify_float_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, vid_is_expected: bool, vid: ty::FloatVid, val: ast::FloatTy) -> RelateResult<'tcx, Ty<'tcx>> { try!(infcx .float_unification_table .borrow_mut() .unify_var_value(vid, val) .map_err(|e| float_unification_error(vid_is_expected, e))); Ok(ty::mk_mach_float(infcx.tcx, val)) } impl<'a, 'tcx> CombineFields<'a, 'tcx> { pub fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.infcx.tcx } pub fn switch_expected(&self) -> CombineFields<'a, 'tcx> { CombineFields { a_is_expected:!self.a_is_expected, ..(*self).clone() } } pub fn equate(&self) -> Equate<'a, 'tcx> { Equate::new(self.clone()) } pub fn bivariate(&self) -> Bivariate<'a, 'tcx> { Bivariate::new(self.clone()) } pub fn sub(&self) -> Sub<'a, 'tcx> { Sub::new(self.clone()) } pub fn lub(&self) -> Lub<'a, 'tcx> { Lub::new(self.clone()) } pub fn glb(&self) -> Glb<'a, 'tcx> { Glb::new(self.clone()) } pub fn instantiate(&self, a_ty: Ty<'tcx>, dir: RelationDir, b_vid: ty::TyVid) -> RelateResult<'tcx, ()> { let tcx = self.infcx.tcx; let mut stack = Vec::new(); stack.push((a_ty, dir, b_vid)); loop { // For each turn of the loop, we extract a tuple // // (a_ty, dir, b_vid) // // to relate. Here dir is either SubtypeOf or // SupertypeOf. The idea is that we should ensure that // the type `a_ty` is a subtype or supertype (respectively) of the // type to which `b_vid` is bound. // // If `b_vid` has not yet been instantiated with a type // (which is always true on the first iteration, but not // necessarily true on later iterations), we will first // instantiate `b_vid` with a *generalized* version of // `a_ty`. Generalization introduces other inference // variables wherever subtyping could occur (at time of // this writing, this means replacing free regions with // region variables). let (a_ty, dir, b_vid) = match stack.pop() { None => break, Some(e) => e, }; debug!("instantiate(a_ty={} dir={:?} b_vid={})", a_ty.repr(tcx), dir, b_vid.repr(tcx)); // Check whether `vid` has been instantiated yet. If not, // make a generalized form of `ty` and instantiate with // that. let b_ty = self.infcx.type_variables.borrow().probe(b_vid); let b_ty = match b_ty { Some(t) => t, //...already instantiated. None => { //...not yet instantiated: // Generalize type if necessary. let generalized_ty = try!(match dir { EqTo => self.generalize(a_ty, b_vid, false), BiTo | SupertypeOf | SubtypeOf => self.generalize(a_ty, b_vid, true), }); debug!("instantiate(a_ty={}, dir={:?}, \ b_vid={}, generalized_ty={})", a_ty.repr(tcx), dir, b_vid.repr(tcx), generalized_ty.repr(tcx)); self.infcx.type_variables .borrow_mut() .instantiate_and_push( b_vid, generalized_ty, &mut stack); generalized_ty } }; // The original triple was `(a_ty, dir, b_vid)` -- now we have // resolved `b_vid` to `b_ty`, so apply `(a_ty, dir, b_ty)`: // // FIXME(#16847): This code is non-ideal because all these subtype // relations wind up attributed to the same spans. We need // to associate causes/spans with each of the relations in // the stack to get this right. try!(match dir { BiTo => self.bivariate().relate(&a_ty, &b_ty), EqTo => self.equate().relate(&a_ty, &b_ty), SubtypeOf => self.sub().relate(&a_ty, &b_ty), SupertypeOf => self.sub().relate_with_variance(ty::Contravariant, &a_ty, &b_ty), }); } Ok(()) } /// Attempts to generalize `ty` for the type variable `for_vid`. This checks for cycle -- that /// is, whether the type `ty` references `for_vid`. If `make_region_vars` is true, it will also /// replace all regions with fresh variables. Returns `TyError` in the case of a cycle, `Ok` /// otherwise. fn generalize(&self, ty: Ty<'tcx>, for_vid: ty::TyVid, make_region_vars: bool) -> RelateResult<'tcx, Ty<'tcx>> { let mut generalize = Generalizer { infcx: self.infcx, span: self.trace.origin.span(), for_vid: for_vid, make_region_vars: make_region_vars, cycle_detected: false }; let u = ty.fold_with(&mut generalize); if generalize.cycle_detected { Err(ty::terr_cyclic_ty) } else { Ok(u) } } } struct Generalizer<'cx, 'tcx:'cx> { infcx: &'cx InferCtxt<'cx, 'tcx>, span: Span, for_vid: ty::TyVid, make_region_vars: bool, cycle_detected: bool, } impl<'cx, 'tcx> ty_fold::TypeFolder<'tcx> for Generalizer<'cx, 'tcx> { fn tcx(&self) -> &ty::ctxt<'tcx> { self.infcx.tcx } fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { // Check to see whether the type we are genealizing references // `vid`. At the same time, also update any type variables to // the values that they are bound to. This is needed to truly // check for cycles, but also just makes things readable. // // (In particular, you could have something like `$0 = Box<$1>` // where `$1` has already been instantiated with `Box<$0>`) match t.sty { ty::TyInfer(ty::TyVar(vid)) => { if vid == self.for_vid { self.cycle_detected = true; self.tcx().types.err } else { match self.infcx.type_variables.borrow().probe(vid) { Some(u) => self.fold_ty(u), None => t, } } } _ => { ty_fold::super_fold_ty(self, t) } } } fn fold_region(&mut self, r: ty::Region) -> ty::Region { match r { // Never make variables for regions bound within the type itself. ty::ReLateBound(..) => { return r; } // Early-bound regions should really have been substituted away before // we get to this point. ty::ReEarlyBound(..) => { self.tcx().sess.span_bug( self.span, &format!("Encountered early bound region when generalizing: {}", r.repr(self.tcx()))); } // Always make a fresh region variable for skolemized regions; // the higher-ranked decision procedures rely on this. ty::ReInfer(ty::ReSkolemized(..)) => { } // For anything else, we make a region variable, unless we // are *equating*, in which case it's just wasteful. ty::ReEmpty | ty::ReStatic | ty::ReScope(..) | ty::ReInfer(ty::ReVar(..)) | ty::ReFree(..) => { if!self.make_region_vars { return r; } } } // FIXME: This is non-ideal because we don't give a // very descriptive origin for this region variable. self.infcx.next_region_var(MiscVariable(self.span)) } } pub trait RelateResultCompare<'tcx, T> { fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where F: FnOnce() -> ty::type_err<'tcx>; } impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> { fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where F: FnOnce() -> ty::type_err<'tcx>, { self.clone().and_then(|s| { if s == t { self.clone() } else
}) } } fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue)) -> ty::type_err<'tcx> { let (a, b) = v; ty::terr_int_mismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b)) } fn float_unification_error<'tcx>(a_is_expected: bool, v: (ast::FloatTy, ast::FloatTy)) -> ty::type_err<'tcx> { let (a, b) = v; ty::terr_float_mismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b)) }
{ Err(f()) }
conditional_block
combine.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. /////////////////////////////////////////////////////////////////////////// // # Type combining // // There are four type combiners: equate, sub, lub, and glb. Each // implements the trait `Combine` and contains methods for combining // two instances of various things and yielding a new instance. These // combiner methods always yield a `Result<T>`. There is a lot of // common code for these operations, implemented as default methods on // the `Combine` trait. // // Each operation may have side-effects on the inference context, // though these can be unrolled using snapshots. On success, the // LUB/GLB operations return the appropriate bound. The Eq and Sub // operations generally return the first operand. // // ## Contravariance // // When you are relating two things which have a contravariant // relationship, you should use `contratys()` or `contraregions()`, // rather than inversing the order of arguments! This is necessary // because the order of arguments is not relevant for LUB and GLB. It // is also useful to track which value is the "expected" value in // terms of error reporting. use super::bivariate::Bivariate; use super::equate::Equate; use super::glb::Glb; use super::lub::Lub; use super::sub::Sub; use super::{InferCtxt}; use super::{MiscVariable, TypeTrace}; use super::type_variable::{RelationDir, BiTo, EqTo, SubtypeOf, SupertypeOf}; use middle::ty::{TyVar}; use middle::ty::{IntType, UintType}; use middle::ty::{self, Ty}; use middle::ty_fold; use middle::ty_fold::{TypeFolder, TypeFoldable}; use middle::ty_relate::{self, Relate, RelateResult, TypeRelation}; use util::ppaux::Repr; use syntax::ast; use syntax::codemap::Span; #[derive(Clone)] pub struct CombineFields<'a, 'tcx: 'a> { pub infcx: &'a InferCtxt<'a, 'tcx>, pub a_is_expected: bool, pub trace: TypeTrace<'tcx>, } pub fn super_combine_tys<'a,'tcx:'a,R>(infcx: &InferCtxt<'a, 'tcx>, relation: &mut R, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> where R: TypeRelation<'a,'tcx> { let a_is_expected = relation.a_is_expected(); match (&a.sty, &b.sty) { // Relate integral variables to other types (&ty::TyInfer(ty::IntVar(a_id)), &ty::TyInfer(ty::IntVar(b_id))) => { try!(infcx.int_unification_table .borrow_mut() .unify_var_var(a_id, b_id) .map_err(|e| int_unification_error(a_is_expected, e))); Ok(a) } (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyInt(v)) => { unify_integral_variable(infcx, a_is_expected, v_id, IntType(v)) } (&ty::TyInt(v), &ty::TyInfer(ty::IntVar(v_id))) => { unify_integral_variable(infcx,!a_is_expected, v_id, IntType(v)) } (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyUint(v)) => { unify_integral_variable(infcx, a_is_expected, v_id, UintType(v)) } (&ty::TyUint(v), &ty::TyInfer(ty::IntVar(v_id))) => { unify_integral_variable(infcx,!a_is_expected, v_id, UintType(v)) } // Relate floating-point variables to other types (&ty::TyInfer(ty::FloatVar(a_id)), &ty::TyInfer(ty::FloatVar(b_id))) => { try!(infcx.float_unification_table .borrow_mut() .unify_var_var(a_id, b_id) .map_err(|e| float_unification_error(relation.a_is_expected(), e))); Ok(a) } (&ty::TyInfer(ty::FloatVar(v_id)), &ty::TyFloat(v)) => { unify_float_variable(infcx, a_is_expected, v_id, v) } (&ty::TyFloat(v), &ty::TyInfer(ty::FloatVar(v_id))) => { unify_float_variable(infcx,!a_is_expected, v_id, v) } // All other cases of inference are errors (&ty::TyInfer(_), _) | (_, &ty::TyInfer(_)) => { Err(ty::terr_sorts(ty_relate::expected_found(relation, &a, &b))) } _ => { ty_relate::super_relate_tys(relation, a, b) } } } fn unify_integral_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, vid_is_expected: bool, vid: ty::IntVid, val: ty::IntVarValue) -> RelateResult<'tcx, Ty<'tcx>> { try!(infcx .int_unification_table .borrow_mut() .unify_var_value(vid, val) .map_err(|e| int_unification_error(vid_is_expected, e))); match val { IntType(v) => Ok(ty::mk_mach_int(infcx.tcx, v)), UintType(v) => Ok(ty::mk_mach_uint(infcx.tcx, v)), } } fn unify_float_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, vid_is_expected: bool, vid: ty::FloatVid, val: ast::FloatTy) -> RelateResult<'tcx, Ty<'tcx>> { try!(infcx .float_unification_table .borrow_mut() .unify_var_value(vid, val) .map_err(|e| float_unification_error(vid_is_expected, e))); Ok(ty::mk_mach_float(infcx.tcx, val)) } impl<'a, 'tcx> CombineFields<'a, 'tcx> { pub fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.infcx.tcx } pub fn switch_expected(&self) -> CombineFields<'a, 'tcx> { CombineFields { a_is_expected:!self.a_is_expected, ..(*self).clone() } } pub fn equate(&self) -> Equate<'a, 'tcx> { Equate::new(self.clone()) } pub fn bivariate(&self) -> Bivariate<'a, 'tcx> { Bivariate::new(self.clone()) } pub fn sub(&self) -> Sub<'a, 'tcx> { Sub::new(self.clone()) } pub fn lub(&self) -> Lub<'a, 'tcx> { Lub::new(self.clone()) } pub fn glb(&self) -> Glb<'a, 'tcx> { Glb::new(self.clone()) } pub fn instantiate(&self, a_ty: Ty<'tcx>, dir: RelationDir, b_vid: ty::TyVid) -> RelateResult<'tcx, ()> { let tcx = self.infcx.tcx; let mut stack = Vec::new(); stack.push((a_ty, dir, b_vid)); loop { // For each turn of the loop, we extract a tuple // // (a_ty, dir, b_vid) // // to relate. Here dir is either SubtypeOf or // SupertypeOf. The idea is that we should ensure that // the type `a_ty` is a subtype or supertype (respectively) of the // type to which `b_vid` is bound. // // If `b_vid` has not yet been instantiated with a type // (which is always true on the first iteration, but not // necessarily true on later iterations), we will first // instantiate `b_vid` with a *generalized* version of // `a_ty`. Generalization introduces other inference // variables wherever subtyping could occur (at time of // this writing, this means replacing free regions with // region variables). let (a_ty, dir, b_vid) = match stack.pop() { None => break, Some(e) => e, }; debug!("instantiate(a_ty={} dir={:?} b_vid={})", a_ty.repr(tcx), dir, b_vid.repr(tcx)); // Check whether `vid` has been instantiated yet. If not, // make a generalized form of `ty` and instantiate with // that. let b_ty = self.infcx.type_variables.borrow().probe(b_vid); let b_ty = match b_ty { Some(t) => t, //...already instantiated. None => { //...not yet instantiated: // Generalize type if necessary. let generalized_ty = try!(match dir { EqTo => self.generalize(a_ty, b_vid, false), BiTo | SupertypeOf | SubtypeOf => self.generalize(a_ty, b_vid, true), }); debug!("instantiate(a_ty={}, dir={:?}, \ b_vid={}, generalized_ty={})", a_ty.repr(tcx), dir, b_vid.repr(tcx), generalized_ty.repr(tcx)); self.infcx.type_variables .borrow_mut() .instantiate_and_push( b_vid, generalized_ty, &mut stack); generalized_ty } }; // The original triple was `(a_ty, dir, b_vid)` -- now we have // resolved `b_vid` to `b_ty`, so apply `(a_ty, dir, b_ty)`: // // FIXME(#16847): This code is non-ideal because all these subtype // relations wind up attributed to the same spans. We need // to associate causes/spans with each of the relations in // the stack to get this right. try!(match dir { BiTo => self.bivariate().relate(&a_ty, &b_ty), EqTo => self.equate().relate(&a_ty, &b_ty), SubtypeOf => self.sub().relate(&a_ty, &b_ty), SupertypeOf => self.sub().relate_with_variance(ty::Contravariant, &a_ty, &b_ty), }); } Ok(()) } /// Attempts to generalize `ty` for the type variable `for_vid`. This checks for cycle -- that /// is, whether the type `ty` references `for_vid`. If `make_region_vars` is true, it will also /// replace all regions with fresh variables. Returns `TyError` in the case of a cycle, `Ok` /// otherwise. fn generalize(&self, ty: Ty<'tcx>, for_vid: ty::TyVid, make_region_vars: bool) -> RelateResult<'tcx, Ty<'tcx>> { let mut generalize = Generalizer { infcx: self.infcx, span: self.trace.origin.span(), for_vid: for_vid, make_region_vars: make_region_vars, cycle_detected: false }; let u = ty.fold_with(&mut generalize); if generalize.cycle_detected { Err(ty::terr_cyclic_ty) } else { Ok(u) } } } struct Generalizer<'cx, 'tcx:'cx> { infcx: &'cx InferCtxt<'cx, 'tcx>, span: Span, for_vid: ty::TyVid, make_region_vars: bool, cycle_detected: bool, } impl<'cx, 'tcx> ty_fold::TypeFolder<'tcx> for Generalizer<'cx, 'tcx> { fn tcx(&self) -> &ty::ctxt<'tcx> { self.infcx.tcx } fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { // Check to see whether the type we are genealizing references // `vid`. At the same time, also update any type variables to // the values that they are bound to. This is needed to truly // check for cycles, but also just makes things readable. // // (In particular, you could have something like `$0 = Box<$1>` // where `$1` has already been instantiated with `Box<$0>`) match t.sty { ty::TyInfer(ty::TyVar(vid)) => { if vid == self.for_vid { self.cycle_detected = true; self.tcx().types.err } else { match self.infcx.type_variables.borrow().probe(vid) { Some(u) => self.fold_ty(u), None => t, } } } _ => { ty_fold::super_fold_ty(self, t) } } } fn fold_region(&mut self, r: ty::Region) -> ty::Region { match r { // Never make variables for regions bound within the type itself. ty::ReLateBound(..) => { return r; } // Early-bound regions should really have been substituted away before // we get to this point. ty::ReEarlyBound(..) => { self.tcx().sess.span_bug( self.span, &format!("Encountered early bound region when generalizing: {}", r.repr(self.tcx()))); } // Always make a fresh region variable for skolemized regions; // the higher-ranked decision procedures rely on this. ty::ReInfer(ty::ReSkolemized(..)) => { } // For anything else, we make a region variable, unless we // are *equating*, in which case it's just wasteful. ty::ReEmpty | ty::ReStatic | ty::ReScope(..) | ty::ReInfer(ty::ReVar(..)) | ty::ReFree(..) => { if!self.make_region_vars { return r; } } } // FIXME: This is non-ideal because we don't give a // very descriptive origin for this region variable. self.infcx.next_region_var(MiscVariable(self.span)) } } pub trait RelateResultCompare<'tcx, T> { fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where F: FnOnce() -> ty::type_err<'tcx>; } impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> { fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where F: FnOnce() -> ty::type_err<'tcx>, { self.clone().and_then(|s| { if s == t { self.clone() } else { Err(f()) } }) } } fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue)) -> ty::type_err<'tcx> { let (a, b) = v; ty::terr_int_mismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b)) } fn
<'tcx>(a_is_expected: bool, v: (ast::FloatTy, ast::FloatTy)) -> ty::type_err<'tcx> { let (a, b) = v; ty::terr_float_mismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b)) }
float_unification_error
identifier_name
regions-infer-contravariance-due-to-decl.rs
// Test that a type which is contravariant with respect to its region // parameter yields an error when used in a covariant way. // // Note: see variance-regions-*.rs for the tests that check that the // variance inference works in the first place. use std::marker; // This is contravariant with respect to 'a, meaning that // Contravariant<'foo> <: Contravariant<'static> because // 'foo <='static struct
<'a> { marker: marker::PhantomData<&'a()> } fn use_<'short,'long>(c: Contravariant<'short>, s: &'short isize, l: &'long isize, _where:Option<&'short &'long ()>) { // Test whether Contravariant<'short> <: Contravariant<'long>. Since //'short <= 'long, this would be true if the Contravariant type were // covariant with respect to its parameter 'a. let _: Contravariant<'long> = c; //~ ERROR E0623 } fn main() {}
Contravariant
identifier_name
regions-infer-contravariance-due-to-decl.rs
// Test that a type which is contravariant with respect to its region // parameter yields an error when used in a covariant way. // // Note: see variance-regions-*.rs for the tests that check that the // variance inference works in the first place. use std::marker; // This is contravariant with respect to 'a, meaning that // Contravariant<'foo> <: Contravariant<'static> because // 'foo <='static struct Contravariant<'a> { marker: marker::PhantomData<&'a()>
fn use_<'short,'long>(c: Contravariant<'short>, s: &'short isize, l: &'long isize, _where:Option<&'short &'long ()>) { // Test whether Contravariant<'short> <: Contravariant<'long>. Since //'short <= 'long, this would be true if the Contravariant type were // covariant with respect to its parameter 'a. let _: Contravariant<'long> = c; //~ ERROR E0623 } fn main() {}
}
random_line_split
out_of.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 core::ops::{Range, RangeTo, RangeFrom, RangeFull}; pub trait OutOf<T = ()> { fn out_of(t: T) -> Self; } impl<T> OutOf<T> for T { fn out_of(t: T) -> T { t } } impl<T> OutOf<Range<T>> for Range<Option<T>> { fn out_of(u: Range<T>) -> Self { Range { start: Some(u.start), end: Some(u.end) } } } impl<T> OutOf<RangeTo<T>> for Range<Option<T>> { fn out_of(u: RangeTo<T>) -> Self { Range { start: None, end: Some(u.end) } } } impl<T> OutOf<RangeFrom<T>> for Range<Option<T>> { fn out_of(u: RangeFrom<T>) -> Self { Range { start: Some(u.start), end: None } } } impl<T> OutOf<RangeFull> for Range<Option<T>> { fn out_of(_: RangeFull) -> Self { Range { start: None, end: None } } } macro_rules! as_out_of { ($from:ty as $to:ty) => { impl OutOf<$from> for $to { fn out_of(from: $from) -> $to { from as $to } } } } as_out_of!(u8 as u16); as_out_of!(u8 as u32); as_out_of!(u8 as u64); as_out_of!(u8 as usize); as_out_of!(u16 as u32); as_out_of!(u16 as u64); as_out_of!(u16 as usize); as_out_of!(u32 as u64); as_out_of!(u32 as usize); as_out_of!(u8 as i16); as_out_of!(u8 as i32); as_out_of!(u8 as i64); as_out_of!(u8 as isize); as_out_of!(u16 as i32); as_out_of!(u16 as i64); as_out_of!(u16 as isize); as_out_of!(u32 as i64); as_out_of!(u32 as isize); as_out_of!(i8 as i16); as_out_of!(i8 as i32); as_out_of!(i8 as i64); as_out_of!(i8 as isize); as_out_of!(i16 as i32); as_out_of!(i16 as i64); as_out_of!(i16 as isize); as_out_of!(i32 as i64); as_out_of!(i32 as isize); macro_rules! zero { ($ty:ty) => { impl OutOf for $ty { fn out_of(_: ()) -> $ty { 0 } }
} zero!(u8 ); zero!(u16 ); zero!(u32 ); zero!(u64 ); zero!(usize ); zero!(i8 ); zero!(i16 ); zero!(i32 ); zero!(i64 ); zero!(isize ); impl<T> OutOf for Option<T> { fn out_of(_: ()) -> Option<T> { None } }
}
random_line_split
out_of.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 core::ops::{Range, RangeTo, RangeFrom, RangeFull}; pub trait OutOf<T = ()> { fn out_of(t: T) -> Self; } impl<T> OutOf<T> for T { fn out_of(t: T) -> T { t } } impl<T> OutOf<Range<T>> for Range<Option<T>> { fn out_of(u: Range<T>) -> Self { Range { start: Some(u.start), end: Some(u.end) } } } impl<T> OutOf<RangeTo<T>> for Range<Option<T>> { fn out_of(u: RangeTo<T>) -> Self { Range { start: None, end: Some(u.end) } } } impl<T> OutOf<RangeFrom<T>> for Range<Option<T>> { fn out_of(u: RangeFrom<T>) -> Self { Range { start: Some(u.start), end: None } } } impl<T> OutOf<RangeFull> for Range<Option<T>> { fn
(_: RangeFull) -> Self { Range { start: None, end: None } } } macro_rules! as_out_of { ($from:ty as $to:ty) => { impl OutOf<$from> for $to { fn out_of(from: $from) -> $to { from as $to } } } } as_out_of!(u8 as u16); as_out_of!(u8 as u32); as_out_of!(u8 as u64); as_out_of!(u8 as usize); as_out_of!(u16 as u32); as_out_of!(u16 as u64); as_out_of!(u16 as usize); as_out_of!(u32 as u64); as_out_of!(u32 as usize); as_out_of!(u8 as i16); as_out_of!(u8 as i32); as_out_of!(u8 as i64); as_out_of!(u8 as isize); as_out_of!(u16 as i32); as_out_of!(u16 as i64); as_out_of!(u16 as isize); as_out_of!(u32 as i64); as_out_of!(u32 as isize); as_out_of!(i8 as i16); as_out_of!(i8 as i32); as_out_of!(i8 as i64); as_out_of!(i8 as isize); as_out_of!(i16 as i32); as_out_of!(i16 as i64); as_out_of!(i16 as isize); as_out_of!(i32 as i64); as_out_of!(i32 as isize); macro_rules! zero { ($ty:ty) => { impl OutOf for $ty { fn out_of(_: ()) -> $ty { 0 } } } } zero!(u8 ); zero!(u16 ); zero!(u32 ); zero!(u64 ); zero!(usize ); zero!(i8 ); zero!(i16 ); zero!(i32 ); zero!(i64 ); zero!(isize ); impl<T> OutOf for Option<T> { fn out_of(_: ()) -> Option<T> { None } }
out_of
identifier_name
out_of.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 core::ops::{Range, RangeTo, RangeFrom, RangeFull}; pub trait OutOf<T = ()> { fn out_of(t: T) -> Self; } impl<T> OutOf<T> for T { fn out_of(t: T) -> T { t } } impl<T> OutOf<Range<T>> for Range<Option<T>> { fn out_of(u: Range<T>) -> Self
} impl<T> OutOf<RangeTo<T>> for Range<Option<T>> { fn out_of(u: RangeTo<T>) -> Self { Range { start: None, end: Some(u.end) } } } impl<T> OutOf<RangeFrom<T>> for Range<Option<T>> { fn out_of(u: RangeFrom<T>) -> Self { Range { start: Some(u.start), end: None } } } impl<T> OutOf<RangeFull> for Range<Option<T>> { fn out_of(_: RangeFull) -> Self { Range { start: None, end: None } } } macro_rules! as_out_of { ($from:ty as $to:ty) => { impl OutOf<$from> for $to { fn out_of(from: $from) -> $to { from as $to } } } } as_out_of!(u8 as u16); as_out_of!(u8 as u32); as_out_of!(u8 as u64); as_out_of!(u8 as usize); as_out_of!(u16 as u32); as_out_of!(u16 as u64); as_out_of!(u16 as usize); as_out_of!(u32 as u64); as_out_of!(u32 as usize); as_out_of!(u8 as i16); as_out_of!(u8 as i32); as_out_of!(u8 as i64); as_out_of!(u8 as isize); as_out_of!(u16 as i32); as_out_of!(u16 as i64); as_out_of!(u16 as isize); as_out_of!(u32 as i64); as_out_of!(u32 as isize); as_out_of!(i8 as i16); as_out_of!(i8 as i32); as_out_of!(i8 as i64); as_out_of!(i8 as isize); as_out_of!(i16 as i32); as_out_of!(i16 as i64); as_out_of!(i16 as isize); as_out_of!(i32 as i64); as_out_of!(i32 as isize); macro_rules! zero { ($ty:ty) => { impl OutOf for $ty { fn out_of(_: ()) -> $ty { 0 } } } } zero!(u8 ); zero!(u16 ); zero!(u32 ); zero!(u64 ); zero!(usize ); zero!(i8 ); zero!(i16 ); zero!(i32 ); zero!(i64 ); zero!(isize ); impl<T> OutOf for Option<T> { fn out_of(_: ()) -> Option<T> { None } }
{ Range { start: Some(u.start), end: Some(u.end) } }
identifier_body
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Utilities for program-wide and customizable logging //! //! # Examples //! //! ``` //! #[macro_use] extern crate log; //! //! fn main() { //! debug!("this is a debug {:?}", "message"); //! error!("this is printed by default"); //! //! if log_enabled!(log::INFO) { //! let x = 3i * 4i; // expensive computation //! info!("the answer was: {:?}", x); //! } //! } //! ``` //! //! Assumes the binary is `main`: //! //! ```{.bash} //! $ RUST_LOG=error./main //! ERROR:main: this is printed by default //! ``` //! //! ```{.bash} //! $ RUST_LOG=info./main //! ERROR:main: this is printed by default //! INFO:main: the answer was: 12 //! ``` //! //! ```{.bash} //! $ RUST_LOG=debug./main //! DEBUG:main: this is a debug message //! ERROR:main: this is printed by default //! INFO:main: the answer was: 12 //! ``` //! //! You can also set the log level on a per module basis: //! //! ```{.bash} //! $ RUST_LOG=main=info./main //! ERROR:main: this is printed by default //! INFO:main: the answer was: 12 //! ``` //! //! And enable all logging: //! //! ```{.bash} //! $ RUST_LOG=main./main //! DEBUG:main: this is a debug message //! ERROR:main: this is printed by default //! INFO:main: the answer was: 12 //! ``` //! //! # Logging Macros //! //! There are five macros that the logging subsystem uses: //! //! * `log!(level,...)` - the generic logging macro, takes a level as a u32 and any //! related `format!` arguments //! * `debug!(...)` - a macro hard-wired to the log level of `DEBUG` //! * `info!(...)` - a macro hard-wired to the log level of `INFO` //! * `warn!(...)` - a macro hard-wired to the log level of `WARN` //! * `error!(...)` - a macro hard-wired to the log level of `ERROR` //! //! All of these macros use the same style of syntax as the `format!` syntax //! extension. Details about the syntax can be found in the documentation of //! `std::fmt` along with the Rust tutorial/manual. //! //! If you want to check at runtime if a given logging level is enabled (e.g. if the //! information you would want to log is expensive to produce), you can use the //! following macro: //! //! * `log_enabled!(level)` - returns true if logging of the given level is enabled //! //! # Enabling logging //! //! Log levels are controlled on a per-module basis, and by default all logging is //! disabled except for `error!` (a log level of 1). Logging is controlled via the //! `RUST_LOG` environment variable. The value of this environment variable is a //! comma-separated list of logging directives. A logging directive is of the form: //! //! ```text //! path::to::module=log_level //! ``` //! //! The path to the module is rooted in the name of the crate it was compiled for, //! so if your program is contained in a file `hello.rs`, for example, to turn on //! logging for this file you would use a value of `RUST_LOG=hello`. //! Furthermore, this path is a prefix-search, so all modules nested in the //! specified module will also have logging enabled. //! //! The actual `log_level` is optional to specify. If omitted, all logging will be //! enabled. If specified, the it must be either a numeric in the range of 1-255, or //! it must be one of the strings `debug`, `error`, `info`, or `warn`. If a numeric //! is specified, then all logging less than or equal to that numeral is enabled. //! For example, if logging level 3 is active, error, warn, and info logs will be //! printed, but debug will be omitted. //! //! As the log level for a module is optional, the module to enable logging for is //! also optional. If only a `log_level` is provided, then the global log level for //! all modules is set to this value. //! //! Some examples of valid values of `RUST_LOG` are: //! //! * `hello` turns on all logging for the 'hello' module //! * `info` turns on all info logging //! * `hello=debug` turns on debug logging for 'hello' //! * `hello=3` turns on info logging for 'hello' //! * `hello,std::option` turns on hello, and std's option logging //! * `error,hello=warn` turn on global error logging and also warn for hello //! //! # Filtering results //! //! A RUST_LOG directive may include a regex filter. The syntax is to append `/` //! followed by a regex. Each message is checked against the regex, and is only //! logged if it matches. Note that the matching is done after formatting the log //! string but before adding any logging meta-data. There is a single filter for all //! modules. //! //! Some examples: //! //! * `hello/foo` turns on all logging for the 'hello' module where the log message //! includes 'foo'. //! * `info/f.o` turns on all info logging where the log message includes 'foo', //! 'f1o', 'fao', etc. //! * `hello=debug/foo*foo` turns on debug logging for 'hello' where the log //! message includes 'foofoo' or 'fofoo' or 'fooooooofoo', etc. //! * `error,hello=warn/[0-9] scopes` turn on global error logging and also warn for //! hello. In both cases the log message must include a single digit number //! followed by'scopes' //! //! # Performance and Side Effects //! //! Each of these macros will expand to code similar to: //! //! ```rust,ignore //! if log_level <= my_module_log_level() { //! ::log::log(log_level, format!(...)); //! } //! ``` //! //! What this means is that each of these macros are very cheap at runtime if //! they're turned off (just a load and an integer comparison). This also means that //! if logging is disabled, none of the components of the log will be executed. #![crate_name = "log"] #![experimental = "use the crates.io `log` library instead"] #![staged_api] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] #![allow(unknown_features)] #![feature(slicing_syntax)] #![feature(box_syntax)] #![deny(missing_docs)] extern crate regex; use std::cell::RefCell; use std::fmt; use std::io::LineBufferedWriter; use std::io; use std::mem; use std::os; use std::rt; use std::slice; use std::sync::{Once, ONCE_INIT}; use regex::Regex; use directive::LOG_LEVEL_NAMES; #[macro_use] pub mod macros; mod directive; /// Maximum logging level of a module that can be specified. Common logging /// levels are found in the DEBUG/INFO/WARN/ERROR constants. pub const MAX_LOG_LEVEL: u32 = 255; /// The default logging level of a crate if no other is specified. const DEFAULT_LOG_LEVEL: u32 = 1; /// An unsafe constant that is the maximum logging level of any module /// specified. This is the first line of defense to determining whether a /// logging statement should be run. static mut LOG_LEVEL: u32 = MAX_LOG_LEVEL; static mut DIRECTIVES: *const Vec<directive::LogDirective> = 0 as *const Vec<directive::LogDirective>; /// Optional regex filter. static mut FILTER: *const Regex = 0 as *const _; /// Debug log level pub const DEBUG: u32 = 4; /// Info log level pub const INFO: u32 = 3; /// Warn log level pub const WARN: u32 = 2; /// Error log level pub const ERROR: u32 = 1; thread_local! { static LOCAL_LOGGER: RefCell<Option<Box<Logger + Send>>> = { RefCell::new(None) } } /// A trait used to represent an interface to a task-local logger. Each task /// can have its own custom logger which can respond to logging messages /// however it likes. pub trait Logger { /// Logs a single message described by the `record`. fn log(&mut self, record: &LogRecord); } struct DefaultLogger { handle: LineBufferedWriter<io::stdio::StdWriter>, } /// Wraps the log level with fmt implementations. #[derive(Copy, PartialEq, PartialOrd)] pub struct LogLevel(pub u32); impl fmt::Show for LogLevel { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::String::fmt(self, fmt) } } impl fmt::String for LogLevel { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let LogLevel(level) = *self; match LOG_LEVEL_NAMES.get(level as uint - 1) { Some(ref name) => fmt::String::fmt(name, fmt), None => fmt::String::fmt(&level, fmt) } } } impl Logger for DefaultLogger { fn
(&mut self, record: &LogRecord) { match writeln!(&mut self.handle, "{}:{}: {}", record.level, record.module_path, record.args) { Err(e) => panic!("failed to log: {:?}", e), Ok(()) => {} } } } impl Drop for DefaultLogger { fn drop(&mut self) { // FIXME(#12628): is panicking the right thing to do? match self.handle.flush() { Err(e) => panic!("failed to flush a logger: {:?}", e), Ok(()) => {} } } } /// This function is called directly by the compiler when using the logging /// macros. This function does not take into account whether the log level /// specified is active or not, it will always log something if this method is /// called. /// /// It is not recommended to call this function directly, rather it should be /// invoked through the logging family of macros. #[doc(hidden)] pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments) { // Test the literal string from args against the current filter, if there // is one. match unsafe { FILTER.as_ref() } { Some(filter) if!filter.is_match(&args.to_string()[]) => return, _ => {} } // Completely remove the local logger from TLS in case anyone attempts to // frob the slot while we're doing the logging. This will destroy any logger // set during logging. let mut logger = LOCAL_LOGGER.with(|s| { s.borrow_mut().take() }).unwrap_or_else(|| { box DefaultLogger { handle: io::stderr() } as Box<Logger + Send> }); logger.log(&LogRecord { level: LogLevel(level), args: args, file: loc.file, module_path: loc.module_path, line: loc.line, }); set_logger(logger); } /// Getter for the global log level. This is a function so that it can be called /// safely #[doc(hidden)] #[inline(always)] pub fn log_level() -> u32 { unsafe { LOG_LEVEL } } /// Replaces the task-local logger with the specified logger, returning the old /// logger. pub fn set_logger(logger: Box<Logger + Send>) -> Option<Box<Logger + Send>> { let mut l = Some(logger); LOCAL_LOGGER.with(|slot| { mem::replace(&mut *slot.borrow_mut(), l.take()) }) } /// A LogRecord is created by the logging macros, and passed as the only /// argument to Loggers. #[derive(Show)] pub struct LogRecord<'a> { /// The module path of where the LogRecord originated. pub module_path: &'a str, /// The LogLevel of this record. pub level: LogLevel, /// The arguments from the log line. pub args: fmt::Arguments<'a>, /// The file of where the LogRecord originated. pub file: &'a str, /// The line number of where the LogRecord originated. pub line: uint, } #[doc(hidden)] #[derive(Copy)] pub struct LogLocation { pub module_path: &'static str, pub file: &'static str, pub line: uint, } /// Tests whether a given module's name is enabled for a particular level of /// logging. This is the second layer of defense about determining whether a /// module's log statement should be emitted or not. #[doc(hidden)] pub fn mod_enabled(level: u32, module: &str) -> bool { static INIT: Once = ONCE_INIT; INIT.call_once(init); // It's possible for many threads are in this function, only one of them // will perform the global initialization, but all of them will need to check // again to whether they should really be here or not. Hence, despite this // check being expanded manually in the logging macro, this function checks // the log level again. if level > unsafe { LOG_LEVEL } { return false } // This assertion should never get tripped unless we're in an at_exit // handler after logging has been torn down and a logging attempt was made. assert!(unsafe {!DIRECTIVES.is_null() }); enabled(level, module, unsafe { (*DIRECTIVES).iter() }) } fn enabled(level: u32, module: &str, iter: slice::Iter<directive::LogDirective>) -> bool { // Search for the longest match, the vector is assumed to be pre-sorted. for directive in iter.rev() { match directive.name { Some(ref name) if!module.starts_with(&name[]) => {}, Some(..) | None => { return level <= directive.level } } } level <= DEFAULT_LOG_LEVEL } /// Initialize logging for the current process. /// /// This is not threadsafe at all, so initialization is performed through a /// `Once` primitive (and this function is called from that primitive). fn init() { let (mut directives, filter) = match os::getenv("RUST_LOG") { Some(spec) => directive::parse_logging_spec(&spec[]), None => (Vec::new(), None), }; // Sort the provided directives by length of their name, this allows a // little more efficient lookup at runtime. directives.sort_by(|a, b| { let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0); let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0); alen.cmp(&blen) }); let max_level = { let max = directives.iter().max_by(|d| d.level); max.map(|d| d.level).unwrap_or(DEFAULT_LOG_LEVEL) }; unsafe { LOG_LEVEL = max_level; assert!(FILTER.is_null()); match filter { Some(f) => FILTER = mem::transmute(box f), None => {} } assert!(DIRECTIVES.is_null()); DIRECTIVES = mem::transmute(box directives); // Schedule the cleanup for the globals for when the runtime exits. rt::at_exit(move |:| { assert!(!DIRECTIVES.is_null()); let _directives: Box<Vec<directive::LogDirective>> = mem::transmute(DIRECTIVES); DIRECTIVES = 0 as *const Vec<directive::LogDirective>; if!FILTER.is_null() { let _filter: Box<Regex> = mem::transmute(FILTER); FILTER = 0 as *const _; } }); } } #[cfg(test)] mod tests { use super::enabled; use directive::LogDirective; #[test] fn match_full_path() { let dirs = [ LogDirective { name: Some("crate2".to_string()), level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(enabled(2, "crate1::mod1", dirs.iter())); assert!(!enabled(3, "crate1::mod1", dirs.iter())); assert!(enabled(3, "crate2", dirs.iter())); assert!(!enabled(4, "crate2", dirs.iter())); } #[test] fn no_match() { let dirs = [ LogDirective { name: Some("crate2".to_string()), level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(!enabled(2, "crate3", dirs.iter())); } #[test] fn match_beginning() { let dirs = [ LogDirective { name: Some("crate2".to_string()), level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(enabled(3, "crate2::mod1", dirs.iter())); } #[test] fn match_beginning_longest_match() { let dirs = [ LogDirective { name: Some("crate2".to_string()), level: 3 }, LogDirective { name: Some("crate2::mod".to_string()), level: 4 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(enabled(4, "crate2::mod1", dirs.iter())); assert!(!enabled(4, "crate2", dirs.iter())); } #[test] fn match_default() { let dirs = [ LogDirective { name: None, level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(enabled(2, "crate1::mod1", dirs.iter())); assert!(enabled(3, "crate2::mod2", dirs.iter())); } #[test] fn zero_level() { let dirs = [ LogDirective { name: None, level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 0 } ]; assert!(!enabled(1, "crate1::mod1", dirs.iter())); assert!(enabled(3, "crate2::mod2", dirs.iter())); } }
log
identifier_name
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Utilities for program-wide and customizable logging //!
//! #[macro_use] extern crate log; //! //! fn main() { //! debug!("this is a debug {:?}", "message"); //! error!("this is printed by default"); //! //! if log_enabled!(log::INFO) { //! let x = 3i * 4i; // expensive computation //! info!("the answer was: {:?}", x); //! } //! } //! ``` //! //! Assumes the binary is `main`: //! //! ```{.bash} //! $ RUST_LOG=error./main //! ERROR:main: this is printed by default //! ``` //! //! ```{.bash} //! $ RUST_LOG=info./main //! ERROR:main: this is printed by default //! INFO:main: the answer was: 12 //! ``` //! //! ```{.bash} //! $ RUST_LOG=debug./main //! DEBUG:main: this is a debug message //! ERROR:main: this is printed by default //! INFO:main: the answer was: 12 //! ``` //! //! You can also set the log level on a per module basis: //! //! ```{.bash} //! $ RUST_LOG=main=info./main //! ERROR:main: this is printed by default //! INFO:main: the answer was: 12 //! ``` //! //! And enable all logging: //! //! ```{.bash} //! $ RUST_LOG=main./main //! DEBUG:main: this is a debug message //! ERROR:main: this is printed by default //! INFO:main: the answer was: 12 //! ``` //! //! # Logging Macros //! //! There are five macros that the logging subsystem uses: //! //! * `log!(level,...)` - the generic logging macro, takes a level as a u32 and any //! related `format!` arguments //! * `debug!(...)` - a macro hard-wired to the log level of `DEBUG` //! * `info!(...)` - a macro hard-wired to the log level of `INFO` //! * `warn!(...)` - a macro hard-wired to the log level of `WARN` //! * `error!(...)` - a macro hard-wired to the log level of `ERROR` //! //! All of these macros use the same style of syntax as the `format!` syntax //! extension. Details about the syntax can be found in the documentation of //! `std::fmt` along with the Rust tutorial/manual. //! //! If you want to check at runtime if a given logging level is enabled (e.g. if the //! information you would want to log is expensive to produce), you can use the //! following macro: //! //! * `log_enabled!(level)` - returns true if logging of the given level is enabled //! //! # Enabling logging //! //! Log levels are controlled on a per-module basis, and by default all logging is //! disabled except for `error!` (a log level of 1). Logging is controlled via the //! `RUST_LOG` environment variable. The value of this environment variable is a //! comma-separated list of logging directives. A logging directive is of the form: //! //! ```text //! path::to::module=log_level //! ``` //! //! The path to the module is rooted in the name of the crate it was compiled for, //! so if your program is contained in a file `hello.rs`, for example, to turn on //! logging for this file you would use a value of `RUST_LOG=hello`. //! Furthermore, this path is a prefix-search, so all modules nested in the //! specified module will also have logging enabled. //! //! The actual `log_level` is optional to specify. If omitted, all logging will be //! enabled. If specified, the it must be either a numeric in the range of 1-255, or //! it must be one of the strings `debug`, `error`, `info`, or `warn`. If a numeric //! is specified, then all logging less than or equal to that numeral is enabled. //! For example, if logging level 3 is active, error, warn, and info logs will be //! printed, but debug will be omitted. //! //! As the log level for a module is optional, the module to enable logging for is //! also optional. If only a `log_level` is provided, then the global log level for //! all modules is set to this value. //! //! Some examples of valid values of `RUST_LOG` are: //! //! * `hello` turns on all logging for the 'hello' module //! * `info` turns on all info logging //! * `hello=debug` turns on debug logging for 'hello' //! * `hello=3` turns on info logging for 'hello' //! * `hello,std::option` turns on hello, and std's option logging //! * `error,hello=warn` turn on global error logging and also warn for hello //! //! # Filtering results //! //! A RUST_LOG directive may include a regex filter. The syntax is to append `/` //! followed by a regex. Each message is checked against the regex, and is only //! logged if it matches. Note that the matching is done after formatting the log //! string but before adding any logging meta-data. There is a single filter for all //! modules. //! //! Some examples: //! //! * `hello/foo` turns on all logging for the 'hello' module where the log message //! includes 'foo'. //! * `info/f.o` turns on all info logging where the log message includes 'foo', //! 'f1o', 'fao', etc. //! * `hello=debug/foo*foo` turns on debug logging for 'hello' where the log //! message includes 'foofoo' or 'fofoo' or 'fooooooofoo', etc. //! * `error,hello=warn/[0-9] scopes` turn on global error logging and also warn for //! hello. In both cases the log message must include a single digit number //! followed by'scopes' //! //! # Performance and Side Effects //! //! Each of these macros will expand to code similar to: //! //! ```rust,ignore //! if log_level <= my_module_log_level() { //! ::log::log(log_level, format!(...)); //! } //! ``` //! //! What this means is that each of these macros are very cheap at runtime if //! they're turned off (just a load and an integer comparison). This also means that //! if logging is disabled, none of the components of the log will be executed. #![crate_name = "log"] #![experimental = "use the crates.io `log` library instead"] #![staged_api] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] #![allow(unknown_features)] #![feature(slicing_syntax)] #![feature(box_syntax)] #![deny(missing_docs)] extern crate regex; use std::cell::RefCell; use std::fmt; use std::io::LineBufferedWriter; use std::io; use std::mem; use std::os; use std::rt; use std::slice; use std::sync::{Once, ONCE_INIT}; use regex::Regex; use directive::LOG_LEVEL_NAMES; #[macro_use] pub mod macros; mod directive; /// Maximum logging level of a module that can be specified. Common logging /// levels are found in the DEBUG/INFO/WARN/ERROR constants. pub const MAX_LOG_LEVEL: u32 = 255; /// The default logging level of a crate if no other is specified. const DEFAULT_LOG_LEVEL: u32 = 1; /// An unsafe constant that is the maximum logging level of any module /// specified. This is the first line of defense to determining whether a /// logging statement should be run. static mut LOG_LEVEL: u32 = MAX_LOG_LEVEL; static mut DIRECTIVES: *const Vec<directive::LogDirective> = 0 as *const Vec<directive::LogDirective>; /// Optional regex filter. static mut FILTER: *const Regex = 0 as *const _; /// Debug log level pub const DEBUG: u32 = 4; /// Info log level pub const INFO: u32 = 3; /// Warn log level pub const WARN: u32 = 2; /// Error log level pub const ERROR: u32 = 1; thread_local! { static LOCAL_LOGGER: RefCell<Option<Box<Logger + Send>>> = { RefCell::new(None) } } /// A trait used to represent an interface to a task-local logger. Each task /// can have its own custom logger which can respond to logging messages /// however it likes. pub trait Logger { /// Logs a single message described by the `record`. fn log(&mut self, record: &LogRecord); } struct DefaultLogger { handle: LineBufferedWriter<io::stdio::StdWriter>, } /// Wraps the log level with fmt implementations. #[derive(Copy, PartialEq, PartialOrd)] pub struct LogLevel(pub u32); impl fmt::Show for LogLevel { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::String::fmt(self, fmt) } } impl fmt::String for LogLevel { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let LogLevel(level) = *self; match LOG_LEVEL_NAMES.get(level as uint - 1) { Some(ref name) => fmt::String::fmt(name, fmt), None => fmt::String::fmt(&level, fmt) } } } impl Logger for DefaultLogger { fn log(&mut self, record: &LogRecord) { match writeln!(&mut self.handle, "{}:{}: {}", record.level, record.module_path, record.args) { Err(e) => panic!("failed to log: {:?}", e), Ok(()) => {} } } } impl Drop for DefaultLogger { fn drop(&mut self) { // FIXME(#12628): is panicking the right thing to do? match self.handle.flush() { Err(e) => panic!("failed to flush a logger: {:?}", e), Ok(()) => {} } } } /// This function is called directly by the compiler when using the logging /// macros. This function does not take into account whether the log level /// specified is active or not, it will always log something if this method is /// called. /// /// It is not recommended to call this function directly, rather it should be /// invoked through the logging family of macros. #[doc(hidden)] pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments) { // Test the literal string from args against the current filter, if there // is one. match unsafe { FILTER.as_ref() } { Some(filter) if!filter.is_match(&args.to_string()[]) => return, _ => {} } // Completely remove the local logger from TLS in case anyone attempts to // frob the slot while we're doing the logging. This will destroy any logger // set during logging. let mut logger = LOCAL_LOGGER.with(|s| { s.borrow_mut().take() }).unwrap_or_else(|| { box DefaultLogger { handle: io::stderr() } as Box<Logger + Send> }); logger.log(&LogRecord { level: LogLevel(level), args: args, file: loc.file, module_path: loc.module_path, line: loc.line, }); set_logger(logger); } /// Getter for the global log level. This is a function so that it can be called /// safely #[doc(hidden)] #[inline(always)] pub fn log_level() -> u32 { unsafe { LOG_LEVEL } } /// Replaces the task-local logger with the specified logger, returning the old /// logger. pub fn set_logger(logger: Box<Logger + Send>) -> Option<Box<Logger + Send>> { let mut l = Some(logger); LOCAL_LOGGER.with(|slot| { mem::replace(&mut *slot.borrow_mut(), l.take()) }) } /// A LogRecord is created by the logging macros, and passed as the only /// argument to Loggers. #[derive(Show)] pub struct LogRecord<'a> { /// The module path of where the LogRecord originated. pub module_path: &'a str, /// The LogLevel of this record. pub level: LogLevel, /// The arguments from the log line. pub args: fmt::Arguments<'a>, /// The file of where the LogRecord originated. pub file: &'a str, /// The line number of where the LogRecord originated. pub line: uint, } #[doc(hidden)] #[derive(Copy)] pub struct LogLocation { pub module_path: &'static str, pub file: &'static str, pub line: uint, } /// Tests whether a given module's name is enabled for a particular level of /// logging. This is the second layer of defense about determining whether a /// module's log statement should be emitted or not. #[doc(hidden)] pub fn mod_enabled(level: u32, module: &str) -> bool { static INIT: Once = ONCE_INIT; INIT.call_once(init); // It's possible for many threads are in this function, only one of them // will perform the global initialization, but all of them will need to check // again to whether they should really be here or not. Hence, despite this // check being expanded manually in the logging macro, this function checks // the log level again. if level > unsafe { LOG_LEVEL } { return false } // This assertion should never get tripped unless we're in an at_exit // handler after logging has been torn down and a logging attempt was made. assert!(unsafe {!DIRECTIVES.is_null() }); enabled(level, module, unsafe { (*DIRECTIVES).iter() }) } fn enabled(level: u32, module: &str, iter: slice::Iter<directive::LogDirective>) -> bool { // Search for the longest match, the vector is assumed to be pre-sorted. for directive in iter.rev() { match directive.name { Some(ref name) if!module.starts_with(&name[]) => {}, Some(..) | None => { return level <= directive.level } } } level <= DEFAULT_LOG_LEVEL } /// Initialize logging for the current process. /// /// This is not threadsafe at all, so initialization is performed through a /// `Once` primitive (and this function is called from that primitive). fn init() { let (mut directives, filter) = match os::getenv("RUST_LOG") { Some(spec) => directive::parse_logging_spec(&spec[]), None => (Vec::new(), None), }; // Sort the provided directives by length of their name, this allows a // little more efficient lookup at runtime. directives.sort_by(|a, b| { let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0); let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0); alen.cmp(&blen) }); let max_level = { let max = directives.iter().max_by(|d| d.level); max.map(|d| d.level).unwrap_or(DEFAULT_LOG_LEVEL) }; unsafe { LOG_LEVEL = max_level; assert!(FILTER.is_null()); match filter { Some(f) => FILTER = mem::transmute(box f), None => {} } assert!(DIRECTIVES.is_null()); DIRECTIVES = mem::transmute(box directives); // Schedule the cleanup for the globals for when the runtime exits. rt::at_exit(move |:| { assert!(!DIRECTIVES.is_null()); let _directives: Box<Vec<directive::LogDirective>> = mem::transmute(DIRECTIVES); DIRECTIVES = 0 as *const Vec<directive::LogDirective>; if!FILTER.is_null() { let _filter: Box<Regex> = mem::transmute(FILTER); FILTER = 0 as *const _; } }); } } #[cfg(test)] mod tests { use super::enabled; use directive::LogDirective; #[test] fn match_full_path() { let dirs = [ LogDirective { name: Some("crate2".to_string()), level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(enabled(2, "crate1::mod1", dirs.iter())); assert!(!enabled(3, "crate1::mod1", dirs.iter())); assert!(enabled(3, "crate2", dirs.iter())); assert!(!enabled(4, "crate2", dirs.iter())); } #[test] fn no_match() { let dirs = [ LogDirective { name: Some("crate2".to_string()), level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(!enabled(2, "crate3", dirs.iter())); } #[test] fn match_beginning() { let dirs = [ LogDirective { name: Some("crate2".to_string()), level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(enabled(3, "crate2::mod1", dirs.iter())); } #[test] fn match_beginning_longest_match() { let dirs = [ LogDirective { name: Some("crate2".to_string()), level: 3 }, LogDirective { name: Some("crate2::mod".to_string()), level: 4 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(enabled(4, "crate2::mod1", dirs.iter())); assert!(!enabled(4, "crate2", dirs.iter())); } #[test] fn match_default() { let dirs = [ LogDirective { name: None, level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(enabled(2, "crate1::mod1", dirs.iter())); assert!(enabled(3, "crate2::mod2", dirs.iter())); } #[test] fn zero_level() { let dirs = [ LogDirective { name: None, level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 0 } ]; assert!(!enabled(1, "crate1::mod1", dirs.iter())); assert!(enabled(3, "crate2::mod2", dirs.iter())); } }
//! # Examples //! //! ```
random_line_split
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Utilities for program-wide and customizable logging //! //! # Examples //! //! ``` //! #[macro_use] extern crate log; //! //! fn main() { //! debug!("this is a debug {:?}", "message"); //! error!("this is printed by default"); //! //! if log_enabled!(log::INFO) { //! let x = 3i * 4i; // expensive computation //! info!("the answer was: {:?}", x); //! } //! } //! ``` //! //! Assumes the binary is `main`: //! //! ```{.bash} //! $ RUST_LOG=error./main //! ERROR:main: this is printed by default //! ``` //! //! ```{.bash} //! $ RUST_LOG=info./main //! ERROR:main: this is printed by default //! INFO:main: the answer was: 12 //! ``` //! //! ```{.bash} //! $ RUST_LOG=debug./main //! DEBUG:main: this is a debug message //! ERROR:main: this is printed by default //! INFO:main: the answer was: 12 //! ``` //! //! You can also set the log level on a per module basis: //! //! ```{.bash} //! $ RUST_LOG=main=info./main //! ERROR:main: this is printed by default //! INFO:main: the answer was: 12 //! ``` //! //! And enable all logging: //! //! ```{.bash} //! $ RUST_LOG=main./main //! DEBUG:main: this is a debug message //! ERROR:main: this is printed by default //! INFO:main: the answer was: 12 //! ``` //! //! # Logging Macros //! //! There are five macros that the logging subsystem uses: //! //! * `log!(level,...)` - the generic logging macro, takes a level as a u32 and any //! related `format!` arguments //! * `debug!(...)` - a macro hard-wired to the log level of `DEBUG` //! * `info!(...)` - a macro hard-wired to the log level of `INFO` //! * `warn!(...)` - a macro hard-wired to the log level of `WARN` //! * `error!(...)` - a macro hard-wired to the log level of `ERROR` //! //! All of these macros use the same style of syntax as the `format!` syntax //! extension. Details about the syntax can be found in the documentation of //! `std::fmt` along with the Rust tutorial/manual. //! //! If you want to check at runtime if a given logging level is enabled (e.g. if the //! information you would want to log is expensive to produce), you can use the //! following macro: //! //! * `log_enabled!(level)` - returns true if logging of the given level is enabled //! //! # Enabling logging //! //! Log levels are controlled on a per-module basis, and by default all logging is //! disabled except for `error!` (a log level of 1). Logging is controlled via the //! `RUST_LOG` environment variable. The value of this environment variable is a //! comma-separated list of logging directives. A logging directive is of the form: //! //! ```text //! path::to::module=log_level //! ``` //! //! The path to the module is rooted in the name of the crate it was compiled for, //! so if your program is contained in a file `hello.rs`, for example, to turn on //! logging for this file you would use a value of `RUST_LOG=hello`. //! Furthermore, this path is a prefix-search, so all modules nested in the //! specified module will also have logging enabled. //! //! The actual `log_level` is optional to specify. If omitted, all logging will be //! enabled. If specified, the it must be either a numeric in the range of 1-255, or //! it must be one of the strings `debug`, `error`, `info`, or `warn`. If a numeric //! is specified, then all logging less than or equal to that numeral is enabled. //! For example, if logging level 3 is active, error, warn, and info logs will be //! printed, but debug will be omitted. //! //! As the log level for a module is optional, the module to enable logging for is //! also optional. If only a `log_level` is provided, then the global log level for //! all modules is set to this value. //! //! Some examples of valid values of `RUST_LOG` are: //! //! * `hello` turns on all logging for the 'hello' module //! * `info` turns on all info logging //! * `hello=debug` turns on debug logging for 'hello' //! * `hello=3` turns on info logging for 'hello' //! * `hello,std::option` turns on hello, and std's option logging //! * `error,hello=warn` turn on global error logging and also warn for hello //! //! # Filtering results //! //! A RUST_LOG directive may include a regex filter. The syntax is to append `/` //! followed by a regex. Each message is checked against the regex, and is only //! logged if it matches. Note that the matching is done after formatting the log //! string but before adding any logging meta-data. There is a single filter for all //! modules. //! //! Some examples: //! //! * `hello/foo` turns on all logging for the 'hello' module where the log message //! includes 'foo'. //! * `info/f.o` turns on all info logging where the log message includes 'foo', //! 'f1o', 'fao', etc. //! * `hello=debug/foo*foo` turns on debug logging for 'hello' where the log //! message includes 'foofoo' or 'fofoo' or 'fooooooofoo', etc. //! * `error,hello=warn/[0-9] scopes` turn on global error logging and also warn for //! hello. In both cases the log message must include a single digit number //! followed by'scopes' //! //! # Performance and Side Effects //! //! Each of these macros will expand to code similar to: //! //! ```rust,ignore //! if log_level <= my_module_log_level() { //! ::log::log(log_level, format!(...)); //! } //! ``` //! //! What this means is that each of these macros are very cheap at runtime if //! they're turned off (just a load and an integer comparison). This also means that //! if logging is disabled, none of the components of the log will be executed. #![crate_name = "log"] #![experimental = "use the crates.io `log` library instead"] #![staged_api] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] #![allow(unknown_features)] #![feature(slicing_syntax)] #![feature(box_syntax)] #![deny(missing_docs)] extern crate regex; use std::cell::RefCell; use std::fmt; use std::io::LineBufferedWriter; use std::io; use std::mem; use std::os; use std::rt; use std::slice; use std::sync::{Once, ONCE_INIT}; use regex::Regex; use directive::LOG_LEVEL_NAMES; #[macro_use] pub mod macros; mod directive; /// Maximum logging level of a module that can be specified. Common logging /// levels are found in the DEBUG/INFO/WARN/ERROR constants. pub const MAX_LOG_LEVEL: u32 = 255; /// The default logging level of a crate if no other is specified. const DEFAULT_LOG_LEVEL: u32 = 1; /// An unsafe constant that is the maximum logging level of any module /// specified. This is the first line of defense to determining whether a /// logging statement should be run. static mut LOG_LEVEL: u32 = MAX_LOG_LEVEL; static mut DIRECTIVES: *const Vec<directive::LogDirective> = 0 as *const Vec<directive::LogDirective>; /// Optional regex filter. static mut FILTER: *const Regex = 0 as *const _; /// Debug log level pub const DEBUG: u32 = 4; /// Info log level pub const INFO: u32 = 3; /// Warn log level pub const WARN: u32 = 2; /// Error log level pub const ERROR: u32 = 1; thread_local! { static LOCAL_LOGGER: RefCell<Option<Box<Logger + Send>>> = { RefCell::new(None) } } /// A trait used to represent an interface to a task-local logger. Each task /// can have its own custom logger which can respond to logging messages /// however it likes. pub trait Logger { /// Logs a single message described by the `record`. fn log(&mut self, record: &LogRecord); } struct DefaultLogger { handle: LineBufferedWriter<io::stdio::StdWriter>, } /// Wraps the log level with fmt implementations. #[derive(Copy, PartialEq, PartialOrd)] pub struct LogLevel(pub u32); impl fmt::Show for LogLevel { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::String::fmt(self, fmt) } } impl fmt::String for LogLevel { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let LogLevel(level) = *self; match LOG_LEVEL_NAMES.get(level as uint - 1) { Some(ref name) => fmt::String::fmt(name, fmt), None => fmt::String::fmt(&level, fmt) } } } impl Logger for DefaultLogger { fn log(&mut self, record: &LogRecord) { match writeln!(&mut self.handle, "{}:{}: {}", record.level, record.module_path, record.args) { Err(e) => panic!("failed to log: {:?}", e), Ok(()) => {} } } } impl Drop for DefaultLogger { fn drop(&mut self) { // FIXME(#12628): is panicking the right thing to do? match self.handle.flush() { Err(e) => panic!("failed to flush a logger: {:?}", e), Ok(()) => {} } } } /// This function is called directly by the compiler when using the logging /// macros. This function does not take into account whether the log level /// specified is active or not, it will always log something if this method is /// called. /// /// It is not recommended to call this function directly, rather it should be /// invoked through the logging family of macros. #[doc(hidden)] pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments) { // Test the literal string from args against the current filter, if there // is one. match unsafe { FILTER.as_ref() } { Some(filter) if!filter.is_match(&args.to_string()[]) => return, _ => {} } // Completely remove the local logger from TLS in case anyone attempts to // frob the slot while we're doing the logging. This will destroy any logger // set during logging. let mut logger = LOCAL_LOGGER.with(|s| { s.borrow_mut().take() }).unwrap_or_else(|| { box DefaultLogger { handle: io::stderr() } as Box<Logger + Send> }); logger.log(&LogRecord { level: LogLevel(level), args: args, file: loc.file, module_path: loc.module_path, line: loc.line, }); set_logger(logger); } /// Getter for the global log level. This is a function so that it can be called /// safely #[doc(hidden)] #[inline(always)] pub fn log_level() -> u32 { unsafe { LOG_LEVEL } } /// Replaces the task-local logger with the specified logger, returning the old /// logger. pub fn set_logger(logger: Box<Logger + Send>) -> Option<Box<Logger + Send>> { let mut l = Some(logger); LOCAL_LOGGER.with(|slot| { mem::replace(&mut *slot.borrow_mut(), l.take()) }) } /// A LogRecord is created by the logging macros, and passed as the only /// argument to Loggers. #[derive(Show)] pub struct LogRecord<'a> { /// The module path of where the LogRecord originated. pub module_path: &'a str, /// The LogLevel of this record. pub level: LogLevel, /// The arguments from the log line. pub args: fmt::Arguments<'a>, /// The file of where the LogRecord originated. pub file: &'a str, /// The line number of where the LogRecord originated. pub line: uint, } #[doc(hidden)] #[derive(Copy)] pub struct LogLocation { pub module_path: &'static str, pub file: &'static str, pub line: uint, } /// Tests whether a given module's name is enabled for a particular level of /// logging. This is the second layer of defense about determining whether a /// module's log statement should be emitted or not. #[doc(hidden)] pub fn mod_enabled(level: u32, module: &str) -> bool { static INIT: Once = ONCE_INIT; INIT.call_once(init); // It's possible for many threads are in this function, only one of them // will perform the global initialization, but all of them will need to check // again to whether they should really be here or not. Hence, despite this // check being expanded manually in the logging macro, this function checks // the log level again. if level > unsafe { LOG_LEVEL }
// This assertion should never get tripped unless we're in an at_exit // handler after logging has been torn down and a logging attempt was made. assert!(unsafe {!DIRECTIVES.is_null() }); enabled(level, module, unsafe { (*DIRECTIVES).iter() }) } fn enabled(level: u32, module: &str, iter: slice::Iter<directive::LogDirective>) -> bool { // Search for the longest match, the vector is assumed to be pre-sorted. for directive in iter.rev() { match directive.name { Some(ref name) if!module.starts_with(&name[]) => {}, Some(..) | None => { return level <= directive.level } } } level <= DEFAULT_LOG_LEVEL } /// Initialize logging for the current process. /// /// This is not threadsafe at all, so initialization is performed through a /// `Once` primitive (and this function is called from that primitive). fn init() { let (mut directives, filter) = match os::getenv("RUST_LOG") { Some(spec) => directive::parse_logging_spec(&spec[]), None => (Vec::new(), None), }; // Sort the provided directives by length of their name, this allows a // little more efficient lookup at runtime. directives.sort_by(|a, b| { let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0); let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0); alen.cmp(&blen) }); let max_level = { let max = directives.iter().max_by(|d| d.level); max.map(|d| d.level).unwrap_or(DEFAULT_LOG_LEVEL) }; unsafe { LOG_LEVEL = max_level; assert!(FILTER.is_null()); match filter { Some(f) => FILTER = mem::transmute(box f), None => {} } assert!(DIRECTIVES.is_null()); DIRECTIVES = mem::transmute(box directives); // Schedule the cleanup for the globals for when the runtime exits. rt::at_exit(move |:| { assert!(!DIRECTIVES.is_null()); let _directives: Box<Vec<directive::LogDirective>> = mem::transmute(DIRECTIVES); DIRECTIVES = 0 as *const Vec<directive::LogDirective>; if!FILTER.is_null() { let _filter: Box<Regex> = mem::transmute(FILTER); FILTER = 0 as *const _; } }); } } #[cfg(test)] mod tests { use super::enabled; use directive::LogDirective; #[test] fn match_full_path() { let dirs = [ LogDirective { name: Some("crate2".to_string()), level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(enabled(2, "crate1::mod1", dirs.iter())); assert!(!enabled(3, "crate1::mod1", dirs.iter())); assert!(enabled(3, "crate2", dirs.iter())); assert!(!enabled(4, "crate2", dirs.iter())); } #[test] fn no_match() { let dirs = [ LogDirective { name: Some("crate2".to_string()), level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(!enabled(2, "crate3", dirs.iter())); } #[test] fn match_beginning() { let dirs = [ LogDirective { name: Some("crate2".to_string()), level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(enabled(3, "crate2::mod1", dirs.iter())); } #[test] fn match_beginning_longest_match() { let dirs = [ LogDirective { name: Some("crate2".to_string()), level: 3 }, LogDirective { name: Some("crate2::mod".to_string()), level: 4 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(enabled(4, "crate2::mod1", dirs.iter())); assert!(!enabled(4, "crate2", dirs.iter())); } #[test] fn match_default() { let dirs = [ LogDirective { name: None, level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(enabled(2, "crate1::mod1", dirs.iter())); assert!(enabled(3, "crate2::mod2", dirs.iter())); } #[test] fn zero_level() { let dirs = [ LogDirective { name: None, level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 0 } ]; assert!(!enabled(1, "crate1::mod1", dirs.iter())); assert!(enabled(3, "crate2::mod2", dirs.iter())); } }
{ return false }
conditional_block
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Utilities for program-wide and customizable logging //! //! # Examples //! //! ``` //! #[macro_use] extern crate log; //! //! fn main() { //! debug!("this is a debug {:?}", "message"); //! error!("this is printed by default"); //! //! if log_enabled!(log::INFO) { //! let x = 3i * 4i; // expensive computation //! info!("the answer was: {:?}", x); //! } //! } //! ``` //! //! Assumes the binary is `main`: //! //! ```{.bash} //! $ RUST_LOG=error./main //! ERROR:main: this is printed by default //! ``` //! //! ```{.bash} //! $ RUST_LOG=info./main //! ERROR:main: this is printed by default //! INFO:main: the answer was: 12 //! ``` //! //! ```{.bash} //! $ RUST_LOG=debug./main //! DEBUG:main: this is a debug message //! ERROR:main: this is printed by default //! INFO:main: the answer was: 12 //! ``` //! //! You can also set the log level on a per module basis: //! //! ```{.bash} //! $ RUST_LOG=main=info./main //! ERROR:main: this is printed by default //! INFO:main: the answer was: 12 //! ``` //! //! And enable all logging: //! //! ```{.bash} //! $ RUST_LOG=main./main //! DEBUG:main: this is a debug message //! ERROR:main: this is printed by default //! INFO:main: the answer was: 12 //! ``` //! //! # Logging Macros //! //! There are five macros that the logging subsystem uses: //! //! * `log!(level,...)` - the generic logging macro, takes a level as a u32 and any //! related `format!` arguments //! * `debug!(...)` - a macro hard-wired to the log level of `DEBUG` //! * `info!(...)` - a macro hard-wired to the log level of `INFO` //! * `warn!(...)` - a macro hard-wired to the log level of `WARN` //! * `error!(...)` - a macro hard-wired to the log level of `ERROR` //! //! All of these macros use the same style of syntax as the `format!` syntax //! extension. Details about the syntax can be found in the documentation of //! `std::fmt` along with the Rust tutorial/manual. //! //! If you want to check at runtime if a given logging level is enabled (e.g. if the //! information you would want to log is expensive to produce), you can use the //! following macro: //! //! * `log_enabled!(level)` - returns true if logging of the given level is enabled //! //! # Enabling logging //! //! Log levels are controlled on a per-module basis, and by default all logging is //! disabled except for `error!` (a log level of 1). Logging is controlled via the //! `RUST_LOG` environment variable. The value of this environment variable is a //! comma-separated list of logging directives. A logging directive is of the form: //! //! ```text //! path::to::module=log_level //! ``` //! //! The path to the module is rooted in the name of the crate it was compiled for, //! so if your program is contained in a file `hello.rs`, for example, to turn on //! logging for this file you would use a value of `RUST_LOG=hello`. //! Furthermore, this path is a prefix-search, so all modules nested in the //! specified module will also have logging enabled. //! //! The actual `log_level` is optional to specify. If omitted, all logging will be //! enabled. If specified, the it must be either a numeric in the range of 1-255, or //! it must be one of the strings `debug`, `error`, `info`, or `warn`. If a numeric //! is specified, then all logging less than or equal to that numeral is enabled. //! For example, if logging level 3 is active, error, warn, and info logs will be //! printed, but debug will be omitted. //! //! As the log level for a module is optional, the module to enable logging for is //! also optional. If only a `log_level` is provided, then the global log level for //! all modules is set to this value. //! //! Some examples of valid values of `RUST_LOG` are: //! //! * `hello` turns on all logging for the 'hello' module //! * `info` turns on all info logging //! * `hello=debug` turns on debug logging for 'hello' //! * `hello=3` turns on info logging for 'hello' //! * `hello,std::option` turns on hello, and std's option logging //! * `error,hello=warn` turn on global error logging and also warn for hello //! //! # Filtering results //! //! A RUST_LOG directive may include a regex filter. The syntax is to append `/` //! followed by a regex. Each message is checked against the regex, and is only //! logged if it matches. Note that the matching is done after formatting the log //! string but before adding any logging meta-data. There is a single filter for all //! modules. //! //! Some examples: //! //! * `hello/foo` turns on all logging for the 'hello' module where the log message //! includes 'foo'. //! * `info/f.o` turns on all info logging where the log message includes 'foo', //! 'f1o', 'fao', etc. //! * `hello=debug/foo*foo` turns on debug logging for 'hello' where the log //! message includes 'foofoo' or 'fofoo' or 'fooooooofoo', etc. //! * `error,hello=warn/[0-9] scopes` turn on global error logging and also warn for //! hello. In both cases the log message must include a single digit number //! followed by'scopes' //! //! # Performance and Side Effects //! //! Each of these macros will expand to code similar to: //! //! ```rust,ignore //! if log_level <= my_module_log_level() { //! ::log::log(log_level, format!(...)); //! } //! ``` //! //! What this means is that each of these macros are very cheap at runtime if //! they're turned off (just a load and an integer comparison). This also means that //! if logging is disabled, none of the components of the log will be executed. #![crate_name = "log"] #![experimental = "use the crates.io `log` library instead"] #![staged_api] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] #![allow(unknown_features)] #![feature(slicing_syntax)] #![feature(box_syntax)] #![deny(missing_docs)] extern crate regex; use std::cell::RefCell; use std::fmt; use std::io::LineBufferedWriter; use std::io; use std::mem; use std::os; use std::rt; use std::slice; use std::sync::{Once, ONCE_INIT}; use regex::Regex; use directive::LOG_LEVEL_NAMES; #[macro_use] pub mod macros; mod directive; /// Maximum logging level of a module that can be specified. Common logging /// levels are found in the DEBUG/INFO/WARN/ERROR constants. pub const MAX_LOG_LEVEL: u32 = 255; /// The default logging level of a crate if no other is specified. const DEFAULT_LOG_LEVEL: u32 = 1; /// An unsafe constant that is the maximum logging level of any module /// specified. This is the first line of defense to determining whether a /// logging statement should be run. static mut LOG_LEVEL: u32 = MAX_LOG_LEVEL; static mut DIRECTIVES: *const Vec<directive::LogDirective> = 0 as *const Vec<directive::LogDirective>; /// Optional regex filter. static mut FILTER: *const Regex = 0 as *const _; /// Debug log level pub const DEBUG: u32 = 4; /// Info log level pub const INFO: u32 = 3; /// Warn log level pub const WARN: u32 = 2; /// Error log level pub const ERROR: u32 = 1; thread_local! { static LOCAL_LOGGER: RefCell<Option<Box<Logger + Send>>> = { RefCell::new(None) } } /// A trait used to represent an interface to a task-local logger. Each task /// can have its own custom logger which can respond to logging messages /// however it likes. pub trait Logger { /// Logs a single message described by the `record`. fn log(&mut self, record: &LogRecord); } struct DefaultLogger { handle: LineBufferedWriter<io::stdio::StdWriter>, } /// Wraps the log level with fmt implementations. #[derive(Copy, PartialEq, PartialOrd)] pub struct LogLevel(pub u32); impl fmt::Show for LogLevel { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::String::fmt(self, fmt) } } impl fmt::String for LogLevel { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let LogLevel(level) = *self; match LOG_LEVEL_NAMES.get(level as uint - 1) { Some(ref name) => fmt::String::fmt(name, fmt), None => fmt::String::fmt(&level, fmt) } } } impl Logger for DefaultLogger { fn log(&mut self, record: &LogRecord) { match writeln!(&mut self.handle, "{}:{}: {}", record.level, record.module_path, record.args) { Err(e) => panic!("failed to log: {:?}", e), Ok(()) => {} } } } impl Drop for DefaultLogger { fn drop(&mut self) { // FIXME(#12628): is panicking the right thing to do? match self.handle.flush() { Err(e) => panic!("failed to flush a logger: {:?}", e), Ok(()) => {} } } } /// This function is called directly by the compiler when using the logging /// macros. This function does not take into account whether the log level /// specified is active or not, it will always log something if this method is /// called. /// /// It is not recommended to call this function directly, rather it should be /// invoked through the logging family of macros. #[doc(hidden)] pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments) { // Test the literal string from args against the current filter, if there // is one. match unsafe { FILTER.as_ref() } { Some(filter) if!filter.is_match(&args.to_string()[]) => return, _ => {} } // Completely remove the local logger from TLS in case anyone attempts to // frob the slot while we're doing the logging. This will destroy any logger // set during logging. let mut logger = LOCAL_LOGGER.with(|s| { s.borrow_mut().take() }).unwrap_or_else(|| { box DefaultLogger { handle: io::stderr() } as Box<Logger + Send> }); logger.log(&LogRecord { level: LogLevel(level), args: args, file: loc.file, module_path: loc.module_path, line: loc.line, }); set_logger(logger); } /// Getter for the global log level. This is a function so that it can be called /// safely #[doc(hidden)] #[inline(always)] pub fn log_level() -> u32 { unsafe { LOG_LEVEL } } /// Replaces the task-local logger with the specified logger, returning the old /// logger. pub fn set_logger(logger: Box<Logger + Send>) -> Option<Box<Logger + Send>> { let mut l = Some(logger); LOCAL_LOGGER.with(|slot| { mem::replace(&mut *slot.borrow_mut(), l.take()) }) } /// A LogRecord is created by the logging macros, and passed as the only /// argument to Loggers. #[derive(Show)] pub struct LogRecord<'a> { /// The module path of where the LogRecord originated. pub module_path: &'a str, /// The LogLevel of this record. pub level: LogLevel, /// The arguments from the log line. pub args: fmt::Arguments<'a>, /// The file of where the LogRecord originated. pub file: &'a str, /// The line number of where the LogRecord originated. pub line: uint, } #[doc(hidden)] #[derive(Copy)] pub struct LogLocation { pub module_path: &'static str, pub file: &'static str, pub line: uint, } /// Tests whether a given module's name is enabled for a particular level of /// logging. This is the second layer of defense about determining whether a /// module's log statement should be emitted or not. #[doc(hidden)] pub fn mod_enabled(level: u32, module: &str) -> bool
fn enabled(level: u32, module: &str, iter: slice::Iter<directive::LogDirective>) -> bool { // Search for the longest match, the vector is assumed to be pre-sorted. for directive in iter.rev() { match directive.name { Some(ref name) if!module.starts_with(&name[]) => {}, Some(..) | None => { return level <= directive.level } } } level <= DEFAULT_LOG_LEVEL } /// Initialize logging for the current process. /// /// This is not threadsafe at all, so initialization is performed through a /// `Once` primitive (and this function is called from that primitive). fn init() { let (mut directives, filter) = match os::getenv("RUST_LOG") { Some(spec) => directive::parse_logging_spec(&spec[]), None => (Vec::new(), None), }; // Sort the provided directives by length of their name, this allows a // little more efficient lookup at runtime. directives.sort_by(|a, b| { let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0); let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0); alen.cmp(&blen) }); let max_level = { let max = directives.iter().max_by(|d| d.level); max.map(|d| d.level).unwrap_or(DEFAULT_LOG_LEVEL) }; unsafe { LOG_LEVEL = max_level; assert!(FILTER.is_null()); match filter { Some(f) => FILTER = mem::transmute(box f), None => {} } assert!(DIRECTIVES.is_null()); DIRECTIVES = mem::transmute(box directives); // Schedule the cleanup for the globals for when the runtime exits. rt::at_exit(move |:| { assert!(!DIRECTIVES.is_null()); let _directives: Box<Vec<directive::LogDirective>> = mem::transmute(DIRECTIVES); DIRECTIVES = 0 as *const Vec<directive::LogDirective>; if!FILTER.is_null() { let _filter: Box<Regex> = mem::transmute(FILTER); FILTER = 0 as *const _; } }); } } #[cfg(test)] mod tests { use super::enabled; use directive::LogDirective; #[test] fn match_full_path() { let dirs = [ LogDirective { name: Some("crate2".to_string()), level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(enabled(2, "crate1::mod1", dirs.iter())); assert!(!enabled(3, "crate1::mod1", dirs.iter())); assert!(enabled(3, "crate2", dirs.iter())); assert!(!enabled(4, "crate2", dirs.iter())); } #[test] fn no_match() { let dirs = [ LogDirective { name: Some("crate2".to_string()), level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(!enabled(2, "crate3", dirs.iter())); } #[test] fn match_beginning() { let dirs = [ LogDirective { name: Some("crate2".to_string()), level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(enabled(3, "crate2::mod1", dirs.iter())); } #[test] fn match_beginning_longest_match() { let dirs = [ LogDirective { name: Some("crate2".to_string()), level: 3 }, LogDirective { name: Some("crate2::mod".to_string()), level: 4 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(enabled(4, "crate2::mod1", dirs.iter())); assert!(!enabled(4, "crate2", dirs.iter())); } #[test] fn match_default() { let dirs = [ LogDirective { name: None, level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 2 } ]; assert!(enabled(2, "crate1::mod1", dirs.iter())); assert!(enabled(3, "crate2::mod2", dirs.iter())); } #[test] fn zero_level() { let dirs = [ LogDirective { name: None, level: 3 }, LogDirective { name: Some("crate1::mod1".to_string()), level: 0 } ]; assert!(!enabled(1, "crate1::mod1", dirs.iter())); assert!(enabled(3, "crate2::mod2", dirs.iter())); } }
{ static INIT: Once = ONCE_INIT; INIT.call_once(init); // It's possible for many threads are in this function, only one of them // will perform the global initialization, but all of them will need to check // again to whether they should really be here or not. Hence, despite this // check being expanded manually in the logging macro, this function checks // the log level again. if level > unsafe { LOG_LEVEL } { return false } // This assertion should never get tripped unless we're in an at_exit // handler after logging has been torn down and a logging attempt was made. assert!(unsafe { !DIRECTIVES.is_null() }); enabled(level, module, unsafe { (*DIRECTIVES).iter() }) }
identifier_body
arithmetic_ast.rs
#[macro_use] extern crate nom; use std::fmt; use std::fmt::{Display, Debug, Formatter}; use std::str; use std::str::FromStr; use nom::{IResult, digit, multispace}; pub enum Expr { Value(i64), Add(Box<Expr>, Box<Expr>), Sub(Box<Expr>, Box<Expr>), Mul(Box<Expr>, Box<Expr>), Div(Box<Expr>, Box<Expr>), Paren(Box<Expr>), } pub enum Oper { Add, Sub, Mul, Div, } impl Display for Expr { fn fmt(&self, format: &mut Formatter) -> fmt::Result { use self::Expr::*; match *self { Value(val) => write!(format, "{}", val), Add(ref left, ref right) => write!(format, "{} + {}", left, right), Sub(ref left, ref right) => write!(format, "{} - {}", left, right), Mul(ref left, ref right) => write!(format, "{} * {}", left, right), Div(ref left, ref right) => write!(format, "{} / {}", left, right), Paren(ref expr) => write!(format, "({})", expr), } } } impl Debug for Expr { fn fmt(&self, format: &mut Formatter) -> fmt::Result { use self::Expr::*; match *self { Value(val) => write!(format, "{}", val), Add(ref left, ref right) => write!(format, "({:?} + {:?})", left, right), Sub(ref left, ref right) => write!(format, "({:?} - {:?})", left, right), Mul(ref left, ref right) => write!(format, "({:?} * {:?})", left, right), Div(ref left, ref right) => write!(format, "({:?} / {:?})", left, right), Paren(ref expr) => write!(format, "[{:?}]", expr), } } } named!(parens< Expr >, delimited!( delimited!(opt!(multispace), tag!("("), opt!(multispace)), map!(map!(expr, Box::new), Expr::Paren), delimited!(opt!(multispace), tag!(")"), opt!(multispace)) ) ); named!(factor< Expr >, alt_complete!( map!( map_res!( map_res!( delimited!(opt!(multispace), digit, opt!(multispace)), str::from_utf8 ), FromStr::from_str ), Expr::Value) | parens ) ); fn fold_exprs(initial: Expr, remainder: Vec<(Oper, Expr)>) -> Expr { remainder.into_iter().fold(initial, |acc, pair| { let (oper, expr) = pair; match oper { Oper::Add => Expr::Add(Box::new(acc), Box::new(expr)), Oper::Sub => Expr::Sub(Box::new(acc), Box::new(expr)), Oper::Mul => Expr::Mul(Box::new(acc), Box::new(expr)), Oper::Div => Expr::Div(Box::new(acc), Box::new(expr)), } }) } named!(term< Expr >, chain!( initial: factor ~ remainder: many0!( alt!( chain!(tag!("*") ~ mul: factor, || { (Oper::Mul, mul) }) | chain!(tag!("/") ~ div: factor, || { (Oper::Div, div) }) ) ), || fold_exprs(initial, remainder)) ); named!(expr< Expr >, chain!( initial: term ~ remainder: many0!( alt!( chain!(tag!("+") ~ add: term, || { (Oper::Add, add) }) | chain!(tag!("-") ~ sub: term, || { (Oper::Sub, sub) }) ) ), || fold_exprs(initial, remainder)) ); #[test] fn factor_test() { assert_eq!(factor(&b" 3 "[..]).map(|x| format!("{:?}", x)), IResult::Done(&b""[..], String::from("3"))); } #[test] fn term_test() { assert_eq!(term(&b" 3 * 5 "[..]).map(|x| format!("{:?}", x)), IResult::Done(&b""[..], String::from("(3 * 5)"))); } #[test] fn
() { assert_eq!(expr(&b" 1 + 2 * 3 "[..]).map(|x| format!("{:?}", x)), IResult::Done(&b""[..], String::from("(1 + (2 * 3))"))); assert_eq!(expr(&b" 1 + 2 * 3 / 4 - 5 "[..]).map(|x| format!("{:?}", x)), IResult::Done(&b""[..], String::from("((1 + ((2 * 3) / 4)) - 5)"))); assert_eq!(expr(&b" 72 / 2 / 3 "[..]).map(|x| format!("{:?}", x)), IResult::Done(&b""[..], String::from("((72 / 2) / 3)"))); } #[test] fn parens_test() { assert_eq!(expr(&b" ( 1 + 2 ) * 3 "[..]).map(|x| format!("{:?}", x)), IResult::Done(&b""[..], String::from("([(1 + 2)] * 3)"))); }
expr_test
identifier_name
arithmetic_ast.rs
#[macro_use] extern crate nom; use std::fmt; use std::fmt::{Display, Debug, Formatter}; use std::str; use std::str::FromStr; use nom::{IResult, digit, multispace}; pub enum Expr { Value(i64), Add(Box<Expr>, Box<Expr>), Sub(Box<Expr>, Box<Expr>), Mul(Box<Expr>, Box<Expr>), Div(Box<Expr>, Box<Expr>), Paren(Box<Expr>), } pub enum Oper { Add, Sub, Mul, Div, } impl Display for Expr { fn fmt(&self, format: &mut Formatter) -> fmt::Result { use self::Expr::*; match *self { Value(val) => write!(format, "{}", val), Add(ref left, ref right) => write!(format, "{} + {}", left, right), Sub(ref left, ref right) => write!(format, "{} - {}", left, right), Mul(ref left, ref right) => write!(format, "{} * {}", left, right), Div(ref left, ref right) => write!(format, "{} / {}", left, right), Paren(ref expr) => write!(format, "({})", expr), } } } impl Debug for Expr { fn fmt(&self, format: &mut Formatter) -> fmt::Result { use self::Expr::*; match *self { Value(val) => write!(format, "{}", val), Add(ref left, ref right) => write!(format, "({:?} + {:?})", left, right), Sub(ref left, ref right) => write!(format, "({:?} - {:?})", left, right), Mul(ref left, ref right) => write!(format, "({:?} * {:?})", left, right), Div(ref left, ref right) => write!(format, "({:?} / {:?})", left, right), Paren(ref expr) => write!(format, "[{:?}]", expr), } } } named!(parens< Expr >, delimited!( delimited!(opt!(multispace), tag!("("), opt!(multispace)), map!(map!(expr, Box::new), Expr::Paren), delimited!(opt!(multispace), tag!(")"), opt!(multispace)) ) ); named!(factor< Expr >, alt_complete!( map!( map_res!( map_res!( delimited!(opt!(multispace), digit, opt!(multispace)), str::from_utf8 ), FromStr::from_str ), Expr::Value) | parens ) ); fn fold_exprs(initial: Expr, remainder: Vec<(Oper, Expr)>) -> Expr { remainder.into_iter().fold(initial, |acc, pair| { let (oper, expr) = pair; match oper { Oper::Add => Expr::Add(Box::new(acc), Box::new(expr)), Oper::Sub => Expr::Sub(Box::new(acc), Box::new(expr)), Oper::Mul => Expr::Mul(Box::new(acc), Box::new(expr)), Oper::Div => Expr::Div(Box::new(acc), Box::new(expr)), } }) } named!(term< Expr >, chain!( initial: factor ~
chain!(tag!("/") ~ div: factor, || { (Oper::Div, div) }) ) ), || fold_exprs(initial, remainder)) ); named!(expr< Expr >, chain!( initial: term ~ remainder: many0!( alt!( chain!(tag!("+") ~ add: term, || { (Oper::Add, add) }) | chain!(tag!("-") ~ sub: term, || { (Oper::Sub, sub) }) ) ), || fold_exprs(initial, remainder)) ); #[test] fn factor_test() { assert_eq!(factor(&b" 3 "[..]).map(|x| format!("{:?}", x)), IResult::Done(&b""[..], String::from("3"))); } #[test] fn term_test() { assert_eq!(term(&b" 3 * 5 "[..]).map(|x| format!("{:?}", x)), IResult::Done(&b""[..], String::from("(3 * 5)"))); } #[test] fn expr_test() { assert_eq!(expr(&b" 1 + 2 * 3 "[..]).map(|x| format!("{:?}", x)), IResult::Done(&b""[..], String::from("(1 + (2 * 3))"))); assert_eq!(expr(&b" 1 + 2 * 3 / 4 - 5 "[..]).map(|x| format!("{:?}", x)), IResult::Done(&b""[..], String::from("((1 + ((2 * 3) / 4)) - 5)"))); assert_eq!(expr(&b" 72 / 2 / 3 "[..]).map(|x| format!("{:?}", x)), IResult::Done(&b""[..], String::from("((72 / 2) / 3)"))); } #[test] fn parens_test() { assert_eq!(expr(&b" ( 1 + 2 ) * 3 "[..]).map(|x| format!("{:?}", x)), IResult::Done(&b""[..], String::from("([(1 + 2)] * 3)"))); }
remainder: many0!( alt!( chain!(tag!("*") ~ mul: factor, || { (Oper::Mul, mul) }) |
random_line_split
at_exit_imp.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. //! Implementation of running at_exit routines //! //! Documentation can be found on the `rt::at_exit` function. use core::prelude::*; use boxed::Box; use vec::Vec; use mem; use thunk::Thunk; use sys_common::mutex::{Mutex, MUTEX_INIT}; type Queue = Vec<Thunk<'static>>; // NB these are specifically not types from `std::sync` as they currently rely // on poisoning and this module needs to operate at a lower level than requiring // the thread infrastructure to be in place (useful on the borders of // initialization/destruction). static LOCK: Mutex = MUTEX_INIT; static mut QUEUE: *mut Queue = 0 as *mut Queue; unsafe fn init() { if QUEUE.is_null()
else { // can't re-init after a cleanup rtassert!(QUEUE as uint!= 1); } // FIXME: switch this to use atexit as below. Currently this // segfaults (the queue's memory is mysteriously gone), so // instead the cleanup is tied to the `std::rt` entry point. // // ::libc::atexit(cleanup); } pub fn cleanup() { unsafe { LOCK.lock(); let queue = QUEUE; QUEUE = 1 as *mut _; LOCK.unlock(); // make sure we're not recursively cleaning up rtassert!(queue as uint!= 1); // If we never called init, not need to cleanup! if queue as uint!= 0 { let queue: Box<Queue> = mem::transmute(queue); for to_run in *queue { to_run.invoke(()); } } } } pub fn push(f: Thunk<'static>) { unsafe { LOCK.lock(); init(); (*QUEUE).push(f); LOCK.unlock(); } }
{ let state: Box<Queue> = box Vec::new(); QUEUE = mem::transmute(state); }
conditional_block
at_exit_imp.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. //! Implementation of running at_exit routines //! //! Documentation can be found on the `rt::at_exit` function. use core::prelude::*; use boxed::Box; use vec::Vec; use mem; use thunk::Thunk; use sys_common::mutex::{Mutex, MUTEX_INIT}; type Queue = Vec<Thunk<'static>>; // NB these are specifically not types from `std::sync` as they currently rely // on poisoning and this module needs to operate at a lower level than requiring // the thread infrastructure to be in place (useful on the borders of // initialization/destruction). static LOCK: Mutex = MUTEX_INIT; static mut QUEUE: *mut Queue = 0 as *mut Queue; unsafe fn init()
pub fn cleanup() { unsafe { LOCK.lock(); let queue = QUEUE; QUEUE = 1 as *mut _; LOCK.unlock(); // make sure we're not recursively cleaning up rtassert!(queue as uint!= 1); // If we never called init, not need to cleanup! if queue as uint!= 0 { let queue: Box<Queue> = mem::transmute(queue); for to_run in *queue { to_run.invoke(()); } } } } pub fn push(f: Thunk<'static>) { unsafe { LOCK.lock(); init(); (*QUEUE).push(f); LOCK.unlock(); } }
{ if QUEUE.is_null() { let state: Box<Queue> = box Vec::new(); QUEUE = mem::transmute(state); } else { // can't re-init after a cleanup rtassert!(QUEUE as uint != 1); } // FIXME: switch this to use atexit as below. Currently this // segfaults (the queue's memory is mysteriously gone), so // instead the cleanup is tied to the `std::rt` entry point. // // ::libc::atexit(cleanup); }
identifier_body
at_exit_imp.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. //! Implementation of running at_exit routines //! //! Documentation can be found on the `rt::at_exit` function. use core::prelude::*; use boxed::Box; use vec::Vec; use mem; use thunk::Thunk; use sys_common::mutex::{Mutex, MUTEX_INIT}; type Queue = Vec<Thunk<'static>>; // NB these are specifically not types from `std::sync` as they currently rely // on poisoning and this module needs to operate at a lower level than requiring // the thread infrastructure to be in place (useful on the borders of // initialization/destruction). static LOCK: Mutex = MUTEX_INIT; static mut QUEUE: *mut Queue = 0 as *mut Queue; unsafe fn init() { if QUEUE.is_null() { let state: Box<Queue> = box Vec::new(); QUEUE = mem::transmute(state); } else { // can't re-init after a cleanup rtassert!(QUEUE as uint!= 1); } // FIXME: switch this to use atexit as below. Currently this // segfaults (the queue's memory is mysteriously gone), so // instead the cleanup is tied to the `std::rt` entry point. // // ::libc::atexit(cleanup); } pub fn cleanup() { unsafe { LOCK.lock(); let queue = QUEUE; QUEUE = 1 as *mut _; LOCK.unlock(); // make sure we're not recursively cleaning up rtassert!(queue as uint!= 1); // If we never called init, not need to cleanup! if queue as uint!= 0 { let queue: Box<Queue> = mem::transmute(queue); for to_run in *queue { to_run.invoke(()); } } } } pub fn push(f: Thunk<'static>) { unsafe { LOCK.lock(); init(); (*QUEUE).push(f); LOCK.unlock(); } }
random_line_split
at_exit_imp.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. //! Implementation of running at_exit routines //! //! Documentation can be found on the `rt::at_exit` function. use core::prelude::*; use boxed::Box; use vec::Vec; use mem; use thunk::Thunk; use sys_common::mutex::{Mutex, MUTEX_INIT}; type Queue = Vec<Thunk<'static>>; // NB these are specifically not types from `std::sync` as they currently rely // on poisoning and this module needs to operate at a lower level than requiring // the thread infrastructure to be in place (useful on the borders of // initialization/destruction). static LOCK: Mutex = MUTEX_INIT; static mut QUEUE: *mut Queue = 0 as *mut Queue; unsafe fn
() { if QUEUE.is_null() { let state: Box<Queue> = box Vec::new(); QUEUE = mem::transmute(state); } else { // can't re-init after a cleanup rtassert!(QUEUE as uint!= 1); } // FIXME: switch this to use atexit as below. Currently this // segfaults (the queue's memory is mysteriously gone), so // instead the cleanup is tied to the `std::rt` entry point. // // ::libc::atexit(cleanup); } pub fn cleanup() { unsafe { LOCK.lock(); let queue = QUEUE; QUEUE = 1 as *mut _; LOCK.unlock(); // make sure we're not recursively cleaning up rtassert!(queue as uint!= 1); // If we never called init, not need to cleanup! if queue as uint!= 0 { let queue: Box<Queue> = mem::transmute(queue); for to_run in *queue { to_run.invoke(()); } } } } pub fn push(f: Thunk<'static>) { unsafe { LOCK.lock(); init(); (*QUEUE).push(f); LOCK.unlock(); } }
init
identifier_name
htmlselectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLSelectElementDerived, HTMLFieldSetElementDerived}; use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement; use dom::bindings::js::{JSRef, Temporary}; use dom::document::Document; use dom::element::{AttributeHandlers, Element}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; use string_cache::Atom; #[dom_struct] pub struct HTMLSelectElement { htmlelement: HTMLElement } impl HTMLSelectElementDerived for EventTarget { fn is_htmlselectelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement))) } } impl HTMLSelectElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLSelectElement { HTMLSelectElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLSelectElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLSelectElement> { let element = HTMLSelectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap) } } impl<'a> HTMLSelectElementMethods for JSRef<'a, HTMLSelectElement> { fn Validity(self) -> Temporary<ValidityState>
// Note: this function currently only exists for test_union.html. fn Add(self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // http://www.whatwg.org/html/#dom-fe-disabled make_bool_getter!(Disabled) // http://www.whatwg.org/html/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled") // https://html.spec.whatwg.org/multipage/forms.html#dom-select-type fn Type(self) -> DOMString { let elem: JSRef<Element> = ElementCast::from_ref(self); if elem.has_attribute(&atom!("multiple")) { "select-multiple".into_string() } else { "select-one".into_string() } } } impl<'a> VirtualMethods for JSRef<'a, HTMLSelectElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.after_set_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(true); node.set_enabled_state(false); }, _ => () } } fn before_remove_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.before_remove_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(false); node.set_enabled_state(true); node.check_ancestors_disabled_state_for_form_control(); }, _ => () } } fn bind_to_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.bind_to_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); node.check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.unbind_from_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); if node.ancestors().any(|ancestor| ancestor.is_htmlfieldsetelement()) { node.check_ancestors_disabled_state_for_form_control(); } else { node.check_disabled_attribute(); } } }
{ let window = window_from_node(self).root(); ValidityState::new(window.r()) }
identifier_body
htmlselectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLSelectElementDerived, HTMLFieldSetElementDerived}; use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement; use dom::bindings::js::{JSRef, Temporary}; use dom::document::Document; use dom::element::{AttributeHandlers, Element}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; use string_cache::Atom; #[dom_struct] pub struct HTMLSelectElement { htmlelement: HTMLElement } impl HTMLSelectElementDerived for EventTarget { fn is_htmlselectelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement))) } } impl HTMLSelectElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLSelectElement { HTMLSelectElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLSelectElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLSelectElement> { let element = HTMLSelectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap) } } impl<'a> HTMLSelectElementMethods for JSRef<'a, HTMLSelectElement> { fn Validity(self) -> Temporary<ValidityState> { let window = window_from_node(self).root(); ValidityState::new(window.r()) } // Note: this function currently only exists for test_union.html. fn Add(self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // http://www.whatwg.org/html/#dom-fe-disabled make_bool_getter!(Disabled) // http://www.whatwg.org/html/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled") // https://html.spec.whatwg.org/multipage/forms.html#dom-select-type fn Type(self) -> DOMString { let elem: JSRef<Element> = ElementCast::from_ref(self); if elem.has_attribute(&atom!("multiple"))
else { "select-one".into_string() } } } impl<'a> VirtualMethods for JSRef<'a, HTMLSelectElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.after_set_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(true); node.set_enabled_state(false); }, _ => () } } fn before_remove_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.before_remove_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(false); node.set_enabled_state(true); node.check_ancestors_disabled_state_for_form_control(); }, _ => () } } fn bind_to_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.bind_to_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); node.check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.unbind_from_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); if node.ancestors().any(|ancestor| ancestor.is_htmlfieldsetelement()) { node.check_ancestors_disabled_state_for_form_control(); } else { node.check_disabled_attribute(); } } }
{ "select-multiple".into_string() }
conditional_block
htmlselectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLSelectElementDerived, HTMLFieldSetElementDerived}; use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement; use dom::bindings::js::{JSRef, Temporary}; use dom::document::Document; use dom::element::{AttributeHandlers, Element}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; use string_cache::Atom; #[dom_struct] pub struct HTMLSelectElement { htmlelement: HTMLElement } impl HTMLSelectElementDerived for EventTarget { fn is_htmlselectelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement))) } } impl HTMLSelectElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLSelectElement { HTMLSelectElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLSelectElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLSelectElement> { let element = HTMLSelectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap) } } impl<'a> HTMLSelectElementMethods for JSRef<'a, HTMLSelectElement> { fn Validity(self) -> Temporary<ValidityState> { let window = window_from_node(self).root(); ValidityState::new(window.r()) } // Note: this function currently only exists for test_union.html. fn Add(self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // http://www.whatwg.org/html/#dom-fe-disabled make_bool_getter!(Disabled) // http://www.whatwg.org/html/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled") // https://html.spec.whatwg.org/multipage/forms.html#dom-select-type fn Type(self) -> DOMString { let elem: JSRef<Element> = ElementCast::from_ref(self); if elem.has_attribute(&atom!("multiple")) { "select-multiple".into_string() } else { "select-one".into_string() } } } impl<'a> VirtualMethods for JSRef<'a, HTMLSelectElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.after_set_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(true); node.set_enabled_state(false); }, _ => () } } fn before_remove_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.before_remove_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(false); node.set_enabled_state(true); node.check_ancestors_disabled_state_for_form_control(); }, _ => () } } fn bind_to_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.bind_to_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); node.check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, tree_in_doc: bool) {
let node: JSRef<Node> = NodeCast::from_ref(*self); if node.ancestors().any(|ancestor| ancestor.is_htmlfieldsetelement()) { node.check_ancestors_disabled_state_for_form_control(); } else { node.check_disabled_attribute(); } } }
match self.super_type() { Some(ref s) => s.unbind_from_tree(tree_in_doc), _ => (), }
random_line_split
htmlselectelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLSelectElementDerived, HTMLFieldSetElementDerived}; use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement; use dom::bindings::js::{JSRef, Temporary}; use dom::document::Document; use dom::element::{AttributeHandlers, Element}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; use string_cache::Atom; #[dom_struct] pub struct HTMLSelectElement { htmlelement: HTMLElement } impl HTMLSelectElementDerived for EventTarget { fn is_htmlselectelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement))) } } impl HTMLSelectElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLSelectElement { HTMLSelectElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLSelectElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLSelectElement> { let element = HTMLSelectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap) } } impl<'a> HTMLSelectElementMethods for JSRef<'a, HTMLSelectElement> { fn Validity(self) -> Temporary<ValidityState> { let window = window_from_node(self).root(); ValidityState::new(window.r()) } // Note: this function currently only exists for test_union.html. fn Add(self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // http://www.whatwg.org/html/#dom-fe-disabled make_bool_getter!(Disabled) // http://www.whatwg.org/html/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled") // https://html.spec.whatwg.org/multipage/forms.html#dom-select-type fn Type(self) -> DOMString { let elem: JSRef<Element> = ElementCast::from_ref(self); if elem.has_attribute(&atom!("multiple")) { "select-multiple".into_string() } else { "select-one".into_string() } } } impl<'a> VirtualMethods for JSRef<'a, HTMLSelectElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.after_set_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(true); node.set_enabled_state(false); }, _ => () } } fn
(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.before_remove_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(false); node.set_enabled_state(true); node.check_ancestors_disabled_state_for_form_control(); }, _ => () } } fn bind_to_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.bind_to_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); node.check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, tree_in_doc: bool) { match self.super_type() { Some(ref s) => s.unbind_from_tree(tree_in_doc), _ => (), } let node: JSRef<Node> = NodeCast::from_ref(*self); if node.ancestors().any(|ancestor| ancestor.is_htmlfieldsetelement()) { node.check_ancestors_disabled_state_for_form_control(); } else { node.check_disabled_attribute(); } } }
before_remove_attr
identifier_name
pattern.rs
use address::PAYMENT_ADDRESS_PREFIX; use bs58; use byteorder::{BigEndian, ByteOrder}; use std::fmt; #[derive(Clone)] pub struct Pattern { pub prefix: String, pub range: (u64, u64), } impl fmt::Display for Pattern { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(self.prefix.as_str()) } } impl Pattern { pub fn new(prefix: String) -> Result<Pattern, String> { match prefix_to_range_u64(prefix.as_str()) { Ok(range) => Ok(Pattern { prefix, range, }), Err(err) => Err(err), } } pub fn case_insensitive(&self) -> Vec<Pattern> { let prefix_bytes = self.prefix.as_bytes().to_owned(); let mut patterns = vec![]; let alpha = bs58::alphabet::DEFAULT; let mut rev = [0xff; 128]; for (i, &c) in alpha.iter().enumerate() { rev[c as usize] = i; } for (i, &c) in alpha.iter().enumerate() { let lower = (c as char).to_lowercase().next().unwrap() as usize; if lower!= c as usize && rev[lower]!= 0xff { rev[c as usize] = rev[lower]; rev[lower] = i; } } let mut i = 0; let mut max = 1; while i < max { let mut tmp = prefix_bytes.clone().to_owned(); let mut k = 1u64; for c in &mut tmp { if alpha[rev[*c as usize]]!= *c { if i & k!= 0 { *c = alpha[rev[*c as usize]]; } k <<= 1; } } max = k; if let Ok(pattern) = Pattern::new(String::from_utf8(tmp).unwrap()) { patterns.push(pattern); } i += 1; } patterns } } fn prefix_to_range_u64(prefix: &str) -> Result<(u64, u64), String> { // 2-byte prefix, 32-byte a_pk, 32-byte pk_enc, 4-byte check let mut address_data = [0u8; 2 + 32 * 2 + 4]; address_data[..2].copy_from_slice(&PAYMENT_ADDRESS_PREFIX); let address_00 = bs58::encode(address_data.as_ref()).into_string(); for d in address_data.iter_mut().skip(2) { *d = 0xff; } let address_ff = bs58::encode(address_data.as_ref()).into_string(); let suffix_length = address_ff.len() - prefix.len(); let prefix_1 = prefix.to_owned() + &"1".repeat(suffix_length); let prefix_z = prefix.to_owned() + &"z".repeat(suffix_length); if prefix_z < address_00 { return Err(format!( "Invalid z-addr: {} < {}", prefix, &address_00[..prefix.len()] )); } if prefix_1 > address_ff { return Err(format!( "Invalid z-addr: {} > {}", prefix, &address_ff[..prefix.len()] )); } let pattern_1 = if prefix_1 < address_00 { <u64>::min_value() } else { bs58::decode(prefix_1).into(address_data.as_mut()).unwrap(); BigEndian::read_u64(&address_data[2..10]) }; let pattern_z = if prefix_z > address_ff { <u64>::max_value() } else { bs58::decode(prefix_z).into(address_data.as_mut()).unwrap(); BigEndian::read_u64(&address_data[2..10]) }; Ok((pattern_1, pattern_z)) } #[cfg(test)] mod test { use super::*; #[test] fn case_insensitive_vanity() { let pattern = Pattern::new("zcVANiTY".to_string()).unwrap(); assert_eq!( pattern .case_insensitive() .iter() .map(|p| p.prefix.as_str()) .collect::<Vec<&str>>(), vec![ "zcVANiTY", "zcVaNiTY", "zcVAniTY", "zcVaniTY", "zcVANitY", "zcVaNitY", "zcVAnitY", "zcVanitY", "zcVANiTy", "zcVaNiTy", "zcVAniTy", "zcVaniTy", "zcVANity", "zcVaNity", "zcVAnity", "zcVanity", ] ); } #[test] fn
() { let pattern = Pattern::new("zcA".to_string()).unwrap(); assert_eq!( pattern .case_insensitive() .iter() .map(|p| p.prefix.as_str()) .collect::<Vec<&str>>(), vec![ "zcA", "zca", ] ); } }
case_insensitive_a
identifier_name
pattern.rs
use address::PAYMENT_ADDRESS_PREFIX; use bs58; use byteorder::{BigEndian, ByteOrder}; use std::fmt; #[derive(Clone)] pub struct Pattern { pub prefix: String, pub range: (u64, u64), } impl fmt::Display for Pattern { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(self.prefix.as_str()) } } impl Pattern { pub fn new(prefix: String) -> Result<Pattern, String>
pub fn case_insensitive(&self) -> Vec<Pattern> { let prefix_bytes = self.prefix.as_bytes().to_owned(); let mut patterns = vec![]; let alpha = bs58::alphabet::DEFAULT; let mut rev = [0xff; 128]; for (i, &c) in alpha.iter().enumerate() { rev[c as usize] = i; } for (i, &c) in alpha.iter().enumerate() { let lower = (c as char).to_lowercase().next().unwrap() as usize; if lower!= c as usize && rev[lower]!= 0xff { rev[c as usize] = rev[lower]; rev[lower] = i; } } let mut i = 0; let mut max = 1; while i < max { let mut tmp = prefix_bytes.clone().to_owned(); let mut k = 1u64; for c in &mut tmp { if alpha[rev[*c as usize]]!= *c { if i & k!= 0 { *c = alpha[rev[*c as usize]]; } k <<= 1; } } max = k; if let Ok(pattern) = Pattern::new(String::from_utf8(tmp).unwrap()) { patterns.push(pattern); } i += 1; } patterns } } fn prefix_to_range_u64(prefix: &str) -> Result<(u64, u64), String> { // 2-byte prefix, 32-byte a_pk, 32-byte pk_enc, 4-byte check let mut address_data = [0u8; 2 + 32 * 2 + 4]; address_data[..2].copy_from_slice(&PAYMENT_ADDRESS_PREFIX); let address_00 = bs58::encode(address_data.as_ref()).into_string(); for d in address_data.iter_mut().skip(2) { *d = 0xff; } let address_ff = bs58::encode(address_data.as_ref()).into_string(); let suffix_length = address_ff.len() - prefix.len(); let prefix_1 = prefix.to_owned() + &"1".repeat(suffix_length); let prefix_z = prefix.to_owned() + &"z".repeat(suffix_length); if prefix_z < address_00 { return Err(format!( "Invalid z-addr: {} < {}", prefix, &address_00[..prefix.len()] )); } if prefix_1 > address_ff { return Err(format!( "Invalid z-addr: {} > {}", prefix, &address_ff[..prefix.len()] )); } let pattern_1 = if prefix_1 < address_00 { <u64>::min_value() } else { bs58::decode(prefix_1).into(address_data.as_mut()).unwrap(); BigEndian::read_u64(&address_data[2..10]) }; let pattern_z = if prefix_z > address_ff { <u64>::max_value() } else { bs58::decode(prefix_z).into(address_data.as_mut()).unwrap(); BigEndian::read_u64(&address_data[2..10]) }; Ok((pattern_1, pattern_z)) } #[cfg(test)] mod test { use super::*; #[test] fn case_insensitive_vanity() { let pattern = Pattern::new("zcVANiTY".to_string()).unwrap(); assert_eq!( pattern .case_insensitive() .iter() .map(|p| p.prefix.as_str()) .collect::<Vec<&str>>(), vec![ "zcVANiTY", "zcVaNiTY", "zcVAniTY", "zcVaniTY", "zcVANitY", "zcVaNitY", "zcVAnitY", "zcVanitY", "zcVANiTy", "zcVaNiTy", "zcVAniTy", "zcVaniTy", "zcVANity", "zcVaNity", "zcVAnity", "zcVanity", ] ); } #[test] fn case_insensitive_a() { let pattern = Pattern::new("zcA".to_string()).unwrap(); assert_eq!( pattern .case_insensitive() .iter() .map(|p| p.prefix.as_str()) .collect::<Vec<&str>>(), vec![ "zcA", "zca", ] ); } }
{ match prefix_to_range_u64(prefix.as_str()) { Ok(range) => Ok(Pattern { prefix, range, }), Err(err) => Err(err), } }
identifier_body
pattern.rs
use address::PAYMENT_ADDRESS_PREFIX; use bs58; use byteorder::{BigEndian, ByteOrder}; use std::fmt; #[derive(Clone)] pub struct Pattern { pub prefix: String, pub range: (u64, u64), } impl fmt::Display for Pattern { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(self.prefix.as_str()) } } impl Pattern { pub fn new(prefix: String) -> Result<Pattern, String> { match prefix_to_range_u64(prefix.as_str()) { Ok(range) => Ok(Pattern { prefix, range, }), Err(err) => Err(err), } } pub fn case_insensitive(&self) -> Vec<Pattern> { let prefix_bytes = self.prefix.as_bytes().to_owned(); let mut patterns = vec![]; let alpha = bs58::alphabet::DEFAULT; let mut rev = [0xff; 128]; for (i, &c) in alpha.iter().enumerate() { rev[c as usize] = i; } for (i, &c) in alpha.iter().enumerate() { let lower = (c as char).to_lowercase().next().unwrap() as usize; if lower!= c as usize && rev[lower]!= 0xff { rev[c as usize] = rev[lower]; rev[lower] = i; } } let mut i = 0; let mut max = 1; while i < max { let mut tmp = prefix_bytes.clone().to_owned(); let mut k = 1u64;
k <<= 1; } } max = k; if let Ok(pattern) = Pattern::new(String::from_utf8(tmp).unwrap()) { patterns.push(pattern); } i += 1; } patterns } } fn prefix_to_range_u64(prefix: &str) -> Result<(u64, u64), String> { // 2-byte prefix, 32-byte a_pk, 32-byte pk_enc, 4-byte check let mut address_data = [0u8; 2 + 32 * 2 + 4]; address_data[..2].copy_from_slice(&PAYMENT_ADDRESS_PREFIX); let address_00 = bs58::encode(address_data.as_ref()).into_string(); for d in address_data.iter_mut().skip(2) { *d = 0xff; } let address_ff = bs58::encode(address_data.as_ref()).into_string(); let suffix_length = address_ff.len() - prefix.len(); let prefix_1 = prefix.to_owned() + &"1".repeat(suffix_length); let prefix_z = prefix.to_owned() + &"z".repeat(suffix_length); if prefix_z < address_00 { return Err(format!( "Invalid z-addr: {} < {}", prefix, &address_00[..prefix.len()] )); } if prefix_1 > address_ff { return Err(format!( "Invalid z-addr: {} > {}", prefix, &address_ff[..prefix.len()] )); } let pattern_1 = if prefix_1 < address_00 { <u64>::min_value() } else { bs58::decode(prefix_1).into(address_data.as_mut()).unwrap(); BigEndian::read_u64(&address_data[2..10]) }; let pattern_z = if prefix_z > address_ff { <u64>::max_value() } else { bs58::decode(prefix_z).into(address_data.as_mut()).unwrap(); BigEndian::read_u64(&address_data[2..10]) }; Ok((pattern_1, pattern_z)) } #[cfg(test)] mod test { use super::*; #[test] fn case_insensitive_vanity() { let pattern = Pattern::new("zcVANiTY".to_string()).unwrap(); assert_eq!( pattern .case_insensitive() .iter() .map(|p| p.prefix.as_str()) .collect::<Vec<&str>>(), vec![ "zcVANiTY", "zcVaNiTY", "zcVAniTY", "zcVaniTY", "zcVANitY", "zcVaNitY", "zcVAnitY", "zcVanitY", "zcVANiTy", "zcVaNiTy", "zcVAniTy", "zcVaniTy", "zcVANity", "zcVaNity", "zcVAnity", "zcVanity", ] ); } #[test] fn case_insensitive_a() { let pattern = Pattern::new("zcA".to_string()).unwrap(); assert_eq!( pattern .case_insensitive() .iter() .map(|p| p.prefix.as_str()) .collect::<Vec<&str>>(), vec![ "zcA", "zca", ] ); } }
for c in &mut tmp { if alpha[rev[*c as usize]] != *c { if i & k != 0 { *c = alpha[rev[*c as usize]]; }
random_line_split
pattern.rs
use address::PAYMENT_ADDRESS_PREFIX; use bs58; use byteorder::{BigEndian, ByteOrder}; use std::fmt; #[derive(Clone)] pub struct Pattern { pub prefix: String, pub range: (u64, u64), } impl fmt::Display for Pattern { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(self.prefix.as_str()) } } impl Pattern { pub fn new(prefix: String) -> Result<Pattern, String> { match prefix_to_range_u64(prefix.as_str()) { Ok(range) => Ok(Pattern { prefix, range, }), Err(err) => Err(err), } } pub fn case_insensitive(&self) -> Vec<Pattern> { let prefix_bytes = self.prefix.as_bytes().to_owned(); let mut patterns = vec![]; let alpha = bs58::alphabet::DEFAULT; let mut rev = [0xff; 128]; for (i, &c) in alpha.iter().enumerate() { rev[c as usize] = i; } for (i, &c) in alpha.iter().enumerate() { let lower = (c as char).to_lowercase().next().unwrap() as usize; if lower!= c as usize && rev[lower]!= 0xff { rev[c as usize] = rev[lower]; rev[lower] = i; } } let mut i = 0; let mut max = 1; while i < max { let mut tmp = prefix_bytes.clone().to_owned(); let mut k = 1u64; for c in &mut tmp { if alpha[rev[*c as usize]]!= *c { if i & k!= 0
k <<= 1; } } max = k; if let Ok(pattern) = Pattern::new(String::from_utf8(tmp).unwrap()) { patterns.push(pattern); } i += 1; } patterns } } fn prefix_to_range_u64(prefix: &str) -> Result<(u64, u64), String> { // 2-byte prefix, 32-byte a_pk, 32-byte pk_enc, 4-byte check let mut address_data = [0u8; 2 + 32 * 2 + 4]; address_data[..2].copy_from_slice(&PAYMENT_ADDRESS_PREFIX); let address_00 = bs58::encode(address_data.as_ref()).into_string(); for d in address_data.iter_mut().skip(2) { *d = 0xff; } let address_ff = bs58::encode(address_data.as_ref()).into_string(); let suffix_length = address_ff.len() - prefix.len(); let prefix_1 = prefix.to_owned() + &"1".repeat(suffix_length); let prefix_z = prefix.to_owned() + &"z".repeat(suffix_length); if prefix_z < address_00 { return Err(format!( "Invalid z-addr: {} < {}", prefix, &address_00[..prefix.len()] )); } if prefix_1 > address_ff { return Err(format!( "Invalid z-addr: {} > {}", prefix, &address_ff[..prefix.len()] )); } let pattern_1 = if prefix_1 < address_00 { <u64>::min_value() } else { bs58::decode(prefix_1).into(address_data.as_mut()).unwrap(); BigEndian::read_u64(&address_data[2..10]) }; let pattern_z = if prefix_z > address_ff { <u64>::max_value() } else { bs58::decode(prefix_z).into(address_data.as_mut()).unwrap(); BigEndian::read_u64(&address_data[2..10]) }; Ok((pattern_1, pattern_z)) } #[cfg(test)] mod test { use super::*; #[test] fn case_insensitive_vanity() { let pattern = Pattern::new("zcVANiTY".to_string()).unwrap(); assert_eq!( pattern .case_insensitive() .iter() .map(|p| p.prefix.as_str()) .collect::<Vec<&str>>(), vec![ "zcVANiTY", "zcVaNiTY", "zcVAniTY", "zcVaniTY", "zcVANitY", "zcVaNitY", "zcVAnitY", "zcVanitY", "zcVANiTy", "zcVaNiTy", "zcVAniTy", "zcVaniTy", "zcVANity", "zcVaNity", "zcVAnity", "zcVanity", ] ); } #[test] fn case_insensitive_a() { let pattern = Pattern::new("zcA".to_string()).unwrap(); assert_eq!( pattern .case_insensitive() .iter() .map(|p| p.prefix.as_str()) .collect::<Vec<&str>>(), vec![ "zcA", "zca", ] ); } }
{ *c = alpha[rev[*c as usize]]; }
conditional_block
copy.rs
use super::{copy_buf, BufReader, CopyBuf}; use futures_core::future::Future; use futures_core::task::{Context, Poll}; use futures_io::{AsyncRead, AsyncWrite}; use pin_project_lite::pin_project; use std::io; use std::pin::Pin; /// Creates a future which copies all the bytes from one object to another. /// /// The returned future will copy all the bytes read from this `AsyncRead` into the /// `writer` specified. This future will only complete once the `reader` has hit /// EOF and all bytes have been written to and flushed from the `writer` /// provided. /// /// On success the number of bytes is returned. /// /// # Examples /// /// ``` /// # futures::executor::block_on(async { /// use futures::io::{self, AsyncWriteExt, Cursor}; /// /// let reader = Cursor::new([1, 2, 3, 4]); /// let mut writer = Cursor::new(vec![0u8; 5]); /// /// let bytes = io::copy(reader, &mut writer).await?; /// writer.close().await?; /// /// assert_eq!(bytes, 4); /// assert_eq!(writer.into_inner(), [1, 2, 3, 4, 0]); /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap(); /// ``` pub fn copy<R, W>(reader: R, writer: &mut W) -> Copy<'_, R, W> where R: AsyncRead, W: AsyncWrite + Unpin +?Sized,
pin_project! { /// Future for the [`copy()`] function. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Copy<'a, R, W:?Sized> { #[pin] inner: CopyBuf<'a, BufReader<R>, W>, } } impl<R: AsyncRead, W: AsyncWrite + Unpin +?Sized> Future for Copy<'_, R, W> { type Output = io::Result<u64>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { self.project().inner.poll(cx) } }
{ Copy { inner: copy_buf(BufReader::new(reader), writer) } }
identifier_body
copy.rs
use super::{copy_buf, BufReader, CopyBuf}; use futures_core::future::Future; use futures_core::task::{Context, Poll}; use futures_io::{AsyncRead, AsyncWrite}; use pin_project_lite::pin_project; use std::io; use std::pin::Pin; /// Creates a future which copies all the bytes from one object to another. /// /// The returned future will copy all the bytes read from this `AsyncRead` into the /// `writer` specified. This future will only complete once the `reader` has hit /// EOF and all bytes have been written to and flushed from the `writer` /// provided. /// /// On success the number of bytes is returned. /// /// # Examples /// /// ``` /// # futures::executor::block_on(async { /// use futures::io::{self, AsyncWriteExt, Cursor}; /// /// let reader = Cursor::new([1, 2, 3, 4]); /// let mut writer = Cursor::new(vec![0u8; 5]); /// /// let bytes = io::copy(reader, &mut writer).await?; /// writer.close().await?; /// /// assert_eq!(bytes, 4); /// assert_eq!(writer.into_inner(), [1, 2, 3, 4, 0]); /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap(); /// ``` pub fn copy<R, W>(reader: R, writer: &mut W) -> Copy<'_, R, W> where R: AsyncRead, W: AsyncWrite + Unpin +?Sized, { Copy { inner: copy_buf(BufReader::new(reader), writer) } } pin_project! { /// Future for the [`copy()`] function. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Copy<'a, R, W:?Sized> { #[pin] inner: CopyBuf<'a, BufReader<R>, W>, } } impl<R: AsyncRead, W: AsyncWrite + Unpin +?Sized> Future for Copy<'_, R, W> { type Output = io::Result<u64>; fn
(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { self.project().inner.poll(cx) } }
poll
identifier_name
copy.rs
use super::{copy_buf, BufReader, CopyBuf}; use futures_core::future::Future; use futures_core::task::{Context, Poll}; use futures_io::{AsyncRead, AsyncWrite}; use pin_project_lite::pin_project; use std::io; use std::pin::Pin; /// Creates a future which copies all the bytes from one object to another. /// /// The returned future will copy all the bytes read from this `AsyncRead` into the /// `writer` specified. This future will only complete once the `reader` has hit /// EOF and all bytes have been written to and flushed from the `writer` /// provided. /// /// On success the number of bytes is returned. /// /// # Examples /// /// ``` /// # futures::executor::block_on(async { /// use futures::io::{self, AsyncWriteExt, Cursor}; /// /// let reader = Cursor::new([1, 2, 3, 4]); /// let mut writer = Cursor::new(vec![0u8; 5]); /// /// let bytes = io::copy(reader, &mut writer).await?; /// writer.close().await?; /// /// assert_eq!(bytes, 4); /// assert_eq!(writer.into_inner(), [1, 2, 3, 4, 0]); /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap(); /// ``` pub fn copy<R, W>(reader: R, writer: &mut W) -> Copy<'_, R, W> where R: AsyncRead, W: AsyncWrite + Unpin +?Sized, { Copy { inner: copy_buf(BufReader::new(reader), writer) } } pin_project! { /// Future for the [`copy()`] function. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Copy<'a, R, W:?Sized> {
} impl<R: AsyncRead, W: AsyncWrite + Unpin +?Sized> Future for Copy<'_, R, W> { type Output = io::Result<u64>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { self.project().inner.poll(cx) } }
#[pin] inner: CopyBuf<'a, BufReader<R>, W>, }
random_line_split
submatrix.rs
use crate::math::{Determinant, Matrix, Matrix2, Matrix3, Matrix4, Scalar}; pub trait Submatrix : Matrix { type Output: Matrix; fn submatrix(&self, y: usize, x: usize) -> <Self as Submatrix>::Output; fn minor(&self, y: usize, x: usize) -> Scalar { self.submatrix(y, x).determinant() } fn cofactor(&self, y: usize, x: usize) -> Scalar { if (x + y) % 2 == 0 { self.minor(y, x) } else { -self.minor(y, x) } } } impl Submatrix for Matrix3 { type Output = Matrix2; fn submatrix(&self, y: usize, x: usize) -> Matrix2 { let mut data = [[0.0; 2]; 2]; for ny in 0..2 { for nx in 0..2 { let oy = if ny >= y { ny + 1 } else { ny }; let ox = if nx >= x { nx + 1 } else
; data[ny][nx] = self[oy][ox]; } } Matrix2::new(data) } } impl Submatrix for Matrix4 { type Output = Matrix3; fn submatrix(&self, y: usize, x: usize) -> Matrix3 { let mut data = [[0.0; 3]; 3]; for ny in 0..3 { for nx in 0..3 { let oy = if ny >= y { ny + 1 } else { ny }; let ox = if nx >= x { nx + 1 } else { nx }; data[ny][nx] = self[oy][ox]; } } Matrix3::new(data) } }
{ nx }
conditional_block
submatrix.rs
use crate::math::{Determinant, Matrix, Matrix2, Matrix3, Matrix4, Scalar}; pub trait Submatrix : Matrix {
type Output: Matrix; fn submatrix(&self, y: usize, x: usize) -> <Self as Submatrix>::Output; fn minor(&self, y: usize, x: usize) -> Scalar { self.submatrix(y, x).determinant() } fn cofactor(&self, y: usize, x: usize) -> Scalar { if (x + y) % 2 == 0 { self.minor(y, x) } else { -self.minor(y, x) } } } impl Submatrix for Matrix3 { type Output = Matrix2; fn submatrix(&self, y: usize, x: usize) -> Matrix2 { let mut data = [[0.0; 2]; 2]; for ny in 0..2 { for nx in 0..2 { let oy = if ny >= y { ny + 1 } else { ny }; let ox = if nx >= x { nx + 1 } else { nx }; data[ny][nx] = self[oy][ox]; } } Matrix2::new(data) } } impl Submatrix for Matrix4 { type Output = Matrix3; fn submatrix(&self, y: usize, x: usize) -> Matrix3 { let mut data = [[0.0; 3]; 3]; for ny in 0..3 { for nx in 0..3 { let oy = if ny >= y { ny + 1 } else { ny }; let ox = if nx >= x { nx + 1 } else { nx }; data[ny][nx] = self[oy][ox]; } } Matrix3::new(data) } }
random_line_split
submatrix.rs
use crate::math::{Determinant, Matrix, Matrix2, Matrix3, Matrix4, Scalar}; pub trait Submatrix : Matrix { type Output: Matrix; fn submatrix(&self, y: usize, x: usize) -> <Self as Submatrix>::Output; fn minor(&self, y: usize, x: usize) -> Scalar { self.submatrix(y, x).determinant() } fn cofactor(&self, y: usize, x: usize) -> Scalar { if (x + y) % 2 == 0 { self.minor(y, x) } else { -self.minor(y, x) } } } impl Submatrix for Matrix3 { type Output = Matrix2; fn
(&self, y: usize, x: usize) -> Matrix2 { let mut data = [[0.0; 2]; 2]; for ny in 0..2 { for nx in 0..2 { let oy = if ny >= y { ny + 1 } else { ny }; let ox = if nx >= x { nx + 1 } else { nx }; data[ny][nx] = self[oy][ox]; } } Matrix2::new(data) } } impl Submatrix for Matrix4 { type Output = Matrix3; fn submatrix(&self, y: usize, x: usize) -> Matrix3 { let mut data = [[0.0; 3]; 3]; for ny in 0..3 { for nx in 0..3 { let oy = if ny >= y { ny + 1 } else { ny }; let ox = if nx >= x { nx + 1 } else { nx }; data[ny][nx] = self[oy][ox]; } } Matrix3::new(data) } }
submatrix
identifier_name
submatrix.rs
use crate::math::{Determinant, Matrix, Matrix2, Matrix3, Matrix4, Scalar}; pub trait Submatrix : Matrix { type Output: Matrix; fn submatrix(&self, y: usize, x: usize) -> <Self as Submatrix>::Output; fn minor(&self, y: usize, x: usize) -> Scalar { self.submatrix(y, x).determinant() } fn cofactor(&self, y: usize, x: usize) -> Scalar { if (x + y) % 2 == 0 { self.minor(y, x) } else { -self.minor(y, x) } } } impl Submatrix for Matrix3 { type Output = Matrix2; fn submatrix(&self, y: usize, x: usize) -> Matrix2
} impl Submatrix for Matrix4 { type Output = Matrix3; fn submatrix(&self, y: usize, x: usize) -> Matrix3 { let mut data = [[0.0; 3]; 3]; for ny in 0..3 { for nx in 0..3 { let oy = if ny >= y { ny + 1 } else { ny }; let ox = if nx >= x { nx + 1 } else { nx }; data[ny][nx] = self[oy][ox]; } } Matrix3::new(data) } }
{ let mut data = [[0.0; 2]; 2]; for ny in 0..2 { for nx in 0..2 { let oy = if ny >= y { ny + 1 } else { ny }; let ox = if nx >= x { nx + 1 } else { nx }; data[ny][nx] = self[oy][ox]; } } Matrix2::new(data) }
identifier_body
while-loop-constraints-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[allow(dead_assignment)]; #[allow(unused_variable)]; pub fn
() { let mut y: int = 42; let mut z: int = 42; let mut x: int; while z < 50 { z += 1; while false { x = y; y = z; } info!("{}", y); } assert!((y == 42 && z == 50)); }
main
identifier_name
while-loop-constraints-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[allow(dead_assignment)]; #[allow(unused_variable)];
pub fn main() { let mut y: int = 42; let mut z: int = 42; let mut x: int; while z < 50 { z += 1; while false { x = y; y = z; } info!("{}", y); } assert!((y == 42 && z == 50)); }
random_line_split
while-loop-constraints-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[allow(dead_assignment)]; #[allow(unused_variable)]; pub fn main()
{ let mut y: int = 42; let mut z: int = 42; let mut x: int; while z < 50 { z += 1; while false { x = y; y = z; } info!("{}", y); } assert!((y == 42 && z == 50)); }
identifier_body
link.rs
// * This file is part of the uutils coreutils package. // *
use clap::{crate_version, App, AppSettings, Arg}; use std::fs::hard_link; use std::path::Path; use uucore::display::Quotable; use uucore::error::{FromIo, UResult}; use uucore::format_usage; static ABOUT: &str = "Call the link function to create a link named FILE2 to an existing FILE1."; const USAGE: &str = "{} FILE1 FILE2"; pub mod options { pub static FILES: &str = "FILES"; } #[uucore::main] pub fn uumain(args: impl uucore::Args) -> UResult<()> { let matches = uu_app().get_matches_from(args); let files: Vec<_> = matches .values_of_os(options::FILES) .unwrap_or_default() .collect(); let old = Path::new(files[0]); let new = Path::new(files[1]); hard_link(old, new) .map_err_context(|| format!("cannot create link {} to {}", new.quote(), old.quote())) } pub fn uu_app<'a>() -> App<'a> { App::new(uucore::util_name()) .version(crate_version!()) .about(ABOUT) .override_usage(format_usage(USAGE)) .setting(AppSettings::InferLongArgs) .arg( Arg::new(options::FILES) .hide(true) .required(true) .min_values(2) .max_values(2) .takes_value(true) .allow_invalid_utf8(true), ) }
// * (c) Michael Gehring <[email protected]> // * // * For the full copyright and license information, please view the LICENSE // * file that was distributed with this source code.
random_line_split
link.rs
// * This file is part of the uutils coreutils package. // * // * (c) Michael Gehring <[email protected]> // * // * For the full copyright and license information, please view the LICENSE // * file that was distributed with this source code. use clap::{crate_version, App, AppSettings, Arg}; use std::fs::hard_link; use std::path::Path; use uucore::display::Quotable; use uucore::error::{FromIo, UResult}; use uucore::format_usage; static ABOUT: &str = "Call the link function to create a link named FILE2 to an existing FILE1."; const USAGE: &str = "{} FILE1 FILE2"; pub mod options { pub static FILES: &str = "FILES"; } #[uucore::main] pub fn uumain(args: impl uucore::Args) -> UResult<()> { let matches = uu_app().get_matches_from(args); let files: Vec<_> = matches .values_of_os(options::FILES) .unwrap_or_default() .collect(); let old = Path::new(files[0]); let new = Path::new(files[1]); hard_link(old, new) .map_err_context(|| format!("cannot create link {} to {}", new.quote(), old.quote())) } pub fn uu_app<'a>() -> App<'a>
{ App::new(uucore::util_name()) .version(crate_version!()) .about(ABOUT) .override_usage(format_usage(USAGE)) .setting(AppSettings::InferLongArgs) .arg( Arg::new(options::FILES) .hide(true) .required(true) .min_values(2) .max_values(2) .takes_value(true) .allow_invalid_utf8(true), ) }
identifier_body
link.rs
// * This file is part of the uutils coreutils package. // * // * (c) Michael Gehring <[email protected]> // * // * For the full copyright and license information, please view the LICENSE // * file that was distributed with this source code. use clap::{crate_version, App, AppSettings, Arg}; use std::fs::hard_link; use std::path::Path; use uucore::display::Quotable; use uucore::error::{FromIo, UResult}; use uucore::format_usage; static ABOUT: &str = "Call the link function to create a link named FILE2 to an existing FILE1."; const USAGE: &str = "{} FILE1 FILE2"; pub mod options { pub static FILES: &str = "FILES"; } #[uucore::main] pub fn uumain(args: impl uucore::Args) -> UResult<()> { let matches = uu_app().get_matches_from(args); let files: Vec<_> = matches .values_of_os(options::FILES) .unwrap_or_default() .collect(); let old = Path::new(files[0]); let new = Path::new(files[1]); hard_link(old, new) .map_err_context(|| format!("cannot create link {} to {}", new.quote(), old.quote())) } pub fn
<'a>() -> App<'a> { App::new(uucore::util_name()) .version(crate_version!()) .about(ABOUT) .override_usage(format_usage(USAGE)) .setting(AppSettings::InferLongArgs) .arg( Arg::new(options::FILES) .hide(true) .required(true) .min_values(2) .max_values(2) .takes_value(true) .allow_invalid_utf8(true), ) }
uu_app
identifier_name
sign.rs
use integer::Integer; use malachite_base::num::arithmetic::traits::Sign; use std::cmp::Ordering; impl Sign for Integer { /// Returns the sign of an `Integer`. Interpret the result as the result of a comparison to /// zero, so that `Equal` means zero, `Greater` means positive, and `Less` means negative. /// /// Time: worst case O(1) /// /// Additional memory: worst case O(1) /// /// # Examples /// ``` /// extern crate malachite_base; /// extern crate malachite_nz; /// /// use malachite_base::num::arithmetic::traits::Sign; /// use malachite_base::num::basic::traits::Zero; /// use malachite_nz::integer::Integer; /// use std::cmp::Ordering; /// /// assert_eq!(Integer::ZERO.sign(), Ordering::Equal); /// assert_eq!(Integer::from(123).sign(), Ordering::Greater); /// assert_eq!(Integer::from(-123).sign(), Ordering::Less); /// ``` fn sign(&self) -> Ordering { if self.sign { if self.abs == 0
else { Ordering::Greater } } else { Ordering::Less } } }
{ Ordering::Equal }
conditional_block
sign.rs
use integer::Integer; use malachite_base::num::arithmetic::traits::Sign; use std::cmp::Ordering; impl Sign for Integer { /// Returns the sign of an `Integer`. Interpret the result as the result of a comparison to /// zero, so that `Equal` means zero, `Greater` means positive, and `Less` means negative. /// /// Time: worst case O(1) /// /// Additional memory: worst case O(1) /// /// # Examples /// ``` /// extern crate malachite_base; /// extern crate malachite_nz; /// /// use malachite_base::num::arithmetic::traits::Sign; /// use malachite_base::num::basic::traits::Zero; /// use malachite_nz::integer::Integer; /// use std::cmp::Ordering; /// /// assert_eq!(Integer::ZERO.sign(), Ordering::Equal); /// assert_eq!(Integer::from(123).sign(), Ordering::Greater); /// assert_eq!(Integer::from(-123).sign(), Ordering::Less); /// ``` fn
(&self) -> Ordering { if self.sign { if self.abs == 0 { Ordering::Equal } else { Ordering::Greater } } else { Ordering::Less } } }
sign
identifier_name
sign.rs
use integer::Integer; use malachite_base::num::arithmetic::traits::Sign; use std::cmp::Ordering; impl Sign for Integer { /// Returns the sign of an `Integer`. Interpret the result as the result of a comparison to /// zero, so that `Equal` means zero, `Greater` means positive, and `Less` means negative. /// /// Time: worst case O(1) /// /// Additional memory: worst case O(1) /// /// # Examples /// ``` /// extern crate malachite_base; /// extern crate malachite_nz;
/// use std::cmp::Ordering; /// /// assert_eq!(Integer::ZERO.sign(), Ordering::Equal); /// assert_eq!(Integer::from(123).sign(), Ordering::Greater); /// assert_eq!(Integer::from(-123).sign(), Ordering::Less); /// ``` fn sign(&self) -> Ordering { if self.sign { if self.abs == 0 { Ordering::Equal } else { Ordering::Greater } } else { Ordering::Less } } }
/// /// use malachite_base::num::arithmetic::traits::Sign; /// use malachite_base::num::basic::traits::Zero; /// use malachite_nz::integer::Integer;
random_line_split
sign.rs
use integer::Integer; use malachite_base::num::arithmetic::traits::Sign; use std::cmp::Ordering; impl Sign for Integer { /// Returns the sign of an `Integer`. Interpret the result as the result of a comparison to /// zero, so that `Equal` means zero, `Greater` means positive, and `Less` means negative. /// /// Time: worst case O(1) /// /// Additional memory: worst case O(1) /// /// # Examples /// ``` /// extern crate malachite_base; /// extern crate malachite_nz; /// /// use malachite_base::num::arithmetic::traits::Sign; /// use malachite_base::num::basic::traits::Zero; /// use malachite_nz::integer::Integer; /// use std::cmp::Ordering; /// /// assert_eq!(Integer::ZERO.sign(), Ordering::Equal); /// assert_eq!(Integer::from(123).sign(), Ordering::Greater); /// assert_eq!(Integer::from(-123).sign(), Ordering::Less); /// ``` fn sign(&self) -> Ordering
}
{ if self.sign { if self.abs == 0 { Ordering::Equal } else { Ordering::Greater } } else { Ordering::Less } }
identifier_body
shootout-reverse-complement.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2013-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // - Neither the name of "The Computer Language Benchmarks Game" nor // the name of "The Computer Language Shootout Benchmarks" nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. // ignore-android see #10393 #13206 #![feature(unboxed_closures)] extern crate libc; use std::io::stdio::{stdin_raw, stdout_raw}; use std::io::{IoResult, EndOfFile}; use std::ptr::{copy_memory, Unique}; use std::thread::Thread; struct Tables { table8: [u8;1 << 8], table16: [u16;1 << 16] } impl Tables { fn new() -> Tables { let mut table8 = [0;1 << 8]; for (i, v) in table8.iter_mut().enumerate() { *v = Tables::computed_cpl8(i as u8); } let mut table16 = [0;1 << 16]; for (i, v) in table16.iter_mut().enumerate() { *v = (table8[i & 255] as u16) << 8 | table8[i >> 8] as u16; } Tables { table8: table8, table16: table16 } } fn computed_cpl8(c: u8) -> u8 { match c { b'A' | b'a' => b'T', b'C' | b'c' => b'G', b'G' | b'g' => b'C', b'T' | b't' => b'A', b'U' | b'u' => b'A', b'M' | b'm' => b'K', b'R' | b'r' => b'Y', b'W' | b'w' => b'W', b'S' | b's' => b'S',
b'B' | b'b' => b'V', b'N' | b'n' => b'N', i => i, } } /// Retreives the complement for `i`. fn cpl8(&self, i: u8) -> u8 { self.table8[i as uint] } /// Retreives the complement for `i`. fn cpl16(&self, i: u16) -> u16 { self.table16[i as uint] } } /// Reads all remaining bytes from the stream. fn read_to_end<R: Reader>(r: &mut R) -> IoResult<Vec<u8>> { // As reading the input stream in memory is a bottleneck, we tune // Reader::read_to_end() with a fast growing policy to limit // recopies. If MREMAP_RETAIN is implemented in the linux kernel // and jemalloc use it, this trick will become useless. const CHUNK: uint = 64 * 1024; let mut vec = Vec::with_capacity(CHUNK); loop { // workaround: very fast growing let len = vec.len(); if vec.capacity() - len < CHUNK { let cap = vec.capacity(); let mult = if cap < 256 * 1024 * 1024 { 16 } else { 2 }; vec.reserve_exact(mult * cap - len); } match r.push_at_least(1, CHUNK, &mut vec) { Ok(_) => {} Err(ref e) if e.kind == EndOfFile => break, Err(e) => return Err(e) } } Ok(vec) } /// Finds the first position at which `b` occurs in `s`. fn memchr(h: &[u8], n: u8) -> Option<uint> { use libc::{c_void, c_int, size_t}; let res = unsafe { libc::memchr(h.as_ptr() as *const c_void, n as c_int, h.len() as size_t) }; if res.is_null() { None } else { Some(res as uint - h.as_ptr() as uint) } } /// A mutable iterator over DNA sequences struct MutDnaSeqs<'a> { s: &'a mut [u8] } fn mut_dna_seqs<'a>(s: &'a mut [u8]) -> MutDnaSeqs<'a> { MutDnaSeqs { s: s } } impl<'a> Iterator for MutDnaSeqs<'a> { type Item = &'a mut [u8]; fn next(&mut self) -> Option<&'a mut [u8]> { let tmp = std::mem::replace(&mut self.s, &mut []); let tmp = match memchr(tmp, b'\n') { Some(i) => tmp.slice_from_mut(i + 1), None => return None, }; let (seq, tmp) = match memchr(tmp, b'>') { Some(i) => tmp.split_at_mut(i), None => { let len = tmp.len(); tmp.split_at_mut(len) } }; self.s = tmp; Some(seq) } } /// Length of a normal line without the terminating \n. const LINE_LEN: uint = 60; /// Compute the reverse complement. fn reverse_complement(seq: &mut [u8], tables: &Tables) { let seq = seq.init_mut();// Drop the last newline let len = seq.len(); let off = LINE_LEN - len % (LINE_LEN + 1); let mut i = LINE_LEN; while i < len { unsafe { copy_memory(seq.as_mut_ptr().offset((i - off + 1) as int), seq.as_ptr().offset((i - off) as int), off); *seq.get_unchecked_mut(i - off) = b'\n'; } i += LINE_LEN + 1; } let div = len / 4; let rem = len % 4; unsafe { let mut left = seq.as_mut_ptr() as *mut u16; // This is slow if len % 2!= 0 but still faster than bytewise operations. let mut right = seq.as_mut_ptr().offset(len as int - 2) as *mut u16; let end = left.offset(div as int); while left!= end { let tmp = tables.cpl16(*left); *left = tables.cpl16(*right); *right = tmp; left = left.offset(1); right = right.offset(-1); } let end = end as *mut u8; match rem { 1 => *end = tables.cpl8(*end), 2 => { let tmp = tables.cpl8(*end); *end = tables.cpl8(*end.offset(1)); *end.offset(1) = tmp; }, 3 => { *end.offset(1) = tables.cpl8(*end.offset(1)); let tmp = tables.cpl8(*end); *end = tables.cpl8(*end.offset(2)); *end.offset(2) = tmp; }, _ => { }, } } } struct Racy<T>(T); unsafe impl<T:'static> Send for Racy<T> {} /// Executes a closure in parallel over the given iterator over mutable slice. /// The closure `f` is run in parallel with an element of `iter`. fn parallel<'a, I, T, F>(mut iter: I, f: F) where T: 'a+Send + Sync, I: Iterator<Item=&'a mut [T]>, F: Fn(&mut [T]) + Sync { use std::mem; use std::raw::Repr; iter.map(|chunk| { // Need to convert `f` and `chunk` to something that can cross the task // boundary. let f = Racy(&f as *const F as *const uint); let raw = Racy(chunk.repr()); Thread::scoped(move|| { let f = f.0 as *const F; unsafe { (*f)(mem::transmute(raw.0)) } }) }).collect::<Vec<_>>(); } fn main() { let mut data = read_to_end(&mut stdin_raw()).unwrap(); let tables = &Tables::new(); parallel(mut_dna_seqs(data.as_mut_slice()), |&: seq| reverse_complement(seq, tables)); stdout_raw().write(data.as_mut_slice()).unwrap(); }
b'Y' | b'y' => b'R', b'K' | b'k' => b'M', b'V' | b'v' => b'B', b'H' | b'h' => b'D', b'D' | b'd' => b'H',
random_line_split
shootout-reverse-complement.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2013-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // - Neither the name of "The Computer Language Benchmarks Game" nor // the name of "The Computer Language Shootout Benchmarks" nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. // ignore-android see #10393 #13206 #![feature(unboxed_closures)] extern crate libc; use std::io::stdio::{stdin_raw, stdout_raw}; use std::io::{IoResult, EndOfFile}; use std::ptr::{copy_memory, Unique}; use std::thread::Thread; struct Tables { table8: [u8;1 << 8], table16: [u16;1 << 16] } impl Tables { fn new() -> Tables { let mut table8 = [0;1 << 8]; for (i, v) in table8.iter_mut().enumerate() { *v = Tables::computed_cpl8(i as u8); } let mut table16 = [0;1 << 16]; for (i, v) in table16.iter_mut().enumerate() { *v = (table8[i & 255] as u16) << 8 | table8[i >> 8] as u16; } Tables { table8: table8, table16: table16 } } fn computed_cpl8(c: u8) -> u8 { match c { b'A' | b'a' => b'T', b'C' | b'c' => b'G', b'G' | b'g' => b'C', b'T' | b't' => b'A', b'U' | b'u' => b'A', b'M' | b'm' => b'K', b'R' | b'r' => b'Y', b'W' | b'w' => b'W', b'S' | b's' => b'S', b'Y' | b'y' => b'R', b'K' | b'k' => b'M', b'V' | b'v' => b'B', b'H' | b'h' => b'D', b'D' | b'd' => b'H', b'B' | b'b' => b'V', b'N' | b'n' => b'N', i => i, } } /// Retreives the complement for `i`. fn cpl8(&self, i: u8) -> u8 { self.table8[i as uint] } /// Retreives the complement for `i`. fn cpl16(&self, i: u16) -> u16 { self.table16[i as uint] } } /// Reads all remaining bytes from the stream. fn read_to_end<R: Reader>(r: &mut R) -> IoResult<Vec<u8>> { // As reading the input stream in memory is a bottleneck, we tune // Reader::read_to_end() with a fast growing policy to limit // recopies. If MREMAP_RETAIN is implemented in the linux kernel // and jemalloc use it, this trick will become useless. const CHUNK: uint = 64 * 1024; let mut vec = Vec::with_capacity(CHUNK); loop { // workaround: very fast growing let len = vec.len(); if vec.capacity() - len < CHUNK { let cap = vec.capacity(); let mult = if cap < 256 * 1024 * 1024 { 16 } else { 2 }; vec.reserve_exact(mult * cap - len); } match r.push_at_least(1, CHUNK, &mut vec) { Ok(_) => {} Err(ref e) if e.kind == EndOfFile => break, Err(e) => return Err(e) } } Ok(vec) } /// Finds the first position at which `b` occurs in `s`. fn memchr(h: &[u8], n: u8) -> Option<uint> { use libc::{c_void, c_int, size_t}; let res = unsafe { libc::memchr(h.as_ptr() as *const c_void, n as c_int, h.len() as size_t) }; if res.is_null() { None } else { Some(res as uint - h.as_ptr() as uint) } } /// A mutable iterator over DNA sequences struct MutDnaSeqs<'a> { s: &'a mut [u8] } fn mut_dna_seqs<'a>(s: &'a mut [u8]) -> MutDnaSeqs<'a> { MutDnaSeqs { s: s } } impl<'a> Iterator for MutDnaSeqs<'a> { type Item = &'a mut [u8]; fn next(&mut self) -> Option<&'a mut [u8]> { let tmp = std::mem::replace(&mut self.s, &mut []); let tmp = match memchr(tmp, b'\n') { Some(i) => tmp.slice_from_mut(i + 1), None => return None, }; let (seq, tmp) = match memchr(tmp, b'>') { Some(i) => tmp.split_at_mut(i), None => { let len = tmp.len(); tmp.split_at_mut(len) } }; self.s = tmp; Some(seq) } } /// Length of a normal line without the terminating \n. const LINE_LEN: uint = 60; /// Compute the reverse complement. fn reverse_complement(seq: &mut [u8], tables: &Tables) { let seq = seq.init_mut();// Drop the last newline let len = seq.len(); let off = LINE_LEN - len % (LINE_LEN + 1); let mut i = LINE_LEN; while i < len { unsafe { copy_memory(seq.as_mut_ptr().offset((i - off + 1) as int), seq.as_ptr().offset((i - off) as int), off); *seq.get_unchecked_mut(i - off) = b'\n'; } i += LINE_LEN + 1; } let div = len / 4; let rem = len % 4; unsafe { let mut left = seq.as_mut_ptr() as *mut u16; // This is slow if len % 2!= 0 but still faster than bytewise operations. let mut right = seq.as_mut_ptr().offset(len as int - 2) as *mut u16; let end = left.offset(div as int); while left!= end { let tmp = tables.cpl16(*left); *left = tables.cpl16(*right); *right = tmp; left = left.offset(1); right = right.offset(-1); } let end = end as *mut u8; match rem { 1 => *end = tables.cpl8(*end), 2 => { let tmp = tables.cpl8(*end); *end = tables.cpl8(*end.offset(1)); *end.offset(1) = tmp; }, 3 => { *end.offset(1) = tables.cpl8(*end.offset(1)); let tmp = tables.cpl8(*end); *end = tables.cpl8(*end.offset(2)); *end.offset(2) = tmp; }, _ => { }, } } } struct Racy<T>(T); unsafe impl<T:'static> Send for Racy<T> {} /// Executes a closure in parallel over the given iterator over mutable slice. /// The closure `f` is run in parallel with an element of `iter`. fn parallel<'a, I, T, F>(mut iter: I, f: F) where T: 'a+Send + Sync, I: Iterator<Item=&'a mut [T]>, F: Fn(&mut [T]) + Sync
fn main() { let mut data = read_to_end(&mut stdin_raw()).unwrap(); let tables = &Tables::new(); parallel(mut_dna_seqs(data.as_mut_slice()), |&: seq| reverse_complement(seq, tables)); stdout_raw().write(data.as_mut_slice()).unwrap(); }
{ use std::mem; use std::raw::Repr; iter.map(|chunk| { // Need to convert `f` and `chunk` to something that can cross the task // boundary. let f = Racy(&f as *const F as *const uint); let raw = Racy(chunk.repr()); Thread::scoped(move|| { let f = f.0 as *const F; unsafe { (*f)(mem::transmute(raw.0)) } }) }).collect::<Vec<_>>(); }
identifier_body
shootout-reverse-complement.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2013-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // - Neither the name of "The Computer Language Benchmarks Game" nor // the name of "The Computer Language Shootout Benchmarks" nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. // ignore-android see #10393 #13206 #![feature(unboxed_closures)] extern crate libc; use std::io::stdio::{stdin_raw, stdout_raw}; use std::io::{IoResult, EndOfFile}; use std::ptr::{copy_memory, Unique}; use std::thread::Thread; struct Tables { table8: [u8;1 << 8], table16: [u16;1 << 16] } impl Tables { fn new() -> Tables { let mut table8 = [0;1 << 8]; for (i, v) in table8.iter_mut().enumerate() { *v = Tables::computed_cpl8(i as u8); } let mut table16 = [0;1 << 16]; for (i, v) in table16.iter_mut().enumerate() { *v = (table8[i & 255] as u16) << 8 | table8[i >> 8] as u16; } Tables { table8: table8, table16: table16 } } fn computed_cpl8(c: u8) -> u8 { match c { b'A' | b'a' => b'T', b'C' | b'c' => b'G', b'G' | b'g' => b'C', b'T' | b't' => b'A', b'U' | b'u' => b'A', b'M' | b'm' => b'K', b'R' | b'r' => b'Y', b'W' | b'w' => b'W', b'S' | b's' => b'S', b'Y' | b'y' => b'R', b'K' | b'k' => b'M', b'V' | b'v' => b'B', b'H' | b'h' => b'D', b'D' | b'd' => b'H', b'B' | b'b' => b'V', b'N' | b'n' => b'N', i => i, } } /// Retreives the complement for `i`. fn cpl8(&self, i: u8) -> u8 { self.table8[i as uint] } /// Retreives the complement for `i`. fn cpl16(&self, i: u16) -> u16 { self.table16[i as uint] } } /// Reads all remaining bytes from the stream. fn read_to_end<R: Reader>(r: &mut R) -> IoResult<Vec<u8>> { // As reading the input stream in memory is a bottleneck, we tune // Reader::read_to_end() with a fast growing policy to limit // recopies. If MREMAP_RETAIN is implemented in the linux kernel // and jemalloc use it, this trick will become useless. const CHUNK: uint = 64 * 1024; let mut vec = Vec::with_capacity(CHUNK); loop { // workaround: very fast growing let len = vec.len(); if vec.capacity() - len < CHUNK { let cap = vec.capacity(); let mult = if cap < 256 * 1024 * 1024 { 16 } else { 2 }; vec.reserve_exact(mult * cap - len); } match r.push_at_least(1, CHUNK, &mut vec) { Ok(_) => {} Err(ref e) if e.kind == EndOfFile => break, Err(e) => return Err(e) } } Ok(vec) } /// Finds the first position at which `b` occurs in `s`. fn memchr(h: &[u8], n: u8) -> Option<uint> { use libc::{c_void, c_int, size_t}; let res = unsafe { libc::memchr(h.as_ptr() as *const c_void, n as c_int, h.len() as size_t) }; if res.is_null() { None } else { Some(res as uint - h.as_ptr() as uint) } } /// A mutable iterator over DNA sequences struct MutDnaSeqs<'a> { s: &'a mut [u8] } fn mut_dna_seqs<'a>(s: &'a mut [u8]) -> MutDnaSeqs<'a> { MutDnaSeqs { s: s } } impl<'a> Iterator for MutDnaSeqs<'a> { type Item = &'a mut [u8]; fn next(&mut self) -> Option<&'a mut [u8]> { let tmp = std::mem::replace(&mut self.s, &mut []); let tmp = match memchr(tmp, b'\n') { Some(i) => tmp.slice_from_mut(i + 1), None => return None, }; let (seq, tmp) = match memchr(tmp, b'>') { Some(i) => tmp.split_at_mut(i), None => { let len = tmp.len(); tmp.split_at_mut(len) } }; self.s = tmp; Some(seq) } } /// Length of a normal line without the terminating \n. const LINE_LEN: uint = 60; /// Compute the reverse complement. fn
(seq: &mut [u8], tables: &Tables) { let seq = seq.init_mut();// Drop the last newline let len = seq.len(); let off = LINE_LEN - len % (LINE_LEN + 1); let mut i = LINE_LEN; while i < len { unsafe { copy_memory(seq.as_mut_ptr().offset((i - off + 1) as int), seq.as_ptr().offset((i - off) as int), off); *seq.get_unchecked_mut(i - off) = b'\n'; } i += LINE_LEN + 1; } let div = len / 4; let rem = len % 4; unsafe { let mut left = seq.as_mut_ptr() as *mut u16; // This is slow if len % 2!= 0 but still faster than bytewise operations. let mut right = seq.as_mut_ptr().offset(len as int - 2) as *mut u16; let end = left.offset(div as int); while left!= end { let tmp = tables.cpl16(*left); *left = tables.cpl16(*right); *right = tmp; left = left.offset(1); right = right.offset(-1); } let end = end as *mut u8; match rem { 1 => *end = tables.cpl8(*end), 2 => { let tmp = tables.cpl8(*end); *end = tables.cpl8(*end.offset(1)); *end.offset(1) = tmp; }, 3 => { *end.offset(1) = tables.cpl8(*end.offset(1)); let tmp = tables.cpl8(*end); *end = tables.cpl8(*end.offset(2)); *end.offset(2) = tmp; }, _ => { }, } } } struct Racy<T>(T); unsafe impl<T:'static> Send for Racy<T> {} /// Executes a closure in parallel over the given iterator over mutable slice. /// The closure `f` is run in parallel with an element of `iter`. fn parallel<'a, I, T, F>(mut iter: I, f: F) where T: 'a+Send + Sync, I: Iterator<Item=&'a mut [T]>, F: Fn(&mut [T]) + Sync { use std::mem; use std::raw::Repr; iter.map(|chunk| { // Need to convert `f` and `chunk` to something that can cross the task // boundary. let f = Racy(&f as *const F as *const uint); let raw = Racy(chunk.repr()); Thread::scoped(move|| { let f = f.0 as *const F; unsafe { (*f)(mem::transmute(raw.0)) } }) }).collect::<Vec<_>>(); } fn main() { let mut data = read_to_end(&mut stdin_raw()).unwrap(); let tables = &Tables::new(); parallel(mut_dna_seqs(data.as_mut_slice()), |&: seq| reverse_complement(seq, tables)); stdout_raw().write(data.as_mut_slice()).unwrap(); }
reverse_complement
identifier_name
Z_Algorithm.rs
/* Problem Statement : Find all occurrences of * a pattern in a string in linear time O(m+n) * where m is the length of the pattern and n * is the length of the string.*/ use std::io::{stdin, stdout, Write}; use std::convert::TryInto; fn z_array(zstring: &Vec<char>) -> Vec<u32> { let z_length = zstring.len(); let mut z_arr = vec![0u32; z_length]; z_arr[0] = 1; let mut index = 1; let mut var_ind = 0; let mut left = 0; let mut right = 0; /* To form the z array, run two loops from the beg of the * array, match the char at that index for the outer loop * with the char at index in the inner loop. If they match, * move both of the indices forward, calculate the max length * til which they match. */ while index < z_length { if index > right { left = index; right = index; while right < z_length && zstring[right - left] == zstring[right] { right += 1; } z_arr[index] = (right - left).try_into().unwrap(); right -= 1; } else { var_ind = index - left; if z_arr[var_ind] < ((right - index + 1).try_into().unwrap()) { z_arr[index] = z_arr[var_ind]; } else { left = index; while (right < z_length && zstring[right - left] == zstring[right]) { right += 1; } z_arr[index] = (right - left).try_into().unwrap(); right -= 1; } } index += 1; } z_arr } fn search_the_pattern(strng :&str, pattern :&str) { let strng: Vec<char> = strng.chars().collect(); let pattern: Vec<char> = pattern.chars().collect(); let mut z_string = Vec::with_capacity(strng.len() + pattern.len()); let pattern_length = pattern.len(); z_string.extend(pattern); z_string.push('$'); z_string.extend(strng); let z_array = z_array(&z_string); // Go through the z array, if at any index value is equal to the // length of the pattern, the pattern appears in the string. for index in pattern_length + 1.. z_array.len() - 1 { if z_array[index] as usize == pattern_length { println!("Pattern found at index : {}", index - pattern_length - 1); } } } fn
() { println!("Enter the string :"); let mut strng = String::new(); //let _ = stdout().flush(); stdin().read_line(&mut strng).expect("Error in string input."); let strng: String = strng.trim().parse().unwrap(); let strng: &str = &*strng; let mut pattern = String::new(); // make a mutable string variable println!("Enter the pattern :"); stdin().read_line(&mut pattern).expect("Error in pattern input."); let pattern: String = pattern.trim().parse().unwrap(); let pattern: &str = &*pattern; //let tokens:Vec<&str>= strng.split(",").collect(); // Call the driver function with the string and the pattern search_the_pattern(strng, pattern); } /* Example : * Enter the string : The thesis was defended there then. Enter the pattern : the Pattern found at index : 4 Pattern found at index : 24 Pattern found at index : 30 */
main
identifier_name
Z_Algorithm.rs
/* Problem Statement : Find all occurrences of * a pattern in a string in linear time O(m+n) * where m is the length of the pattern and n * is the length of the string.*/ use std::io::{stdin, stdout, Write}; use std::convert::TryInto; fn z_array(zstring: &Vec<char>) -> Vec<u32> { let z_length = zstring.len(); let mut z_arr = vec![0u32; z_length]; z_arr[0] = 1; let mut index = 1; let mut var_ind = 0; let mut left = 0; let mut right = 0; /* To form the z array, run two loops from the beg of the * array, match the char at that index for the outer loop * with the char at index in the inner loop. If they match, * move both of the indices forward, calculate the max length * til which they match. */ while index < z_length { if index > right { left = index; right = index; while right < z_length && zstring[right - left] == zstring[right] { right += 1; } z_arr[index] = (right - left).try_into().unwrap(); right -= 1; } else { var_ind = index - left; if z_arr[var_ind] < ((right - index + 1).try_into().unwrap()) { z_arr[index] = z_arr[var_ind]; } else { left = index; while (right < z_length && zstring[right - left] == zstring[right]) { right += 1; } z_arr[index] = (right - left).try_into().unwrap(); right -= 1; } } index += 1; } z_arr } fn search_the_pattern(strng :&str, pattern :&str) { let strng: Vec<char> = strng.chars().collect(); let pattern: Vec<char> = pattern.chars().collect(); let mut z_string = Vec::with_capacity(strng.len() + pattern.len()); let pattern_length = pattern.len(); z_string.extend(pattern); z_string.push('$'); z_string.extend(strng); let z_array = z_array(&z_string); // Go through the z array, if at any index value is equal to the // length of the pattern, the pattern appears in the string. for index in pattern_length + 1.. z_array.len() - 1 { if z_array[index] as usize == pattern_length
} } fn main() { println!("Enter the string :"); let mut strng = String::new(); //let _ = stdout().flush(); stdin().read_line(&mut strng).expect("Error in string input."); let strng: String = strng.trim().parse().unwrap(); let strng: &str = &*strng; let mut pattern = String::new(); // make a mutable string variable println!("Enter the pattern :"); stdin().read_line(&mut pattern).expect("Error in pattern input."); let pattern: String = pattern.trim().parse().unwrap(); let pattern: &str = &*pattern; //let tokens:Vec<&str>= strng.split(",").collect(); // Call the driver function with the string and the pattern search_the_pattern(strng, pattern); } /* Example : * Enter the string : The thesis was defended there then. Enter the pattern : the Pattern found at index : 4 Pattern found at index : 24 Pattern found at index : 30 */
{ println!("Pattern found at index : {}", index - pattern_length - 1); }
conditional_block
Z_Algorithm.rs
/* Problem Statement : Find all occurrences of * a pattern in a string in linear time O(m+n) * where m is the length of the pattern and n * is the length of the string.*/ use std::io::{stdin, stdout, Write}; use std::convert::TryInto; fn z_array(zstring: &Vec<char>) -> Vec<u32> { let z_length = zstring.len(); let mut z_arr = vec![0u32; z_length]; z_arr[0] = 1; let mut index = 1; let mut var_ind = 0; let mut left = 0; let mut right = 0; /* To form the z array, run two loops from the beg of the * array, match the char at that index for the outer loop * with the char at index in the inner loop. If they match, * move both of the indices forward, calculate the max length * til which they match. */ while index < z_length { if index > right { left = index; right = index; while right < z_length && zstring[right - left] == zstring[right] { right += 1; } z_arr[index] = (right - left).try_into().unwrap(); right -= 1; } else { var_ind = index - left; if z_arr[var_ind] < ((right - index + 1).try_into().unwrap()) { z_arr[index] = z_arr[var_ind]; } else { left = index; while (right < z_length && zstring[right - left] == zstring[right]) { right += 1; } z_arr[index] = (right - left).try_into().unwrap(); right -= 1; } } index += 1; } z_arr } fn search_the_pattern(strng :&str, pattern :&str)
fn main() { println!("Enter the string :"); let mut strng = String::new(); //let _ = stdout().flush(); stdin().read_line(&mut strng).expect("Error in string input."); let strng: String = strng.trim().parse().unwrap(); let strng: &str = &*strng; let mut pattern = String::new(); // make a mutable string variable println!("Enter the pattern :"); stdin().read_line(&mut pattern).expect("Error in pattern input."); let pattern: String = pattern.trim().parse().unwrap(); let pattern: &str = &*pattern; //let tokens:Vec<&str>= strng.split(",").collect(); // Call the driver function with the string and the pattern search_the_pattern(strng, pattern); } /* Example : * Enter the string : The thesis was defended there then. Enter the pattern : the Pattern found at index : 4 Pattern found at index : 24 Pattern found at index : 30 */
{ let strng: Vec<char> = strng.chars().collect(); let pattern: Vec<char> = pattern.chars().collect(); let mut z_string = Vec::with_capacity(strng.len() + pattern.len()); let pattern_length = pattern.len(); z_string.extend(pattern); z_string.push('$'); z_string.extend(strng); let z_array = z_array(&z_string); // Go through the z array, if at any index value is equal to the // length of the pattern, the pattern appears in the string. for index in pattern_length + 1.. z_array.len() - 1 { if z_array[index] as usize == pattern_length { println!("Pattern found at index : {}", index - pattern_length - 1); } } }
identifier_body
Z_Algorithm.rs
/* Problem Statement : Find all occurrences of * a pattern in a string in linear time O(m+n) * where m is the length of the pattern and n * is the length of the string.*/ use std::io::{stdin, stdout, Write}; use std::convert::TryInto; fn z_array(zstring: &Vec<char>) -> Vec<u32> { let z_length = zstring.len(); let mut z_arr = vec![0u32; z_length]; z_arr[0] = 1; let mut index = 1; let mut var_ind = 0; let mut left = 0; let mut right = 0; /* To form the z array, run two loops from the beg of the * array, match the char at that index for the outer loop * with the char at index in the inner loop. If they match, * move both of the indices forward, calculate the max length * til which they match. */ while index < z_length { if index > right { left = index; right = index; while right < z_length && zstring[right - left] == zstring[right] { right += 1; } z_arr[index] = (right - left).try_into().unwrap(); right -= 1; } else { var_ind = index - left; if z_arr[var_ind] < ((right - index + 1).try_into().unwrap()) { z_arr[index] = z_arr[var_ind]; } else { left = index; while (right < z_length && zstring[right - left] == zstring[right]) { right += 1; } z_arr[index] = (right - left).try_into().unwrap(); right -= 1; } } index += 1; } z_arr } fn search_the_pattern(strng :&str, pattern :&str) { let strng: Vec<char> = strng.chars().collect(); let pattern: Vec<char> = pattern.chars().collect(); let mut z_string = Vec::with_capacity(strng.len() + pattern.len()); let pattern_length = pattern.len(); z_string.extend(pattern); z_string.push('$'); z_string.extend(strng); let z_array = z_array(&z_string); // Go through the z array, if at any index value is equal to the // length of the pattern, the pattern appears in the string. for index in pattern_length + 1.. z_array.len() - 1 { if z_array[index] as usize == pattern_length { println!("Pattern found at index : {}", index - pattern_length - 1); } } } fn main() { println!("Enter the string :"); let mut strng = String::new(); //let _ = stdout().flush(); stdin().read_line(&mut strng).expect("Error in string input.");
let mut pattern = String::new(); // make a mutable string variable println!("Enter the pattern :"); stdin().read_line(&mut pattern).expect("Error in pattern input."); let pattern: String = pattern.trim().parse().unwrap(); let pattern: &str = &*pattern; //let tokens:Vec<&str>= strng.split(",").collect(); // Call the driver function with the string and the pattern search_the_pattern(strng, pattern); } /* Example : * Enter the string : The thesis was defended there then. Enter the pattern : the Pattern found at index : 4 Pattern found at index : 24 Pattern found at index : 30 */
let strng: String = strng.trim().parse().unwrap(); let strng: &str = &*strng;
random_line_split
resource.rs
use std::path::Path; use glium::{self, Display}; use glium::texture::CompressedTexture2d; use image::{self, GenericImage}; use oil_shared::resource::new_resource_id; // Reexport pub use oil_shared::resource::ResourceId; pub use oil_shared::resource::BasicResourceManager; // ======================================== // // INTERFACE // // ======================================== // pub trait ResourceManager: BasicResourceManager { fn get_texture(&self, id: ResourceId) -> &CompressedTexture2d; } pub fn create_resource_manager<'a>(display: &'a Display) -> ResourceManagerImpl { ResourceManagerImpl::new(display) } /// Create a ResourceManager that does nothing. /// Usefull when you know that you won't have any resources /// or that your program will stop after parsing. pub fn create_null_manager() -> NullResourceManager { NullResourceManager } // ======================================== // // INTERNALS // // ======================================== // struct TextureResource { handle: glium::texture::CompressedTexture2d, img_width: u32, img_height: u32, } pub struct ResourceManagerImpl<'a> { textures: Vec<TextureResource>, display: &'a Display } impl<'a> ResourceManagerImpl<'a> { fn new(display: &'a Display) -> ResourceManagerImpl<'a> { ResourceManagerImpl { textures: Vec::new(), display: display, } } } impl<'a> BasicResourceManager for ResourceManagerImpl<'a> { fn get_texture_id(&mut self, p: &Path) -> ResourceId { let image = image::open(p).unwrap(); let (iw, ih) = image.dimensions(); let tex = glium::texture::CompressedTexture2d::new(self.display, image); let id = self.textures.len(); self.textures.push(TextureResource { handle: tex, img_width: iw, img_height: ih }); unsafe { new_resource_id(id) } } fn get_image_dimensions( &self, id: ResourceId) -> (u32, u32) { unsafe { (self.textures[id.get()].img_width, self.textures[id.get()].img_height) } } } impl<'a> ResourceManager for ResourceManagerImpl<'a> { fn get_texture(&self, id: ResourceId) -> &CompressedTexture2d
} pub struct NullResourceManager; impl BasicResourceManager for NullResourceManager { fn get_texture_id(&mut self, _: &Path) -> ResourceId { unsafe { new_resource_id(0) } } fn get_image_dimensions(&self, _: ResourceId) -> (u32, u32) { (0, 0) } } impl ResourceManager for NullResourceManager { fn get_texture(&self, _: ResourceId) -> &CompressedTexture2d { panic!("NullResourceManager purpose is for test only,\ it has a limited use."); } }
{ unsafe { &self.textures[id.get()].handle } }
identifier_body
resource.rs
use std::path::Path; use glium::{self, Display}; use glium::texture::CompressedTexture2d; use image::{self, GenericImage}; use oil_shared::resource::new_resource_id; // Reexport pub use oil_shared::resource::ResourceId; pub use oil_shared::resource::BasicResourceManager; // ======================================== // // INTERFACE // // ======================================== // pub trait ResourceManager: BasicResourceManager { fn get_texture(&self, id: ResourceId) -> &CompressedTexture2d; } pub fn create_resource_manager<'a>(display: &'a Display) -> ResourceManagerImpl { ResourceManagerImpl::new(display) } /// Create a ResourceManager that does nothing. /// Usefull when you know that you won't have any resources /// or that your program will stop after parsing. pub fn create_null_manager() -> NullResourceManager { NullResourceManager } // ======================================== // // INTERNALS // // ======================================== // struct TextureResource { handle: glium::texture::CompressedTexture2d, img_width: u32, img_height: u32, } pub struct ResourceManagerImpl<'a> { textures: Vec<TextureResource>, display: &'a Display } impl<'a> ResourceManagerImpl<'a> { fn new(display: &'a Display) -> ResourceManagerImpl<'a> { ResourceManagerImpl { textures: Vec::new(), display: display, } } } impl<'a> BasicResourceManager for ResourceManagerImpl<'a> { fn get_texture_id(&mut self, p: &Path) -> ResourceId { let image = image::open(p).unwrap(); let (iw, ih) = image.dimensions(); let tex = glium::texture::CompressedTexture2d::new(self.display, image); let id = self.textures.len(); self.textures.push(TextureResource { handle: tex, img_width: iw, img_height: ih }); unsafe { new_resource_id(id) } } fn
( &self, id: ResourceId) -> (u32, u32) { unsafe { (self.textures[id.get()].img_width, self.textures[id.get()].img_height) } } } impl<'a> ResourceManager for ResourceManagerImpl<'a> { fn get_texture(&self, id: ResourceId) -> &CompressedTexture2d { unsafe { &self.textures[id.get()].handle } } } pub struct NullResourceManager; impl BasicResourceManager for NullResourceManager { fn get_texture_id(&mut self, _: &Path) -> ResourceId { unsafe { new_resource_id(0) } } fn get_image_dimensions(&self, _: ResourceId) -> (u32, u32) { (0, 0) } } impl ResourceManager for NullResourceManager { fn get_texture(&self, _: ResourceId) -> &CompressedTexture2d { panic!("NullResourceManager purpose is for test only,\ it has a limited use."); } }
get_image_dimensions
identifier_name
resource.rs
use std::path::Path; use glium::{self, Display}; use glium::texture::CompressedTexture2d; use image::{self, GenericImage};
pub use oil_shared::resource::ResourceId; pub use oil_shared::resource::BasicResourceManager; // ======================================== // // INTERFACE // // ======================================== // pub trait ResourceManager: BasicResourceManager { fn get_texture(&self, id: ResourceId) -> &CompressedTexture2d; } pub fn create_resource_manager<'a>(display: &'a Display) -> ResourceManagerImpl { ResourceManagerImpl::new(display) } /// Create a ResourceManager that does nothing. /// Usefull when you know that you won't have any resources /// or that your program will stop after parsing. pub fn create_null_manager() -> NullResourceManager { NullResourceManager } // ======================================== // // INTERNALS // // ======================================== // struct TextureResource { handle: glium::texture::CompressedTexture2d, img_width: u32, img_height: u32, } pub struct ResourceManagerImpl<'a> { textures: Vec<TextureResource>, display: &'a Display } impl<'a> ResourceManagerImpl<'a> { fn new(display: &'a Display) -> ResourceManagerImpl<'a> { ResourceManagerImpl { textures: Vec::new(), display: display, } } } impl<'a> BasicResourceManager for ResourceManagerImpl<'a> { fn get_texture_id(&mut self, p: &Path) -> ResourceId { let image = image::open(p).unwrap(); let (iw, ih) = image.dimensions(); let tex = glium::texture::CompressedTexture2d::new(self.display, image); let id = self.textures.len(); self.textures.push(TextureResource { handle: tex, img_width: iw, img_height: ih }); unsafe { new_resource_id(id) } } fn get_image_dimensions( &self, id: ResourceId) -> (u32, u32) { unsafe { (self.textures[id.get()].img_width, self.textures[id.get()].img_height) } } } impl<'a> ResourceManager for ResourceManagerImpl<'a> { fn get_texture(&self, id: ResourceId) -> &CompressedTexture2d { unsafe { &self.textures[id.get()].handle } } } pub struct NullResourceManager; impl BasicResourceManager for NullResourceManager { fn get_texture_id(&mut self, _: &Path) -> ResourceId { unsafe { new_resource_id(0) } } fn get_image_dimensions(&self, _: ResourceId) -> (u32, u32) { (0, 0) } } impl ResourceManager for NullResourceManager { fn get_texture(&self, _: ResourceId) -> &CompressedTexture2d { panic!("NullResourceManager purpose is for test only,\ it has a limited use."); } }
use oil_shared::resource::new_resource_id; // Reexport
random_line_split
test_option.rs
fn checked_division(dividend: i32, divisor: i32) -> Option<i32> { if divisor == 0 { None } else { Some(dividend / divisor) } } fn try_division(dividend: i32, divisor: i32) { match checked_division(dividend, divisor) { None =>println!("{} / {} failed", dividend, divisor), Some(quotient) => { println!("{} / {} = {}", dividend, divisor, quotient) }, } } fn main ()
{ try_division(4,2); try_division(1,0); let none: Option<i32> = None; let _equivalent_none = None::<i32>; let optional_float = Some(0f32); println!("1- {:?} unwraps to {:?}", optional_float, optional_float.unwrap()); //println!("2- {:?} unwraps to {:?}", _equivalent_none, _equivalent_none.unwrap()); println!("3- {:?} unwraps to {:?}", none, none.unwrap()); }
identifier_body
test_option.rs
fn checked_division(dividend: i32, divisor: i32) -> Option<i32> { if divisor == 0 { None } else { Some(dividend / divisor) } } fn try_division(dividend: i32, divisor: i32) { match checked_division(dividend, divisor) {
Some(quotient) => { println!("{} / {} = {}", dividend, divisor, quotient) }, } } fn main () { try_division(4,2); try_division(1,0); let none: Option<i32> = None; let _equivalent_none = None::<i32>; let optional_float = Some(0f32); println!("1- {:?} unwraps to {:?}", optional_float, optional_float.unwrap()); //println!("2- {:?} unwraps to {:?}", _equivalent_none, _equivalent_none.unwrap()); println!("3- {:?} unwraps to {:?}", none, none.unwrap()); }
None =>println!("{} / {} failed", dividend, divisor),
random_line_split
test_option.rs
fn checked_division(dividend: i32, divisor: i32) -> Option<i32> { if divisor == 0 { None } else
} fn try_division(dividend: i32, divisor: i32) { match checked_division(dividend, divisor) { None =>println!("{} / {} failed", dividend, divisor), Some(quotient) => { println!("{} / {} = {}", dividend, divisor, quotient) }, } } fn main () { try_division(4,2); try_division(1,0); let none: Option<i32> = None; let _equivalent_none = None::<i32>; let optional_float = Some(0f32); println!("1- {:?} unwraps to {:?}", optional_float, optional_float.unwrap()); //println!("2- {:?} unwraps to {:?}", _equivalent_none, _equivalent_none.unwrap()); println!("3- {:?} unwraps to {:?}", none, none.unwrap()); }
{ Some(dividend / divisor) }
conditional_block
test_option.rs
fn checked_division(dividend: i32, divisor: i32) -> Option<i32> { if divisor == 0 { None } else { Some(dividend / divisor) } } fn try_division(dividend: i32, divisor: i32) { match checked_division(dividend, divisor) { None =>println!("{} / {} failed", dividend, divisor), Some(quotient) => { println!("{} / {} = {}", dividend, divisor, quotient) }, } } fn
() { try_division(4,2); try_division(1,0); let none: Option<i32> = None; let _equivalent_none = None::<i32>; let optional_float = Some(0f32); println!("1- {:?} unwraps to {:?}", optional_float, optional_float.unwrap()); //println!("2- {:?} unwraps to {:?}", _equivalent_none, _equivalent_none.unwrap()); println!("3- {:?} unwraps to {:?}", none, none.unwrap()); }
main
identifier_name
build.rs
extern crate gcc; use std::env; use std::io::{self, Write}; use std::fmt; fn main()
}, _ => () } }
{ match (env::var("JDK_HOME"), env::var("OPENCV_PATH")) { (Ok(jdk_path), Ok(opencv_path)) => { //compile JNI code gcc::Config::new() //.compiler("g++") .file("c/rs_jni_pipe.c") .flag("-fpermissive") .include(format!("{jdk}/include", jdk=jdk_path)) .include(format!("{jdk}/include/win32", jdk=jdk_path)) .compile("librs_jni_pipe.a"); //compile opencv code gcc::Config::new() .file("c/opencv_cam.c") .flag("-fpermissive") .include(format!("{opencv}/include", opencv=opencv_path)) .compile("libopencv_cam.a"); println!("cargo:rustc-flags=-l jvm -L {jdk}/jre/bin/server -L {jdk}/jre/bin -L {jdk}/bin -L {jdk}/lib", jdk=jdk_path);
identifier_body
build.rs
extern crate gcc; use std::env; use std::io::{self, Write}; use std::fmt; fn
() { match (env::var("JDK_HOME"), env::var("OPENCV_PATH")) { (Ok(jdk_path), Ok(opencv_path)) => { //compile JNI code gcc::Config::new() //.compiler("g++") .file("c/rs_jni_pipe.c") .flag("-fpermissive") .include(format!("{jdk}/include", jdk=jdk_path)) .include(format!("{jdk}/include/win32", jdk=jdk_path)) .compile("librs_jni_pipe.a"); //compile opencv code gcc::Config::new() .file("c/opencv_cam.c") .flag("-fpermissive") .include(format!("{opencv}/include", opencv=opencv_path)) .compile("libopencv_cam.a"); println!("cargo:rustc-flags=-l jvm -L {jdk}/jre/bin/server -L {jdk}/jre/bin -L {jdk}/bin -L {jdk}/lib", jdk=jdk_path); }, _ => () } }
main
identifier_name
build.rs
extern crate gcc; use std::env; use std::io::{self, Write}; use std::fmt; fn main() { match (env::var("JDK_HOME"), env::var("OPENCV_PATH")) { (Ok(jdk_path), Ok(opencv_path)) => { //compile JNI code gcc::Config::new() //.compiler("g++") .file("c/rs_jni_pipe.c") .flag("-fpermissive") .include(format!("{jdk}/include", jdk=jdk_path)) .include(format!("{jdk}/include/win32", jdk=jdk_path)) .compile("librs_jni_pipe.a"); //compile opencv code gcc::Config::new() .file("c/opencv_cam.c") .flag("-fpermissive") .include(format!("{opencv}/include", opencv=opencv_path)) .compile("libopencv_cam.a"); println!("cargo:rustc-flags=-l jvm -L {jdk}/jre/bin/server -L {jdk}/jre/bin -L {jdk}/bin -L {jdk}/lib", jdk=jdk_path); }, _ => ()
} }
random_line_split
notifications.rs
use std::path::Path; use std::fmt::{self, Display}; use url::Url; use notify::NotificationLevel; #[derive(Debug)] pub enum Notification<'a> { CreatingDirectory(&'a str, &'a Path), LinkingDirectory(&'a Path, &'a Path), CopyingDirectory(&'a Path, &'a Path), RemovingDirectory(&'a str, &'a Path), DownloadingFile(&'a Url, &'a Path), /// Received the Content-Length of the to-be downloaded data. DownloadContentLengthReceived(u64), /// Received some data. DownloadDataReceived(&'a [u8]), /// Download has finished. DownloadFinished,
UsingHyper, UsingRustls, } impl<'a> Notification<'a> { pub fn level(&self) -> NotificationLevel { use self::Notification::*; match *self { CreatingDirectory(_, _) | RemovingDirectory(_, _) => NotificationLevel::Verbose, LinkingDirectory(_, _) | CopyingDirectory(_, _) | DownloadingFile(_, _) | DownloadContentLengthReceived(_) | DownloadDataReceived(_) | DownloadFinished | ResumingPartialDownload | UsingCurl | UsingHyper | UsingRustls => NotificationLevel::Verbose, NoCanonicalPath(_) => NotificationLevel::Warn, } } } impl<'a> Display for Notification<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> ::std::result::Result<(), fmt::Error> { use self::Notification::*; match *self { CreatingDirectory(name, path) => { write!(f, "creating {} directory: '{}'", name, path.display()) } LinkingDirectory(_, dest) => write!(f, "linking directory from: '{}'", dest.display()), CopyingDirectory(src, _) => write!(f, "coping directory from: '{}'", src.display()), RemovingDirectory(name, path) => { write!(f, "removing {} directory: '{}'", name, path.display()) } DownloadingFile(url, _) => write!(f, "downloading file from: '{}'", url), DownloadContentLengthReceived(len) => write!(f, "download size is: '{}'", len), DownloadDataReceived(data) => write!(f, "received some data of size {}", data.len()), DownloadFinished => write!(f, "download finished"), NoCanonicalPath(path) => write!(f, "could not canonicalize path: '{}'", path.display()), ResumingPartialDownload => write!(f, "resuming partial download"), UsingCurl => write!(f, "downloading with curl"), UsingHyper => write!(f, "downloading with hyper + native_tls"), UsingRustls => write!(f, "downloading with hyper + rustls"), } } }
NoCanonicalPath(&'a Path), ResumingPartialDownload, UsingCurl,
random_line_split
notifications.rs
use std::path::Path; use std::fmt::{self, Display}; use url::Url; use notify::NotificationLevel; #[derive(Debug)] pub enum Notification<'a> { CreatingDirectory(&'a str, &'a Path), LinkingDirectory(&'a Path, &'a Path), CopyingDirectory(&'a Path, &'a Path), RemovingDirectory(&'a str, &'a Path), DownloadingFile(&'a Url, &'a Path), /// Received the Content-Length of the to-be downloaded data. DownloadContentLengthReceived(u64), /// Received some data. DownloadDataReceived(&'a [u8]), /// Download has finished. DownloadFinished, NoCanonicalPath(&'a Path), ResumingPartialDownload, UsingCurl, UsingHyper, UsingRustls, } impl<'a> Notification<'a> { pub fn level(&self) -> NotificationLevel { use self::Notification::*; match *self { CreatingDirectory(_, _) | RemovingDirectory(_, _) => NotificationLevel::Verbose, LinkingDirectory(_, _) | CopyingDirectory(_, _) | DownloadingFile(_, _) | DownloadContentLengthReceived(_) | DownloadDataReceived(_) | DownloadFinished | ResumingPartialDownload | UsingCurl | UsingHyper | UsingRustls => NotificationLevel::Verbose, NoCanonicalPath(_) => NotificationLevel::Warn, } } } impl<'a> Display for Notification<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> ::std::result::Result<(), fmt::Error>
} } }
{ use self::Notification::*; match *self { CreatingDirectory(name, path) => { write!(f, "creating {} directory: '{}'", name, path.display()) } LinkingDirectory(_, dest) => write!(f, "linking directory from: '{}'", dest.display()), CopyingDirectory(src, _) => write!(f, "coping directory from: '{}'", src.display()), RemovingDirectory(name, path) => { write!(f, "removing {} directory: '{}'", name, path.display()) } DownloadingFile(url, _) => write!(f, "downloading file from: '{}'", url), DownloadContentLengthReceived(len) => write!(f, "download size is: '{}'", len), DownloadDataReceived(data) => write!(f, "received some data of size {}", data.len()), DownloadFinished => write!(f, "download finished"), NoCanonicalPath(path) => write!(f, "could not canonicalize path: '{}'", path.display()), ResumingPartialDownload => write!(f, "resuming partial download"), UsingCurl => write!(f, "downloading with curl"), UsingHyper => write!(f, "downloading with hyper + native_tls"), UsingRustls => write!(f, "downloading with hyper + rustls"),
identifier_body
notifications.rs
use std::path::Path; use std::fmt::{self, Display}; use url::Url; use notify::NotificationLevel; #[derive(Debug)] pub enum
<'a> { CreatingDirectory(&'a str, &'a Path), LinkingDirectory(&'a Path, &'a Path), CopyingDirectory(&'a Path, &'a Path), RemovingDirectory(&'a str, &'a Path), DownloadingFile(&'a Url, &'a Path), /// Received the Content-Length of the to-be downloaded data. DownloadContentLengthReceived(u64), /// Received some data. DownloadDataReceived(&'a [u8]), /// Download has finished. DownloadFinished, NoCanonicalPath(&'a Path), ResumingPartialDownload, UsingCurl, UsingHyper, UsingRustls, } impl<'a> Notification<'a> { pub fn level(&self) -> NotificationLevel { use self::Notification::*; match *self { CreatingDirectory(_, _) | RemovingDirectory(_, _) => NotificationLevel::Verbose, LinkingDirectory(_, _) | CopyingDirectory(_, _) | DownloadingFile(_, _) | DownloadContentLengthReceived(_) | DownloadDataReceived(_) | DownloadFinished | ResumingPartialDownload | UsingCurl | UsingHyper | UsingRustls => NotificationLevel::Verbose, NoCanonicalPath(_) => NotificationLevel::Warn, } } } impl<'a> Display for Notification<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> ::std::result::Result<(), fmt::Error> { use self::Notification::*; match *self { CreatingDirectory(name, path) => { write!(f, "creating {} directory: '{}'", name, path.display()) } LinkingDirectory(_, dest) => write!(f, "linking directory from: '{}'", dest.display()), CopyingDirectory(src, _) => write!(f, "coping directory from: '{}'", src.display()), RemovingDirectory(name, path) => { write!(f, "removing {} directory: '{}'", name, path.display()) } DownloadingFile(url, _) => write!(f, "downloading file from: '{}'", url), DownloadContentLengthReceived(len) => write!(f, "download size is: '{}'", len), DownloadDataReceived(data) => write!(f, "received some data of size {}", data.len()), DownloadFinished => write!(f, "download finished"), NoCanonicalPath(path) => write!(f, "could not canonicalize path: '{}'", path.display()), ResumingPartialDownload => write!(f, "resuming partial download"), UsingCurl => write!(f, "downloading with curl"), UsingHyper => write!(f, "downloading with hyper + native_tls"), UsingRustls => write!(f, "downloading with hyper + rustls"), } } }
Notification
identifier_name
string.rs
use crate::ffi_fn; use libc::c_char; use std::ffi::{CStr, CString}; use std::ops::Not; // All of this module is `pub(crate)` and should not appear in the C header file // or documentation. /// Converts the string into a C-compatible null terminated string, /// then forgets the container while returning a pointer to the /// underlying buffer. /// /// The returned pointer must be passed to CString::from_raw to /// prevent leaking memory. pub(crate) fn to_c(t: &str) -> anyhow::Result<*mut c_char>
ffi_fn! { /// Delete a string previously returned by this FFI. /// /// It is explicitly allowed to pass a null pointer to this function; /// in that case the function will do nothing. fn pactffi_string_delete(string: *mut c_char) { if string.is_null().not() { let string = unsafe { CString::from_raw(string) }; std::mem::drop(string); } } } /// Construct a CStr safely with null checks. #[macro_export] macro_rules! cstr { ( $name:ident ) => {{ use ::std::ffi::CStr; if $name.is_null() { ::anyhow::bail!(concat!(stringify!($name), " is null")); } unsafe { CStr::from_ptr($name) } }}; } /// Construct a `&str` safely with null checks. #[macro_export] macro_rules! safe_str { ( $name:ident ) => {{ $crate::cstr!($name).to_str().context(concat!( "error parsing ", stringify!($name), " as UTF-8" ))? }}; } /// Returns the Rust string from the C string pointer, returning the default value if the pointer /// is NULL pub(crate) fn if_null(s: *const c_char, default: &str) -> String { if s.is_null() { default.to_string() } else { unsafe { CStr::from_ptr(s).to_string_lossy().to_string() } } }
{ Ok(CString::new(t)?.into_raw()) }
identifier_body
string.rs
use crate::ffi_fn; use libc::c_char; use std::ffi::{CStr, CString}; use std::ops::Not; // All of this module is `pub(crate)` and should not appear in the C header file // or documentation. /// Converts the string into a C-compatible null terminated string, /// then forgets the container while returning a pointer to the /// underlying buffer. /// /// The returned pointer must be passed to CString::from_raw to /// prevent leaking memory. pub(crate) fn to_c(t: &str) -> anyhow::Result<*mut c_char> { Ok(CString::new(t)?.into_raw()) } ffi_fn! { /// Delete a string previously returned by this FFI. /// /// It is explicitly allowed to pass a null pointer to this function; /// in that case the function will do nothing. fn pactffi_string_delete(string: *mut c_char) { if string.is_null().not() { let string = unsafe { CString::from_raw(string) }; std::mem::drop(string); } } } /// Construct a CStr safely with null checks. #[macro_export] macro_rules! cstr { ( $name:ident ) => {{ use ::std::ffi::CStr; if $name.is_null() { ::anyhow::bail!(concat!(stringify!($name), " is null")); } unsafe { CStr::from_ptr($name) } }}; } /// Construct a `&str` safely with null checks. #[macro_export] macro_rules! safe_str { ( $name:ident ) => {{ $crate::cstr!($name).to_str().context(concat!( "error parsing ", stringify!($name), " as UTF-8" ))? }}; } /// Returns the Rust string from the C string pointer, returning the default value if the pointer /// is NULL pub(crate) fn if_null(s: *const c_char, default: &str) -> String { if s.is_null() { default.to_string() } else
}
{ unsafe { CStr::from_ptr(s).to_string_lossy().to_string() } }
conditional_block
string.rs
use crate::ffi_fn; use libc::c_char; use std::ffi::{CStr, CString}; use std::ops::Not; // All of this module is `pub(crate)` and should not appear in the C header file // or documentation. /// Converts the string into a C-compatible null terminated string, /// then forgets the container while returning a pointer to the /// underlying buffer. /// /// The returned pointer must be passed to CString::from_raw to /// prevent leaking memory. pub(crate) fn to_c(t: &str) -> anyhow::Result<*mut c_char> { Ok(CString::new(t)?.into_raw()) } ffi_fn! { /// Delete a string previously returned by this FFI. /// /// It is explicitly allowed to pass a null pointer to this function; /// in that case the function will do nothing. fn pactffi_string_delete(string: *mut c_char) { if string.is_null().not() { let string = unsafe { CString::from_raw(string) }; std::mem::drop(string); } } } /// Construct a CStr safely with null checks. #[macro_export] macro_rules! cstr { ( $name:ident ) => {{ use ::std::ffi::CStr; if $name.is_null() { ::anyhow::bail!(concat!(stringify!($name), " is null")); } unsafe { CStr::from_ptr($name) } }}; } /// Construct a `&str` safely with null checks. #[macro_export]
$crate::cstr!($name).to_str().context(concat!( "error parsing ", stringify!($name), " as UTF-8" ))? }}; } /// Returns the Rust string from the C string pointer, returning the default value if the pointer /// is NULL pub(crate) fn if_null(s: *const c_char, default: &str) -> String { if s.is_null() { default.to_string() } else { unsafe { CStr::from_ptr(s).to_string_lossy().to_string() } } }
macro_rules! safe_str { ( $name:ident ) => {{
random_line_split
string.rs
use crate::ffi_fn; use libc::c_char; use std::ffi::{CStr, CString}; use std::ops::Not; // All of this module is `pub(crate)` and should not appear in the C header file // or documentation. /// Converts the string into a C-compatible null terminated string, /// then forgets the container while returning a pointer to the /// underlying buffer. /// /// The returned pointer must be passed to CString::from_raw to /// prevent leaking memory. pub(crate) fn to_c(t: &str) -> anyhow::Result<*mut c_char> { Ok(CString::new(t)?.into_raw()) } ffi_fn! { /// Delete a string previously returned by this FFI. /// /// It is explicitly allowed to pass a null pointer to this function; /// in that case the function will do nothing. fn pactffi_string_delete(string: *mut c_char) { if string.is_null().not() { let string = unsafe { CString::from_raw(string) }; std::mem::drop(string); } } } /// Construct a CStr safely with null checks. #[macro_export] macro_rules! cstr { ( $name:ident ) => {{ use ::std::ffi::CStr; if $name.is_null() { ::anyhow::bail!(concat!(stringify!($name), " is null")); } unsafe { CStr::from_ptr($name) } }}; } /// Construct a `&str` safely with null checks. #[macro_export] macro_rules! safe_str { ( $name:ident ) => {{ $crate::cstr!($name).to_str().context(concat!( "error parsing ", stringify!($name), " as UTF-8" ))? }}; } /// Returns the Rust string from the C string pointer, returning the default value if the pointer /// is NULL pub(crate) fn
(s: *const c_char, default: &str) -> String { if s.is_null() { default.to_string() } else { unsafe { CStr::from_ptr(s).to_string_lossy().to_string() } } }
if_null
identifier_name
track.rs
// Copyright (c) 2016, Mikkel Kroman <[email protected]> // All rights reserved. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::fmt; use std::str; use url::Url; use serde_json; use error::{Error, Result}; use client::{Client, User, App}; #[derive(Debug)] pub enum Filter { All, Public, Private } impl str::FromStr for Filter { type Err = Error; fn from_str(s: &str) -> Result<Filter> { match s { "all" => Ok(Filter::All), "public" => Ok(Filter::Public), "private" => Ok(Filter::Private), _ => Err(Error::InvalidFilter(s.to_string())), } } } impl fmt::Display for Filter { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.to_str()) } } impl Filter { pub fn to_str(&self) -> &str { match *self { Filter::All => "all", Filter::Public => "public", Filter::Private => "private", } } } /// Uploaded track. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Track { /// Integer ID. pub id: u64, /// Time of which the track was uploaded, as an unparsed string. pub created_at: String, /// User ID of the uploader. pub user_id: u64, /// Small representation of the uploaders user. pub user: User, /// Title. pub title: String, /// Permalink of the resource. pub permalink: String, /// URL to the SoundCloud.com page. pub permalink_url: String, /// API resource URL. pub uri: String, /// Sharing status. pub sharing: String, /// Who can embed this track. pub embeddable_by: String, /// External purchase link. pub purchase_url: Option<String>, /// URL to a JPEG image. pub artwork_url: Option<String>, /// HTML description. pub description: Option<String>, /// Representation of a labels user. pub label: Option<serde_json::Value>, /// Duration in milliseconds. pub duration: u64, /// Genre. pub genre: Option<String>, /// List of tags. pub tags: Option<String>, /// Label user ID. pub label_id: Option<u64>, /// Label user name. pub label_name: Option<String>, /// Release number. pub release: Option<String>, /// Day of the release. pub release_day: Option<u64>, /// Month of the release. pub release_month: Option<u64>, /// Year of the release. pub release_year: Option<u64>, /// If the track is available for stream via the API. pub streamable: bool, /// If the track is available for download. pub downloadable: bool, /// Purchase title. pub purchase_title: Option<String>, /// Encoding state. pub state: String, /// Creative common license. pub license: String, /// Track type. pub track_type: Option<String>, /// URL to waveform PNG image. pub waveform_url: String, /// URL to original file. pub download_url: Option<String>, /// URL to 128kbps mp3 stream. pub stream_url: Option<String>, /// External video link. pub video_url: Option<String>, /// Beats per minute. pub bpm: Option<u64>, /// Commentable. pub commentable: bool, /// ISRC. pub isrc: Option<String>, /// Key. pub key_signature: Option<String>, /// Number of comments. pub comment_count: u64, /// Number of downloads. pub download_count: u64, /// Number of playbacks. pub playback_count: u64, /// Number of times favorited. pub favoritings_count: u64, /// Original upload format. pub original_format: String, /// Original upload size. pub original_content_size: u64, /// Application the track was uploaded with. pub created_with: Option<App>, /// Binary data of the audio file. Only for uploading. pub asset_data: Option<Vec<u8>>, /// Binary data of the artwork image. Only for uploading. pub artwork_data: Option<Vec<u8>>, /// User favorite. pub user_favorite: Option<bool>, } #[derive(Debug)] pub struct TrackRequestBuilder<'a> { client: &'a Client, query: Option<String>, tags: Option<String>, filter: Option<Filter>, license: Option<String>, ids: Option<Vec<usize>>, duration: Option<(usize, usize)>, bpm: Option<(usize, usize)>, genres: Option<String>, types: Option<String> } #[derive(Debug)] pub struct SingleTrackRequestBuilder<'a> { client: &'a Client, pub id: usize, } impl<'a> SingleTrackRequestBuilder<'a> { /// Constructs a new track request. pub fn new(client: &'a Client, id: usize) -> SingleTrackRequestBuilder { SingleTrackRequestBuilder { client: client, id: id, } } /// Sends the request and return the tracks. pub fn get(&mut self) -> Result<Track> { let no_params: Option<&[(&str, &str)]> = None; let response = try!(self.client.get(&format!("/tracks/{}", self.id), no_params)); let track: Track = try!(serde_json::from_reader(response)); Ok(track) } pub fn request_url(&self) -> Url { let url = Url::parse(&format!("https://{}/tracks/{}", super::API_HOST, self.id)).unwrap(); url } } impl<'a> TrackRequestBuilder<'a> { /// Creates a new track request builder, with no set parameters. pub fn new(client: &'a Client) -> TrackRequestBuilder {
filter: None, license: None, ids: None, duration: None, bpm: None, genres: None, types: None, } } /// Sets the search query filter, which will only return tracks with a matching query. pub fn query<S>(&'a mut self, query: Option<S>) -> &mut TrackRequestBuilder where S: AsRef<str> { self.query = query.map(|s| s.as_ref().to_owned()); self } /// Sets the tags filter, which will only return tracks with a matching tag. pub fn tags<I, T>(&'a mut self, tags: Option<I>) -> &mut TrackRequestBuilder where I: AsRef<[T]>, T: AsRef<str> { self.tags = tags.map(|s| { let tags_as_ref: Vec<_> = s.as_ref().iter().map(T::as_ref).collect(); tags_as_ref.join(",") }); self } pub fn genres<I, T>(&'a mut self, genres: Option<I>) -> &mut TrackRequestBuilder where I: AsRef<[T]>, T: AsRef<str> { self.genres = genres.map(|s| { let genres_as_ref: Vec<_> = s.as_ref().iter().map(T::as_ref).collect(); genres_as_ref.join(",") }); self } /// Sets whether to filter private or public tracks. pub fn filter(&'a mut self, filter: Option<Filter>) -> &mut TrackRequestBuilder { self.filter = filter; self } /// Sets the license filter. pub fn license<S: AsRef<str>>(&'a mut self, license: Option<S>) -> &mut TrackRequestBuilder { self.license = license.map(|s| s.as_ref().to_owned()); self } /// Sets a list of track ids to look up. pub fn ids(&'a mut self, ids: Option<Vec<usize>>) -> &mut TrackRequestBuilder { self.ids = ids; self } /// Returns a builder for a single track. pub fn id(&'a mut self, id: usize) -> SingleTrackRequestBuilder { SingleTrackRequestBuilder { client: &self.client, id: id, } } /// Performs the request and returns a list of tracks if there are any results, None otherwise, /// or an error if one occurred. pub fn get(&mut self) -> Result<Option<Vec<Track>>> { use serde_json::Value; let response = try!(self.client.get("/tracks", Some(self.request_params()))); let track_list: Value = try!(serde_json::from_reader(response)); if let Some(track_list) = track_list.as_array() { if track_list.is_empty() { return Ok(None); } else { let tracks: Vec<Track> = track_list .iter().map(|t| serde_json::from_value::<Track>(t.clone()).unwrap()).collect(); return Ok(Some(tracks)); } } return Err(Error::ApiError("expected response to be an array".to_owned())); } fn request_params(&self) -> Vec<(&str, String)> { let mut result = vec![]; if let Some(ref query) = self.query { result.push(("q", query.clone())); } if let Some(ref tags) = self.tags { result.push(("tags", tags.clone())); } if let Some(ref filter) = self.filter { result.push(("filter", filter.to_str().to_owned())); } if let Some(ref ids) = self.ids { let ids_as_strings: Vec<String> = ids.iter().map(|id| format!("{}", id)).collect(); result.push(("ids", ids_as_strings.join(","))); } if let Some(ref _duration) = self.duration { unimplemented!(); } if let Some(ref _bpm) = self.bpm { unimplemented!(); } if let Some(ref genres) = self.genres { result.push(("genres", genres.clone())); } if let Some(ref types) = self.types { result.push(("types", types.clone())); } result } } impl PartialEq for Track { fn eq(&self, other: &Track) -> bool { other.id == self.id } }
TrackRequestBuilder { client: client, query: None, tags: None,
random_line_split
track.rs
// Copyright (c) 2016, Mikkel Kroman <[email protected]> // All rights reserved. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::fmt; use std::str; use url::Url; use serde_json; use error::{Error, Result}; use client::{Client, User, App}; #[derive(Debug)] pub enum Filter { All, Public, Private } impl str::FromStr for Filter { type Err = Error; fn from_str(s: &str) -> Result<Filter> { match s { "all" => Ok(Filter::All), "public" => Ok(Filter::Public), "private" => Ok(Filter::Private), _ => Err(Error::InvalidFilter(s.to_string())), } } } impl fmt::Display for Filter { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.to_str()) } } impl Filter { pub fn to_str(&self) -> &str { match *self { Filter::All => "all", Filter::Public => "public", Filter::Private => "private", } } } /// Uploaded track. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Track { /// Integer ID. pub id: u64, /// Time of which the track was uploaded, as an unparsed string. pub created_at: String, /// User ID of the uploader. pub user_id: u64, /// Small representation of the uploaders user. pub user: User, /// Title. pub title: String, /// Permalink of the resource. pub permalink: String, /// URL to the SoundCloud.com page. pub permalink_url: String, /// API resource URL. pub uri: String, /// Sharing status. pub sharing: String, /// Who can embed this track. pub embeddable_by: String, /// External purchase link. pub purchase_url: Option<String>, /// URL to a JPEG image. pub artwork_url: Option<String>, /// HTML description. pub description: Option<String>, /// Representation of a labels user. pub label: Option<serde_json::Value>, /// Duration in milliseconds. pub duration: u64, /// Genre. pub genre: Option<String>, /// List of tags. pub tags: Option<String>, /// Label user ID. pub label_id: Option<u64>, /// Label user name. pub label_name: Option<String>, /// Release number. pub release: Option<String>, /// Day of the release. pub release_day: Option<u64>, /// Month of the release. pub release_month: Option<u64>, /// Year of the release. pub release_year: Option<u64>, /// If the track is available for stream via the API. pub streamable: bool, /// If the track is available for download. pub downloadable: bool, /// Purchase title. pub purchase_title: Option<String>, /// Encoding state. pub state: String, /// Creative common license. pub license: String, /// Track type. pub track_type: Option<String>, /// URL to waveform PNG image. pub waveform_url: String, /// URL to original file. pub download_url: Option<String>, /// URL to 128kbps mp3 stream. pub stream_url: Option<String>, /// External video link. pub video_url: Option<String>, /// Beats per minute. pub bpm: Option<u64>, /// Commentable. pub commentable: bool, /// ISRC. pub isrc: Option<String>, /// Key. pub key_signature: Option<String>, /// Number of comments. pub comment_count: u64, /// Number of downloads. pub download_count: u64, /// Number of playbacks. pub playback_count: u64, /// Number of times favorited. pub favoritings_count: u64, /// Original upload format. pub original_format: String, /// Original upload size. pub original_content_size: u64, /// Application the track was uploaded with. pub created_with: Option<App>, /// Binary data of the audio file. Only for uploading. pub asset_data: Option<Vec<u8>>, /// Binary data of the artwork image. Only for uploading. pub artwork_data: Option<Vec<u8>>, /// User favorite. pub user_favorite: Option<bool>, } #[derive(Debug)] pub struct TrackRequestBuilder<'a> { client: &'a Client, query: Option<String>, tags: Option<String>, filter: Option<Filter>, license: Option<String>, ids: Option<Vec<usize>>, duration: Option<(usize, usize)>, bpm: Option<(usize, usize)>, genres: Option<String>, types: Option<String> } #[derive(Debug)] pub struct SingleTrackRequestBuilder<'a> { client: &'a Client, pub id: usize, } impl<'a> SingleTrackRequestBuilder<'a> { /// Constructs a new track request. pub fn new(client: &'a Client, id: usize) -> SingleTrackRequestBuilder { SingleTrackRequestBuilder { client: client, id: id, } } /// Sends the request and return the tracks. pub fn
(&mut self) -> Result<Track> { let no_params: Option<&[(&str, &str)]> = None; let response = try!(self.client.get(&format!("/tracks/{}", self.id), no_params)); let track: Track = try!(serde_json::from_reader(response)); Ok(track) } pub fn request_url(&self) -> Url { let url = Url::parse(&format!("https://{}/tracks/{}", super::API_HOST, self.id)).unwrap(); url } } impl<'a> TrackRequestBuilder<'a> { /// Creates a new track request builder, with no set parameters. pub fn new(client: &'a Client) -> TrackRequestBuilder { TrackRequestBuilder { client: client, query: None, tags: None, filter: None, license: None, ids: None, duration: None, bpm: None, genres: None, types: None, } } /// Sets the search query filter, which will only return tracks with a matching query. pub fn query<S>(&'a mut self, query: Option<S>) -> &mut TrackRequestBuilder where S: AsRef<str> { self.query = query.map(|s| s.as_ref().to_owned()); self } /// Sets the tags filter, which will only return tracks with a matching tag. pub fn tags<I, T>(&'a mut self, tags: Option<I>) -> &mut TrackRequestBuilder where I: AsRef<[T]>, T: AsRef<str> { self.tags = tags.map(|s| { let tags_as_ref: Vec<_> = s.as_ref().iter().map(T::as_ref).collect(); tags_as_ref.join(",") }); self } pub fn genres<I, T>(&'a mut self, genres: Option<I>) -> &mut TrackRequestBuilder where I: AsRef<[T]>, T: AsRef<str> { self.genres = genres.map(|s| { let genres_as_ref: Vec<_> = s.as_ref().iter().map(T::as_ref).collect(); genres_as_ref.join(",") }); self } /// Sets whether to filter private or public tracks. pub fn filter(&'a mut self, filter: Option<Filter>) -> &mut TrackRequestBuilder { self.filter = filter; self } /// Sets the license filter. pub fn license<S: AsRef<str>>(&'a mut self, license: Option<S>) -> &mut TrackRequestBuilder { self.license = license.map(|s| s.as_ref().to_owned()); self } /// Sets a list of track ids to look up. pub fn ids(&'a mut self, ids: Option<Vec<usize>>) -> &mut TrackRequestBuilder { self.ids = ids; self } /// Returns a builder for a single track. pub fn id(&'a mut self, id: usize) -> SingleTrackRequestBuilder { SingleTrackRequestBuilder { client: &self.client, id: id, } } /// Performs the request and returns a list of tracks if there are any results, None otherwise, /// or an error if one occurred. pub fn get(&mut self) -> Result<Option<Vec<Track>>> { use serde_json::Value; let response = try!(self.client.get("/tracks", Some(self.request_params()))); let track_list: Value = try!(serde_json::from_reader(response)); if let Some(track_list) = track_list.as_array() { if track_list.is_empty() { return Ok(None); } else { let tracks: Vec<Track> = track_list .iter().map(|t| serde_json::from_value::<Track>(t.clone()).unwrap()).collect(); return Ok(Some(tracks)); } } return Err(Error::ApiError("expected response to be an array".to_owned())); } fn request_params(&self) -> Vec<(&str, String)> { let mut result = vec![]; if let Some(ref query) = self.query { result.push(("q", query.clone())); } if let Some(ref tags) = self.tags { result.push(("tags", tags.clone())); } if let Some(ref filter) = self.filter { result.push(("filter", filter.to_str().to_owned())); } if let Some(ref ids) = self.ids { let ids_as_strings: Vec<String> = ids.iter().map(|id| format!("{}", id)).collect(); result.push(("ids", ids_as_strings.join(","))); } if let Some(ref _duration) = self.duration { unimplemented!(); } if let Some(ref _bpm) = self.bpm { unimplemented!(); } if let Some(ref genres) = self.genres { result.push(("genres", genres.clone())); } if let Some(ref types) = self.types { result.push(("types", types.clone())); } result } } impl PartialEq for Track { fn eq(&self, other: &Track) -> bool { other.id == self.id } }
get
identifier_name
lib.rs
/// Requests a string from the user with the specified prompt. pub fn get_string(prompt: &str) -> String { get_input(prompt, false).unwrap_or_default() } /// Requests a string from the user with the specified prompt, treating the input as a password. pub fn get_password(prompt: &str) -> String
fn get_input(prompt: &str, is_password: bool) -> Option<String> { if is_password { println!("{}:{}", GET_CMD_PASSWORD, prompt); } else { println!("{}:{}", GET_CMD, prompt); } let mut line = String::new(); std::io::stdin().read_line(&mut line).ok()?; Some(line.trim().to_owned()) } // The following constants are here so that they can be shared between this crate and Evcxr. They're // not really intended to be used. #[doc(hidden)] pub const GET_CMD: &str = "EVCXR_INPUT_REQUEST"; #[doc(hidden)] pub const GET_CMD_PASSWORD: &str = "EVCXR_INPUT_REQUEST_PASSWORD";
{ get_input(prompt, true).unwrap_or_default() }
identifier_body
lib.rs
/// Requests a string from the user with the specified prompt. pub fn get_string(prompt: &str) -> String { get_input(prompt, false).unwrap_or_default() } /// Requests a string from the user with the specified prompt, treating the input as a password. pub fn get_password(prompt: &str) -> String { get_input(prompt, true).unwrap_or_default() } fn get_input(prompt: &str, is_password: bool) -> Option<String> { if is_password
else { println!("{}:{}", GET_CMD, prompt); } let mut line = String::new(); std::io::stdin().read_line(&mut line).ok()?; Some(line.trim().to_owned()) } // The following constants are here so that they can be shared between this crate and Evcxr. They're // not really intended to be used. #[doc(hidden)] pub const GET_CMD: &str = "EVCXR_INPUT_REQUEST"; #[doc(hidden)] pub const GET_CMD_PASSWORD: &str = "EVCXR_INPUT_REQUEST_PASSWORD";
{ println!("{}:{}", GET_CMD_PASSWORD, prompt); }
conditional_block
lib.rs
/// Requests a string from the user with the specified prompt. pub fn
(prompt: &str) -> String { get_input(prompt, false).unwrap_or_default() } /// Requests a string from the user with the specified prompt, treating the input as a password. pub fn get_password(prompt: &str) -> String { get_input(prompt, true).unwrap_or_default() } fn get_input(prompt: &str, is_password: bool) -> Option<String> { if is_password { println!("{}:{}", GET_CMD_PASSWORD, prompt); } else { println!("{}:{}", GET_CMD, prompt); } let mut line = String::new(); std::io::stdin().read_line(&mut line).ok()?; Some(line.trim().to_owned()) } // The following constants are here so that they can be shared between this crate and Evcxr. They're // not really intended to be used. #[doc(hidden)] pub const GET_CMD: &str = "EVCXR_INPUT_REQUEST"; #[doc(hidden)] pub const GET_CMD_PASSWORD: &str = "EVCXR_INPUT_REQUEST_PASSWORD";
get_string
identifier_name
lib.rs
/// Requests a string from the user with the specified prompt. pub fn get_string(prompt: &str) -> String { get_input(prompt, false).unwrap_or_default() }
/// Requests a string from the user with the specified prompt, treating the input as a password. pub fn get_password(prompt: &str) -> String { get_input(prompt, true).unwrap_or_default() } fn get_input(prompt: &str, is_password: bool) -> Option<String> { if is_password { println!("{}:{}", GET_CMD_PASSWORD, prompt); } else { println!("{}:{}", GET_CMD, prompt); } let mut line = String::new(); std::io::stdin().read_line(&mut line).ok()?; Some(line.trim().to_owned()) } // The following constants are here so that they can be shared between this crate and Evcxr. They're // not really intended to be used. #[doc(hidden)] pub const GET_CMD: &str = "EVCXR_INPUT_REQUEST"; #[doc(hidden)] pub const GET_CMD_PASSWORD: &str = "EVCXR_INPUT_REQUEST_PASSWORD";
random_line_split
easage_pack.rs
use clap::{Arg, ArgMatches, App, SubCommand}; use ::std::fs::OpenOptions; use ::std::io::Write; use ::lib::{Kind, packer}; use ::{CliResult, CliError}; pub const COMMAND_NAME: &'static str = "pack"; const ARG_NAME_SOURCE: &'static str = "source"; const ARG_NAME_OUTPUT: &'static str = "output"; const ARG_NAME_KIND: &'static str = "kind"; const ARG_NAME_STRIP_PREFIX: &'static str = "strip-prefix"; const ARG_NAME_ORDER: &'static str = "order"; const ARG_VALUE_KIND_BIGF: &'static str = "BIGF"; const ARG_VALUE_KIND_BIG4: &'static str = "BIG4"; const ARG_VALUE_ORDER_SMALLEST_TO_LARGEST: &'static str = "smallest-to-largest"; const ARG_VALUE_ORDER_PATH: &'static str = "path"; pub fn
<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name(COMMAND_NAME) .about("Recursively package a directory structure into a BIG archive") .author("Taryn Hill <[email protected]>") .arg(Arg::with_name(ARG_NAME_SOURCE) .long(ARG_NAME_SOURCE) .value_name(ARG_NAME_SOURCE) .takes_value(true) .required(true) .help("path to the directory to pack into a BIG archive")) .arg(Arg::with_name(ARG_NAME_OUTPUT) .long(ARG_NAME_OUTPUT) .value_name(ARG_NAME_OUTPUT) .takes_value(true) .required(true) .help("path to the output BIG archive")) .arg(Arg::with_name(ARG_NAME_KIND) .long(ARG_NAME_KIND) .value_name(ARG_NAME_KIND) .takes_value(true) .default_value(ARG_VALUE_KIND_BIGF) .possible_values(&[ARG_VALUE_KIND_BIGF, ARG_VALUE_KIND_BIG4]) .help("use BIG4 for the Battle for Middle-Earth series or BIGF for Generals / Zero-Hour")) .arg(Arg::with_name(ARG_NAME_STRIP_PREFIX) .long(ARG_NAME_STRIP_PREFIX) .value_name(ARG_NAME_STRIP_PREFIX) .takes_value(true) .help("a prefix to strip from entry names")) .arg(Arg::with_name(ARG_NAME_ORDER) .long(ARG_NAME_ORDER) .value_name(ARG_NAME_ORDER) .takes_value(true) .default_value(ARG_VALUE_ORDER_PATH) .validator(validate_order) .possible_values(&[ARG_VALUE_ORDER_SMALLEST_TO_LARGEST, ARG_VALUE_ORDER_PATH]) .help("criteria used to determine entry order in the archive")) } pub fn run(args: &ArgMatches) -> CliResult<()> { let source = args.value_of(ARG_NAME_SOURCE).unwrap(); let output = args.value_of(ARG_NAME_OUTPUT).unwrap(); let entry_order_criteria = args.value_of(ARG_NAME_ORDER) .map(arg_order_to_enum) .unwrap(); let strip_prefix = args.value_of(ARG_NAME_STRIP_PREFIX) .map(|s| s.to_string()); let kind = args.value_of(ARG_NAME_KIND).unwrap(); let kind = Kind::try_from_bytes(kind.as_bytes()).unwrap(); let settings = packer::Settings { entry_order_criteria, strip_prefix, kind, }; let archive = packer::pack_directory(&source, settings) .map_err(|e_lib| CliError::PackArchive { inner: e_lib })?; let mut file = OpenOptions::new() .read(true) .write(true) .create(true) .truncate(true) .open(output) .map_err(|e| CliError::IO { inner: e, path: output.to_string(), })?; let data = archive.as_slice(); file.write_all(data)?; Ok(()) } fn arg_order_to_enum(input: &str) -> packer::EntryOrderCriteria { match input { ARG_VALUE_ORDER_SMALLEST_TO_LARGEST => packer::EntryOrderCriteria::SmallestToLargest, ARG_VALUE_ORDER_PATH => packer::EntryOrderCriteria::Path, _ => { eprintln!(r#" Unexpected error! Please file a bug at https://github.com/Phrohdoh/easage/issues/new and provide the following text: Invalid input to 'arg_order_to_enum': {:?} Did you validate input via 'validate_order'? "#, input); ::std::process::exit(1); }, } } fn validate_order(v: String) -> Result<(), String> { if v == ARG_VALUE_ORDER_SMALLEST_TO_LARGEST || v == ARG_VALUE_ORDER_PATH { Ok(()) } else { Err(format!("{} must be one of '{}' or '{}'", ARG_NAME_ORDER, ARG_VALUE_ORDER_SMALLEST_TO_LARGEST, ARG_VALUE_ORDER_PATH)) } }
get_command
identifier_name
easage_pack.rs
use clap::{Arg, ArgMatches, App, SubCommand}; use ::std::fs::OpenOptions; use ::std::io::Write; use ::lib::{Kind, packer}; use ::{CliResult, CliError}; pub const COMMAND_NAME: &'static str = "pack"; const ARG_NAME_SOURCE: &'static str = "source"; const ARG_NAME_OUTPUT: &'static str = "output"; const ARG_NAME_KIND: &'static str = "kind"; const ARG_NAME_STRIP_PREFIX: &'static str = "strip-prefix"; const ARG_NAME_ORDER: &'static str = "order"; const ARG_VALUE_KIND_BIGF: &'static str = "BIGF"; const ARG_VALUE_KIND_BIG4: &'static str = "BIG4"; const ARG_VALUE_ORDER_SMALLEST_TO_LARGEST: &'static str = "smallest-to-largest"; const ARG_VALUE_ORDER_PATH: &'static str = "path"; pub fn get_command<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name(COMMAND_NAME) .about("Recursively package a directory structure into a BIG archive") .author("Taryn Hill <[email protected]>") .arg(Arg::with_name(ARG_NAME_SOURCE) .long(ARG_NAME_SOURCE) .value_name(ARG_NAME_SOURCE) .takes_value(true) .required(true) .help("path to the directory to pack into a BIG archive")) .arg(Arg::with_name(ARG_NAME_OUTPUT) .long(ARG_NAME_OUTPUT) .value_name(ARG_NAME_OUTPUT) .takes_value(true) .required(true) .help("path to the output BIG archive")) .arg(Arg::with_name(ARG_NAME_KIND) .long(ARG_NAME_KIND) .value_name(ARG_NAME_KIND) .takes_value(true) .default_value(ARG_VALUE_KIND_BIGF) .possible_values(&[ARG_VALUE_KIND_BIGF, ARG_VALUE_KIND_BIG4]) .help("use BIG4 for the Battle for Middle-Earth series or BIGF for Generals / Zero-Hour")) .arg(Arg::with_name(ARG_NAME_STRIP_PREFIX) .long(ARG_NAME_STRIP_PREFIX) .value_name(ARG_NAME_STRIP_PREFIX) .takes_value(true) .help("a prefix to strip from entry names")) .arg(Arg::with_name(ARG_NAME_ORDER) .long(ARG_NAME_ORDER) .value_name(ARG_NAME_ORDER) .takes_value(true) .default_value(ARG_VALUE_ORDER_PATH) .validator(validate_order) .possible_values(&[ARG_VALUE_ORDER_SMALLEST_TO_LARGEST, ARG_VALUE_ORDER_PATH]) .help("criteria used to determine entry order in the archive")) } pub fn run(args: &ArgMatches) -> CliResult<()> { let source = args.value_of(ARG_NAME_SOURCE).unwrap(); let output = args.value_of(ARG_NAME_OUTPUT).unwrap(); let entry_order_criteria = args.value_of(ARG_NAME_ORDER) .map(arg_order_to_enum) .unwrap(); let strip_prefix = args.value_of(ARG_NAME_STRIP_PREFIX) .map(|s| s.to_string()); let kind = args.value_of(ARG_NAME_KIND).unwrap(); let kind = Kind::try_from_bytes(kind.as_bytes()).unwrap(); let settings = packer::Settings { entry_order_criteria, strip_prefix, kind, }; let archive = packer::pack_directory(&source, settings) .map_err(|e_lib| CliError::PackArchive { inner: e_lib })?; let mut file = OpenOptions::new() .read(true) .write(true) .create(true) .truncate(true) .open(output) .map_err(|e| CliError::IO { inner: e, path: output.to_string(), })?; let data = archive.as_slice(); file.write_all(data)?; Ok(()) } fn arg_order_to_enum(input: &str) -> packer::EntryOrderCriteria { match input { ARG_VALUE_ORDER_SMALLEST_TO_LARGEST => packer::EntryOrderCriteria::SmallestToLargest, ARG_VALUE_ORDER_PATH => packer::EntryOrderCriteria::Path, _ => { eprintln!(r#" Unexpected error! Please file a bug at https://github.com/Phrohdoh/easage/issues/new and provide the following text: Invalid input to 'arg_order_to_enum': {:?} Did you validate input via 'validate_order'? "#, input); ::std::process::exit(1);
} fn validate_order(v: String) -> Result<(), String> { if v == ARG_VALUE_ORDER_SMALLEST_TO_LARGEST || v == ARG_VALUE_ORDER_PATH { Ok(()) } else { Err(format!("{} must be one of '{}' or '{}'", ARG_NAME_ORDER, ARG_VALUE_ORDER_SMALLEST_TO_LARGEST, ARG_VALUE_ORDER_PATH)) } }
}, }
random_line_split
easage_pack.rs
use clap::{Arg, ArgMatches, App, SubCommand}; use ::std::fs::OpenOptions; use ::std::io::Write; use ::lib::{Kind, packer}; use ::{CliResult, CliError}; pub const COMMAND_NAME: &'static str = "pack"; const ARG_NAME_SOURCE: &'static str = "source"; const ARG_NAME_OUTPUT: &'static str = "output"; const ARG_NAME_KIND: &'static str = "kind"; const ARG_NAME_STRIP_PREFIX: &'static str = "strip-prefix"; const ARG_NAME_ORDER: &'static str = "order"; const ARG_VALUE_KIND_BIGF: &'static str = "BIGF"; const ARG_VALUE_KIND_BIG4: &'static str = "BIG4"; const ARG_VALUE_ORDER_SMALLEST_TO_LARGEST: &'static str = "smallest-to-largest"; const ARG_VALUE_ORDER_PATH: &'static str = "path"; pub fn get_command<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name(COMMAND_NAME) .about("Recursively package a directory structure into a BIG archive") .author("Taryn Hill <[email protected]>") .arg(Arg::with_name(ARG_NAME_SOURCE) .long(ARG_NAME_SOURCE) .value_name(ARG_NAME_SOURCE) .takes_value(true) .required(true) .help("path to the directory to pack into a BIG archive")) .arg(Arg::with_name(ARG_NAME_OUTPUT) .long(ARG_NAME_OUTPUT) .value_name(ARG_NAME_OUTPUT) .takes_value(true) .required(true) .help("path to the output BIG archive")) .arg(Arg::with_name(ARG_NAME_KIND) .long(ARG_NAME_KIND) .value_name(ARG_NAME_KIND) .takes_value(true) .default_value(ARG_VALUE_KIND_BIGF) .possible_values(&[ARG_VALUE_KIND_BIGF, ARG_VALUE_KIND_BIG4]) .help("use BIG4 for the Battle for Middle-Earth series or BIGF for Generals / Zero-Hour")) .arg(Arg::with_name(ARG_NAME_STRIP_PREFIX) .long(ARG_NAME_STRIP_PREFIX) .value_name(ARG_NAME_STRIP_PREFIX) .takes_value(true) .help("a prefix to strip from entry names")) .arg(Arg::with_name(ARG_NAME_ORDER) .long(ARG_NAME_ORDER) .value_name(ARG_NAME_ORDER) .takes_value(true) .default_value(ARG_VALUE_ORDER_PATH) .validator(validate_order) .possible_values(&[ARG_VALUE_ORDER_SMALLEST_TO_LARGEST, ARG_VALUE_ORDER_PATH]) .help("criteria used to determine entry order in the archive")) } pub fn run(args: &ArgMatches) -> CliResult<()> { let source = args.value_of(ARG_NAME_SOURCE).unwrap(); let output = args.value_of(ARG_NAME_OUTPUT).unwrap(); let entry_order_criteria = args.value_of(ARG_NAME_ORDER) .map(arg_order_to_enum) .unwrap(); let strip_prefix = args.value_of(ARG_NAME_STRIP_PREFIX) .map(|s| s.to_string()); let kind = args.value_of(ARG_NAME_KIND).unwrap(); let kind = Kind::try_from_bytes(kind.as_bytes()).unwrap(); let settings = packer::Settings { entry_order_criteria, strip_prefix, kind, }; let archive = packer::pack_directory(&source, settings) .map_err(|e_lib| CliError::PackArchive { inner: e_lib })?; let mut file = OpenOptions::new() .read(true) .write(true) .create(true) .truncate(true) .open(output) .map_err(|e| CliError::IO { inner: e, path: output.to_string(), })?; let data = archive.as_slice(); file.write_all(data)?; Ok(()) } fn arg_order_to_enum(input: &str) -> packer::EntryOrderCriteria { match input { ARG_VALUE_ORDER_SMALLEST_TO_LARGEST => packer::EntryOrderCriteria::SmallestToLargest, ARG_VALUE_ORDER_PATH => packer::EntryOrderCriteria::Path, _ => { eprintln!(r#" Unexpected error! Please file a bug at https://github.com/Phrohdoh/easage/issues/new and provide the following text: Invalid input to 'arg_order_to_enum': {:?} Did you validate input via 'validate_order'? "#, input); ::std::process::exit(1); }, } } fn validate_order(v: String) -> Result<(), String>
{ if v == ARG_VALUE_ORDER_SMALLEST_TO_LARGEST || v == ARG_VALUE_ORDER_PATH { Ok(()) } else { Err(format!("{} must be one of '{}' or '{}'", ARG_NAME_ORDER, ARG_VALUE_ORDER_SMALLEST_TO_LARGEST, ARG_VALUE_ORDER_PATH)) } }
identifier_body
build.rs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 anyhow::{Context, Result}; use std::{io::Write, path::Path, process::Command}; fn main() -> Result<()>
assert!( Path::new(&format!("{}/deploy_lib.o", out_dir)).exists(), "Could not prepare demo: {}", String::from_utf8(output.stderr) .unwrap() .trim() .split("\n") .last() .unwrap_or("") ); println!("cargo:rustc-link-search=native={}", out_dir); Ok(()) }
{ let out_dir = std::env::var("CARGO_MANIFEST_DIR")?; let python_script = concat!(env!("CARGO_MANIFEST_DIR"), "/src/build_resnet.py"); let synset_txt = concat!(env!("CARGO_MANIFEST_DIR"), "/synset.txt"); println!("cargo:rerun-if-changed={}", python_script); println!("cargo:rerun-if-changed={}", synset_txt); let output = Command::new("python3") .arg(python_script) .arg(&format!("--build-dir={}", out_dir)) .output() .with_context(|| anyhow::anyhow!("failed to run python3"))?; if !output.status.success() { std::io::stdout() .write_all(&output.stderr) .context("Failed to write error")?; panic!("Failed to execute build script"); }
identifier_body
build.rs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 anyhow::{Context, Result}; use std::{io::Write, path::Path, process::Command}; fn
() -> Result<()> { let out_dir = std::env::var("CARGO_MANIFEST_DIR")?; let python_script = concat!(env!("CARGO_MANIFEST_DIR"), "/src/build_resnet.py"); let synset_txt = concat!(env!("CARGO_MANIFEST_DIR"), "/synset.txt"); println!("cargo:rerun-if-changed={}", python_script); println!("cargo:rerun-if-changed={}", synset_txt); let output = Command::new("python3") .arg(python_script) .arg(&format!("--build-dir={}", out_dir)) .output() .with_context(|| anyhow::anyhow!("failed to run python3"))?; if!output.status.success() { std::io::stdout() .write_all(&output.stderr) .context("Failed to write error")?; panic!("Failed to execute build script"); } assert!( Path::new(&format!("{}/deploy_lib.o", out_dir)).exists(), "Could not prepare demo: {}", String::from_utf8(output.stderr) .unwrap() .trim() .split("\n") .last() .unwrap_or("") ); println!("cargo:rustc-link-search=native={}", out_dir); Ok(()) }
main
identifier_name
build.rs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */
let out_dir = std::env::var("CARGO_MANIFEST_DIR")?; let python_script = concat!(env!("CARGO_MANIFEST_DIR"), "/src/build_resnet.py"); let synset_txt = concat!(env!("CARGO_MANIFEST_DIR"), "/synset.txt"); println!("cargo:rerun-if-changed={}", python_script); println!("cargo:rerun-if-changed={}", synset_txt); let output = Command::new("python3") .arg(python_script) .arg(&format!("--build-dir={}", out_dir)) .output() .with_context(|| anyhow::anyhow!("failed to run python3"))?; if!output.status.success() { std::io::stdout() .write_all(&output.stderr) .context("Failed to write error")?; panic!("Failed to execute build script"); } assert!( Path::new(&format!("{}/deploy_lib.o", out_dir)).exists(), "Could not prepare demo: {}", String::from_utf8(output.stderr) .unwrap() .trim() .split("\n") .last() .unwrap_or("") ); println!("cargo:rustc-link-search=native={}", out_dir); Ok(()) }
use anyhow::{Context, Result}; use std::{io::Write, path::Path, process::Command}; fn main() -> Result<()> {
random_line_split
build.rs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 anyhow::{Context, Result}; use std::{io::Write, path::Path, process::Command}; fn main() -> Result<()> { let out_dir = std::env::var("CARGO_MANIFEST_DIR")?; let python_script = concat!(env!("CARGO_MANIFEST_DIR"), "/src/build_resnet.py"); let synset_txt = concat!(env!("CARGO_MANIFEST_DIR"), "/synset.txt"); println!("cargo:rerun-if-changed={}", python_script); println!("cargo:rerun-if-changed={}", synset_txt); let output = Command::new("python3") .arg(python_script) .arg(&format!("--build-dir={}", out_dir)) .output() .with_context(|| anyhow::anyhow!("failed to run python3"))?; if!output.status.success()
assert!( Path::new(&format!("{}/deploy_lib.o", out_dir)).exists(), "Could not prepare demo: {}", String::from_utf8(output.stderr) .unwrap() .trim() .split("\n") .last() .unwrap_or("") ); println!("cargo:rustc-link-search=native={}", out_dir); Ok(()) }
{ std::io::stdout() .write_all(&output.stderr) .context("Failed to write error")?; panic!("Failed to execute build script"); }
conditional_block
open_action.rs
use crate::{ actionable_events::{ActionDispatcher, ActionableEvent}, entity::{Entity, EntityRef, Realm}, player_output::PlayerOutput, utils::{capitalize, definite_character_name}, }; use std::time::Duration; /// Opens a portal. pub fn open( realm: &mut Realm, action_dispatcher: &ActionDispatcher, character_ref: EntityRef, portal_ref: EntityRef, ) -> Result<Vec<PlayerOutput>, String> { let (character, room) = realm.character_and_room_res(character_ref)?; let portal = realm.portal(portal_ref).ok_or("That exit doesn't exist.")?; if!portal.can_open_from_room(room.entity_ref()) { return Err("Exit cannot be opened.".into()); } let name = portal.name_from_room(room.entity_ref()); if portal.is_open() { return Err(format!("The {} is already open.", name)); } let mut output = vec![]; if let Some(openable) = portal.as_openable() { let required_key = openable.required_key(); if required_key.is_empty() { output.push(PlayerOutput::new_from_string( character_ref.id(), format!("You open the {}.\n", name), )); } else if character .inventory() .iter() .any(|item| match realm.item(*item) { Some(item) => item.name() == required_key, _ => false, }) { output.push(PlayerOutput::new_from_string( character_ref.id(), format!("You use the {} and open the {}.\n", required_key, name), )); } else { return Err(format!("The {} is locked.", name)); } } let character_name = capitalize(&definite_character_name(realm, character_ref)?); for character in room.characters() { if *character!= character_ref { output.push(PlayerOutput::new_from_string( character.id(), format!("{} opens the {}.\n", character_name, name), )); } } if let Some(openable) = realm.openable_mut(portal_ref) { openable.set_open(true); } if let Some(openable) = realm.openable(portal_ref) { if let Some(timeout) = openable.auto_close_timeout() { action_dispatcher.dispatch_after( ActionableEvent::AutoClose(portal_ref, openable.auto_close_message().to_owned()), Duration::from_millis(timeout.get() as u64), ) } } Ok(output) } /// Closes a portal. pub fn
( realm: &mut Realm, character_ref: EntityRef, portal_ref: EntityRef, ) -> Result<Vec<PlayerOutput>, String> { let (_, room) = realm.character_and_room_res(character_ref)?; let portal = realm.portal(portal_ref).ok_or("That exit doesn't exist.")?; if!portal.can_open_from_room(room.entity_ref()) { return Err("Exit cannot be closed.".into()); } let name = portal.name_from_room(room.entity_ref()); if!portal.is_open() { return Err(format!("The {} is already closed.", name)); } let mut output = vec![PlayerOutput::new_from_string( character_ref.id(), format!("You close the {}.\n", name), )]; let character_name = capitalize(&definite_character_name(realm, character_ref)?); for character in room.characters() { if *character!= character_ref { output.push(PlayerOutput::new_from_string( character.id(), format!("{} closes the {}.\n", character_name, name), )); } } if let Some(portal) = realm.portal_mut(portal_ref) { portal.set_open(false); } Ok(output) }
close
identifier_name
open_action.rs
use crate::{ actionable_events::{ActionDispatcher, ActionableEvent}, entity::{Entity, EntityRef, Realm}, player_output::PlayerOutput, utils::{capitalize, definite_character_name},
/// Opens a portal. pub fn open( realm: &mut Realm, action_dispatcher: &ActionDispatcher, character_ref: EntityRef, portal_ref: EntityRef, ) -> Result<Vec<PlayerOutput>, String> { let (character, room) = realm.character_and_room_res(character_ref)?; let portal = realm.portal(portal_ref).ok_or("That exit doesn't exist.")?; if!portal.can_open_from_room(room.entity_ref()) { return Err("Exit cannot be opened.".into()); } let name = portal.name_from_room(room.entity_ref()); if portal.is_open() { return Err(format!("The {} is already open.", name)); } let mut output = vec![]; if let Some(openable) = portal.as_openable() { let required_key = openable.required_key(); if required_key.is_empty() { output.push(PlayerOutput::new_from_string( character_ref.id(), format!("You open the {}.\n", name), )); } else if character .inventory() .iter() .any(|item| match realm.item(*item) { Some(item) => item.name() == required_key, _ => false, }) { output.push(PlayerOutput::new_from_string( character_ref.id(), format!("You use the {} and open the {}.\n", required_key, name), )); } else { return Err(format!("The {} is locked.", name)); } } let character_name = capitalize(&definite_character_name(realm, character_ref)?); for character in room.characters() { if *character!= character_ref { output.push(PlayerOutput::new_from_string( character.id(), format!("{} opens the {}.\n", character_name, name), )); } } if let Some(openable) = realm.openable_mut(portal_ref) { openable.set_open(true); } if let Some(openable) = realm.openable(portal_ref) { if let Some(timeout) = openable.auto_close_timeout() { action_dispatcher.dispatch_after( ActionableEvent::AutoClose(portal_ref, openable.auto_close_message().to_owned()), Duration::from_millis(timeout.get() as u64), ) } } Ok(output) } /// Closes a portal. pub fn close( realm: &mut Realm, character_ref: EntityRef, portal_ref: EntityRef, ) -> Result<Vec<PlayerOutput>, String> { let (_, room) = realm.character_and_room_res(character_ref)?; let portal = realm.portal(portal_ref).ok_or("That exit doesn't exist.")?; if!portal.can_open_from_room(room.entity_ref()) { return Err("Exit cannot be closed.".into()); } let name = portal.name_from_room(room.entity_ref()); if!portal.is_open() { return Err(format!("The {} is already closed.", name)); } let mut output = vec![PlayerOutput::new_from_string( character_ref.id(), format!("You close the {}.\n", name), )]; let character_name = capitalize(&definite_character_name(realm, character_ref)?); for character in room.characters() { if *character!= character_ref { output.push(PlayerOutput::new_from_string( character.id(), format!("{} closes the {}.\n", character_name, name), )); } } if let Some(portal) = realm.portal_mut(portal_ref) { portal.set_open(false); } Ok(output) }
}; use std::time::Duration;
random_line_split
open_action.rs
use crate::{ actionable_events::{ActionDispatcher, ActionableEvent}, entity::{Entity, EntityRef, Realm}, player_output::PlayerOutput, utils::{capitalize, definite_character_name}, }; use std::time::Duration; /// Opens a portal. pub fn open( realm: &mut Realm, action_dispatcher: &ActionDispatcher, character_ref: EntityRef, portal_ref: EntityRef, ) -> Result<Vec<PlayerOutput>, String>
format!("You open the {}.\n", name), )); } else if character .inventory() .iter() .any(|item| match realm.item(*item) { Some(item) => item.name() == required_key, _ => false, }) { output.push(PlayerOutput::new_from_string( character_ref.id(), format!("You use the {} and open the {}.\n", required_key, name), )); } else { return Err(format!("The {} is locked.", name)); } } let character_name = capitalize(&definite_character_name(realm, character_ref)?); for character in room.characters() { if *character!= character_ref { output.push(PlayerOutput::new_from_string( character.id(), format!("{} opens the {}.\n", character_name, name), )); } } if let Some(openable) = realm.openable_mut(portal_ref) { openable.set_open(true); } if let Some(openable) = realm.openable(portal_ref) { if let Some(timeout) = openable.auto_close_timeout() { action_dispatcher.dispatch_after( ActionableEvent::AutoClose(portal_ref, openable.auto_close_message().to_owned()), Duration::from_millis(timeout.get() as u64), ) } } Ok(output) } /// Closes a portal. pub fn close( realm: &mut Realm, character_ref: EntityRef, portal_ref: EntityRef, ) -> Result<Vec<PlayerOutput>, String> { let (_, room) = realm.character_and_room_res(character_ref)?; let portal = realm.portal(portal_ref).ok_or("That exit doesn't exist.")?; if!portal.can_open_from_room(room.entity_ref()) { return Err("Exit cannot be closed.".into()); } let name = portal.name_from_room(room.entity_ref()); if!portal.is_open() { return Err(format!("The {} is already closed.", name)); } let mut output = vec![PlayerOutput::new_from_string( character_ref.id(), format!("You close the {}.\n", name), )]; let character_name = capitalize(&definite_character_name(realm, character_ref)?); for character in room.characters() { if *character!= character_ref { output.push(PlayerOutput::new_from_string( character.id(), format!("{} closes the {}.\n", character_name, name), )); } } if let Some(portal) = realm.portal_mut(portal_ref) { portal.set_open(false); } Ok(output) }
{ let (character, room) = realm.character_and_room_res(character_ref)?; let portal = realm.portal(portal_ref).ok_or("That exit doesn't exist.")?; if !portal.can_open_from_room(room.entity_ref()) { return Err("Exit cannot be opened.".into()); } let name = portal.name_from_room(room.entity_ref()); if portal.is_open() { return Err(format!("The {} is already open.", name)); } let mut output = vec![]; if let Some(openable) = portal.as_openable() { let required_key = openable.required_key(); if required_key.is_empty() { output.push(PlayerOutput::new_from_string( character_ref.id(),
identifier_body
lib.rs
#![feature(cstr_memory)] extern crate libc; use std::collections::HashMap; use std::ffi::{CStr, CString}; use libc::c_char; use std::str; #[derive(Debug)] pub struct Usage { calls: HashMap<String, u32>, total: u32 } impl Usage { fn new() -> Usage { Usage { calls: HashMap::new(), total: 0 } } fn record(&mut self, method_name: String) { *self.calls.entry(method_name).or_insert(0) += 1; self.total += 1; } } #[derive(Debug)] pub struct CallCount { count: u32, method_name: String } impl CallCount { fn new(method: &str, count: &u32) -> CallCount { CallCount { method_name: method.to_string(), count: *count } } fn to_c_struct(&self) -> CCallCount { let method = self.method_name.clone(); let method = CString::new(method).unwrap(); CCallCount { method_name: method.into_ptr(), count: self.count } } } #[repr(C)] pub struct CCallCount { count: u32, method_name: *const c_char } #[repr(C)] pub struct Report { length: usize, call_counts: *const CCallCount } #[no_mangle] pub extern "C" fn
() -> Box<Usage> { Box::new(Usage::new()) } #[no_mangle] pub extern "C" fn record(usage: &mut Usage, event: *const c_char, file: *const c_char, line: u32, id: *const c_char, classname: *const c_char) { let event = unsafe { CStr::from_ptr(event) }; let event = str::from_utf8(event.to_bytes()).unwrap(); if event == "call" || event == "c-call" { let method_name = unsafe { CStr::from_ptr(id) }; let method_name = str::from_utf8(method_name.to_bytes()).unwrap(); let class_name = unsafe { CStr::from_ptr(classname) }; let class_name = str::from_utf8(class_name.to_bytes()).unwrap(); usage.record(class_name.to_string() + "#" + method_name) } } #[no_mangle] pub extern "C" fn report(usage: &Usage) -> Report { let mut counts: Vec<CallCount> = usage.calls .iter() .map(|(method, count)| CallCount::new(method, count) ) .collect(); counts.sort_by(|a, b| a.count.cmp(&b.count).reverse()); let c_counts: Vec<CCallCount> = counts .iter() .map(|cc| cc.to_c_struct()) .collect(); Report { length: c_counts.len(), call_counts: c_counts.as_ptr() } }
new_usage
identifier_name
lib.rs
#![feature(cstr_memory)] extern crate libc; use std::collections::HashMap; use std::ffi::{CStr, CString}; use libc::c_char; use std::str; #[derive(Debug)] pub struct Usage { calls: HashMap<String, u32>, total: u32 } impl Usage { fn new() -> Usage { Usage { calls: HashMap::new(), total: 0 } } fn record(&mut self, method_name: String) { *self.calls.entry(method_name).or_insert(0) += 1; self.total += 1; } } #[derive(Debug)] pub struct CallCount { count: u32, method_name: String } impl CallCount { fn new(method: &str, count: &u32) -> CallCount { CallCount { method_name: method.to_string(), count: *count } } fn to_c_struct(&self) -> CCallCount { let method = self.method_name.clone(); let method = CString::new(method).unwrap(); CCallCount { method_name: method.into_ptr(), count: self.count } } } #[repr(C)] pub struct CCallCount { count: u32, method_name: *const c_char } #[repr(C)] pub struct Report { length: usize, call_counts: *const CCallCount } #[no_mangle] pub extern "C" fn new_usage() -> Box<Usage> { Box::new(Usage::new()) } #[no_mangle] pub extern "C" fn record(usage: &mut Usage, event: *const c_char, file: *const c_char, line: u32, id: *const c_char, classname: *const c_char) { let event = unsafe { CStr::from_ptr(event) }; let event = str::from_utf8(event.to_bytes()).unwrap(); if event == "call" || event == "c-call"
} #[no_mangle] pub extern "C" fn report(usage: &Usage) -> Report { let mut counts: Vec<CallCount> = usage.calls .iter() .map(|(method, count)| CallCount::new(method, count) ) .collect(); counts.sort_by(|a, b| a.count.cmp(&b.count).reverse()); let c_counts: Vec<CCallCount> = counts .iter() .map(|cc| cc.to_c_struct()) .collect(); Report { length: c_counts.len(), call_counts: c_counts.as_ptr() } }
{ let method_name = unsafe { CStr::from_ptr(id) }; let method_name = str::from_utf8(method_name.to_bytes()).unwrap(); let class_name = unsafe { CStr::from_ptr(classname) }; let class_name = str::from_utf8(class_name.to_bytes()).unwrap(); usage.record(class_name.to_string() + "#" + method_name) }
conditional_block
lib.rs
#![feature(cstr_memory)] extern crate libc; use std::collections::HashMap; use std::ffi::{CStr, CString}; use libc::c_char; use std::str; #[derive(Debug)] pub struct Usage { calls: HashMap<String, u32>, total: u32 } impl Usage { fn new() -> Usage { Usage { calls: HashMap::new(), total: 0 } } fn record(&mut self, method_name: String) { *self.calls.entry(method_name).or_insert(0) += 1; self.total += 1; } } #[derive(Debug)] pub struct CallCount { count: u32, method_name: String } impl CallCount { fn new(method: &str, count: &u32) -> CallCount { CallCount { method_name: method.to_string(), count: *count } } fn to_c_struct(&self) -> CCallCount { let method = self.method_name.clone(); let method = CString::new(method).unwrap(); CCallCount { method_name: method.into_ptr(), count: self.count } } } #[repr(C)] pub struct CCallCount { count: u32, method_name: *const c_char } #[repr(C)] pub struct Report { length: usize, call_counts: *const CCallCount } #[no_mangle] pub extern "C" fn new_usage() -> Box<Usage>
#[no_mangle] pub extern "C" fn record(usage: &mut Usage, event: *const c_char, file: *const c_char, line: u32, id: *const c_char, classname: *const c_char) { let event = unsafe { CStr::from_ptr(event) }; let event = str::from_utf8(event.to_bytes()).unwrap(); if event == "call" || event == "c-call" { let method_name = unsafe { CStr::from_ptr(id) }; let method_name = str::from_utf8(method_name.to_bytes()).unwrap(); let class_name = unsafe { CStr::from_ptr(classname) }; let class_name = str::from_utf8(class_name.to_bytes()).unwrap(); usage.record(class_name.to_string() + "#" + method_name) } } #[no_mangle] pub extern "C" fn report(usage: &Usage) -> Report { let mut counts: Vec<CallCount> = usage.calls .iter() .map(|(method, count)| CallCount::new(method, count) ) .collect(); counts.sort_by(|a, b| a.count.cmp(&b.count).reverse()); let c_counts: Vec<CCallCount> = counts .iter() .map(|cc| cc.to_c_struct()) .collect(); Report { length: c_counts.len(), call_counts: c_counts.as_ptr() } }
{ Box::new(Usage::new()) }
identifier_body
lib.rs
#![feature(cstr_memory)] extern crate libc; use std::collections::HashMap; use std::ffi::{CStr, CString}; use libc::c_char; use std::str; #[derive(Debug)] pub struct Usage { calls: HashMap<String, u32>, total: u32 } impl Usage {
total: 0 } } fn record(&mut self, method_name: String) { *self.calls.entry(method_name).or_insert(0) += 1; self.total += 1; } } #[derive(Debug)] pub struct CallCount { count: u32, method_name: String } impl CallCount { fn new(method: &str, count: &u32) -> CallCount { CallCount { method_name: method.to_string(), count: *count } } fn to_c_struct(&self) -> CCallCount { let method = self.method_name.clone(); let method = CString::new(method).unwrap(); CCallCount { method_name: method.into_ptr(), count: self.count } } } #[repr(C)] pub struct CCallCount { count: u32, method_name: *const c_char } #[repr(C)] pub struct Report { length: usize, call_counts: *const CCallCount } #[no_mangle] pub extern "C" fn new_usage() -> Box<Usage> { Box::new(Usage::new()) } #[no_mangle] pub extern "C" fn record(usage: &mut Usage, event: *const c_char, file: *const c_char, line: u32, id: *const c_char, classname: *const c_char) { let event = unsafe { CStr::from_ptr(event) }; let event = str::from_utf8(event.to_bytes()).unwrap(); if event == "call" || event == "c-call" { let method_name = unsafe { CStr::from_ptr(id) }; let method_name = str::from_utf8(method_name.to_bytes()).unwrap(); let class_name = unsafe { CStr::from_ptr(classname) }; let class_name = str::from_utf8(class_name.to_bytes()).unwrap(); usage.record(class_name.to_string() + "#" + method_name) } } #[no_mangle] pub extern "C" fn report(usage: &Usage) -> Report { let mut counts: Vec<CallCount> = usage.calls .iter() .map(|(method, count)| CallCount::new(method, count) ) .collect(); counts.sort_by(|a, b| a.count.cmp(&b.count).reverse()); let c_counts: Vec<CCallCount> = counts .iter() .map(|cc| cc.to_c_struct()) .collect(); Report { length: c_counts.len(), call_counts: c_counts.as_ptr() } }
fn new() -> Usage { Usage { calls: HashMap::new(),
random_line_split
deriving-cmp-generic-struct-enum.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. #![feature(struct_variant)] #[deriving(Eq, TotalEq, Ord, TotalOrd)] enum ES<T> { ES1 { x: T }, ES2 { x: T, y: T } } pub fn
() { let (es11, es12, es21, es22) = (ES1 {x: 1}, ES1 {x: 2}, ES2 {x: 1, y: 1}, ES2 {x: 1, y: 2}); // in order for both Ord and TotalOrd let ess = [es11, es12, es21, es22]; for (i, es1) in ess.iter().enumerate() { for (j, es2) in ess.iter().enumerate() { let ord = i.cmp(&j); let eq = i == j; let (lt, le) = (i < j, i <= j); let (gt, ge) = (i > j, i >= j); // Eq assert_eq!(*es1 == *es2, eq); assert_eq!(*es1!= *es2,!eq); // Ord assert_eq!(*es1 < *es2, lt); assert_eq!(*es1 > *es2, gt); assert_eq!(*es1 <= *es2, le); assert_eq!(*es1 >= *es2, ge); // TotalOrd assert_eq!(es1.cmp(es2), ord); } } }
main
identifier_name
deriving-cmp-generic-struct-enum.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. #![feature(struct_variant)] #[deriving(Eq, TotalEq, Ord, TotalOrd)] enum ES<T> { ES1 { x: T }, ES2 { x: T, y: T } } pub fn main()
assert_eq!(*es1 > *es2, gt); assert_eq!(*es1 <= *es2, le); assert_eq!(*es1 >= *es2, ge); // TotalOrd assert_eq!(es1.cmp(es2), ord); } } }
{ let (es11, es12, es21, es22) = (ES1 {x: 1}, ES1 {x: 2}, ES2 {x: 1, y: 1}, ES2 {x: 1, y: 2}); // in order for both Ord and TotalOrd let ess = [es11, es12, es21, es22]; for (i, es1) in ess.iter().enumerate() { for (j, es2) in ess.iter().enumerate() { let ord = i.cmp(&j); let eq = i == j; let (lt, le) = (i < j, i <= j); let (gt, ge) = (i > j, i >= j); // Eq assert_eq!(*es1 == *es2, eq); assert_eq!(*es1 != *es2, !eq); // Ord assert_eq!(*es1 < *es2, lt);
identifier_body
deriving-cmp-generic-struct-enum.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. #![feature(struct_variant)] #[deriving(Eq, TotalEq, Ord, TotalOrd)] enum ES<T> { ES1 { x: T }, ES2 { x: T, y: T } }
let (es11, es12, es21, es22) = (ES1 {x: 1}, ES1 {x: 2}, ES2 {x: 1, y: 1}, ES2 {x: 1, y: 2}); // in order for both Ord and TotalOrd let ess = [es11, es12, es21, es22]; for (i, es1) in ess.iter().enumerate() { for (j, es2) in ess.iter().enumerate() { let ord = i.cmp(&j); let eq = i == j; let (lt, le) = (i < j, i <= j); let (gt, ge) = (i > j, i >= j); // Eq assert_eq!(*es1 == *es2, eq); assert_eq!(*es1!= *es2,!eq); // Ord assert_eq!(*es1 < *es2, lt); assert_eq!(*es1 > *es2, gt); assert_eq!(*es1 <= *es2, le); assert_eq!(*es1 >= *es2, ge); // TotalOrd assert_eq!(es1.cmp(es2), ord); } } }
pub fn main() {
random_line_split
stack.rs
//! Low-level details of stack accesses. //! //! The `ir::StackSlots` type deals with stack slots and stack frame layout. The `StackRef` type //! defined in this module expresses the low-level details of accessing a stack slot from an //! encoded instruction. use crate::ir::stackslot::{StackOffset, StackSlotKind, StackSlots}; use crate::ir::StackSlot; /// A method for referencing a stack slot in the current stack frame. /// /// Stack slots are addressed with a constant offset from a base register. The base can be the /// stack pointer, the frame pointer, or (in the future) a zone register pointing to an inner zone /// of a large stack frame. #[derive(Clone, Copy, Debug)] pub struct StackRef { /// The base register to use for addressing. pub base: StackBase, /// Immediate offset from the base register to the first byte of the stack slot. pub offset: StackOffset, } impl StackRef { /// Get a reference to the stack slot `ss` using one of the base pointers in `mask`. pub fn masked(ss: StackSlot, mask: StackBaseMask, frame: &StackSlots) -> Option<Self> { // Try an SP-relative reference. if mask.contains(StackBase::SP) { return Some(Self::sp(ss, frame)); } // No reference possible with this mask. None } /// Get a reference to `ss` using the stack pointer as a base. pub fn sp(ss: StackSlot, frame: &StackSlots) -> Self { let size = frame .frame_size .expect("Stack layout must be computed before referencing stack slots"); let slot = &frame[ss]; let offset = if slot.kind == StackSlotKind::OutgoingArg { // Outgoing argument slots have offsets relative to our stack pointer. slot.offset.unwrap() } else { // All other slots have offsets relative to our caller's stack frame. // Offset where SP is pointing. (All ISAs have stacks growing downwards.) let sp_offset = -(size as StackOffset); slot.offset.unwrap() - sp_offset }; Self { base: StackBase::SP, offset, } } } /// Generic base register for referencing stack slots. /// /// Most ISAs have a stack pointer and an optional frame pointer, so provide generic names for /// those two base pointers. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum StackBase { /// Use the stack pointer. SP = 0, /// Use the frame pointer (if one is present). FP = 1, /// Use an explicit zone pointer in a general-purpose register. /// /// This feature is not yet implemented. Zone = 2, } /// Bit mask of supported stack bases. /// /// Many instruction encodings can use different base registers while others only work with the /// stack pointer, say. A `StackBaseMask` is a bit mask of supported stack bases for a given /// instruction encoding. /// /// This behaves like a set of `StackBase` variants. /// /// The internal representation as a `u8` is public because stack base masks are used in constant /// tables generated from the Python encoding definitions.
pub fn contains(self, base: StackBase) -> bool { self.0 & (1 << base as usize)!= 0 } }
#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct StackBaseMask(pub u8); impl StackBaseMask { /// Check if this mask contains the `base` variant.
random_line_split
stack.rs
//! Low-level details of stack accesses. //! //! The `ir::StackSlots` type deals with stack slots and stack frame layout. The `StackRef` type //! defined in this module expresses the low-level details of accessing a stack slot from an //! encoded instruction. use crate::ir::stackslot::{StackOffset, StackSlotKind, StackSlots}; use crate::ir::StackSlot; /// A method for referencing a stack slot in the current stack frame. /// /// Stack slots are addressed with a constant offset from a base register. The base can be the /// stack pointer, the frame pointer, or (in the future) a zone register pointing to an inner zone /// of a large stack frame. #[derive(Clone, Copy, Debug)] pub struct StackRef { /// The base register to use for addressing. pub base: StackBase, /// Immediate offset from the base register to the first byte of the stack slot. pub offset: StackOffset, } impl StackRef { /// Get a reference to the stack slot `ss` using one of the base pointers in `mask`. pub fn masked(ss: StackSlot, mask: StackBaseMask, frame: &StackSlots) -> Option<Self> { // Try an SP-relative reference. if mask.contains(StackBase::SP) { return Some(Self::sp(ss, frame)); } // No reference possible with this mask. None } /// Get a reference to `ss` using the stack pointer as a base. pub fn sp(ss: StackSlot, frame: &StackSlots) -> Self { let size = frame .frame_size .expect("Stack layout must be computed before referencing stack slots"); let slot = &frame[ss]; let offset = if slot.kind == StackSlotKind::OutgoingArg { // Outgoing argument slots have offsets relative to our stack pointer. slot.offset.unwrap() } else
; Self { base: StackBase::SP, offset, } } } /// Generic base register for referencing stack slots. /// /// Most ISAs have a stack pointer and an optional frame pointer, so provide generic names for /// those two base pointers. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum StackBase { /// Use the stack pointer. SP = 0, /// Use the frame pointer (if one is present). FP = 1, /// Use an explicit zone pointer in a general-purpose register. /// /// This feature is not yet implemented. Zone = 2, } /// Bit mask of supported stack bases. /// /// Many instruction encodings can use different base registers while others only work with the /// stack pointer, say. A `StackBaseMask` is a bit mask of supported stack bases for a given /// instruction encoding. /// /// This behaves like a set of `StackBase` variants. /// /// The internal representation as a `u8` is public because stack base masks are used in constant /// tables generated from the Python encoding definitions. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct StackBaseMask(pub u8); impl StackBaseMask { /// Check if this mask contains the `base` variant. pub fn contains(self, base: StackBase) -> bool { self.0 & (1 << base as usize)!= 0 } }
{ // All other slots have offsets relative to our caller's stack frame. // Offset where SP is pointing. (All ISAs have stacks growing downwards.) let sp_offset = -(size as StackOffset); slot.offset.unwrap() - sp_offset }
conditional_block
stack.rs
//! Low-level details of stack accesses. //! //! The `ir::StackSlots` type deals with stack slots and stack frame layout. The `StackRef` type //! defined in this module expresses the low-level details of accessing a stack slot from an //! encoded instruction. use crate::ir::stackslot::{StackOffset, StackSlotKind, StackSlots}; use crate::ir::StackSlot; /// A method for referencing a stack slot in the current stack frame. /// /// Stack slots are addressed with a constant offset from a base register. The base can be the /// stack pointer, the frame pointer, or (in the future) a zone register pointing to an inner zone /// of a large stack frame. #[derive(Clone, Copy, Debug)] pub struct StackRef { /// The base register to use for addressing. pub base: StackBase, /// Immediate offset from the base register to the first byte of the stack slot. pub offset: StackOffset, } impl StackRef { /// Get a reference to the stack slot `ss` using one of the base pointers in `mask`. pub fn masked(ss: StackSlot, mask: StackBaseMask, frame: &StackSlots) -> Option<Self> { // Try an SP-relative reference. if mask.contains(StackBase::SP) { return Some(Self::sp(ss, frame)); } // No reference possible with this mask. None } /// Get a reference to `ss` using the stack pointer as a base. pub fn sp(ss: StackSlot, frame: &StackSlots) -> Self { let size = frame .frame_size .expect("Stack layout must be computed before referencing stack slots"); let slot = &frame[ss]; let offset = if slot.kind == StackSlotKind::OutgoingArg { // Outgoing argument slots have offsets relative to our stack pointer. slot.offset.unwrap() } else { // All other slots have offsets relative to our caller's stack frame. // Offset where SP is pointing. (All ISAs have stacks growing downwards.) let sp_offset = -(size as StackOffset); slot.offset.unwrap() - sp_offset }; Self { base: StackBase::SP, offset, } } } /// Generic base register for referencing stack slots. /// /// Most ISAs have a stack pointer and an optional frame pointer, so provide generic names for /// those two base pointers. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum StackBase { /// Use the stack pointer. SP = 0, /// Use the frame pointer (if one is present). FP = 1, /// Use an explicit zone pointer in a general-purpose register. /// /// This feature is not yet implemented. Zone = 2, } /// Bit mask of supported stack bases. /// /// Many instruction encodings can use different base registers while others only work with the /// stack pointer, say. A `StackBaseMask` is a bit mask of supported stack bases for a given /// instruction encoding. /// /// This behaves like a set of `StackBase` variants. /// /// The internal representation as a `u8` is public because stack base masks are used in constant /// tables generated from the Python encoding definitions. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct StackBaseMask(pub u8); impl StackBaseMask { /// Check if this mask contains the `base` variant. pub fn contains(self, base: StackBase) -> bool
}
{ self.0 & (1 << base as usize) != 0 }
identifier_body
stack.rs
//! Low-level details of stack accesses. //! //! The `ir::StackSlots` type deals with stack slots and stack frame layout. The `StackRef` type //! defined in this module expresses the low-level details of accessing a stack slot from an //! encoded instruction. use crate::ir::stackslot::{StackOffset, StackSlotKind, StackSlots}; use crate::ir::StackSlot; /// A method for referencing a stack slot in the current stack frame. /// /// Stack slots are addressed with a constant offset from a base register. The base can be the /// stack pointer, the frame pointer, or (in the future) a zone register pointing to an inner zone /// of a large stack frame. #[derive(Clone, Copy, Debug)] pub struct StackRef { /// The base register to use for addressing. pub base: StackBase, /// Immediate offset from the base register to the first byte of the stack slot. pub offset: StackOffset, } impl StackRef { /// Get a reference to the stack slot `ss` using one of the base pointers in `mask`. pub fn masked(ss: StackSlot, mask: StackBaseMask, frame: &StackSlots) -> Option<Self> { // Try an SP-relative reference. if mask.contains(StackBase::SP) { return Some(Self::sp(ss, frame)); } // No reference possible with this mask. None } /// Get a reference to `ss` using the stack pointer as a base. pub fn sp(ss: StackSlot, frame: &StackSlots) -> Self { let size = frame .frame_size .expect("Stack layout must be computed before referencing stack slots"); let slot = &frame[ss]; let offset = if slot.kind == StackSlotKind::OutgoingArg { // Outgoing argument slots have offsets relative to our stack pointer. slot.offset.unwrap() } else { // All other slots have offsets relative to our caller's stack frame. // Offset where SP is pointing. (All ISAs have stacks growing downwards.) let sp_offset = -(size as StackOffset); slot.offset.unwrap() - sp_offset }; Self { base: StackBase::SP, offset, } } } /// Generic base register for referencing stack slots. /// /// Most ISAs have a stack pointer and an optional frame pointer, so provide generic names for /// those two base pointers. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum
{ /// Use the stack pointer. SP = 0, /// Use the frame pointer (if one is present). FP = 1, /// Use an explicit zone pointer in a general-purpose register. /// /// This feature is not yet implemented. Zone = 2, } /// Bit mask of supported stack bases. /// /// Many instruction encodings can use different base registers while others only work with the /// stack pointer, say. A `StackBaseMask` is a bit mask of supported stack bases for a given /// instruction encoding. /// /// This behaves like a set of `StackBase` variants. /// /// The internal representation as a `u8` is public because stack base masks are used in constant /// tables generated from the Python encoding definitions. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct StackBaseMask(pub u8); impl StackBaseMask { /// Check if this mask contains the `base` variant. pub fn contains(self, base: StackBase) -> bool { self.0 & (1 << base as usize)!= 0 } }
StackBase
identifier_name
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 http://mozilla.org/MPL/2.0/. */ #![feature(plugin)] #![plugin(serde_macros)] #![plugin(clippy)] #![deny(clippy)] #[macro_use] extern crate hyper; extern crate iron; #[macro_use] extern crate log; extern crate mktemp; extern crate openssl; extern crate openssl_sys; extern crate serde; extern crate serde_json; macro_rules! checklock ( ($e: expr) => { match $e { Ok(guard) => guard, Err(poisoned) => poisoned.into_inner(), } } ); macro_rules! current_dir { () => { { use std::path::PathBuf; let mut this_file = PathBuf::from(file!()); this_file.pop(); this_file.to_str().unwrap().to_owned() } }; } mod certificate_manager; mod certificate_record; mod dns_client; mod https_server_factory; mod letsencrypt; mod ssl_context; mod utils; pub use certificate_manager::*; pub use certificate_record::*; pub use dns_client::*; pub use https_server_factory::*; pub use letsencrypt::*; pub use ssl_context::*; #[derive(Clone, Eq, PartialEq)] pub enum
{ Enabled, Disabled, }
TlsOption
identifier_name
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 http://mozilla.org/MPL/2.0/. */ #![feature(plugin)] #![plugin(serde_macros)] #![plugin(clippy)] #![deny(clippy)] #[macro_use] extern crate hyper; extern crate iron; #[macro_use] extern crate log; extern crate mktemp; extern crate openssl; extern crate openssl_sys; extern crate serde; extern crate serde_json; macro_rules! checklock ( ($e: expr) => { match $e { Ok(guard) => guard, Err(poisoned) => poisoned.into_inner(), }
} ); macro_rules! current_dir { () => { { use std::path::PathBuf; let mut this_file = PathBuf::from(file!()); this_file.pop(); this_file.to_str().unwrap().to_owned() } }; } mod certificate_manager; mod certificate_record; mod dns_client; mod https_server_factory; mod letsencrypt; mod ssl_context; mod utils; pub use certificate_manager::*; pub use certificate_record::*; pub use dns_client::*; pub use https_server_factory::*; pub use letsencrypt::*; pub use ssl_context::*; #[derive(Clone, Eq, PartialEq)] pub enum TlsOption { Enabled, Disabled, }
random_line_split
htmlbodyelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::HTMLBodyElementBinding; use dom::bindings::codegen::Bindings::HTMLBodyElementBinding::HTMLBodyElementMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::InheritTypes::EventTargetCast; use dom::bindings::codegen::InheritTypes::{HTMLBodyElementDerived, HTMLElementCast}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::HTMLBodyElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId, EventTargetHelpers}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId, window_from_node}; use dom::virtualmethods::VirtualMethods; use servo_util::atom::Atom; use servo_util::str::DOMString; #[deriving(Encodable)] #[must_root] pub struct HTMLBodyElement { pub htmlelement: HTMLElement } impl HTMLBodyElementDerived for EventTarget { fn is_htmlbodyelement(&self) -> bool { self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLBodyElementTypeId)) } } impl HTMLBodyElement { pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLBodyElement { HTMLBodyElement { htmlelement: HTMLElement::new_inherited(HTMLBodyElementTypeId, localName, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLBodyElement> { let element = HTMLBodyElement::new_inherited(localName, document); Node::reflect_node(box element, document, HTMLBodyElementBinding::Wrap) } } impl<'a> HTMLBodyElementMethods for JSRef<'a, HTMLBodyElement> { fn GetOnunload(self) -> Option<EventHandlerNonNull> { let win = window_from_node(self).root(); win.deref().GetOnunload() } fn SetOnunload(self, listener: Option<EventHandlerNonNull>) { let win = window_from_node(self).root(); win.deref().SetOnunload(listener) } } impl<'a> VirtualMethods for JSRef<'a, HTMLBodyElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods>
fn after_set_attr(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.after_set_attr(name, value.clone()), _ => (), } if name.as_slice().starts_with("on") { static forwarded_events: &'static [&'static str] = &["onfocus", "onload", "onscroll", "onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onstorage", "onresize", "onunload", "onerror"]; let window = window_from_node(*self).root(); let (cx, url, reflector) = (window.get_cx(), window.get_url(), window.reflector().get_jsobject()); let evtarget: JSRef<EventTarget> = if forwarded_events.iter().any(|&event| name.as_slice() == event) { EventTargetCast::from_ref(*window) } else { EventTargetCast::from_ref(*self) }; evtarget.set_event_handler_uncompiled(cx, url, reflector, name.as_slice().slice_from(2), value); } } } impl Reflectable for HTMLBodyElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
{ let element: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(element as &VirtualMethods) }
identifier_body
htmlbodyelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::HTMLBodyElementBinding; use dom::bindings::codegen::Bindings::HTMLBodyElementBinding::HTMLBodyElementMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::InheritTypes::EventTargetCast; use dom::bindings::codegen::InheritTypes::{HTMLBodyElementDerived, HTMLElementCast}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::HTMLBodyElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId, EventTargetHelpers}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId, window_from_node}; use dom::virtualmethods::VirtualMethods; use servo_util::atom::Atom; use servo_util::str::DOMString; #[deriving(Encodable)] #[must_root] pub struct
{ pub htmlelement: HTMLElement } impl HTMLBodyElementDerived for EventTarget { fn is_htmlbodyelement(&self) -> bool { self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLBodyElementTypeId)) } } impl HTMLBodyElement { pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLBodyElement { HTMLBodyElement { htmlelement: HTMLElement::new_inherited(HTMLBodyElementTypeId, localName, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLBodyElement> { let element = HTMLBodyElement::new_inherited(localName, document); Node::reflect_node(box element, document, HTMLBodyElementBinding::Wrap) } } impl<'a> HTMLBodyElementMethods for JSRef<'a, HTMLBodyElement> { fn GetOnunload(self) -> Option<EventHandlerNonNull> { let win = window_from_node(self).root(); win.deref().GetOnunload() } fn SetOnunload(self, listener: Option<EventHandlerNonNull>) { let win = window_from_node(self).root(); win.deref().SetOnunload(listener) } } impl<'a> VirtualMethods for JSRef<'a, HTMLBodyElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let element: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(element as &VirtualMethods) } fn after_set_attr(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.after_set_attr(name, value.clone()), _ => (), } if name.as_slice().starts_with("on") { static forwarded_events: &'static [&'static str] = &["onfocus", "onload", "onscroll", "onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onstorage", "onresize", "onunload", "onerror"]; let window = window_from_node(*self).root(); let (cx, url, reflector) = (window.get_cx(), window.get_url(), window.reflector().get_jsobject()); let evtarget: JSRef<EventTarget> = if forwarded_events.iter().any(|&event| name.as_slice() == event) { EventTargetCast::from_ref(*window) } else { EventTargetCast::from_ref(*self) }; evtarget.set_event_handler_uncompiled(cx, url, reflector, name.as_slice().slice_from(2), value); } } } impl Reflectable for HTMLBodyElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
HTMLBodyElement
identifier_name
htmlbodyelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::InheritTypes::EventTargetCast; use dom::bindings::codegen::InheritTypes::{HTMLBodyElementDerived, HTMLElementCast}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::HTMLBodyElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId, EventTargetHelpers}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId, window_from_node}; use dom::virtualmethods::VirtualMethods; use servo_util::atom::Atom; use servo_util::str::DOMString; #[deriving(Encodable)] #[must_root] pub struct HTMLBodyElement { pub htmlelement: HTMLElement } impl HTMLBodyElementDerived for EventTarget { fn is_htmlbodyelement(&self) -> bool { self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLBodyElementTypeId)) } } impl HTMLBodyElement { pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLBodyElement { HTMLBodyElement { htmlelement: HTMLElement::new_inherited(HTMLBodyElementTypeId, localName, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLBodyElement> { let element = HTMLBodyElement::new_inherited(localName, document); Node::reflect_node(box element, document, HTMLBodyElementBinding::Wrap) } } impl<'a> HTMLBodyElementMethods for JSRef<'a, HTMLBodyElement> { fn GetOnunload(self) -> Option<EventHandlerNonNull> { let win = window_from_node(self).root(); win.deref().GetOnunload() } fn SetOnunload(self, listener: Option<EventHandlerNonNull>) { let win = window_from_node(self).root(); win.deref().SetOnunload(listener) } } impl<'a> VirtualMethods for JSRef<'a, HTMLBodyElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let element: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(element as &VirtualMethods) } fn after_set_attr(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.after_set_attr(name, value.clone()), _ => (), } if name.as_slice().starts_with("on") { static forwarded_events: &'static [&'static str] = &["onfocus", "onload", "onscroll", "onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onstorage", "onresize", "onunload", "onerror"]; let window = window_from_node(*self).root(); let (cx, url, reflector) = (window.get_cx(), window.get_url(), window.reflector().get_jsobject()); let evtarget: JSRef<EventTarget> = if forwarded_events.iter().any(|&event| name.as_slice() == event) { EventTargetCast::from_ref(*window) } else { EventTargetCast::from_ref(*self) }; evtarget.set_event_handler_uncompiled(cx, url, reflector, name.as_slice().slice_from(2), value); } } } impl Reflectable for HTMLBodyElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::HTMLBodyElementBinding; use dom::bindings::codegen::Bindings::HTMLBodyElementBinding::HTMLBodyElementMethods;
random_line_split
htmlbodyelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::HTMLBodyElementBinding; use dom::bindings::codegen::Bindings::HTMLBodyElementBinding::HTMLBodyElementMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::InheritTypes::EventTargetCast; use dom::bindings::codegen::InheritTypes::{HTMLBodyElementDerived, HTMLElementCast}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::HTMLBodyElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId, EventTargetHelpers}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId, window_from_node}; use dom::virtualmethods::VirtualMethods; use servo_util::atom::Atom; use servo_util::str::DOMString; #[deriving(Encodable)] #[must_root] pub struct HTMLBodyElement { pub htmlelement: HTMLElement } impl HTMLBodyElementDerived for EventTarget { fn is_htmlbodyelement(&self) -> bool { self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLBodyElementTypeId)) } } impl HTMLBodyElement { pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLBodyElement { HTMLBodyElement { htmlelement: HTMLElement::new_inherited(HTMLBodyElementTypeId, localName, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLBodyElement> { let element = HTMLBodyElement::new_inherited(localName, document); Node::reflect_node(box element, document, HTMLBodyElementBinding::Wrap) } } impl<'a> HTMLBodyElementMethods for JSRef<'a, HTMLBodyElement> { fn GetOnunload(self) -> Option<EventHandlerNonNull> { let win = window_from_node(self).root(); win.deref().GetOnunload() } fn SetOnunload(self, listener: Option<EventHandlerNonNull>) { let win = window_from_node(self).root(); win.deref().SetOnunload(listener) } } impl<'a> VirtualMethods for JSRef<'a, HTMLBodyElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let element: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(element as &VirtualMethods) } fn after_set_attr(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.after_set_attr(name, value.clone()), _ => (), } if name.as_slice().starts_with("on")
} } impl Reflectable for HTMLBodyElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
{ static forwarded_events: &'static [&'static str] = &["onfocus", "onload", "onscroll", "onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onstorage", "onresize", "onunload", "onerror"]; let window = window_from_node(*self).root(); let (cx, url, reflector) = (window.get_cx(), window.get_url(), window.reflector().get_jsobject()); let evtarget: JSRef<EventTarget> = if forwarded_events.iter().any(|&event| name.as_slice() == event) { EventTargetCast::from_ref(*window) } else { EventTargetCast::from_ref(*self) }; evtarget.set_event_handler_uncompiled(cx, url, reflector, name.as_slice().slice_from(2), value); }
conditional_block