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
region.rs
(&self, sub: FreeRegion, sup: FreeRegion) -> bool { can_reach(&*self.free_region_map.borrow(), sub, sup) } /// Determines whether one region is a subregion of another. This is intended to run *after /// inference* and sadly the logic is somewhat duplicated with the code in infer.rs. pub fn is_subregion_of(&self, sub_region: ty::Region, super_region: ty::Region) -> bool { debug!("is_subregion_of(sub_region={}, super_region={})", sub_region, super_region); sub_region == super_region || { match (sub_region, super_region) { (ty::ReEmpty, _) | (_, ty::ReStatic) => { true } (ty::ReScope(sub_scope), ty::ReScope(super_scope)) => { self.is_subscope_of(sub_scope, super_scope) } (ty::ReScope(sub_scope), ty::ReFree(ref fr)) => { self.is_subscope_of(sub_scope, fr.scope) } (ty::ReFree(sub_fr), ty::ReFree(super_fr)) => { self.sub_free_region(sub_fr, super_fr) } (ty::ReEarlyBound(param_id_a, param_space_a, index_a, _), ty::ReEarlyBound(param_id_b, param_space_b, index_b, _)) => { // This case is used only to make sure that explicitly- // specified `Self` types match the real self type in // implementations. param_id_a == param_id_b && param_space_a == param_space_b && index_a == index_b } _ => { false } } } } /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest /// scope which is greater than or equal to both `scope_a` and `scope_b`. pub fn nearest_common_ancestor(&self, scope_a: CodeExtent, scope_b: CodeExtent) -> Option<CodeExtent> { if scope_a == scope_b { return Some(scope_a); } let a_ancestors = ancestors_of(self, scope_a); let b_ancestors = ancestors_of(self, scope_b); let mut a_index = a_ancestors.len() - 1u; let mut b_index = b_ancestors.len() - 1u; // Here, ~[ab]_ancestors is a vector going from narrow to broad. // The end of each vector will be the item where the scope is // defined; if there are any common ancestors, then the tails of // the vector will be the same. So basically we want to walk // backwards from the tail of each vector and find the first point // where they diverge. If one vector is a suffix of the other, // then the corresponding scope is a superscope of the other. if a_ancestors[a_index]!= b_ancestors[b_index] { return None; } loop { // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index] // for all indices between a_index and the end of the array if a_index == 0u { return Some(scope_a); } if b_index == 0u { return Some(scope_b); } a_index -= 1u; b_index -= 1u; if a_ancestors[a_index]!= b_ancestors[b_index] { return Some(a_ancestors[a_index + 1]); } } fn ancestors_of(this: &RegionMaps, scope: CodeExtent) -> Vec<CodeExtent> { // debug!("ancestors_of(scope={})", scope); let mut result = vec!(scope); let mut scope = scope; loop { match this.scope_map.borrow().get(&scope) { None => return result, Some(&superscope) => { result.push(superscope); scope = superscope; } } // debug!("ancestors_of_loop(scope={})", scope); } } } } /// Records the current parent (if any) as the parent of `child_id`. fn record_superlifetime(visitor: &mut RegionResolutionVisitor, child_id: ast::NodeId, _sp: Span) { match visitor.cx.parent { Some(parent_id) => { let child_scope = CodeExtent::from_node_id(child_id); let parent_scope = CodeExtent::from_node_id(parent_id); visitor.region_maps.record_encl_scope(child_scope, parent_scope); } None => {} } } /// Records the lifetime of a local variable as `cx.var_parent` fn record_var_lifetime(visitor: &mut RegionResolutionVisitor, var_id: ast::NodeId, _sp: Span) { match visitor.cx.var_parent { Some(parent_id) => { let parent_scope = CodeExtent::from_node_id(parent_id); visitor.region_maps.record_var_scope(var_id, parent_scope); } None => { // this can happen in extern fn declarations like // // extern fn isalnum(c: c_int) -> c_int } } } fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) { debug!("resolve_block(blk.id={})", blk.id); // Record the parent of this block. record_superlifetime(visitor, blk.id, blk.span); // We treat the tail expression in the block (if any) somewhat // differently from the statements. The issue has to do with // temporary lifetimes. If the user writes: // // { // ... (&foo())... // } // let prev_cx = visitor.cx; visitor.cx = Context {var_parent: Some(blk.id), parent: Some(blk.id)}; visit::walk_block(visitor, blk); visitor.cx = prev_cx; } fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &ast::Arm) { let arm_body_scope = CodeExtent::from_node_id(arm.body.id); visitor.region_maps.mark_as_terminating_scope(arm_body_scope); match arm.guard { Some(ref expr) => { let guard_scope = CodeExtent::from_node_id(expr.id); visitor.region_maps.mark_as_terminating_scope(guard_scope); } None => { } } visit::walk_arm(visitor, arm); } fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &ast::Pat) { record_superlifetime(visitor, pat.id, pat.span); // If this is a binding (or maybe a binding, I'm too lazy to check // the def map) then record the lifetime of that binding. match pat.node { ast::PatIdent(..) => { record_var_lifetime(visitor, pat.id, pat.span); } _ => { } } visit::walk_pat(visitor, pat); } fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &ast::Stmt) { let stmt_id = stmt_id(stmt); debug!("resolve_stmt(stmt.id={})", stmt_id); let stmt_scope = CodeExtent::from_node_id(stmt_id); visitor.region_maps.mark_as_terminating_scope(stmt_scope); record_superlifetime(visitor, stmt_id, stmt.span); let prev_parent = visitor.cx.parent; visitor.cx.parent = Some(stmt_id); visit::walk_stmt(visitor, stmt); visitor.cx.parent = prev_parent; } fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) { debug!("resolve_expr(expr.id={})", expr.id); record_superlifetime(visitor, expr.id, expr.span); let prev_cx = visitor.cx; visitor.cx.parent = Some(expr.id); { let region_maps = &mut visitor.region_maps; let terminating = |id| { let scope = CodeExtent::from_node_id(id); region_maps.mark_as_terminating_scope(scope) }; match expr.node { // Conditional or repeating scopes are always terminating // scopes, meaning that temporaries cannot outlive them. // This ensures fixed size stacks. ast::ExprBinary(ast::BiAnd, _, ref r) | ast::ExprBinary(ast::BiOr, _, ref r) => { // For shortcircuiting operators, mark the RHS as a terminating // scope since it only executes conditionally. terminating(r.id); } ast::ExprIf(_, ref then, Some(ref otherwise)) => { terminating(then.id); terminating(otherwise.id); } ast::ExprIf(ref expr, ref then, None) => { terminating(expr.id); terminating(then.id); } ast::ExprLoop(ref body, _) => { terminating(body.id); } ast::ExprWhile(ref expr, ref body, _) => { terminating(expr.id); terminating(body.id); } ast::ExprForLoop(ref _pat, ref _head, ref body, _) => { terminating(body.id); // The variable parent of everything inside (most importantly, the // pattern) is the body. visitor.cx.var_parent = Some(body.id); } ast::ExprMatch(..) => { visitor.cx.var_parent = Some(expr.id); } ast::ExprAssignOp(..) | ast::ExprIndex(..) | ast::ExprUnary(..) | ast::ExprCall(..) | ast::ExprMethodCall(..) => { // FIXME(#6268) Nested method calls // // The lifetimes for a call or method call look as follows: // // call.id // - arg0.id // -... // - argN.id // - call.callee_id // // The idea is that call.callee_id represents *the time when // the invoked function is actually running* and call.id // represents *the time to prepare the arguments and make the // call*. See the section "Borrows in Calls" borrowck/doc.rs // for an extended explanation of why this distinction is // important. // // record_superlifetime(new_cx, expr.callee_id); } _ => {} } } visit::walk_expr(visitor, expr); visitor.cx = prev_cx; } fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) { debug!("resolve_local(local.id={},local.init={})", local.id,local.init.is_some()); let blk_id = match visitor.cx.var_parent { Some(id) => id, None => { visitor.sess.span_bug( local.span, "local without enclosing block"); } }; // For convenience in trans, associate with the local-id the var // scope that will be used for any bindings declared in this // pattern. let blk_scope = CodeExtent::from_node_id(blk_id); visitor.region_maps.record_var_scope(local.id, blk_scope); // As an exception to the normal rules governing temporary // lifetimes, initializers in a let have a temporary lifetime // of the enclosing block. This means that e.g. a program // like the following is legal: // // let ref x = HashMap::new(); // // Because the hash map will be freed in the enclosing block. // // We express the rules more formally based on 3 grammars (defined // fully in the helpers below that implement them): // // 1. `E&`, which matches expressions like `&<rvalue>` that // own a pointer into the stack. // // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref // y)` that produce ref bindings into the value they are // matched against or something (at least partially) owned by // the value they are matched against. (By partially owned, // I mean that creating a binding into a ref-counted or managed value // would still count.) // // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues // based on rvalues like `foo().x[2].y`. // // A subexpression `<rvalue>` that appears in a let initializer // `let pat [: ty] = expr` has an extended temporary lifetime if // any of the following conditions are met: // // A. `pat` matches `P&` and `expr` matches `ET` // (covers cases where `pat` creates ref bindings into an rvalue // produced by `expr`) // B. `ty` is a borrowed pointer and `expr` matches `ET` // (covers cases where coercion creates a borrow) // C. `expr` matches `E&` // (covers cases `expr` borrows an rvalue that is then assigned // to memory (at least partially) owned by the binding) // // Here are some examples hopefully giving an intuition where each // rule comes into play and why: // // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)` // would have an extended lifetime, but not `foo()`. // // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]` // would have an extended lifetime, but not `foo()`. // // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended // lifetime. // // In some cases, multiple rules may apply (though not to the same // rvalue). For example: // // let ref x = [&a(), &b()]; // // Here, the expression `[...]` has an extended lifetime due to rule // A, but the inner rvalues `a()` and `b()` have an extended lifetime // due to rule C. // // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST. match local.init { Some(ref expr) => { record_rvalue_scope_if_borrow_expr(visitor, &**expr, blk_scope); if is_binding_pat(&*local.pat) || is_borrowed_ty(&*local.ty) { record_rvalue_scope(visitor, &**expr, blk_scope); } } None => { } } visit::walk_local(visitor, local); /// True if `pat` match the `P&` nonterminal: /// /// P& = ref X /// | StructName {..., P&,... } /// | VariantName(..., P&,...) /// | [..., P&,... ] /// | (..., P&,... ) /// | box P& fn is_binding_pat(pat: &ast::Pat) -> bool { match pat.node { ast::PatIdent(ast::BindByRef(_), _, _) => true, ast::PatStruct(_, ref field_pats, _) => { field_pats.iter().any(|fp| is_binding_pat(&*fp.node.pat)) } ast::PatVec(ref pats1, ref pats2, ref pats3) => { pats1.iter().any(|p| is_binding_pat(&**p)) || pats2.iter().any(|p| is_binding_pat(&**p)) || pats3.iter().any(|p| is_binding_pat(&**p)) } ast::PatEnum(_, Some(ref subpats)) | ast::PatTup(ref subpats) => { subpats.iter().any(|p| is_binding_pat(&**p)) } ast::PatBox(ref subpat) => { is_binding_pat(&**subpat) } _ => false, } } /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`. fn is_borrowed_ty(ty: &ast::Ty) -> bool { match ty.node { ast::TyRptr(..) => true, _ => false } } /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate: /// /// E& = & ET /// | StructName {..., f: E&,... } /// | [..., E&,... ] /// | (..., E&,... ) /// | {...; E&} /// | box E& /// | E& as... /// | ( E& ) fn record_rvalue_scope_if_borrow_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr, blk_id: CodeExtent) { match expr.node { ast::ExprAddrOf(_, ref subexpr) => { record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id); record_rvalue_scope(visitor, &**subexpr, blk_id); } ast::ExprStruct(_, ref fields, _) => { for field in fields.iter() { record_rvalue_scope_if_borrow_expr( visitor, &*field.expr, blk_id); } } ast::ExprVec(ref subexprs) | ast::ExprTup(ref subexprs) => { for subexpr in subexprs.iter() { record_rvalue_scope_if_borrow_expr( visitor, &**subexpr, blk_id); } } ast::ExprUnary(ast::UnUniq, ref subexpr) => { record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id); } ast::ExprCast(ref subexpr, _) | ast::ExprParen(ref subexpr) => { record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id) } ast::ExprBlock(ref block) => { match block.expr { Some(ref subexpr) => { record_rvalue_scope_if_borrow_expr( visitor, &**subexpr, blk_id); } None =>
{ }
conditional_block
region.rs
_id()); self.var_map.borrow_mut().insert(var, lifetime); } pub fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) { debug!("record_rvalue_scope(sub={}, sup={})", var, lifetime); assert!(var!= lifetime.node_id()); self.rvalue_scopes.borrow_mut().insert(var, lifetime); } /// Records that a scope is a TERMINATING SCOPE. Whenever we create automatic temporaries -- /// e.g. by an expression like `a().f` -- they will be freed within the innermost terminating /// scope. pub fn mark_as_terminating_scope(&self, scope_id: CodeExtent) { debug!("record_terminating_scope(scope_id={})", scope_id); self.terminating_scopes.borrow_mut().insert(scope_id); } pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> { //! Returns the narrowest scope that encloses `id`, if any. self.scope_map.borrow().get(&id).map(|x| *x) } #[allow(dead_code)] // used in middle::cfg pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent { //! Returns the narrowest scope that encloses `id`, if any. match self.scope_map.borrow().get(&id) { Some(&r) => r, None => { panic!("no enclosing scope for id {}", id); } } } /// Returns the lifetime of the local variable `var_id` pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent { match self.var_map.borrow().get(&var_id) { Some(&r) => r, None => { panic!("no enclosing scope for id {}", var_id); } } } pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> { //! Returns the scope when temp created by expr_id will be cleaned up // check for a designated rvalue scope match self.rvalue_scopes.borrow().get(&expr_id) { Some(&s) => { debug!("temporary_scope({}) = {} [custom]", expr_id, s); return Some(s); } None => { } } // else, locate the innermost terminating scope // if there's one. Static items, for instance, won't // have an enclosing scope, hence no scope will be // returned. let mut id = match self.opt_encl_scope(CodeExtent::from_node_id(expr_id)) { Some(i) => i, None => { return None; } }; while!self.terminating_scopes.borrow().contains(&id) { match self.opt_encl_scope(id) { Some(p) => { id = p; } None => { debug!("temporary_scope({}) = None", expr_id); return None; } } } debug!("temporary_scope({}) = {} [enclosing]", expr_id, id); return Some(id); } pub fn var_region(&self, id: ast::NodeId) -> ty::Region { //! Returns the lifetime of the variable `id`. let scope = ty::ReScope(self.var_scope(id)); debug!("var_region({}) = {}", id, scope); scope } pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent) -> bool
/// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false /// otherwise. pub fn is_subscope_of(&self, subscope: CodeExtent, superscope: CodeExtent) -> bool { let mut s = subscope; while superscope!= s { match self.scope_map.borrow().get(&s) { None => { debug!("is_subscope_of({}, {}, s={})=false", subscope, superscope, s); return false; } Some(&scope) => s = scope } } debug!("is_subscope_of({}, {})=true", subscope, superscope); return true; } /// Determines whether two free regions have a subregion relationship /// by walking the graph encoded in `free_region_map`. Note that /// it is possible that `sub!= sup` and `sub <= sup` and `sup <= sub` /// (that is, the user can give two different names to the same lifetime). pub fn sub_free_region(&self, sub: FreeRegion, sup: FreeRegion) -> bool { can_reach(&*self.free_region_map.borrow(), sub, sup) } /// Determines whether one region is a subregion of another. This is intended to run *after /// inference* and sadly the logic is somewhat duplicated with the code in infer.rs. pub fn is_subregion_of(&self, sub_region: ty::Region, super_region: ty::Region) -> bool { debug!("is_subregion_of(sub_region={}, super_region={})", sub_region, super_region); sub_region == super_region || { match (sub_region, super_region) { (ty::ReEmpty, _) | (_, ty::ReStatic) => { true } (ty::ReScope(sub_scope), ty::ReScope(super_scope)) => { self.is_subscope_of(sub_scope, super_scope) } (ty::ReScope(sub_scope), ty::ReFree(ref fr)) => { self.is_subscope_of(sub_scope, fr.scope) } (ty::ReFree(sub_fr), ty::ReFree(super_fr)) => { self.sub_free_region(sub_fr, super_fr) } (ty::ReEarlyBound(param_id_a, param_space_a, index_a, _), ty::ReEarlyBound(param_id_b, param_space_b, index_b, _)) => { // This case is used only to make sure that explicitly- // specified `Self` types match the real self type in // implementations. param_id_a == param_id_b && param_space_a == param_space_b && index_a == index_b } _ => { false } } } } /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest /// scope which is greater than or equal to both `scope_a` and `scope_b`. pub fn nearest_common_ancestor(&self, scope_a: CodeExtent, scope_b: CodeExtent) -> Option<CodeExtent> { if scope_a == scope_b { return Some(scope_a); } let a_ancestors = ancestors_of(self, scope_a); let b_ancestors = ancestors_of(self, scope_b); let mut a_index = a_ancestors.len() - 1u; let mut b_index = b_ancestors.len() - 1u; // Here, ~[ab]_ancestors is a vector going from narrow to broad. // The end of each vector will be the item where the scope is // defined; if there are any common ancestors, then the tails of // the vector will be the same. So basically we want to walk // backwards from the tail of each vector and find the first point // where they diverge. If one vector is a suffix of the other, // then the corresponding scope is a superscope of the other. if a_ancestors[a_index]!= b_ancestors[b_index] { return None; } loop { // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index] // for all indices between a_index and the end of the array if a_index == 0u { return Some(scope_a); } if b_index == 0u { return Some(scope_b); } a_index -= 1u; b_index -= 1u; if a_ancestors[a_index]!= b_ancestors[b_index] { return Some(a_ancestors[a_index + 1]); } } fn ancestors_of(this: &RegionMaps, scope: CodeExtent) -> Vec<CodeExtent> { // debug!("ancestors_of(scope={})", scope); let mut result = vec!(scope); let mut scope = scope; loop { match this.scope_map.borrow().get(&scope) { None => return result, Some(&superscope) => { result.push(superscope); scope = superscope; } } // debug!("ancestors_of_loop(scope={})", scope); } } } } /// Records the current parent (if any) as the parent of `child_id`. fn record_superlifetime(visitor: &mut RegionResolutionVisitor, child_id: ast::NodeId, _sp: Span) { match visitor.cx.parent { Some(parent_id) => { let child_scope = CodeExtent::from_node_id(child_id); let parent_scope = CodeExtent::from_node_id(parent_id); visitor.region_maps.record_encl_scope(child_scope, parent_scope); } None => {} } } /// Records the lifetime of a local variable as `cx.var_parent` fn record_var_lifetime(visitor: &mut RegionResolutionVisitor, var_id: ast::NodeId, _sp: Span) { match visitor.cx.var_parent { Some(parent_id) => { let parent_scope = CodeExtent::from_node_id(parent_id); visitor.region_maps.record_var_scope(var_id, parent_scope); } None => { // this can happen in extern fn declarations like // // extern fn isalnum(c: c_int) -> c_int } } } fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) { debug!("resolve_block(blk.id={})", blk.id); // Record the parent of this block. record_superlifetime(visitor, blk.id, blk.span); // We treat the tail expression in the block (if any) somewhat // differently from the statements. The issue has to do with // temporary lifetimes. If the user writes: // // { // ... (&foo())... // } // let prev_cx = visitor.cx; visitor.cx = Context {var_parent: Some(blk.id), parent: Some(blk.id)}; visit::walk_block(visitor, blk); visitor.cx = prev_cx; } fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &ast::Arm) { let arm_body_scope = CodeExtent::from_node_id(arm.body.id); visitor.region_maps.mark_as_terminating_scope(arm_body_scope); match arm.guard { Some(ref expr) => { let guard_scope = CodeExtent::from_node_id(expr.id); visitor.region_maps.mark_as_terminating_scope(guard_scope); } None => { } } visit::walk_arm(visitor, arm); } fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &ast::Pat) { record_superlifetime(visitor, pat.id, pat.span); // If this is a binding (or maybe a binding, I'm too lazy to check // the def map) then record the lifetime of that binding. match pat.node { ast::PatIdent(..) => { record_var_lifetime(visitor, pat.id, pat.span); } _ => { } } visit::walk_pat(visitor, pat); } fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &ast::Stmt) { let stmt_id = stmt_id(stmt); debug!("resolve_stmt(stmt.id={})", stmt_id); let stmt_scope = CodeExtent::from_node_id(stmt_id); visitor.region_maps.mark_as_terminating_scope(stmt_scope); record_superlifetime(visitor, stmt_id, stmt.span); let prev_parent = visitor.cx.parent; visitor.cx.parent = Some(stmt_id); visit::walk_stmt(visitor, stmt); visitor.cx.parent = prev_parent; } fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) { debug!("resolve_expr(expr.id={})", expr.id); record_superlifetime(visitor, expr.id, expr.span); let prev_cx = visitor.cx; visitor.cx.parent = Some(expr.id); { let region_maps = &mut visitor.region_maps; let terminating = |id| { let scope = CodeExtent::from_node_id(id); region_maps.mark_as_terminating_scope(scope) }; match expr.node { // Conditional or repeating scopes are always terminating // scopes, meaning that temporaries cannot outlive them. // This ensures fixed size stacks. ast::ExprBinary(ast::BiAnd, _, ref r) | ast::ExprBinary(ast::BiOr, _, ref r) => { // For shortcircuiting operators, mark the RHS as a terminating // scope since it only executes conditionally. terminating(r.id); } ast::ExprIf(_, ref then, Some(ref otherwise)) => { terminating(then.id); terminating(otherwise.id); } ast::ExprIf(ref expr, ref then, None) => { terminating(expr.id); terminating(then.id); } ast::ExprLoop(ref body, _) => { terminating(body.id); } ast::ExprWhile(ref expr, ref body, _) => { terminating(expr.id); terminating(body.id); } ast::ExprForLoop(ref _pat, ref _head, ref body, _) => { terminating(body.id); // The variable parent of everything inside (most importantly, the // pattern) is the body. visitor.cx.var_parent = Some(body.id); } ast::ExprMatch(..) => { visitor.cx.var_parent = Some(expr.id); } ast::ExprAssignOp(..) | ast::ExprIndex(..) | ast::ExprUnary(..) | ast::ExprCall(..) | ast::ExprMethodCall(..) => { // FIXME(#6268) Nested method calls // // The lifetimes for a call or method call look as follows: // // call.id // - arg0.id // -... // - argN.id // - call.callee_id // // The idea is that call.callee_id represents *the time when // the invoked function is actually running* and call.id // represents *the time to prepare the arguments and make the // call*. See the section "Borrows in Calls" borrowck/doc.rs // for an extended explanation of why this distinction is // important. // // record_superlifetime(new_cx, expr.callee_id); } _ => {} } } visit::walk_expr(visitor, expr); visitor.cx = prev_cx; } fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) { debug!("resolve_local(local.id={},local.init={})", local.id,local.init.is_some()); let blk_id = match visitor.cx.var_parent { Some(id) => id, None => { visitor.sess.span_bug( local.span, "local without enclosing block"); } }; // For convenience in trans, associate with the local-id the var // scope that will be used for any bindings declared in this // pattern. let blk_scope = CodeExtent::from_node_id(blk_id); visitor.region_maps.record_var_scope(local.id, blk_scope); // As an exception to the normal rules governing temporary // lifetimes, initializers in a let have a temporary lifetime // of the enclosing block. This means that e.g. a program // like the following is legal: // // let ref x = HashMap::new(); // // Because the hash map will be freed in the enclosing block. // // We express the rules more formally based on 3 grammars (defined // fully in the helpers below that implement them): // // 1. `E&`, which matches expressions like `&<rvalue>` that // own a pointer into the stack. // // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref // y)` that produce ref bindings into the value they are // matched against or something (at least partially) owned by // the value they are matched against. (By partially owned, // I mean that creating a binding into a ref-counted or managed value // would still count.) // // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues // based on rvalues like `foo().x[2].y`. // // A subexpression `<rvalue>` that appears in a let initializer // `let pat [: ty] = expr` has an extended temporary lifetime if // any of the following conditions are met: // // A. `pat` matches `P&` and `expr` matches `ET` // (covers cases where `pat` creates ref bindings into an rvalue // produced by `expr`) // B. `ty` is a borrowed pointer and `expr` matches `ET` // (covers cases where coercion creates a borrow) // C. `expr` matches `E&` // (covers cases `expr` borrows an rvalue that is then assigned // to memory (at least partially) owned by the binding) // // Here are some examples hopefully giving an intuition where each // rule comes into play and why: // // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)` // would have an extended lifetime, but not `foo()`. // // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]` // would have an extended lifetime, but not `foo()`. // // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended // lifetime. // // In some cases, multiple rules may apply (though not to the same // rvalue). For example: // // let ref x = [&a(), &b()]; // // Here, the expression `[...]` has an extended lifetime due to rule // A, but the inner rvalues `a()` and `b()` have an extended lifetime // due to rule C. // // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST. match local.init { Some(ref expr) => {
{ self.is_subscope_of(scope1, scope2) || self.is_subscope_of(scope2, scope1) }
identifier_body
region.rs
node_id()); self.var_map.borrow_mut().insert(var, lifetime); } pub fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) { debug!("record_rvalue_scope(sub={}, sup={})", var, lifetime); assert!(var!= lifetime.node_id()); self.rvalue_scopes.borrow_mut().insert(var, lifetime); } /// Records that a scope is a TERMINATING SCOPE. Whenever we create automatic temporaries -- /// e.g. by an expression like `a().f` -- they will be freed within the innermost terminating /// scope. pub fn mark_as_terminating_scope(&self, scope_id: CodeExtent) { debug!("record_terminating_scope(scope_id={})", scope_id); self.terminating_scopes.borrow_mut().insert(scope_id); } pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> { //! Returns the narrowest scope that encloses `id`, if any. self.scope_map.borrow().get(&id).map(|x| *x) } #[allow(dead_code)] // used in middle::cfg pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent { //! Returns the narrowest scope that encloses `id`, if any. match self.scope_map.borrow().get(&id) { Some(&r) => r, None => { panic!("no enclosing scope for id {}", id); } } } /// Returns the lifetime of the local variable `var_id` pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent { match self.var_map.borrow().get(&var_id) { Some(&r) => r, None => { panic!("no enclosing scope for id {}", var_id); } } } pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> { //! Returns the scope when temp created by expr_id will be cleaned up // check for a designated rvalue scope match self.rvalue_scopes.borrow().get(&expr_id) { Some(&s) => { debug!("temporary_scope({}) = {} [custom]", expr_id, s); return Some(s); } None => { } } // else, locate the innermost terminating scope // if there's one. Static items, for instance, won't // have an enclosing scope, hence no scope will be // returned. let mut id = match self.opt_encl_scope(CodeExtent::from_node_id(expr_id)) { Some(i) => i, None => { return None; } }; while!self.terminating_scopes.borrow().contains(&id) { match self.opt_encl_scope(id) { Some(p) => { id = p; } None => { debug!("temporary_scope({}) = None", expr_id); return None; } } } debug!("temporary_scope({}) = {} [enclosing]", expr_id, id); return Some(id); } pub fn var_region(&self, id: ast::NodeId) -> ty::Region { //! Returns the lifetime of the variable `id`.
pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent) -> bool { self.is_subscope_of(scope1, scope2) || self.is_subscope_of(scope2, scope1) } /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false /// otherwise. pub fn is_subscope_of(&self, subscope: CodeExtent, superscope: CodeExtent) -> bool { let mut s = subscope; while superscope!= s { match self.scope_map.borrow().get(&s) { None => { debug!("is_subscope_of({}, {}, s={})=false", subscope, superscope, s); return false; } Some(&scope) => s = scope } } debug!("is_subscope_of({}, {})=true", subscope, superscope); return true; } /// Determines whether two free regions have a subregion relationship /// by walking the graph encoded in `free_region_map`. Note that /// it is possible that `sub!= sup` and `sub <= sup` and `sup <= sub` /// (that is, the user can give two different names to the same lifetime). pub fn sub_free_region(&self, sub: FreeRegion, sup: FreeRegion) -> bool { can_reach(&*self.free_region_map.borrow(), sub, sup) } /// Determines whether one region is a subregion of another. This is intended to run *after /// inference* and sadly the logic is somewhat duplicated with the code in infer.rs. pub fn is_subregion_of(&self, sub_region: ty::Region, super_region: ty::Region) -> bool { debug!("is_subregion_of(sub_region={}, super_region={})", sub_region, super_region); sub_region == super_region || { match (sub_region, super_region) { (ty::ReEmpty, _) | (_, ty::ReStatic) => { true } (ty::ReScope(sub_scope), ty::ReScope(super_scope)) => { self.is_subscope_of(sub_scope, super_scope) } (ty::ReScope(sub_scope), ty::ReFree(ref fr)) => { self.is_subscope_of(sub_scope, fr.scope) } (ty::ReFree(sub_fr), ty::ReFree(super_fr)) => { self.sub_free_region(sub_fr, super_fr) } (ty::ReEarlyBound(param_id_a, param_space_a, index_a, _), ty::ReEarlyBound(param_id_b, param_space_b, index_b, _)) => { // This case is used only to make sure that explicitly- // specified `Self` types match the real self type in // implementations. param_id_a == param_id_b && param_space_a == param_space_b && index_a == index_b } _ => { false } } } } /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest /// scope which is greater than or equal to both `scope_a` and `scope_b`. pub fn nearest_common_ancestor(&self, scope_a: CodeExtent, scope_b: CodeExtent) -> Option<CodeExtent> { if scope_a == scope_b { return Some(scope_a); } let a_ancestors = ancestors_of(self, scope_a); let b_ancestors = ancestors_of(self, scope_b); let mut a_index = a_ancestors.len() - 1u; let mut b_index = b_ancestors.len() - 1u; // Here, ~[ab]_ancestors is a vector going from narrow to broad. // The end of each vector will be the item where the scope is // defined; if there are any common ancestors, then the tails of // the vector will be the same. So basically we want to walk // backwards from the tail of each vector and find the first point // where they diverge. If one vector is a suffix of the other, // then the corresponding scope is a superscope of the other. if a_ancestors[a_index]!= b_ancestors[b_index] { return None; } loop { // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index] // for all indices between a_index and the end of the array if a_index == 0u { return Some(scope_a); } if b_index == 0u { return Some(scope_b); } a_index -= 1u; b_index -= 1u; if a_ancestors[a_index]!= b_ancestors[b_index] { return Some(a_ancestors[a_index + 1]); } } fn ancestors_of(this: &RegionMaps, scope: CodeExtent) -> Vec<CodeExtent> { // debug!("ancestors_of(scope={})", scope); let mut result = vec!(scope); let mut scope = scope; loop { match this.scope_map.borrow().get(&scope) { None => return result, Some(&superscope) => { result.push(superscope); scope = superscope; } } // debug!("ancestors_of_loop(scope={})", scope); } } } } /// Records the current parent (if any) as the parent of `child_id`. fn record_superlifetime(visitor: &mut RegionResolutionVisitor, child_id: ast::NodeId, _sp: Span) { match visitor.cx.parent { Some(parent_id) => { let child_scope = CodeExtent::from_node_id(child_id); let parent_scope = CodeExtent::from_node_id(parent_id); visitor.region_maps.record_encl_scope(child_scope, parent_scope); } None => {} } } /// Records the lifetime of a local variable as `cx.var_parent` fn record_var_lifetime(visitor: &mut RegionResolutionVisitor, var_id: ast::NodeId, _sp: Span) { match visitor.cx.var_parent { Some(parent_id) => { let parent_scope = CodeExtent::from_node_id(parent_id); visitor.region_maps.record_var_scope(var_id, parent_scope); } None => { // this can happen in extern fn declarations like // // extern fn isalnum(c: c_int) -> c_int } } } fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) { debug!("resolve_block(blk.id={})", blk.id); // Record the parent of this block. record_superlifetime(visitor, blk.id, blk.span); // We treat the tail expression in the block (if any) somewhat // differently from the statements. The issue has to do with // temporary lifetimes. If the user writes: // // { // ... (&foo())... // } // let prev_cx = visitor.cx; visitor.cx = Context {var_parent: Some(blk.id), parent: Some(blk.id)}; visit::walk_block(visitor, blk); visitor.cx = prev_cx; } fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &ast::Arm) { let arm_body_scope = CodeExtent::from_node_id(arm.body.id); visitor.region_maps.mark_as_terminating_scope(arm_body_scope); match arm.guard { Some(ref expr) => { let guard_scope = CodeExtent::from_node_id(expr.id); visitor.region_maps.mark_as_terminating_scope(guard_scope); } None => { } } visit::walk_arm(visitor, arm); } fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &ast::Pat) { record_superlifetime(visitor, pat.id, pat.span); // If this is a binding (or maybe a binding, I'm too lazy to check // the def map) then record the lifetime of that binding. match pat.node { ast::PatIdent(..) => { record_var_lifetime(visitor, pat.id, pat.span); } _ => { } } visit::walk_pat(visitor, pat); } fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &ast::Stmt) { let stmt_id = stmt_id(stmt); debug!("resolve_stmt(stmt.id={})", stmt_id); let stmt_scope = CodeExtent::from_node_id(stmt_id); visitor.region_maps.mark_as_terminating_scope(stmt_scope); record_superlifetime(visitor, stmt_id, stmt.span); let prev_parent = visitor.cx.parent; visitor.cx.parent = Some(stmt_id); visit::walk_stmt(visitor, stmt); visitor.cx.parent = prev_parent; } fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) { debug!("resolve_expr(expr.id={})", expr.id); record_superlifetime(visitor, expr.id, expr.span); let prev_cx = visitor.cx; visitor.cx.parent = Some(expr.id); { let region_maps = &mut visitor.region_maps; let terminating = |id| { let scope = CodeExtent::from_node_id(id); region_maps.mark_as_terminating_scope(scope) }; match expr.node { // Conditional or repeating scopes are always terminating // scopes, meaning that temporaries cannot outlive them. // This ensures fixed size stacks. ast::ExprBinary(ast::BiAnd, _, ref r) | ast::ExprBinary(ast::BiOr, _, ref r) => { // For shortcircuiting operators, mark the RHS as a terminating // scope since it only executes conditionally. terminating(r.id); } ast::ExprIf(_, ref then, Some(ref otherwise)) => { terminating(then.id); terminating(otherwise.id); } ast::ExprIf(ref expr, ref then, None) => { terminating(expr.id); terminating(then.id); } ast::ExprLoop(ref body, _) => { terminating(body.id); } ast::ExprWhile(ref expr, ref body, _) => { terminating(expr.id); terminating(body.id); } ast::ExprForLoop(ref _pat, ref _head, ref body, _) => { terminating(body.id); // The variable parent of everything inside (most importantly, the // pattern) is the body. visitor.cx.var_parent = Some(body.id); } ast::ExprMatch(..) => { visitor.cx.var_parent = Some(expr.id); } ast::ExprAssignOp(..) | ast::ExprIndex(..) | ast::ExprUnary(..) | ast::ExprCall(..) | ast::ExprMethodCall(..) => { // FIXME(#6268) Nested method calls // // The lifetimes for a call or method call look as follows: // // call.id // - arg0.id // -... // - argN.id // - call.callee_id // // The idea is that call.callee_id represents *the time when // the invoked function is actually running* and call.id // represents *the time to prepare the arguments and make the // call*. See the section "Borrows in Calls" borrowck/doc.rs // for an extended explanation of why this distinction is // important. // // record_superlifetime(new_cx, expr.callee_id); } _ => {} } } visit::walk_expr(visitor, expr); visitor.cx = prev_cx; } fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) { debug!("resolve_local(local.id={},local.init={})", local.id,local.init.is_some()); let blk_id = match visitor.cx.var_parent { Some(id) => id, None => { visitor.sess.span_bug( local.span, "local without enclosing block"); } }; // For convenience in trans, associate with the local-id the var // scope that will be used for any bindings declared in this // pattern. let blk_scope = CodeExtent::from_node_id(blk_id); visitor.region_maps.record_var_scope(local.id, blk_scope); // As an exception to the normal rules governing temporary // lifetimes, initializers in a let have a temporary lifetime // of the enclosing block. This means that e.g. a program // like the following is legal: // // let ref x = HashMap::new(); // // Because the hash map will be freed in the enclosing block. // // We express the rules more formally based on 3 grammars (defined // fully in the helpers below that implement them): // // 1. `E&`, which matches expressions like `&<rvalue>` that // own a pointer into the stack. // // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref // y)` that produce ref bindings into the value they are // matched against or something (at least partially) owned by // the value they are matched against. (By partially owned, // I mean that creating a binding into a ref-counted or managed value // would still count.) // // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues // based on rvalues like `foo().x[2].y`. // // A subexpression `<rvalue>` that appears in a let initializer // `let pat [: ty] = expr` has an extended temporary lifetime if // any of the following conditions are met: // // A. `pat` matches `P&` and `expr` matches `ET` // (covers cases where `pat` creates ref bindings into an rvalue // produced by `expr`) // B. `ty` is a borrowed pointer and `expr` matches `ET` // (covers cases where coercion creates a borrow) // C. `expr` matches `E&` // (covers cases `expr` borrows an rvalue that is then assigned // to memory (at least partially) owned by the binding) // // Here are some examples hopefully giving an intuition where each // rule comes into play and why: // // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)` // would have an extended lifetime, but not `foo()`. // // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]` // would have an extended lifetime, but not `foo()`. // // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended // lifetime. // // In some cases, multiple rules may apply (though not to the same // rvalue). For example: // // let ref x = [&a(), &b()]; // // Here, the expression `[...]` has an extended lifetime due to rule // A, but the inner rvalues `a()` and `b()` have an extended lifetime // due to rule C. // // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST. match local.init { Some(ref expr) => {
let scope = ty::ReScope(self.var_scope(id)); debug!("var_region({}) = {}", id, scope); scope }
random_line_split
main.rs
extern crate clap; // Time Start: Mon, 02 Dec 2019 12:59:41 -0500 // Time Finish 1: Mon, 02 Dec 2019 14:46:54 -0500 (1 hour, 47 minutes, 13 seconds) // Time Finish 2: Mon, 02 Dec 2019 14:53:56 -0500 (7 minutes, 2 seconds) // Time Total: 1 hour, 54 minutes, 15 seconds use std::convert::TryFrom; use std::fmt; use std::fs; use clap::{Arg, App}; struct Intcode { program: Vec<i32>, pos: usize, } impl Intcode { fn new() -> Intcode { return Intcode { program: Vec::new(), pos: 0 }; } fn load(fname: &String) -> Intcode { let mut ic = Intcode::new(); // One line, CSV integers let csv = fs::read_to_string(fname).unwrap_or_else(|err| panic!("Error reading {}: {}", fname, err)); for instr in csv.trim().split(',') { ic.program.push( instr.parse().unwrap_or_else(|err| panic!("Not an integer '{}' in {}: {}", instr, fname, err)) ); } return ic; } fn is_halted(&self) -> bool { 99 == *self.program.get(self.pos).unwrap_or(&99) } fn run(&mut self) { while self.step() { } } fn step(&mut self) -> bool { let step = match self.peeka(0) { 1 => { let (a, b, c) = (self.peeka(1), self.peeka(2), self.peeka(3)); // immutable borrow self.add(a, b, c); // mutable borrow 4 }, 2 => { let (a, b, c) = (self.peeka(1), self.peeka(2), self.peeka(3)); // immutable borrow self.mul(a, b, c); // mutable borrow 4 }, 99 => 0, x_ => panic!("Unknown command at position {}: {}", self.pos, x_), }; self.pos += step; return step > 0; } fn
(&mut self, a: usize, b: usize, c: usize) { self.program[c] = self.program[a] + self.program[b]; } fn mul(&mut self, a: usize, b: usize, c: usize) { self.program[c] = self.program[a] * self.program[b]; } fn get(&self, i: usize) -> i32 { self.program[i] } fn peek(&self, i: usize) -> i32 { self.get(self.pos + i) } fn geta(&self, i: usize) -> usize { usize::try_from( self.program[i] ).unwrap_or_else(|err| panic!("Expected address at position {}, found '{}' instead: {}", i, self.program[i], err)) } fn peeka(&self, i: usize) -> usize { self.geta(self.pos + i) } } impl fmt::Display for Intcode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self.program) } } fn main() { let matches = App::new("Advent of Code 2019, Day 02") .arg(Arg::with_name("FILE") .help("Input file to process") .index(1)) .get_matches(); let fname = String::from(matches.value_of("FILE").unwrap_or("02.in")); { let mut ic = Intcode::load(&fname); ic.program[1] = 12; ic.program[2] = 2; ic.run(); println!("Part 1: {}", ic.get(0)); } for noun in 0..100 { for verb in 0..100 { let mut ic = Intcode::load(&fname); ic.program[1] = noun; ic.program[2] = verb; ic.run(); if ic.get(0) == 19690720 { println!("Part 2: got 19690720 with noun={}, verb={}, key={}", noun, verb, 100 * noun + verb); return; } } } }
add
identifier_name
main.rs
extern crate clap; // Time Start: Mon, 02 Dec 2019 12:59:41 -0500 // Time Finish 1: Mon, 02 Dec 2019 14:46:54 -0500 (1 hour, 47 minutes, 13 seconds) // Time Finish 2: Mon, 02 Dec 2019 14:53:56 -0500 (7 minutes, 2 seconds) // Time Total: 1 hour, 54 minutes, 15 seconds use std::convert::TryFrom; use std::fmt; use std::fs; use clap::{Arg, App}; struct Intcode { program: Vec<i32>, pos: usize, } impl Intcode { fn new() -> Intcode { return Intcode { program: Vec::new(), pos: 0 }; } fn load(fname: &String) -> Intcode { let mut ic = Intcode::new(); // One line, CSV integers let csv = fs::read_to_string(fname).unwrap_or_else(|err| panic!("Error reading {}: {}", fname, err)); for instr in csv.trim().split(',') { ic.program.push( instr.parse().unwrap_or_else(|err| panic!("Not an integer '{}' in {}: {}", instr, fname, err)) ); } return ic; } fn is_halted(&self) -> bool { 99 == *self.program.get(self.pos).unwrap_or(&99) } fn run(&mut self) { while self.step() { } } fn step(&mut self) -> bool { let step = match self.peeka(0) { 1 => { let (a, b, c) = (self.peeka(1), self.peeka(2), self.peeka(3)); // immutable borrow self.add(a, b, c); // mutable borrow 4 }, 2 => { let (a, b, c) = (self.peeka(1), self.peeka(2), self.peeka(3)); // immutable borrow self.mul(a, b, c); // mutable borrow 4 }, 99 => 0, x_ => panic!("Unknown command at position {}: {}", self.pos, x_), }; self.pos += step; return step > 0; } fn add(&mut self, a: usize, b: usize, c: usize) {
self.program[c] = self.program[a] * self.program[b]; } fn get(&self, i: usize) -> i32 { self.program[i] } fn peek(&self, i: usize) -> i32 { self.get(self.pos + i) } fn geta(&self, i: usize) -> usize { usize::try_from( self.program[i] ).unwrap_or_else(|err| panic!("Expected address at position {}, found '{}' instead: {}", i, self.program[i], err)) } fn peeka(&self, i: usize) -> usize { self.geta(self.pos + i) } } impl fmt::Display for Intcode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self.program) } } fn main() { let matches = App::new("Advent of Code 2019, Day 02") .arg(Arg::with_name("FILE") .help("Input file to process") .index(1)) .get_matches(); let fname = String::from(matches.value_of("FILE").unwrap_or("02.in")); { let mut ic = Intcode::load(&fname); ic.program[1] = 12; ic.program[2] = 2; ic.run(); println!("Part 1: {}", ic.get(0)); } for noun in 0..100 { for verb in 0..100 { let mut ic = Intcode::load(&fname); ic.program[1] = noun; ic.program[2] = verb; ic.run(); if ic.get(0) == 19690720 { println!("Part 2: got 19690720 with noun={}, verb={}, key={}", noun, verb, 100 * noun + verb); return; } } } }
self.program[c] = self.program[a] + self.program[b]; } fn mul(&mut self, a: usize, b: usize, c: usize) {
random_line_split
error.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::fmt; #[derive(Debug)] /// Crypto error pub enum Error { /// Invalid secret key InvalidSecret, /// Invalid public key InvalidPublic, /// Invalid address InvalidAddress, /// Invalid EC signature InvalidSignature, /// Invalid AES message InvalidMessage, /// IO Error Io(::std::io::Error), /// Custom Custom(String), } impl fmt::Display for Error { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { let msg = match *self { Error::InvalidSecret => "Invalid secret".into(), Error::InvalidPublic => "Invalid public".into(), Error::InvalidAddress => "Invalid address".into(), Error::InvalidSignature => "Invalid EC signature".into(), Error::InvalidMessage => "Invalid AES message".into(), Error::Io(ref err) => format!("I/O error: {}", err), Error::Custom(ref s) => s.clone(), }; f.write_fmt(format_args!("Crypto error ({})", msg)) } } impl From<::secp256k1::Error> for Error { fn from(e: ::secp256k1::Error) -> Error { match e { ::secp256k1::Error::InvalidMessage => Error::InvalidMessage, ::secp256k1::Error::InvalidPublicKey => Error::InvalidPublic, ::secp256k1::Error::InvalidSecretKey => Error::InvalidSecret, _ => Error::InvalidSignature, } } } impl From<::std::io::Error> for Error { fn from(err: ::std::io::Error) -> Error { Error::Io(err) } }
fmt
identifier_name
error.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::fmt; #[derive(Debug)] /// Crypto error pub enum Error { /// Invalid secret key InvalidSecret, /// Invalid public key InvalidPublic, /// Invalid address InvalidAddress, /// Invalid EC signature InvalidSignature, /// Invalid AES message InvalidMessage, /// IO Error Io(::std::io::Error), /// Custom Custom(String), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let msg = match *self { Error::InvalidSecret => "Invalid secret".into(), Error::InvalidPublic => "Invalid public".into(), Error::InvalidAddress => "Invalid address".into(), Error::InvalidSignature => "Invalid EC signature".into(), Error::InvalidMessage => "Invalid AES message".into(), Error::Io(ref err) => format!("I/O error: {}", err), Error::Custom(ref s) => s.clone(), }; f.write_fmt(format_args!("Crypto error ({})", msg)) } }
impl From<::secp256k1::Error> for Error { fn from(e: ::secp256k1::Error) -> Error { match e { ::secp256k1::Error::InvalidMessage => Error::InvalidMessage, ::secp256k1::Error::InvalidPublicKey => Error::InvalidPublic, ::secp256k1::Error::InvalidSecretKey => Error::InvalidSecret, _ => Error::InvalidSignature, } } } impl From<::std::io::Error> for Error { fn from(err: ::std::io::Error) -> Error { Error::Io(err) } }
random_line_split
webdriver_msg.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 constellation_msg::PipelineId; use euclid::rect::Rect; use ipc_channel::ipc::IpcSender; use rustc_serialize::json::{Json, ToJson}; use url::Url; #[derive(Deserialize, Serialize)] pub enum WebDriverScriptCommand { ExecuteScript(String, IpcSender<WebDriverJSResult>), ExecuteAsyncScript(String, IpcSender<WebDriverJSResult>), FindElementCSS(String, IpcSender<Result<Option<String>, ()>>), FindElementsCSS(String, IpcSender<Result<Vec<String>, ()>>), FocusElement(String, IpcSender<Result<(), ()>>), GetActiveElement(IpcSender<Option<String>>), GetElementAttribute(String, String, IpcSender<Result<Option<String>, ()>>), GetElementCSS(String, String, IpcSender<Result<String, ()>>), GetElementRect(String, IpcSender<Result<Rect<f64>, ()>>), GetElementTagName(String, IpcSender<Result<String, ()>>), GetElementText(String, IpcSender<Result<String, ()>>), GetFrameId(WebDriverFrameId, IpcSender<Result<Option<PipelineId>, ()>>), GetUrl(IpcSender<Url>), IsEnabled(String, IpcSender<Result<bool, ()>>), IsSelected(String, IpcSender<Result<bool, ()>>), GetTitle(IpcSender<String>) } #[derive(Deserialize, Serialize)] pub enum WebDriverJSValue { Undefined, Null, Boolean(bool), Number(f64), String(String), // TODO: Object and WebElement }
#[derive(Deserialize, Serialize)] pub enum WebDriverJSError { Timeout, UnknownType } pub type WebDriverJSResult = Result<WebDriverJSValue, WebDriverJSError>; #[derive(Deserialize, Serialize)] pub enum WebDriverFrameId { Short(u16), Element(String), Parent } impl ToJson for WebDriverJSValue { fn to_json(&self) -> Json { match *self { WebDriverJSValue::Undefined => Json::Null, WebDriverJSValue::Null => Json::Null, WebDriverJSValue::Boolean(ref x) => x.to_json(), WebDriverJSValue::Number(ref x) => x.to_json(), WebDriverJSValue::String(ref x) => x.to_json() } } } #[derive(Deserialize, Serialize)] pub enum LoadStatus { LoadComplete, LoadTimeout }
random_line_split
webdriver_msg.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 constellation_msg::PipelineId; use euclid::rect::Rect; use ipc_channel::ipc::IpcSender; use rustc_serialize::json::{Json, ToJson}; use url::Url; #[derive(Deserialize, Serialize)] pub enum WebDriverScriptCommand { ExecuteScript(String, IpcSender<WebDriverJSResult>), ExecuteAsyncScript(String, IpcSender<WebDriverJSResult>), FindElementCSS(String, IpcSender<Result<Option<String>, ()>>), FindElementsCSS(String, IpcSender<Result<Vec<String>, ()>>), FocusElement(String, IpcSender<Result<(), ()>>), GetActiveElement(IpcSender<Option<String>>), GetElementAttribute(String, String, IpcSender<Result<Option<String>, ()>>), GetElementCSS(String, String, IpcSender<Result<String, ()>>), GetElementRect(String, IpcSender<Result<Rect<f64>, ()>>), GetElementTagName(String, IpcSender<Result<String, ()>>), GetElementText(String, IpcSender<Result<String, ()>>), GetFrameId(WebDriverFrameId, IpcSender<Result<Option<PipelineId>, ()>>), GetUrl(IpcSender<Url>), IsEnabled(String, IpcSender<Result<bool, ()>>), IsSelected(String, IpcSender<Result<bool, ()>>), GetTitle(IpcSender<String>) } #[derive(Deserialize, Serialize)] pub enum WebDriverJSValue { Undefined, Null, Boolean(bool), Number(f64), String(String), // TODO: Object and WebElement } #[derive(Deserialize, Serialize)] pub enum
{ Timeout, UnknownType } pub type WebDriverJSResult = Result<WebDriverJSValue, WebDriverJSError>; #[derive(Deserialize, Serialize)] pub enum WebDriverFrameId { Short(u16), Element(String), Parent } impl ToJson for WebDriverJSValue { fn to_json(&self) -> Json { match *self { WebDriverJSValue::Undefined => Json::Null, WebDriverJSValue::Null => Json::Null, WebDriverJSValue::Boolean(ref x) => x.to_json(), WebDriverJSValue::Number(ref x) => x.to_json(), WebDriverJSValue::String(ref x) => x.to_json() } } } #[derive(Deserialize, Serialize)] pub enum LoadStatus { LoadComplete, LoadTimeout }
WebDriverJSError
identifier_name
minwinbase.rs
// Copyright © 2016-2017 winapi-rs developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms //! This module defines the 32-Bit Windows Base APIs use shared::basetsd::ULONG_PTR; use shared::minwindef::{BOOL, BYTE, DWORD, FILETIME, HMODULE, LPVOID, MAX_PATH, UINT, ULONG, WORD}; use shared::ntstatus::{ STATUS_ACCESS_VIOLATION, STATUS_ARRAY_BOUNDS_EXCEEDED, STATUS_BREAKPOINT, STATUS_CONTROL_C_EXIT, STATUS_DATATYPE_MISALIGNMENT, STATUS_FLOAT_DENORMAL_OPERAND, STATUS_FLOAT_DIVIDE_BY_ZERO, STATUS_FLOAT_INEXACT_RESULT, STATUS_FLOAT_INVALID_OPERATION, STATUS_FLOAT_OVERFLOW, STATUS_FLOAT_STACK_CHECK, STATUS_FLOAT_UNDERFLOW, STATUS_GUARD_PAGE_VIOLATION, STATUS_ILLEGAL_INSTRUCTION, STATUS_INTEGER_DIVIDE_BY_ZERO, STATUS_INTEGER_OVERFLOW, STATUS_INVALID_DISPOSITION, STATUS_INVALID_HANDLE, STATUS_IN_PAGE_ERROR, STATUS_NONCONTINUABLE_EXCEPTION, STATUS_PENDING, STATUS_POSSIBLE_DEADLOCK, STATUS_PRIVILEGED_INSTRUCTION, STATUS_SINGLE_STEP, STATUS_STACK_OVERFLOW, }; use um::winnt::{ CHAR, EXCEPTION_RECORD, HANDLE, LPSTR, LPWSTR, PCONTEXT, PRTL_CRITICAL_SECTION, PRTL_CRITICAL_SECTION_DEBUG, PVOID, RTL_CRITICAL_SECTION, RTL_CRITICAL_SECTION_DEBUG, WCHAR, }; //MoveMemory //CopyMemory //FillMemory //ZeroMemory STRUCT!{struct SECURITY_ATTRIBUTES { nLength: DWORD, lpSecurityDescriptor: LPVOID, bInheritHandle: BOOL, }} pub type PSECURITY_ATTRIBUTES = *mut SECURITY_ATTRIBUTES; pub type LPSECURITY_ATTRIBUTES = *mut SECURITY_ATTRIBUTES; STRUCT!{struct OVERLAPPED_u_s { Offset: DWORD, OffsetHigh: DWORD, }} UNION!{union OVERLAPPED_u { [u32; 2] [u64; 1], s s_mut: OVERLAPPED_u_s, Pointer Pointer_mut: PVOID, }} STRUCT!{struct OVERLAPPED { Internal: ULONG_PTR, InternalHigh: ULONG_PTR, u: OVERLAPPED_u, hEvent: HANDLE, }} pub type LPOVERLAPPED = *mut OVERLAPPED; STRUCT!{struct OVERLAPPED_ENTRY { lpCompletionKey: ULONG_PTR, lpOverlapped: LPOVERLAPPED, Internal: ULONG_PTR, dwNumberOfBytesTransferred: DWORD, }} pub type LPOVERLAPPED_ENTRY = *mut OVERLAPPED_ENTRY; STRUCT!{struct SYSTEMTIME { wYear: WORD, wMonth: WORD, wDayOfWeek: WORD, wDay: WORD, wHour: WORD, wMinute: WORD, wSecond: WORD, wMilliseconds: WORD, }} pub type PSYSTEMTIME = *mut SYSTEMTIME; pub type LPSYSTEMTIME = *mut SYSTEMTIME; STRUCT!{struct WIN32_FIND_DATAA { dwFileAttributes: DWORD, ftCreationTime: FILETIME, ftLastAccessTime: FILETIME, ftLastWriteTime: FILETIME, nFileSizeHigh: DWORD, nFileSizeLow: DWORD, dwReserved0: DWORD, dwReserved1: DWORD, cFileName: [CHAR; MAX_PATH], cAlternateFileName: [CHAR; 14], }} pub type PWIN32_FIND_DATAA = *mut WIN32_FIND_DATAA; pub type LPWIN32_FIND_DATAA = *mut WIN32_FIND_DATAA; STRUCT!{struct WIN32_FIND_DATAW { dwFileAttributes: DWORD, ftCreationTime: FILETIME, ftLastAccessTime: FILETIME, ftLastWriteTime: FILETIME, nFileSizeHigh: DWORD, nFileSizeLow: DWORD, dwReserved0: DWORD, dwReserved1: DWORD, cFileName: [WCHAR; MAX_PATH], cAlternateFileName: [WCHAR; 14], }} pub type PWIN32_FIND_DATAW = *mut WIN32_FIND_DATAW; pub type LPWIN32_FIND_DATAW = *mut WIN32_FIND_DATAW; ENUM!{enum FINDEX_INFO_LEVELS { FindExInfoStandard, FindExInfoBasic, FindExInfoMaxInfoLevel, }} pub const FIND_FIRST_EX_CASE_SENSITIVE: DWORD = 0x00000001; pub const FIND_FIRST_EX_LARGE_FETCH: DWORD = 0x00000002; ENUM!{enum FINDEX_SEARCH_OPS { FindExSearchNameMatch, FindExSearchLimitToDirectories, FindExSearchLimitToDevices, FindExSearchMaxSearchOp, }} ENUM!{enum GET_FILEEX_INFO_LEVELS { GetFileExInfoStandard, GetFileExMaxInfoLevel, }} ENUM!{enum FILE_INFO_BY_HANDLE_CLASS { FileBasicInfo, FileStandardInfo, FileNameInfo, FileRenameInfo, FileDispositionInfo, FileAllocationInfo, FileEndOfFileInfo, FileStreamInfo, FileCompressionInfo, FileAttributeTagInfo, FileIdBothDirectoryInfo, FileIdBothDirectoryRestartInfo, FileIoPriorityHintInfo, FileRemoteProtocolInfo, FileFullDirectoryInfo, FileFullDirectoryRestartInfo, FileStorageInfo, FileAlignmentInfo, FileIdInfo, FileIdExtdDirectoryInfo, FileIdExtdDirectoryRestartInfo, FileDispositionInfoEx, FileRenameInfoEx, MaximumFileInfoByHandleClass, }} pub type PFILE_INFO_BY_HANDLE_CLASS = *mut FILE_INFO_BY_HANDLE_CLASS; pub type CRITICAL_SECTION = RTL_CRITICAL_SECTION; pub type PCRITICAL_SECTION = PRTL_CRITICAL_SECTION; pub type LPCRITICAL_SECTION = PRTL_CRITICAL_SECTION; pub type CRITICAL_SECTION_DEBUG = RTL_CRITICAL_SECTION_DEBUG; pub type PCRITICAL_SECTION_DEBUG = PRTL_CRITICAL_SECTION_DEBUG; pub type LPCRITICAL_SECTION_DEBUG = PRTL_CRITICAL_SECTION_DEBUG; FN!{stdcall LPOVERLAPPED_COMPLETION_ROUTINE( dwErrorCode: DWORD, dwNumberOfBytesTransfered: DWORD, lpOverlapped: LPOVERLAPPED, ) -> ()} pub const LOCKFILE_FAIL_IMMEDIATELY: DWORD = 0x00000001; pub const LOCKFILE_EXCLUSIVE_LOCK: DWORD = 0x00000002; STRUCT!{struct PROCESS_HEAP_ENTRY_Block { hMem: HANDLE, dwReserved: [DWORD; 3], }} STRUCT!{struct PROCESS_HEAP_ENTRY_Region { dwCommittedSize: DWORD, dwUnCommittedSize: DWORD, lpFirstBlock: LPVOID, lpLastBlock: LPVOID, }} UNION!{union PROCESS_HEAP_ENTRY_u { [u32; 4] [u64; 3], Block Block_mut: PROCESS_HEAP_ENTRY_Block, Region Region_mut: PROCESS_HEAP_ENTRY_Region, }} STRUCT!{struct PROCESS_HEAP_ENTRY { lpData: PVOID, cbData: DWORD, cbOverhead: BYTE, iRegionIndex: BYTE, wFlags: WORD, u: PROCESS_HEAP_ENTRY_u, }} pub type LPPROCESS_HEAP_ENTRY = *mut PROCESS_HEAP_ENTRY; pub type PPROCESS_HEAP_ENTRY = *mut PROCESS_HEAP_ENTRY; pub const PROCESS_HEAP_REGION: WORD = 0x0001; pub const PROCESS_HEAP_UNCOMMITTED_RANGE: WORD = 0x0002; pub const PROCESS_HEAP_ENTRY_BUSY: WORD = 0x0004; pub const PROCESS_HEAP_SEG_ALLOC: WORD = 0x0008; pub const PROCESS_HEAP_ENTRY_MOVEABLE: WORD = 0x0010; pub const PROCESS_HEAP_ENTRY_DDESHARE: WORD = 0x0020; STRUCT!{struct REASON_CONTEXT_Detailed { LocalizedReasonModule: HMODULE, LocalizedReasonId: ULONG, ReasonStringCount: ULONG, ReasonStrings: *mut LPWSTR, }} UNION!{union REASON_CONTEXT_Reason { [u32; 4] [u64; 3], Detailed Detailed_mut: REASON_CONTEXT_Detailed, SimpleReasonString SimpleReasonString_mut: LPWSTR, }} STRUCT!{struct REASON_CONTEXT { Version: ULONG, Flags: DWORD, Reason: REASON_CONTEXT_Reason, }} pub type PREASON_CONTEXT = *mut REASON_CONTEXT; pub const EXCEPTION_DEBUG_EVENT: DWORD = 1; pub const CREATE_THREAD_DEBUG_EVENT: DWORD = 2; pub const CREATE_PROCESS_DEBUG_EVENT: DWORD = 3; pub const EXIT_THREAD_DEBUG_EVENT: DWORD = 4; pub const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5; pub const LOAD_DLL_DEBUG_EVENT: DWORD = 6; pub const UNLOAD_DLL_DEBUG_EVENT: DWORD = 7; pub const OUTPUT_DEBUG_STRING_EVENT: DWORD = 8; pub const RIP_EVENT: DWORD = 9; FN!{stdcall PTHREAD_START_ROUTINE( lpThreadParameter: LPVOID, ) -> DWORD} pub type LPTHREAD_START_ROUTINE = PTHREAD_START_ROUTINE; STRUCT!{struct EXCEPTION_DEBUG_INFO { ExceptionRecord: EXCEPTION_RECORD, dwFirstChance: DWORD, }} pub type LPEXCEPTION_DEBUG_INFO = *mut EXCEPTION_DEBUG_INFO; STRUCT!{struct CREATE_THREAD_DEBUG_INFO { hThread: HANDLE, lpThreadLocalBase: LPVOID, lpStartAddress: LPTHREAD_START_ROUTINE, }} pub type LPCREATE_THREAD_DEBUG_INFO = *mut CREATE_THREAD_DEBUG_INFO; STRUCT!{struct CREATE_PROCESS_DEBUG_INFO { hFile: HANDLE,
lpBaseOfImage: LPVOID, dwDebugInfoFileOffset: DWORD, nDebugInfoSize: DWORD, lpThreadLocalBase: LPVOID, lpStartAddress: LPTHREAD_START_ROUTINE, lpImageName: LPVOID, fUnicode: WORD, }} pub type LPCREATE_PROCESS_DEBUG_INFO = *mut CREATE_PROCESS_DEBUG_INFO; STRUCT!{struct EXIT_THREAD_DEBUG_INFO { dwExitCode: DWORD, }} pub type LPEXIT_THREAD_DEBUG_INFO = *mut EXIT_THREAD_DEBUG_INFO; STRUCT!{struct EXIT_PROCESS_DEBUG_INFO { dwExitCode: DWORD, }} pub type LPEXIT_PROCESS_DEBUG_INFO = *mut EXIT_PROCESS_DEBUG_INFO; STRUCT!{struct LOAD_DLL_DEBUG_INFO { hFile: HANDLE, lpBaseOfDll: LPVOID, dwDebugInfoFileOffset: DWORD, nDebugInfoSize: DWORD, lpImageName: LPVOID, fUnicode: WORD, }} pub type LPLOAD_DLL_DEBUG_INFO = *mut LOAD_DLL_DEBUG_INFO; STRUCT!{struct UNLOAD_DLL_DEBUG_INFO { lpBaseOfDll: LPVOID, }} pub type LPUNLOAD_DLL_DEBUG_INFO = *mut UNLOAD_DLL_DEBUG_INFO; STRUCT!{struct OUTPUT_DEBUG_STRING_INFO { lpDebugStringData: LPSTR, fUnicode: WORD, nDebugStringLength: WORD, }} pub type LPOUTPUT_DEBUG_STRING_INFO = *mut OUTPUT_DEBUG_STRING_INFO; STRUCT!{struct RIP_INFO { dwError: DWORD, dwType: DWORD, }} pub type LPRIP_INFO = *mut RIP_INFO; UNION!{union DEBUG_EVENT_u { [u32; 21] [u64; 20], Exception Exception_mut: EXCEPTION_DEBUG_INFO, CreateThread CreateThread_mut: CREATE_THREAD_DEBUG_INFO, CreateProcessInfo CreateProcessInfo_mut: CREATE_PROCESS_DEBUG_INFO, ExitThread ExitThread_mut: EXIT_THREAD_DEBUG_INFO, ExitProcess ExitProcess_mut: EXIT_PROCESS_DEBUG_INFO, LoadDll LoadDll_mut: LOAD_DLL_DEBUG_INFO, UnloadDll UnloadDll_mut: UNLOAD_DLL_DEBUG_INFO, DebugString DebugString_mut: OUTPUT_DEBUG_STRING_INFO, RipInfo RipInfo_mut: RIP_INFO, }} STRUCT!{struct DEBUG_EVENT { dwDebugEventCode: DWORD, dwProcessId: DWORD, dwThreadId: DWORD, u: DEBUG_EVENT_u, }} pub type LPDEBUG_EVENT = *mut DEBUG_EVENT; pub type LPCONTEXT = PCONTEXT; pub const STILL_ACTIVE: DWORD = STATUS_PENDING as u32; pub const EXCEPTION_ACCESS_VIOLATION: DWORD = STATUS_ACCESS_VIOLATION as u32; pub const EXCEPTION_DATATYPE_MISALIGNMENT: DWORD = STATUS_DATATYPE_MISALIGNMENT as u32; pub const EXCEPTION_BREAKPOINT: DWORD = STATUS_BREAKPOINT as u32; pub const EXCEPTION_SINGLE_STEP: DWORD = STATUS_SINGLE_STEP as u32; pub const EXCEPTION_ARRAY_BOUNDS_EXCEEDED: DWORD = STATUS_ARRAY_BOUNDS_EXCEEDED as u32; pub const EXCEPTION_FLT_DENORMAL_OPERAND: DWORD = STATUS_FLOAT_DENORMAL_OPERAND as u32; pub const EXCEPTION_FLT_DIVIDE_BY_ZERO: DWORD = STATUS_FLOAT_DIVIDE_BY_ZERO as u32; pub const EXCEPTION_FLT_INEXACT_RESULT: DWORD = STATUS_FLOAT_INEXACT_RESULT as u32; pub const EXCEPTION_FLT_INVALID_OPERATION: DWORD = STATUS_FLOAT_INVALID_OPERATION as u32; pub const EXCEPTION_FLT_OVERFLOW: DWORD = STATUS_FLOAT_OVERFLOW as u32; pub const EXCEPTION_FLT_STACK_CHECK: DWORD = STATUS_FLOAT_STACK_CHECK as u32; pub const EXCEPTION_FLT_UNDERFLOW: DWORD = STATUS_FLOAT_UNDERFLOW as u32; pub const EXCEPTION_INT_DIVIDE_BY_ZERO: DWORD = STATUS_INTEGER_DIVIDE_BY_ZERO as u32; pub const EXCEPTION_INT_OVERFLOW: DWORD = STATUS_INTEGER_OVERFLOW as u32; pub const EXCEPTION_PRIV_INSTRUCTION: DWORD = STATUS_PRIVILEGED_INSTRUCTION as u32; pub const EXCEPTION_IN_PAGE_ERROR: DWORD = STATUS_IN_PAGE_ERROR as u32; pub const EXCEPTION_ILLEGAL_INSTRUCTION: DWORD = STATUS_ILLEGAL_INSTRUCTION as u32; pub const EXCEPTION_NONCONTINUABLE_EXCEPTION: DWORD = STATUS_NONCONTINUABLE_EXCEPTION as u32; pub const EXCEPTION_STACK_OVERFLOW: DWORD = STATUS_STACK_OVERFLOW as u32; pub const EXCEPTION_INVALID_DISPOSITION: DWORD = STATUS_INVALID_DISPOSITION as u32; pub const EXCEPTION_GUARD_PAGE: DWORD = STATUS_GUARD_PAGE_VIOLATION as u32; pub const EXCEPTION_INVALID_HANDLE: DWORD = STATUS_INVALID_HANDLE as u32; pub const EXCEPTION_POSSIBLE_DEADLOCK: DWORD = STATUS_POSSIBLE_DEADLOCK as u32; pub const CONTROL_C_EXIT: DWORD = STATUS_CONTROL_C_EXIT as u32; pub const LMEM_FIXED: UINT = 0x0000; pub const LMEM_MOVEABLE: UINT = 0x0002; pub const LMEM_NOCOMPACT: UINT = 0x0010; pub const LMEM_NODISCARD: UINT = 0x0020; pub const LMEM_ZEROINIT: UINT = 0x0040; pub const LMEM_MODIFY: UINT = 0x0080; pub const LMEM_DISCARDABLE: UINT = 0x0F00; pub const LMEM_VALID_FLAGS: UINT = 0x0F72; pub const LMEM_INVALID_HANDLE: UINT = 0x8000; pub const LHND: UINT = LMEM_MOVEABLE | LMEM_ZEROINIT; pub const LPTR: UINT = LMEM_FIXED | LMEM_ZEROINIT; pub const NONZEROLHND: UINT = LMEM_MOVEABLE; pub const NONZEROLPTR: UINT = LMEM_FIXED; //LocalDiscard pub const LMEM_DISCARDED: UINT = 0x4000; pub const LMEM_LOCKCOUNT: UINT = 0x00FF; pub const NUMA_NO_PREFERRED_NODE: DWORD = -1i32 as DWORD;
hProcess: HANDLE, hThread: HANDLE,
random_line_split
compositionevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CompositionEventBinding::{ self, CompositionEventMethods, }; use crate::dom::bindings::codegen::Bindings::UIEventBinding::UIEventBinding::UIEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::{DomRoot, RootedReference}; use crate::dom::bindings::str::DOMString; use crate::dom::uievent::UIEvent; use crate::dom::window::Window; use dom_struct::dom_struct; #[dom_struct] pub struct CompositionEvent { uievent: UIEvent, data: DOMString, } impl CompositionEvent { pub fn new( window: &Window, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<&Window>, detail: i32, data: DOMString, ) -> DomRoot<CompositionEvent> { let ev = reflect_dom_object( Box::new(CompositionEvent { uievent: UIEvent::new_inherited(), data: data, }), window, CompositionEventBinding::Wrap, ); ev.uievent .InitUIEvent(type_, can_bubble, cancelable, view, detail); ev } pub fn Constructor( window: &Window, type_: DOMString, init: &CompositionEventBinding::CompositionEventInit, ) -> Fallible<DomRoot<CompositionEvent>> { let event = CompositionEvent::new( window, type_, init.parent.parent.bubbles, init.parent.parent.cancelable, init.parent.view.r(), init.parent.detail, init.data.clone(), ); Ok(event) } pub fn data(&self) -> &str
} impl CompositionEventMethods for CompositionEvent { // https://w3c.github.io/uievents/#dom-compositionevent-data fn Data(&self) -> DOMString { self.data.clone() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.uievent.IsTrusted() } }
{ &*self.data }
identifier_body
compositionevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CompositionEventBinding::{ self, CompositionEventMethods, }; use crate::dom::bindings::codegen::Bindings::UIEventBinding::UIEventBinding::UIEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::{DomRoot, RootedReference}; use crate::dom::bindings::str::DOMString; use crate::dom::uievent::UIEvent; use crate::dom::window::Window; use dom_struct::dom_struct; #[dom_struct] pub struct CompositionEvent { uievent: UIEvent, data: DOMString, } impl CompositionEvent { pub fn new( window: &Window, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<&Window>, detail: i32, data: DOMString, ) -> DomRoot<CompositionEvent> { let ev = reflect_dom_object( Box::new(CompositionEvent { uievent: UIEvent::new_inherited(), data: data, }), window, CompositionEventBinding::Wrap, ); ev.uievent .InitUIEvent(type_, can_bubble, cancelable, view, detail); ev } pub fn Constructor( window: &Window, type_: DOMString, init: &CompositionEventBinding::CompositionEventInit, ) -> Fallible<DomRoot<CompositionEvent>> { let event = CompositionEvent::new( window, type_, init.parent.parent.bubbles, init.parent.parent.cancelable, init.parent.view.r(), init.parent.detail, init.data.clone(), );
} pub fn data(&self) -> &str { &*self.data } } impl CompositionEventMethods for CompositionEvent { // https://w3c.github.io/uievents/#dom-compositionevent-data fn Data(&self) -> DOMString { self.data.clone() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.uievent.IsTrusted() } }
Ok(event)
random_line_split
compositionevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CompositionEventBinding::{ self, CompositionEventMethods, }; use crate::dom::bindings::codegen::Bindings::UIEventBinding::UIEventBinding::UIEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::{DomRoot, RootedReference}; use crate::dom::bindings::str::DOMString; use crate::dom::uievent::UIEvent; use crate::dom::window::Window; use dom_struct::dom_struct; #[dom_struct] pub struct CompositionEvent { uievent: UIEvent, data: DOMString, } impl CompositionEvent { pub fn new( window: &Window, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<&Window>, detail: i32, data: DOMString, ) -> DomRoot<CompositionEvent> { let ev = reflect_dom_object( Box::new(CompositionEvent { uievent: UIEvent::new_inherited(), data: data, }), window, CompositionEventBinding::Wrap, ); ev.uievent .InitUIEvent(type_, can_bubble, cancelable, view, detail); ev } pub fn Constructor( window: &Window, type_: DOMString, init: &CompositionEventBinding::CompositionEventInit, ) -> Fallible<DomRoot<CompositionEvent>> { let event = CompositionEvent::new( window, type_, init.parent.parent.bubbles, init.parent.parent.cancelable, init.parent.view.r(), init.parent.detail, init.data.clone(), ); Ok(event) } pub fn
(&self) -> &str { &*self.data } } impl CompositionEventMethods for CompositionEvent { // https://w3c.github.io/uievents/#dom-compositionevent-data fn Data(&self) -> DOMString { self.data.clone() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.uievent.IsTrusted() } }
data
identifier_name
blob.rs
use std::marker; use std::slice; use {raw, Oid, Object}; use util::Binding; /// A structure to represent a git [blob][1] /// /// [1]: http://git-scm.com/book/en/Git-Internals-Git-Objects pub struct Blob<'repo> { raw: *mut raw::git_blob, _marker: marker::PhantomData<Object<'repo>>, } impl<'repo> Blob<'repo> { /// Get the id (SHA1) of a repository blob pub fn id(&self) -> Oid
/// Determine if the blob content is most certainly binary or not. pub fn is_binary(&self) -> bool { unsafe { raw::git_blob_is_binary(&*self.raw) == 1 } } /// Get the content of this blob. pub fn content(&self) -> &[u8] { unsafe { let data = raw::git_blob_rawcontent(&*self.raw) as *const u8; let len = raw::git_blob_rawsize(&*self.raw) as usize; slice::from_raw_parts(data, len) } } } impl<'repo> Binding for Blob<'repo> { type Raw = *mut raw::git_blob; unsafe fn from_raw(raw: *mut raw::git_blob) -> Blob<'repo> { Blob { raw: raw, _marker: marker::PhantomData, } } fn raw(&self) -> *mut raw::git_blob { self.raw } } impl<'repo> Drop for Blob<'repo> { fn drop(&mut self) { unsafe { raw::git_blob_free(self.raw) } } } #[cfg(test)] mod tests { use std::io::prelude::*; use std::fs::File; use tempdir::TempDir; use Repository; #[test] fn buffer() { let td = TempDir::new("test").unwrap(); let repo = Repository::init(td.path()).unwrap(); let id = repo.blob(&[5, 4, 6]).unwrap(); let blob = repo.find_blob(id).unwrap(); assert_eq!(blob.id(), id); assert_eq!(blob.content(), [5, 4, 6]); assert!(blob.is_binary()); repo.find_object(id, None).unwrap().as_blob().unwrap(); } #[test] fn path() { let td = TempDir::new("test").unwrap(); let path = td.path().join("foo"); File::create(&path).unwrap().write_all(&[7, 8, 9]).unwrap(); let repo = Repository::init(td.path()).unwrap(); let id = repo.blob_path(&path).unwrap(); let blob = repo.find_blob(id).unwrap(); assert_eq!(blob.content(), [7, 8, 9]); } }
{ unsafe { Binding::from_raw(raw::git_blob_id(&*self.raw)) } }
identifier_body
blob.rs
use std::marker; use std::slice; use {raw, Oid, Object}; use util::Binding; /// A structure to represent a git [blob][1] /// /// [1]: http://git-scm.com/book/en/Git-Internals-Git-Objects pub struct Blob<'repo> { raw: *mut raw::git_blob, _marker: marker::PhantomData<Object<'repo>>, } impl<'repo> Blob<'repo> { /// Get the id (SHA1) of a repository blob pub fn id(&self) -> Oid { unsafe { Binding::from_raw(raw::git_blob_id(&*self.raw)) } } /// Determine if the blob content is most certainly binary or not. pub fn is_binary(&self) -> bool { unsafe { raw::git_blob_is_binary(&*self.raw) == 1 } } /// Get the content of this blob. pub fn content(&self) -> &[u8] { unsafe { let data = raw::git_blob_rawcontent(&*self.raw) as *const u8; let len = raw::git_blob_rawsize(&*self.raw) as usize; slice::from_raw_parts(data, len) } } } impl<'repo> Binding for Blob<'repo> { type Raw = *mut raw::git_blob; unsafe fn from_raw(raw: *mut raw::git_blob) -> Blob<'repo> { Blob { raw: raw, _marker: marker::PhantomData, } } fn raw(&self) -> *mut raw::git_blob { self.raw } } impl<'repo> Drop for Blob<'repo> { fn drop(&mut self) { unsafe { raw::git_blob_free(self.raw) } } } #[cfg(test)] mod tests { use std::io::prelude::*; use std::fs::File; use tempdir::TempDir; use Repository; #[test] fn buffer() { let td = TempDir::new("test").unwrap(); let repo = Repository::init(td.path()).unwrap(); let id = repo.blob(&[5, 4, 6]).unwrap(); let blob = repo.find_blob(id).unwrap(); assert_eq!(blob.id(), id); assert_eq!(blob.content(), [5, 4, 6]); assert!(blob.is_binary()); repo.find_object(id, None).unwrap().as_blob().unwrap(); } #[test] fn path() {
let td = TempDir::new("test").unwrap(); let path = td.path().join("foo"); File::create(&path).unwrap().write_all(&[7, 8, 9]).unwrap(); let repo = Repository::init(td.path()).unwrap(); let id = repo.blob_path(&path).unwrap(); let blob = repo.find_blob(id).unwrap(); assert_eq!(blob.content(), [7, 8, 9]); } }
random_line_split
blob.rs
use std::marker; use std::slice; use {raw, Oid, Object}; use util::Binding; /// A structure to represent a git [blob][1] /// /// [1]: http://git-scm.com/book/en/Git-Internals-Git-Objects pub struct Blob<'repo> { raw: *mut raw::git_blob, _marker: marker::PhantomData<Object<'repo>>, } impl<'repo> Blob<'repo> { /// Get the id (SHA1) of a repository blob pub fn id(&self) -> Oid { unsafe { Binding::from_raw(raw::git_blob_id(&*self.raw)) } } /// Determine if the blob content is most certainly binary or not. pub fn is_binary(&self) -> bool { unsafe { raw::git_blob_is_binary(&*self.raw) == 1 } } /// Get the content of this blob. pub fn content(&self) -> &[u8] { unsafe { let data = raw::git_blob_rawcontent(&*self.raw) as *const u8; let len = raw::git_blob_rawsize(&*self.raw) as usize; slice::from_raw_parts(data, len) } } } impl<'repo> Binding for Blob<'repo> { type Raw = *mut raw::git_blob; unsafe fn
(raw: *mut raw::git_blob) -> Blob<'repo> { Blob { raw: raw, _marker: marker::PhantomData, } } fn raw(&self) -> *mut raw::git_blob { self.raw } } impl<'repo> Drop for Blob<'repo> { fn drop(&mut self) { unsafe { raw::git_blob_free(self.raw) } } } #[cfg(test)] mod tests { use std::io::prelude::*; use std::fs::File; use tempdir::TempDir; use Repository; #[test] fn buffer() { let td = TempDir::new("test").unwrap(); let repo = Repository::init(td.path()).unwrap(); let id = repo.blob(&[5, 4, 6]).unwrap(); let blob = repo.find_blob(id).unwrap(); assert_eq!(blob.id(), id); assert_eq!(blob.content(), [5, 4, 6]); assert!(blob.is_binary()); repo.find_object(id, None).unwrap().as_blob().unwrap(); } #[test] fn path() { let td = TempDir::new("test").unwrap(); let path = td.path().join("foo"); File::create(&path).unwrap().write_all(&[7, 8, 9]).unwrap(); let repo = Repository::init(td.path()).unwrap(); let id = repo.blob_path(&path).unwrap(); let blob = repo.find_blob(id).unwrap(); assert_eq!(blob.content(), [7, 8, 9]); } }
from_raw
identifier_name
main.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![cfg(test)] #[macro_use] extern crate lazy_static; mod cookie; mod cookie_http_state; mod data_loader; mod fetch; mod file_loader;
mod mime_classifier; mod resource_thread; mod subresource_integrity; use devtools_traits::DevtoolsControlMsg; use embedder_traits::resources::{self, Resource}; use embedder_traits::{EmbedderProxy, EventLoopWaker}; use futures::{Future, Stream}; use hyper::server::conn::Http; use hyper::server::Server as HyperServer; use hyper::service::service_fn_ok; use hyper::{Body, Request as HyperRequest, Response as HyperResponse}; use net::connector::create_ssl_connector_builder; use net::fetch::cors_cache::CorsCache; use net::fetch::methods::{self, CancellationListener, FetchContext}; use net::filemanager_thread::FileManager; use net::test::HttpState; use net_traits::request::Request; use net_traits::response::Response; use net_traits::FetchTaskTarget; use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod}; use servo_channel::{channel, Sender}; use servo_url::ServoUrl; use std::net::TcpListener as StdTcpListener; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use tokio::net::TcpListener; use tokio::runtime::Runtime; use tokio_openssl::SslAcceptorExt; lazy_static! { pub static ref HANDLE: Mutex<Runtime> = { Mutex::new(Runtime::new().unwrap()) }; } const DEFAULT_USER_AGENT: &'static str = "Such Browser. Very Layout. Wow."; struct FetchResponseCollector { sender: Sender<Response>, } fn create_embedder_proxy() -> EmbedderProxy { let (sender, _) = channel(); let event_loop_waker = || { struct DummyEventLoopWaker {} impl DummyEventLoopWaker { fn new() -> DummyEventLoopWaker { DummyEventLoopWaker {} } } impl EventLoopWaker for DummyEventLoopWaker { fn wake(&self) {} fn clone(&self) -> Box<dyn EventLoopWaker + Send> { Box::new(DummyEventLoopWaker {}) } } Box::new(DummyEventLoopWaker::new()) }; EmbedderProxy { sender: sender, event_loop_waker: event_loop_waker(), } } fn new_fetch_context( dc: Option<Sender<DevtoolsControlMsg>>, fc: Option<EmbedderProxy>, ) -> FetchContext { let ssl_connector = create_ssl_connector_builder(&resources::read_string(Resource::SSLCertificates)); let sender = fc.unwrap_or_else(|| create_embedder_proxy()); FetchContext { state: Arc::new(HttpState::new(ssl_connector)), user_agent: DEFAULT_USER_AGENT.into(), devtools_chan: dc, filemanager: FileManager::new(sender), cancellation_listener: Arc::new(Mutex::new(CancellationListener::new(None))), } } impl FetchTaskTarget for FetchResponseCollector { fn process_request_body(&mut self, _: &Request) {} fn process_request_eof(&mut self, _: &Request) {} fn process_response(&mut self, _: &Response) {} fn process_response_chunk(&mut self, _: Vec<u8>) {} /// Fired when the response is fully fetched fn process_response_eof(&mut self, response: &Response) { let _ = self.sender.send(response.clone()); } } fn fetch(request: &mut Request, dc: Option<Sender<DevtoolsControlMsg>>) -> Response { fetch_with_context(request, &new_fetch_context(dc, None)) } fn fetch_with_context(request: &mut Request, context: &FetchContext) -> Response { let (sender, receiver) = channel(); let mut target = FetchResponseCollector { sender: sender }; methods::fetch(request, &mut target, context); receiver.recv().unwrap() } fn fetch_with_cors_cache(request: &mut Request, cache: &mut CorsCache) -> Response { let (sender, receiver) = channel(); let mut target = FetchResponseCollector { sender: sender }; methods::fetch_with_cors_cache(request, cache, &mut target, &new_fetch_context(None, None)); receiver.recv().unwrap() } pub(crate) struct Server { pub close_channel: futures::sync::oneshot::Sender<()>, } impl Server { fn close(self) { self.close_channel.send(()).unwrap(); } } fn make_server<H>(handler: H) -> (Server, ServoUrl) where H: Fn(HyperRequest<Body>, &mut HyperResponse<Body>) + Send + Sync +'static, { let handler = Arc::new(handler); let listener = StdTcpListener::bind("0.0.0.0:0").unwrap(); let url_string = format!("http://localhost:{}", listener.local_addr().unwrap().port()); let url = ServoUrl::parse(&url_string).unwrap(); let (tx, rx) = futures::sync::oneshot::channel::<()>(); let server = HyperServer::from_tcp(listener) .unwrap() .serve(move || { let handler = handler.clone(); service_fn_ok(move |req: HyperRequest<Body>| { let mut response = HyperResponse::new(Vec::<u8>::new().into()); handler(req, &mut response); response }) }) .with_graceful_shutdown(rx) .map_err(|_| ()); HANDLE.lock().unwrap().spawn(server); let server = Server { close_channel: tx }; (server, url) } fn make_ssl_server<H>(handler: H, cert_path: PathBuf, key_path: PathBuf) -> (Server, ServoUrl) where H: Fn(HyperRequest<Body>, &mut HyperResponse<Body>) + Send + Sync +'static, { let handler = Arc::new(handler); let listener = StdTcpListener::bind("[::0]:0").unwrap(); let listener = TcpListener::from_std(listener, &HANDLE.lock().unwrap().reactor()).unwrap(); let url_string = format!("http://localhost:{}", listener.local_addr().unwrap().port()); let url = ServoUrl::parse(&url_string).unwrap(); let server = listener.incoming().map_err(|_| ()).for_each(move |sock| { let mut ssl_builder = SslAcceptor::mozilla_modern(SslMethod::tls()).unwrap(); ssl_builder .set_certificate_file(&cert_path, SslFiletype::PEM) .unwrap(); ssl_builder .set_private_key_file(&key_path, SslFiletype::PEM) .unwrap(); let handler = handler.clone(); ssl_builder .build() .accept_async(sock) .map_err(|_| ()) .and_then(move |ssl| { Http::new() .serve_connection( ssl, service_fn_ok(move |req: HyperRequest<Body>| { let mut response = HyperResponse::new(Vec::<u8>::new().into()); handler(req, &mut response); response }), ) .map_err(|_| ()) }) }); let (tx, rx) = futures::sync::oneshot::channel::<()>(); let server = server .select(rx.map_err(|_| ())) .map(|_| ()) .map_err(|_| ()); HANDLE.lock().unwrap().spawn(server); let server = Server { close_channel: tx }; (server, url) }
mod filemanager_thread; mod hsts; mod http_loader;
random_line_split
main.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![cfg(test)] #[macro_use] extern crate lazy_static; mod cookie; mod cookie_http_state; mod data_loader; mod fetch; mod file_loader; mod filemanager_thread; mod hsts; mod http_loader; mod mime_classifier; mod resource_thread; mod subresource_integrity; use devtools_traits::DevtoolsControlMsg; use embedder_traits::resources::{self, Resource}; use embedder_traits::{EmbedderProxy, EventLoopWaker}; use futures::{Future, Stream}; use hyper::server::conn::Http; use hyper::server::Server as HyperServer; use hyper::service::service_fn_ok; use hyper::{Body, Request as HyperRequest, Response as HyperResponse}; use net::connector::create_ssl_connector_builder; use net::fetch::cors_cache::CorsCache; use net::fetch::methods::{self, CancellationListener, FetchContext}; use net::filemanager_thread::FileManager; use net::test::HttpState; use net_traits::request::Request; use net_traits::response::Response; use net_traits::FetchTaskTarget; use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod}; use servo_channel::{channel, Sender}; use servo_url::ServoUrl; use std::net::TcpListener as StdTcpListener; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use tokio::net::TcpListener; use tokio::runtime::Runtime; use tokio_openssl::SslAcceptorExt; lazy_static! { pub static ref HANDLE: Mutex<Runtime> = { Mutex::new(Runtime::new().unwrap()) }; } const DEFAULT_USER_AGENT: &'static str = "Such Browser. Very Layout. Wow."; struct FetchResponseCollector { sender: Sender<Response>, } fn create_embedder_proxy() -> EmbedderProxy { let (sender, _) = channel(); let event_loop_waker = || { struct DummyEventLoopWaker {} impl DummyEventLoopWaker { fn new() -> DummyEventLoopWaker { DummyEventLoopWaker {} } } impl EventLoopWaker for DummyEventLoopWaker { fn wake(&self) {} fn clone(&self) -> Box<dyn EventLoopWaker + Send> { Box::new(DummyEventLoopWaker {}) } } Box::new(DummyEventLoopWaker::new()) }; EmbedderProxy { sender: sender, event_loop_waker: event_loop_waker(), } } fn new_fetch_context( dc: Option<Sender<DevtoolsControlMsg>>, fc: Option<EmbedderProxy>, ) -> FetchContext { let ssl_connector = create_ssl_connector_builder(&resources::read_string(Resource::SSLCertificates)); let sender = fc.unwrap_or_else(|| create_embedder_proxy()); FetchContext { state: Arc::new(HttpState::new(ssl_connector)), user_agent: DEFAULT_USER_AGENT.into(), devtools_chan: dc, filemanager: FileManager::new(sender), cancellation_listener: Arc::new(Mutex::new(CancellationListener::new(None))), } } impl FetchTaskTarget for FetchResponseCollector { fn process_request_body(&mut self, _: &Request) {} fn process_request_eof(&mut self, _: &Request) {} fn process_response(&mut self, _: &Response) {} fn process_response_chunk(&mut self, _: Vec<u8>) {} /// Fired when the response is fully fetched fn process_response_eof(&mut self, response: &Response) { let _ = self.sender.send(response.clone()); } } fn fetch(request: &mut Request, dc: Option<Sender<DevtoolsControlMsg>>) -> Response { fetch_with_context(request, &new_fetch_context(dc, None)) } fn fetch_with_context(request: &mut Request, context: &FetchContext) -> Response { let (sender, receiver) = channel(); let mut target = FetchResponseCollector { sender: sender }; methods::fetch(request, &mut target, context); receiver.recv().unwrap() } fn fetch_with_cors_cache(request: &mut Request, cache: &mut CorsCache) -> Response { let (sender, receiver) = channel(); let mut target = FetchResponseCollector { sender: sender }; methods::fetch_with_cors_cache(request, cache, &mut target, &new_fetch_context(None, None)); receiver.recv().unwrap() } pub(crate) struct Server { pub close_channel: futures::sync::oneshot::Sender<()>, } impl Server { fn close(self) { self.close_channel.send(()).unwrap(); } } fn make_server<H>(handler: H) -> (Server, ServoUrl) where H: Fn(HyperRequest<Body>, &mut HyperResponse<Body>) + Send + Sync +'static, { let handler = Arc::new(handler); let listener = StdTcpListener::bind("0.0.0.0:0").unwrap(); let url_string = format!("http://localhost:{}", listener.local_addr().unwrap().port()); let url = ServoUrl::parse(&url_string).unwrap(); let (tx, rx) = futures::sync::oneshot::channel::<()>(); let server = HyperServer::from_tcp(listener) .unwrap() .serve(move || { let handler = handler.clone(); service_fn_ok(move |req: HyperRequest<Body>| { let mut response = HyperResponse::new(Vec::<u8>::new().into()); handler(req, &mut response); response }) }) .with_graceful_shutdown(rx) .map_err(|_| ()); HANDLE.lock().unwrap().spawn(server); let server = Server { close_channel: tx }; (server, url) } fn make_ssl_server<H>(handler: H, cert_path: PathBuf, key_path: PathBuf) -> (Server, ServoUrl) where H: Fn(HyperRequest<Body>, &mut HyperResponse<Body>) + Send + Sync +'static,
.map_err(|_| ()) .and_then(move |ssl| { Http::new() .serve_connection( ssl, service_fn_ok(move |req: HyperRequest<Body>| { let mut response = HyperResponse::new(Vec::<u8>::new().into()); handler(req, &mut response); response }), ) .map_err(|_| ()) }) }); let (tx, rx) = futures::sync::oneshot::channel::<()>(); let server = server .select(rx.map_err(|_| ())) .map(|_| ()) .map_err(|_| ()); HANDLE.lock().unwrap().spawn(server); let server = Server { close_channel: tx }; (server, url) }
{ let handler = Arc::new(handler); let listener = StdTcpListener::bind("[::0]:0").unwrap(); let listener = TcpListener::from_std(listener, &HANDLE.lock().unwrap().reactor()).unwrap(); let url_string = format!("http://localhost:{}", listener.local_addr().unwrap().port()); let url = ServoUrl::parse(&url_string).unwrap(); let server = listener.incoming().map_err(|_| ()).for_each(move |sock| { let mut ssl_builder = SslAcceptor::mozilla_modern(SslMethod::tls()).unwrap(); ssl_builder .set_certificate_file(&cert_path, SslFiletype::PEM) .unwrap(); ssl_builder .set_private_key_file(&key_path, SslFiletype::PEM) .unwrap(); let handler = handler.clone(); ssl_builder .build() .accept_async(sock)
identifier_body
main.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![cfg(test)] #[macro_use] extern crate lazy_static; mod cookie; mod cookie_http_state; mod data_loader; mod fetch; mod file_loader; mod filemanager_thread; mod hsts; mod http_loader; mod mime_classifier; mod resource_thread; mod subresource_integrity; use devtools_traits::DevtoolsControlMsg; use embedder_traits::resources::{self, Resource}; use embedder_traits::{EmbedderProxy, EventLoopWaker}; use futures::{Future, Stream}; use hyper::server::conn::Http; use hyper::server::Server as HyperServer; use hyper::service::service_fn_ok; use hyper::{Body, Request as HyperRequest, Response as HyperResponse}; use net::connector::create_ssl_connector_builder; use net::fetch::cors_cache::CorsCache; use net::fetch::methods::{self, CancellationListener, FetchContext}; use net::filemanager_thread::FileManager; use net::test::HttpState; use net_traits::request::Request; use net_traits::response::Response; use net_traits::FetchTaskTarget; use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod}; use servo_channel::{channel, Sender}; use servo_url::ServoUrl; use std::net::TcpListener as StdTcpListener; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use tokio::net::TcpListener; use tokio::runtime::Runtime; use tokio_openssl::SslAcceptorExt; lazy_static! { pub static ref HANDLE: Mutex<Runtime> = { Mutex::new(Runtime::new().unwrap()) }; } const DEFAULT_USER_AGENT: &'static str = "Such Browser. Very Layout. Wow."; struct
{ sender: Sender<Response>, } fn create_embedder_proxy() -> EmbedderProxy { let (sender, _) = channel(); let event_loop_waker = || { struct DummyEventLoopWaker {} impl DummyEventLoopWaker { fn new() -> DummyEventLoopWaker { DummyEventLoopWaker {} } } impl EventLoopWaker for DummyEventLoopWaker { fn wake(&self) {} fn clone(&self) -> Box<dyn EventLoopWaker + Send> { Box::new(DummyEventLoopWaker {}) } } Box::new(DummyEventLoopWaker::new()) }; EmbedderProxy { sender: sender, event_loop_waker: event_loop_waker(), } } fn new_fetch_context( dc: Option<Sender<DevtoolsControlMsg>>, fc: Option<EmbedderProxy>, ) -> FetchContext { let ssl_connector = create_ssl_connector_builder(&resources::read_string(Resource::SSLCertificates)); let sender = fc.unwrap_or_else(|| create_embedder_proxy()); FetchContext { state: Arc::new(HttpState::new(ssl_connector)), user_agent: DEFAULT_USER_AGENT.into(), devtools_chan: dc, filemanager: FileManager::new(sender), cancellation_listener: Arc::new(Mutex::new(CancellationListener::new(None))), } } impl FetchTaskTarget for FetchResponseCollector { fn process_request_body(&mut self, _: &Request) {} fn process_request_eof(&mut self, _: &Request) {} fn process_response(&mut self, _: &Response) {} fn process_response_chunk(&mut self, _: Vec<u8>) {} /// Fired when the response is fully fetched fn process_response_eof(&mut self, response: &Response) { let _ = self.sender.send(response.clone()); } } fn fetch(request: &mut Request, dc: Option<Sender<DevtoolsControlMsg>>) -> Response { fetch_with_context(request, &new_fetch_context(dc, None)) } fn fetch_with_context(request: &mut Request, context: &FetchContext) -> Response { let (sender, receiver) = channel(); let mut target = FetchResponseCollector { sender: sender }; methods::fetch(request, &mut target, context); receiver.recv().unwrap() } fn fetch_with_cors_cache(request: &mut Request, cache: &mut CorsCache) -> Response { let (sender, receiver) = channel(); let mut target = FetchResponseCollector { sender: sender }; methods::fetch_with_cors_cache(request, cache, &mut target, &new_fetch_context(None, None)); receiver.recv().unwrap() } pub(crate) struct Server { pub close_channel: futures::sync::oneshot::Sender<()>, } impl Server { fn close(self) { self.close_channel.send(()).unwrap(); } } fn make_server<H>(handler: H) -> (Server, ServoUrl) where H: Fn(HyperRequest<Body>, &mut HyperResponse<Body>) + Send + Sync +'static, { let handler = Arc::new(handler); let listener = StdTcpListener::bind("0.0.0.0:0").unwrap(); let url_string = format!("http://localhost:{}", listener.local_addr().unwrap().port()); let url = ServoUrl::parse(&url_string).unwrap(); let (tx, rx) = futures::sync::oneshot::channel::<()>(); let server = HyperServer::from_tcp(listener) .unwrap() .serve(move || { let handler = handler.clone(); service_fn_ok(move |req: HyperRequest<Body>| { let mut response = HyperResponse::new(Vec::<u8>::new().into()); handler(req, &mut response); response }) }) .with_graceful_shutdown(rx) .map_err(|_| ()); HANDLE.lock().unwrap().spawn(server); let server = Server { close_channel: tx }; (server, url) } fn make_ssl_server<H>(handler: H, cert_path: PathBuf, key_path: PathBuf) -> (Server, ServoUrl) where H: Fn(HyperRequest<Body>, &mut HyperResponse<Body>) + Send + Sync +'static, { let handler = Arc::new(handler); let listener = StdTcpListener::bind("[::0]:0").unwrap(); let listener = TcpListener::from_std(listener, &HANDLE.lock().unwrap().reactor()).unwrap(); let url_string = format!("http://localhost:{}", listener.local_addr().unwrap().port()); let url = ServoUrl::parse(&url_string).unwrap(); let server = listener.incoming().map_err(|_| ()).for_each(move |sock| { let mut ssl_builder = SslAcceptor::mozilla_modern(SslMethod::tls()).unwrap(); ssl_builder .set_certificate_file(&cert_path, SslFiletype::PEM) .unwrap(); ssl_builder .set_private_key_file(&key_path, SslFiletype::PEM) .unwrap(); let handler = handler.clone(); ssl_builder .build() .accept_async(sock) .map_err(|_| ()) .and_then(move |ssl| { Http::new() .serve_connection( ssl, service_fn_ok(move |req: HyperRequest<Body>| { let mut response = HyperResponse::new(Vec::<u8>::new().into()); handler(req, &mut response); response }), ) .map_err(|_| ()) }) }); let (tx, rx) = futures::sync::oneshot::channel::<()>(); let server = server .select(rx.map_err(|_| ())) .map(|_| ()) .map_err(|_| ()); HANDLE.lock().unwrap().spawn(server); let server = Server { close_channel: tx }; (server, url) }
FetchResponseCollector
identifier_name
main4.rs
fn main() { let value = std::env::args().nth(1); let convert_and_double = compose(convert, double); match convert_and_double(value) { Some(n) => println!("{}", n), None => println!("No value"), } } fn convert(n: Option<String>) -> Option<f32>
fn double(n: Option<f32>) -> Option<f32> { n.map(|n| n * 2.0) } fn compose<'f, T1, T2, T3, F1, F2>(a: F1, b: F2) -> Box<Fn(T1) -> T3 + 'f> where F1:Fn(T1) -> T2 + 'f, F2:Fn(T2) -> T3 + 'f { Box::new(move |input| b(a(input))) }
{ n.and_then(|n| n.parse().ok()) }
identifier_body
main4.rs
fn main() { let value = std::env::args().nth(1); let convert_and_double = compose(convert, double); match convert_and_double(value) { Some(n) => println!("{}", n), None => println!("No value"),
fn convert(n: Option<String>) -> Option<f32> { n.and_then(|n| n.parse().ok()) } fn double(n: Option<f32>) -> Option<f32> { n.map(|n| n * 2.0) } fn compose<'f, T1, T2, T3, F1, F2>(a: F1, b: F2) -> Box<Fn(T1) -> T3 + 'f> where F1:Fn(T1) -> T2 + 'f, F2:Fn(T2) -> T3 + 'f { Box::new(move |input| b(a(input))) }
} }
random_line_split
main4.rs
fn main() { let value = std::env::args().nth(1); let convert_and_double = compose(convert, double); match convert_and_double(value) { Some(n) => println!("{}", n), None => println!("No value"), } } fn convert(n: Option<String>) -> Option<f32> { n.and_then(|n| n.parse().ok()) } fn double(n: Option<f32>) -> Option<f32> { n.map(|n| n * 2.0) } fn
<'f, T1, T2, T3, F1, F2>(a: F1, b: F2) -> Box<Fn(T1) -> T3 + 'f> where F1:Fn(T1) -> T2 + 'f, F2:Fn(T2) -> T3 + 'f { Box::new(move |input| b(a(input))) }
compose
identifier_name
glass.rs
//! Defines a specular glass material //! //! # Scene Usage Example //! The specular glass material describes a thing glass surface type of material, //! not a solid block of glass (there is no absorption of light). The glass requires //! a reflective and emissive color along with a refrective index, eta. //! //! ```json //! "materials": [ //! { //! "name": "clear_glass", //! "type": "glass", //! "reflect": [1, 1, 1], //! "transmit": [1, 1, 1], //! "eta": 1.52 //! }, //! ... //! ] //! ``` use std::vec::Vec; use film::Colorf; use geometry::Intersection; use bxdf::{BxDF, BSDF, SpecularReflection, SpecularTransmission}; use bxdf::fresnel::{Dielectric, Fresnel}; use material::Material; /// The Glass material describes specularly transmissive and reflective glass material pub struct Glass { bxdfs: Vec<Box<BxDF + Send + Sync>>, eta: f32, } impl Glass { /// Create the glass material with the desired color and index of refraction /// `reflect`: color of reflected light /// `transmit`: color of transmitted light /// `eta`: refractive index of the material pub fn new(reflect: &Colorf, transmit: &Colorf, eta: f32) -> Glass { let mut bxdfs = Vec::new(); if!reflect.is_black()
if!transmit.is_black() { bxdfs.push(Box::new(SpecularTransmission::new(transmit, Dielectric::new(1.0, eta))) as Box<BxDF + Send + Sync>); } Glass { bxdfs: bxdfs, eta: eta } } } impl Material for Glass { fn bsdf<'a, 'b>(&'a self, hit: &Intersection<'a, 'b>) -> BSDF<'a> { BSDF::new(&self.bxdfs, self.eta, &hit.dg) } }
{ bxdfs.push(Box::new(SpecularReflection::new(reflect, Box::new(Dielectric::new(1.0, eta)) as Box<Fresnel + Send + Sync>)) as Box<BxDF + Send + Sync>); }
conditional_block
glass.rs
//! Defines a specular glass material //! //! # Scene Usage Example //! The specular glass material describes a thing glass surface type of material, //! not a solid block of glass (there is no absorption of light). The glass requires //! a reflective and emissive color along with a refrective index, eta. //! //! ```json //! "materials": [ //! { //! "name": "clear_glass", //! "type": "glass", //! "reflect": [1, 1, 1], //! "transmit": [1, 1, 1], //! "eta": 1.52 //! }, //! ... //! ] //! ``` use std::vec::Vec; use film::Colorf; use geometry::Intersection; use bxdf::{BxDF, BSDF, SpecularReflection, SpecularTransmission}; use bxdf::fresnel::{Dielectric, Fresnel}; use material::Material; /// The Glass material describes specularly transmissive and reflective glass material pub struct Glass { bxdfs: Vec<Box<BxDF + Send + Sync>>, eta: f32, } impl Glass { /// Create the glass material with the desired color and index of refraction /// `reflect`: color of reflected light /// `transmit`: color of transmitted light /// `eta`: refractive index of the material pub fn new(reflect: &Colorf, transmit: &Colorf, eta: f32) -> Glass
} impl Material for Glass { fn bsdf<'a, 'b>(&'a self, hit: &Intersection<'a, 'b>) -> BSDF<'a> { BSDF::new(&self.bxdfs, self.eta, &hit.dg) } }
{ let mut bxdfs = Vec::new(); if !reflect.is_black() { bxdfs.push(Box::new(SpecularReflection::new(reflect, Box::new(Dielectric::new(1.0, eta)) as Box<Fresnel + Send + Sync>)) as Box<BxDF + Send + Sync>); } if !transmit.is_black() { bxdfs.push(Box::new(SpecularTransmission::new(transmit, Dielectric::new(1.0, eta))) as Box<BxDF + Send + Sync>); } Glass { bxdfs: bxdfs, eta: eta } }
identifier_body
glass.rs
//! Defines a specular glass material //! //! # Scene Usage Example //! The specular glass material describes a thing glass surface type of material, //! not a solid block of glass (there is no absorption of light). The glass requires //! a reflective and emissive color along with a refrective index, eta. //! //! ```json //! "materials": [ //! { //! "name": "clear_glass", //! "type": "glass", //! "reflect": [1, 1, 1], //! "transmit": [1, 1, 1], //! "eta": 1.52 //! }, //! ... //! ] //! ``` use std::vec::Vec; use film::Colorf; use geometry::Intersection; use bxdf::{BxDF, BSDF, SpecularReflection, SpecularTransmission}; use bxdf::fresnel::{Dielectric, Fresnel}; use material::Material; /// The Glass material describes specularly transmissive and reflective glass material pub struct Glass { bxdfs: Vec<Box<BxDF + Send + Sync>>, eta: f32, } impl Glass { /// Create the glass material with the desired color and index of refraction /// `reflect`: color of reflected light /// `transmit`: color of transmitted light /// `eta`: refractive index of the material pub fn new(reflect: &Colorf, transmit: &Colorf, eta: f32) -> Glass { let mut bxdfs = Vec::new(); if!reflect.is_black() { bxdfs.push(Box::new(SpecularReflection::new(reflect, Box::new(Dielectric::new(1.0, eta)) as Box<Fresnel + Send + Sync>)) as Box<BxDF + Send + Sync>); } if!transmit.is_black() { bxdfs.push(Box::new(SpecularTransmission::new(transmit, Dielectric::new(1.0, eta))) as Box<BxDF + Send + Sync>); } Glass { bxdfs: bxdfs, eta: eta } } } impl Material for Glass { fn
<'a, 'b>(&'a self, hit: &Intersection<'a, 'b>) -> BSDF<'a> { BSDF::new(&self.bxdfs, self.eta, &hit.dg) } }
bsdf
identifier_name
glass.rs
//! Defines a specular glass material //! //! # Scene Usage Example //! The specular glass material describes a thing glass surface type of material, //! not a solid block of glass (there is no absorption of light). The glass requires //! a reflective and emissive color along with a refrective index, eta. //! //! ```json //! "materials": [ //! { //! "name": "clear_glass", //! "type": "glass", //! "reflect": [1, 1, 1], //! "transmit": [1, 1, 1], //! "eta": 1.52 //! }, //! ... //! ] //! ``` use std::vec::Vec; use film::Colorf; use geometry::Intersection; use bxdf::{BxDF, BSDF, SpecularReflection, SpecularTransmission};
/// The Glass material describes specularly transmissive and reflective glass material pub struct Glass { bxdfs: Vec<Box<BxDF + Send + Sync>>, eta: f32, } impl Glass { /// Create the glass material with the desired color and index of refraction /// `reflect`: color of reflected light /// `transmit`: color of transmitted light /// `eta`: refractive index of the material pub fn new(reflect: &Colorf, transmit: &Colorf, eta: f32) -> Glass { let mut bxdfs = Vec::new(); if!reflect.is_black() { bxdfs.push(Box::new(SpecularReflection::new(reflect, Box::new(Dielectric::new(1.0, eta)) as Box<Fresnel + Send + Sync>)) as Box<BxDF + Send + Sync>); } if!transmit.is_black() { bxdfs.push(Box::new(SpecularTransmission::new(transmit, Dielectric::new(1.0, eta))) as Box<BxDF + Send + Sync>); } Glass { bxdfs: bxdfs, eta: eta } } } impl Material for Glass { fn bsdf<'a, 'b>(&'a self, hit: &Intersection<'a, 'b>) -> BSDF<'a> { BSDF::new(&self.bxdfs, self.eta, &hit.dg) } }
use bxdf::fresnel::{Dielectric, Fresnel}; use material::Material;
random_line_split
error.rs
// This is a part of rust-encoding. // Copyright (c) 2013-2015, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! A placeholder encoding that returns encoder/decoder error for every case. use libtww::std::convert::Into; use types::*; /// An encoding that returns encoder/decoder error for every case. #[derive(Clone, Copy)] pub struct ErrorEncoding; impl Encoding for ErrorEncoding { fn name(&self) -> &'static str { "error" } fn raw_encoder(&self) -> Box<RawEncoder> { ErrorEncoder::new() } fn raw_decoder(&self) -> Box<RawDecoder> { ErrorDecoder::new() } } /// An encoder that always returns error. #[derive(Clone, Copy)] pub struct ErrorEncoder; impl ErrorEncoder { pub fn new() -> Box<RawEncoder> { Box::new(ErrorEncoder) } } impl RawEncoder for ErrorEncoder { fn from_self(&self) -> Box<RawEncoder>
fn raw_feed(&mut self, input: &str, _output: &mut ByteWriter) -> (usize, Option<CodecError>) { if let Some(ch) = input.chars().next() { (0, Some(CodecError { upto: ch.len_utf8() as isize, cause: "unrepresentable character".into(), })) } else { (0, None) } } fn raw_finish(&mut self, _output: &mut ByteWriter) -> Option<CodecError> { None } } /// A decoder that always returns error. #[derive(Clone, Copy)] pub struct ErrorDecoder; impl ErrorDecoder { pub fn new() -> Box<RawDecoder> { Box::new(ErrorDecoder) } } impl RawDecoder for ErrorDecoder { fn from_self(&self) -> Box<RawDecoder> { ErrorDecoder::new() } fn raw_feed(&mut self, input: &[u8], _output: &mut StringWriter) -> (usize, Option<CodecError>) { if input.len() > 0 { (0, Some(CodecError { upto: 1, cause: "invalid sequence".into(), })) } else { (0, None) } } fn raw_finish(&mut self, _output: &mut StringWriter) -> Option<CodecError> { None } } #[cfg(test)] mod tests { use super::ErrorEncoding; use types::*; #[test] fn test_encoder() { let mut e = ErrorEncoding.raw_encoder(); assert_feed_err!(e, "", "A", "", []); assert_feed_err!(e, "", "B", "C", []); assert_feed_ok!(e, "", "", []); assert_feed_err!(e, "", "\u{a0}", "", []); assert_finish_ok!(e, []); } #[test] fn test_decoder() { let mut d = ErrorEncoding.raw_decoder(); assert_feed_err!(d, [], [0x41], [], ""); assert_feed_err!(d, [], [0x42], [0x43], ""); assert_feed_ok!(d, [], [], ""); assert_feed_err!(d, [], [0xa0], [], ""); assert_finish_ok!(d, ""); } }
{ ErrorEncoder::new() }
identifier_body
error.rs
// This is a part of rust-encoding. // Copyright (c) 2013-2015, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! A placeholder encoding that returns encoder/decoder error for every case. use libtww::std::convert::Into; use types::*; /// An encoding that returns encoder/decoder error for every case. #[derive(Clone, Copy)] pub struct ErrorEncoding; impl Encoding for ErrorEncoding { fn name(&self) -> &'static str { "error" } fn raw_encoder(&self) -> Box<RawEncoder> { ErrorEncoder::new() } fn raw_decoder(&self) -> Box<RawDecoder> { ErrorDecoder::new() } } /// An encoder that always returns error. #[derive(Clone, Copy)] pub struct ErrorEncoder; impl ErrorEncoder { pub fn new() -> Box<RawEncoder> { Box::new(ErrorEncoder) } } impl RawEncoder for ErrorEncoder { fn from_self(&self) -> Box<RawEncoder> { ErrorEncoder::new() } fn raw_feed(&mut self, input: &str, _output: &mut ByteWriter) -> (usize, Option<CodecError>) { if let Some(ch) = input.chars().next() { (0, Some(CodecError { upto: ch.len_utf8() as isize, cause: "unrepresentable character".into(), })) } else
} fn raw_finish(&mut self, _output: &mut ByteWriter) -> Option<CodecError> { None } } /// A decoder that always returns error. #[derive(Clone, Copy)] pub struct ErrorDecoder; impl ErrorDecoder { pub fn new() -> Box<RawDecoder> { Box::new(ErrorDecoder) } } impl RawDecoder for ErrorDecoder { fn from_self(&self) -> Box<RawDecoder> { ErrorDecoder::new() } fn raw_feed(&mut self, input: &[u8], _output: &mut StringWriter) -> (usize, Option<CodecError>) { if input.len() > 0 { (0, Some(CodecError { upto: 1, cause: "invalid sequence".into(), })) } else { (0, None) } } fn raw_finish(&mut self, _output: &mut StringWriter) -> Option<CodecError> { None } } #[cfg(test)] mod tests { use super::ErrorEncoding; use types::*; #[test] fn test_encoder() { let mut e = ErrorEncoding.raw_encoder(); assert_feed_err!(e, "", "A", "", []); assert_feed_err!(e, "", "B", "C", []); assert_feed_ok!(e, "", "", []); assert_feed_err!(e, "", "\u{a0}", "", []); assert_finish_ok!(e, []); } #[test] fn test_decoder() { let mut d = ErrorEncoding.raw_decoder(); assert_feed_err!(d, [], [0x41], [], ""); assert_feed_err!(d, [], [0x42], [0x43], ""); assert_feed_ok!(d, [], [], ""); assert_feed_err!(d, [], [0xa0], [], ""); assert_finish_ok!(d, ""); } }
{ (0, None) }
conditional_block
error.rs
// This is a part of rust-encoding. // Copyright (c) 2013-2015, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! A placeholder encoding that returns encoder/decoder error for every case. use libtww::std::convert::Into; use types::*; /// An encoding that returns encoder/decoder error for every case. #[derive(Clone, Copy)] pub struct ErrorEncoding; impl Encoding for ErrorEncoding { fn name(&self) -> &'static str { "error" }
ErrorEncoder::new() } fn raw_decoder(&self) -> Box<RawDecoder> { ErrorDecoder::new() } } /// An encoder that always returns error. #[derive(Clone, Copy)] pub struct ErrorEncoder; impl ErrorEncoder { pub fn new() -> Box<RawEncoder> { Box::new(ErrorEncoder) } } impl RawEncoder for ErrorEncoder { fn from_self(&self) -> Box<RawEncoder> { ErrorEncoder::new() } fn raw_feed(&mut self, input: &str, _output: &mut ByteWriter) -> (usize, Option<CodecError>) { if let Some(ch) = input.chars().next() { (0, Some(CodecError { upto: ch.len_utf8() as isize, cause: "unrepresentable character".into(), })) } else { (0, None) } } fn raw_finish(&mut self, _output: &mut ByteWriter) -> Option<CodecError> { None } } /// A decoder that always returns error. #[derive(Clone, Copy)] pub struct ErrorDecoder; impl ErrorDecoder { pub fn new() -> Box<RawDecoder> { Box::new(ErrorDecoder) } } impl RawDecoder for ErrorDecoder { fn from_self(&self) -> Box<RawDecoder> { ErrorDecoder::new() } fn raw_feed(&mut self, input: &[u8], _output: &mut StringWriter) -> (usize, Option<CodecError>) { if input.len() > 0 { (0, Some(CodecError { upto: 1, cause: "invalid sequence".into(), })) } else { (0, None) } } fn raw_finish(&mut self, _output: &mut StringWriter) -> Option<CodecError> { None } } #[cfg(test)] mod tests { use super::ErrorEncoding; use types::*; #[test] fn test_encoder() { let mut e = ErrorEncoding.raw_encoder(); assert_feed_err!(e, "", "A", "", []); assert_feed_err!(e, "", "B", "C", []); assert_feed_ok!(e, "", "", []); assert_feed_err!(e, "", "\u{a0}", "", []); assert_finish_ok!(e, []); } #[test] fn test_decoder() { let mut d = ErrorEncoding.raw_decoder(); assert_feed_err!(d, [], [0x41], [], ""); assert_feed_err!(d, [], [0x42], [0x43], ""); assert_feed_ok!(d, [], [], ""); assert_feed_err!(d, [], [0xa0], [], ""); assert_finish_ok!(d, ""); } }
fn raw_encoder(&self) -> Box<RawEncoder> {
random_line_split
error.rs
// This is a part of rust-encoding. // Copyright (c) 2013-2015, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! A placeholder encoding that returns encoder/decoder error for every case. use libtww::std::convert::Into; use types::*; /// An encoding that returns encoder/decoder error for every case. #[derive(Clone, Copy)] pub struct ErrorEncoding; impl Encoding for ErrorEncoding { fn name(&self) -> &'static str { "error" } fn raw_encoder(&self) -> Box<RawEncoder> { ErrorEncoder::new() } fn raw_decoder(&self) -> Box<RawDecoder> { ErrorDecoder::new() } } /// An encoder that always returns error. #[derive(Clone, Copy)] pub struct ErrorEncoder; impl ErrorEncoder { pub fn new() -> Box<RawEncoder> { Box::new(ErrorEncoder) } } impl RawEncoder for ErrorEncoder { fn from_self(&self) -> Box<RawEncoder> { ErrorEncoder::new() } fn raw_feed(&mut self, input: &str, _output: &mut ByteWriter) -> (usize, Option<CodecError>) { if let Some(ch) = input.chars().next() { (0, Some(CodecError { upto: ch.len_utf8() as isize, cause: "unrepresentable character".into(), })) } else { (0, None) } } fn
(&mut self, _output: &mut ByteWriter) -> Option<CodecError> { None } } /// A decoder that always returns error. #[derive(Clone, Copy)] pub struct ErrorDecoder; impl ErrorDecoder { pub fn new() -> Box<RawDecoder> { Box::new(ErrorDecoder) } } impl RawDecoder for ErrorDecoder { fn from_self(&self) -> Box<RawDecoder> { ErrorDecoder::new() } fn raw_feed(&mut self, input: &[u8], _output: &mut StringWriter) -> (usize, Option<CodecError>) { if input.len() > 0 { (0, Some(CodecError { upto: 1, cause: "invalid sequence".into(), })) } else { (0, None) } } fn raw_finish(&mut self, _output: &mut StringWriter) -> Option<CodecError> { None } } #[cfg(test)] mod tests { use super::ErrorEncoding; use types::*; #[test] fn test_encoder() { let mut e = ErrorEncoding.raw_encoder(); assert_feed_err!(e, "", "A", "", []); assert_feed_err!(e, "", "B", "C", []); assert_feed_ok!(e, "", "", []); assert_feed_err!(e, "", "\u{a0}", "", []); assert_finish_ok!(e, []); } #[test] fn test_decoder() { let mut d = ErrorEncoding.raw_decoder(); assert_feed_err!(d, [], [0x41], [], ""); assert_feed_err!(d, [], [0x42], [0x43], ""); assert_feed_ok!(d, [], [], ""); assert_feed_err!(d, [], [0xa0], [], ""); assert_finish_ok!(d, ""); } }
raw_finish
identifier_name
domtokenlist.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::bindings::codegen::Bindings::DOMTokenListBinding; use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods; use dom::bindings::error::Error::{InvalidCharacter, Syntax}; use dom::bindings::error::{ErrorResult, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::element::Element; use dom::node::window_from_node; use std::borrow::ToOwned; use string_cache::Atom; use util::str::{DOMString, HTML_SPACE_CHARACTERS, str_join}; #[dom_struct] pub struct DOMTokenList { reflector_: Reflector, element: JS<Element>, local_name: Atom, } impl DOMTokenList { pub fn new_inherited(element: &Element, local_name: Atom) -> DOMTokenList { DOMTokenList { reflector_: Reflector::new(), element: JS::from_ref(element), local_name: local_name, } } pub fn new(element: &Element, local_name: &Atom) -> Root<DOMTokenList> { let window = window_from_node(element); reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()), GlobalRef::Window(window.r()), DOMTokenListBinding::Wrap) } fn attribute(&self) -> Option<Root<Attr>> { let element = self.element.root(); element.r().get_attribute(&ns!(""), &self.local_name) } fn check_token_exceptions(&self, token: &str) -> Fallible<Atom> { match token { "" => Err(Syntax), slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(InvalidCharacter), slice => Ok(Atom::from_slice(slice)) } } } // https://dom.spec.whatwg.org/#domtokenlist impl DOMTokenListMethods for DOMTokenList { // https://dom.spec.whatwg.org/#dom-domtokenlist-length fn Length(&self) -> u32 { self.attribute().map(|attr| { let attr = attr.r(); attr.value().as_tokens().len() }).unwrap_or(0) as u32 } // https://dom.spec.whatwg.org/#dom-domtokenlist-item fn Item(&self, index: u32) -> Option<DOMString> { self.attribute().and_then(|attr| { let attr = attr.r(); Some(attr.value().as_tokens()).and_then(|tokens| { tokens.get(index as usize).map(|token| (**token).to_owned()) }) }) } // https://dom.spec.whatwg.org/#dom-domtokenlist-contains fn Contains(&self, token: DOMString) -> Fallible<bool> { self.check_token_exceptions(&token).map(|token| { self.attribute().map(|attr| { let attr = attr.r(); attr.value() .as_tokens() .iter() .any(|atom: &Atom| *atom == token) }).unwrap_or(false) }) } // https://dom.spec.whatwg.org/#dom-domtokenlist-add fn Add(&self, tokens: Vec<DOMString>) -> ErrorResult { let element = self.element.root(); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name); for token in &tokens { let token = try!(self.check_token_exceptions(&token)); if!atoms.iter().any(|atom| *atom == token) { atoms.push(token); } } element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(()) } // https://dom.spec.whatwg.org/#dom-domtokenlist-remove fn Remove(&self, tokens: Vec<DOMString>) -> ErrorResult
// https://dom.spec.whatwg.org/#dom-domtokenlist-toggle fn Toggle(&self, token: DOMString, force: Option<bool>) -> Fallible<bool> { let element = self.element.root(); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name); let token = try!(self.check_token_exceptions(&token)); match atoms.iter().position(|atom| *atom == token) { Some(index) => match force { Some(true) => Ok(true), _ => { atoms.remove(index); element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(false) } }, None => match force { Some(false) => Ok(false), _ => { atoms.push(token); element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(true) } } } } // https://dom.spec.whatwg.org/#stringification-behavior fn Stringifier(&self) -> DOMString { let tokenlist = self.element.root().r().get_tokenlist_attribute(&self.local_name); str_join(&tokenlist, "\x20") } // check-tidy: no specs after this line fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option<DOMString> { let item = self.Item(index); *found = item.is_some(); item } }
{ let element = self.element.root(); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name); for token in &tokens { let token = try!(self.check_token_exceptions(&token)); atoms.iter().position(|atom| *atom == token).map(|index| { atoms.remove(index) }); } element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(()) }
identifier_body
domtokenlist.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::bindings::codegen::Bindings::DOMTokenListBinding; use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods; use dom::bindings::error::Error::{InvalidCharacter, Syntax}; use dom::bindings::error::{ErrorResult, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::element::Element; use dom::node::window_from_node; use std::borrow::ToOwned; use string_cache::Atom; use util::str::{DOMString, HTML_SPACE_CHARACTERS, str_join}; #[dom_struct] pub struct DOMTokenList { reflector_: Reflector, element: JS<Element>, local_name: Atom, } impl DOMTokenList { pub fn new_inherited(element: &Element, local_name: Atom) -> DOMTokenList { DOMTokenList { reflector_: Reflector::new(), element: JS::from_ref(element), local_name: local_name, } } pub fn new(element: &Element, local_name: &Atom) -> Root<DOMTokenList> { let window = window_from_node(element); reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()), GlobalRef::Window(window.r()), DOMTokenListBinding::Wrap) } fn attribute(&self) -> Option<Root<Attr>> { let element = self.element.root(); element.r().get_attribute(&ns!(""), &self.local_name) } fn check_token_exceptions(&self, token: &str) -> Fallible<Atom> { match token { "" => Err(Syntax), slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(InvalidCharacter), slice => Ok(Atom::from_slice(slice)) } } } // https://dom.spec.whatwg.org/#domtokenlist impl DOMTokenListMethods for DOMTokenList { // https://dom.spec.whatwg.org/#dom-domtokenlist-length fn Length(&self) -> u32 { self.attribute().map(|attr| { let attr = attr.r(); attr.value().as_tokens().len() }).unwrap_or(0) as u32 } // https://dom.spec.whatwg.org/#dom-domtokenlist-item fn Item(&self, index: u32) -> Option<DOMString> { self.attribute().and_then(|attr| { let attr = attr.r(); Some(attr.value().as_tokens()).and_then(|tokens| { tokens.get(index as usize).map(|token| (**token).to_owned()) }) }) } // https://dom.spec.whatwg.org/#dom-domtokenlist-contains fn Contains(&self, token: DOMString) -> Fallible<bool> { self.check_token_exceptions(&token).map(|token| { self.attribute().map(|attr| { let attr = attr.r(); attr.value() .as_tokens() .iter() .any(|atom: &Atom| *atom == token) }).unwrap_or(false) }) } // https://dom.spec.whatwg.org/#dom-domtokenlist-add fn
(&self, tokens: Vec<DOMString>) -> ErrorResult { let element = self.element.root(); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name); for token in &tokens { let token = try!(self.check_token_exceptions(&token)); if!atoms.iter().any(|atom| *atom == token) { atoms.push(token); } } element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(()) } // https://dom.spec.whatwg.org/#dom-domtokenlist-remove fn Remove(&self, tokens: Vec<DOMString>) -> ErrorResult { let element = self.element.root(); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name); for token in &tokens { let token = try!(self.check_token_exceptions(&token)); atoms.iter().position(|atom| *atom == token).map(|index| { atoms.remove(index) }); } element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(()) } // https://dom.spec.whatwg.org/#dom-domtokenlist-toggle fn Toggle(&self, token: DOMString, force: Option<bool>) -> Fallible<bool> { let element = self.element.root(); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name); let token = try!(self.check_token_exceptions(&token)); match atoms.iter().position(|atom| *atom == token) { Some(index) => match force { Some(true) => Ok(true), _ => { atoms.remove(index); element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(false) } }, None => match force { Some(false) => Ok(false), _ => { atoms.push(token); element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(true) } } } } // https://dom.spec.whatwg.org/#stringification-behavior fn Stringifier(&self) -> DOMString { let tokenlist = self.element.root().r().get_tokenlist_attribute(&self.local_name); str_join(&tokenlist, "\x20") } // check-tidy: no specs after this line fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option<DOMString> { let item = self.Item(index); *found = item.is_some(); item } }
Add
identifier_name
domtokenlist.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::bindings::codegen::Bindings::DOMTokenListBinding; use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods; use dom::bindings::error::Error::{InvalidCharacter, Syntax}; use dom::bindings::error::{ErrorResult, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::element::Element; use dom::node::window_from_node; use std::borrow::ToOwned; use string_cache::Atom; use util::str::{DOMString, HTML_SPACE_CHARACTERS, str_join}; #[dom_struct] pub struct DOMTokenList { reflector_: Reflector, element: JS<Element>, local_name: Atom, } impl DOMTokenList { pub fn new_inherited(element: &Element, local_name: Atom) -> DOMTokenList { DOMTokenList { reflector_: Reflector::new(), element: JS::from_ref(element), local_name: local_name, } } pub fn new(element: &Element, local_name: &Atom) -> Root<DOMTokenList> { let window = window_from_node(element); reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()), GlobalRef::Window(window.r()), DOMTokenListBinding::Wrap) } fn attribute(&self) -> Option<Root<Attr>> { let element = self.element.root(); element.r().get_attribute(&ns!(""), &self.local_name) } fn check_token_exceptions(&self, token: &str) -> Fallible<Atom> { match token { "" => Err(Syntax), slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(InvalidCharacter), slice => Ok(Atom::from_slice(slice)) } } } // https://dom.spec.whatwg.org/#domtokenlist impl DOMTokenListMethods for DOMTokenList { // https://dom.spec.whatwg.org/#dom-domtokenlist-length fn Length(&self) -> u32 { self.attribute().map(|attr| { let attr = attr.r(); attr.value().as_tokens().len() }).unwrap_or(0) as u32 } // https://dom.spec.whatwg.org/#dom-domtokenlist-item fn Item(&self, index: u32) -> Option<DOMString> { self.attribute().and_then(|attr| { let attr = attr.r(); Some(attr.value().as_tokens()).and_then(|tokens| { tokens.get(index as usize).map(|token| (**token).to_owned()) }) }) } // https://dom.spec.whatwg.org/#dom-domtokenlist-contains fn Contains(&self, token: DOMString) -> Fallible<bool> { self.check_token_exceptions(&token).map(|token| { self.attribute().map(|attr| { let attr = attr.r(); attr.value() .as_tokens() .iter() .any(|atom: &Atom| *atom == token) }).unwrap_or(false) }) } // https://dom.spec.whatwg.org/#dom-domtokenlist-add fn Add(&self, tokens: Vec<DOMString>) -> ErrorResult { let element = self.element.root(); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name); for token in &tokens { let token = try!(self.check_token_exceptions(&token)); if!atoms.iter().any(|atom| *atom == token) { atoms.push(token); } } element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(()) } // https://dom.spec.whatwg.org/#dom-domtokenlist-remove fn Remove(&self, tokens: Vec<DOMString>) -> ErrorResult { let element = self.element.root(); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name); for token in &tokens { let token = try!(self.check_token_exceptions(&token)); atoms.iter().position(|atom| *atom == token).map(|index| { atoms.remove(index) }); } element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(()) } // https://dom.spec.whatwg.org/#dom-domtokenlist-toggle fn Toggle(&self, token: DOMString, force: Option<bool>) -> Fallible<bool> { let element = self.element.root(); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name); let token = try!(self.check_token_exceptions(&token)); match atoms.iter().position(|atom| *atom == token) { Some(index) => match force { Some(true) => Ok(true), _ => { atoms.remove(index); element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(false) } }, None => match force {
atoms.push(token); element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(true) } } } } // https://dom.spec.whatwg.org/#stringification-behavior fn Stringifier(&self) -> DOMString { let tokenlist = self.element.root().r().get_tokenlist_attribute(&self.local_name); str_join(&tokenlist, "\x20") } // check-tidy: no specs after this line fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option<DOMString> { let item = self.Item(index); *found = item.is_some(); item } }
Some(false) => Ok(false), _ => {
random_line_split
domtokenlist.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::bindings::codegen::Bindings::DOMTokenListBinding; use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods; use dom::bindings::error::Error::{InvalidCharacter, Syntax}; use dom::bindings::error::{ErrorResult, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::element::Element; use dom::node::window_from_node; use std::borrow::ToOwned; use string_cache::Atom; use util::str::{DOMString, HTML_SPACE_CHARACTERS, str_join}; #[dom_struct] pub struct DOMTokenList { reflector_: Reflector, element: JS<Element>, local_name: Atom, } impl DOMTokenList { pub fn new_inherited(element: &Element, local_name: Atom) -> DOMTokenList { DOMTokenList { reflector_: Reflector::new(), element: JS::from_ref(element), local_name: local_name, } } pub fn new(element: &Element, local_name: &Atom) -> Root<DOMTokenList> { let window = window_from_node(element); reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()), GlobalRef::Window(window.r()), DOMTokenListBinding::Wrap) } fn attribute(&self) -> Option<Root<Attr>> { let element = self.element.root(); element.r().get_attribute(&ns!(""), &self.local_name) } fn check_token_exceptions(&self, token: &str) -> Fallible<Atom> { match token { "" => Err(Syntax), slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(InvalidCharacter), slice => Ok(Atom::from_slice(slice)) } } } // https://dom.spec.whatwg.org/#domtokenlist impl DOMTokenListMethods for DOMTokenList { // https://dom.spec.whatwg.org/#dom-domtokenlist-length fn Length(&self) -> u32 { self.attribute().map(|attr| { let attr = attr.r(); attr.value().as_tokens().len() }).unwrap_or(0) as u32 } // https://dom.spec.whatwg.org/#dom-domtokenlist-item fn Item(&self, index: u32) -> Option<DOMString> { self.attribute().and_then(|attr| { let attr = attr.r(); Some(attr.value().as_tokens()).and_then(|tokens| { tokens.get(index as usize).map(|token| (**token).to_owned()) }) }) } // https://dom.spec.whatwg.org/#dom-domtokenlist-contains fn Contains(&self, token: DOMString) -> Fallible<bool> { self.check_token_exceptions(&token).map(|token| { self.attribute().map(|attr| { let attr = attr.r(); attr.value() .as_tokens() .iter() .any(|atom: &Atom| *atom == token) }).unwrap_or(false) }) } // https://dom.spec.whatwg.org/#dom-domtokenlist-add fn Add(&self, tokens: Vec<DOMString>) -> ErrorResult { let element = self.element.root(); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name); for token in &tokens { let token = try!(self.check_token_exceptions(&token)); if!atoms.iter().any(|atom| *atom == token) { atoms.push(token); } } element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(()) } // https://dom.spec.whatwg.org/#dom-domtokenlist-remove fn Remove(&self, tokens: Vec<DOMString>) -> ErrorResult { let element = self.element.root(); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name); for token in &tokens { let token = try!(self.check_token_exceptions(&token)); atoms.iter().position(|atom| *atom == token).map(|index| { atoms.remove(index) }); } element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(()) } // https://dom.spec.whatwg.org/#dom-domtokenlist-toggle fn Toggle(&self, token: DOMString, force: Option<bool>) -> Fallible<bool> { let element = self.element.root(); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name); let token = try!(self.check_token_exceptions(&token)); match atoms.iter().position(|atom| *atom == token) { Some(index) => match force { Some(true) => Ok(true), _ => { atoms.remove(index); element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(false) } }, None => match force { Some(false) => Ok(false), _ =>
} } } // https://dom.spec.whatwg.org/#stringification-behavior fn Stringifier(&self) -> DOMString { let tokenlist = self.element.root().r().get_tokenlist_attribute(&self.local_name); str_join(&tokenlist, "\x20") } // check-tidy: no specs after this line fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option<DOMString> { let item = self.Item(index); *found = item.is_some(); item } }
{ atoms.push(token); element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(true) }
conditional_block
log.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ extern crate libc; use std::ffi::CString; use std::path::Path; use core::*; #[derive(Debug)] pub enum Level { NotSet = -1, None = 0, Emergency, Alert, Critical, Error, Warning, Notice, Info, Perf, Config, Debug, } pub static mut LEVEL: i32 = Level::NotSet as i32; pub fn get_log_level() -> i32 { unsafe { LEVEL } } fn basename(filename: &str) -> &str { let path = Path::new(filename); for os_str in path.file_name() { for basename in os_str.to_str() { return basename; } } return filename; } pub fn sclog(level: Level, file: &str, line: u32, function: &str, code: i32, message: &str) { let filename = basename(file); sc_log_message(level, filename, line, function, code, message); } /// Return the function name, but for now just return <rust> as Rust /// has no macro to return the function name, but may in the future, /// see: https://github.com/rust-lang/rfcs/pull/1719 macro_rules!function { () => {{ "<rust>" }} } #[macro_export] macro_rules!do_log { ($level:expr, $file:expr, $line:expr, $function:expr, $code:expr, $($arg:tt)*) => { if get_log_level() >= $level as i32 { sclog($level, $file, $line, $function, $code, &(format!($($arg)*))); } } } #[macro_export] macro_rules!SCLogNotice { ($($arg:tt)*) => { do_log!(Level::Notice, file!(), line!(), function!(), 0, $($arg)*); } } #[macro_export] macro_rules!SCLogInfo { ($($arg:tt)*) => { do_log!(Level::Info, file!(), line!(), function!(), 0, $($arg)*); } } #[macro_export] macro_rules!SCLogPerf { ($($arg:tt)*) => { do_log!(Level::Perf, file!(), line!(), function!(), 0, $($arg)*); } } #[macro_export] macro_rules!SCLogConfig { ($($arg:tt)*) => { do_log!(Level::Config, file!(), line!(), function!(), 0, $($arg)*); } } #[macro_export] macro_rules!SCLogDebug { ($($arg:tt)*) => { do_log!(Level::Debug, file!(), line!(), function!(), 0, $($arg)*); } } #[no_mangle] pub extern "C" fn rs_log_set_level(level: i32) { unsafe { LEVEL = level; } } pub fn log_set_level(level: Level) { rs_log_set_level(level as i32); } /// SCLogMessage wrapper. If the Suricata C context is not registered /// a more basic log format will be used (for example, when running /// Rust unit tests). pub fn sc_log_message(level: Level, filename: &str, line: libc::c_uint, function: &str, code: libc::c_int, message: &str) -> libc::c_int
println!("{}:{} <{:?}> -- {}", filename, line, level, message); return 0; } // Convert a &str into a CString by first stripping NUL bytes. fn to_safe_cstring(val: &str) -> CString { let mut safe = Vec::with_capacity(val.len()); for c in val.as_bytes() { if *c!= 0 { safe.push(*c); } } match CString::new(safe) { Ok(cstr) => cstr, _ => { CString::new("<failed to encode string>").unwrap() } } }
{ unsafe { if let Some(c) = SC { return (c.SCLogMessage)( level as i32, to_safe_cstring(filename).as_ptr(), line, to_safe_cstring(function).as_ptr(), code, to_safe_cstring(message).as_ptr()); } } // Fall back if the Suricata C context is not registered which is // the case when Rust unit tests are running. // // We don't log the time right now as I don't think it can be done // with Rust 1.7.0 without using an external crate. With Rust // 1.8.0 and newer we can unix UNIX_EPOCH.elapsed() to get the // unix time.
identifier_body
log.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ extern crate libc; use std::ffi::CString; use std::path::Path; use core::*; #[derive(Debug)] pub enum Level { NotSet = -1, None = 0, Emergency, Alert, Critical, Error, Warning, Notice, Info, Perf, Config, Debug, } pub static mut LEVEL: i32 = Level::NotSet as i32; pub fn get_log_level() -> i32 { unsafe { LEVEL } } fn basename(filename: &str) -> &str { let path = Path::new(filename); for os_str in path.file_name() { for basename in os_str.to_str() { return basename; } } return filename; } pub fn sclog(level: Level, file: &str, line: u32, function: &str, code: i32, message: &str) { let filename = basename(file); sc_log_message(level, filename, line, function, code, message); } /// Return the function name, but for now just return <rust> as Rust /// has no macro to return the function name, but may in the future, /// see: https://github.com/rust-lang/rfcs/pull/1719 macro_rules!function { () => {{ "<rust>" }} } #[macro_export] macro_rules!do_log { ($level:expr, $file:expr, $line:expr, $function:expr, $code:expr, $($arg:tt)*) => { if get_log_level() >= $level as i32 { sclog($level, $file, $line, $function, $code, &(format!($($arg)*))); } } } #[macro_export] macro_rules!SCLogNotice { ($($arg:tt)*) => { do_log!(Level::Notice, file!(), line!(), function!(), 0, $($arg)*); } } #[macro_export] macro_rules!SCLogInfo { ($($arg:tt)*) => { do_log!(Level::Info, file!(), line!(), function!(), 0, $($arg)*); } } #[macro_export] macro_rules!SCLogPerf { ($($arg:tt)*) => { do_log!(Level::Perf, file!(), line!(), function!(), 0, $($arg)*); } } #[macro_export] macro_rules!SCLogConfig { ($($arg:tt)*) => { do_log!(Level::Config, file!(), line!(), function!(), 0, $($arg)*); } } #[macro_export] macro_rules!SCLogDebug { ($($arg:tt)*) => { do_log!(Level::Debug, file!(), line!(), function!(), 0, $($arg)*); } } #[no_mangle] pub extern "C" fn rs_log_set_level(level: i32) { unsafe { LEVEL = level; } } pub fn log_set_level(level: Level) { rs_log_set_level(level as i32); } /// SCLogMessage wrapper. If the Suricata C context is not registered /// a more basic log format will be used (for example, when running /// Rust unit tests). pub fn sc_log_message(level: Level, filename: &str, line: libc::c_uint, function: &str, code: libc::c_int, message: &str) -> libc::c_int { unsafe { if let Some(c) = SC
} // Fall back if the Suricata C context is not registered which is // the case when Rust unit tests are running. // // We don't log the time right now as I don't think it can be done // with Rust 1.7.0 without using an external crate. With Rust // 1.8.0 and newer we can unix UNIX_EPOCH.elapsed() to get the // unix time. println!("{}:{} <{:?}> -- {}", filename, line, level, message); return 0; } // Convert a &str into a CString by first stripping NUL bytes. fn to_safe_cstring(val: &str) -> CString { let mut safe = Vec::with_capacity(val.len()); for c in val.as_bytes() { if *c!= 0 { safe.push(*c); } } match CString::new(safe) { Ok(cstr) => cstr, _ => { CString::new("<failed to encode string>").unwrap() } } }
{ return (c.SCLogMessage)( level as i32, to_safe_cstring(filename).as_ptr(), line, to_safe_cstring(function).as_ptr(), code, to_safe_cstring(message).as_ptr()); }
conditional_block
log.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ extern crate libc; use std::ffi::CString; use std::path::Path; use core::*; #[derive(Debug)] pub enum Level { NotSet = -1, None = 0, Emergency, Alert, Critical, Error, Warning, Notice, Info, Perf, Config, Debug, } pub static mut LEVEL: i32 = Level::NotSet as i32; pub fn get_log_level() -> i32 { unsafe { LEVEL } } fn basename(filename: &str) -> &str { let path = Path::new(filename); for os_str in path.file_name() { for basename in os_str.to_str() { return basename; } } return filename; } pub fn sclog(level: Level, file: &str, line: u32, function: &str, code: i32, message: &str) { let filename = basename(file); sc_log_message(level, filename, line, function, code, message); } /// Return the function name, but for now just return <rust> as Rust /// has no macro to return the function name, but may in the future, /// see: https://github.com/rust-lang/rfcs/pull/1719 macro_rules!function { () => {{ "<rust>" }} } #[macro_export] macro_rules!do_log { ($level:expr, $file:expr, $line:expr, $function:expr, $code:expr, $($arg:tt)*) => { if get_log_level() >= $level as i32 { sclog($level, $file, $line, $function, $code, &(format!($($arg)*))); } } } #[macro_export] macro_rules!SCLogNotice { ($($arg:tt)*) => { do_log!(Level::Notice, file!(), line!(), function!(), 0, $($arg)*); } } #[macro_export] macro_rules!SCLogInfo { ($($arg:tt)*) => { do_log!(Level::Info, file!(), line!(), function!(), 0, $($arg)*); } } #[macro_export] macro_rules!SCLogPerf { ($($arg:tt)*) => { do_log!(Level::Perf, file!(), line!(), function!(), 0, $($arg)*); } } #[macro_export] macro_rules!SCLogConfig {
#[macro_export] macro_rules!SCLogDebug { ($($arg:tt)*) => { do_log!(Level::Debug, file!(), line!(), function!(), 0, $($arg)*); } } #[no_mangle] pub extern "C" fn rs_log_set_level(level: i32) { unsafe { LEVEL = level; } } pub fn log_set_level(level: Level) { rs_log_set_level(level as i32); } /// SCLogMessage wrapper. If the Suricata C context is not registered /// a more basic log format will be used (for example, when running /// Rust unit tests). pub fn sc_log_message(level: Level, filename: &str, line: libc::c_uint, function: &str, code: libc::c_int, message: &str) -> libc::c_int { unsafe { if let Some(c) = SC { return (c.SCLogMessage)( level as i32, to_safe_cstring(filename).as_ptr(), line, to_safe_cstring(function).as_ptr(), code, to_safe_cstring(message).as_ptr()); } } // Fall back if the Suricata C context is not registered which is // the case when Rust unit tests are running. // // We don't log the time right now as I don't think it can be done // with Rust 1.7.0 without using an external crate. With Rust // 1.8.0 and newer we can unix UNIX_EPOCH.elapsed() to get the // unix time. println!("{}:{} <{:?}> -- {}", filename, line, level, message); return 0; } // Convert a &str into a CString by first stripping NUL bytes. fn to_safe_cstring(val: &str) -> CString { let mut safe = Vec::with_capacity(val.len()); for c in val.as_bytes() { if *c!= 0 { safe.push(*c); } } match CString::new(safe) { Ok(cstr) => cstr, _ => { CString::new("<failed to encode string>").unwrap() } } }
($($arg:tt)*) => { do_log!(Level::Config, file!(), line!(), function!(), 0, $($arg)*); } }
random_line_split
log.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ extern crate libc; use std::ffi::CString; use std::path::Path; use core::*; #[derive(Debug)] pub enum Level { NotSet = -1, None = 0, Emergency, Alert, Critical, Error, Warning, Notice, Info, Perf, Config, Debug, } pub static mut LEVEL: i32 = Level::NotSet as i32; pub fn get_log_level() -> i32 { unsafe { LEVEL } } fn basename(filename: &str) -> &str { let path = Path::new(filename); for os_str in path.file_name() { for basename in os_str.to_str() { return basename; } } return filename; } pub fn sclog(level: Level, file: &str, line: u32, function: &str, code: i32, message: &str) { let filename = basename(file); sc_log_message(level, filename, line, function, code, message); } /// Return the function name, but for now just return <rust> as Rust /// has no macro to return the function name, but may in the future, /// see: https://github.com/rust-lang/rfcs/pull/1719 macro_rules!function { () => {{ "<rust>" }} } #[macro_export] macro_rules!do_log { ($level:expr, $file:expr, $line:expr, $function:expr, $code:expr, $($arg:tt)*) => { if get_log_level() >= $level as i32 { sclog($level, $file, $line, $function, $code, &(format!($($arg)*))); } } } #[macro_export] macro_rules!SCLogNotice { ($($arg:tt)*) => { do_log!(Level::Notice, file!(), line!(), function!(), 0, $($arg)*); } } #[macro_export] macro_rules!SCLogInfo { ($($arg:tt)*) => { do_log!(Level::Info, file!(), line!(), function!(), 0, $($arg)*); } } #[macro_export] macro_rules!SCLogPerf { ($($arg:tt)*) => { do_log!(Level::Perf, file!(), line!(), function!(), 0, $($arg)*); } } #[macro_export] macro_rules!SCLogConfig { ($($arg:tt)*) => { do_log!(Level::Config, file!(), line!(), function!(), 0, $($arg)*); } } #[macro_export] macro_rules!SCLogDebug { ($($arg:tt)*) => { do_log!(Level::Debug, file!(), line!(), function!(), 0, $($arg)*); } } #[no_mangle] pub extern "C" fn rs_log_set_level(level: i32) { unsafe { LEVEL = level; } } pub fn log_set_level(level: Level) { rs_log_set_level(level as i32); } /// SCLogMessage wrapper. If the Suricata C context is not registered /// a more basic log format will be used (for example, when running /// Rust unit tests). pub fn
(level: Level, filename: &str, line: libc::c_uint, function: &str, code: libc::c_int, message: &str) -> libc::c_int { unsafe { if let Some(c) = SC { return (c.SCLogMessage)( level as i32, to_safe_cstring(filename).as_ptr(), line, to_safe_cstring(function).as_ptr(), code, to_safe_cstring(message).as_ptr()); } } // Fall back if the Suricata C context is not registered which is // the case when Rust unit tests are running. // // We don't log the time right now as I don't think it can be done // with Rust 1.7.0 without using an external crate. With Rust // 1.8.0 and newer we can unix UNIX_EPOCH.elapsed() to get the // unix time. println!("{}:{} <{:?}> -- {}", filename, line, level, message); return 0; } // Convert a &str into a CString by first stripping NUL bytes. fn to_safe_cstring(val: &str) -> CString { let mut safe = Vec::with_capacity(val.len()); for c in val.as_bytes() { if *c!= 0 { safe.push(*c); } } match CString::new(safe) { Ok(cstr) => cstr, _ => { CString::new("<failed to encode string>").unwrap() } } }
sc_log_message
identifier_name
note.rs
//! Manipulations of MIDI notes. use std::collections::HashMap; use std::ops::Add; use Result; // The value of a single MIDI note. A wrapper around the raw MIDI note value. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Note(pub u8); impl Note { /// Try to decode a textual node name. Notes are a letter possibly followed by a sharp or flat /// sign (in ascii of Unicode). The resulting note will be between middle C and the B above /// that. pub fn from_str(text: &str) -> Result<Note> { let mut base = None; let mut accidental = None; for ch in text.chars() { match NOTES.get(&ch) { Some(&new_base) => { if!base.is_none() { return Err(format!("Invalid note {:?}", text).into()); } base = Some(new_base); continue; } None => (), } match ACCIDENTALS.get(&ch) { Some(&new_accidental) => { if!accidental.is_none() { return Err(format!("Invalid note {:?}", text).into()); } if base.is_none() { return Err(format!("Invalid note {:?}", text).into()); } accidental = Some(new_accidental); continue; } None => (), } return Err(format!("Invalid note {:?}", text).into()); } if base.is_none() { return Err(format!("Invalid note {:?}", text).into()); } Ok(Note((base.unwrap() as i8 + accidental.unwrap_or(0)) as u8)) } } impl Add<i8> for Note { type Output = Note; fn
(self, other: i8) -> Note { Note((self.0 as i8 + other) as u8) } } lazy_static! { static ref NOTES: HashMap<char, u8> = { let mut m = HashMap::new(); m.insert('C', 60); m.insert('D', 62); m.insert('E', 64); m.insert('F', 65); m.insert('G', 67); m.insert('A', 69); m.insert('B', 71); m }; static ref ACCIDENTALS: HashMap<char, i8> = { let mut m = HashMap::new(); m.insert('#', 1); m.insert('♯', 1); m.insert('b', -1); m.insert('♭', -1); m }; } #[cfg(test)] mod test { use super::Note; #[test] fn test_note() { bad("C$"); bad("C##"); bad("C#b"); bad("Cbb"); bad("C♭♯"); good("C", 60); good("Cb", 59); good("C#", 61); good("C♭", 59); good("C♯", 61); good("D", 62); good("Db", 61); good("D#", 63); good("D♭", 61); good("D♯", 63); good("E", 64); good("F", 65); good("G", 67); good("A", 69); good("B", 71); good("B#", 72); } fn good(text: &str, expect: u8) { match Note::from_str(text) { Ok(Note(value)) => assert_eq!(expect, value), Err(_) => panic!("Expected note to parse: {:?}", text), } } fn bad(text: &str) { match Note::from_str(text) { Ok(_) => panic!("Should not have parsed: {:?}", text), Err(_) => (), } } }
add
identifier_name
note.rs
//! Manipulations of MIDI notes. use std::collections::HashMap; use std::ops::Add; use Result; // The value of a single MIDI note. A wrapper around the raw MIDI note value. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Note(pub u8); impl Note { /// Try to decode a textual node name. Notes are a letter possibly followed by a sharp or flat /// sign (in ascii of Unicode). The resulting note will be between middle C and the B above /// that. pub fn from_str(text: &str) -> Result<Note> { let mut base = None; let mut accidental = None; for ch in text.chars() { match NOTES.get(&ch) { Some(&new_base) => { if!base.is_none() { return Err(format!("Invalid note {:?}", text).into()); } base = Some(new_base); continue; } None => (), } match ACCIDENTALS.get(&ch) { Some(&new_accidental) => { if!accidental.is_none() { return Err(format!("Invalid note {:?}", text).into()); } if base.is_none() { return Err(format!("Invalid note {:?}", text).into()); } accidental = Some(new_accidental); continue; } None => (), } return Err(format!("Invalid note {:?}", text).into()); } if base.is_none() { return Err(format!("Invalid note {:?}", text).into()); } Ok(Note((base.unwrap() as i8 + accidental.unwrap_or(0)) as u8)) } } impl Add<i8> for Note { type Output = Note; fn add(self, other: i8) -> Note { Note((self.0 as i8 + other) as u8) } } lazy_static! { static ref NOTES: HashMap<char, u8> = { let mut m = HashMap::new(); m.insert('C', 60); m.insert('D', 62); m.insert('E', 64); m.insert('F', 65); m.insert('G', 67); m.insert('A', 69); m.insert('B', 71); m }; static ref ACCIDENTALS: HashMap<char, i8> = { let mut m = HashMap::new(); m.insert('#', 1); m.insert('♯', 1); m.insert('b', -1); m.insert('♭', -1); m }; } #[cfg(test)] mod test { use super::Note; #[test] fn test_note() { bad("C$"); bad("C##"); bad("C#b"); bad("Cbb"); bad("C♭♯"); good("C", 60); good("Cb", 59); good("C#", 61); good("C♭", 59); good("C♯", 61); good("D", 62); good("Db", 61); good("D#", 63); good("D♭", 61);
good("F", 65); good("G", 67); good("A", 69); good("B", 71); good("B#", 72); } fn good(text: &str, expect: u8) { match Note::from_str(text) { Ok(Note(value)) => assert_eq!(expect, value), Err(_) => panic!("Expected note to parse: {:?}", text), } } fn bad(text: &str) { match Note::from_str(text) { Ok(_) => panic!("Should not have parsed: {:?}", text), Err(_) => (), } } }
good("D♯", 63); good("E", 64);
random_line_split
note.rs
//! Manipulations of MIDI notes. use std::collections::HashMap; use std::ops::Add; use Result; // The value of a single MIDI note. A wrapper around the raw MIDI note value. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Note(pub u8); impl Note { /// Try to decode a textual node name. Notes are a letter possibly followed by a sharp or flat /// sign (in ascii of Unicode). The resulting note will be between middle C and the B above /// that. pub fn from_str(text: &str) -> Result<Note> { let mut base = None; let mut accidental = None; for ch in text.chars() { match NOTES.get(&ch) { Some(&new_base) => { if!base.is_none() { return Err(format!("Invalid note {:?}", text).into()); } base = Some(new_base); continue; } None => (), } match ACCIDENTALS.get(&ch) { Some(&new_accidental) => { if!accidental.is_none() { return Err(format!("Invalid note {:?}", text).into()); } if base.is_none() { return Err(format!("Invalid note {:?}", text).into()); } accidental = Some(new_accidental); continue; } None => (), } return Err(format!("Invalid note {:?}", text).into()); } if base.is_none()
Ok(Note((base.unwrap() as i8 + accidental.unwrap_or(0)) as u8)) } } impl Add<i8> for Note { type Output = Note; fn add(self, other: i8) -> Note { Note((self.0 as i8 + other) as u8) } } lazy_static! { static ref NOTES: HashMap<char, u8> = { let mut m = HashMap::new(); m.insert('C', 60); m.insert('D', 62); m.insert('E', 64); m.insert('F', 65); m.insert('G', 67); m.insert('A', 69); m.insert('B', 71); m }; static ref ACCIDENTALS: HashMap<char, i8> = { let mut m = HashMap::new(); m.insert('#', 1); m.insert('♯', 1); m.insert('b', -1); m.insert('♭', -1); m }; } #[cfg(test)] mod test { use super::Note; #[test] fn test_note() { bad("C$"); bad("C##"); bad("C#b"); bad("Cbb"); bad("C♭♯"); good("C", 60); good("Cb", 59); good("C#", 61); good("C♭", 59); good("C♯", 61); good("D", 62); good("Db", 61); good("D#", 63); good("D♭", 61); good("D♯", 63); good("E", 64); good("F", 65); good("G", 67); good("A", 69); good("B", 71); good("B#", 72); } fn good(text: &str, expect: u8) { match Note::from_str(text) { Ok(Note(value)) => assert_eq!(expect, value), Err(_) => panic!("Expected note to parse: {:?}", text), } } fn bad(text: &str) { match Note::from_str(text) { Ok(_) => panic!("Should not have parsed: {:?}", text), Err(_) => (), } } }
{ return Err(format!("Invalid note {:?}", text).into()); }
conditional_block
note.rs
//! Manipulations of MIDI notes. use std::collections::HashMap; use std::ops::Add; use Result; // The value of a single MIDI note. A wrapper around the raw MIDI note value. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Note(pub u8); impl Note { /// Try to decode a textual node name. Notes are a letter possibly followed by a sharp or flat /// sign (in ascii of Unicode). The resulting note will be between middle C and the B above /// that. pub fn from_str(text: &str) -> Result<Note> { let mut base = None; let mut accidental = None; for ch in text.chars() { match NOTES.get(&ch) { Some(&new_base) => { if!base.is_none() { return Err(format!("Invalid note {:?}", text).into()); } base = Some(new_base); continue; } None => (), } match ACCIDENTALS.get(&ch) { Some(&new_accidental) => { if!accidental.is_none() { return Err(format!("Invalid note {:?}", text).into()); } if base.is_none() { return Err(format!("Invalid note {:?}", text).into()); } accidental = Some(new_accidental); continue; } None => (), } return Err(format!("Invalid note {:?}", text).into()); } if base.is_none() { return Err(format!("Invalid note {:?}", text).into()); } Ok(Note((base.unwrap() as i8 + accidental.unwrap_or(0)) as u8)) } } impl Add<i8> for Note { type Output = Note; fn add(self, other: i8) -> Note { Note((self.0 as i8 + other) as u8) } } lazy_static! { static ref NOTES: HashMap<char, u8> = { let mut m = HashMap::new(); m.insert('C', 60); m.insert('D', 62); m.insert('E', 64); m.insert('F', 65); m.insert('G', 67); m.insert('A', 69); m.insert('B', 71); m }; static ref ACCIDENTALS: HashMap<char, i8> = { let mut m = HashMap::new(); m.insert('#', 1); m.insert('♯', 1); m.insert('b', -1); m.insert('♭', -1); m }; } #[cfg(test)] mod test { use super::Note; #[test] fn test_note() { bad("C$"); bad("C##"); bad("C#b"); bad("Cbb"); bad("C♭♯"); good("C", 60); good("Cb", 59); good("C#", 61); good("C♭", 59); good("C♯", 61); good("D", 62); good("Db", 61); good("D#", 63); good("D♭", 61); good("D♯", 63); good("E", 64); good("F", 65); good("G", 67); good("A", 69); good("B", 71); good("B#", 72); } fn good(text: &str, expect: u8) { match Note::from_str(text) { Ok(Note(value)) => assert_eq!(expect, value), Err(_) => panic!("Expected note to parse: {:?}", text), } } fn bad(text: &str) { match
Note::from_str(text) { Ok(_) => panic!("Should not have parsed: {:?}", text), Err(_) => (), } } }
identifier_body
main.rs
//#[cfg(not(test))] #![crate_type = "bin"] #![crate_name = "krakusc"] #![feature(non_ascii_idents)] #[macro_use] extern crate krakus_vm as krakus; extern crate getopts; use getopts::Options; use krakus::*; use std::env; use std::mem; fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} [options]", program); print!("{}", opts.usage(&brief)); } #[cfg_attr(test, allow(dead_code))] fn
() { use std::io::prelude::*; use std::fs::File; let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); //opts.optopt("o", "", "set output file name", "NAME"); opts.optflag("h", "help", "print this help menu"); let matches = match opts.parse(&args[1..]) { Ok(m) => { m } Err(f) => { panic!(f.to_string()) } }; if matches.opt_present("h") { print_usage(&program, opts); return; } //let output = matches.opt_str("o"); let input = if!matches.free.is_empty() { matches.free[0].clone() } else { print_usage(&program, opts); return; }; let mut f = match File::open(input) { Ok(v) => v, Err(_) => panic!("Guy, that is not a file I can open!"), }; let mut s = String::new(); f.read_to_string(&mut s).unwrap(); let forward_euler_ff = |args: Vec<u64>| -> Vec<u64> { let mut args = args.clone(); let a = uint_to_float!(args[0]); let b = uint_to_float!(args[1]); let mut t = uint_to_float!(args[2]); let mut y = uint_to_float!(args[3]); let dt = uint_to_float!(args[4]); let n = ((b-a)/dt) as u64; let mut i = 0; while i < n { y = y + dt*y; t += dt; i += 1; } println!("in ff:{:.20}",y); args[2] = float_to_uint!(t); args[3] = float_to_uint!(y); return args; }; let mut kr_con = KrakusContext::new(); kr_con.add_function("forward-euler".to_string(),5,&forward_euler_ff); kr_con.execute_assembly(s); krakus::sexpr::test_s_expr(); }
main
identifier_name
main.rs
//#[cfg(not(test))] #![crate_type = "bin"]
#![crate_name = "krakusc"] #![feature(non_ascii_idents)] #[macro_use] extern crate krakus_vm as krakus; extern crate getopts; use getopts::Options; use krakus::*; use std::env; use std::mem; fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} [options]", program); print!("{}", opts.usage(&brief)); } #[cfg_attr(test, allow(dead_code))] fn main() { use std::io::prelude::*; use std::fs::File; let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); //opts.optopt("o", "", "set output file name", "NAME"); opts.optflag("h", "help", "print this help menu"); let matches = match opts.parse(&args[1..]) { Ok(m) => { m } Err(f) => { panic!(f.to_string()) } }; if matches.opt_present("h") { print_usage(&program, opts); return; } //let output = matches.opt_str("o"); let input = if!matches.free.is_empty() { matches.free[0].clone() } else { print_usage(&program, opts); return; }; let mut f = match File::open(input) { Ok(v) => v, Err(_) => panic!("Guy, that is not a file I can open!"), }; let mut s = String::new(); f.read_to_string(&mut s).unwrap(); let forward_euler_ff = |args: Vec<u64>| -> Vec<u64> { let mut args = args.clone(); let a = uint_to_float!(args[0]); let b = uint_to_float!(args[1]); let mut t = uint_to_float!(args[2]); let mut y = uint_to_float!(args[3]); let dt = uint_to_float!(args[4]); let n = ((b-a)/dt) as u64; let mut i = 0; while i < n { y = y + dt*y; t += dt; i += 1; } println!("in ff:{:.20}",y); args[2] = float_to_uint!(t); args[3] = float_to_uint!(y); return args; }; let mut kr_con = KrakusContext::new(); kr_con.add_function("forward-euler".to_string(),5,&forward_euler_ff); kr_con.execute_assembly(s); krakus::sexpr::test_s_expr(); }
random_line_split
main.rs
//#[cfg(not(test))] #![crate_type = "bin"] #![crate_name = "krakusc"] #![feature(non_ascii_idents)] #[macro_use] extern crate krakus_vm as krakus; extern crate getopts; use getopts::Options; use krakus::*; use std::env; use std::mem; fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} [options]", program); print!("{}", opts.usage(&brief)); } #[cfg_attr(test, allow(dead_code))] fn main() { use std::io::prelude::*; use std::fs::File; let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); //opts.optopt("o", "", "set output file name", "NAME"); opts.optflag("h", "help", "print this help menu"); let matches = match opts.parse(&args[1..]) { Ok(m) => { m } Err(f) => { panic!(f.to_string()) } }; if matches.opt_present("h") { print_usage(&program, opts); return; } //let output = matches.opt_str("o"); let input = if!matches.free.is_empty()
else { print_usage(&program, opts); return; }; let mut f = match File::open(input) { Ok(v) => v, Err(_) => panic!("Guy, that is not a file I can open!"), }; let mut s = String::new(); f.read_to_string(&mut s).unwrap(); let forward_euler_ff = |args: Vec<u64>| -> Vec<u64> { let mut args = args.clone(); let a = uint_to_float!(args[0]); let b = uint_to_float!(args[1]); let mut t = uint_to_float!(args[2]); let mut y = uint_to_float!(args[3]); let dt = uint_to_float!(args[4]); let n = ((b-a)/dt) as u64; let mut i = 0; while i < n { y = y + dt*y; t += dt; i += 1; } println!("in ff:{:.20}",y); args[2] = float_to_uint!(t); args[3] = float_to_uint!(y); return args; }; let mut kr_con = KrakusContext::new(); kr_con.add_function("forward-euler".to_string(),5,&forward_euler_ff); kr_con.execute_assembly(s); krakus::sexpr::test_s_expr(); }
{ matches.free[0].clone() }
conditional_block
main.rs
//#[cfg(not(test))] #![crate_type = "bin"] #![crate_name = "krakusc"] #![feature(non_ascii_idents)] #[macro_use] extern crate krakus_vm as krakus; extern crate getopts; use getopts::Options; use krakus::*; use std::env; use std::mem; fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} [options]", program); print!("{}", opts.usage(&brief)); } #[cfg_attr(test, allow(dead_code))] fn main()
matches.free[0].clone() } else { print_usage(&program, opts); return; }; let mut f = match File::open(input) { Ok(v) => v, Err(_) => panic!("Guy, that is not a file I can open!"), }; let mut s = String::new(); f.read_to_string(&mut s).unwrap(); let forward_euler_ff = |args: Vec<u64>| -> Vec<u64> { let mut args = args.clone(); let a = uint_to_float!(args[0]); let b = uint_to_float!(args[1]); let mut t = uint_to_float!(args[2]); let mut y = uint_to_float!(args[3]); let dt = uint_to_float!(args[4]); let n = ((b-a)/dt) as u64; let mut i = 0; while i < n { y = y + dt*y; t += dt; i += 1; } println!("in ff:{:.20}",y); args[2] = float_to_uint!(t); args[3] = float_to_uint!(y); return args; }; let mut kr_con = KrakusContext::new(); kr_con.add_function("forward-euler".to_string(),5,&forward_euler_ff); kr_con.execute_assembly(s); krakus::sexpr::test_s_expr(); }
{ use std::io::prelude::*; use std::fs::File; let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); //opts.optopt("o", "", "set output file name", "NAME"); opts.optflag("h", "help", "print this help menu"); let matches = match opts.parse(&args[1..]) { Ok(m) => { m } Err(f) => { panic!(f.to_string()) } }; if matches.opt_present("h") { print_usage(&program, opts); return; } //let output = matches.opt_str("o"); let input = if !matches.free.is_empty() {
identifier_body
extern-call-indirect.rs
// run-pass // ignore-wasm32-bare no libc to test ffi with #![feature(rustc_private)] extern crate libc; mod rustrt { extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] extern "C" { pub fn rust_dbg_call( cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, data: libc::uintptr_t, ) -> libc::uintptr_t; } } extern "C" fn cb(data: libc::uintptr_t) -> libc::uintptr_t { if data == 1 { data } else { fact(data - 1) * data } } fn fact(n: libc::uintptr_t) -> libc::uintptr_t { unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } } pub fn main()
{ let result = fact(10); println!("result = {}", result); assert_eq!(result, 3628800); }
identifier_body
extern-call-indirect.rs
// run-pass
extern crate libc; mod rustrt { extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] extern "C" { pub fn rust_dbg_call( cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, data: libc::uintptr_t, ) -> libc::uintptr_t; } } extern "C" fn cb(data: libc::uintptr_t) -> libc::uintptr_t { if data == 1 { data } else { fact(data - 1) * data } } fn fact(n: libc::uintptr_t) -> libc::uintptr_t { unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { let result = fact(10); println!("result = {}", result); assert_eq!(result, 3628800); }
// ignore-wasm32-bare no libc to test ffi with #![feature(rustc_private)]
random_line_split
extern-call-indirect.rs
// run-pass // ignore-wasm32-bare no libc to test ffi with #![feature(rustc_private)] extern crate libc; mod rustrt { extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] extern "C" { pub fn rust_dbg_call( cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, data: libc::uintptr_t, ) -> libc::uintptr_t; } } extern "C" fn cb(data: libc::uintptr_t) -> libc::uintptr_t { if data == 1
else { fact(data - 1) * data } } fn fact(n: libc::uintptr_t) -> libc::uintptr_t { unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { let result = fact(10); println!("result = {}", result); assert_eq!(result, 3628800); }
{ data }
conditional_block
extern-call-indirect.rs
// run-pass // ignore-wasm32-bare no libc to test ffi with #![feature(rustc_private)] extern crate libc; mod rustrt { extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] extern "C" { pub fn rust_dbg_call( cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, data: libc::uintptr_t, ) -> libc::uintptr_t; } } extern "C" fn
(data: libc::uintptr_t) -> libc::uintptr_t { if data == 1 { data } else { fact(data - 1) * data } } fn fact(n: libc::uintptr_t) -> libc::uintptr_t { unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { let result = fact(10); println!("result = {}", result); assert_eq!(result, 3628800); }
cb
identifier_name
syntax.rs
extern crate liquid; use liquid::LiquidOptions; use liquid::Renderable; use liquid::Context; use liquid::parse; use std::default::Default; macro_rules! compare { ($input:expr, $output:expr) => { let input = $input.replace("…", " "); let expected = $output.replace("…", " "); let options: LiquidOptions = Default::default(); let template = parse(&input, options).unwrap(); let mut data = Context::new(); let output = template.render(&mut data); assert_eq!(output.unwrap(), Some(expected)); } } #[test] pub fn no_whitespace_control() { compare!( " topic1 ……{% assign foo = \"bar\" %} ……{% if foo %} …………-……{{ foo }} ……{% endif %} ", " topic1 …… …… …………-……bar …… " ); } #[test] pub fn simple_whitespace_control() { compare!( " topic1 ……{% assign foo = \"bar\" -%} ……{% if foo -%} …………-……{{- foo }} ……{%- endif %} ", " topic1 ……-bar " ); } #[test] pub fn double_sided_whitespace_control() { compare!( " topic1 ……{%- assign foo = \"bar\" -%} ……-……{{- foo -}}…… ",
}
" topic1-bar\ " );
random_line_split
syntax.rs
extern crate liquid; use liquid::LiquidOptions; use liquid::Renderable; use liquid::Context; use liquid::parse; use std::default::Default; macro_rules! compare { ($input:expr, $output:expr) => { let input = $input.replace("…", " "); let expected = $output.replace("…", " "); let options: LiquidOptions = Default::default(); let template = parse(&input, options).unwrap(); let mut data = Context::new(); let output = template.render(&mut data); assert_eq!(output.unwrap(), Some(expected)); } } #[test] pub fn no_whitespace_control() { compare!( " topic1 ……{% assign foo = \"bar\" %} ……{% if foo %} …………-……{{ foo }} ……{% endif %} ", " topic1 …… …… …………-……bar …… " ); } #[test] pub fn simple_whitespace_control() { compare!( " topic1 ……{% assign foo = \
ic1 ……{%- assign foo = \"bar\" -%} ……-……{{- foo -}}…… ", " topic1-bar\ " ); }
"bar\" -%} ……{% if foo -%} …………-……{{- foo }} ……{%- endif %} ", " topic1 ……-bar " ); } #[test] pub fn double_sided_whitespace_control() { compare!( " top
identifier_body
syntax.rs
extern crate liquid; use liquid::LiquidOptions; use liquid::Renderable; use liquid::Context; use liquid::parse; use std::default::Default; macro_rules! compare { ($input:expr, $output:expr) => { let input = $input.replace("…", " "); let expected = $output.replace("…", " "); let options: LiquidOptions = Default::default(); let template = parse(&input, options).unwrap(); let mut data = Context::new(); let output = template.render(&mut data); assert_eq!(output.unwrap(), Some(expected)); } } #[test] pub fn no_w
compare!( " topic1 ……{% assign foo = \"bar\" %} ……{% if foo %} …………-……{{ foo }} ……{% endif %} ", " topic1 …… …… …………-……bar …… " ); } #[test] pub fn simple_whitespace_control() { compare!( " topic1 ……{% assign foo = \"bar\" -%} ……{% if foo -%} …………-……{{- foo }} ……{%- endif %} ", " topic1 ……-bar " ); } #[test] pub fn double_sided_whitespace_control() { compare!( " topic1 ……{%- assign foo = \"bar\" -%} ……-……{{- foo -}}…… ", " topic1-bar\ " ); }
hitespace_control() {
identifier_name
macros.rs
/// Helper macro to get real values out of Value while retaining /// proper errors in filters /// /// Takes 4 args: /// /// - the filter name, /// - the variable name: use "value" if you are using it on the variable the filter is ran on /// - the expected type /// - the actual variable
/// ```rust,ignore /// let arr = try_get_value!("first", "value", Vec<Value>, value); /// let val = try_get_value!("pluralize", "suffix", String, val.clone()); /// ``` #[macro_export] macro_rules! try_get_value { ($filter_name:expr, $var_name:expr, $ty:ty, $val:expr) => {{ match $crate::from_value::<$ty>($val.clone()) { Ok(s) => s, Err(_) => { if $var_name == "value" { return Err($crate::Error::msg(format!( "Filter `{}` was called on an incorrect value: got `{}` but expected a {}", $filter_name, $val, stringify!($ty) ))); } else { return Err($crate::Error::msg(format!( "Filter `{}` received an incorrect type for arg `{}`: got `{}` but expected a {}", $filter_name, $var_name, $val, stringify!($ty) ))); } } } }}; }
///
random_line_split
lint-unused-mut-variables.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. // Exercise the unused_mut attribute in some positive and negative cases #[allow(dead_assignment)]; #[allow(unused_variable)]; #[allow(dead_code)]; #[deny(unused_mut)]; fn main() { // negative cases let mut a = 3; //~ ERROR: variable does not need to be mutable let mut a = 2; //~ ERROR: variable does not need to be mutable let mut b = 3; //~ ERROR: variable does not need to be mutable let mut a = ~[3]; //~ ERROR: variable does not need to be mutable let (mut a, b) = (1, 2); //~ ERROR: variable does not need to be mutable match 30 { mut x => {} //~ ERROR: variable does not need to be mutable } let x = |mut y: int| 10; //~ ERROR: variable does not need to be mutable fn what(mut foo: int) {} //~ ERROR: variable does not need to be mutable // positive cases let mut a = 2; a = 3; let mut a = ~[]; a.push(3); let mut a = ~[]; callback(|| { a.push(3); }); let (mut a, b) = (1, 2); a = 34; match 30 { mut x => { x = 21; } } let x = |mut y: int| y = 32; fn nothing(mut foo: int) { foo = 37; } // leading underscore should avoid the warning, just like the // unused variable lint. let mut _allowed = 1; } fn
(f: ||) {} // make sure the lint attribute can be turned off #[allow(unused_mut)] fn foo(mut a: int) { let mut a = 3; let mut b = ~[2]; }
callback
identifier_name
lint-unused-mut-variables.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. // Exercise the unused_mut attribute in some positive and negative cases #[allow(dead_assignment)]; #[allow(unused_variable)]; #[allow(dead_code)]; #[deny(unused_mut)]; fn main() { // negative cases let mut a = 3; //~ ERROR: variable does not need to be mutable let mut a = 2; //~ ERROR: variable does not need to be mutable let mut b = 3; //~ ERROR: variable does not need to be mutable let mut a = ~[3]; //~ ERROR: variable does not need to be mutable let (mut a, b) = (1, 2); //~ ERROR: variable does not need to be mutable match 30 { mut x => {} //~ ERROR: variable does not need to be mutable } let x = |mut y: int| 10; //~ ERROR: variable does not need to be mutable fn what(mut foo: int) {} //~ ERROR: variable does not need to be mutable // positive cases let mut a = 2; a = 3; let mut a = ~[]; a.push(3); let mut a = ~[]; callback(|| { a.push(3); }); let (mut a, b) = (1, 2); a = 34; match 30 { mut x => { x = 21; }
fn nothing(mut foo: int) { foo = 37; } // leading underscore should avoid the warning, just like the // unused variable lint. let mut _allowed = 1; } fn callback(f: ||) {} // make sure the lint attribute can be turned off #[allow(unused_mut)] fn foo(mut a: int) { let mut a = 3; let mut b = ~[2]; }
} let x = |mut y: int| y = 32;
random_line_split
lint-unused-mut-variables.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. // Exercise the unused_mut attribute in some positive and negative cases #[allow(dead_assignment)]; #[allow(unused_variable)]; #[allow(dead_code)]; #[deny(unused_mut)]; fn main() { // negative cases let mut a = 3; //~ ERROR: variable does not need to be mutable let mut a = 2; //~ ERROR: variable does not need to be mutable let mut b = 3; //~ ERROR: variable does not need to be mutable let mut a = ~[3]; //~ ERROR: variable does not need to be mutable let (mut a, b) = (1, 2); //~ ERROR: variable does not need to be mutable match 30 { mut x => {} //~ ERROR: variable does not need to be mutable } let x = |mut y: int| 10; //~ ERROR: variable does not need to be mutable fn what(mut foo: int)
//~ ERROR: variable does not need to be mutable // positive cases let mut a = 2; a = 3; let mut a = ~[]; a.push(3); let mut a = ~[]; callback(|| { a.push(3); }); let (mut a, b) = (1, 2); a = 34; match 30 { mut x => { x = 21; } } let x = |mut y: int| y = 32; fn nothing(mut foo: int) { foo = 37; } // leading underscore should avoid the warning, just like the // unused variable lint. let mut _allowed = 1; } fn callback(f: ||) {} // make sure the lint attribute can be turned off #[allow(unused_mut)] fn foo(mut a: int) { let mut a = 3; let mut b = ~[2]; }
{}
identifier_body
str.rs
: &mut H) { self.0.hash(state); } } impl FromStr for ByteString { type Err = (); fn from_str(s: &str) -> Result<ByteString, ()> { Ok(ByteString::new(s.to_owned().into_bytes())) } } impl ops::Deref for ByteString { type Target = [u8]; fn deref(&self) -> &[u8] { &self.0 } } /// A string that is constructed from a UCS-2 buffer by replacing invalid code /// points with the replacement character. #[derive(Clone, Default, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd)] pub struct USVString(pub String); impl Borrow<str> for USVString { #[inline] fn borrow(&self) -> &str { &self.0 } } impl Deref for USVString { type Target = str; #[inline] fn deref(&self) -> &str { &self.0 } } impl DerefMut for USVString { #[inline] fn deref_mut(&mut self) -> &mut str { &mut self.0 } } impl AsRef<str> for USVString { fn as_ref(&self) -> &str { &self.0 } } impl fmt::Display for USVString { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, f) } } impl PartialEq<str> for USVString { fn eq(&self, other: &str) -> bool { &**self == other } } impl<'a> PartialEq<&'a str> for USVString { fn eq(&self, other: &&'a str) -> bool { &**self == *other } } impl From<String> for USVString { fn from(contents: String) -> USVString { USVString(contents) } } /// Returns whether `s` is a `token`, as defined by /// [RFC 2616](http://tools.ietf.org/html/rfc2616#page-17). pub fn is_token(s: &[u8]) -> bool { if s.is_empty() { return false; // A token must be at least a single character } s.iter().all(|&x| { // http://tools.ietf.org/html/rfc2616#section-2.2 match x { 0..=31 | 127 => false, // CTLs 40 | 41 | 60 | 62 | 64 | 44 | 59 | 58 | 92 | 34 | 47 | 91 | 93 | 63 | 61 | 123 | 125 | 32 => false, // separators x if x > 127 => false, // non-CHARs _ => true, } }) } /// A DOMString. /// /// This type corresponds to the [`DOMString`](idl) type in WebIDL. /// /// [idl]: https://heycam.github.io/webidl/#idl-DOMString /// /// Conceptually, a DOMString has the same value space as a JavaScript String, /// i.e., an array of 16-bit *code units* representing UTF-16, potentially with /// unpaired surrogates present (also sometimes called WTF-16). /// /// Currently, this type stores a Rust `String`, in order to avoid issues when /// integrating with the rest of the Rust ecosystem and even the rest of the /// browser itself. /// /// However, Rust `String`s are guaranteed to be valid UTF-8, and as such have /// a *smaller value space* than WTF-16 (i.e., some JavaScript String values /// can not be represented as a Rust `String`). This introduces the question of /// what to do with values being passed from JavaScript to Rust that contain /// unpaired surrogates. /// /// The hypothesis is that it does not matter much how exactly those values are /// transformed, because passing unpaired surrogates into the DOM is very rare. /// In order to test this hypothesis, Servo will panic when encountering any /// unpaired surrogates on conversion to `DOMString` by default. (The command /// line option `-Z replace-surrogates` instead causes Servo to replace the /// unpaired surrogate by a U+FFFD replacement character.) /// /// Currently, the lack of crash reports about this issue provides some /// evidence to support the hypothesis. This evidence will hopefully be used to /// convince other browser vendors that it would be safe to replace unpaired /// surrogates at the boundary between JavaScript and native code. (This would /// unify the `DOMString` and `USVString` types, both in the WebIDL standard /// and in Servo.) /// /// This type is currently `!Send`, in order to help with an independent /// experiment to store `JSString`s rather than Rust `String`s. #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd)] pub struct DOMString(String, PhantomData<*const ()>); impl DOMString { /// Creates a new `DOMString`. pub fn new() -> DOMString { DOMString(String::new(), PhantomData) } /// Creates a new `DOMString` from a `String`. pub fn from_string(s: String) -> DOMString { DOMString(s, PhantomData) } /// Appends a given string slice onto the end of this String. pub fn push_str(&mut self, string: &str) { self.0.push_str(string) } /// Clears this `DOMString`, removing all contents. pub fn clear(&mut self) { self.0.clear() } /// Shortens this String to the specified length. pub fn truncate(&mut self, new_len: usize) { self.0.truncate(new_len); } /// Removes newline characters according to <https://infra.spec.whatwg.org/#strip-newlines>. pub fn strip_newlines(&mut self) { self.0.retain(|c| c!= '\r' && c!= '\n'); } /// Removes leading and trailing ASCII whitespaces according to /// <https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace>. pub fn strip_leading_and_trailing_ascii_whitespace(&mut self) { if self.0.len() == 0 { return; } let trailing_whitespace_len = self .0 .trim_end_matches(|ref c| char::is_ascii_whitespace(c)) .len(); self.0.truncate(trailing_whitespace_len); if self.0.is_empty() { return; } let first_non_whitespace = self.0.find(|ref c|!char::is_ascii_whitespace(c)).unwrap(); let _ = self.0.replace_range(0..first_non_whitespace, ""); } /// Validates this `DOMString` is a time string according to /// <https://html.spec.whatwg.org/multipage/#valid-time-string>. pub fn is_valid_time_string(&self) -> bool { enum State { HourHigh, HourLow09, HourLow03, MinuteColon, MinuteHigh, MinuteLow, SecondColon, SecondHigh, SecondLow, MilliStop, MilliHigh, MilliMiddle, MilliLow, Done, Error, } let next_state = |valid: bool, next: State| -> State { if valid { next } else { State::Error } }; let state = self.chars().fold(State::HourHigh, |state, c| { match state { // Step 1 "HH" State::HourHigh => match c { '0' | '1' => State::HourLow09, '2' => State::HourLow03, _ => State::Error, }, State::HourLow09 => next_state(c.is_digit(10), State::MinuteColon), State::HourLow03 => next_state(c.is_digit(4), State::MinuteColon), // Step 2 ":" State::MinuteColon => next_state(c == ':', State::MinuteHigh), // Step 3 "mm" State::MinuteHigh => next_state(c.is_digit(6), State::MinuteLow), State::MinuteLow => next_state(c.is_digit(10), State::SecondColon), // Step 4.1 ":" State::SecondColon => next_state(c == ':', State::SecondHigh), // Step 4.2 "ss" State::SecondHigh => next_state(c.is_digit(6), State::SecondLow), State::SecondLow => next_state(c.is_digit(10), State::MilliStop), // Step 4.3.1 "." State::MilliStop => next_state(c == '.', State::MilliHigh), // Step 4.3.2 "SSS" State::MilliHigh => next_state(c.is_digit(10), State::MilliMiddle), State::MilliMiddle => next_state(c.is_digit(10), State::MilliLow), State::MilliLow => next_state(c.is_digit(10), State::Done), _ => State::Error, } }); match state { State::Done | // Step 4 (optional) State::SecondColon | // Step 4.3 (optional) State::MilliStop | // Step 4.3.2 (only 1 digit required) State::MilliMiddle | State::MilliLow => true, _ => false } } /// A valid date string should be "YYYY-MM-DD" /// YYYY must be four or more digits, MM and DD both must be two digits /// https://html.spec.whatwg.org/multipage/#valid-date-string pub fn is_valid_date_string(&self) -> bool { self.parse_date_string().is_ok() } /// https://html.spec.whatwg.org/multipage/#parse-a-date-string pub fn parse_date_string(&self) -> Result<(i32, u32, u32), ()> { let value = &self.0; // Step 1, 2, 3 let (year_int, month_int, day_int) = parse_date_component(value)?; // Step 4 if value.split('-').nth(3).is_some() { return Err(()); } // Step 5, 6 Ok((year_int, month_int, day_int)) } /// https://html.spec.whatwg.org/multipage/#parse-a-time-string pub fn parse_time_string(&self) -> Result<(u32, u32, f64), ()> { let value = &self.0; // Step 1, 2, 3 let (hour_int, minute_int, second_float) = parse_time_component(value)?; // Step 4 if value.split(':').nth(3).is_some() { return Err(()); } // Step 5, 6 Ok((hour_int, minute_int, second_float)) } /// A valid month string should be "YYYY-MM" /// YYYY must be four or more digits, MM both must be two digits /// https://html.spec.whatwg.org/multipage/#valid-month-string pub fn is_valid_month_string(&self) -> bool { self.parse_month_string().is_ok() } /// https://html.spec.whatwg.org/multipage/#parse-a-month-string pub fn parse_month_string(&self) -> Result<(i32, u32), ()> { let value = &self; // Step 1, 2, 3 let (year_int, month_int) = parse_month_component(value)?; // Step 4 if value.split("-").nth(2).is_some() { return Err(()); } // Step 5 Ok((year_int, month_int)) } /// A valid week string should be like {YYYY}-W{WW}, such as "2017-W52" /// YYYY must be four or more digits, WW both must be two digits /// https://html.spec.whatwg.org/multipage/#valid-week-string pub fn is_valid_week_string(&self) -> bool { self.parse_week_string().is_ok() } /// https://html.spec.whatwg.org/multipage/#parse-a-week-string pub fn parse_week_string(&self) -> Result<(i32, u32), ()> { let value = &self.0; // Step 1, 2, 3 let mut iterator = value.split('-'); let year = iterator.next().ok_or(())?; // Step 4 let year_int = year.parse::<i32>().map_err(|_| ())?; if year.len() < 4 || year_int == 0 { return Err(()); } // Step 5, 6 let week = iterator.next().ok_or(())?; let (week_first, week_last) = week.split_at(1); if week_first!= "W" { return Err(()); } // Step 7 let week_int = week_last.parse::<u32>().map_err(|_| ())?; if week_last.len()!= 2 { return Err(()); } // Step 8 let max_week = max_week_in_year(year_int); // Step 9 if week_int < 1 || week_int > max_week { return Err(()); } // Step 10 if iterator.next().is_some() { return Err(()); } // Step 11 Ok((year_int, week_int)) } /// https://html.spec.whatwg.org/multipage/#valid-floating-point-number pub fn is_valid_floating_point_number_string(&self) -> bool { lazy_static! { static ref RE: Regex = Regex::new(r"^-?(?:\d+\.\d+|\d+|\.\d+)(?:(e|E)(\+|\-)?\d+)?$").unwrap(); } RE.is_match(&self.0) && self.parse_floating_point_number().is_ok() } /// https://html.spec.whatwg.org/multipage/#rules-for-parsing-floating-point-number-values pub fn parse_floating_point_number(&self) -> Result<f64, ()> { // Steps 15-16 are telling us things about IEEE rounding modes // for floating-point significands; this code assumes the Rust // compiler already matches them in any cases where // that actually matters. They are not // related to f64::round(), which is for rounding to integers. let input = &self.0; match input.trim().parse::<f64>() { Ok(val) if!( // A valid number is the same as what rust considers to be valid, // except for +1., NaN, and Infinity. val.is_infinite() || val.is_nan() || input.ends_with(".") || input.starts_with("+") ) => { Ok(val) }, _ => Err(()), } } /// https://html.spec.whatwg.org/multipage/#best-representation-of-the-number-as-a-floating-point-number pub fn set_best_representation_of_the_floating_point_number(&mut self) { if let Ok(val) = self.parse_floating_point_number() { self.0 = val.to_string(); } } /// A valid normalized local date and time string should be "{date}T{time}" /// where date and time are both valid, and the time string must be as short as possible /// https://html.spec.whatwg.org/multipage/#valid-normalised-local-date-and-time-string pub fn convert_valid_normalized_local_date_and_time_string(&mut self) -> Result<(), ()> { let ((year, month, day), (hour, minute, second)) = self.parse_local_date_and_time_string()?; if second == 0.0 { self.0 = format!( "{:04}-{:02}-{:02}T{:02}:{:02}", year, month, day, hour, minute ); } else { self.0 = format!( "{:04}-{:02}-{:02}T{:02}:{:02}:{}", year, month, day, hour, minute, second ); } Ok(()) } /// https://html.spec.whatwg.org/multipage/#parse-a-local-date-and-time-string pub fn parse_local_date_and_time_string( &self, ) -> Result<((i32, u32, u32), (u32, u32, f64)), ()> { let value = &self; // Step 1, 2, 4 let mut iterator = if value.contains('T') { value.split('T') } else {
// Step 3 let date = iterator.next().ok_or(())?; let date_tuple = parse_date_component(date)?; // Step 5 let time = iterator.next().ok_or(())?; let time_tuple = parse_time_component(time)?; // Step 6 if iterator.next().is_some() { return Err(()); } // Step 7, 8, 9 Ok((date_tuple, time_tuple)) } } impl Borrow<str> for DOMString { #[inline] fn borrow(&self) -> &str { &self.0 } } impl Default for DOMString { fn default() -> Self { DOMString(String::new(), PhantomData) } } impl Deref for DOMString { type Target = str; #[inline] fn deref(&self) -> &str { &self.0 } } impl DerefMut for DOMString { #[inline] fn deref_mut(&mut self) -> &mut str { &mut self.0 } } impl AsRef<str> for DOMString { fn as_ref(&self) -> &str { &self.0 } } impl fmt::Display for DOMString { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, f) } } impl PartialEq<str> for DOMString { fn eq(&self, other: &str) -> bool { &**self == other } } impl<'a> PartialEq<&'a str> for DOMString { fn eq(&self, other: &&'a str) -> bool { &**self == *other } } impl From<String> for DOMString { fn from(contents: String) -> DOMString { DOMString(contents, PhantomData) } } impl<'a> From<&'a str> for DOMString { fn from(contents: &str) -> DOMString { DOMString::from(String::from(contents)) } } impl<'a> From<Cow<'a, str>> for DOMString { fn from(contents: Cow<'a, str>) -> DOMString { match contents { Cow::Owned(s) => DOMString::from(s), Cow::Borrowed(s) => DOMString::from(s), } } } impl From<DOMString> for LocalName { fn from(contents: DOMString) -> LocalName { LocalName::from(contents.0) } } impl From<DOMString> for Namespace { fn from(contents: DOMString) -> Namespace { Namespace::from(contents.0) } } impl From<DOMString> for Atom { fn from(contents: DOMString) -> Atom { Atom::from(contents.0) } } impl From<DOMString> for String { fn from(contents: DOMString) -> String { contents.0 } } impl Into<Vec<u8>> for DOMString { fn into(self) -> Vec<u8> { self.0.into() } } impl<'a> Into<Cow<'a, str>> for DOMString { fn into(self) -> Cow<'a, str> { self.0.into() } } impl<'a> Into<CowRcStr<'a>> for DOMString { fn into(self) -> CowRcStr<'a> { self.0.into() } } impl Extend<char> for DOMString { fn extend<I>(&mut self, iterable: I) where I: IntoIterator<Item = char>, { self.0.extend(iterable) } } /// https://html.spec.whatwg.org/multipage/#parse-a-month-component fn parse_month_component(value: &str) -> Result<(i32, u32), ()> { // Step 3 let mut iterator = value.split('-'); let year = iterator.next().ok_or(())?; let month = iterator.next().ok_or(())?; // Step 1, 2 let year_int = year.parse::<i32>().map_err(|_| ())?; if year.len() < 4 || year_int == 0 { return Err(()); } // Step 4, 5 let month_int = month.parse::<u32>().map_err(|_| ())?; if month.len()!= 2 || month_int > 12 || month_int < 1 { return Err(()); } // Step 6 Ok((year_int, month_int)) } /// https://html.spec.whatwg.org/multipage/#parse-a-date-component fn parse_date_component(value: &str) -> Result<(i32, u32, u32), ()> { // Step 1 let (year_int, month_int) = parse_month_component(value
value.split(' ') };
conditional_block
str.rs
&mut H) { self.0.hash(state); } } impl FromStr for ByteString { type Err = (); fn from_str(s: &str) -> Result<ByteString, ()> { Ok(ByteString::new(s.to_owned().into_bytes())) } } impl ops::Deref for ByteString { type Target = [u8]; fn deref(&self) -> &[u8] { &self.0 } } /// A string that is constructed from a UCS-2 buffer by replacing invalid code /// points with the replacement character. #[derive(Clone, Default, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd)] pub struct USVString(pub String); impl Borrow<str> for USVString { #[inline] fn borrow(&self) -> &str { &self.0 } } impl Deref for USVString { type Target = str; #[inline] fn deref(&self) -> &str { &self.0 } } impl DerefMut for USVString { #[inline] fn deref_mut(&mut self) -> &mut str { &mut self.0 } } impl AsRef<str> for USVString { fn as_ref(&self) -> &str { &self.0 } } impl fmt::Display for USVString { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, f) } } impl PartialEq<str> for USVString { fn eq(&self, other: &str) -> bool { &**self == other } } impl<'a> PartialEq<&'a str> for USVString { fn eq(&
lf, other: &&'a str) -> bool { &**self == *other } } impl From<String> for USVString { fn from(contents: String) -> USVString { USVString(contents) } } /// Returns whether `s` is a `token`, as defined by /// [RFC 2616](http://tools.ietf.org/html/rfc2616#page-17). pub fn is_token(s: &[u8]) -> bool { if s.is_empty() { return false; // A token must be at least a single character } s.iter().all(|&x| { // http://tools.ietf.org/html/rfc2616#section-2.2 match x { 0..=31 | 127 => false, // CTLs 40 | 41 | 60 | 62 | 64 | 44 | 59 | 58 | 92 | 34 | 47 | 91 | 93 | 63 | 61 | 123 | 125 | 32 => false, // separators x if x > 127 => false, // non-CHARs _ => true, } }) } /// A DOMString. /// /// This type corresponds to the [`DOMString`](idl) type in WebIDL. /// /// [idl]: https://heycam.github.io/webidl/#idl-DOMString /// /// Conceptually, a DOMString has the same value space as a JavaScript String, /// i.e., an array of 16-bit *code units* representing UTF-16, potentially with /// unpaired surrogates present (also sometimes called WTF-16). /// /// Currently, this type stores a Rust `String`, in order to avoid issues when /// integrating with the rest of the Rust ecosystem and even the rest of the /// browser itself. /// /// However, Rust `String`s are guaranteed to be valid UTF-8, and as such have /// a *smaller value space* than WTF-16 (i.e., some JavaScript String values /// can not be represented as a Rust `String`). This introduces the question of /// what to do with values being passed from JavaScript to Rust that contain /// unpaired surrogates. /// /// The hypothesis is that it does not matter much how exactly those values are /// transformed, because passing unpaired surrogates into the DOM is very rare. /// In order to test this hypothesis, Servo will panic when encountering any /// unpaired surrogates on conversion to `DOMString` by default. (The command /// line option `-Z replace-surrogates` instead causes Servo to replace the /// unpaired surrogate by a U+FFFD replacement character.) /// /// Currently, the lack of crash reports about this issue provides some /// evidence to support the hypothesis. This evidence will hopefully be used to /// convince other browser vendors that it would be safe to replace unpaired /// surrogates at the boundary between JavaScript and native code. (This would /// unify the `DOMString` and `USVString` types, both in the WebIDL standard /// and in Servo.) /// /// This type is currently `!Send`, in order to help with an independent /// experiment to store `JSString`s rather than Rust `String`s. #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd)] pub struct DOMString(String, PhantomData<*const ()>); impl DOMString { /// Creates a new `DOMString`. pub fn new() -> DOMString { DOMString(String::new(), PhantomData) } /// Creates a new `DOMString` from a `String`. pub fn from_string(s: String) -> DOMString { DOMString(s, PhantomData) } /// Appends a given string slice onto the end of this String. pub fn push_str(&mut self, string: &str) { self.0.push_str(string) } /// Clears this `DOMString`, removing all contents. pub fn clear(&mut self) { self.0.clear() } /// Shortens this String to the specified length. pub fn truncate(&mut self, new_len: usize) { self.0.truncate(new_len); } /// Removes newline characters according to <https://infra.spec.whatwg.org/#strip-newlines>. pub fn strip_newlines(&mut self) { self.0.retain(|c| c!= '\r' && c!= '\n'); } /// Removes leading and trailing ASCII whitespaces according to /// <https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace>. pub fn strip_leading_and_trailing_ascii_whitespace(&mut self) { if self.0.len() == 0 { return; } let trailing_whitespace_len = self .0 .trim_end_matches(|ref c| char::is_ascii_whitespace(c)) .len(); self.0.truncate(trailing_whitespace_len); if self.0.is_empty() { return; } let first_non_whitespace = self.0.find(|ref c|!char::is_ascii_whitespace(c)).unwrap(); let _ = self.0.replace_range(0..first_non_whitespace, ""); } /// Validates this `DOMString` is a time string according to /// <https://html.spec.whatwg.org/multipage/#valid-time-string>. pub fn is_valid_time_string(&self) -> bool { enum State { HourHigh, HourLow09, HourLow03, MinuteColon, MinuteHigh, MinuteLow, SecondColon, SecondHigh, SecondLow, MilliStop, MilliHigh, MilliMiddle, MilliLow, Done, Error, } let next_state = |valid: bool, next: State| -> State { if valid { next } else { State::Error } }; let state = self.chars().fold(State::HourHigh, |state, c| { match state { // Step 1 "HH" State::HourHigh => match c { '0' | '1' => State::HourLow09, '2' => State::HourLow03, _ => State::Error, }, State::HourLow09 => next_state(c.is_digit(10), State::MinuteColon), State::HourLow03 => next_state(c.is_digit(4), State::MinuteColon), // Step 2 ":" State::MinuteColon => next_state(c == ':', State::MinuteHigh), // Step 3 "mm" State::MinuteHigh => next_state(c.is_digit(6), State::MinuteLow), State::MinuteLow => next_state(c.is_digit(10), State::SecondColon), // Step 4.1 ":" State::SecondColon => next_state(c == ':', State::SecondHigh), // Step 4.2 "ss" State::SecondHigh => next_state(c.is_digit(6), State::SecondLow), State::SecondLow => next_state(c.is_digit(10), State::MilliStop), // Step 4.3.1 "." State::MilliStop => next_state(c == '.', State::MilliHigh), // Step 4.3.2 "SSS" State::MilliHigh => next_state(c.is_digit(10), State::MilliMiddle), State::MilliMiddle => next_state(c.is_digit(10), State::MilliLow), State::MilliLow => next_state(c.is_digit(10), State::Done), _ => State::Error, } }); match state { State::Done | // Step 4 (optional) State::SecondColon | // Step 4.3 (optional) State::MilliStop | // Step 4.3.2 (only 1 digit required) State::MilliMiddle | State::MilliLow => true, _ => false } } /// A valid date string should be "YYYY-MM-DD" /// YYYY must be four or more digits, MM and DD both must be two digits /// https://html.spec.whatwg.org/multipage/#valid-date-string pub fn is_valid_date_string(&self) -> bool { self.parse_date_string().is_ok() } /// https://html.spec.whatwg.org/multipage/#parse-a-date-string pub fn parse_date_string(&self) -> Result<(i32, u32, u32), ()> { let value = &self.0; // Step 1, 2, 3 let (year_int, month_int, day_int) = parse_date_component(value)?; // Step 4 if value.split('-').nth(3).is_some() { return Err(()); } // Step 5, 6 Ok((year_int, month_int, day_int)) } /// https://html.spec.whatwg.org/multipage/#parse-a-time-string pub fn parse_time_string(&self) -> Result<(u32, u32, f64), ()> { let value = &self.0; // Step 1, 2, 3 let (hour_int, minute_int, second_float) = parse_time_component(value)?; // Step 4 if value.split(':').nth(3).is_some() { return Err(()); } // Step 5, 6 Ok((hour_int, minute_int, second_float)) } /// A valid month string should be "YYYY-MM" /// YYYY must be four or more digits, MM both must be two digits /// https://html.spec.whatwg.org/multipage/#valid-month-string pub fn is_valid_month_string(&self) -> bool { self.parse_month_string().is_ok() } /// https://html.spec.whatwg.org/multipage/#parse-a-month-string pub fn parse_month_string(&self) -> Result<(i32, u32), ()> { let value = &self; // Step 1, 2, 3 let (year_int, month_int) = parse_month_component(value)?; // Step 4 if value.split("-").nth(2).is_some() { return Err(()); } // Step 5 Ok((year_int, month_int)) } /// A valid week string should be like {YYYY}-W{WW}, such as "2017-W52" /// YYYY must be four or more digits, WW both must be two digits /// https://html.spec.whatwg.org/multipage/#valid-week-string pub fn is_valid_week_string(&self) -> bool { self.parse_week_string().is_ok() } /// https://html.spec.whatwg.org/multipage/#parse-a-week-string pub fn parse_week_string(&self) -> Result<(i32, u32), ()> { let value = &self.0; // Step 1, 2, 3 let mut iterator = value.split('-'); let year = iterator.next().ok_or(())?; // Step 4 let year_int = year.parse::<i32>().map_err(|_| ())?; if year.len() < 4 || year_int == 0 { return Err(()); } // Step 5, 6 let week = iterator.next().ok_or(())?; let (week_first, week_last) = week.split_at(1); if week_first!= "W" { return Err(()); } // Step 7 let week_int = week_last.parse::<u32>().map_err(|_| ())?; if week_last.len()!= 2 { return Err(()); } // Step 8 let max_week = max_week_in_year(year_int); // Step 9 if week_int < 1 || week_int > max_week { return Err(()); } // Step 10 if iterator.next().is_some() { return Err(()); } // Step 11 Ok((year_int, week_int)) } /// https://html.spec.whatwg.org/multipage/#valid-floating-point-number pub fn is_valid_floating_point_number_string(&self) -> bool { lazy_static! { static ref RE: Regex = Regex::new(r"^-?(?:\d+\.\d+|\d+|\.\d+)(?:(e|E)(\+|\-)?\d+)?$").unwrap(); } RE.is_match(&self.0) && self.parse_floating_point_number().is_ok() } /// https://html.spec.whatwg.org/multipage/#rules-for-parsing-floating-point-number-values pub fn parse_floating_point_number(&self) -> Result<f64, ()> { // Steps 15-16 are telling us things about IEEE rounding modes // for floating-point significands; this code assumes the Rust // compiler already matches them in any cases where // that actually matters. They are not // related to f64::round(), which is for rounding to integers. let input = &self.0; match input.trim().parse::<f64>() { Ok(val) if!( // A valid number is the same as what rust considers to be valid, // except for +1., NaN, and Infinity. val.is_infinite() || val.is_nan() || input.ends_with(".") || input.starts_with("+") ) => { Ok(val) }, _ => Err(()), } } /// https://html.spec.whatwg.org/multipage/#best-representation-of-the-number-as-a-floating-point-number pub fn set_best_representation_of_the_floating_point_number(&mut self) { if let Ok(val) = self.parse_floating_point_number() { self.0 = val.to_string(); } } /// A valid normalized local date and time string should be "{date}T{time}" /// where date and time are both valid, and the time string must be as short as possible /// https://html.spec.whatwg.org/multipage/#valid-normalised-local-date-and-time-string pub fn convert_valid_normalized_local_date_and_time_string(&mut self) -> Result<(), ()> { let ((year, month, day), (hour, minute, second)) = self.parse_local_date_and_time_string()?; if second == 0.0 { self.0 = format!( "{:04}-{:02}-{:02}T{:02}:{:02}", year, month, day, hour, minute ); } else { self.0 = format!( "{:04}-{:02}-{:02}T{:02}:{:02}:{}", year, month, day, hour, minute, second ); } Ok(()) } /// https://html.spec.whatwg.org/multipage/#parse-a-local-date-and-time-string pub fn parse_local_date_and_time_string( &self, ) -> Result<((i32, u32, u32), (u32, u32, f64)), ()> { let value = &self; // Step 1, 2, 4 let mut iterator = if value.contains('T') { value.split('T') } else { value.split(' ') }; // Step 3 let date = iterator.next().ok_or(())?; let date_tuple = parse_date_component(date)?; // Step 5 let time = iterator.next().ok_or(())?; let time_tuple = parse_time_component(time)?; // Step 6 if iterator.next().is_some() { return Err(()); } // Step 7, 8, 9 Ok((date_tuple, time_tuple)) } } impl Borrow<str> for DOMString { #[inline] fn borrow(&self) -> &str { &self.0 } } impl Default for DOMString { fn default() -> Self { DOMString(String::new(), PhantomData) } } impl Deref for DOMString { type Target = str; #[inline] fn deref(&self) -> &str { &self.0 } } impl DerefMut for DOMString { #[inline] fn deref_mut(&mut self) -> &mut str { &mut self.0 } } impl AsRef<str> for DOMString { fn as_ref(&self) -> &str { &self.0 } } impl fmt::Display for DOMString { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, f) } } impl PartialEq<str> for DOMString { fn eq(&self, other: &str) -> bool { &**self == other } } impl<'a> PartialEq<&'a str> for DOMString { fn eq(&self, other: &&'a str) -> bool { &**self == *other } } impl From<String> for DOMString { fn from(contents: String) -> DOMString { DOMString(contents, PhantomData) } } impl<'a> From<&'a str> for DOMString { fn from(contents: &str) -> DOMString { DOMString::from(String::from(contents)) } } impl<'a> From<Cow<'a, str>> for DOMString { fn from(contents: Cow<'a, str>) -> DOMString { match contents { Cow::Owned(s) => DOMString::from(s), Cow::Borrowed(s) => DOMString::from(s), } } } impl From<DOMString> for LocalName { fn from(contents: DOMString) -> LocalName { LocalName::from(contents.0) } } impl From<DOMString> for Namespace { fn from(contents: DOMString) -> Namespace { Namespace::from(contents.0) } } impl From<DOMString> for Atom { fn from(contents: DOMString) -> Atom { Atom::from(contents.0) } } impl From<DOMString> for String { fn from(contents: DOMString) -> String { contents.0 } } impl Into<Vec<u8>> for DOMString { fn into(self) -> Vec<u8> { self.0.into() } } impl<'a> Into<Cow<'a, str>> for DOMString { fn into(self) -> Cow<'a, str> { self.0.into() } } impl<'a> Into<CowRcStr<'a>> for DOMString { fn into(self) -> CowRcStr<'a> { self.0.into() } } impl Extend<char> for DOMString { fn extend<I>(&mut self, iterable: I) where I: IntoIterator<Item = char>, { self.0.extend(iterable) } } /// https://html.spec.whatwg.org/multipage/#parse-a-month-component fn parse_month_component(value: &str) -> Result<(i32, u32), ()> { // Step 3 let mut iterator = value.split('-'); let year = iterator.next().ok_or(())?; let month = iterator.next().ok_or(())?; // Step 1, 2 let year_int = year.parse::<i32>().map_err(|_| ())?; if year.len() < 4 || year_int == 0 { return Err(()); } // Step 4, 5 let month_int = month.parse::<u32>().map_err(|_| ())?; if month.len()!= 2 || month_int > 12 || month_int < 1 { return Err(()); } // Step 6 Ok((year_int, month_int)) } /// https://html.spec.whatwg.org/multipage/#parse-a-date-component fn parse_date_component(value: &str) -> Result<(i32, u32, u32), ()> { // Step 1 let (year_int, month_int) = parse_month_component(
se
identifier_name
str.rs
state: &mut H) { self.0.hash(state); } } impl FromStr for ByteString { type Err = (); fn from_str(s: &str) -> Result<ByteString, ()> { Ok(ByteString::new(s.to_owned().into_bytes())) } } impl ops::Deref for ByteString { type Target = [u8]; fn deref(&self) -> &[u8] { &self.0 } } /// A string that is constructed from a UCS-2 buffer by replacing invalid code /// points with the replacement character. #[derive(Clone, Default, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd)] pub struct USVString(pub String); impl Borrow<str> for USVString { #[inline] fn borrow(&self) -> &str { &self.0 } } impl Deref for USVString { type Target = str; #[inline] fn deref(&self) -> &str { &self.0 } } impl DerefMut for USVString { #[inline] fn deref_mut(&mut self) -> &mut str { &mut self.0 } } impl AsRef<str> for USVString { fn as_ref(&self) -> &str { &self.0 } } impl fmt::Display for USVString { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, f) } } impl PartialEq<str> for USVString { fn eq(&self, other: &str) -> bool { &**self == other } } impl<'a> PartialEq<&'a str> for USVString { fn eq(&self, other: &&'a str) -> bool { &**self == *other } } impl From<String> for USVString { fn from(contents: String) -> USVString { USVString(contents) } } /// Returns whether `s` is a `token`, as defined by /// [RFC 2616](http://tools.ietf.org/html/rfc2616#page-17). pub fn is_token(s: &[u8]) -> bool { if s.is_empty() { return false; // A token must be at least a single character } s.iter().all(|&x| { // http://tools.ietf.org/html/rfc2616#section-2.2 match x { 0..=31 | 127 => false, // CTLs 40 | 41 | 60 | 62 | 64 | 44 | 59 | 58 | 92 | 34 | 47 | 91 | 93 | 63 | 61 | 123 | 125 | 32 => false, // separators x if x > 127 => false, // non-CHARs _ => true, } }) } /// A DOMString. /// /// This type corresponds to the [`DOMString`](idl) type in WebIDL. /// /// [idl]: https://heycam.github.io/webidl/#idl-DOMString /// /// Conceptually, a DOMString has the same value space as a JavaScript String, /// i.e., an array of 16-bit *code units* representing UTF-16, potentially with /// unpaired surrogates present (also sometimes called WTF-16). /// /// Currently, this type stores a Rust `String`, in order to avoid issues when /// integrating with the rest of the Rust ecosystem and even the rest of the /// browser itself. /// /// However, Rust `String`s are guaranteed to be valid UTF-8, and as such have /// a *smaller value space* than WTF-16 (i.e., some JavaScript String values /// can not be represented as a Rust `String`). This introduces the question of /// what to do with values being passed from JavaScript to Rust that contain /// unpaired surrogates. /// /// The hypothesis is that it does not matter much how exactly those values are /// transformed, because passing unpaired surrogates into the DOM is very rare. /// In order to test this hypothesis, Servo will panic when encountering any /// unpaired surrogates on conversion to `DOMString` by default. (The command /// line option `-Z replace-surrogates` instead causes Servo to replace the /// unpaired surrogate by a U+FFFD replacement character.) /// /// Currently, the lack of crash reports about this issue provides some /// evidence to support the hypothesis. This evidence will hopefully be used to /// convince other browser vendors that it would be safe to replace unpaired /// surrogates at the boundary between JavaScript and native code. (This would /// unify the `DOMString` and `USVString` types, both in the WebIDL standard /// and in Servo.) /// /// This type is currently `!Send`, in order to help with an independent /// experiment to store `JSString`s rather than Rust `String`s. #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd)] pub struct DOMString(String, PhantomData<*const ()>); impl DOMString { /// Creates a new `DOMString`. pub fn new() -> DOMString { DOMString(String::new(), PhantomData) } /// Creates a new `DOMString` from a `String`. pub fn from_string(s: String) -> DOMString { DOMString(s, PhantomData) } /// Appends a given string slice onto the end of this String. pub fn push_str(&mut self, string: &str) { self.0.push_str(string) } /// Clears this `DOMString`, removing all contents. pub fn clear(&mut self) { self.0.clear() } /// Shortens this String to the specified length. pub fn truncate(&mut self, new_len: usize) { self.0.truncate(new_len); } /// Removes newline characters according to <https://infra.spec.whatwg.org/#strip-newlines>. pub fn strip_newlines(&mut self) { self.0.retain(|c| c!= '\r' && c!= '\n'); } /// Removes leading and trailing ASCII whitespaces according to /// <https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace>. pub fn strip_leading_and_trailing_ascii_whitespace(&mut self) { if self.0.len() == 0 { return; } let trailing_whitespace_len = self .0 .trim_end_matches(|ref c| char::is_ascii_whitespace(c)) .len(); self.0.truncate(trailing_whitespace_len); if self.0.is_empty() { return; } let first_non_whitespace = self.0.find(|ref c|!char::is_ascii_whitespace(c)).unwrap(); let _ = self.0.replace_range(0..first_non_whitespace, ""); } /// Validates this `DOMString` is a time string according to /// <https://html.spec.whatwg.org/multipage/#valid-time-string>. pub fn is_valid_time_string(&self) -> bool { enum State { HourHigh, HourLow09, HourLow03, MinuteColon, MinuteHigh, MinuteLow, SecondColon, SecondHigh, SecondLow, MilliStop, MilliHigh, MilliMiddle, MilliLow, Done, Error, } let next_state = |valid: bool, next: State| -> State { if valid { next } else { State::Error } }; let state = self.chars().fold(State::HourHigh, |state, c| { match state { // Step 1 "HH" State::HourHigh => match c { '0' | '1' => State::HourLow09, '2' => State::HourLow03, _ => State::Error, }, State::HourLow09 => next_state(c.is_digit(10), State::MinuteColon), State::HourLow03 => next_state(c.is_digit(4), State::MinuteColon), // Step 2 ":" State::MinuteColon => next_state(c == ':', State::MinuteHigh), // Step 3 "mm" State::MinuteHigh => next_state(c.is_digit(6), State::MinuteLow), State::MinuteLow => next_state(c.is_digit(10), State::SecondColon), // Step 4.1 ":" State::SecondColon => next_state(c == ':', State::SecondHigh), // Step 4.2 "ss" State::SecondHigh => next_state(c.is_digit(6), State::SecondLow), State::SecondLow => next_state(c.is_digit(10), State::MilliStop), // Step 4.3.1 "." State::MilliStop => next_state(c == '.', State::MilliHigh), // Step 4.3.2 "SSS" State::MilliHigh => next_state(c.is_digit(10), State::MilliMiddle), State::MilliMiddle => next_state(c.is_digit(10), State::MilliLow), State::MilliLow => next_state(c.is_digit(10), State::Done), _ => State::Error, } }); match state { State::Done | // Step 4 (optional) State::SecondColon | // Step 4.3 (optional) State::MilliStop | // Step 4.3.2 (only 1 digit required) State::MilliMiddle | State::MilliLow => true, _ => false } } /// A valid date string should be "YYYY-MM-DD" /// YYYY must be four or more digits, MM and DD both must be two digits /// https://html.spec.whatwg.org/multipage/#valid-date-string pub fn is_valid_date_string(&self) -> bool { self.parse_date_string().is_ok() } /// https://html.spec.whatwg.org/multipage/#parse-a-date-string pub fn parse_date_string(&self) -> Result<(i32, u32, u32), ()> { let value = &self.0; // Step 1, 2, 3 let (year_int, month_int, day_int) = parse_date_component(value)?; // Step 4 if value.split('-').nth(3).is_some() { return Err(()); } // Step 5, 6 Ok((year_int, month_int, day_int)) } /// https://html.spec.whatwg.org/multipage/#parse-a-time-string pub fn parse_time_string(&self) -> Result<(u32, u32, f64), ()> { let value = &self.0; // Step 1, 2, 3 let (hour_int, minute_int, second_float) = parse_time_component(value)?; // Step 4 if value.split(':').nth(3).is_some() { return Err(()); } // Step 5, 6 Ok((hour_int, minute_int, second_float)) } /// A valid month string should be "YYYY-MM" /// YYYY must be four or more digits, MM both must be two digits /// https://html.spec.whatwg.org/multipage/#valid-month-string pub fn is_valid_month_string(&self) -> bool { self.parse_month_string().is_ok() } /// https://html.spec.whatwg.org/multipage/#parse-a-month-string pub fn parse_month_string(&self) -> Result<(i32, u32), ()> { let value = &self; // Step 1, 2, 3 let (year_int, month_int) = parse_month_component(value)?; // Step 4 if value.split("-").nth(2).is_some() { return Err(()); } // Step 5 Ok((year_int, month_int)) } /// A valid week string should be like {YYYY}-W{WW}, such as "2017-W52" /// YYYY must be four or more digits, WW both must be two digits /// https://html.spec.whatwg.org/multipage/#valid-week-string pub fn is_valid_week_string(&self) -> bool { self.parse_week_string().is_ok() } /// https://html.spec.whatwg.org/multipage/#parse-a-week-string pub fn parse_week_string(&self) -> Result<(i32, u32), ()> { let value = &self.0; // Step 1, 2, 3 let mut iterator = value.split('-'); let year = iterator.next().ok_or(())?; // Step 4 let year_int = year.parse::<i32>().map_err(|_| ())?; if year.len() < 4 || year_int == 0 { return Err(()); } // Step 5, 6 let week = iterator.next().ok_or(())?; let (week_first, week_last) = week.split_at(1); if week_first!= "W" { return Err(()); } // Step 7 let week_int = week_last.parse::<u32>().map_err(|_| ())?; if week_last.len()!= 2 { return Err(()); } // Step 8 let max_week = max_week_in_year(year_int); // Step 9 if week_int < 1 || week_int > max_week { return Err(()); } // Step 10 if iterator.next().is_some() { return Err(()); } // Step 11 Ok((year_int, week_int)) } /// https://html.spec.whatwg.org/multipage/#valid-floating-point-number pub fn is_valid_floating_point_number_string(&self) -> bool { lazy_static! { static ref RE: Regex = Regex::new(r"^-?(?:\d+\.\d+|\d+|\.\d+)(?:(e|E)(\+|\-)?\d+)?$").unwrap(); } RE.is_match(&self.0) && self.parse_floating_point_number().is_ok() } /// https://html.spec.whatwg.org/multipage/#rules-for-parsing-floating-point-number-values pub fn parse_floating_point_number(&self) -> Result<f64, ()> { // Steps 15-16 are telling us things about IEEE rounding modes // for floating-point significands; this code assumes the Rust // compiler already matches them in any cases where // that actually matters. They are not // related to f64::round(), which is for rounding to integers. let input = &self.0; match input.trim().parse::<f64>() { Ok(val) if!( // A valid number is the same as what rust considers to be valid, // except for +1., NaN, and Infinity. val.is_infinite() || val.is_nan() || input.ends_with(".") || input.starts_with("+") ) => { Ok(val) }, _ => Err(()), } } /// https://html.spec.whatwg.org/multipage/#best-representation-of-the-number-as-a-floating-point-number pub fn set_best_representation_of_the_floating_point_number(&mut self) { if let Ok(val) = self.parse_floating_point_number() { self.0 = val.to_string(); } } /// A valid normalized local date and time string should be "{date}T{time}" /// where date and time are both valid, and the time string must be as short as possible /// https://html.spec.whatwg.org/multipage/#valid-normalised-local-date-and-time-string pub fn convert_valid_normalized_local_date_and_time_string(&mut self) -> Result<(), ()> { let ((year, month, day), (hour, minute, second)) = self.parse_local_date_and_time_string()?; if second == 0.0 { self.0 = format!( "{:04}-{:02}-{:02}T{:02}:{:02}", year, month, day, hour, minute ); } else { self.0 = format!( "{:04}-{:02}-{:02}T{:02}:{:02}:{}", year, month, day, hour, minute, second ); } Ok(()) } /// https://html.spec.whatwg.org/multipage/#parse-a-local-date-and-time-string pub fn parse_local_date_and_time_string( &self, ) -> Result<((i32, u32, u32), (u32, u32, f64)), ()> { let value = &self; // Step 1, 2, 4 let mut iterator = if value.contains('T') { value.split('T') } else { value.split(' ') }; // Step 3 let date = iterator.next().ok_or(())?; let date_tuple = parse_date_component(date)?; // Step 5 let time = iterator.next().ok_or(())?; let time_tuple = parse_time_component(time)?; // Step 6 if iterator.next().is_some() { return Err(()); } // Step 7, 8, 9 Ok((date_tuple, time_tuple)) } } impl Borrow<str> for DOMString { #[inline] fn borrow(&self) -> &str { &self.0 } } impl Default for DOMString { fn default() -> Self { DOMString(String::new(), PhantomData) } } impl Deref for DOMString { type Target = str;
#[inline] fn deref(&self) -> &str { &self.0 } } impl DerefMut for DOMString { #[inline] fn deref_mut(&mut self) -> &mut str { &mut self.0 } } impl AsRef<str> for DOMString { fn as_ref(&self) -> &str { &self.0 } } impl fmt::Display for DOMString { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, f) } } impl PartialEq<str> for DOMString { fn eq(&self, other: &str) -> bool { &**self == other } } impl<'a> PartialEq<&'a str> for DOMString { fn eq(&self, other: &&'a str) -> bool { &**self == *other } } impl From<String> for DOMString { fn from(contents: String) -> DOMString { DOMString(contents, PhantomData) } } impl<'a> From<&'a str> for DOMString { fn from(contents: &str) -> DOMString { DOMString::from(String::from(contents)) } } impl<'a> From<Cow<'a, str>> for DOMString { fn from(contents: Cow<'a, str>) -> DOMString { match contents { Cow::Owned(s) => DOMString::from(s), Cow::Borrowed(s) => DOMString::from(s), } } } impl From<DOMString> for LocalName { fn from(contents: DOMString) -> LocalName { LocalName::from(contents.0) } } impl From<DOMString> for Namespace { fn from(contents: DOMString) -> Namespace { Namespace::from(contents.0) } } impl From<DOMString> for Atom { fn from(contents: DOMString) -> Atom { Atom::from(contents.0) } } impl From<DOMString> for String { fn from(contents: DOMString) -> String { contents.0 } } impl Into<Vec<u8>> for DOMString { fn into(self) -> Vec<u8> { self.0.into() } } impl<'a> Into<Cow<'a, str>> for DOMString { fn into(self) -> Cow<'a, str> { self.0.into() } } impl<'a> Into<CowRcStr<'a>> for DOMString { fn into(self) -> CowRcStr<'a> { self.0.into() } } impl Extend<char> for DOMString { fn extend<I>(&mut self, iterable: I) where I: IntoIterator<Item = char>, { self.0.extend(iterable) } } /// https://html.spec.whatwg.org/multipage/#parse-a-month-component fn parse_month_component(value: &str) -> Result<(i32, u32), ()> { // Step 3 let mut iterator = value.split('-'); let year = iterator.next().ok_or(())?; let month = iterator.next().ok_or(())?; // Step 1, 2 let year_int = year.parse::<i32>().map_err(|_| ())?; if year.len() < 4 || year_int == 0 { return Err(()); } // Step 4, 5 let month_int = month.parse::<u32>().map_err(|_| ())?; if month.len()!= 2 || month_int > 12 || month_int < 1 { return Err(()); } // Step 6 Ok((year_int, month_int)) } /// https://html.spec.whatwg.org/multipage/#parse-a-date-component fn parse_date_component(value: &str) -> Result<(i32, u32, u32), ()> { // Step 1 let (year_int, month_int) = parse_month_component(value)?;
random_line_split
16843_H2.rs
Per(s)PSA @ damp 02% PSA @ damp 05% PSA @ damp 07% PSA @ damp 10% PSA @ damp 20% PSA @ damp 30% (m/s/s) 0.000 1.2913000E-001 1.2913000E-001 1.2913000E-001 1.2913000E-001 1.2913000E-001 1.2913000E-001 0.010 1.2913360E-001 1.2913613E-001 1.2913640E-001 1.2913629E-001 1.2913558E-001 1.2913461E-001 0.020 1.2915231E-001 1.2915239E-001 1.2915218E-001 1.2915164E-001 1.2914930E-001 1.2914635E-001 0.030 1.2916261E-001 1.2916411E-001 1.2916511E-001 1.2916619E-001 1.2916665E-001 1.2916389E-001 0.040 1.2921219E-001 1.2920949E-001 1.2920821E-001 1.2920611E-001 1.2920001E-001 1.2919329E-001 0.050 1.2921681E-001 1.2922041E-001 1.2922579E-001 1.2923214E-001 1.2923875E-001 1.2923248E-001 0.075 1.2957017E-001 1.2948889E-001 1.2946925E-001 1.2945361E-001 1.2942289E-001 1.2939022E-001 0.100 1.3159746E-001 1.3037595E-001 1.3007656E-001 1.2985694E-001 1.2962759E-001 1.2959455E-001 0.110 1.2984712E-001 1.2975469E-001 1.2975976E-001 1.2985192E-001 1.2986232E-001 1.2971316E-001 0.120 1.3077432E-001 1.3020417E-001 1.3020512E-001 1.3022786E-001 1.3017425E-001 1.2998855E-001 0.130 1.3161880E-001 1.3102892E-001 1.3090348E-001 1.3079141E-001 1.3054974E-001 1.3029180E-001 0.140 1.3259299E-001 1.3165945E-001 1.3132356E-001 1.3125429E-001 1.3093366E-001 1.3061287E-001 0.150 1.3565391E-001 1.3342097E-001 1.3334017E-001 1.3297413E-001 1.3178256E-001 1.3097739E-001 0.160 1.4432240E-001 1.3795647E-001 1.3644022E-001 1.3521270E-001 1.3324597E-001 1.3199154E-001 0.170 1.3468261E-001 1.3712779E-001 1.3716155E-001 1.3655764E-001 1.3468631E-001 1.3305108E-001 0.180 1.5921161E-001 1.3842295E-001 1.3759238E-001 1.3749480E-001 1.3619816E-001 1.3414915E-001 0.190 1.6675156E-001 1.3880195E-001 1.3837703E-001 1.3943501E-001 1.3797025E-001 1.3528071E-001 0.200 1.6987601E-001 1.4801158E-001 1.4601976E-001 1.4431787E-001 1.4005554E-001 1.3641547E-001 0.220 1.9268166E-001 1.6949527E-001 1.6224015E-001 1.5549053E-001 1.4429341E-001 1.3845192E-001 0.240 1.9155322E-001 1.6686396E-001 1.6456133E-001 1.6040896E-001 1.4713363E-001 1.3977952E-001 0.260 2.1385278E-001 1.8472162E-001 1.7541498E-001 1.6544260E-001 1.4804198E-001 1.4018896E-001 0.280 2.1832441E-001 1.8432660E-001 1.7411493E-001 1.6354592E-001 1.4671156E-001 1.3975798E-001 0.300 2.1541482E-001 1.8507345E-001 1.7141443E-001 1.5834181E-001 1.4448695E-001 1.4066619E-001 0.320 2.8846803E-001 1.8038215E-001 1.7292826E-001 1.6365641E-001 1.4741646E-001 1.4223142E-001 0.340 2.1981412E-001 1.9227949E-001 1.8390042E-001 1.7239921E-001 1.4986774E-001 1.4396881E-001 0.360 3.0142096E-001 2.3537421E-001 2.1785957E-001 1.9616775E-001 1.5463503E-001 1.4584914E-001 0.380 3.5109425E-001 2.9019102E-001 2.5198179E-001 2.1396267E-001 1.5906401E-001 1.4820157E-001 0.400 4.9607569E-001 2.9760507E-001 2.4915728E-001 2.0996036E-001 1.5925483E-001 1.5085845E-001 0.420 2.6296914E-001 2.2062084E-001 2.0299484E-001 1.8517837E-001 1.6341034E-001 1.5365759E-001 0.440 2.6643819E-001 2.1635883E-001 2.0006937E-001 1.9010341E-001 1.6986543E-001 1.5638320E-001 0.460 2.9266268E-001 2.4918723E-001 2.2907300E-001 2.0910951E-001 1.7608745E-001 1.5881459E-001 0.480 3.5950878E-001 2.6947156E-001 2.4578035E-001 2.2260234E-001 1.8127638E-001 1.6073985E-001 0.500 2.7006108E-001 2.6075462E-001 2.5047719E-001 2.3099084E-001 1.8497232E-001 1.6204323E-001 0.550 4.9328771E-001 3.3264616E-001 2.8584355E-001 2.4444793E-001 1.8638256E-001 1.6239737E-001 0.600 4.3671170E-001 3.3953878E-001 3.0230883E-001 2.6124862E-001 1.9344032E-001 1.6620257E-001
0.850 5.5704033E-001 3.8282755E-001 3.2834914E-001 2.7688667E-001 2.2146527E-001 1.8825164E-001 0.900 6.7406952E-001 4.6881771E-001 3.9615718E-001 3.3011246E-001 2.3729219E-001 1.9391888E-001 0.950 6.9230747E-001 4.9054167E-001 4.1994503E-001 3.5270956E-001 2.4773170E-001 1.9823655E-001 1.000 6.5518957E-001 4.5714578E-001 3.9079541E-001 3.4190845E-001 2.5271231E-001 2.0135500E-001 1.100 7.4664891E-001 5.2378768E-001 4.4087610E-001 3.7498334E-001 2.6082474E-001 2.0497963E-001 1.200 5.7735598E-001 4.7785038E-001 4.1401985E-001 3.7635654E-001 2.6380095E-001 2.0465401E-001 1.300 7.7835774E-001 5.2056247E-001 4.5764345E-001 3.9052933E-001 2.5554368E-001 2.0006523E-001 1.400 6.4661270E-001 4.8457909E-001 4.3476295E-001 3.7069684E-001 2.4752796E-001 1.9131818E-001 1.500 5.6205094E-001 4.4049338E-001 3.8673472E-001 3.2575890E-001 2.3151307E-001 1.7923491E-001 1.600 4.1930878E-001 3.5512742E-001 3.2265058E-001 2.8571886E-001 2.1047375E-001 1.6533205E-001 1.700 6.4699197E-001 4.5628104E-001 3.8239244E-001 3.1244794E-001 2.1290654E-001 1.6431171E-001 1.800 6.3576359E-001 4.7732174E-001 4.0150422E-001 3.2747546E-001 2.1925257E-001 1.6373569E-001 1.900 5.4431248E-001 4.3190563E-001 3.8004619E-001 3.2212585E-001 2.1662244E-001 1.5922195E-001 2.000 5.5421597E-001 4.1696417E-001 3.6946398E-001 3.1319329E-001 2.0710649E-001 1.5151551E-001 2.200 5.1986110E-001 3.7226915E-001 3.1638232E-001 2.6208043E-001 1.7386132E-001 1.3051872E-001 2.400 2.2987238E-001 2.0340221E-001 1.8332106E-001 1.6847828E-001 1.3638358E-001 1.0827857E-001 2.600 1.9414009E-001 1.4694317E-001 1.4223607E-001 1.3143629E-001 1.0881983E-001 8.9078350E-002 2.800 2.1904181E-001 1.5008719E-001 1.2882473E-001 1.1517445E-001 8.9408220E-002 7.3380370E-002 3.000 1.7631400E-001 1.2689121E-001 1.0658292E-001 9.5457400E-002 7.6998500E-002 6.5091770E-002 3.200 1.4021914E-001 9.7044770E-002 9.2792640E-002 8.6207520E-002 6.9399860E-002 5.8337780E-002 3.400 1.2514071E-001 9.3710900E-002 8.5438200E-002 7.7180970E-002 6.1704300E-002 5.2122660E-002 3.600 7.1263050E-002 6.9277560E-002 6.7425160E-002 6.4216730E-002 5.4160780E-002 4.6391900E-002 3.800 4.9205470E-002 5.2887010E-002 5.4010660E-002 5.3625030E-002 4.7348520E-002 4.1180020E-002 4.000 5.3168640E-002 5.0726760E-002 4.9400710E-002 4.7491730E-002 4.1463640E-002 3.6501830E-002 4.200 5.4895780E-002 4.8576110E-002 4.5640840E-002 4.2438090E-002 3.6266940E-002 3.2326100E-002 4.400 4.9211180E-002 4.2198370E-002 3.9337300E-002 3.6443050E-002 3.1525780E-002 2.8612570E-002 4.600 4.5159100E-002 3.8682800E-002 3.5769130E-002 3.2603790E-002 2.7217210E-002 2.5337880E-002 4.800 3.9804830E-002 3.5144990E-002 3.2736410E-002 2.9945900E-002 2.4566930E-002 2.2484270E-002 5.000 3.3016370E-002 3.0023660E-002 2.8433770E-002 2.6499270E-002 2.2353110E-002 2.0031930E-002 5.500 1.8736540E-002 1.7799860E-002 1.8192140E-002 1.8325740E-002 1.7323150E-002 1.5988440E-002 6.000 1.4625570E-002 1.3906150E-002 1.3974340E-002 1.3999330E-002 1.3616490E-002 1.2950220E-002 6.500 1.2994920E-002 1.2027190E-002 1.1659240E-002 1.1336250E-002 1.0934720E-002 1.0625840E-002 7.000 1.1493440E-002 1.0200500E-002 9.6755700E-003 9.0688900E-003 8.8779900E-003 8.8506800E-003 7.500 9.8616500E-003 8.9026200E-003 8.4259600E-003 7.8744500E-003 7.6489100E-003 7.6190300E-003 8.000 8.9555000E-003 8.1611100E-003 7.7976300E-003 7.4157100E-003 6.8566300E-003 6.6989800E-003 8.500 7.7450800E-003 7.2227200E-003 6.9477500E-003 6.6290900E-003 6.0904100E-003 5.9152800E-003 9.000 6.1925800E-003 5.9542200E-003 5.8210100E-003 5.6576100E-003 5.3499400E-003 5.2342600E-003 9.500 5.4911300E-003 5.2380600E-003 5.1052300E-003 4.9523600E-003 4.6927800E-003 4.6441500E-003 10.00 5.4414600E-003 5.0656600E-003 4.8777700E-003 4.6641000E-003 4.2958600E-003 4.1544700E-003 -1 3.2372954E-002 3.2372954E-002 3.2372954E-002 3.2372954E-002 3.2372954E-002 3.2372954E-002
0.650 4.7647312E-001 3.5121968E-001 3.0050832E-001 2.5218114E-001 1.9111256E-001 1.6741602E-001 0.700 5.9655309E-001 3.8487825E-001 3.2717097E-001 2.7232391E-001 1.8298441E-001 1.6780384E-001 0.750 4.4711676E-001 3.2956755E-001 2.9612157E-001 2.5945029E-001 1.9378230E-001 1.7481418E-001 0.800 3.8252521E-001 2.8678602E-001 2.6020724E-001 2.3827465E-001 2.0535292E-001 1.8167761E-001
random_line_split
counterfeit.rs
extern crate glktest; extern crate glulx; extern crate iff; use std::time::Instant; use glktest::TestOutput::Match; mod common; #[test] #[ignore] fn
() { let start = Instant::now(); assert!(common::run_blorb("CounterfeitMonkey-6.gblorb", vec![ (Match("\n\n\nCan you hear me? >> "), "yes"), (Match("\nGood, you\'re conscious. We\'re conscious. I\'ve heard urban legends about synthesis going wrong, one half person getting lost.\n\nDo you remember our name?\n\n>"), "yes"), (Match("Right, we're Alexandra now. Before the synthesis, I was Alex. You were...\n\n>"), "andra"), (Match("...yes! Okay. We\'re both here, neither of us lost our minds in the synthesis process. As far as I can tell, the operation was a success. We\'re meant to be one person now, unrecognizable to anyone who knew us before.\n\n"), " "), (Match("Counterfeit Monkey\nA Removal by Emily Short\nRelease 6 / Serial number 160520 / Inform 7 build 6G60 (I6/v6.32 lib 6/12N) \n\n\nLet\'s try to get a look around. I haven\'t been able to run our body without your help, but maybe now you\'re awake, it\'ll work better.\n\nTo get a look around, type LOOK and press return. If you do not want help getting started, type TUTORIAL OFF.\n>"), "quit"), (Match("Are you sure you want to quit? "), "y"), ]).is_ok()); let t = Instant::now().duration_since(start); println!("Time: {}.{:09}", t.as_secs(), t.subsec_nanos()); }
counterfeit
identifier_name
counterfeit.rs
extern crate glktest; extern crate glulx; extern crate iff; use std::time::Instant; use glktest::TestOutput::Match; mod common; #[test] #[ignore] fn counterfeit()
{ let start = Instant::now(); assert!(common::run_blorb("CounterfeitMonkey-6.gblorb", vec![ (Match("\n\n\nCan you hear me? >> "), "yes"), (Match("\nGood, you\'re conscious. We\'re conscious. I\'ve heard urban legends about synthesis going wrong, one half person getting lost.\n\nDo you remember our name?\n\n>"), "yes"), (Match("Right, we're Alexandra now. Before the synthesis, I was Alex. You were...\n\n>"), "andra"), (Match("...yes! Okay. We\'re both here, neither of us lost our minds in the synthesis process. As far as I can tell, the operation was a success. We\'re meant to be one person now, unrecognizable to anyone who knew us before.\n\n"), " "), (Match("Counterfeit Monkey\nA Removal by Emily Short\nRelease 6 / Serial number 160520 / Inform 7 build 6G60 (I6/v6.32 lib 6/12N) \n\n\nLet\'s try to get a look around. I haven\'t been able to run our body without your help, but maybe now you\'re awake, it\'ll work better.\n\nTo get a look around, type LOOK and press return. If you do not want help getting started, type TUTORIAL OFF.\n>"), "quit"), (Match("Are you sure you want to quit? "), "y"), ]).is_ok()); let t = Instant::now().duration_since(start); println!("Time: {}.{:09}", t.as_secs(), t.subsec_nanos()); }
identifier_body
counterfeit.rs
extern crate glktest; extern crate glulx; extern crate iff; use std::time::Instant; use glktest::TestOutput::Match; mod common;
let start = Instant::now(); assert!(common::run_blorb("CounterfeitMonkey-6.gblorb", vec![ (Match("\n\n\nCan you hear me? >> "), "yes"), (Match("\nGood, you\'re conscious. We\'re conscious. I\'ve heard urban legends about synthesis going wrong, one half person getting lost.\n\nDo you remember our name?\n\n>"), "yes"), (Match("Right, we're Alexandra now. Before the synthesis, I was Alex. You were...\n\n>"), "andra"), (Match("...yes! Okay. We\'re both here, neither of us lost our minds in the synthesis process. As far as I can tell, the operation was a success. We\'re meant to be one person now, unrecognizable to anyone who knew us before.\n\n"), " "), (Match("Counterfeit Monkey\nA Removal by Emily Short\nRelease 6 / Serial number 160520 / Inform 7 build 6G60 (I6/v6.32 lib 6/12N) \n\n\nLet\'s try to get a look around. I haven\'t been able to run our body without your help, but maybe now you\'re awake, it\'ll work better.\n\nTo get a look around, type LOOK and press return. If you do not want help getting started, type TUTORIAL OFF.\n>"), "quit"), (Match("Are you sure you want to quit? "), "y"), ]).is_ok()); let t = Instant::now().duration_since(start); println!("Time: {}.{:09}", t.as_secs(), t.subsec_nanos()); }
#[test] #[ignore] fn counterfeit() {
random_line_split
007.rs
#![feature(associated_types, slicing_syntax)] extern crate test; extern crate time; use std::collections::HashMap; use std::io::stdio; use std::os; struct Primes { map: HashMap<u32, u32>, n: u32, } impl Iterator for Primes { type Item = u32; fn next(&mut self) -> Option<u32> { loop { self.n += 1; let q = self.n; match self.map.remove(&q) { None => { self.map.insert(q * q, q); return Some(q); }, Some(p) => { let mut x = p + q; while self.map.contains_key(&x) { x += p; } self.map.insert(x, p); }, } } } } fn primes(capacity: uint) -> Primes { Primes { map: HashMap::with_capacity(capacity), n: 1, } } fn solution() -> u32 { let target = 10_000; primes(target).nth(target).unwrap() } fn main() { match os::args()[] { [_, ref flag] if flag[] == "-a" => return println!("{}", solution()), _ =>
, } for line in stdio::stdin().lock().lines() { let iters: u64 = line.unwrap()[].trim().parse().unwrap(); let start = time::precise_time_ns(); for _ in range(0, iters) { test::black_box(solution()); } let end = time::precise_time_ns(); println!("{}", end - start); } }
{}
conditional_block
007.rs
#![feature(associated_types, slicing_syntax)] extern crate test; extern crate time; use std::collections::HashMap; use std::io::stdio; use std::os; struct Primes { map: HashMap<u32, u32>, n: u32, } impl Iterator for Primes { type Item = u32; fn next(&mut self) -> Option<u32> { loop { self.n += 1; let q = self.n; match self.map.remove(&q) { None => { self.map.insert(q * q, q); return Some(q); }, Some(p) => { let mut x = p + q; while self.map.contains_key(&x) { x += p; } self.map.insert(x, p); }, } } } } fn primes(capacity: uint) -> Primes { Primes { map: HashMap::with_capacity(capacity), n: 1, } } fn solution() -> u32 { let target = 10_000; primes(target).nth(target).unwrap() } fn main() { match os::args()[] { [_, ref flag] if flag[] == "-a" => return println!("{}", solution()), _ => {}, } for line in stdio::stdin().lock().lines() { let iters: u64 = line.unwrap()[].trim().parse().unwrap(); let start = time::precise_time_ns(); for _ in range(0, iters) { test::black_box(solution());
let end = time::precise_time_ns(); println!("{}", end - start); } }
}
random_line_split
007.rs
#![feature(associated_types, slicing_syntax)] extern crate test; extern crate time; use std::collections::HashMap; use std::io::stdio; use std::os; struct Primes { map: HashMap<u32, u32>, n: u32, } impl Iterator for Primes { type Item = u32; fn next(&mut self) -> Option<u32> { loop { self.n += 1; let q = self.n; match self.map.remove(&q) { None => { self.map.insert(q * q, q); return Some(q); }, Some(p) => { let mut x = p + q; while self.map.contains_key(&x) { x += p; } self.map.insert(x, p); }, } } } } fn primes(capacity: uint) -> Primes
fn solution() -> u32 { let target = 10_000; primes(target).nth(target).unwrap() } fn main() { match os::args()[] { [_, ref flag] if flag[] == "-a" => return println!("{}", solution()), _ => {}, } for line in stdio::stdin().lock().lines() { let iters: u64 = line.unwrap()[].trim().parse().unwrap(); let start = time::precise_time_ns(); for _ in range(0, iters) { test::black_box(solution()); } let end = time::precise_time_ns(); println!("{}", end - start); } }
{ Primes { map: HashMap::with_capacity(capacity), n: 1, } }
identifier_body
007.rs
#![feature(associated_types, slicing_syntax)] extern crate test; extern crate time; use std::collections::HashMap; use std::io::stdio; use std::os; struct Primes { map: HashMap<u32, u32>, n: u32, } impl Iterator for Primes { type Item = u32; fn next(&mut self) -> Option<u32> { loop { self.n += 1; let q = self.n; match self.map.remove(&q) { None => { self.map.insert(q * q, q); return Some(q); }, Some(p) => { let mut x = p + q; while self.map.contains_key(&x) { x += p; } self.map.insert(x, p); }, } } } } fn
(capacity: uint) -> Primes { Primes { map: HashMap::with_capacity(capacity), n: 1, } } fn solution() -> u32 { let target = 10_000; primes(target).nth(target).unwrap() } fn main() { match os::args()[] { [_, ref flag] if flag[] == "-a" => return println!("{}", solution()), _ => {}, } for line in stdio::stdin().lock().lines() { let iters: u64 = line.unwrap()[].trim().parse().unwrap(); let start = time::precise_time_ns(); for _ in range(0, iters) { test::black_box(solution()); } let end = time::precise_time_ns(); println!("{}", end - start); } }
primes
identifier_name
trace_macros.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. use ast; use codemap::span; use ext::base::ExtCtxt; use ext::base; use parse::lexer::{new_tt_reader, reader}; use parse::parser::Parser; use parse::token::keywords; pub fn
(cx: @ExtCtxt, sp: span, tt: &[ast::token_tree]) -> base::MacResult { let sess = cx.parse_sess(); let cfg = cx.cfg(); let tt_rdr = new_tt_reader( copy cx.parse_sess().span_diagnostic, None, tt.to_owned() ); let rdr = tt_rdr as @reader; let rust_parser = Parser( sess, copy cfg, rdr.dup() ); if rust_parser.is_keyword(keywords::True) { cx.set_trace_macros(true); } else if rust_parser.is_keyword(keywords::False) { cx.set_trace_macros(false); } else { cx.span_fatal(sp, "trace_macros! only accepts `true` or `false`") } rust_parser.bump(); let rust_parser = Parser(sess, cfg, rdr.dup()); let result = rust_parser.parse_expr(); base::MRExpr(result) }
expand_trace_macros
identifier_name
trace_macros.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. use ast; use codemap::span; use ext::base::ExtCtxt; use ext::base; use parse::lexer::{new_tt_reader, reader}; use parse::parser::Parser; use parse::token::keywords; pub fn expand_trace_macros(cx: @ExtCtxt, sp: span, tt: &[ast::token_tree]) -> base::MacResult { let sess = cx.parse_sess(); let cfg = cx.cfg(); let tt_rdr = new_tt_reader( copy cx.parse_sess().span_diagnostic, None, tt.to_owned() ); let rdr = tt_rdr as @reader; let rust_parser = Parser( sess, copy cfg, rdr.dup() ); if rust_parser.is_keyword(keywords::True) { cx.set_trace_macros(true); } else if rust_parser.is_keyword(keywords::False) { cx.set_trace_macros(false); } else { cx.span_fatal(sp, "trace_macros! only accepts `true` or `false`") } rust_parser.bump(); let rust_parser = Parser(sess, cfg, rdr.dup()); let result = rust_parser.parse_expr(); base::MRExpr(result)
}
random_line_split
trace_macros.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. use ast; use codemap::span; use ext::base::ExtCtxt; use ext::base; use parse::lexer::{new_tt_reader, reader}; use parse::parser::Parser; use parse::token::keywords; pub fn expand_trace_macros(cx: @ExtCtxt, sp: span, tt: &[ast::token_tree]) -> base::MacResult { let sess = cx.parse_sess(); let cfg = cx.cfg(); let tt_rdr = new_tt_reader( copy cx.parse_sess().span_diagnostic, None, tt.to_owned() ); let rdr = tt_rdr as @reader; let rust_parser = Parser( sess, copy cfg, rdr.dup() ); if rust_parser.is_keyword(keywords::True)
else if rust_parser.is_keyword(keywords::False) { cx.set_trace_macros(false); } else { cx.span_fatal(sp, "trace_macros! only accepts `true` or `false`") } rust_parser.bump(); let rust_parser = Parser(sess, cfg, rdr.dup()); let result = rust_parser.parse_expr(); base::MRExpr(result) }
{ cx.set_trace_macros(true); }
conditional_block
trace_macros.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. use ast; use codemap::span; use ext::base::ExtCtxt; use ext::base; use parse::lexer::{new_tt_reader, reader}; use parse::parser::Parser; use parse::token::keywords; pub fn expand_trace_macros(cx: @ExtCtxt, sp: span, tt: &[ast::token_tree]) -> base::MacResult
cx.span_fatal(sp, "trace_macros! only accepts `true` or `false`") } rust_parser.bump(); let rust_parser = Parser(sess, cfg, rdr.dup()); let result = rust_parser.parse_expr(); base::MRExpr(result) }
{ let sess = cx.parse_sess(); let cfg = cx.cfg(); let tt_rdr = new_tt_reader( copy cx.parse_sess().span_diagnostic, None, tt.to_owned() ); let rdr = tt_rdr as @reader; let rust_parser = Parser( sess, copy cfg, rdr.dup() ); if rust_parser.is_keyword(keywords::True) { cx.set_trace_macros(true); } else if rust_parser.is_keyword(keywords::False) { cx.set_trace_macros(false); } else {
identifier_body
world_scene.rs
use caches::art_cache::ArtCache; use caches::texmap_cache::TexMapCache; use cgmath::Point2; use ggez::event::{KeyCode, KeyMods}; use ggez::graphics::{self}; use ggez::{Context, GameResult}; use map::render::draw_block; use map::{map_id_to_facet, Facet, MAP_DETAILS}; use scene::{BoxedScene, Scene, SceneChangeEvent, SceneName}; const STEP_X: u32 = 1; const STEP_Y: u32 = 1; const MAX_BLOCKS_WIDTH: u32 = 6; const MAX_BLOCKS_HEIGHT: u32 = 6; pub struct WorldScene { art_cache: ArtCache, texmap_cache: TexMapCache, facet: Facet, x: u32, y: u32, map_id: u8, exiting: bool, } // TODO: Make this less nasty fn block_at(x: i32, y: i32) -> Point2<f32> { Point2::new( ((22 * 8) * x - (y * (22 * 8)) + (22 * 16)) as f32, ((22 * 8) * y + (x * (22 * 8)) - (22 * 24)) as f32, ) } impl<'a> WorldScene { pub fn new() -> BoxedScene<'a, SceneName, ()> { let scene = Box::new(WorldScene { exiting: false, map_id: 0, facet: map_id_to_facet(0), art_cache: ArtCache::new(), texmap_cache: TexMapCache::new(), x: 160, y: 208, }); scene } pub fn draw_page(&mut self, ctx: &mut Context) -> GameResult<()> { for y in 0..MAX_BLOCKS_HEIGHT { for x in 0..MAX_BLOCKS_WIDTH { let ((ref block, ref statics), ref altitudes) = self.facet.read_block(x + self.x, y + self.y); let transform = block_at(x as i32, y as i32); draw_block( ctx, &mut self.art_cache, &mut self.texmap_cache, Some(block), statics, altitudes, transform, )?; } } Ok(()) } } impl Scene<SceneName, ()> for WorldScene { fn draw(&mut self, ctx: &mut Context, _engine_data: &mut ()) -> GameResult<()> { graphics::clear(ctx, graphics::BLACK); self.draw_page(ctx) } fn key_down_event( &mut self, _ctx: &mut Context, keycode: KeyCode, _keymods: KeyMods, _repeat: bool, _engine_data: &mut (), ) { match keycode { KeyCode::Escape => self.exiting = true, KeyCode::Left => { if self.x >= STEP_X as u32 { self.x -= STEP_X as u32; } } KeyCode::Right => { self.x += STEP_X as u32; } KeyCode::Up => { if self.y >= STEP_Y as u32 { self.y -= STEP_Y as u32; } } KeyCode::Down => { self.y += STEP_Y as u32; } KeyCode::Tab => { self.map_id = (self.map_id + 1) % MAP_DETAILS.len() as u8; self.facet = map_id_to_facet(self.map_id); self.x = 0; self.y = 0; } _ => (), } } fn update( &mut self, _ctx: &mut Context, _engine_data: &mut (), ) -> GameResult<Option<SceneChangeEvent<SceneName>>>
}
{ if self.exiting { Ok(Some(SceneChangeEvent::PopScene)) } else { Ok(None) } }
identifier_body
world_scene.rs
use caches::art_cache::ArtCache; use caches::texmap_cache::TexMapCache; use cgmath::Point2; use ggez::event::{KeyCode, KeyMods}; use ggez::graphics::{self}; use ggez::{Context, GameResult}; use map::render::draw_block; use map::{map_id_to_facet, Facet, MAP_DETAILS}; use scene::{BoxedScene, Scene, SceneChangeEvent, SceneName}; const STEP_X: u32 = 1; const STEP_Y: u32 = 1; const MAX_BLOCKS_WIDTH: u32 = 6; const MAX_BLOCKS_HEIGHT: u32 = 6; pub struct WorldScene { art_cache: ArtCache, texmap_cache: TexMapCache, facet: Facet, x: u32, y: u32, map_id: u8, exiting: bool, } // TODO: Make this less nasty fn block_at(x: i32, y: i32) -> Point2<f32> { Point2::new( ((22 * 8) * x - (y * (22 * 8)) + (22 * 16)) as f32, ((22 * 8) * y + (x * (22 * 8)) - (22 * 24)) as f32, ) } impl<'a> WorldScene { pub fn new() -> BoxedScene<'a, SceneName, ()> { let scene = Box::new(WorldScene { exiting: false, map_id: 0, facet: map_id_to_facet(0), art_cache: ArtCache::new(), texmap_cache: TexMapCache::new(), x: 160, y: 208, }); scene } pub fn draw_page(&mut self, ctx: &mut Context) -> GameResult<()> { for y in 0..MAX_BLOCKS_HEIGHT { for x in 0..MAX_BLOCKS_WIDTH { let ((ref block, ref statics), ref altitudes) = self.facet.read_block(x + self.x, y + self.y); let transform = block_at(x as i32, y as i32); draw_block( ctx, &mut self.art_cache, &mut self.texmap_cache, Some(block), statics, altitudes, transform, )?; } } Ok(()) } } impl Scene<SceneName, ()> for WorldScene { fn draw(&mut self, ctx: &mut Context, _engine_data: &mut ()) -> GameResult<()> { graphics::clear(ctx, graphics::BLACK); self.draw_page(ctx) } fn key_down_event( &mut self, _ctx: &mut Context, keycode: KeyCode, _keymods: KeyMods, _repeat: bool, _engine_data: &mut (), ) { match keycode { KeyCode::Escape => self.exiting = true, KeyCode::Left => { if self.x >= STEP_X as u32 { self.x -= STEP_X as u32; } } KeyCode::Right => { self.x += STEP_X as u32; } KeyCode::Up => { if self.y >= STEP_Y as u32 { self.y -= STEP_Y as u32; } } KeyCode::Down => { self.y += STEP_Y as u32; } KeyCode::Tab => { self.map_id = (self.map_id + 1) % MAP_DETAILS.len() as u8; self.facet = map_id_to_facet(self.map_id); self.x = 0; self.y = 0; } _ => (), } } fn
( &mut self, _ctx: &mut Context, _engine_data: &mut (), ) -> GameResult<Option<SceneChangeEvent<SceneName>>> { if self.exiting { Ok(Some(SceneChangeEvent::PopScene)) } else { Ok(None) } } }
update
identifier_name
world_scene.rs
use caches::art_cache::ArtCache; use caches::texmap_cache::TexMapCache; use cgmath::Point2; use ggez::event::{KeyCode, KeyMods}; use ggez::graphics::{self}; use ggez::{Context, GameResult}; use map::render::draw_block; use map::{map_id_to_facet, Facet, MAP_DETAILS}; use scene::{BoxedScene, Scene, SceneChangeEvent, SceneName}; const STEP_X: u32 = 1; const STEP_Y: u32 = 1; const MAX_BLOCKS_WIDTH: u32 = 6; const MAX_BLOCKS_HEIGHT: u32 = 6; pub struct WorldScene { art_cache: ArtCache, texmap_cache: TexMapCache, facet: Facet, x: u32, y: u32, map_id: u8, exiting: bool, } // TODO: Make this less nasty fn block_at(x: i32, y: i32) -> Point2<f32> { Point2::new( ((22 * 8) * x - (y * (22 * 8)) + (22 * 16)) as f32, ((22 * 8) * y + (x * (22 * 8)) - (22 * 24)) as f32, ) } impl<'a> WorldScene { pub fn new() -> BoxedScene<'a, SceneName, ()> { let scene = Box::new(WorldScene { exiting: false, map_id: 0, facet: map_id_to_facet(0), art_cache: ArtCache::new(), texmap_cache: TexMapCache::new(), x: 160, y: 208, }); scene } pub fn draw_page(&mut self, ctx: &mut Context) -> GameResult<()> { for y in 0..MAX_BLOCKS_HEIGHT { for x in 0..MAX_BLOCKS_WIDTH { let ((ref block, ref statics), ref altitudes) = self.facet.read_block(x + self.x, y + self.y); let transform = block_at(x as i32, y as i32); draw_block( ctx, &mut self.art_cache, &mut self.texmap_cache, Some(block), statics, altitudes, transform, )?; } } Ok(()) } } impl Scene<SceneName, ()> for WorldScene { fn draw(&mut self, ctx: &mut Context, _engine_data: &mut ()) -> GameResult<()> { graphics::clear(ctx, graphics::BLACK); self.draw_page(ctx) } fn key_down_event( &mut self, _ctx: &mut Context, keycode: KeyCode, _keymods: KeyMods, _repeat: bool, _engine_data: &mut (), ) { match keycode { KeyCode::Escape => self.exiting = true, KeyCode::Left => { if self.x >= STEP_X as u32 { self.x -= STEP_X as u32; } } KeyCode::Right => { self.x += STEP_X as u32; } KeyCode::Up => { if self.y >= STEP_Y as u32 { self.y -= STEP_Y as u32; } } KeyCode::Down => { self.y += STEP_Y as u32; } KeyCode::Tab => { self.map_id = (self.map_id + 1) % MAP_DETAILS.len() as u8; self.facet = map_id_to_facet(self.map_id); self.x = 0; self.y = 0; } _ => (), } } fn update( &mut self, _ctx: &mut Context, _engine_data: &mut (),
if self.exiting { Ok(Some(SceneChangeEvent::PopScene)) } else { Ok(None) } } }
) -> GameResult<Option<SceneChangeEvent<SceneName>>> {
random_line_split
world_scene.rs
use caches::art_cache::ArtCache; use caches::texmap_cache::TexMapCache; use cgmath::Point2; use ggez::event::{KeyCode, KeyMods}; use ggez::graphics::{self}; use ggez::{Context, GameResult}; use map::render::draw_block; use map::{map_id_to_facet, Facet, MAP_DETAILS}; use scene::{BoxedScene, Scene, SceneChangeEvent, SceneName}; const STEP_X: u32 = 1; const STEP_Y: u32 = 1; const MAX_BLOCKS_WIDTH: u32 = 6; const MAX_BLOCKS_HEIGHT: u32 = 6; pub struct WorldScene { art_cache: ArtCache, texmap_cache: TexMapCache, facet: Facet, x: u32, y: u32, map_id: u8, exiting: bool, } // TODO: Make this less nasty fn block_at(x: i32, y: i32) -> Point2<f32> { Point2::new( ((22 * 8) * x - (y * (22 * 8)) + (22 * 16)) as f32, ((22 * 8) * y + (x * (22 * 8)) - (22 * 24)) as f32, ) } impl<'a> WorldScene { pub fn new() -> BoxedScene<'a, SceneName, ()> { let scene = Box::new(WorldScene { exiting: false, map_id: 0, facet: map_id_to_facet(0), art_cache: ArtCache::new(), texmap_cache: TexMapCache::new(), x: 160, y: 208, }); scene } pub fn draw_page(&mut self, ctx: &mut Context) -> GameResult<()> { for y in 0..MAX_BLOCKS_HEIGHT { for x in 0..MAX_BLOCKS_WIDTH { let ((ref block, ref statics), ref altitudes) = self.facet.read_block(x + self.x, y + self.y); let transform = block_at(x as i32, y as i32); draw_block( ctx, &mut self.art_cache, &mut self.texmap_cache, Some(block), statics, altitudes, transform, )?; } } Ok(()) } } impl Scene<SceneName, ()> for WorldScene { fn draw(&mut self, ctx: &mut Context, _engine_data: &mut ()) -> GameResult<()> { graphics::clear(ctx, graphics::BLACK); self.draw_page(ctx) } fn key_down_event( &mut self, _ctx: &mut Context, keycode: KeyCode, _keymods: KeyMods, _repeat: bool, _engine_data: &mut (), ) { match keycode { KeyCode::Escape => self.exiting = true, KeyCode::Left => { if self.x >= STEP_X as u32 { self.x -= STEP_X as u32; } } KeyCode::Right => { self.x += STEP_X as u32; } KeyCode::Up =>
KeyCode::Down => { self.y += STEP_Y as u32; } KeyCode::Tab => { self.map_id = (self.map_id + 1) % MAP_DETAILS.len() as u8; self.facet = map_id_to_facet(self.map_id); self.x = 0; self.y = 0; } _ => (), } } fn update( &mut self, _ctx: &mut Context, _engine_data: &mut (), ) -> GameResult<Option<SceneChangeEvent<SceneName>>> { if self.exiting { Ok(Some(SceneChangeEvent::PopScene)) } else { Ok(None) } } }
{ if self.y >= STEP_Y as u32 { self.y -= STEP_Y as u32; } }
conditional_block
reflect-object-param.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that types that appear in input types in an object type are // subject to the reflect check. use std::marker::Reflect; use std::io::Write; trait Get<T> { fn get(self) -> T; } struct
<T>(T); fn is_reflect<T:Reflect>() { } fn a<T>() { is_reflect::<T>(); //~ ERROR not implemented } fn ok_a<T: Reflect>() { is_reflect::<T>(); // OK } fn b<T>() { is_reflect::<Box<Get<T>>>(); //~ ERROR not implemented } fn ok_b<T: Reflect>() { is_reflect::<Box<Get<T>>>(); // OK } fn c<T>() { is_reflect::<Box<Get<Struct<T>>>>(); //~ ERROR not implemented } fn main() { is_reflect::<Box<Get<Struct<()>>>>(); // OK }
Struct
identifier_name
reflect-object-param.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that types that appear in input types in an object type are // subject to the reflect check. use std::marker::Reflect; use std::io::Write; trait Get<T> { fn get(self) -> T; } struct Struct<T>(T); fn is_reflect<T:Reflect>() { } fn a<T>() { is_reflect::<T>(); //~ ERROR not implemented } fn ok_a<T: Reflect>() { is_reflect::<T>(); // OK } fn b<T>() { is_reflect::<Box<Get<T>>>(); //~ ERROR not implemented } fn ok_b<T: Reflect>() { is_reflect::<Box<Get<T>>>(); // OK
fn c<T>() { is_reflect::<Box<Get<Struct<T>>>>(); //~ ERROR not implemented } fn main() { is_reflect::<Box<Get<Struct<()>>>>(); // OK }
}
random_line_split
reflect-object-param.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that types that appear in input types in an object type are // subject to the reflect check. use std::marker::Reflect; use std::io::Write; trait Get<T> { fn get(self) -> T; } struct Struct<T>(T); fn is_reflect<T:Reflect>() { } fn a<T>()
fn ok_a<T: Reflect>() { is_reflect::<T>(); // OK } fn b<T>() { is_reflect::<Box<Get<T>>>(); //~ ERROR not implemented } fn ok_b<T: Reflect>() { is_reflect::<Box<Get<T>>>(); // OK } fn c<T>() { is_reflect::<Box<Get<Struct<T>>>>(); //~ ERROR not implemented } fn main() { is_reflect::<Box<Get<Struct<()>>>>(); // OK }
{ is_reflect::<T>(); //~ ERROR not implemented }
identifier_body
random.rs
// The MIT License (MIT) // // Copyright (c) 2015 dinowernli // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. use rand::{Rng, SeedableRng, StdRng}; /// Basic random number generator (not necessarily cryptographically secure). pub trait Random { /// Returns a random number in the range [0, limit - 1]. fn next_modulo(&mut self, limit: u64) -> u64; } /// Default implementation of the Random trait. pub struct RandomImpl { generator: StdRng, } impl RandomImpl { pub fn create(seed: usize) -> Self { let seed_slice: &[_] = &[seed as usize]; return RandomImpl { generator: SeedableRng::from_seed(seed_slice), }; } /// Returns a new random number generator seeded with the /// next random number produced by this generator. pub fn new_child(&mut self) -> Self { return RandomImpl::create(self.next() as usize); } /// Returns a random number. fn next(&mut self) -> u64 {
impl Random for RandomImpl { fn next_modulo(&mut self, limit: u64) -> u64 { return self.next() % limit; } }
self.generator.gen::<u64>() } }
random_line_split
random.rs
// The MIT License (MIT) // // Copyright (c) 2015 dinowernli // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. use rand::{Rng, SeedableRng, StdRng}; /// Basic random number generator (not necessarily cryptographically secure). pub trait Random { /// Returns a random number in the range [0, limit - 1]. fn next_modulo(&mut self, limit: u64) -> u64; } /// Default implementation of the Random trait. pub struct RandomImpl { generator: StdRng, } impl RandomImpl { pub fn create(seed: usize) -> Self { let seed_slice: &[_] = &[seed as usize]; return RandomImpl { generator: SeedableRng::from_seed(seed_slice), }; } /// Returns a new random number generator seeded with the /// next random number produced by this generator. pub fn new_child(&mut self) -> Self { return RandomImpl::create(self.next() as usize); } /// Returns a random number. fn
(&mut self) -> u64 { self.generator.gen::<u64>() } } impl Random for RandomImpl { fn next_modulo(&mut self, limit: u64) -> u64 { return self.next() % limit; } }
next
identifier_name
random.rs
// The MIT License (MIT) // // Copyright (c) 2015 dinowernli // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. use rand::{Rng, SeedableRng, StdRng}; /// Basic random number generator (not necessarily cryptographically secure). pub trait Random { /// Returns a random number in the range [0, limit - 1]. fn next_modulo(&mut self, limit: u64) -> u64; } /// Default implementation of the Random trait. pub struct RandomImpl { generator: StdRng, } impl RandomImpl { pub fn create(seed: usize) -> Self { let seed_slice: &[_] = &[seed as usize]; return RandomImpl { generator: SeedableRng::from_seed(seed_slice), }; } /// Returns a new random number generator seeded with the /// next random number produced by this generator. pub fn new_child(&mut self) -> Self { return RandomImpl::create(self.next() as usize); } /// Returns a random number. fn next(&mut self) -> u64
} impl Random for RandomImpl { fn next_modulo(&mut self, limit: u64) -> u64 { return self.next() % limit; } }
{ self.generator.gen::<u64>() }
identifier_body
namespace.rs
//! Contains namespace manipulation types and functions. use std::iter::{Map, Rev}; use std::collections::btree_map::{BTreeMap, Entry}; use std::collections::btree_map::Iter as Entries; use std::collections::HashSet; use std::slice::Iter; /// Designates prefix for namespace definitions. /// /// See [Namespaces in XML][namespace] spec for more information. /// /// [namespace]: http://www.w3.org/TR/xml-names/#ns-decl pub const NS_XMLNS_PREFIX: &'static str = "xmlns"; /// Designates the standard URI for `xmlns` prefix. /// /// See [A Namespace Name for xmlns Attributes][1] for more information. /// /// [namespace]: http://www.w3.org/2000/xmlns/ pub const NS_XMLNS_URI: &'static str = "http://www.w3.org/2000/xmlns/"; /// Designates prefix for a namespace containing several special predefined attributes. /// /// See [2.10 White Space handling][1], [2.1 Language Identification][2], /// [XML Base specification][3] and [xml:id specification][4] for more information. /// /// [1]: http://www.w3.org/TR/REC-xml/#sec-white-space /// [2]: http://www.w3.org/TR/REC-xml/#sec-lang-tag /// [3]: http://www.w3.org/TR/xmlbase/ /// [4]: http://www.w3.org/TR/xml-id/ pub const NS_XML_PREFIX: &'static str = "xml"; /// Designates the standard URI for `xml` prefix. /// /// See `NS_XML_PREFIX` documentation for more information. pub const NS_XML_URI: &'static str = "http://www.w3.org/XML/1998/namespace"; /// Designates the absence of prefix in a qualified name. /// /// This constant should be used to define or query default namespace which should be used /// for element or attribute names without prefix. For example, if a namespace mapping /// at a particular point in the document contains correspondence like /// /// ```none /// NS_NO_PREFIX --> urn:some:namespace /// ``` /// /// then all names declared without an explicit prefix `urn:some:namespace` is assumed as /// a namespace URI. /// /// By default empty prefix corresponds to absence of namespace, but this can change either /// when writing an XML document (manually) or when reading an XML document (based on namespace /// declarations). pub const NS_NO_PREFIX: &'static str = ""; /// Designates an empty namespace URI, which is equivalent to absence of namespace. /// /// This constant should not usually be used directly; it is used to designate that /// empty prefix corresponds to absent namespace in `NamespaceStack` instances created with /// `NamespaceStack::default()`. Therefore, it can be used to restore `NS_NO_PREFIX` mapping /// in a namespace back to its default value. pub const NS_EMPTY_URI: &'static str = ""; /// Namespace is a map from prefixes to namespace URIs. /// /// No prefix (i.e. default namespace) is designated by `NS_NO_PREFIX` constant. #[derive(PartialEq, Eq, Clone, Debug)] pub struct Namespace(pub BTreeMap<String, String>); impl Namespace { /// Returns an empty namespace. #[inline] pub fn empty() -> Namespace { Namespace(BTreeMap::new()) } /// Checks whether this namespace is empty. #[inline] pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Checks whether this namespace is essentially empty, that is, it does not contain /// anything but default mappings. pub fn is_essentially_empty(&self) -> bool { // a shortcut for a namespace which is definitely not empty if self.0.len() > 3 { return false; } self.0.iter().all(|(k, v)| match (&**k, &**v) { (NS_NO_PREFIX, NS_EMPTY_URI) => true, (NS_XMLNS_PREFIX, NS_XMLNS_URI) => true, (NS_XML_PREFIX, NS_XML_URI) => true, _ => false }) } /// Checks whether this namespace mapping contains the given prefix. /// /// # Parameters /// * `prefix` --- namespace prefix. /// /// # Return value /// `true` if this namespace contains the given prefix, `false` otherwise. #[inline] pub fn contains<P:?Sized+AsRef<str>>(&self, prefix: &P) -> bool { self.0.contains_key(prefix.as_ref()) } /// Puts a mapping into this namespace. /// /// This method does not override any already existing mappings. /// /// Returns a boolean flag indicating whether the map already contained /// the given prefix. /// /// # Parameters /// * `prefix` --- namespace prefix; /// * `uri` --- namespace URI. /// /// # Return value /// `true` if `prefix` has been inserted successfully; `false` if the `prefix` /// was already present in the namespace. pub fn put<P, U>(&mut self, prefix: P, uri: U) -> bool where P: Into<String>, U: Into<String> { match self.0.entry(prefix.into()) { Entry::Occupied(_) => false, Entry::Vacant(ve) => { ve.insert(uri.into()); true } } } /// Puts a mapping into this namespace forcefully. /// /// This method, unlike `put()`, does replace an already existing mapping. /// /// Returns previous URI which was assigned to the given prefix, if it is present. /// /// # Parameters /// * `prefix` --- namespace prefix; /// * `uri` --- namespace URI. /// /// # Return value /// `Some(uri)` with `uri` being a previous URI assigned to the `prefix`, or /// `None` if such prefix was not present in the namespace before. pub fn force_put<P, U>(&mut self, prefix: P, uri: U) -> Option<String> where P: Into<String>, U: Into<String> { self.0.insert(prefix.into(), uri.into()) } /// Queries the namespace for the given prefix. /// /// # Parameters /// * `prefix` --- namespace prefix. /// /// # Return value /// Namespace URI corresponding to the given prefix, if it is present. pub fn get<'a, P:?Sized+AsRef<str>>(&'a self, prefix: &P) -> Option<&'a str> { self.0.get(prefix.as_ref()).map(|s| &**s) } } /// An alias for iterator type for namespace mappings contained in a namespace. pub type NamespaceMappings<'a> = Map< Entries<'a, String, String>, for<'b> fn((&'b String, &'b String)) -> UriMapping<'b> >; impl<'a> IntoIterator for &'a Namespace { type Item = UriMapping<'a>; type IntoIter = NamespaceMappings<'a>; fn into_iter(self) -> Self::IntoIter { fn mapper<'a>((prefix, uri): (&'a String, &'a String)) -> UriMapping<'a> { (&*prefix, &*uri) } self.0.iter().map(mapper) } } /// Namespace stack is a sequence of namespaces. /// /// Namespace stack is used to represent cumulative namespace consisting of /// combined namespaces from nested elements. #[derive(Clone, Eq, PartialEq, Debug)] pub struct NamespaceStack(pub Vec<Namespace>); impl NamespaceStack { /// Returns an empty namespace stack. #[inline] pub fn empty() -> NamespaceStack { NamespaceStack(Vec::with_capacity(2)) } /// Returns a namespace stack with default items in it. /// /// Default items are the following: /// /// * `xml` → `http://www.w3.org/XML/1998/namespace`; /// * `xmlns` → `http://www.w3.org/2000/xmlns/`. #[inline] pub fn default() -> NamespaceStack { let mut nst = NamespaceStack::empty(); nst.push_empty(); // xml namespace nst.put(NS_XML_PREFIX, NS_XML_URI); // xmlns namespace nst.put(NS_XMLNS_PREFIX, NS_XMLNS_URI); // empty namespace nst.put(NS_NO_PREFIX, NS_EMPTY_URI); nst } /// Adds an empty namespace to the top of this stack. #[inline] pub fn push_empty(&mut self) -> &mut NamespaceStack { self.0.push(Namespace::empty()); self } /// Removes the topmost namespace in this stack. /// /// Panics if the stack is empty. #[inline] pub fn pop(&mut self) -> Namespace { self.0.pop().unwrap() } /// Removes the topmost namespace in this stack. /// /// Returns `Some(namespace)` if this stack is not empty and `None` otherwise. #[inline] pub fn try_pop(&mut self) -> Option<Namespace> { self.0.pop() } /// Borrows the topmost namespace mutably, leaving the stack intact. /// /// Panics if the stack is empty. #[inline] pub fn peek_mut(&mut self) -> &mut Namespace { self.0.last_mut().unwrap() } /// Borrows the topmost namespace immutably, leaving the stack intact. /// /// Panics if the stack is empty. #[inline] pub fn peek(&self) -> &Namespace { self.0.last().unwrap() } /// Puts a mapping into the topmost namespace if this stack does not already contain one. /// /// Returns a boolean flag indicating whether the insertion has completed successfully. /// Note that both key and value are matched and the mapping is inserted if either /// namespace prefix is not already mapped, or if it is mapped, but to a different URI. /// /// # Parameters /// * `prefix` --- namespace prefix; /// * `uri` --- namespace URI. /// /// # Return value /// `true` if `prefix` has been inserted successfully; `false` if the `prefix` /// was already present in the namespace stack. pub fn put_checked<P, U>(&mut self, prefix: P, uri: U) -> bool where P: Into<String> + AsRef<str>, U: Into<String> + AsRef<str> { if self.0.iter().any(|ns| ns.get(&prefix) == Some(uri.as_ref())) { false } else { self.put(prefix, uri); true } } /// Puts a mapping into the topmost namespace in this stack. /// /// This method does not override a mapping in the topmost namespace if it is /// already present, however, it does not depend on other namespaces in the stack, /// so it is possible to put a mapping which is present in lower namespaces. /// /// Returns a boolean flag indicating whether the insertion has completed successfully. /// /// # Parameters /// * `prefix` --- namespace prefix; /// * `uri` --- namespace URI. /// /// # Return value /// `true` if `prefix` has been inserted successfully; `false` if the `prefix` /// was already present in the namespace. #[inline] pub fn put<P, U>(&mut self, prefix: P, uri: U) -> bool where P: Into<String>, U: Into<String> { self.0.last_mut().unwrap().put(prefix, uri) } /// Performs a search for the given prefix in the whole stack. /// /// This method walks the stack from top to bottom, querying each namespace /// in order for the given prefix. If none of the namespaces contains the prefix, /// `None` is returned. /// /// # Parameters /// * `prefix` --- namespace prefix. #[inline] pub fn get<'a, P:?Sized+AsRef<str>>(&'a self, prefix: &P) -> Option<&'a str> { let prefix = prefix.as_ref(); for ns in self.0.iter().rev() { match ns.get(prefix) { None => {}, r => return r, } } None } /// Combines this stack of namespaces into a single namespace. /// /// Namespaces are combined in left-to-right order, that is, rightmost namespace /// elements take priority over leftmost ones. pub fn squash(&self) -> Namespace { let mut result = BTreeMap::new(); for ns in self.0.iter() { result.extend(ns.0.iter().map(|(k, v)| (k.clone(), v.clone()))); } Namespace(result) } /// Returns an object which implements `Extend` using `put_checked()` instead of `put()`. /// /// See `CheckedTarget` for more information. #[inline] pub fn checked_target(&mut self) -> CheckedTarget { CheckedTarget(self) } /// Returns an iterator over all mappings in this namespace stack. #[inline] pub fn iter(&self) -> NamespaceStackMappings { self.into_iter() } } /// An iterator over mappings from prefixes to URIs in a namespace stack. /// /// # Example /// ``` /// # use xml::namespace::NamespaceStack; /// let mut nst = NamespaceStack::empty(); /// nst.push_empty(); /// nst.put("a", "urn:A"); /// nst.put("b", "urn:B"); /// nst.push_empty(); /// nst.put("c", "urn:C"); /// /// assert_eq!(vec![("c", "urn:C"), ("a", "urn:A"), ("b", "urn:B")], nst.iter().collect::<Vec<_>>()); /// ``` pub struct NamespaceStackMappings<'a> { namespaces: Rev<Iter<'a, Namespace>>, current_namespace: Option<NamespaceMappings<'a>>, used_keys: HashSet<&'a str> } impl<'a> NamespaceStackMappings<'a> { fn go_to_next_namespace(&mut self) -> bool { self.current_namespace = self.namespaces.next().map(|ns| ns.into_iter()); self.current_namespace.is_some() } } impl<'a> Iterator for NamespaceStackMappings<'a> { type Item = UriMapping<'a>; fn next(&mut self) -> Option<UriMapping<'a>> { // If there is no current namespace and no next namespace, we're finished if self.current_namespace.is_none() &&!self.go_to_next_namespace() { return None; } let next_item = self.current_namespace.as_mut().unwrap().next(); match next_item { // There is an element in the current namespace Some((k, v)) => if self.used_keys.contains(&k) { // If the current key is used, go to the next one self.next() } else { // Otherwise insert the current key to the set of used keys and // return the mapping self.used_keys.insert(k); Some((k, v)) }, // Current namespace is exhausted None => if self.go_to_next_namespace() {
e { // No next namespace, exiting None } } } } impl<'a> IntoIterator for &'a NamespaceStack { type Item = UriMapping<'a>; type IntoIter = NamespaceStackMappings<'a>; fn into_iter(self) -> Self::IntoIter { NamespaceStackMappings { namespaces: self.0.iter().rev(), current_namespace: None, used_keys: HashSet::new() } } } /// A type alias for a pair of `(prefix, uri)` values returned by namespace iterators. pub type UriMapping<'a> = (&'a str, &'a str); impl<'a> Extend<UriMapping<'a>> for Namespace { fn extend<T>(&mut self, iterable: T) where T: IntoIterator<Item=UriMapping<'a>> { for (prefix, uri) in iterable { self.put(prefix, uri); } } } impl<'a> Extend<UriMapping<'a>> for NamespaceStack { fn extend<T>(&mut self, iterable: T) where T: IntoIterator<Item=UriMapping<'a>> { for (prefix, uri) in iterable { self.put(prefix, uri); } } } /// A wrapper around `NamespaceStack` which implements `Extend` using `put_checked()`. /// /// # Example /// /// ``` /// # use xml::namespace::NamespaceStack; /// /// let mut nst = NamespaceStack::empty(); /// nst.push_empty(); /// nst.put("a", "urn:A"); /// nst.put("b", "urn:B"); /// nst.push_empty(); /// nst.put("c", "urn:C"); /// /// nst.checked_target().extend(vec![("a", "urn:Z"), ("b", "urn:B"), ("c", "urn:Y"), ("d", "urn:D")]); /// assert_eq!( /// vec![("a", "urn:Z"), ("c", "urn:C"), ("d", "urn:D"), ("b", "urn:B")], /// nst.iter().collect::<Vec<_>>() /// ); /// ``` /// /// Compare: /// /// ``` /// # use xml::namespace::NamespaceStack; /// # let mut nst = NamespaceStack::empty(); /// # nst.push_empty(); /// # nst.put("a", "urn:A"); /// # nst.put("b", "urn:B"); /// # nst.push_empty(); /// # nst.put("c", "urn:C"); /// /// nst.extend(vec![("a", "urn:Z"), ("b", "urn:B"), ("c", "urn:Y"), ("d", "urn:D")]); /// assert_eq!( /// vec![("a", "urn:Z"), ("b", "urn:B"), ("c", "urn:C"), ("d", "urn:D")], /// nst.iter().collect::<Vec<_>>() /// ); /// ``` pub struct CheckedTarget<'a>(&'a mut NamespaceStack); impl<'a, 'b> Extend<UriMapping<'b>> for CheckedTarget<'a> { fn extend<T>(&mut self, iterable: T) where T: IntoIterator<Item=UriMapping<'b>> { for (prefix, uri) in iterable { self.0.put_checked(prefix, uri); } } }
// If there is next namespace, continue from it self.next() } els
conditional_block
namespace.rs
//! Contains namespace manipulation types and functions. use std::iter::{Map, Rev}; use std::collections::btree_map::{BTreeMap, Entry}; use std::collections::btree_map::Iter as Entries; use std::collections::HashSet; use std::slice::Iter; /// Designates prefix for namespace definitions. /// /// See [Namespaces in XML][namespace] spec for more information. /// /// [namespace]: http://www.w3.org/TR/xml-names/#ns-decl pub const NS_XMLNS_PREFIX: &'static str = "xmlns"; /// Designates the standard URI for `xmlns` prefix. /// /// See [A Namespace Name for xmlns Attributes][1] for more information. /// /// [namespace]: http://www.w3.org/2000/xmlns/ pub const NS_XMLNS_URI: &'static str = "http://www.w3.org/2000/xmlns/"; /// Designates prefix for a namespace containing several special predefined attributes. /// /// See [2.10 White Space handling][1], [2.1 Language Identification][2], /// [XML Base specification][3] and [xml:id specification][4] for more information. /// /// [1]: http://www.w3.org/TR/REC-xml/#sec-white-space /// [2]: http://www.w3.org/TR/REC-xml/#sec-lang-tag /// [3]: http://www.w3.org/TR/xmlbase/ /// [4]: http://www.w3.org/TR/xml-id/ pub const NS_XML_PREFIX: &'static str = "xml"; /// Designates the standard URI for `xml` prefix. /// /// See `NS_XML_PREFIX` documentation for more information. pub const NS_XML_URI: &'static str = "http://www.w3.org/XML/1998/namespace"; /// Designates the absence of prefix in a qualified name. /// /// This constant should be used to define or query default namespace which should be used /// for element or attribute names without prefix. For example, if a namespace mapping /// at a particular point in the document contains correspondence like /// /// ```none /// NS_NO_PREFIX --> urn:some:namespace /// ``` /// /// then all names declared without an explicit prefix `urn:some:namespace` is assumed as /// a namespace URI. /// /// By default empty prefix corresponds to absence of namespace, but this can change either /// when writing an XML document (manually) or when reading an XML document (based on namespace /// declarations). pub const NS_NO_PREFIX: &'static str = ""; /// Designates an empty namespace URI, which is equivalent to absence of namespace. /// /// This constant should not usually be used directly; it is used to designate that /// empty prefix corresponds to absent namespace in `NamespaceStack` instances created with /// `NamespaceStack::default()`. Therefore, it can be used to restore `NS_NO_PREFIX` mapping /// in a namespace back to its default value. pub const NS_EMPTY_URI: &'static str = ""; /// Namespace is a map from prefixes to namespace URIs. /// /// No prefix (i.e. default namespace) is designated by `NS_NO_PREFIX` constant. #[derive(PartialEq, Eq, Clone, Debug)] pub struct Namespace(pub BTreeMap<String, String>); impl Namespace { /// Returns an empty namespace. #[inline] pub fn empty() -> Namespace { Namespace(BTreeMap::new()) } /// Checks whether this namespace is empty. #[inline] pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Checks whether this namespace is essentially empty, that is, it does not contain /// anything but default mappings. pub fn is_essentially_empty(&self) -> bool { // a shortcut for a namespace which is definitely not empty if self.0.len() > 3 { return false; } self.0.iter().all(|(k, v)| match (&**k, &**v) { (NS_NO_PREFIX, NS_EMPTY_URI) => true, (NS_XMLNS_PREFIX, NS_XMLNS_URI) => true, (NS_XML_PREFIX, NS_XML_URI) => true, _ => false }) } /// Checks whether this namespace mapping contains the given prefix. /// /// # Parameters /// * `prefix` --- namespace prefix. /// /// # Return value /// `true` if this namespace contains the given prefix, `false` otherwise. #[inline] pub fn contains<P:?Sized+AsRef<str>>(&self, prefix: &P) -> bool { self.0.contains_key(prefix.as_ref()) } /// Puts a mapping into this namespace. /// /// This method does not override any already existing mappings. /// /// Returns a boolean flag indicating whether the map already contained /// the given prefix. /// /// # Parameters /// * `prefix` --- namespace prefix; /// * `uri` --- namespace URI. /// /// # Return value /// `true` if `prefix` has been inserted successfully; `false` if the `prefix` /// was already present in the namespace. pub fn put<P, U>(&mut self, prefix: P, uri: U) -> bool where P: Into<String>, U: Into<String> { match self.0.entry(prefix.into()) { Entry::Occupied(_) => false, Entry::Vacant(ve) => { ve.insert(uri.into()); true } } } /// Puts a mapping into this namespace forcefully. /// /// This method, unlike `put()`, does replace an already existing mapping. /// /// Returns previous URI which was assigned to the given prefix, if it is present. /// /// # Parameters /// * `prefix` --- namespace prefix; /// * `uri` --- namespace URI. /// /// # Return value /// `Some(uri)` with `uri` being a previous URI assigned to the `prefix`, or /// `None` if such prefix was not present in the namespace before. pub fn force_put<P, U>(&mut self, prefix: P, uri: U) -> Option<String> where P: Into<String>, U: Into<String> { self.0.insert(prefix.into(), uri.into()) } /// Queries the namespace for the given prefix. /// /// # Parameters /// * `prefix` --- namespace prefix. /// /// # Return value /// Namespace URI corresponding to the given prefix, if it is present. pub fn get<'a, P:?Sized+AsRef<str>>(&'a self, prefix: &P) -> Option<&'a str> { self.0.get(prefix.as_ref()).map(|s| &**s) } } /// An alias for iterator type for namespace mappings contained in a namespace. pub type NamespaceMappings<'a> = Map< Entries<'a, String, String>, for<'b> fn((&'b String, &'b String)) -> UriMapping<'b> >; impl<'a> IntoIterator for &'a Namespace { type Item = UriMapping<'a>; type IntoIter = NamespaceMappings<'a>; fn into_iter(self) -> Self::IntoIter { fn mapper<'a>((prefix, uri): (&'a String, &'a String)) -> UriMapping<'a> { (&*prefix, &*uri) }
/// Namespace stack is a sequence of namespaces. /// /// Namespace stack is used to represent cumulative namespace consisting of /// combined namespaces from nested elements. #[derive(Clone, Eq, PartialEq, Debug)] pub struct NamespaceStack(pub Vec<Namespace>); impl NamespaceStack { /// Returns an empty namespace stack. #[inline] pub fn empty() -> NamespaceStack { NamespaceStack(Vec::with_capacity(2)) } /// Returns a namespace stack with default items in it. /// /// Default items are the following: /// /// * `xml` → `http://www.w3.org/XML/1998/namespace`; /// * `xmlns` → `http://www.w3.org/2000/xmlns/`. #[inline] pub fn default() -> NamespaceStack { let mut nst = NamespaceStack::empty(); nst.push_empty(); // xml namespace nst.put(NS_XML_PREFIX, NS_XML_URI); // xmlns namespace nst.put(NS_XMLNS_PREFIX, NS_XMLNS_URI); // empty namespace nst.put(NS_NO_PREFIX, NS_EMPTY_URI); nst } /// Adds an empty namespace to the top of this stack. #[inline] pub fn push_empty(&mut self) -> &mut NamespaceStack { self.0.push(Namespace::empty()); self } /// Removes the topmost namespace in this stack. /// /// Panics if the stack is empty. #[inline] pub fn pop(&mut self) -> Namespace { self.0.pop().unwrap() } /// Removes the topmost namespace in this stack. /// /// Returns `Some(namespace)` if this stack is not empty and `None` otherwise. #[inline] pub fn try_pop(&mut self) -> Option<Namespace> { self.0.pop() } /// Borrows the topmost namespace mutably, leaving the stack intact. /// /// Panics if the stack is empty. #[inline] pub fn peek_mut(&mut self) -> &mut Namespace { self.0.last_mut().unwrap() } /// Borrows the topmost namespace immutably, leaving the stack intact. /// /// Panics if the stack is empty. #[inline] pub fn peek(&self) -> &Namespace { self.0.last().unwrap() } /// Puts a mapping into the topmost namespace if this stack does not already contain one. /// /// Returns a boolean flag indicating whether the insertion has completed successfully. /// Note that both key and value are matched and the mapping is inserted if either /// namespace prefix is not already mapped, or if it is mapped, but to a different URI. /// /// # Parameters /// * `prefix` --- namespace prefix; /// * `uri` --- namespace URI. /// /// # Return value /// `true` if `prefix` has been inserted successfully; `false` if the `prefix` /// was already present in the namespace stack. pub fn put_checked<P, U>(&mut self, prefix: P, uri: U) -> bool where P: Into<String> + AsRef<str>, U: Into<String> + AsRef<str> { if self.0.iter().any(|ns| ns.get(&prefix) == Some(uri.as_ref())) { false } else { self.put(prefix, uri); true } } /// Puts a mapping into the topmost namespace in this stack. /// /// This method does not override a mapping in the topmost namespace if it is /// already present, however, it does not depend on other namespaces in the stack, /// so it is possible to put a mapping which is present in lower namespaces. /// /// Returns a boolean flag indicating whether the insertion has completed successfully. /// /// # Parameters /// * `prefix` --- namespace prefix; /// * `uri` --- namespace URI. /// /// # Return value /// `true` if `prefix` has been inserted successfully; `false` if the `prefix` /// was already present in the namespace. #[inline] pub fn put<P, U>(&mut self, prefix: P, uri: U) -> bool where P: Into<String>, U: Into<String> { self.0.last_mut().unwrap().put(prefix, uri) } /// Performs a search for the given prefix in the whole stack. /// /// This method walks the stack from top to bottom, querying each namespace /// in order for the given prefix. If none of the namespaces contains the prefix, /// `None` is returned. /// /// # Parameters /// * `prefix` --- namespace prefix. #[inline] pub fn get<'a, P:?Sized+AsRef<str>>(&'a self, prefix: &P) -> Option<&'a str> { let prefix = prefix.as_ref(); for ns in self.0.iter().rev() { match ns.get(prefix) { None => {}, r => return r, } } None } /// Combines this stack of namespaces into a single namespace. /// /// Namespaces are combined in left-to-right order, that is, rightmost namespace /// elements take priority over leftmost ones. pub fn squash(&self) -> Namespace { let mut result = BTreeMap::new(); for ns in self.0.iter() { result.extend(ns.0.iter().map(|(k, v)| (k.clone(), v.clone()))); } Namespace(result) } /// Returns an object which implements `Extend` using `put_checked()` instead of `put()`. /// /// See `CheckedTarget` for more information. #[inline] pub fn checked_target(&mut self) -> CheckedTarget { CheckedTarget(self) } /// Returns an iterator over all mappings in this namespace stack. #[inline] pub fn iter(&self) -> NamespaceStackMappings { self.into_iter() } } /// An iterator over mappings from prefixes to URIs in a namespace stack. /// /// # Example /// ``` /// # use xml::namespace::NamespaceStack; /// let mut nst = NamespaceStack::empty(); /// nst.push_empty(); /// nst.put("a", "urn:A"); /// nst.put("b", "urn:B"); /// nst.push_empty(); /// nst.put("c", "urn:C"); /// /// assert_eq!(vec![("c", "urn:C"), ("a", "urn:A"), ("b", "urn:B")], nst.iter().collect::<Vec<_>>()); /// ``` pub struct NamespaceStackMappings<'a> { namespaces: Rev<Iter<'a, Namespace>>, current_namespace: Option<NamespaceMappings<'a>>, used_keys: HashSet<&'a str> } impl<'a> NamespaceStackMappings<'a> { fn go_to_next_namespace(&mut self) -> bool { self.current_namespace = self.namespaces.next().map(|ns| ns.into_iter()); self.current_namespace.is_some() } } impl<'a> Iterator for NamespaceStackMappings<'a> { type Item = UriMapping<'a>; fn next(&mut self) -> Option<UriMapping<'a>> { // If there is no current namespace and no next namespace, we're finished if self.current_namespace.is_none() &&!self.go_to_next_namespace() { return None; } let next_item = self.current_namespace.as_mut().unwrap().next(); match next_item { // There is an element in the current namespace Some((k, v)) => if self.used_keys.contains(&k) { // If the current key is used, go to the next one self.next() } else { // Otherwise insert the current key to the set of used keys and // return the mapping self.used_keys.insert(k); Some((k, v)) }, // Current namespace is exhausted None => if self.go_to_next_namespace() { // If there is next namespace, continue from it self.next() } else { // No next namespace, exiting None } } } } impl<'a> IntoIterator for &'a NamespaceStack { type Item = UriMapping<'a>; type IntoIter = NamespaceStackMappings<'a>; fn into_iter(self) -> Self::IntoIter { NamespaceStackMappings { namespaces: self.0.iter().rev(), current_namespace: None, used_keys: HashSet::new() } } } /// A type alias for a pair of `(prefix, uri)` values returned by namespace iterators. pub type UriMapping<'a> = (&'a str, &'a str); impl<'a> Extend<UriMapping<'a>> for Namespace { fn extend<T>(&mut self, iterable: T) where T: IntoIterator<Item=UriMapping<'a>> { for (prefix, uri) in iterable { self.put(prefix, uri); } } } impl<'a> Extend<UriMapping<'a>> for NamespaceStack { fn extend<T>(&mut self, iterable: T) where T: IntoIterator<Item=UriMapping<'a>> { for (prefix, uri) in iterable { self.put(prefix, uri); } } } /// A wrapper around `NamespaceStack` which implements `Extend` using `put_checked()`. /// /// # Example /// /// ``` /// # use xml::namespace::NamespaceStack; /// /// let mut nst = NamespaceStack::empty(); /// nst.push_empty(); /// nst.put("a", "urn:A"); /// nst.put("b", "urn:B"); /// nst.push_empty(); /// nst.put("c", "urn:C"); /// /// nst.checked_target().extend(vec![("a", "urn:Z"), ("b", "urn:B"), ("c", "urn:Y"), ("d", "urn:D")]); /// assert_eq!( /// vec![("a", "urn:Z"), ("c", "urn:C"), ("d", "urn:D"), ("b", "urn:B")], /// nst.iter().collect::<Vec<_>>() /// ); /// ``` /// /// Compare: /// /// ``` /// # use xml::namespace::NamespaceStack; /// # let mut nst = NamespaceStack::empty(); /// # nst.push_empty(); /// # nst.put("a", "urn:A"); /// # nst.put("b", "urn:B"); /// # nst.push_empty(); /// # nst.put("c", "urn:C"); /// /// nst.extend(vec![("a", "urn:Z"), ("b", "urn:B"), ("c", "urn:Y"), ("d", "urn:D")]); /// assert_eq!( /// vec![("a", "urn:Z"), ("b", "urn:B"), ("c", "urn:C"), ("d", "urn:D")], /// nst.iter().collect::<Vec<_>>() /// ); /// ``` pub struct CheckedTarget<'a>(&'a mut NamespaceStack); impl<'a, 'b> Extend<UriMapping<'b>> for CheckedTarget<'a> { fn extend<T>(&mut self, iterable: T) where T: IntoIterator<Item=UriMapping<'b>> { for (prefix, uri) in iterable { self.0.put_checked(prefix, uri); } } }
self.0.iter().map(mapper) } }
random_line_split
namespace.rs
//! Contains namespace manipulation types and functions. use std::iter::{Map, Rev}; use std::collections::btree_map::{BTreeMap, Entry}; use std::collections::btree_map::Iter as Entries; use std::collections::HashSet; use std::slice::Iter; /// Designates prefix for namespace definitions. /// /// See [Namespaces in XML][namespace] spec for more information. /// /// [namespace]: http://www.w3.org/TR/xml-names/#ns-decl pub const NS_XMLNS_PREFIX: &'static str = "xmlns"; /// Designates the standard URI for `xmlns` prefix. /// /// See [A Namespace Name for xmlns Attributes][1] for more information. /// /// [namespace]: http://www.w3.org/2000/xmlns/ pub const NS_XMLNS_URI: &'static str = "http://www.w3.org/2000/xmlns/"; /// Designates prefix for a namespace containing several special predefined attributes. /// /// See [2.10 White Space handling][1], [2.1 Language Identification][2], /// [XML Base specification][3] and [xml:id specification][4] for more information. /// /// [1]: http://www.w3.org/TR/REC-xml/#sec-white-space /// [2]: http://www.w3.org/TR/REC-xml/#sec-lang-tag /// [3]: http://www.w3.org/TR/xmlbase/ /// [4]: http://www.w3.org/TR/xml-id/ pub const NS_XML_PREFIX: &'static str = "xml"; /// Designates the standard URI for `xml` prefix. /// /// See `NS_XML_PREFIX` documentation for more information. pub const NS_XML_URI: &'static str = "http://www.w3.org/XML/1998/namespace"; /// Designates the absence of prefix in a qualified name. /// /// This constant should be used to define or query default namespace which should be used /// for element or attribute names without prefix. For example, if a namespace mapping /// at a particular point in the document contains correspondence like /// /// ```none /// NS_NO_PREFIX --> urn:some:namespace /// ``` /// /// then all names declared without an explicit prefix `urn:some:namespace` is assumed as /// a namespace URI. /// /// By default empty prefix corresponds to absence of namespace, but this can change either /// when writing an XML document (manually) or when reading an XML document (based on namespace /// declarations). pub const NS_NO_PREFIX: &'static str = ""; /// Designates an empty namespace URI, which is equivalent to absence of namespace. /// /// This constant should not usually be used directly; it is used to designate that /// empty prefix corresponds to absent namespace in `NamespaceStack` instances created with /// `NamespaceStack::default()`. Therefore, it can be used to restore `NS_NO_PREFIX` mapping /// in a namespace back to its default value. pub const NS_EMPTY_URI: &'static str = ""; /// Namespace is a map from prefixes to namespace URIs. /// /// No prefix (i.e. default namespace) is designated by `NS_NO_PREFIX` constant. #[derive(PartialEq, Eq, Clone, Debug)] pub struct Namespace(pub BTreeMap<String, String>); impl Namespace { /// Returns an empty namespace. #[inline] pub fn empty() -> Namespace { Namespace(BTreeMap::new()) } /// Checks whether this namespace is empty. #[inline] pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Checks whether this namespace is essentially empty, that is, it does not contain /// anything but default mappings. pub fn is_essentially_empty(&self) -> bool { // a shortcut for a namespace which is definitely not empty if self.0.len() > 3 { return false; } self.0.iter().all(|(k, v)| match (&**k, &**v) { (NS_NO_PREFIX, NS_EMPTY_URI) => true, (NS_XMLNS_PREFIX, NS_XMLNS_URI) => true, (NS_XML_PREFIX, NS_XML_URI) => true, _ => false }) } /// Checks whether this namespace mapping contains the given prefix. /// /// # Parameters /// * `prefix` --- namespace prefix. /// /// # Return value /// `true` if this namespace contains the given prefix, `false` otherwise. #[inline] pub fn contains<P:?Sized+AsRef<str>>(&self, prefix: &P) -> bool { self.0.contains_key(prefix.as_ref()) } /// Puts a mapping into this namespace. /// /// This method does not override any already existing mappings. /// /// Returns a boolean flag indicating whether the map already contained /// the given prefix. /// /// # Parameters /// * `prefix` --- namespace prefix; /// * `uri` --- namespace URI. /// /// # Return value /// `true` if `prefix` has been inserted successfully; `false` if the `prefix` /// was already present in the namespace. pub fn put<P, U>(&mut self, prefix: P, uri: U) -> bool where P: Into<String>, U: Into<String> { match self.0.entry(prefix.into()) { Entry::Occupied(_) => false, Entry::Vacant(ve) => { ve.insert(uri.into()); true } } } /// Puts a mapping into this namespace forcefully. /// /// This method, unlike `put()`, does replace an already existing mapping. /// /// Returns previous URI which was assigned to the given prefix, if it is present. /// /// # Parameters /// * `prefix` --- namespace prefix; /// * `uri` --- namespace URI. /// /// # Return value /// `Some(uri)` with `uri` being a previous URI assigned to the `prefix`, or /// `None` if such prefix was not present in the namespace before. pub fn
<P, U>(&mut self, prefix: P, uri: U) -> Option<String> where P: Into<String>, U: Into<String> { self.0.insert(prefix.into(), uri.into()) } /// Queries the namespace for the given prefix. /// /// # Parameters /// * `prefix` --- namespace prefix. /// /// # Return value /// Namespace URI corresponding to the given prefix, if it is present. pub fn get<'a, P:?Sized+AsRef<str>>(&'a self, prefix: &P) -> Option<&'a str> { self.0.get(prefix.as_ref()).map(|s| &**s) } } /// An alias for iterator type for namespace mappings contained in a namespace. pub type NamespaceMappings<'a> = Map< Entries<'a, String, String>, for<'b> fn((&'b String, &'b String)) -> UriMapping<'b> >; impl<'a> IntoIterator for &'a Namespace { type Item = UriMapping<'a>; type IntoIter = NamespaceMappings<'a>; fn into_iter(self) -> Self::IntoIter { fn mapper<'a>((prefix, uri): (&'a String, &'a String)) -> UriMapping<'a> { (&*prefix, &*uri) } self.0.iter().map(mapper) } } /// Namespace stack is a sequence of namespaces. /// /// Namespace stack is used to represent cumulative namespace consisting of /// combined namespaces from nested elements. #[derive(Clone, Eq, PartialEq, Debug)] pub struct NamespaceStack(pub Vec<Namespace>); impl NamespaceStack { /// Returns an empty namespace stack. #[inline] pub fn empty() -> NamespaceStack { NamespaceStack(Vec::with_capacity(2)) } /// Returns a namespace stack with default items in it. /// /// Default items are the following: /// /// * `xml` → `http://www.w3.org/XML/1998/namespace`; /// * `xmlns` → `http://www.w3.org/2000/xmlns/`. #[inline] pub fn default() -> NamespaceStack { let mut nst = NamespaceStack::empty(); nst.push_empty(); // xml namespace nst.put(NS_XML_PREFIX, NS_XML_URI); // xmlns namespace nst.put(NS_XMLNS_PREFIX, NS_XMLNS_URI); // empty namespace nst.put(NS_NO_PREFIX, NS_EMPTY_URI); nst } /// Adds an empty namespace to the top of this stack. #[inline] pub fn push_empty(&mut self) -> &mut NamespaceStack { self.0.push(Namespace::empty()); self } /// Removes the topmost namespace in this stack. /// /// Panics if the stack is empty. #[inline] pub fn pop(&mut self) -> Namespace { self.0.pop().unwrap() } /// Removes the topmost namespace in this stack. /// /// Returns `Some(namespace)` if this stack is not empty and `None` otherwise. #[inline] pub fn try_pop(&mut self) -> Option<Namespace> { self.0.pop() } /// Borrows the topmost namespace mutably, leaving the stack intact. /// /// Panics if the stack is empty. #[inline] pub fn peek_mut(&mut self) -> &mut Namespace { self.0.last_mut().unwrap() } /// Borrows the topmost namespace immutably, leaving the stack intact. /// /// Panics if the stack is empty. #[inline] pub fn peek(&self) -> &Namespace { self.0.last().unwrap() } /// Puts a mapping into the topmost namespace if this stack does not already contain one. /// /// Returns a boolean flag indicating whether the insertion has completed successfully. /// Note that both key and value are matched and the mapping is inserted if either /// namespace prefix is not already mapped, or if it is mapped, but to a different URI. /// /// # Parameters /// * `prefix` --- namespace prefix; /// * `uri` --- namespace URI. /// /// # Return value /// `true` if `prefix` has been inserted successfully; `false` if the `prefix` /// was already present in the namespace stack. pub fn put_checked<P, U>(&mut self, prefix: P, uri: U) -> bool where P: Into<String> + AsRef<str>, U: Into<String> + AsRef<str> { if self.0.iter().any(|ns| ns.get(&prefix) == Some(uri.as_ref())) { false } else { self.put(prefix, uri); true } } /// Puts a mapping into the topmost namespace in this stack. /// /// This method does not override a mapping in the topmost namespace if it is /// already present, however, it does not depend on other namespaces in the stack, /// so it is possible to put a mapping which is present in lower namespaces. /// /// Returns a boolean flag indicating whether the insertion has completed successfully. /// /// # Parameters /// * `prefix` --- namespace prefix; /// * `uri` --- namespace URI. /// /// # Return value /// `true` if `prefix` has been inserted successfully; `false` if the `prefix` /// was already present in the namespace. #[inline] pub fn put<P, U>(&mut self, prefix: P, uri: U) -> bool where P: Into<String>, U: Into<String> { self.0.last_mut().unwrap().put(prefix, uri) } /// Performs a search for the given prefix in the whole stack. /// /// This method walks the stack from top to bottom, querying each namespace /// in order for the given prefix. If none of the namespaces contains the prefix, /// `None` is returned. /// /// # Parameters /// * `prefix` --- namespace prefix. #[inline] pub fn get<'a, P:?Sized+AsRef<str>>(&'a self, prefix: &P) -> Option<&'a str> { let prefix = prefix.as_ref(); for ns in self.0.iter().rev() { match ns.get(prefix) { None => {}, r => return r, } } None } /// Combines this stack of namespaces into a single namespace. /// /// Namespaces are combined in left-to-right order, that is, rightmost namespace /// elements take priority over leftmost ones. pub fn squash(&self) -> Namespace { let mut result = BTreeMap::new(); for ns in self.0.iter() { result.extend(ns.0.iter().map(|(k, v)| (k.clone(), v.clone()))); } Namespace(result) } /// Returns an object which implements `Extend` using `put_checked()` instead of `put()`. /// /// See `CheckedTarget` for more information. #[inline] pub fn checked_target(&mut self) -> CheckedTarget { CheckedTarget(self) } /// Returns an iterator over all mappings in this namespace stack. #[inline] pub fn iter(&self) -> NamespaceStackMappings { self.into_iter() } } /// An iterator over mappings from prefixes to URIs in a namespace stack. /// /// # Example /// ``` /// # use xml::namespace::NamespaceStack; /// let mut nst = NamespaceStack::empty(); /// nst.push_empty(); /// nst.put("a", "urn:A"); /// nst.put("b", "urn:B"); /// nst.push_empty(); /// nst.put("c", "urn:C"); /// /// assert_eq!(vec![("c", "urn:C"), ("a", "urn:A"), ("b", "urn:B")], nst.iter().collect::<Vec<_>>()); /// ``` pub struct NamespaceStackMappings<'a> { namespaces: Rev<Iter<'a, Namespace>>, current_namespace: Option<NamespaceMappings<'a>>, used_keys: HashSet<&'a str> } impl<'a> NamespaceStackMappings<'a> { fn go_to_next_namespace(&mut self) -> bool { self.current_namespace = self.namespaces.next().map(|ns| ns.into_iter()); self.current_namespace.is_some() } } impl<'a> Iterator for NamespaceStackMappings<'a> { type Item = UriMapping<'a>; fn next(&mut self) -> Option<UriMapping<'a>> { // If there is no current namespace and no next namespace, we're finished if self.current_namespace.is_none() &&!self.go_to_next_namespace() { return None; } let next_item = self.current_namespace.as_mut().unwrap().next(); match next_item { // There is an element in the current namespace Some((k, v)) => if self.used_keys.contains(&k) { // If the current key is used, go to the next one self.next() } else { // Otherwise insert the current key to the set of used keys and // return the mapping self.used_keys.insert(k); Some((k, v)) }, // Current namespace is exhausted None => if self.go_to_next_namespace() { // If there is next namespace, continue from it self.next() } else { // No next namespace, exiting None } } } } impl<'a> IntoIterator for &'a NamespaceStack { type Item = UriMapping<'a>; type IntoIter = NamespaceStackMappings<'a>; fn into_iter(self) -> Self::IntoIter { NamespaceStackMappings { namespaces: self.0.iter().rev(), current_namespace: None, used_keys: HashSet::new() } } } /// A type alias for a pair of `(prefix, uri)` values returned by namespace iterators. pub type UriMapping<'a> = (&'a str, &'a str); impl<'a> Extend<UriMapping<'a>> for Namespace { fn extend<T>(&mut self, iterable: T) where T: IntoIterator<Item=UriMapping<'a>> { for (prefix, uri) in iterable { self.put(prefix, uri); } } } impl<'a> Extend<UriMapping<'a>> for NamespaceStack { fn extend<T>(&mut self, iterable: T) where T: IntoIterator<Item=UriMapping<'a>> { for (prefix, uri) in iterable { self.put(prefix, uri); } } } /// A wrapper around `NamespaceStack` which implements `Extend` using `put_checked()`. /// /// # Example /// /// ``` /// # use xml::namespace::NamespaceStack; /// /// let mut nst = NamespaceStack::empty(); /// nst.push_empty(); /// nst.put("a", "urn:A"); /// nst.put("b", "urn:B"); /// nst.push_empty(); /// nst.put("c", "urn:C"); /// /// nst.checked_target().extend(vec![("a", "urn:Z"), ("b", "urn:B"), ("c", "urn:Y"), ("d", "urn:D")]); /// assert_eq!( /// vec![("a", "urn:Z"), ("c", "urn:C"), ("d", "urn:D"), ("b", "urn:B")], /// nst.iter().collect::<Vec<_>>() /// ); /// ``` /// /// Compare: /// /// ``` /// # use xml::namespace::NamespaceStack; /// # let mut nst = NamespaceStack::empty(); /// # nst.push_empty(); /// # nst.put("a", "urn:A"); /// # nst.put("b", "urn:B"); /// # nst.push_empty(); /// # nst.put("c", "urn:C"); /// /// nst.extend(vec![("a", "urn:Z"), ("b", "urn:B"), ("c", "urn:Y"), ("d", "urn:D")]); /// assert_eq!( /// vec![("a", "urn:Z"), ("b", "urn:B"), ("c", "urn:C"), ("d", "urn:D")], /// nst.iter().collect::<Vec<_>>() /// ); /// ``` pub struct CheckedTarget<'a>(&'a mut NamespaceStack); impl<'a, 'b> Extend<UriMapping<'b>> for CheckedTarget<'a> { fn extend<T>(&mut self, iterable: T) where T: IntoIterator<Item=UriMapping<'b>> { for (prefix, uri) in iterable { self.0.put_checked(prefix, uri); } } }
force_put
identifier_name
namespace.rs
//! Contains namespace manipulation types and functions. use std::iter::{Map, Rev}; use std::collections::btree_map::{BTreeMap, Entry}; use std::collections::btree_map::Iter as Entries; use std::collections::HashSet; use std::slice::Iter; /// Designates prefix for namespace definitions. /// /// See [Namespaces in XML][namespace] spec for more information. /// /// [namespace]: http://www.w3.org/TR/xml-names/#ns-decl pub const NS_XMLNS_PREFIX: &'static str = "xmlns"; /// Designates the standard URI for `xmlns` prefix. /// /// See [A Namespace Name for xmlns Attributes][1] for more information. /// /// [namespace]: http://www.w3.org/2000/xmlns/ pub const NS_XMLNS_URI: &'static str = "http://www.w3.org/2000/xmlns/"; /// Designates prefix for a namespace containing several special predefined attributes. /// /// See [2.10 White Space handling][1], [2.1 Language Identification][2], /// [XML Base specification][3] and [xml:id specification][4] for more information. /// /// [1]: http://www.w3.org/TR/REC-xml/#sec-white-space /// [2]: http://www.w3.org/TR/REC-xml/#sec-lang-tag /// [3]: http://www.w3.org/TR/xmlbase/ /// [4]: http://www.w3.org/TR/xml-id/ pub const NS_XML_PREFIX: &'static str = "xml"; /// Designates the standard URI for `xml` prefix. /// /// See `NS_XML_PREFIX` documentation for more information. pub const NS_XML_URI: &'static str = "http://www.w3.org/XML/1998/namespace"; /// Designates the absence of prefix in a qualified name. /// /// This constant should be used to define or query default namespace which should be used /// for element or attribute names without prefix. For example, if a namespace mapping /// at a particular point in the document contains correspondence like /// /// ```none /// NS_NO_PREFIX --> urn:some:namespace /// ``` /// /// then all names declared without an explicit prefix `urn:some:namespace` is assumed as /// a namespace URI. /// /// By default empty prefix corresponds to absence of namespace, but this can change either /// when writing an XML document (manually) or when reading an XML document (based on namespace /// declarations). pub const NS_NO_PREFIX: &'static str = ""; /// Designates an empty namespace URI, which is equivalent to absence of namespace. /// /// This constant should not usually be used directly; it is used to designate that /// empty prefix corresponds to absent namespace in `NamespaceStack` instances created with /// `NamespaceStack::default()`. Therefore, it can be used to restore `NS_NO_PREFIX` mapping /// in a namespace back to its default value. pub const NS_EMPTY_URI: &'static str = ""; /// Namespace is a map from prefixes to namespace URIs. /// /// No prefix (i.e. default namespace) is designated by `NS_NO_PREFIX` constant. #[derive(PartialEq, Eq, Clone, Debug)] pub struct Namespace(pub BTreeMap<String, String>); impl Namespace { /// Returns an empty namespace. #[inline] pub fn empty() -> Namespace { Namespace(BTreeMap::new()) } /// Checks whether this namespace is empty. #[inline] pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Checks whether this namespace is essentially empty, that is, it does not contain /// anything but default mappings. pub fn is_essentially_empty(&self) -> bool { // a shortcut for a namespace which is definitely not empty if self.0.len() > 3 { return false; } self.0.iter().all(|(k, v)| match (&**k, &**v) { (NS_NO_PREFIX, NS_EMPTY_URI) => true, (NS_XMLNS_PREFIX, NS_XMLNS_URI) => true, (NS_XML_PREFIX, NS_XML_URI) => true, _ => false }) } /// Checks whether this namespace mapping contains the given prefix. /// /// # Parameters /// * `prefix` --- namespace prefix. /// /// # Return value /// `true` if this namespace contains the given prefix, `false` otherwise. #[inline] pub fn contains<P:?Sized+AsRef<str>>(&self, prefix: &P) -> bool { self.0.contains_key(prefix.as_ref()) } /// Puts a mapping into this namespace. /// /// This method does not override any already existing mappings. /// /// Returns a boolean flag indicating whether the map already contained /// the given prefix. /// /// # Parameters /// * `prefix` --- namespace prefix; /// * `uri` --- namespace URI. /// /// # Return value /// `true` if `prefix` has been inserted successfully; `false` if the `prefix` /// was already present in the namespace. pub fn put<P, U>(&mut self, prefix: P, uri: U) -> bool where P: Into<String>, U: Into<String> { match self.0.entry(prefix.into()) { Entry::Occupied(_) => false, Entry::Vacant(ve) => { ve.insert(uri.into()); true } } } /// Puts a mapping into this namespace forcefully. /// /// This method, unlike `put()`, does replace an already existing mapping. /// /// Returns previous URI which was assigned to the given prefix, if it is present. /// /// # Parameters /// * `prefix` --- namespace prefix; /// * `uri` --- namespace URI. /// /// # Return value /// `Some(uri)` with `uri` being a previous URI assigned to the `prefix`, or /// `None` if such prefix was not present in the namespace before. pub fn force_put<P, U>(&mut self, prefix: P, uri: U) -> Option<String> where P: Into<String>, U: Into<String> { self.0.insert(prefix.into(), uri.into()) } /// Queries the namespace for the given prefix. /// /// # Parameters /// * `prefix` --- namespace prefix. /// /// # Return value /// Namespace URI corresponding to the given prefix, if it is present. pub fn get<'a, P:?Sized+AsRef<str>>(&'a self, prefix: &P) -> Option<&'a str> { self.0.get(prefix.as_ref()).map(|s| &**s) } } /// An alias for iterator type for namespace mappings contained in a namespace. pub type NamespaceMappings<'a> = Map< Entries<'a, String, String>, for<'b> fn((&'b String, &'b String)) -> UriMapping<'b> >; impl<'a> IntoIterator for &'a Namespace { type Item = UriMapping<'a>; type IntoIter = NamespaceMappings<'a>; fn into_iter(self) -> Self::IntoIter { fn mapper<'a>((prefix, uri): (&'a String, &'a String)) -> UriMapping<'a> { (&*prefix, &*uri) } self.0.iter().map(mapper) } } /// Namespace stack is a sequence of namespaces. /// /// Namespace stack is used to represent cumulative namespace consisting of /// combined namespaces from nested elements. #[derive(Clone, Eq, PartialEq, Debug)] pub struct NamespaceStack(pub Vec<Namespace>); impl NamespaceStack { /// Returns an empty namespace stack. #[inline] pub fn empty() -> NamespaceStack { NamespaceStack(Vec::with_capacity(2)) } /// Returns a namespace stack with default items in it. /// /// Default items are the following: /// /// * `xml` → `http://www.w3.org/XML/1998/namespace`; /// * `xmlns` → `http://www.w3.org/2000/xmlns/`. #[inline] pub fn default() -> NamespaceStack { let mut nst = NamespaceStack::empty(); nst.push_empty(); // xml namespace nst.put(NS_XML_PREFIX, NS_XML_URI); // xmlns namespace nst.put(NS_XMLNS_PREFIX, NS_XMLNS_URI); // empty namespace nst.put(NS_NO_PREFIX, NS_EMPTY_URI); nst } /// Adds an empty namespace to the top of this stack. #[inline] pub fn push_empty(&mut self) -> &mut NamespaceStack { self.0.push(Namespace::empty()); self } /// Removes the topmost namespace in this stack. /// /// Panics if the stack is empty. #[inline] pub fn pop(&mut self) -> Namespace { self.0.pop().unwrap() } /// Removes the topmost namespace in this stack. /// /// Returns `Some(namespace)` if this stack is not empty and `None` otherwise. #[inline] pub fn try_pop(&mut self) -> Option<Namespace> { self.0.pop() } /// Borrows the topmost namespace mutably, leaving the stack intact. /// /// Panics if the stack is empty. #[inline] pub fn peek_mut(&mut self) -> &mut Namespace {
/// Borrows the topmost namespace immutably, leaving the stack intact. /// /// Panics if the stack is empty. #[inline] pub fn peek(&self) -> &Namespace { self.0.last().unwrap() } /// Puts a mapping into the topmost namespace if this stack does not already contain one. /// /// Returns a boolean flag indicating whether the insertion has completed successfully. /// Note that both key and value are matched and the mapping is inserted if either /// namespace prefix is not already mapped, or if it is mapped, but to a different URI. /// /// # Parameters /// * `prefix` --- namespace prefix; /// * `uri` --- namespace URI. /// /// # Return value /// `true` if `prefix` has been inserted successfully; `false` if the `prefix` /// was already present in the namespace stack. pub fn put_checked<P, U>(&mut self, prefix: P, uri: U) -> bool where P: Into<String> + AsRef<str>, U: Into<String> + AsRef<str> { if self.0.iter().any(|ns| ns.get(&prefix) == Some(uri.as_ref())) { false } else { self.put(prefix, uri); true } } /// Puts a mapping into the topmost namespace in this stack. /// /// This method does not override a mapping in the topmost namespace if it is /// already present, however, it does not depend on other namespaces in the stack, /// so it is possible to put a mapping which is present in lower namespaces. /// /// Returns a boolean flag indicating whether the insertion has completed successfully. /// /// # Parameters /// * `prefix` --- namespace prefix; /// * `uri` --- namespace URI. /// /// # Return value /// `true` if `prefix` has been inserted successfully; `false` if the `prefix` /// was already present in the namespace. #[inline] pub fn put<P, U>(&mut self, prefix: P, uri: U) -> bool where P: Into<String>, U: Into<String> { self.0.last_mut().unwrap().put(prefix, uri) } /// Performs a search for the given prefix in the whole stack. /// /// This method walks the stack from top to bottom, querying each namespace /// in order for the given prefix. If none of the namespaces contains the prefix, /// `None` is returned. /// /// # Parameters /// * `prefix` --- namespace prefix. #[inline] pub fn get<'a, P:?Sized+AsRef<str>>(&'a self, prefix: &P) -> Option<&'a str> { let prefix = prefix.as_ref(); for ns in self.0.iter().rev() { match ns.get(prefix) { None => {}, r => return r, } } None } /// Combines this stack of namespaces into a single namespace. /// /// Namespaces are combined in left-to-right order, that is, rightmost namespace /// elements take priority over leftmost ones. pub fn squash(&self) -> Namespace { let mut result = BTreeMap::new(); for ns in self.0.iter() { result.extend(ns.0.iter().map(|(k, v)| (k.clone(), v.clone()))); } Namespace(result) } /// Returns an object which implements `Extend` using `put_checked()` instead of `put()`. /// /// See `CheckedTarget` for more information. #[inline] pub fn checked_target(&mut self) -> CheckedTarget { CheckedTarget(self) } /// Returns an iterator over all mappings in this namespace stack. #[inline] pub fn iter(&self) -> NamespaceStackMappings { self.into_iter() } } /// An iterator over mappings from prefixes to URIs in a namespace stack. /// /// # Example /// ``` /// # use xml::namespace::NamespaceStack; /// let mut nst = NamespaceStack::empty(); /// nst.push_empty(); /// nst.put("a", "urn:A"); /// nst.put("b", "urn:B"); /// nst.push_empty(); /// nst.put("c", "urn:C"); /// /// assert_eq!(vec![("c", "urn:C"), ("a", "urn:A"), ("b", "urn:B")], nst.iter().collect::<Vec<_>>()); /// ``` pub struct NamespaceStackMappings<'a> { namespaces: Rev<Iter<'a, Namespace>>, current_namespace: Option<NamespaceMappings<'a>>, used_keys: HashSet<&'a str> } impl<'a> NamespaceStackMappings<'a> { fn go_to_next_namespace(&mut self) -> bool { self.current_namespace = self.namespaces.next().map(|ns| ns.into_iter()); self.current_namespace.is_some() } } impl<'a> Iterator for NamespaceStackMappings<'a> { type Item = UriMapping<'a>; fn next(&mut self) -> Option<UriMapping<'a>> { // If there is no current namespace and no next namespace, we're finished if self.current_namespace.is_none() &&!self.go_to_next_namespace() { return None; } let next_item = self.current_namespace.as_mut().unwrap().next(); match next_item { // There is an element in the current namespace Some((k, v)) => if self.used_keys.contains(&k) { // If the current key is used, go to the next one self.next() } else { // Otherwise insert the current key to the set of used keys and // return the mapping self.used_keys.insert(k); Some((k, v)) }, // Current namespace is exhausted None => if self.go_to_next_namespace() { // If there is next namespace, continue from it self.next() } else { // No next namespace, exiting None } } } } impl<'a> IntoIterator for &'a NamespaceStack { type Item = UriMapping<'a>; type IntoIter = NamespaceStackMappings<'a>; fn into_iter(self) -> Self::IntoIter { NamespaceStackMappings { namespaces: self.0.iter().rev(), current_namespace: None, used_keys: HashSet::new() } } } /// A type alias for a pair of `(prefix, uri)` values returned by namespace iterators. pub type UriMapping<'a> = (&'a str, &'a str); impl<'a> Extend<UriMapping<'a>> for Namespace { fn extend<T>(&mut self, iterable: T) where T: IntoIterator<Item=UriMapping<'a>> { for (prefix, uri) in iterable { self.put(prefix, uri); } } } impl<'a> Extend<UriMapping<'a>> for NamespaceStack { fn extend<T>(&mut self, iterable: T) where T: IntoIterator<Item=UriMapping<'a>> { for (prefix, uri) in iterable { self.put(prefix, uri); } } } /// A wrapper around `NamespaceStack` which implements `Extend` using `put_checked()`. /// /// # Example /// /// ``` /// # use xml::namespace::NamespaceStack; /// /// let mut nst = NamespaceStack::empty(); /// nst.push_empty(); /// nst.put("a", "urn:A"); /// nst.put("b", "urn:B"); /// nst.push_empty(); /// nst.put("c", "urn:C"); /// /// nst.checked_target().extend(vec![("a", "urn:Z"), ("b", "urn:B"), ("c", "urn:Y"), ("d", "urn:D")]); /// assert_eq!( /// vec![("a", "urn:Z"), ("c", "urn:C"), ("d", "urn:D"), ("b", "urn:B")], /// nst.iter().collect::<Vec<_>>() /// ); /// ``` /// /// Compare: /// /// ``` /// # use xml::namespace::NamespaceStack; /// # let mut nst = NamespaceStack::empty(); /// # nst.push_empty(); /// # nst.put("a", "urn:A"); /// # nst.put("b", "urn:B"); /// # nst.push_empty(); /// # nst.put("c", "urn:C"); /// /// nst.extend(vec![("a", "urn:Z"), ("b", "urn:B"), ("c", "urn:Y"), ("d", "urn:D")]); /// assert_eq!( /// vec![("a", "urn:Z"), ("b", "urn:B"), ("c", "urn:C"), ("d", "urn:D")], /// nst.iter().collect::<Vec<_>>() /// ); /// ``` pub struct CheckedTarget<'a>(&'a mut NamespaceStack); impl<'a, 'b> Extend<UriMapping<'b>> for CheckedTarget<'a> { fn extend<T>(&mut self, iterable: T) where T: IntoIterator<Item=UriMapping<'b>> { for (prefix, uri) in iterable { self.0.put_checked(prefix, uri); } } }
self.0.last_mut().unwrap() }
identifier_body
issue-15858.rs
// Copyright 2012-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. static mut DROP_RAN: bool = false; trait Bar { fn do_something(&mut self); } struct BarImpl; impl Bar for BarImpl { fn do_something(&mut self)
} struct Foo<B: Bar>(B); impl<B: Bar> Drop for Foo<B> { fn drop(&mut self) { unsafe { DROP_RAN = true; } } } fn main() { { let _x: Foo<BarImpl> = Foo(BarImpl); } unsafe { assert_eq!(DROP_RAN, true); } }
{}
identifier_body
issue-15858.rs
// Copyright 2012-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. static mut DROP_RAN: bool = false; trait Bar { fn do_something(&mut self); } struct BarImpl; impl Bar for BarImpl { fn do_something(&mut self) {} } struct Foo<B: Bar>(B); impl<B: Bar> Drop for Foo<B> { fn drop(&mut self) { unsafe { DROP_RAN = true; } } } fn main() { { let _x: Foo<BarImpl> = Foo(BarImpl); } unsafe { assert_eq!(DROP_RAN, true); } }
random_line_split
issue-15858.rs
// Copyright 2012-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. static mut DROP_RAN: bool = false; trait Bar { fn do_something(&mut self); } struct BarImpl; impl Bar for BarImpl { fn do_something(&mut self) {} } struct Foo<B: Bar>(B); impl<B: Bar> Drop for Foo<B> { fn
(&mut self) { unsafe { DROP_RAN = true; } } } fn main() { { let _x: Foo<BarImpl> = Foo(BarImpl); } unsafe { assert_eq!(DROP_RAN, true); } }
drop
identifier_name
issue-3668.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. struct P { child: Option<Box<P>> } trait PTrait { fn getChildOption(&self) -> Option<Box<P>>; } impl PTrait for P { fn getChildOption(&self) -> Option<Box<P>> { static childVal: Box<P> = self.child.get(); //~^ ERROR attempt to use a non-constant value in a constant panic!(); } } fn
() {}
main
identifier_name
issue-3668.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. struct P { child: Option<Box<P>> } trait PTrait { fn getChildOption(&self) -> Option<Box<P>>; } impl PTrait for P { fn getChildOption(&self) -> Option<Box<P>> { static childVal: Box<P> = self.child.get(); //~^ ERROR attempt to use a non-constant value in a constant panic!(); } } fn main()
{}
identifier_body
const-adt-align-mismatch.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::mem; #[derive(PartialEq, Show)] enum Foo { A(u32), Bar([u16; 4]), C } // NOTE(eddyb) Don't make this a const, needs to be a static // so it is always instantiated as a LLVM constant value. static FOO: Foo = Foo::C; fn main()
{ assert_eq!(FOO, Foo::C); assert_eq!(mem::size_of::<Foo>(), 12); assert_eq!(mem::min_align_of::<Foo>(), 4); }
identifier_body
const-adt-align-mismatch.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::mem; #[derive(PartialEq, Show)] enum Foo { A(u32), Bar([u16; 4]), C } // NOTE(eddyb) Don't make this a const, needs to be a static // so it is always instantiated as a LLVM constant value. static FOO: Foo = Foo::C; fn main() { assert_eq!(FOO, Foo::C); assert_eq!(mem::size_of::<Foo>(), 12); assert_eq!(mem::min_align_of::<Foo>(), 4); }
random_line_split
const-adt-align-mismatch.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::mem; #[derive(PartialEq, Show)] enum Foo { A(u32), Bar([u16; 4]), C } // NOTE(eddyb) Don't make this a const, needs to be a static // so it is always instantiated as a LLVM constant value. static FOO: Foo = Foo::C; fn
() { assert_eq!(FOO, Foo::C); assert_eq!(mem::size_of::<Foo>(), 12); assert_eq!(mem::min_align_of::<Foo>(), 4); }
main
identifier_name
doc.rs
//! This file tests for the `DOC_MARKDOWN` lint. #![allow(dead_code, incomplete_features)] #![warn(clippy::doc_markdown)] #![feature(custom_inner_attributes, generic_const_exprs, const_option)] #![rustfmt::skip] /// The foo_bar function does _nothing_. See also foo::bar. (note the dot there) /// Markdown is _weird_. I mean _really weird_. This \_ is ok. So is `_`. But not Foo::some_fun /// which should be reported only once despite being __doubly bad__. /// Here be ::a::global:path. /// That's not code ~NotInCodeBlock~. /// be_sure_we_got_to_the_end_of_it fn foo_bar() { } /// That one tests multiline ticks. /// ```rust /// foo_bar FOO_BAR /// _foo bar_ /// ``` /// /// ~~~rust /// foo_bar FOO_BAR /// _foo bar_ /// ~~~ /// be_sure_we_got_to_the_end_of_it fn multiline_codeblock() { } /// This _is a test for /// multiline /// emphasis_. /// be_sure_we_got_to_the_end_of_it fn
() { } /// This tests units. See also #835. /// kiB MiB GiB TiB PiB EiB /// kib Mib Gib Tib Pib Eib /// kB MB GB TB PB EB /// kb Mb Gb Tb Pb Eb /// 32kiB 32MiB 32GiB 32TiB 32PiB 32EiB /// 32kib 32Mib 32Gib 32Tib 32Pib 32Eib /// 32kB 32MB 32GB 32TB 32PB 32EB /// 32kb 32Mb 32Gb 32Tb 32Pb 32Eb /// NaN /// be_sure_we_got_to_the_end_of_it fn test_units() { } /// This tests allowed identifiers. /// KiB MiB GiB TiB PiB EiB /// DirectX /// ECMAScript /// GPLv2 GPLv3 /// GitHub GitLab /// IPv4 IPv6 /// ClojureScript CoffeeScript JavaScript PureScript TypeScript /// NaN NaNs /// OAuth GraphQL /// OCaml /// OpenGL OpenMP OpenSSH OpenSSL OpenStreetMap OpenDNS /// WebGL /// TensorFlow /// TrueType /// iOS macOS FreeBSD /// TeX LaTeX BibTeX BibLaTeX /// MinGW /// CamelCase (see also #2395) /// be_sure_we_got_to_the_end_of_it fn test_allowed() { } /// This test has [a link_with_underscores][chunked-example] inside it. See #823. /// See also [the issue tracker](https://github.com/rust-lang/rust-clippy/search?q=clippy::doc_markdown&type=Issues) /// on GitHub (which is a camel-cased word, but is OK). And here is another [inline link][inline_link]. /// It can also be [inline_link2]. /// /// [chunked-example]: https://en.wikipedia.org/wiki/Chunked_transfer_encoding#Example /// [inline_link]: https://foobar /// [inline_link2]: https://foobar /// The `main` function is the entry point of the program. Here it only calls the `foo_bar` and /// `multiline_ticks` functions. /// /// expression of the type `_ <bit_op> m <cmp_op> c` (where `<bit_op>` /// is one of {`&`, '|'} and `<cmp_op>` is one of {`!=`, `>=`, `>`, /// be_sure_we_got_to_the_end_of_it fn main() { foo_bar(); multiline_codeblock(); test_emphasis(); test_units(); } /// ## CamelCaseThing /// Talks about `CamelCaseThing`. Titles should be ignored; see issue #897. /// /// # CamelCaseThing /// /// Not a title #897 CamelCaseThing /// be_sure_we_got_to_the_end_of_it fn issue897() { } /// I am confused by brackets? (`x_y`) /// I am confused by brackets? (foo `x_y`) /// I am confused by brackets? (`x_y` foo) /// be_sure_we_got_to_the_end_of_it fn issue900() { } /// Diesel queries also have a similar problem to [Iterator][iterator], where /// /// More talking /// returning them from a function requires exposing the implementation of that /// function. The [`helper_types`][helper_types] module exists to help with this, /// but you might want to hide the return type or have it conditionally change. /// Boxing can achieve both. /// /// [iterator]: https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html /// [helper_types]:../helper_types/index.html /// be_sure_we_got_to_the_end_of_it fn issue883() { } /// `foo_bar /// baz_quz` /// [foo /// bar](https://doc.rust-lang.org/stable/std/iter/trait.IteratorFooBar.html) fn multiline() { } /** E.g., serialization of an empty list: FooBar ``` That's in a code block: `PackedNode` ``` And BarQuz too. be_sure_we_got_to_the_end_of_it */ fn issue1073() { } /** E.g., serialization of an empty list: FooBar ``` That's in a code block: PackedNode ``` And BarQuz too. be_sure_we_got_to_the_end_of_it */ fn issue1073_alt() { } /// Tests more than three quotes: /// ```` /// DoNotWarn /// ``` /// StillDont /// ```` /// be_sure_we_got_to_the_end_of_it fn four_quotes() { } /// See [NIST SP 800-56A, revision 2]. /// /// [NIST SP 800-56A, revision 2]: /// https://github.com/rust-lang/rust-clippy/issues/902#issuecomment-261919419 fn issue_902_comment() {} #[cfg_attr(feature = "a", doc = " ```")] #[cfg_attr(not(feature = "a"), doc = " ```ignore")] /// fn main() { /// let s = "localhost:10000".to_string(); /// println!("{}", s); /// } /// ``` fn issue_1469() {} /** * This is a doc comment that should not be a list *This would also be an error under a strict common mark interpretation */ fn issue_1920() {} /// Ok: <http://www.unicode.org/reports/tr9/#Reordering_Resolved_Levels> /// /// Not ok: http://www.unicode.org /// Not ok: https://www.unicode.org /// Not ok: http://www.unicode.org/ /// Not ok: http://www.unicode.org/reports/tr9/#Reordering_Resolved_Levels fn issue_1832() {} /// An iterator over mycrate::Collection's values. /// It should not lint a `'static` lifetime in ticks. fn issue_2210() {} /// This should not cause the lint to trigger: /// #REQ-data-family.lint_partof_exists fn issue_2343() {} /// This should not cause an ICE: /// __|_ _|__||_| fn pulldown_cmark_crash() {} // issue #7033 - generic_const_exprs ICE struct S<T, const N: usize> where [(); N.checked_next_power_of_two().unwrap()]: { arr: [T; N.checked_next_power_of_two().unwrap()], n: usize, } impl<T: Copy + Default, const N: usize> S<T, N> where [(); N.checked_next_power_of_two().unwrap()]: { fn new() -> Self { Self { arr: [T::default(); N.checked_next_power_of_two().unwrap()], n: 0, } } }
test_emphasis
identifier_name
doc.rs
//! This file tests for the `DOC_MARKDOWN` lint. #![allow(dead_code, incomplete_features)] #![warn(clippy::doc_markdown)] #![feature(custom_inner_attributes, generic_const_exprs, const_option)] #![rustfmt::skip] /// The foo_bar function does _nothing_. See also foo::bar. (note the dot there) /// Markdown is _weird_. I mean _really weird_. This \_ is ok. So is `_`. But not Foo::some_fun /// which should be reported only once despite being __doubly bad__. /// Here be ::a::global:path. /// That's not code ~NotInCodeBlock~. /// be_sure_we_got_to_the_end_of_it fn foo_bar() { } /// That one tests multiline ticks. /// ```rust /// foo_bar FOO_BAR /// _foo bar_ /// ``` /// /// ~~~rust /// foo_bar FOO_BAR /// _foo bar_ /// ~~~ /// be_sure_we_got_to_the_end_of_it fn multiline_codeblock() { } /// This _is a test for /// multiline /// emphasis_. /// be_sure_we_got_to_the_end_of_it fn test_emphasis() { } /// This tests units. See also #835. /// kiB MiB GiB TiB PiB EiB
/// kib Mib Gib Tib Pib Eib /// kB MB GB TB PB EB /// kb Mb Gb Tb Pb Eb /// 32kiB 32MiB 32GiB 32TiB 32PiB 32EiB /// 32kib 32Mib 32Gib 32Tib 32Pib 32Eib /// 32kB 32MB 32GB 32TB 32PB 32EB /// 32kb 32Mb 32Gb 32Tb 32Pb 32Eb /// NaN /// be_sure_we_got_to_the_end_of_it fn test_units() { } /// This tests allowed identifiers. /// KiB MiB GiB TiB PiB EiB /// DirectX /// ECMAScript /// GPLv2 GPLv3 /// GitHub GitLab /// IPv4 IPv6 /// ClojureScript CoffeeScript JavaScript PureScript TypeScript /// NaN NaNs /// OAuth GraphQL /// OCaml /// OpenGL OpenMP OpenSSH OpenSSL OpenStreetMap OpenDNS /// WebGL /// TensorFlow /// TrueType /// iOS macOS FreeBSD /// TeX LaTeX BibTeX BibLaTeX /// MinGW /// CamelCase (see also #2395) /// be_sure_we_got_to_the_end_of_it fn test_allowed() { } /// This test has [a link_with_underscores][chunked-example] inside it. See #823. /// See also [the issue tracker](https://github.com/rust-lang/rust-clippy/search?q=clippy::doc_markdown&type=Issues) /// on GitHub (which is a camel-cased word, but is OK). And here is another [inline link][inline_link]. /// It can also be [inline_link2]. /// /// [chunked-example]: https://en.wikipedia.org/wiki/Chunked_transfer_encoding#Example /// [inline_link]: https://foobar /// [inline_link2]: https://foobar /// The `main` function is the entry point of the program. Here it only calls the `foo_bar` and /// `multiline_ticks` functions. /// /// expression of the type `_ <bit_op> m <cmp_op> c` (where `<bit_op>` /// is one of {`&`, '|'} and `<cmp_op>` is one of {`!=`, `>=`, `>`, /// be_sure_we_got_to_the_end_of_it fn main() { foo_bar(); multiline_codeblock(); test_emphasis(); test_units(); } /// ## CamelCaseThing /// Talks about `CamelCaseThing`. Titles should be ignored; see issue #897. /// /// # CamelCaseThing /// /// Not a title #897 CamelCaseThing /// be_sure_we_got_to_the_end_of_it fn issue897() { } /// I am confused by brackets? (`x_y`) /// I am confused by brackets? (foo `x_y`) /// I am confused by brackets? (`x_y` foo) /// be_sure_we_got_to_the_end_of_it fn issue900() { } /// Diesel queries also have a similar problem to [Iterator][iterator], where /// /// More talking /// returning them from a function requires exposing the implementation of that /// function. The [`helper_types`][helper_types] module exists to help with this, /// but you might want to hide the return type or have it conditionally change. /// Boxing can achieve both. /// /// [iterator]: https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html /// [helper_types]:../helper_types/index.html /// be_sure_we_got_to_the_end_of_it fn issue883() { } /// `foo_bar /// baz_quz` /// [foo /// bar](https://doc.rust-lang.org/stable/std/iter/trait.IteratorFooBar.html) fn multiline() { } /** E.g., serialization of an empty list: FooBar ``` That's in a code block: `PackedNode` ``` And BarQuz too. be_sure_we_got_to_the_end_of_it */ fn issue1073() { } /** E.g., serialization of an empty list: FooBar ``` That's in a code block: PackedNode ``` And BarQuz too. be_sure_we_got_to_the_end_of_it */ fn issue1073_alt() { } /// Tests more than three quotes: /// ```` /// DoNotWarn /// ``` /// StillDont /// ```` /// be_sure_we_got_to_the_end_of_it fn four_quotes() { } /// See [NIST SP 800-56A, revision 2]. /// /// [NIST SP 800-56A, revision 2]: /// https://github.com/rust-lang/rust-clippy/issues/902#issuecomment-261919419 fn issue_902_comment() {} #[cfg_attr(feature = "a", doc = " ```")] #[cfg_attr(not(feature = "a"), doc = " ```ignore")] /// fn main() { /// let s = "localhost:10000".to_string(); /// println!("{}", s); /// } /// ``` fn issue_1469() {} /** * This is a doc comment that should not be a list *This would also be an error under a strict common mark interpretation */ fn issue_1920() {} /// Ok: <http://www.unicode.org/reports/tr9/#Reordering_Resolved_Levels> /// /// Not ok: http://www.unicode.org /// Not ok: https://www.unicode.org /// Not ok: http://www.unicode.org/ /// Not ok: http://www.unicode.org/reports/tr9/#Reordering_Resolved_Levels fn issue_1832() {} /// An iterator over mycrate::Collection's values. /// It should not lint a `'static` lifetime in ticks. fn issue_2210() {} /// This should not cause the lint to trigger: /// #REQ-data-family.lint_partof_exists fn issue_2343() {} /// This should not cause an ICE: /// __|_ _|__||_| fn pulldown_cmark_crash() {} // issue #7033 - generic_const_exprs ICE struct S<T, const N: usize> where [(); N.checked_next_power_of_two().unwrap()]: { arr: [T; N.checked_next_power_of_two().unwrap()], n: usize, } impl<T: Copy + Default, const N: usize> S<T, N> where [(); N.checked_next_power_of_two().unwrap()]: { fn new() -> Self { Self { arr: [T::default(); N.checked_next_power_of_two().unwrap()], n: 0, } } }
random_line_split
doc.rs
//! This file tests for the `DOC_MARKDOWN` lint. #![allow(dead_code, incomplete_features)] #![warn(clippy::doc_markdown)] #![feature(custom_inner_attributes, generic_const_exprs, const_option)] #![rustfmt::skip] /// The foo_bar function does _nothing_. See also foo::bar. (note the dot there) /// Markdown is _weird_. I mean _really weird_. This \_ is ok. So is `_`. But not Foo::some_fun /// which should be reported only once despite being __doubly bad__. /// Here be ::a::global:path. /// That's not code ~NotInCodeBlock~. /// be_sure_we_got_to_the_end_of_it fn foo_bar() { } /// That one tests multiline ticks. /// ```rust /// foo_bar FOO_BAR /// _foo bar_ /// ``` /// /// ~~~rust /// foo_bar FOO_BAR /// _foo bar_ /// ~~~ /// be_sure_we_got_to_the_end_of_it fn multiline_codeblock() { } /// This _is a test for /// multiline /// emphasis_. /// be_sure_we_got_to_the_end_of_it fn test_emphasis() { } /// This tests units. See also #835. /// kiB MiB GiB TiB PiB EiB /// kib Mib Gib Tib Pib Eib /// kB MB GB TB PB EB /// kb Mb Gb Tb Pb Eb /// 32kiB 32MiB 32GiB 32TiB 32PiB 32EiB /// 32kib 32Mib 32Gib 32Tib 32Pib 32Eib /// 32kB 32MB 32GB 32TB 32PB 32EB /// 32kb 32Mb 32Gb 32Tb 32Pb 32Eb /// NaN /// be_sure_we_got_to_the_end_of_it fn test_units() { } /// This tests allowed identifiers. /// KiB MiB GiB TiB PiB EiB /// DirectX /// ECMAScript /// GPLv2 GPLv3 /// GitHub GitLab /// IPv4 IPv6 /// ClojureScript CoffeeScript JavaScript PureScript TypeScript /// NaN NaNs /// OAuth GraphQL /// OCaml /// OpenGL OpenMP OpenSSH OpenSSL OpenStreetMap OpenDNS /// WebGL /// TensorFlow /// TrueType /// iOS macOS FreeBSD /// TeX LaTeX BibTeX BibLaTeX /// MinGW /// CamelCase (see also #2395) /// be_sure_we_got_to_the_end_of_it fn test_allowed() { } /// This test has [a link_with_underscores][chunked-example] inside it. See #823. /// See also [the issue tracker](https://github.com/rust-lang/rust-clippy/search?q=clippy::doc_markdown&type=Issues) /// on GitHub (which is a camel-cased word, but is OK). And here is another [inline link][inline_link]. /// It can also be [inline_link2]. /// /// [chunked-example]: https://en.wikipedia.org/wiki/Chunked_transfer_encoding#Example /// [inline_link]: https://foobar /// [inline_link2]: https://foobar /// The `main` function is the entry point of the program. Here it only calls the `foo_bar` and /// `multiline_ticks` functions. /// /// expression of the type `_ <bit_op> m <cmp_op> c` (where `<bit_op>` /// is one of {`&`, '|'} and `<cmp_op>` is one of {`!=`, `>=`, `>`, /// be_sure_we_got_to_the_end_of_it fn main() { foo_bar(); multiline_codeblock(); test_emphasis(); test_units(); } /// ## CamelCaseThing /// Talks about `CamelCaseThing`. Titles should be ignored; see issue #897. /// /// # CamelCaseThing /// /// Not a title #897 CamelCaseThing /// be_sure_we_got_to_the_end_of_it fn issue897() { } /// I am confused by brackets? (`x_y`) /// I am confused by brackets? (foo `x_y`) /// I am confused by brackets? (`x_y` foo) /// be_sure_we_got_to_the_end_of_it fn issue900() { } /// Diesel queries also have a similar problem to [Iterator][iterator], where /// /// More talking /// returning them from a function requires exposing the implementation of that /// function. The [`helper_types`][helper_types] module exists to help with this, /// but you might want to hide the return type or have it conditionally change. /// Boxing can achieve both. /// /// [iterator]: https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html /// [helper_types]:../helper_types/index.html /// be_sure_we_got_to_the_end_of_it fn issue883() { } /// `foo_bar /// baz_quz` /// [foo /// bar](https://doc.rust-lang.org/stable/std/iter/trait.IteratorFooBar.html) fn multiline() { } /** E.g., serialization of an empty list: FooBar ``` That's in a code block: `PackedNode` ``` And BarQuz too. be_sure_we_got_to_the_end_of_it */ fn issue1073() { } /** E.g., serialization of an empty list: FooBar ``` That's in a code block: PackedNode ``` And BarQuz too. be_sure_we_got_to_the_end_of_it */ fn issue1073_alt() { } /// Tests more than three quotes: /// ```` /// DoNotWarn /// ``` /// StillDont /// ```` /// be_sure_we_got_to_the_end_of_it fn four_quotes() { } /// See [NIST SP 800-56A, revision 2]. /// /// [NIST SP 800-56A, revision 2]: /// https://github.com/rust-lang/rust-clippy/issues/902#issuecomment-261919419 fn issue_902_comment()
#[cfg_attr(feature = "a", doc = " ```")] #[cfg_attr(not(feature = "a"), doc = " ```ignore")] /// fn main() { /// let s = "localhost:10000".to_string(); /// println!("{}", s); /// } /// ``` fn issue_1469() {} /** * This is a doc comment that should not be a list *This would also be an error under a strict common mark interpretation */ fn issue_1920() {} /// Ok: <http://www.unicode.org/reports/tr9/#Reordering_Resolved_Levels> /// /// Not ok: http://www.unicode.org /// Not ok: https://www.unicode.org /// Not ok: http://www.unicode.org/ /// Not ok: http://www.unicode.org/reports/tr9/#Reordering_Resolved_Levels fn issue_1832() {} /// An iterator over mycrate::Collection's values. /// It should not lint a `'static` lifetime in ticks. fn issue_2210() {} /// This should not cause the lint to trigger: /// #REQ-data-family.lint_partof_exists fn issue_2343() {} /// This should not cause an ICE: /// __|_ _|__||_| fn pulldown_cmark_crash() {} // issue #7033 - generic_const_exprs ICE struct S<T, const N: usize> where [(); N.checked_next_power_of_two().unwrap()]: { arr: [T; N.checked_next_power_of_two().unwrap()], n: usize, } impl<T: Copy + Default, const N: usize> S<T, N> where [(); N.checked_next_power_of_two().unwrap()]: { fn new() -> Self { Self { arr: [T::default(); N.checked_next_power_of_two().unwrap()], n: 0, } } }
{}
identifier_body
lint-non-camel-case-types.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
#![forbid(non_camel_case_types)] #![allow(dead_code)] struct ONE_TWO_THREE; //~^ ERROR type `ONE_TWO_THREE` should have a camel case name such as `OneTwoThree` struct foo { //~ ERROR type `foo` should have a camel case name such as `Foo` bar: isize, } enum foo2 { //~ ERROR type `foo2` should have a camel case name such as `Foo2` Bar } struct foo3 { //~ ERROR type `foo3` should have a camel case name such as `Foo3` bar: isize } type foo4 = isize; //~ ERROR type `foo4` should have a camel case name such as `Foo4` enum Foo5 { bar //~ ERROR variant `bar` should have a camel case name such as `Bar` } trait foo6 { //~ ERROR trait `foo6` should have a camel case name such as `Foo6` fn dummy(&self) { } } fn f<ty>(_: ty) {} //~ ERROR type parameter `ty` should have a camel case name such as `Ty` #[repr(C)] struct foo7 { bar: isize, } struct X86_64; struct X86__64; //~ ERROR type `X86__64` should have a camel case name such as `X86_64` struct Abc_123; //~ ERROR type `Abc_123` should have a camel case name such as `Abc123` struct A1_b2_c3; //~ ERROR type `A1_b2_c3` should have a camel case name such as `A1B2C3` fn main() { }
// option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
lint-non-camel-case-types.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. #![forbid(non_camel_case_types)] #![allow(dead_code)] struct ONE_TWO_THREE; //~^ ERROR type `ONE_TWO_THREE` should have a camel case name such as `OneTwoThree` struct foo { //~ ERROR type `foo` should have a camel case name such as `Foo` bar: isize, } enum foo2 { //~ ERROR type `foo2` should have a camel case name such as `Foo2` Bar } struct foo3 { //~ ERROR type `foo3` should have a camel case name such as `Foo3` bar: isize } type foo4 = isize; //~ ERROR type `foo4` should have a camel case name such as `Foo4` enum Foo5 { bar //~ ERROR variant `bar` should have a camel case name such as `Bar` } trait foo6 { //~ ERROR trait `foo6` should have a camel case name such as `Foo6` fn dummy(&self) { } } fn f<ty>(_: ty) {} //~ ERROR type parameter `ty` should have a camel case name such as `Ty` #[repr(C)] struct
{ bar: isize, } struct X86_64; struct X86__64; //~ ERROR type `X86__64` should have a camel case name such as `X86_64` struct Abc_123; //~ ERROR type `Abc_123` should have a camel case name such as `Abc123` struct A1_b2_c3; //~ ERROR type `A1_b2_c3` should have a camel case name such as `A1B2C3` fn main() { }
foo7
identifier_name
zlib.rs
//! An Implementation of RFC 1950 //! //! Decoding of zlib compressed streams. //! //! # Related Links //! *http://tools.ietf.org/html/rfc1950 - ZLIB Compressed Data Format Specification use std::old_io; use std::old_io::IoResult; use super::hash::Adler32; use super::deflate::Inflater; enum ZlibState { Start, CompressedData, End } /// A Zlib compressed stream decoder. pub struct ZlibDecoder<R> { inflate: Inflater<R>, adler: Adler32, state: ZlibState, } impl<R: Reader> ZlibDecoder<R> { /// Create a new decoder that decodes from a Reader pub fn new(r: R) -> ZlibDecoder<R> { ZlibDecoder { inflate: Inflater::new(r), adler: Adler32::new(), state: ZlibState::Start, } } /// Return a mutable reference to the wrapped Reader pub fn inner(&mut self) -> &mut R { self.inflate.inner() } fn read_header(&mut self) -> IoResult<()> { let cmf = try!(self.inner().read_u8()); let _cm = cmf & 0x0F; let _cinfo = cmf >> 4; let flg = try!(self.inner().read_u8()); let fdict = (flg & 0b100000)!= 0; if fdict { let _dictid = try!(self.inner().read_be_u32()); panic!("invalid png: zlib detected fdict true") } assert!((cmf as u16 * 256 + flg as u16) % 31 == 0); Ok(()) } fn read_checksum(&mut self) -> IoResult<()> { let stream_adler32 = try!(self.inner().read_be_u32()); let adler32 = self.adler.checksum(); assert!(adler32 == stream_adler32); self.adler.reset(); Ok(()) } } impl<R: Reader> Reader for ZlibDecoder<R> { fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { match self.state { ZlibState::CompressedData => { match self.inflate.read(buf) { Ok(n) => { self.adler.update(&buf[..n]); if self.inflate.eof() { let _ = try!(self.read_checksum()); self.state = ZlibState::End; } Ok(n) } e => e } } ZlibState::Start =>
ZlibState::End => Err(old_io::standard_error(old_io::EndOfFile)) } } }
{ let _ = try!(self.read_header()); self.state = ZlibState::CompressedData; self.read(buf) }
conditional_block