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
moves.rs
only the outermost expression that is needed. The borrow checker and trans, for example, only care about the outermost expressions that are moved. It is more efficient therefore just to store those entries. Sometimes though we want to know the variables that are moved (in particular in the borrow checker). For these cases, the set `moved_variables_set` just collects the ids of variables that are moved. Finally, the `capture_map` maps from the node_id of a closure expression to an array of `CaptureVar` structs detailing which variables are captured and how (by ref, by copy, by move). ## Enforcement of Moves The enforcement of moves is done by the borrow checker. Please see the section "Moves and initialization" in `middle/borrowck/doc.rs`. ## Distributive property Copies are "distributive" over parenthesization, but blocks are considered rvalues. What this means is that, for example, neither `a.clone()` nor `(a).clone()` will move `a` (presuming that `a` has a linear type and `clone()` takes its self by reference), but `{a}.clone()` will move `a`, as would `(if cond {a} else {b}).clone()` and so on. */ use middle::pat_util::{pat_bindings}; use middle::freevars; use middle::ty; use middle::typeck::{method_map}; use util::ppaux; use util::ppaux::Repr; use util::common::indenter; use std::at_vec; use std::hashmap::{HashSet, HashMap}; use syntax::ast::*; use syntax::ast_util; use syntax::visit; use syntax::visit::vt; use syntax::codemap::span; #[deriving(Encodable, Decodable)] pub enum CaptureMode { CapCopy, // Copy the value into the closure. CapMove, // Move the value into the closure. CapRef, // Reference directly from parent stack frame (used by `&fn()`). } #[deriving(Encodable, Decodable)] pub struct CaptureVar { def: def, // Variable being accessed free span: span, // Location of an access to this variable mode: CaptureMode // How variable is being accessed } pub type CaptureMap = @mut HashMap<node_id, @[CaptureVar]>; pub type MovesMap = @mut HashSet<node_id>; /** * Set of variable node-ids that are moved. * * Note: The `VariableMovesMap` stores expression ids that * are moves, whereas this set stores the ids of the variables * that are moved at some point */ pub type MovedVariablesSet = @mut HashSet<node_id>; /** See the section Output on the module comment for explanation. */ pub struct MoveMaps { moves_map: MovesMap, moved_variables_set: MovedVariablesSet, capture_map: CaptureMap } struct VisitContext { tcx: ty::ctxt, method_map: method_map, move_maps: MoveMaps } #[deriving(Eq)] enum UseMode { Move, // This value or something owned by it is moved. Read // Read no matter what the type. } pub fn compute_moves(tcx: ty::ctxt, method_map: method_map, crate: &crate) -> MoveMaps { let visitor = visit::mk_vt(@visit::Visitor { visit_fn: compute_modes_for_fn, visit_expr: compute_modes_for_expr, visit_local: compute_modes_for_local, .. *visit::default_visitor() }); let visit_cx = VisitContext { tcx: tcx, method_map: method_map, move_maps: MoveMaps { moves_map: @mut HashSet::new(), capture_map: @mut HashMap::new(), moved_variables_set: @mut HashSet::new() } }; visit::visit_crate(crate, (visit_cx, visitor)); return visit_cx.move_maps; } pub fn moved_variable_node_id_from_def(def: def) -> Option<node_id> { match def { def_binding(nid, _) | def_arg(nid, _) | def_local(nid, _) | def_self(nid, _) => Some(nid), _ => None } } /////////////////////////////////////////////////////////////////////////// // Expressions fn compute_modes_for_local<'a>(local: @local, (cx, v): (VisitContext, vt<VisitContext>)) { cx.use_pat(local.node.pat); for local.node.init.iter().advance |&init| { cx.use_expr(init, Read, v); } } fn compute_modes_for_fn(fk: &visit::fn_kind, decl: &fn_decl, body: &blk, span: span, id: node_id, (cx, v): (VisitContext, vt<VisitContext>)) { for decl.inputs.iter().advance |a| { cx.use_pat(a.pat); } visit::visit_fn(fk, decl, body, span, id, (cx, v)); } fn compute_modes_for_expr(expr: @expr, (cx, v): (VisitContext, vt<VisitContext>)) { cx.consume_expr(expr, v); } impl VisitContext { pub fn consume_exprs(&self, exprs: &[@expr], visitor: vt<VisitContext>) { for exprs.iter().advance |expr| { self.consume_expr(*expr, visitor); } } pub fn consume_expr(&self, expr: @expr, visitor: vt<VisitContext>) { /*! * Indicates that the value of `expr` will be consumed, * meaning either copied or moved depending on its type. */ debug!("consume_expr(expr=%s)", expr.repr(self.tcx)); let expr_ty = ty::expr_ty_adjusted(self.tcx, expr); if ty::type_moves_by_default(self.tcx, expr_ty) { self.move_maps.moves_map.insert(expr.id); self.use_expr(expr, Move, visitor); } else { self.use_expr(expr, Read, visitor); }; } pub fn consume_block(&self, blk: &blk, visitor: vt<VisitContext>) { /*! * Indicates that the value of `blk` will be consumed, * meaning either copied or moved depending on its type. */ debug!("consume_block(blk.id=%?)", blk.id); for blk.stmts.iter().advance |stmt| { (visitor.visit_stmt)(*stmt, (*self, visitor)); } for blk.expr.iter().advance |tail_expr| { self.consume_expr(*tail_expr, visitor); } } pub fn
(&self, expr: @expr, expr_mode: UseMode, visitor: vt<VisitContext>) { /*! * Indicates that `expr` is used with a given mode. This will * in turn trigger calls to the subcomponents of `expr`. */ debug!("use_expr(expr=%s, mode=%?)", expr.repr(self.tcx), expr_mode); // `expr_mode` refers to the post-adjustment value. If one of // those adjustments is to take a reference, then it's only // reading the underlying expression, not moving it. let comp_mode = match self.tcx.adjustments.find(&expr.id) { Some(&@ty::AutoDerefRef( ty::AutoDerefRef { autoref: Some(_), _})) => Read, _ => expr_mode }; debug!("comp_mode = %?", comp_mode); match expr.node { expr_path(*) | expr_self => { match comp_mode { Move => { let def = self.tcx.def_map.get_copy(&expr.id); let r = moved_variable_node_id_from_def(def); for r.iter().advance |&id| { self.move_maps.moved_variables_set.insert(id); } } Read => {} } } expr_unary(_, deref, base) => { // *base if!self.use_overloaded_operator( expr, base, [], visitor) { // Moving out of *base moves out of base. self.use_expr(base, comp_mode, visitor); } } expr_field(base, _, _) => { // base.f // Moving out of base.f moves out of base. self.use_expr(base, comp_mode, visitor); } expr_index(_, lhs, rhs) => { // lhs[rhs] if!self.use_overloaded_operator( expr, lhs, [rhs], visitor) { self.use_expr(lhs, comp_mode, visitor); self.consume_expr(rhs, visitor); } } expr_call(callee, ref args, _) => { // callee(args) // Figure out whether the called function is consumed. let mode = match ty::get(ty::expr_ty(self.tcx, callee)).sty { ty::ty_closure(ref cty) => { match cty.onceness { Once => Move, Many => Read, } }, ty::ty_bare_fn(*) => Read, ref x => self.tcx.sess.span_bug(callee.span, fmt!("non-function type in moves for expr_call: %?", x)), }; // Note we're not using consume_expr, which uses type_moves_by_default // to determine the mode, for this. The reason is that while stack // closures should be noncopyable, they shouldn't move by default; // calling a closure should only consume it if it's once. if mode == Move { self.move_maps.moves_map.insert(callee.id); } self.use_expr(callee, mode, visitor); self.use_fn_args(callee.id, *args, visitor); } expr_method_call(callee_id, rcvr, _, _, ref args, _) => { // callee.m(args) // Implicit self is equivalent to & mode, but every // other kind should be + mode. self.use_receiver(rcvr, visitor); self.use_fn_args(callee_id, *args, visitor); } expr_struct(_, ref fields, opt_with) => { for fields.iter().advance |field| { self.consume_expr(field.node.expr, visitor); } for opt_with.iter().advance |with_expr| { // If there are any fields whose type is move-by-default, // then `with` is consumed, otherwise it is only read let with_ty = ty::expr_ty(self.tcx, *with_expr); let with_fields = match ty::get(with_ty).sty { ty::ty_struct(did, ref substs) => { ty::struct_fields(self.tcx, did, substs) } ref r => { self.tcx.sess.span_bug( with_expr.span, fmt!("bad base expr type in record: %?", r)) } }; // The `with` expr must be consumed if it contains // any fields which (1) were not explicitly // specified and (2) have a type that // moves-by-default: let consume_with = with_fields.iter().any(|tf| { !fields.iter().any(|f| f.node.ident == tf.ident) && ty::type_moves_by_default(self.tcx, tf.mt.ty) }); if consume_with { self.consume_expr(*with_expr, visitor); } else { self.use_expr(*with_expr, Read, visitor); } } } expr_tup(ref exprs) => { self.consume_exprs(*exprs, visitor); } expr_if(cond_expr, ref then_blk, opt_else_expr) => { self.consume_expr(cond_expr, visitor); self.consume_block(then_blk, visitor); for opt_else_expr.iter().advance |else_expr| { self.consume_expr(*else_expr, visitor); } } expr_match(discr, ref arms) => { // We must do this first so that `arms_have_by_move_bindings` // below knows which bindings are moves. for arms.iter().advance |arm| { self.consume_arm(arm, visitor); } // The discriminant may, in fact, be partially moved // if there are by-move bindings, but borrowck deals // with that itself. self.use_expr(discr, Read, visitor); } expr_copy(base) => { self.use_expr(base, Read, visitor); } expr_paren(base) => { // Note: base is not considered a *component* here, so // use `expr_mode` not `comp_mode`. self.use_expr(base, expr_mode, visitor); } expr_vec(ref exprs, _) => { self.consume_exprs(*exprs, visitor); } expr_addr_of(_, base) => { // &base self.use_expr(base, Read, visitor); } expr_inline_asm(*) | expr_break(*) | expr_again(*) | expr_lit(*) => {} expr_loop(ref blk, _) => { self.consume_block(blk, visitor); } expr_log(a_expr, b_expr) => { self.consume_expr(a_expr, visitor); self.use_expr(b_expr, Read, visitor); } expr_while(cond_expr, ref blk) => { self.consume_expr(cond_expr, visitor); self.consume_block(blk, visitor); } expr_unary(_, _, lhs) => { if!self.use_overloaded_operator( expr, lhs, [], visitor) { self.consume_expr(lhs, visitor); } } expr_binary(_, _, lhs, rhs) => { if!self.use_overloaded_operator( expr, lhs, [rhs], visitor) { self.consume_expr(lhs, visitor); self.consume_expr(rhs, visitor); } } expr_block(ref blk) => { self.consume_block(blk, visitor); } expr_ret(ref opt_expr) => { for opt_expr.iter().advance |expr| { self.consume_expr(*expr, visitor); } } expr_assign(lhs, rhs) => { self.use_expr(lhs, Read, visitor); self.consume_expr(rhs, visitor); } expr_cast(base, _) => { self.consume_expr(base, visitor); } expr_assign_op(_, _, lhs, rhs) => { // FIXME(#4712) --- Overloaded operators? // // if!self.use_overloaded_operator( // expr, DoDerefArgs, lhs, [rhs], visitor) // { self.consume_expr(lhs, visitor); self.consume_expr(rhs, visitor); // } } expr_repeat(base, count, _) => { self.consume_expr(base, visitor); self.consume_expr(count, visitor); } expr_loop_body(base) | expr_do_body(base) => { self.use_expr(base, comp_mode, visitor); } expr_fn_block(ref decl, ref body) => { for decl.inputs.iter().advance |a| { self.use_pat(a.pat); } let cap_vars = self.compute_captures(expr.id); self.move_maps.capture_map.insert(expr.id, cap_vars); self.consume_block(body, visitor); } expr_vstore(base, _) => { self.use_expr(base, comp_mode, visitor); } expr_mac(*) => { self.tcx.sess.span_bug(
use_expr
identifier_name
moves.rs
's only the outermost expression that is needed. The borrow checker and trans, for example, only care about the outermost expressions that are moved. It is more efficient therefore just to store those entries. Sometimes though we want to know the variables that are moved (in particular in the borrow checker). For these cases, the set `moved_variables_set` just collects the ids of variables that are moved. Finally, the `capture_map` maps from the node_id of a closure expression to an array of `CaptureVar` structs detailing which variables are captured and how (by ref, by copy, by move). ## Enforcement of Moves The enforcement of moves is done by the borrow checker. Please see the section "Moves and initialization" in `middle/borrowck/doc.rs`. ## Distributive property Copies are "distributive" over parenthesization, but blocks are considered rvalues. What this means is that, for example, neither `a.clone()` nor `(a).clone()` will move `a` (presuming that `a` has a linear type and `clone()` takes its self by reference), but `{a}.clone()` will move `a`, as would `(if cond {a} else {b}).clone()` and so on. */ use middle::pat_util::{pat_bindings}; use middle::freevars; use middle::ty; use middle::typeck::{method_map}; use util::ppaux; use util::ppaux::Repr; use util::common::indenter; use std::at_vec; use std::hashmap::{HashSet, HashMap}; use syntax::ast::*; use syntax::ast_util; use syntax::visit; use syntax::visit::vt; use syntax::codemap::span; #[deriving(Encodable, Decodable)] pub enum CaptureMode { CapCopy, // Copy the value into the closure. CapMove, // Move the value into the closure. CapRef, // Reference directly from parent stack frame (used by `&fn()`). } #[deriving(Encodable, Decodable)] pub struct CaptureVar { def: def, // Variable being accessed free span: span, // Location of an access to this variable mode: CaptureMode // How variable is being accessed } pub type CaptureMap = @mut HashMap<node_id, @[CaptureVar]>; pub type MovesMap = @mut HashSet<node_id>; /** * Set of variable node-ids that are moved. * * Note: The `VariableMovesMap` stores expression ids that * are moves, whereas this set stores the ids of the variables * that are moved at some point */ pub type MovedVariablesSet = @mut HashSet<node_id>; /** See the section Output on the module comment for explanation. */ pub struct MoveMaps { moves_map: MovesMap, moved_variables_set: MovedVariablesSet, capture_map: CaptureMap } struct VisitContext { tcx: ty::ctxt, method_map: method_map, move_maps: MoveMaps } #[deriving(Eq)] enum UseMode { Move, // This value or something owned by it is moved. Read // Read no matter what the type. } pub fn compute_moves(tcx: ty::ctxt, method_map: method_map, crate: &crate) -> MoveMaps { let visitor = visit::mk_vt(@visit::Visitor { visit_fn: compute_modes_for_fn, visit_expr: compute_modes_for_expr, visit_local: compute_modes_for_local, .. *visit::default_visitor() }); let visit_cx = VisitContext { tcx: tcx, method_map: method_map, move_maps: MoveMaps { moves_map: @mut HashSet::new(), capture_map: @mut HashMap::new(), moved_variables_set: @mut HashSet::new() } }; visit::visit_crate(crate, (visit_cx, visitor)); return visit_cx.move_maps; } pub fn moved_variable_node_id_from_def(def: def) -> Option<node_id> { match def { def_binding(nid, _) | def_arg(nid, _) | def_local(nid, _) | def_self(nid, _) => Some(nid), _ => None } } /////////////////////////////////////////////////////////////////////////// // Expressions fn compute_modes_for_local<'a>(local: @local, (cx, v): (VisitContext, vt<VisitContext>)) { cx.use_pat(local.node.pat); for local.node.init.iter().advance |&init| { cx.use_expr(init, Read, v); } } fn compute_modes_for_fn(fk: &visit::fn_kind, decl: &fn_decl, body: &blk, span: span, id: node_id, (cx, v): (VisitContext, vt<VisitContext>)) { for decl.inputs.iter().advance |a| { cx.use_pat(a.pat); } visit::visit_fn(fk, decl, body, span, id, (cx, v)); } fn compute_modes_for_expr(expr: @expr, (cx, v): (VisitContext, vt<VisitContext>)) { cx.consume_expr(expr, v); } impl VisitContext { pub fn consume_exprs(&self, exprs: &[@expr], visitor: vt<VisitContext>) { for exprs.iter().advance |expr| { self.consume_expr(*expr, visitor); } } pub fn consume_expr(&self, expr: @expr, visitor: vt<VisitContext>) { /*! * Indicates that the value of `expr` will be consumed, * meaning either copied or moved depending on its type. */ debug!("consume_expr(expr=%s)", expr.repr(self.tcx)); let expr_ty = ty::expr_ty_adjusted(self.tcx, expr); if ty::type_moves_by_default(self.tcx, expr_ty) { self.move_maps.moves_map.insert(expr.id); self.use_expr(expr, Move, visitor); } else { self.use_expr(expr, Read, visitor); }; } pub fn consume_block(&self, blk: &blk, visitor: vt<VisitContext>) { /*! * Indicates that the value of `blk` will be consumed, * meaning either copied or moved depending on its type. */ debug!("consume_block(blk.id=%?)", blk.id); for blk.stmts.iter().advance |stmt| { (visitor.visit_stmt)(*stmt, (*self, visitor)); } for blk.expr.iter().advance |tail_expr| { self.consume_expr(*tail_expr, visitor); } } pub fn use_expr(&self, expr: @expr, expr_mode: UseMode, visitor: vt<VisitContext>) { /*! * Indicates that `expr` is used with a given mode. This will * in turn trigger calls to the subcomponents of `expr`. */ debug!("use_expr(expr=%s, mode=%?)", expr.repr(self.tcx), expr_mode); // `expr_mode` refers to the post-adjustment value. If one of // those adjustments is to take a reference, then it's only // reading the underlying expression, not moving it. let comp_mode = match self.tcx.adjustments.find(&expr.id) { Some(&@ty::AutoDerefRef( ty::AutoDerefRef { autoref: Some(_), _})) => Read, _ => expr_mode }; debug!("comp_mode = %?", comp_mode); match expr.node { expr_path(*) | expr_self => { match comp_mode { Move => { let def = self.tcx.def_map.get_copy(&expr.id); let r = moved_variable_node_id_from_def(def); for r.iter().advance |&id| { self.move_maps.moved_variables_set.insert(id); } } Read => {} } } expr_unary(_, deref, base) => { // *base if!self.use_overloaded_operator( expr, base, [], visitor) { // Moving out of *base moves out of base. self.use_expr(base, comp_mode, visitor); } } expr_field(base, _, _) => { // base.f // Moving out of base.f moves out of base. self.use_expr(base, comp_mode, visitor); } expr_index(_, lhs, rhs) => { // lhs[rhs] if!self.use_overloaded_operator( expr, lhs, [rhs], visitor) { self.use_expr(lhs, comp_mode, visitor); self.consume_expr(rhs, visitor); } } expr_call(callee, ref args, _) => { // callee(args) // Figure out whether the called function is consumed. let mode = match ty::get(ty::expr_ty(self.tcx, callee)).sty { ty::ty_closure(ref cty) => { match cty.onceness { Once => Move, Many => Read, } }, ty::ty_bare_fn(*) => Read, ref x => self.tcx.sess.span_bug(callee.span, fmt!("non-function type in moves for expr_call: %?", x)), }; // Note we're not using consume_expr, which uses type_moves_by_default // to determine the mode, for this. The reason is that while stack // closures should be noncopyable, they shouldn't move by default; // calling a closure should only consume it if it's once. if mode == Move { self.move_maps.moves_map.insert(callee.id); } self.use_expr(callee, mode, visitor); self.use_fn_args(callee.id, *args, visitor); } expr_method_call(callee_id, rcvr, _, _, ref args, _) => { // callee.m(args) // Implicit self is equivalent to & mode, but every // other kind should be + mode. self.use_receiver(rcvr, visitor); self.use_fn_args(callee_id, *args, visitor); } expr_struct(_, ref fields, opt_with) => { for fields.iter().advance |field| { self.consume_expr(field.node.expr, visitor); } for opt_with.iter().advance |with_expr| { // If there are any fields whose type is move-by-default, // then `with` is consumed, otherwise it is only read let with_ty = ty::expr_ty(self.tcx, *with_expr); let with_fields = match ty::get(with_ty).sty { ty::ty_struct(did, ref substs) => { ty::struct_fields(self.tcx, did, substs) } ref r => { self.tcx.sess.span_bug( with_expr.span, fmt!("bad base expr type in record: %?", r)) } }; // The `with` expr must be consumed if it contains // any fields which (1) were not explicitly // specified and (2) have a type that // moves-by-default: let consume_with = with_fields.iter().any(|tf| { !fields.iter().any(|f| f.node.ident == tf.ident) && ty::type_moves_by_default(self.tcx, tf.mt.ty) }); if consume_with { self.consume_expr(*with_expr, visitor); } else { self.use_expr(*with_expr, Read, visitor); } } } expr_tup(ref exprs) => { self.consume_exprs(*exprs, visitor); } expr_if(cond_expr, ref then_blk, opt_else_expr) => { self.consume_expr(cond_expr, visitor); self.consume_block(then_blk, visitor); for opt_else_expr.iter().advance |else_expr| { self.consume_expr(*else_expr, visitor); } }
// We must do this first so that `arms_have_by_move_bindings` // below knows which bindings are moves. for arms.iter().advance |arm| { self.consume_arm(arm, visitor); } // The discriminant may, in fact, be partially moved // if there are by-move bindings, but borrowck deals // with that itself. self.use_expr(discr, Read, visitor); } expr_copy(base) => { self.use_expr(base, Read, visitor); } expr_paren(base) => { // Note: base is not considered a *component* here, so // use `expr_mode` not `comp_mode`. self.use_expr(base, expr_mode, visitor); } expr_vec(ref exprs, _) => { self.consume_exprs(*exprs, visitor); } expr_addr_of(_, base) => { // &base self.use_expr(base, Read, visitor); } expr_inline_asm(*) | expr_break(*) | expr_again(*) | expr_lit(*) => {} expr_loop(ref blk, _) => { self.consume_block(blk, visitor); } expr_log(a_expr, b_expr) => { self.consume_expr(a_expr, visitor); self.use_expr(b_expr, Read, visitor); } expr_while(cond_expr, ref blk) => { self.consume_expr(cond_expr, visitor); self.consume_block(blk, visitor); } expr_unary(_, _, lhs) => { if!self.use_overloaded_operator( expr, lhs, [], visitor) { self.consume_expr(lhs, visitor); } } expr_binary(_, _, lhs, rhs) => { if!self.use_overloaded_operator( expr, lhs, [rhs], visitor) { self.consume_expr(lhs, visitor); self.consume_expr(rhs, visitor); } } expr_block(ref blk) => { self.consume_block(blk, visitor); } expr_ret(ref opt_expr) => { for opt_expr.iter().advance |expr| { self.consume_expr(*expr, visitor); } } expr_assign(lhs, rhs) => { self.use_expr(lhs, Read, visitor); self.consume_expr(rhs, visitor); } expr_cast(base, _) => { self.consume_expr(base, visitor); } expr_assign_op(_, _, lhs, rhs) => { // FIXME(#4712) --- Overloaded operators? // // if!self.use_overloaded_operator( // expr, DoDerefArgs, lhs, [rhs], visitor) // { self.consume_expr(lhs, visitor); self.consume_expr(rhs, visitor); // } } expr_repeat(base, count, _) => { self.consume_expr(base, visitor); self.consume_expr(count, visitor); } expr_loop_body(base) | expr_do_body(base) => { self.use_expr(base, comp_mode, visitor); } expr_fn_block(ref decl, ref body) => { for decl.inputs.iter().advance |a| { self.use_pat(a.pat); } let cap_vars = self.compute_captures(expr.id); self.move_maps.capture_map.insert(expr.id, cap_vars); self.consume_block(body, visitor); } expr_vstore(base, _) => { self.use_expr(base, comp_mode, visitor); } expr_mac(*) => { self.tcx.sess.span_bug(
expr_match(discr, ref arms) => {
random_line_split
moves.rs
span: span, id: node_id, (cx, v): (VisitContext, vt<VisitContext>)) { for decl.inputs.iter().advance |a| { cx.use_pat(a.pat); } visit::visit_fn(fk, decl, body, span, id, (cx, v)); } fn compute_modes_for_expr(expr: @expr, (cx, v): (VisitContext, vt<VisitContext>)) { cx.consume_expr(expr, v); } impl VisitContext { pub fn consume_exprs(&self, exprs: &[@expr], visitor: vt<VisitContext>) { for exprs.iter().advance |expr| { self.consume_expr(*expr, visitor); } } pub fn consume_expr(&self, expr: @expr, visitor: vt<VisitContext>) { /*! * Indicates that the value of `expr` will be consumed, * meaning either copied or moved depending on its type. */ debug!("consume_expr(expr=%s)", expr.repr(self.tcx)); let expr_ty = ty::expr_ty_adjusted(self.tcx, expr); if ty::type_moves_by_default(self.tcx, expr_ty) { self.move_maps.moves_map.insert(expr.id); self.use_expr(expr, Move, visitor); } else { self.use_expr(expr, Read, visitor); }; } pub fn consume_block(&self, blk: &blk, visitor: vt<VisitContext>) { /*! * Indicates that the value of `blk` will be consumed, * meaning either copied or moved depending on its type. */ debug!("consume_block(blk.id=%?)", blk.id); for blk.stmts.iter().advance |stmt| { (visitor.visit_stmt)(*stmt, (*self, visitor)); } for blk.expr.iter().advance |tail_expr| { self.consume_expr(*tail_expr, visitor); } } pub fn use_expr(&self, expr: @expr, expr_mode: UseMode, visitor: vt<VisitContext>) { /*! * Indicates that `expr` is used with a given mode. This will * in turn trigger calls to the subcomponents of `expr`. */ debug!("use_expr(expr=%s, mode=%?)", expr.repr(self.tcx), expr_mode); // `expr_mode` refers to the post-adjustment value. If one of // those adjustments is to take a reference, then it's only // reading the underlying expression, not moving it. let comp_mode = match self.tcx.adjustments.find(&expr.id) { Some(&@ty::AutoDerefRef( ty::AutoDerefRef { autoref: Some(_), _})) => Read, _ => expr_mode }; debug!("comp_mode = %?", comp_mode); match expr.node { expr_path(*) | expr_self => { match comp_mode { Move => { let def = self.tcx.def_map.get_copy(&expr.id); let r = moved_variable_node_id_from_def(def); for r.iter().advance |&id| { self.move_maps.moved_variables_set.insert(id); } } Read => {} } } expr_unary(_, deref, base) => { // *base if!self.use_overloaded_operator( expr, base, [], visitor) { // Moving out of *base moves out of base. self.use_expr(base, comp_mode, visitor); } } expr_field(base, _, _) => { // base.f // Moving out of base.f moves out of base. self.use_expr(base, comp_mode, visitor); } expr_index(_, lhs, rhs) => { // lhs[rhs] if!self.use_overloaded_operator( expr, lhs, [rhs], visitor) { self.use_expr(lhs, comp_mode, visitor); self.consume_expr(rhs, visitor); } } expr_call(callee, ref args, _) => { // callee(args) // Figure out whether the called function is consumed. let mode = match ty::get(ty::expr_ty(self.tcx, callee)).sty { ty::ty_closure(ref cty) => { match cty.onceness { Once => Move, Many => Read, } }, ty::ty_bare_fn(*) => Read, ref x => self.tcx.sess.span_bug(callee.span, fmt!("non-function type in moves for expr_call: %?", x)), }; // Note we're not using consume_expr, which uses type_moves_by_default // to determine the mode, for this. The reason is that while stack // closures should be noncopyable, they shouldn't move by default; // calling a closure should only consume it if it's once. if mode == Move { self.move_maps.moves_map.insert(callee.id); } self.use_expr(callee, mode, visitor); self.use_fn_args(callee.id, *args, visitor); } expr_method_call(callee_id, rcvr, _, _, ref args, _) => { // callee.m(args) // Implicit self is equivalent to & mode, but every // other kind should be + mode. self.use_receiver(rcvr, visitor); self.use_fn_args(callee_id, *args, visitor); } expr_struct(_, ref fields, opt_with) => { for fields.iter().advance |field| { self.consume_expr(field.node.expr, visitor); } for opt_with.iter().advance |with_expr| { // If there are any fields whose type is move-by-default, // then `with` is consumed, otherwise it is only read let with_ty = ty::expr_ty(self.tcx, *with_expr); let with_fields = match ty::get(with_ty).sty { ty::ty_struct(did, ref substs) => { ty::struct_fields(self.tcx, did, substs) } ref r => { self.tcx.sess.span_bug( with_expr.span, fmt!("bad base expr type in record: %?", r)) } }; // The `with` expr must be consumed if it contains // any fields which (1) were not explicitly // specified and (2) have a type that // moves-by-default: let consume_with = with_fields.iter().any(|tf| { !fields.iter().any(|f| f.node.ident == tf.ident) && ty::type_moves_by_default(self.tcx, tf.mt.ty) }); if consume_with { self.consume_expr(*with_expr, visitor); } else { self.use_expr(*with_expr, Read, visitor); } } } expr_tup(ref exprs) => { self.consume_exprs(*exprs, visitor); } expr_if(cond_expr, ref then_blk, opt_else_expr) => { self.consume_expr(cond_expr, visitor); self.consume_block(then_blk, visitor); for opt_else_expr.iter().advance |else_expr| { self.consume_expr(*else_expr, visitor); } } expr_match(discr, ref arms) => { // We must do this first so that `arms_have_by_move_bindings` // below knows which bindings are moves. for arms.iter().advance |arm| { self.consume_arm(arm, visitor); } // The discriminant may, in fact, be partially moved // if there are by-move bindings, but borrowck deals // with that itself. self.use_expr(discr, Read, visitor); } expr_copy(base) => { self.use_expr(base, Read, visitor); } expr_paren(base) => { // Note: base is not considered a *component* here, so // use `expr_mode` not `comp_mode`. self.use_expr(base, expr_mode, visitor); } expr_vec(ref exprs, _) => { self.consume_exprs(*exprs, visitor); } expr_addr_of(_, base) => { // &base self.use_expr(base, Read, visitor); } expr_inline_asm(*) | expr_break(*) | expr_again(*) | expr_lit(*) => {} expr_loop(ref blk, _) => { self.consume_block(blk, visitor); } expr_log(a_expr, b_expr) => { self.consume_expr(a_expr, visitor); self.use_expr(b_expr, Read, visitor); } expr_while(cond_expr, ref blk) => { self.consume_expr(cond_expr, visitor); self.consume_block(blk, visitor); } expr_unary(_, _, lhs) => { if!self.use_overloaded_operator( expr, lhs, [], visitor) { self.consume_expr(lhs, visitor); } } expr_binary(_, _, lhs, rhs) => { if!self.use_overloaded_operator( expr, lhs, [rhs], visitor) { self.consume_expr(lhs, visitor); self.consume_expr(rhs, visitor); } } expr_block(ref blk) => { self.consume_block(blk, visitor); } expr_ret(ref opt_expr) => { for opt_expr.iter().advance |expr| { self.consume_expr(*expr, visitor); } } expr_assign(lhs, rhs) => { self.use_expr(lhs, Read, visitor); self.consume_expr(rhs, visitor); } expr_cast(base, _) => { self.consume_expr(base, visitor); } expr_assign_op(_, _, lhs, rhs) => { // FIXME(#4712) --- Overloaded operators? // // if!self.use_overloaded_operator( // expr, DoDerefArgs, lhs, [rhs], visitor) // { self.consume_expr(lhs, visitor); self.consume_expr(rhs, visitor); // } } expr_repeat(base, count, _) => { self.consume_expr(base, visitor); self.consume_expr(count, visitor); } expr_loop_body(base) | expr_do_body(base) => { self.use_expr(base, comp_mode, visitor); } expr_fn_block(ref decl, ref body) => { for decl.inputs.iter().advance |a| { self.use_pat(a.pat); } let cap_vars = self.compute_captures(expr.id); self.move_maps.capture_map.insert(expr.id, cap_vars); self.consume_block(body, visitor); } expr_vstore(base, _) => { self.use_expr(base, comp_mode, visitor); } expr_mac(*) => { self.tcx.sess.span_bug( expr.span, "macro expression remains after expansion"); } } } pub fn use_overloaded_operator(&self, expr: &expr, receiver_expr: @expr, arg_exprs: &[@expr], visitor: vt<VisitContext>) -> bool { if!self.method_map.contains_key(&expr.id) { return false; } self.use_receiver(receiver_expr, visitor); // for overloaded operatrs, we are always passing in a // borrowed pointer, so it's always read mode: for arg_exprs.iter().advance |arg_expr| { self.use_expr(*arg_expr, Read, visitor); } return true; } pub fn consume_arm(&self, arm: &arm, visitor: vt<VisitContext>) { for arm.pats.iter().advance |pat| { self.use_pat(*pat); } for arm.guard.iter().advance |guard| { self.consume_expr(*guard, visitor); } self.consume_block(&arm.body, visitor); } pub fn use_pat(&self, pat: @pat) { /*! * * Decides whether each binding in a pattern moves the value * into itself or not based on its type and annotation. */ do pat_bindings(self.tcx.def_map, pat) |bm, id, _span, path| { let binding_moves = match bm { bind_by_ref(_) => false, bind_infer => { let pat_ty = ty::node_id_to_type(self.tcx, id); debug!("pattern %? %s type is %s", id, ast_util::path_to_ident(path).repr(self.tcx), pat_ty.repr(self.tcx)); ty::type_moves_by_default(self.tcx, pat_ty) } }; debug!("pattern binding %?: bm=%?, binding_moves=%b", id, bm, binding_moves); if binding_moves { self.move_maps.moves_map.insert(id); } } } pub fn use_receiver(&self, receiver_expr: @expr, visitor: vt<VisitContext>) { self.use_fn_arg(receiver_expr, visitor); } pub fn use_fn_args(&self, _: node_id, arg_exprs: &[@expr], visitor: vt<VisitContext>) { //! Uses the argument expressions. for arg_exprs.iter().advance |arg_expr| { self.use_fn_arg(*arg_expr, visitor); } } pub fn use_fn_arg(&self, arg_expr: @expr, visitor: vt<VisitContext>)
{ //! Uses the argument. self.consume_expr(arg_expr, visitor) }
identifier_body
mod.rs
// Copyright (C) 2019 Ruben Gonzalez <[email protected]> // // 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 glib::prelude::*; mod imp; glib::glib_wrapper! { pub struct ClaxonDec(ObjectSubclass<imp::ClaxonDec>) @extends gst_audio::AudioDecoder, gst::Element, gst::Object; } unsafe impl Send for ClaxonDec {} unsafe impl Sync for ClaxonDec {} pub fn register(plugin: &gst::Plugin) -> Result<(), glib::BoolError>
{ gst::Element::register( Some(plugin), "claxondec", gst::Rank::Marginal, ClaxonDec::static_type(), ) }
identifier_body
mod.rs
// Copyright (C) 2019 Ruben Gonzalez <[email protected]> // // 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 glib::prelude::*; mod imp; glib::glib_wrapper! { pub struct ClaxonDec(ObjectSubclass<imp::ClaxonDec>) @extends gst_audio::AudioDecoder, gst::Element, gst::Object; } unsafe impl Send for ClaxonDec {} unsafe impl Sync for ClaxonDec {} pub fn register(plugin: &gst::Plugin) -> Result<(), glib::BoolError> { gst::Element::register( Some(plugin), "claxondec", gst::Rank::Marginal, ClaxonDec::static_type(), )
}
random_line_split
mod.rs
// Copyright (C) 2019 Ruben Gonzalez <[email protected]> // // 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 glib::prelude::*; mod imp; glib::glib_wrapper! { pub struct ClaxonDec(ObjectSubclass<imp::ClaxonDec>) @extends gst_audio::AudioDecoder, gst::Element, gst::Object; } unsafe impl Send for ClaxonDec {} unsafe impl Sync for ClaxonDec {} pub fn
(plugin: &gst::Plugin) -> Result<(), glib::BoolError> { gst::Element::register( Some(plugin), "claxondec", gst::Rank::Marginal, ClaxonDec::static_type(), ) }
register
identifier_name
synonym.rs
use std::collections::HashMap; use std::collections::hash_map::{Entries, Keys}; use std::fmt::Show; use std::hash::Hash; use std::mem; #[deriving(Clone)] pub struct SynonymMap<K, V> { vals: HashMap<K, V>, syns: HashMap<K, K>, } impl<K: Eq + Hash, V> SynonymMap<K, V> { pub fn new() -> SynonymMap<K, V> { SynonymMap { vals: HashMap::new(), syns: HashMap::new(), } } pub fn insert_synonym(&mut self, from: K, to: K) -> bool { assert!(self.vals.contains_key(&to)); self.syns.insert(from, to) } pub fn
<'a>(&'a self) -> Keys<'a, K, V> { self.vals.keys() } pub fn iter<'a>(&'a self) -> Entries<'a, K, V> { self.vals.iter() } pub fn synonyms<'a>(&'a self) -> Entries<'a, K, K> { self.syns.iter() } pub fn find<'a>(&'a self, k: &K) -> Option<&'a V> { self.with_key(k, |k| self.vals.find(k)) } pub fn contains_key(&self, k: &K) -> bool { self.with_key(k, |k| self.vals.contains_key(k)) } pub fn len(&self) -> uint { self.vals.len() } fn with_key<T>(&self, k: &K, with: |&K| -> T) -> T { if self.syns.contains_key(k) { with(&self.syns[*k]) } else { with(k) } } } impl<K: Eq + Hash + Clone, V> SynonymMap<K, V> { pub fn resolve(&self, k: &K) -> K { self.with_key(k, |k| k.clone()) } pub fn get<'a>(&'a self, k: &K) -> &'a V { self.find(k).unwrap() } pub fn find_mut<'a>(&'a mut self, k: &K) -> Option<&'a mut V> { if self.syns.contains_key(k) { self.vals.find_mut(&self.syns[*k]) } else { self.vals.find_mut(k) } } pub fn swap(&mut self, k: K, mut new: V) -> Option<V> { if self.syns.contains_key(&k) { let old = self.vals.find_mut(&k).unwrap(); mem::swap(old, &mut new); Some(new) } else { self.vals.swap(k, new) } } pub fn insert(&mut self, k: K, v: V) -> bool { self.swap(k, v).is_none() } } impl<K: Eq + Hash + Clone, V> FromIterator<(K, V)> for SynonymMap<K, V> { fn from_iter<T: Iterator<(K, V)>>(mut iter: T) -> SynonymMap<K, V> { let mut map = SynonymMap::new(); for (k, v) in iter { map.insert(k, v); } map } } impl<K: Eq + Hash + Show, V: Show> Show for SynonymMap<K, V> { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { try!(self.vals.fmt(f)); write!(f, " (synomyns: {})", self.syns.to_string()) } }
keys
identifier_name
synonym.rs
use std::collections::HashMap; use std::collections::hash_map::{Entries, Keys}; use std::fmt::Show; use std::hash::Hash; use std::mem; #[deriving(Clone)] pub struct SynonymMap<K, V> { vals: HashMap<K, V>, syns: HashMap<K, K>, } impl<K: Eq + Hash, V> SynonymMap<K, V> { pub fn new() -> SynonymMap<K, V> { SynonymMap { vals: HashMap::new(), syns: HashMap::new(), } } pub fn insert_synonym(&mut self, from: K, to: K) -> bool { assert!(self.vals.contains_key(&to)); self.syns.insert(from, to) } pub fn keys<'a>(&'a self) -> Keys<'a, K, V> { self.vals.keys() } pub fn iter<'a>(&'a self) -> Entries<'a, K, V> { self.vals.iter() } pub fn synonyms<'a>(&'a self) -> Entries<'a, K, K> { self.syns.iter() } pub fn find<'a>(&'a self, k: &K) -> Option<&'a V> { self.with_key(k, |k| self.vals.find(k)) } pub fn contains_key(&self, k: &K) -> bool { self.with_key(k, |k| self.vals.contains_key(k)) } pub fn len(&self) -> uint { self.vals.len() } fn with_key<T>(&self, k: &K, with: |&K| -> T) -> T { if self.syns.contains_key(k) { with(&self.syns[*k]) } else { with(k) } } } impl<K: Eq + Hash + Clone, V> SynonymMap<K, V> { pub fn resolve(&self, k: &K) -> K { self.with_key(k, |k| k.clone()) } pub fn get<'a>(&'a self, k: &K) -> &'a V { self.find(k).unwrap() }
if self.syns.contains_key(k) { self.vals.find_mut(&self.syns[*k]) } else { self.vals.find_mut(k) } } pub fn swap(&mut self, k: K, mut new: V) -> Option<V> { if self.syns.contains_key(&k) { let old = self.vals.find_mut(&k).unwrap(); mem::swap(old, &mut new); Some(new) } else { self.vals.swap(k, new) } } pub fn insert(&mut self, k: K, v: V) -> bool { self.swap(k, v).is_none() } } impl<K: Eq + Hash + Clone, V> FromIterator<(K, V)> for SynonymMap<K, V> { fn from_iter<T: Iterator<(K, V)>>(mut iter: T) -> SynonymMap<K, V> { let mut map = SynonymMap::new(); for (k, v) in iter { map.insert(k, v); } map } } impl<K: Eq + Hash + Show, V: Show> Show for SynonymMap<K, V> { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { try!(self.vals.fmt(f)); write!(f, " (synomyns: {})", self.syns.to_string()) } }
pub fn find_mut<'a>(&'a mut self, k: &K) -> Option<&'a mut V> {
random_line_split
synonym.rs
use std::collections::HashMap; use std::collections::hash_map::{Entries, Keys}; use std::fmt::Show; use std::hash::Hash; use std::mem; #[deriving(Clone)] pub struct SynonymMap<K, V> { vals: HashMap<K, V>, syns: HashMap<K, K>, } impl<K: Eq + Hash, V> SynonymMap<K, V> { pub fn new() -> SynonymMap<K, V> { SynonymMap { vals: HashMap::new(), syns: HashMap::new(), } } pub fn insert_synonym(&mut self, from: K, to: K) -> bool { assert!(self.vals.contains_key(&to)); self.syns.insert(from, to) } pub fn keys<'a>(&'a self) -> Keys<'a, K, V> { self.vals.keys() } pub fn iter<'a>(&'a self) -> Entries<'a, K, V> { self.vals.iter() } pub fn synonyms<'a>(&'a self) -> Entries<'a, K, K> { self.syns.iter() } pub fn find<'a>(&'a self, k: &K) -> Option<&'a V> { self.with_key(k, |k| self.vals.find(k)) } pub fn contains_key(&self, k: &K) -> bool { self.with_key(k, |k| self.vals.contains_key(k)) } pub fn len(&self) -> uint { self.vals.len() } fn with_key<T>(&self, k: &K, with: |&K| -> T) -> T { if self.syns.contains_key(k) { with(&self.syns[*k]) } else { with(k) } } } impl<K: Eq + Hash + Clone, V> SynonymMap<K, V> { pub fn resolve(&self, k: &K) -> K { self.with_key(k, |k| k.clone()) } pub fn get<'a>(&'a self, k: &K) -> &'a V { self.find(k).unwrap() } pub fn find_mut<'a>(&'a mut self, k: &K) -> Option<&'a mut V> { if self.syns.contains_key(k)
else { self.vals.find_mut(k) } } pub fn swap(&mut self, k: K, mut new: V) -> Option<V> { if self.syns.contains_key(&k) { let old = self.vals.find_mut(&k).unwrap(); mem::swap(old, &mut new); Some(new) } else { self.vals.swap(k, new) } } pub fn insert(&mut self, k: K, v: V) -> bool { self.swap(k, v).is_none() } } impl<K: Eq + Hash + Clone, V> FromIterator<(K, V)> for SynonymMap<K, V> { fn from_iter<T: Iterator<(K, V)>>(mut iter: T) -> SynonymMap<K, V> { let mut map = SynonymMap::new(); for (k, v) in iter { map.insert(k, v); } map } } impl<K: Eq + Hash + Show, V: Show> Show for SynonymMap<K, V> { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { try!(self.vals.fmt(f)); write!(f, " (synomyns: {})", self.syns.to_string()) } }
{ self.vals.find_mut(&self.syns[*k]) }
conditional_block
synonym.rs
use std::collections::HashMap; use std::collections::hash_map::{Entries, Keys}; use std::fmt::Show; use std::hash::Hash; use std::mem; #[deriving(Clone)] pub struct SynonymMap<K, V> { vals: HashMap<K, V>, syns: HashMap<K, K>, } impl<K: Eq + Hash, V> SynonymMap<K, V> { pub fn new() -> SynonymMap<K, V> { SynonymMap { vals: HashMap::new(), syns: HashMap::new(), } } pub fn insert_synonym(&mut self, from: K, to: K) -> bool { assert!(self.vals.contains_key(&to)); self.syns.insert(from, to) } pub fn keys<'a>(&'a self) -> Keys<'a, K, V> { self.vals.keys() } pub fn iter<'a>(&'a self) -> Entries<'a, K, V> { self.vals.iter() } pub fn synonyms<'a>(&'a self) -> Entries<'a, K, K> { self.syns.iter() } pub fn find<'a>(&'a self, k: &K) -> Option<&'a V> { self.with_key(k, |k| self.vals.find(k)) } pub fn contains_key(&self, k: &K) -> bool { self.with_key(k, |k| self.vals.contains_key(k)) } pub fn len(&self) -> uint { self.vals.len() } fn with_key<T>(&self, k: &K, with: |&K| -> T) -> T { if self.syns.contains_key(k) { with(&self.syns[*k]) } else { with(k) } } } impl<K: Eq + Hash + Clone, V> SynonymMap<K, V> { pub fn resolve(&self, k: &K) -> K { self.with_key(k, |k| k.clone()) } pub fn get<'a>(&'a self, k: &K) -> &'a V { self.find(k).unwrap() } pub fn find_mut<'a>(&'a mut self, k: &K) -> Option<&'a mut V> { if self.syns.contains_key(k) { self.vals.find_mut(&self.syns[*k]) } else { self.vals.find_mut(k) } } pub fn swap(&mut self, k: K, mut new: V) -> Option<V> { if self.syns.contains_key(&k) { let old = self.vals.find_mut(&k).unwrap(); mem::swap(old, &mut new); Some(new) } else { self.vals.swap(k, new) } } pub fn insert(&mut self, k: K, v: V) -> bool { self.swap(k, v).is_none() } } impl<K: Eq + Hash + Clone, V> FromIterator<(K, V)> for SynonymMap<K, V> { fn from_iter<T: Iterator<(K, V)>>(mut iter: T) -> SynonymMap<K, V> { let mut map = SynonymMap::new(); for (k, v) in iter { map.insert(k, v); } map } } impl<K: Eq + Hash + Show, V: Show> Show for SynonymMap<K, V> { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result
}
{ try!(self.vals.fmt(f)); write!(f, " (synomyns: {})", self.syns.to_string()) }
identifier_body
link.rs
// Copyright 2014 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #[cfg(target_os="windows")] #[link(name = "opengl32")] #[link(name = "gdi32")] extern {}
#[cfg(feature = "glfw-sys")] #[link(name = "glfw3", kind = "static")] extern {} #[cfg(not(feature = "glfw-sys"))] // leaving off `kind = static` allows for the specification of a dynamic library if desired #[link(name = "glfw3")] extern {} #[cfg(target_os="linux")] #[link(name = "X11")] #[link(name = "GL")] #[link(name = "Xxf86vm")] #[link(name = "Xrandr")] #[link(name = "Xi")] extern {} #[cfg(target_os="macos")] #[link(name = "Cocoa", kind = "framework")] #[link(name = "OpenGL", kind = "framework")] #[link(name = "IOKit", kind = "framework")] #[link(name = "CoreFoundation", kind = "framework")] #[link(name = "QuartzCore", kind = "framework")] extern {}
random_line_split
mod.rs
use std::collections::HashSet; use conllx::Token; use failure::{format_err, Error}; mod dependency; pub use self::dependency::{Dependency, DependencySet};
mod parser_state; pub use self::parser_state::ParserState; mod trans_system; pub use self::trans_system::{AttachmentAddr, Transition, TransitionLookup, TransitionSystem}; pub fn sentence_to_dependencies(sentence: &[Token]) -> Result<DependencySet, Error> { let mut dependencies = HashSet::new(); for (idx, token) in sentence.iter().enumerate() { let head = token .head() .ok_or_else(|| format_err!("Token {} has no head", idx))?; let head_rel = token .head_rel() .ok_or_else(|| format_err!("Token {} has no head relation", idx))?; dependencies.insert(Dependency { head, relation: head_rel.to_owned(), dependent: idx + 1, }); } Ok(dependencies) }
random_line_split
mod.rs
use std::collections::HashSet; use conllx::Token; use failure::{format_err, Error}; mod dependency; pub use self::dependency::{Dependency, DependencySet}; mod parser_state; pub use self::parser_state::ParserState; mod trans_system; pub use self::trans_system::{AttachmentAddr, Transition, TransitionLookup, TransitionSystem}; pub fn sentence_to_dependencies(sentence: &[Token]) -> Result<DependencySet, Error>
{ let mut dependencies = HashSet::new(); for (idx, token) in sentence.iter().enumerate() { let head = token .head() .ok_or_else(|| format_err!("Token {} has no head", idx))?; let head_rel = token .head_rel() .ok_or_else(|| format_err!("Token {} has no head relation", idx))?; dependencies.insert(Dependency { head, relation: head_rel.to_owned(), dependent: idx + 1, }); } Ok(dependencies) }
identifier_body
mod.rs
use std::collections::HashSet; use conllx::Token; use failure::{format_err, Error}; mod dependency; pub use self::dependency::{Dependency, DependencySet}; mod parser_state; pub use self::parser_state::ParserState; mod trans_system; pub use self::trans_system::{AttachmentAddr, Transition, TransitionLookup, TransitionSystem}; pub fn
(sentence: &[Token]) -> Result<DependencySet, Error> { let mut dependencies = HashSet::new(); for (idx, token) in sentence.iter().enumerate() { let head = token .head() .ok_or_else(|| format_err!("Token {} has no head", idx))?; let head_rel = token .head_rel() .ok_or_else(|| format_err!("Token {} has no head relation", idx))?; dependencies.insert(Dependency { head, relation: head_rel.to_owned(), dependent: idx + 1, }); } Ok(dependencies) }
sentence_to_dependencies
identifier_name
htmlcanvaselement.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 base64; use canvas_traits::canvas::{CanvasMsg, FromScriptMsg}; use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasRenderingContext2DMethods; use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding; use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding::HTMLCanvasElementMethods; use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLContextAttributes; use dom::bindings::codegen::UnionTypes::CanvasRenderingContext2DOrWebGLRenderingContext; use dom::bindings::conversions::ConversionResult; use dom::bindings::error::{Error, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, LayoutJS, Root}; use dom::bindings::num::Finite; use dom::bindings::str::DOMString; use dom::canvasrenderingcontext2d::{CanvasRenderingContext2D, LayoutCanvasRenderingContext2DHelpers}; use dom::document::Document; use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers}; use dom::globalscope::GlobalScope; use dom::htmlelement::HTMLElement; use dom::node::{Node, window_from_node}; use dom::virtualmethods::VirtualMethods; use dom::webglrenderingcontext::{LayoutCanvasWebGLRenderingContextHelpers, WebGLRenderingContext}; use dom_struct::dom_struct; use euclid::Size2D; use html5ever::{LocalName, Prefix}; use image::ColorType; use image::png::PNGEncoder; use ipc_channel::ipc; use js::error::throw_type_error; use js::jsapi::{HandleValue, JSContext}; use offscreen_gl_context::GLContextAttributes; use script_layout_interface::{HTMLCanvasData, HTMLCanvasDataSource}; use std::iter::repeat; use style::attr::{AttrValue, LengthOrPercentageOrAuto}; const DEFAULT_WIDTH: u32 = 300; const DEFAULT_HEIGHT: u32 = 150; #[must_root] #[derive(Clone, HeapSizeOf, JSTraceable)] pub enum CanvasContext { Context2d(JS<CanvasRenderingContext2D>), WebGL(JS<WebGLRenderingContext>), } #[dom_struct] pub struct HTMLCanvasElement { htmlelement: HTMLElement, context: DOMRefCell<Option<CanvasContext>>, } impl HTMLCanvasElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLCanvasElement { HTMLCanvasElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), context: DOMRefCell::new(None), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> Root<HTMLCanvasElement> { Node::reflect_node(box HTMLCanvasElement::new_inherited(local_name, prefix, document), document, HTMLCanvasElementBinding::Wrap) } fn recreate_contexts(&self) { let size = self.get_size(); if let Some(ref context) = *self.context.borrow() { match *context { CanvasContext::Context2d(ref context) => context.set_bitmap_dimensions(size), CanvasContext::WebGL(ref context) => context.recreate(size), } } } pub fn get_size(&self) -> Size2D<i32> { Size2D::new(self.Width() as i32, self.Height() as i32) } pub fn origin_is_clean(&self) -> bool { match *self.context.borrow() { Some(CanvasContext::Context2d(ref context)) => context.origin_is_clean(), _ => true, } } } pub trait LayoutHTMLCanvasElementHelpers { fn data(&self) -> HTMLCanvasData; fn get_width(&self) -> LengthOrPercentageOrAuto; fn get_height(&self) -> LengthOrPercentageOrAuto; } impl LayoutHTMLCanvasElementHelpers for LayoutJS<HTMLCanvasElement> { #[allow(unsafe_code)] fn data(&self) -> HTMLCanvasData { unsafe { let canvas = &*self.unsafe_get(); let source = match canvas.context.borrow_for_layout().as_ref() { Some(&CanvasContext::Context2d(ref context)) => { HTMLCanvasDataSource::Image(Some(context.to_layout().get_ipc_renderer())) }, Some(&CanvasContext::WebGL(ref context)) => { context.to_layout().canvas_data_source() }, None => { HTMLCanvasDataSource::Image(None) } }; let width_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("width")); let height_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("height")); HTMLCanvasData { source: source, width: width_attr.map_or(DEFAULT_WIDTH, |val| val.as_uint()), height: height_attr.map_or(DEFAULT_HEIGHT, |val| val.as_uint()), } } } #[allow(unsafe_code)] fn get_width(&self) -> LengthOrPercentageOrAuto { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("width")) .map(AttrValue::as_uint_px_dimension) .unwrap_or(LengthOrPercentageOrAuto::Auto) } } #[allow(unsafe_code)] fn get_height(&self) -> LengthOrPercentageOrAuto { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("height")) .map(AttrValue::as_uint_px_dimension) .unwrap_or(LengthOrPercentageOrAuto::Auto) } } } impl HTMLCanvasElement { pub fn get_or_init_2d_context(&self) -> Option<Root<CanvasRenderingContext2D>>
#[allow(unsafe_code)] pub fn get_or_init_webgl_context(&self, cx: *mut JSContext, attrs: Option<HandleValue>) -> Option<Root<WebGLRenderingContext>> { if self.context.borrow().is_none() { let window = window_from_node(self); let size = self.get_size(); let attrs = if let Some(webgl_attributes) = attrs { match unsafe { WebGLContextAttributes::new(cx, webgl_attributes) } { Ok(ConversionResult::Success(ref attrs)) => From::from(attrs), Ok(ConversionResult::Failure(ref error)) => { unsafe { throw_type_error(cx, &error); } return None; } _ => { debug!("Unexpected error on conversion of WebGLContextAttributes"); return None; } } } else { GLContextAttributes::default() }; let maybe_ctx = WebGLRenderingContext::new(&window, self, size, attrs); *self.context.borrow_mut() = maybe_ctx.map( |ctx| CanvasContext::WebGL(JS::from_ref(&*ctx))); } if let Some(CanvasContext::WebGL(ref context)) = *self.context.borrow() { Some(Root::from_ref(&*context)) } else { None } } pub fn is_valid(&self) -> bool { self.Height()!= 0 && self.Width()!= 0 } pub fn fetch_all_data(&self) -> Option<(Vec<u8>, Size2D<i32>)> { let size = self.get_size(); if size.width == 0 || size.height == 0 { return None } let data = match self.context.borrow().as_ref() { Some(&CanvasContext::Context2d(ref context)) => { let (sender, receiver) = ipc::channel().unwrap(); let msg = CanvasMsg::FromScript(FromScriptMsg::SendPixels(sender)); context.get_ipc_renderer().send(msg).unwrap(); match receiver.recv().unwrap() { Some(pixels) => pixels, None => { return None; } } }, Some(&CanvasContext::WebGL(_)) => { // TODO: add a method in WebGLRenderingContext to get the pixels. return None; }, None => { repeat(0xffu8).take((size.height as usize) * (size.width as usize) * 4).collect() } }; Some((data, size)) } } impl HTMLCanvasElementMethods for HTMLCanvasElement { // https://html.spec.whatwg.org/multipage/#dom-canvas-width make_uint_getter!(Width, "width", DEFAULT_WIDTH); // https://html.spec.whatwg.org/multipage/#dom-canvas-width make_uint_setter!(SetWidth, "width", DEFAULT_WIDTH); // https://html.spec.whatwg.org/multipage/#dom-canvas-height make_uint_getter!(Height, "height", DEFAULT_HEIGHT); // https://html.spec.whatwg.org/multipage/#dom-canvas-height make_uint_setter!(SetHeight, "height", DEFAULT_HEIGHT); #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext unsafe fn GetContext(&self, cx: *mut JSContext, id: DOMString, attributes: Vec<HandleValue>) -> Option<CanvasRenderingContext2DOrWebGLRenderingContext> { match &*id { "2d" => { self.get_or_init_2d_context() .map(CanvasRenderingContext2DOrWebGLRenderingContext::CanvasRenderingContext2D) } "webgl" | "experimental-webgl" => { self.get_or_init_webgl_context(cx, attributes.get(0).cloned()) .map(CanvasRenderingContext2DOrWebGLRenderingContext::WebGLRenderingContext) } _ => None } } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-canvas-todataurl unsafe fn ToDataURL(&self, _context: *mut JSContext, _mime_type: Option<DOMString>, _arguments: Vec<HandleValue>) -> Fallible<DOMString> { // Step 1. if let Some(CanvasContext::Context2d(ref context)) = *self.context.borrow() { if!context.origin_is_clean() { return Err(Error::Security); } } // Step 2. if self.Width() == 0 || self.Height() == 0 { return Ok(DOMString::from("data:,")); } // Step 3. let raw_data = match *self.context.borrow() { Some(CanvasContext::Context2d(ref context)) => { let image_data = context.GetImageData(Finite::wrap(0f64), Finite::wrap(0f64), Finite::wrap(self.Width() as f64), Finite::wrap(self.Height() as f64))?; image_data.get_data_array() } None => { // Each pixel is fully-transparent black. vec![0; (self.Width() * self.Height() * 4) as usize] } _ => return Err(Error::NotSupported) // WebGL }; // Only handle image/png for now. let mime_type = "image/png"; let mut encoded = Vec::new(); { let encoder: PNGEncoder<&mut Vec<u8>> = PNGEncoder::new(&mut encoded); encoder.encode(&raw_data, self.Width(), self.Height(), ColorType::RGBA(8)).unwrap(); } let encoded = base64::encode(&encoded); Ok(DOMString::from(format!("data:{};base64,{}", mime_type, encoded))) } } impl VirtualMethods for HTMLCanvasElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { &local_name!("width") | &local_name!("height") => self.recreate_contexts(), _ => (), }; } fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH), &local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } } impl<'a> From<&'a WebGLContextAttributes> for GLContextAttributes { fn from(attrs: &'a WebGLContextAttributes) -> GLContextAttributes { GLContextAttributes { alpha: attrs.alpha, depth: attrs.depth, stencil: attrs.stencil, antialias: attrs.antialias, premultiplied_alpha: attrs.premultipliedAlpha, preserve_drawing_buffer: attrs.preserveDrawingBuffer, } } } pub mod utils { use dom::window::Window; use net_traits::image_cache::{ImageResponse, UsePlaceholder, ImageOrMetadataAvailable}; use net_traits::image_cache::CanRequestImages; use servo_url::ServoUrl; pub fn request_image_from_cache(window: &Window, url: ServoUrl) -> ImageResponse { let image_cache = window.image_cache(); let response = image_cache.find_image_or_metadata(url.into(), UsePlaceholder::No, CanRequestImages::No); match response { Ok(ImageOrMetadataAvailable::ImageAvailable(image, url)) => ImageResponse::Loaded(image, url), _ => ImageResponse::None, } } }
{ if self.context.borrow().is_none() { let window = window_from_node(self); let size = self.get_size(); let context = CanvasRenderingContext2D::new(window.upcast::<GlobalScope>(), self, size); *self.context.borrow_mut() = Some(CanvasContext::Context2d(JS::from_ref(&*context))); } match *self.context.borrow().as_ref().unwrap() { CanvasContext::Context2d(ref context) => Some(Root::from_ref(&*context)), _ => None, } }
identifier_body
htmlcanvaselement.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 base64; use canvas_traits::canvas::{CanvasMsg, FromScriptMsg}; use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasRenderingContext2DMethods; use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding; use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding::HTMLCanvasElementMethods; use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLContextAttributes; use dom::bindings::codegen::UnionTypes::CanvasRenderingContext2DOrWebGLRenderingContext; use dom::bindings::conversions::ConversionResult; use dom::bindings::error::{Error, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, LayoutJS, Root}; use dom::bindings::num::Finite; use dom::bindings::str::DOMString; use dom::canvasrenderingcontext2d::{CanvasRenderingContext2D, LayoutCanvasRenderingContext2DHelpers}; use dom::document::Document; use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers}; use dom::globalscope::GlobalScope; use dom::htmlelement::HTMLElement; use dom::node::{Node, window_from_node}; use dom::virtualmethods::VirtualMethods; use dom::webglrenderingcontext::{LayoutCanvasWebGLRenderingContextHelpers, WebGLRenderingContext}; use dom_struct::dom_struct; use euclid::Size2D; use html5ever::{LocalName, Prefix}; use image::ColorType; use image::png::PNGEncoder; use ipc_channel::ipc; use js::error::throw_type_error; use js::jsapi::{HandleValue, JSContext}; use offscreen_gl_context::GLContextAttributes; use script_layout_interface::{HTMLCanvasData, HTMLCanvasDataSource}; use std::iter::repeat; use style::attr::{AttrValue, LengthOrPercentageOrAuto}; const DEFAULT_WIDTH: u32 = 300; const DEFAULT_HEIGHT: u32 = 150; #[must_root] #[derive(Clone, HeapSizeOf, JSTraceable)] pub enum CanvasContext { Context2d(JS<CanvasRenderingContext2D>), WebGL(JS<WebGLRenderingContext>), } #[dom_struct] pub struct HTMLCanvasElement { htmlelement: HTMLElement, context: DOMRefCell<Option<CanvasContext>>, } impl HTMLCanvasElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLCanvasElement { HTMLCanvasElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), context: DOMRefCell::new(None), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> Root<HTMLCanvasElement> { Node::reflect_node(box HTMLCanvasElement::new_inherited(local_name, prefix, document), document, HTMLCanvasElementBinding::Wrap) } fn recreate_contexts(&self) { let size = self.get_size(); if let Some(ref context) = *self.context.borrow() { match *context { CanvasContext::Context2d(ref context) => context.set_bitmap_dimensions(size), CanvasContext::WebGL(ref context) => context.recreate(size), } } } pub fn get_size(&self) -> Size2D<i32> { Size2D::new(self.Width() as i32, self.Height() as i32) } pub fn origin_is_clean(&self) -> bool { match *self.context.borrow() { Some(CanvasContext::Context2d(ref context)) => context.origin_is_clean(), _ => true, } } } pub trait LayoutHTMLCanvasElementHelpers { fn data(&self) -> HTMLCanvasData; fn get_width(&self) -> LengthOrPercentageOrAuto; fn get_height(&self) -> LengthOrPercentageOrAuto; } impl LayoutHTMLCanvasElementHelpers for LayoutJS<HTMLCanvasElement> { #[allow(unsafe_code)] fn data(&self) -> HTMLCanvasData { unsafe { let canvas = &*self.unsafe_get(); let source = match canvas.context.borrow_for_layout().as_ref() { Some(&CanvasContext::Context2d(ref context)) => { HTMLCanvasDataSource::Image(Some(context.to_layout().get_ipc_renderer())) }, Some(&CanvasContext::WebGL(ref context)) => { context.to_layout().canvas_data_source() }, None => { HTMLCanvasDataSource::Image(None) } }; let width_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("width")); let height_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("height")); HTMLCanvasData { source: source, width: width_attr.map_or(DEFAULT_WIDTH, |val| val.as_uint()), height: height_attr.map_or(DEFAULT_HEIGHT, |val| val.as_uint()), } } } #[allow(unsafe_code)] fn get_width(&self) -> LengthOrPercentageOrAuto { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("width")) .map(AttrValue::as_uint_px_dimension) .unwrap_or(LengthOrPercentageOrAuto::Auto) } } #[allow(unsafe_code)] fn get_height(&self) -> LengthOrPercentageOrAuto { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("height")) .map(AttrValue::as_uint_px_dimension) .unwrap_or(LengthOrPercentageOrAuto::Auto) } } } impl HTMLCanvasElement { pub fn get_or_init_2d_context(&self) -> Option<Root<CanvasRenderingContext2D>> { if self.context.borrow().is_none() { let window = window_from_node(self); let size = self.get_size(); let context = CanvasRenderingContext2D::new(window.upcast::<GlobalScope>(), self, size); *self.context.borrow_mut() = Some(CanvasContext::Context2d(JS::from_ref(&*context))); } match *self.context.borrow().as_ref().unwrap() { CanvasContext::Context2d(ref context) => Some(Root::from_ref(&*context)), _ => None, } } #[allow(unsafe_code)] pub fn get_or_init_webgl_context(&self, cx: *mut JSContext, attrs: Option<HandleValue>) -> Option<Root<WebGLRenderingContext>> { if self.context.borrow().is_none() { let window = window_from_node(self); let size = self.get_size(); let attrs = if let Some(webgl_attributes) = attrs { match unsafe { WebGLContextAttributes::new(cx, webgl_attributes) } { Ok(ConversionResult::Success(ref attrs)) => From::from(attrs), Ok(ConversionResult::Failure(ref error)) => { unsafe { throw_type_error(cx, &error); } return None; } _ => { debug!("Unexpected error on conversion of WebGLContextAttributes"); return None; } } } else { GLContextAttributes::default() }; let maybe_ctx = WebGLRenderingContext::new(&window, self, size, attrs); *self.context.borrow_mut() = maybe_ctx.map( |ctx| CanvasContext::WebGL(JS::from_ref(&*ctx))); } if let Some(CanvasContext::WebGL(ref context)) = *self.context.borrow() { Some(Root::from_ref(&*context)) } else { None } } pub fn is_valid(&self) -> bool { self.Height()!= 0 && self.Width()!= 0 } pub fn fetch_all_data(&self) -> Option<(Vec<u8>, Size2D<i32>)> { let size = self.get_size(); if size.width == 0 || size.height == 0 { return None } let data = match self.context.borrow().as_ref() { Some(&CanvasContext::Context2d(ref context)) => { let (sender, receiver) = ipc::channel().unwrap(); let msg = CanvasMsg::FromScript(FromScriptMsg::SendPixels(sender)); context.get_ipc_renderer().send(msg).unwrap(); match receiver.recv().unwrap() { Some(pixels) => pixels, None => { return None; } } }, Some(&CanvasContext::WebGL(_)) => { // TODO: add a method in WebGLRenderingContext to get the pixels. return None; }, None => { repeat(0xffu8).take((size.height as usize) * (size.width as usize) * 4).collect() } }; Some((data, size)) } } impl HTMLCanvasElementMethods for HTMLCanvasElement { // https://html.spec.whatwg.org/multipage/#dom-canvas-width make_uint_getter!(Width, "width", DEFAULT_WIDTH); // https://html.spec.whatwg.org/multipage/#dom-canvas-width make_uint_setter!(SetWidth, "width", DEFAULT_WIDTH); // https://html.spec.whatwg.org/multipage/#dom-canvas-height make_uint_getter!(Height, "height", DEFAULT_HEIGHT); // https://html.spec.whatwg.org/multipage/#dom-canvas-height make_uint_setter!(SetHeight, "height", DEFAULT_HEIGHT); #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext unsafe fn GetContext(&self, cx: *mut JSContext, id: DOMString, attributes: Vec<HandleValue>) -> Option<CanvasRenderingContext2DOrWebGLRenderingContext> { match &*id { "2d" => { self.get_or_init_2d_context() .map(CanvasRenderingContext2DOrWebGLRenderingContext::CanvasRenderingContext2D) } "webgl" | "experimental-webgl" => { self.get_or_init_webgl_context(cx, attributes.get(0).cloned()) .map(CanvasRenderingContext2DOrWebGLRenderingContext::WebGLRenderingContext) } _ => None
} } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-canvas-todataurl unsafe fn ToDataURL(&self, _context: *mut JSContext, _mime_type: Option<DOMString>, _arguments: Vec<HandleValue>) -> Fallible<DOMString> { // Step 1. if let Some(CanvasContext::Context2d(ref context)) = *self.context.borrow() { if!context.origin_is_clean() { return Err(Error::Security); } } // Step 2. if self.Width() == 0 || self.Height() == 0 { return Ok(DOMString::from("data:,")); } // Step 3. let raw_data = match *self.context.borrow() { Some(CanvasContext::Context2d(ref context)) => { let image_data = context.GetImageData(Finite::wrap(0f64), Finite::wrap(0f64), Finite::wrap(self.Width() as f64), Finite::wrap(self.Height() as f64))?; image_data.get_data_array() } None => { // Each pixel is fully-transparent black. vec![0; (self.Width() * self.Height() * 4) as usize] } _ => return Err(Error::NotSupported) // WebGL }; // Only handle image/png for now. let mime_type = "image/png"; let mut encoded = Vec::new(); { let encoder: PNGEncoder<&mut Vec<u8>> = PNGEncoder::new(&mut encoded); encoder.encode(&raw_data, self.Width(), self.Height(), ColorType::RGBA(8)).unwrap(); } let encoded = base64::encode(&encoded); Ok(DOMString::from(format!("data:{};base64,{}", mime_type, encoded))) } } impl VirtualMethods for HTMLCanvasElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { &local_name!("width") | &local_name!("height") => self.recreate_contexts(), _ => (), }; } fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH), &local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } } impl<'a> From<&'a WebGLContextAttributes> for GLContextAttributes { fn from(attrs: &'a WebGLContextAttributes) -> GLContextAttributes { GLContextAttributes { alpha: attrs.alpha, depth: attrs.depth, stencil: attrs.stencil, antialias: attrs.antialias, premultiplied_alpha: attrs.premultipliedAlpha, preserve_drawing_buffer: attrs.preserveDrawingBuffer, } } } pub mod utils { use dom::window::Window; use net_traits::image_cache::{ImageResponse, UsePlaceholder, ImageOrMetadataAvailable}; use net_traits::image_cache::CanRequestImages; use servo_url::ServoUrl; pub fn request_image_from_cache(window: &Window, url: ServoUrl) -> ImageResponse { let image_cache = window.image_cache(); let response = image_cache.find_image_or_metadata(url.into(), UsePlaceholder::No, CanRequestImages::No); match response { Ok(ImageOrMetadataAvailable::ImageAvailable(image, url)) => ImageResponse::Loaded(image, url), _ => ImageResponse::None, } } }
random_line_split
htmlcanvaselement.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 base64; use canvas_traits::canvas::{CanvasMsg, FromScriptMsg}; use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasRenderingContext2DMethods; use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding; use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding::HTMLCanvasElementMethods; use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLContextAttributes; use dom::bindings::codegen::UnionTypes::CanvasRenderingContext2DOrWebGLRenderingContext; use dom::bindings::conversions::ConversionResult; use dom::bindings::error::{Error, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, LayoutJS, Root}; use dom::bindings::num::Finite; use dom::bindings::str::DOMString; use dom::canvasrenderingcontext2d::{CanvasRenderingContext2D, LayoutCanvasRenderingContext2DHelpers}; use dom::document::Document; use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers}; use dom::globalscope::GlobalScope; use dom::htmlelement::HTMLElement; use dom::node::{Node, window_from_node}; use dom::virtualmethods::VirtualMethods; use dom::webglrenderingcontext::{LayoutCanvasWebGLRenderingContextHelpers, WebGLRenderingContext}; use dom_struct::dom_struct; use euclid::Size2D; use html5ever::{LocalName, Prefix}; use image::ColorType; use image::png::PNGEncoder; use ipc_channel::ipc; use js::error::throw_type_error; use js::jsapi::{HandleValue, JSContext}; use offscreen_gl_context::GLContextAttributes; use script_layout_interface::{HTMLCanvasData, HTMLCanvasDataSource}; use std::iter::repeat; use style::attr::{AttrValue, LengthOrPercentageOrAuto}; const DEFAULT_WIDTH: u32 = 300; const DEFAULT_HEIGHT: u32 = 150; #[must_root] #[derive(Clone, HeapSizeOf, JSTraceable)] pub enum CanvasContext { Context2d(JS<CanvasRenderingContext2D>), WebGL(JS<WebGLRenderingContext>), } #[dom_struct] pub struct HTMLCanvasElement { htmlelement: HTMLElement, context: DOMRefCell<Option<CanvasContext>>, } impl HTMLCanvasElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLCanvasElement { HTMLCanvasElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), context: DOMRefCell::new(None), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> Root<HTMLCanvasElement> { Node::reflect_node(box HTMLCanvasElement::new_inherited(local_name, prefix, document), document, HTMLCanvasElementBinding::Wrap) } fn recreate_contexts(&self) { let size = self.get_size(); if let Some(ref context) = *self.context.borrow()
} pub fn get_size(&self) -> Size2D<i32> { Size2D::new(self.Width() as i32, self.Height() as i32) } pub fn origin_is_clean(&self) -> bool { match *self.context.borrow() { Some(CanvasContext::Context2d(ref context)) => context.origin_is_clean(), _ => true, } } } pub trait LayoutHTMLCanvasElementHelpers { fn data(&self) -> HTMLCanvasData; fn get_width(&self) -> LengthOrPercentageOrAuto; fn get_height(&self) -> LengthOrPercentageOrAuto; } impl LayoutHTMLCanvasElementHelpers for LayoutJS<HTMLCanvasElement> { #[allow(unsafe_code)] fn data(&self) -> HTMLCanvasData { unsafe { let canvas = &*self.unsafe_get(); let source = match canvas.context.borrow_for_layout().as_ref() { Some(&CanvasContext::Context2d(ref context)) => { HTMLCanvasDataSource::Image(Some(context.to_layout().get_ipc_renderer())) }, Some(&CanvasContext::WebGL(ref context)) => { context.to_layout().canvas_data_source() }, None => { HTMLCanvasDataSource::Image(None) } }; let width_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("width")); let height_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("height")); HTMLCanvasData { source: source, width: width_attr.map_or(DEFAULT_WIDTH, |val| val.as_uint()), height: height_attr.map_or(DEFAULT_HEIGHT, |val| val.as_uint()), } } } #[allow(unsafe_code)] fn get_width(&self) -> LengthOrPercentageOrAuto { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("width")) .map(AttrValue::as_uint_px_dimension) .unwrap_or(LengthOrPercentageOrAuto::Auto) } } #[allow(unsafe_code)] fn get_height(&self) -> LengthOrPercentageOrAuto { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("height")) .map(AttrValue::as_uint_px_dimension) .unwrap_or(LengthOrPercentageOrAuto::Auto) } } } impl HTMLCanvasElement { pub fn get_or_init_2d_context(&self) -> Option<Root<CanvasRenderingContext2D>> { if self.context.borrow().is_none() { let window = window_from_node(self); let size = self.get_size(); let context = CanvasRenderingContext2D::new(window.upcast::<GlobalScope>(), self, size); *self.context.borrow_mut() = Some(CanvasContext::Context2d(JS::from_ref(&*context))); } match *self.context.borrow().as_ref().unwrap() { CanvasContext::Context2d(ref context) => Some(Root::from_ref(&*context)), _ => None, } } #[allow(unsafe_code)] pub fn get_or_init_webgl_context(&self, cx: *mut JSContext, attrs: Option<HandleValue>) -> Option<Root<WebGLRenderingContext>> { if self.context.borrow().is_none() { let window = window_from_node(self); let size = self.get_size(); let attrs = if let Some(webgl_attributes) = attrs { match unsafe { WebGLContextAttributes::new(cx, webgl_attributes) } { Ok(ConversionResult::Success(ref attrs)) => From::from(attrs), Ok(ConversionResult::Failure(ref error)) => { unsafe { throw_type_error(cx, &error); } return None; } _ => { debug!("Unexpected error on conversion of WebGLContextAttributes"); return None; } } } else { GLContextAttributes::default() }; let maybe_ctx = WebGLRenderingContext::new(&window, self, size, attrs); *self.context.borrow_mut() = maybe_ctx.map( |ctx| CanvasContext::WebGL(JS::from_ref(&*ctx))); } if let Some(CanvasContext::WebGL(ref context)) = *self.context.borrow() { Some(Root::from_ref(&*context)) } else { None } } pub fn is_valid(&self) -> bool { self.Height()!= 0 && self.Width()!= 0 } pub fn fetch_all_data(&self) -> Option<(Vec<u8>, Size2D<i32>)> { let size = self.get_size(); if size.width == 0 || size.height == 0 { return None } let data = match self.context.borrow().as_ref() { Some(&CanvasContext::Context2d(ref context)) => { let (sender, receiver) = ipc::channel().unwrap(); let msg = CanvasMsg::FromScript(FromScriptMsg::SendPixels(sender)); context.get_ipc_renderer().send(msg).unwrap(); match receiver.recv().unwrap() { Some(pixels) => pixels, None => { return None; } } }, Some(&CanvasContext::WebGL(_)) => { // TODO: add a method in WebGLRenderingContext to get the pixels. return None; }, None => { repeat(0xffu8).take((size.height as usize) * (size.width as usize) * 4).collect() } }; Some((data, size)) } } impl HTMLCanvasElementMethods for HTMLCanvasElement { // https://html.spec.whatwg.org/multipage/#dom-canvas-width make_uint_getter!(Width, "width", DEFAULT_WIDTH); // https://html.spec.whatwg.org/multipage/#dom-canvas-width make_uint_setter!(SetWidth, "width", DEFAULT_WIDTH); // https://html.spec.whatwg.org/multipage/#dom-canvas-height make_uint_getter!(Height, "height", DEFAULT_HEIGHT); // https://html.spec.whatwg.org/multipage/#dom-canvas-height make_uint_setter!(SetHeight, "height", DEFAULT_HEIGHT); #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext unsafe fn GetContext(&self, cx: *mut JSContext, id: DOMString, attributes: Vec<HandleValue>) -> Option<CanvasRenderingContext2DOrWebGLRenderingContext> { match &*id { "2d" => { self.get_or_init_2d_context() .map(CanvasRenderingContext2DOrWebGLRenderingContext::CanvasRenderingContext2D) } "webgl" | "experimental-webgl" => { self.get_or_init_webgl_context(cx, attributes.get(0).cloned()) .map(CanvasRenderingContext2DOrWebGLRenderingContext::WebGLRenderingContext) } _ => None } } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-canvas-todataurl unsafe fn ToDataURL(&self, _context: *mut JSContext, _mime_type: Option<DOMString>, _arguments: Vec<HandleValue>) -> Fallible<DOMString> { // Step 1. if let Some(CanvasContext::Context2d(ref context)) = *self.context.borrow() { if!context.origin_is_clean() { return Err(Error::Security); } } // Step 2. if self.Width() == 0 || self.Height() == 0 { return Ok(DOMString::from("data:,")); } // Step 3. let raw_data = match *self.context.borrow() { Some(CanvasContext::Context2d(ref context)) => { let image_data = context.GetImageData(Finite::wrap(0f64), Finite::wrap(0f64), Finite::wrap(self.Width() as f64), Finite::wrap(self.Height() as f64))?; image_data.get_data_array() } None => { // Each pixel is fully-transparent black. vec![0; (self.Width() * self.Height() * 4) as usize] } _ => return Err(Error::NotSupported) // WebGL }; // Only handle image/png for now. let mime_type = "image/png"; let mut encoded = Vec::new(); { let encoder: PNGEncoder<&mut Vec<u8>> = PNGEncoder::new(&mut encoded); encoder.encode(&raw_data, self.Width(), self.Height(), ColorType::RGBA(8)).unwrap(); } let encoded = base64::encode(&encoded); Ok(DOMString::from(format!("data:{};base64,{}", mime_type, encoded))) } } impl VirtualMethods for HTMLCanvasElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { &local_name!("width") | &local_name!("height") => self.recreate_contexts(), _ => (), }; } fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH), &local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } } impl<'a> From<&'a WebGLContextAttributes> for GLContextAttributes { fn from(attrs: &'a WebGLContextAttributes) -> GLContextAttributes { GLContextAttributes { alpha: attrs.alpha, depth: attrs.depth, stencil: attrs.stencil, antialias: attrs.antialias, premultiplied_alpha: attrs.premultipliedAlpha, preserve_drawing_buffer: attrs.preserveDrawingBuffer, } } } pub mod utils { use dom::window::Window; use net_traits::image_cache::{ImageResponse, UsePlaceholder, ImageOrMetadataAvailable}; use net_traits::image_cache::CanRequestImages; use servo_url::ServoUrl; pub fn request_image_from_cache(window: &Window, url: ServoUrl) -> ImageResponse { let image_cache = window.image_cache(); let response = image_cache.find_image_or_metadata(url.into(), UsePlaceholder::No, CanRequestImages::No); match response { Ok(ImageOrMetadataAvailable::ImageAvailable(image, url)) => ImageResponse::Loaded(image, url), _ => ImageResponse::None, } } }
{ match *context { CanvasContext::Context2d(ref context) => context.set_bitmap_dimensions(size), CanvasContext::WebGL(ref context) => context.recreate(size), } }
conditional_block
htmlcanvaselement.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 base64; use canvas_traits::canvas::{CanvasMsg, FromScriptMsg}; use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasRenderingContext2DMethods; use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding; use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding::HTMLCanvasElementMethods; use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLContextAttributes; use dom::bindings::codegen::UnionTypes::CanvasRenderingContext2DOrWebGLRenderingContext; use dom::bindings::conversions::ConversionResult; use dom::bindings::error::{Error, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, LayoutJS, Root}; use dom::bindings::num::Finite; use dom::bindings::str::DOMString; use dom::canvasrenderingcontext2d::{CanvasRenderingContext2D, LayoutCanvasRenderingContext2DHelpers}; use dom::document::Document; use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers}; use dom::globalscope::GlobalScope; use dom::htmlelement::HTMLElement; use dom::node::{Node, window_from_node}; use dom::virtualmethods::VirtualMethods; use dom::webglrenderingcontext::{LayoutCanvasWebGLRenderingContextHelpers, WebGLRenderingContext}; use dom_struct::dom_struct; use euclid::Size2D; use html5ever::{LocalName, Prefix}; use image::ColorType; use image::png::PNGEncoder; use ipc_channel::ipc; use js::error::throw_type_error; use js::jsapi::{HandleValue, JSContext}; use offscreen_gl_context::GLContextAttributes; use script_layout_interface::{HTMLCanvasData, HTMLCanvasDataSource}; use std::iter::repeat; use style::attr::{AttrValue, LengthOrPercentageOrAuto}; const DEFAULT_WIDTH: u32 = 300; const DEFAULT_HEIGHT: u32 = 150; #[must_root] #[derive(Clone, HeapSizeOf, JSTraceable)] pub enum CanvasContext { Context2d(JS<CanvasRenderingContext2D>), WebGL(JS<WebGLRenderingContext>), } #[dom_struct] pub struct HTMLCanvasElement { htmlelement: HTMLElement, context: DOMRefCell<Option<CanvasContext>>, } impl HTMLCanvasElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLCanvasElement { HTMLCanvasElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), context: DOMRefCell::new(None), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> Root<HTMLCanvasElement> { Node::reflect_node(box HTMLCanvasElement::new_inherited(local_name, prefix, document), document, HTMLCanvasElementBinding::Wrap) } fn recreate_contexts(&self) { let size = self.get_size(); if let Some(ref context) = *self.context.borrow() { match *context { CanvasContext::Context2d(ref context) => context.set_bitmap_dimensions(size), CanvasContext::WebGL(ref context) => context.recreate(size), } } } pub fn get_size(&self) -> Size2D<i32> { Size2D::new(self.Width() as i32, self.Height() as i32) } pub fn origin_is_clean(&self) -> bool { match *self.context.borrow() { Some(CanvasContext::Context2d(ref context)) => context.origin_is_clean(), _ => true, } } } pub trait LayoutHTMLCanvasElementHelpers { fn data(&self) -> HTMLCanvasData; fn get_width(&self) -> LengthOrPercentageOrAuto; fn get_height(&self) -> LengthOrPercentageOrAuto; } impl LayoutHTMLCanvasElementHelpers for LayoutJS<HTMLCanvasElement> { #[allow(unsafe_code)] fn data(&self) -> HTMLCanvasData { unsafe { let canvas = &*self.unsafe_get(); let source = match canvas.context.borrow_for_layout().as_ref() { Some(&CanvasContext::Context2d(ref context)) => { HTMLCanvasDataSource::Image(Some(context.to_layout().get_ipc_renderer())) }, Some(&CanvasContext::WebGL(ref context)) => { context.to_layout().canvas_data_source() }, None => { HTMLCanvasDataSource::Image(None) } }; let width_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("width")); let height_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("height")); HTMLCanvasData { source: source, width: width_attr.map_or(DEFAULT_WIDTH, |val| val.as_uint()), height: height_attr.map_or(DEFAULT_HEIGHT, |val| val.as_uint()), } } } #[allow(unsafe_code)] fn get_width(&self) -> LengthOrPercentageOrAuto { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("width")) .map(AttrValue::as_uint_px_dimension) .unwrap_or(LengthOrPercentageOrAuto::Auto) } } #[allow(unsafe_code)] fn get_height(&self) -> LengthOrPercentageOrAuto { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("height")) .map(AttrValue::as_uint_px_dimension) .unwrap_or(LengthOrPercentageOrAuto::Auto) } } } impl HTMLCanvasElement { pub fn get_or_init_2d_context(&self) -> Option<Root<CanvasRenderingContext2D>> { if self.context.borrow().is_none() { let window = window_from_node(self); let size = self.get_size(); let context = CanvasRenderingContext2D::new(window.upcast::<GlobalScope>(), self, size); *self.context.borrow_mut() = Some(CanvasContext::Context2d(JS::from_ref(&*context))); } match *self.context.borrow().as_ref().unwrap() { CanvasContext::Context2d(ref context) => Some(Root::from_ref(&*context)), _ => None, } } #[allow(unsafe_code)] pub fn get_or_init_webgl_context(&self, cx: *mut JSContext, attrs: Option<HandleValue>) -> Option<Root<WebGLRenderingContext>> { if self.context.borrow().is_none() { let window = window_from_node(self); let size = self.get_size(); let attrs = if let Some(webgl_attributes) = attrs { match unsafe { WebGLContextAttributes::new(cx, webgl_attributes) } { Ok(ConversionResult::Success(ref attrs)) => From::from(attrs), Ok(ConversionResult::Failure(ref error)) => { unsafe { throw_type_error(cx, &error); } return None; } _ => { debug!("Unexpected error on conversion of WebGLContextAttributes"); return None; } } } else { GLContextAttributes::default() }; let maybe_ctx = WebGLRenderingContext::new(&window, self, size, attrs); *self.context.borrow_mut() = maybe_ctx.map( |ctx| CanvasContext::WebGL(JS::from_ref(&*ctx))); } if let Some(CanvasContext::WebGL(ref context)) = *self.context.borrow() { Some(Root::from_ref(&*context)) } else { None } } pub fn is_valid(&self) -> bool { self.Height()!= 0 && self.Width()!= 0 } pub fn fetch_all_data(&self) -> Option<(Vec<u8>, Size2D<i32>)> { let size = self.get_size(); if size.width == 0 || size.height == 0 { return None } let data = match self.context.borrow().as_ref() { Some(&CanvasContext::Context2d(ref context)) => { let (sender, receiver) = ipc::channel().unwrap(); let msg = CanvasMsg::FromScript(FromScriptMsg::SendPixels(sender)); context.get_ipc_renderer().send(msg).unwrap(); match receiver.recv().unwrap() { Some(pixels) => pixels, None => { return None; } } }, Some(&CanvasContext::WebGL(_)) => { // TODO: add a method in WebGLRenderingContext to get the pixels. return None; }, None => { repeat(0xffu8).take((size.height as usize) * (size.width as usize) * 4).collect() } }; Some((data, size)) } } impl HTMLCanvasElementMethods for HTMLCanvasElement { // https://html.spec.whatwg.org/multipage/#dom-canvas-width make_uint_getter!(Width, "width", DEFAULT_WIDTH); // https://html.spec.whatwg.org/multipage/#dom-canvas-width make_uint_setter!(SetWidth, "width", DEFAULT_WIDTH); // https://html.spec.whatwg.org/multipage/#dom-canvas-height make_uint_getter!(Height, "height", DEFAULT_HEIGHT); // https://html.spec.whatwg.org/multipage/#dom-canvas-height make_uint_setter!(SetHeight, "height", DEFAULT_HEIGHT); #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext unsafe fn GetContext(&self, cx: *mut JSContext, id: DOMString, attributes: Vec<HandleValue>) -> Option<CanvasRenderingContext2DOrWebGLRenderingContext> { match &*id { "2d" => { self.get_or_init_2d_context() .map(CanvasRenderingContext2DOrWebGLRenderingContext::CanvasRenderingContext2D) } "webgl" | "experimental-webgl" => { self.get_or_init_webgl_context(cx, attributes.get(0).cloned()) .map(CanvasRenderingContext2DOrWebGLRenderingContext::WebGLRenderingContext) } _ => None } } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-canvas-todataurl unsafe fn ToDataURL(&self, _context: *mut JSContext, _mime_type: Option<DOMString>, _arguments: Vec<HandleValue>) -> Fallible<DOMString> { // Step 1. if let Some(CanvasContext::Context2d(ref context)) = *self.context.borrow() { if!context.origin_is_clean() { return Err(Error::Security); } } // Step 2. if self.Width() == 0 || self.Height() == 0 { return Ok(DOMString::from("data:,")); } // Step 3. let raw_data = match *self.context.borrow() { Some(CanvasContext::Context2d(ref context)) => { let image_data = context.GetImageData(Finite::wrap(0f64), Finite::wrap(0f64), Finite::wrap(self.Width() as f64), Finite::wrap(self.Height() as f64))?; image_data.get_data_array() } None => { // Each pixel is fully-transparent black. vec![0; (self.Width() * self.Height() * 4) as usize] } _ => return Err(Error::NotSupported) // WebGL }; // Only handle image/png for now. let mime_type = "image/png"; let mut encoded = Vec::new(); { let encoder: PNGEncoder<&mut Vec<u8>> = PNGEncoder::new(&mut encoded); encoder.encode(&raw_data, self.Width(), self.Height(), ColorType::RGBA(8)).unwrap(); } let encoded = base64::encode(&encoded); Ok(DOMString::from(format!("data:{};base64,{}", mime_type, encoded))) } } impl VirtualMethods for HTMLCanvasElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { &local_name!("width") | &local_name!("height") => self.recreate_contexts(), _ => (), }; } fn
(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH), &local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } } impl<'a> From<&'a WebGLContextAttributes> for GLContextAttributes { fn from(attrs: &'a WebGLContextAttributes) -> GLContextAttributes { GLContextAttributes { alpha: attrs.alpha, depth: attrs.depth, stencil: attrs.stencil, antialias: attrs.antialias, premultiplied_alpha: attrs.premultipliedAlpha, preserve_drawing_buffer: attrs.preserveDrawingBuffer, } } } pub mod utils { use dom::window::Window; use net_traits::image_cache::{ImageResponse, UsePlaceholder, ImageOrMetadataAvailable}; use net_traits::image_cache::CanRequestImages; use servo_url::ServoUrl; pub fn request_image_from_cache(window: &Window, url: ServoUrl) -> ImageResponse { let image_cache = window.image_cache(); let response = image_cache.find_image_or_metadata(url.into(), UsePlaceholder::No, CanRequestImages::No); match response { Ok(ImageOrMetadataAvailable::ImageAvailable(image, url)) => ImageResponse::Loaded(image, url), _ => ImageResponse::None, } } }
parse_plain_attribute
identifier_name
variant.rs
use vtable::VTable; use variant_ref::VariantRef; use variant_ref_mut::VariantRefMut; use std::any::{Any, TypeId}; use std::fmt::{Debug, Display, Error as FmtError, Formatter}; use std::ops::Deref; pub struct Variant<'a> { pub data: *mut (), pub vtable: &'a VTable, } impl<'a> Variant<'a> { pub fn new<T: Any>(value: T, vtable: &'a VTable) -> Self { Variant { data: Box::into_raw(Box::new(value)) as *mut (), vtable: vtable, } } #[inline] pub fn is<T: Any>(&self) -> bool { self.vtable.id == TypeId::of::<T>() } #[inline] pub fn downcast_ref<T: Any>(&self) -> Option<&T> { if self.is::<T>() { unsafe { Some(&*(self.data as *const T)) } } else { None } } #[inline] pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> { if self.is::<T>() { unsafe { Some(&mut *(self.data as *mut T)) } } else { None } } #[inline] pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T { debug_assert!(self.is::<T>()); &*(self.data as *const T) } #[inline] pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T { debug_assert!(self.is::<T>()); &mut *(self.data as *mut T) } } impl<'a> Deref for Variant<'a> { type Target = VariantRef<'a>; fn deref(&self) -> &VariantRef<'a> { self.as_ref() } } impl<'a> AsRef<VariantRef<'a>> for Variant<'a> { fn
(&self) -> &VariantRef<'a> { unsafe { &*(self as *const _ as *const VariantRef<'a>) } } } impl<'a> AsMut<VariantRefMut<'a>> for Variant<'a> { fn as_mut(&mut self) -> &mut VariantRefMut<'a> { unsafe { &mut *(self as *mut _ as *mut VariantRefMut<'a>) } } } impl<'a> Clone for Variant<'a> { fn clone(&self) -> Self { (self.vtable.clone)(self.as_ref()) } } impl<'a> Drop for Variant<'a> { fn drop(&mut self) { (self.vtable.drop)(self) } } impl<'a> Display for Variant<'a> { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { (self.vtable.display)(self.as_ref(), f) } } impl<'a> Debug for Variant<'a> { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { (self.vtable.debug)(self.as_ref(), f) } }
as_ref
identifier_name
variant.rs
use vtable::VTable; use variant_ref::VariantRef; use variant_ref_mut::VariantRefMut; use std::any::{Any, TypeId}; use std::fmt::{Debug, Display, Error as FmtError, Formatter}; use std::ops::Deref; pub struct Variant<'a> { pub data: *mut (), pub vtable: &'a VTable, } impl<'a> Variant<'a> { pub fn new<T: Any>(value: T, vtable: &'a VTable) -> Self { Variant { data: Box::into_raw(Box::new(value)) as *mut (), vtable: vtable, } } #[inline] pub fn is<T: Any>(&self) -> bool { self.vtable.id == TypeId::of::<T>() } #[inline] pub fn downcast_ref<T: Any>(&self) -> Option<&T> { if self.is::<T>() { unsafe { Some(&*(self.data as *const T)) } } else { None } } #[inline] pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> { if self.is::<T>() { unsafe { Some(&mut *(self.data as *mut T)) } } else { None } } #[inline] pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T { debug_assert!(self.is::<T>()); &*(self.data as *const T) } #[inline] pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T { debug_assert!(self.is::<T>()); &mut *(self.data as *mut T) } } impl<'a> Deref for Variant<'a> { type Target = VariantRef<'a>; fn deref(&self) -> &VariantRef<'a> { self.as_ref() } } impl<'a> AsRef<VariantRef<'a>> for Variant<'a> { fn as_ref(&self) -> &VariantRef<'a> { unsafe { &*(self as *const _ as *const VariantRef<'a>) } } } impl<'a> AsMut<VariantRefMut<'a>> for Variant<'a> { fn as_mut(&mut self) -> &mut VariantRefMut<'a>
} impl<'a> Clone for Variant<'a> { fn clone(&self) -> Self { (self.vtable.clone)(self.as_ref()) } } impl<'a> Drop for Variant<'a> { fn drop(&mut self) { (self.vtable.drop)(self) } } impl<'a> Display for Variant<'a> { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { (self.vtable.display)(self.as_ref(), f) } } impl<'a> Debug for Variant<'a> { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { (self.vtable.debug)(self.as_ref(), f) } }
{ unsafe { &mut *(self as *mut _ as *mut VariantRefMut<'a>) } }
identifier_body
variant.rs
use vtable::VTable; use variant_ref::VariantRef; use variant_ref_mut::VariantRefMut; use std::any::{Any, TypeId}; use std::fmt::{Debug, Display, Error as FmtError, Formatter}; use std::ops::Deref; pub struct Variant<'a> { pub data: *mut (), pub vtable: &'a VTable, } impl<'a> Variant<'a> { pub fn new<T: Any>(value: T, vtable: &'a VTable) -> Self { Variant { data: Box::into_raw(Box::new(value)) as *mut (), vtable: vtable, } } #[inline] pub fn is<T: Any>(&self) -> bool { self.vtable.id == TypeId::of::<T>() } #[inline] pub fn downcast_ref<T: Any>(&self) -> Option<&T> { if self.is::<T>() { unsafe { Some(&*(self.data as *const T)) } } else { None } } #[inline] pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> { if self.is::<T>()
else { None } } #[inline] pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T { debug_assert!(self.is::<T>()); &*(self.data as *const T) } #[inline] pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T { debug_assert!(self.is::<T>()); &mut *(self.data as *mut T) } } impl<'a> Deref for Variant<'a> { type Target = VariantRef<'a>; fn deref(&self) -> &VariantRef<'a> { self.as_ref() } } impl<'a> AsRef<VariantRef<'a>> for Variant<'a> { fn as_ref(&self) -> &VariantRef<'a> { unsafe { &*(self as *const _ as *const VariantRef<'a>) } } } impl<'a> AsMut<VariantRefMut<'a>> for Variant<'a> { fn as_mut(&mut self) -> &mut VariantRefMut<'a> { unsafe { &mut *(self as *mut _ as *mut VariantRefMut<'a>) } } } impl<'a> Clone for Variant<'a> { fn clone(&self) -> Self { (self.vtable.clone)(self.as_ref()) } } impl<'a> Drop for Variant<'a> { fn drop(&mut self) { (self.vtable.drop)(self) } } impl<'a> Display for Variant<'a> { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { (self.vtable.display)(self.as_ref(), f) } } impl<'a> Debug for Variant<'a> { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { (self.vtable.debug)(self.as_ref(), f) } }
{ unsafe { Some(&mut *(self.data as *mut T)) } }
conditional_block
variant.rs
use vtable::VTable; use variant_ref::VariantRef; use variant_ref_mut::VariantRefMut; use std::any::{Any, TypeId}; use std::fmt::{Debug, Display, Error as FmtError, Formatter}; use std::ops::Deref; pub struct Variant<'a> { pub data: *mut (), pub vtable: &'a VTable, } impl<'a> Variant<'a> { pub fn new<T: Any>(value: T, vtable: &'a VTable) -> Self { Variant { data: Box::into_raw(Box::new(value)) as *mut (), vtable: vtable, } } #[inline] pub fn is<T: Any>(&self) -> bool { self.vtable.id == TypeId::of::<T>() } #[inline] pub fn downcast_ref<T: Any>(&self) -> Option<&T> { if self.is::<T>() { unsafe { Some(&*(self.data as *const T)) } } else { None } } #[inline] pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> { if self.is::<T>() { unsafe { Some(&mut *(self.data as *mut T)) } } else { None } } #[inline] pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T { debug_assert!(self.is::<T>()); &*(self.data as *const T) } #[inline] pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T { debug_assert!(self.is::<T>()); &mut *(self.data as *mut T) } } impl<'a> Deref for Variant<'a> { type Target = VariantRef<'a>; fn deref(&self) -> &VariantRef<'a> { self.as_ref() } } impl<'a> AsRef<VariantRef<'a>> for Variant<'a> { fn as_ref(&self) -> &VariantRef<'a> { unsafe { &*(self as *const _ as *const VariantRef<'a>) } } } impl<'a> AsMut<VariantRefMut<'a>> for Variant<'a> { fn as_mut(&mut self) -> &mut VariantRefMut<'a> { unsafe { &mut *(self as *mut _ as *mut VariantRefMut<'a>) } } } impl<'a> Clone for Variant<'a> { fn clone(&self) -> Self { (self.vtable.clone)(self.as_ref()) } } impl<'a> Drop for Variant<'a> { fn drop(&mut self) { (self.vtable.drop)(self) } } impl<'a> Display for Variant<'a> {
impl<'a> Debug for Variant<'a> { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { (self.vtable.debug)(self.as_ref(), f) } }
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { (self.vtable.display)(self.as_ref(), f) } }
random_line_split
0-1.rs
// http://rosettacode.org/wiki/Knapsack_problem/0-1 use std::cmp::max; use std::iter::repeat; // This struct is used to store our items that we want in our knap-sack. // // Show is for displaying the fields. // allow(dead_code) removes a dead code warning when the name of the struct is not // used (as in this case happens in the tests) #[derive(Copy, Clone)] struct Want<'a> { #[allow(dead_code)] name: &'a str, weight: usize, value: usize } // Global, immutable allocation of our items. This is so we can reference // this in multiple functions. const ITEMS: &'static [Want<'static>] = &[ Want {name: "map", weight: 9, value: 150}, Want {name: "compass", weight: 13, value: 35}, Want {name: "water", weight: 153, value: 200}, Want {name: "sandwich", weight: 50, value: 160}, Want {name: "glucose", weight: 15, value: 60}, Want {name: "tin", weight: 68, value: 45}, Want {name: "banana", weight: 27, value: 60}, Want {name: "apple", weight: 39, value: 40}, Want {name: "cheese", weight: 23, value: 30}, Want {name: "beer", weight: 52, value: 10}, Want {name: "suntancream", weight: 11, value: 70}, Want {name: "camera", weight: 32, value: 30}, Want {name: "T-shirt", weight: 24, value: 15}, Want {name: "trousers", weight: 48, value: 10}, Want {name: "umbrella", weight: 73, value: 40}, Want {name: "waterproof trousers", weight: 42, value: 70}, Want {name: "waterproof overclothes", weight: 43, value: 75}, Want {name: "note-case", weight: 22, value: 80}, Want {name: "sunglasses", weight: 7, value: 20}, Want {name: "towel", weight: 18, value: 12}, Want {name: "socks", weight: 4, value: 50}, Want {name: "book", weight: 30, value: 10} ]; // This is a bottom-up dynamic programming solution to the 0-1 knap-sack problem.
// maximize value // subject to weights <= max_weight fn knap_01_dp<'a>(xs: &[Want<'a>], max_weight: usize) -> Vec<Want<'a>> { // Save this value, so we don't have to make repeated calls. let xs_len = xs.len(); // Imagine we wrote a recursive function(item, max_weight) that returns a // usize corresponding to the maximum cumulative value by considering a // subset of items such that the combined weight <= max_weight. // // fn best_value(item: usize, max_weight: usize) -> usize{ // if item == 0 { // return 0; // } // if xs[item - 1].weight > max_weight { // return best_value(item - 1, max_weight, xs); // } // return max(best_value(item - 1, max_weight, xs), // best_value(item - 1, max_weight - xs[item - 1].weight, xs) // + xs[item - 1].value); // } // // best_value(xs_len, max_weight) is equal to the maximum value that we // can add to the bag. // // The problem with using this function is that it performs redudant // calculations. // // The dynamic programming solution is to precompute all of the values we // need and put them into a 2D array. // // In a similar vein, the top-down solution would be to memoize the // function then compute the results on demand. let zero_vec: Vec<usize> = repeat(0).take(max_weight + 1).collect(); let mut best_value: Vec<Vec<usize>> = repeat(zero_vec) .take(xs_len + 1).collect(); // loop over the items for i in 0..xs_len { // loop over the weights for w in 1..(max_weight + 1) { // do we have room in our knapsack? if xs[i].weight > w { // if we don't, then we'll say that the value doesn't change // when considering this item best_value[i + 1][w] = best_value[i][w].clone(); } else { // if we do, then we have to see if the value we gain by adding // the item, given the weight, is better than not adding the item best_value[i + 1][w] = max(best_value[i][w].clone(), best_value[i][w - xs[i].weight] + xs[i].value); } } } // a variable representing the weight left in the bag let mut left_weight = max_weight.clone(); // a possibly over-allocated dynamically sized vector to push results to let mut result = Vec::with_capacity(xs_len); // we built up the solution space through a forward pass over the data, // now we have to traverse backwards to get the solution for i in (1..xs_len+1).rev() { // We can check if an item should be added to the knap-sack by comparing // best_value with and without this item. If best_value added this // item then so should we. if best_value[i][left_weight]!= best_value[i - 1][left_weight] { result.push(xs[i - 1]); // we remove the weight of the object from the remaining weight // we can add to the bag left_weight -= xs[i - 1].weight; } } return result; } #[cfg(not(test))] fn main () { let xs = knap_01_dp(ITEMS, 400); // Print the items. We have to reverse the order because we solved the // problem backward. for i in xs.iter().rev() { println!("Item: {}, Weight: {}, Value: {}", i.name, i.weight, i.value); } // Print the sum of weights. let weights = xs.iter().fold(0, |a, &b| a + b.weight); println!("Total Weight: {}", weights); // Print the sum of the values. let values = xs.iter().fold(0, |a, &b| a + b.value); println!("Total Value: {}", values); } #[test] fn test_dp_results() { let dp_results = knap_01_dp(ITEMS, 400); let dp_weights= dp_results.iter().fold(0, |a, &b| a + b.weight); let dp_values = dp_results.iter().fold(0, |a, &b| a + b.value); assert_eq!(dp_weights, 396); assert_eq!(dp_values, 1030); }
random_line_split
0-1.rs
// http://rosettacode.org/wiki/Knapsack_problem/0-1 use std::cmp::max; use std::iter::repeat; // This struct is used to store our items that we want in our knap-sack. // // Show is for displaying the fields. // allow(dead_code) removes a dead code warning when the name of the struct is not // used (as in this case happens in the tests) #[derive(Copy, Clone)] struct Want<'a> { #[allow(dead_code)] name: &'a str, weight: usize, value: usize } // Global, immutable allocation of our items. This is so we can reference // this in multiple functions. const ITEMS: &'static [Want<'static>] = &[ Want {name: "map", weight: 9, value: 150}, Want {name: "compass", weight: 13, value: 35}, Want {name: "water", weight: 153, value: 200}, Want {name: "sandwich", weight: 50, value: 160}, Want {name: "glucose", weight: 15, value: 60}, Want {name: "tin", weight: 68, value: 45}, Want {name: "banana", weight: 27, value: 60}, Want {name: "apple", weight: 39, value: 40}, Want {name: "cheese", weight: 23, value: 30}, Want {name: "beer", weight: 52, value: 10}, Want {name: "suntancream", weight: 11, value: 70}, Want {name: "camera", weight: 32, value: 30}, Want {name: "T-shirt", weight: 24, value: 15}, Want {name: "trousers", weight: 48, value: 10}, Want {name: "umbrella", weight: 73, value: 40}, Want {name: "waterproof trousers", weight: 42, value: 70}, Want {name: "waterproof overclothes", weight: 43, value: 75}, Want {name: "note-case", weight: 22, value: 80}, Want {name: "sunglasses", weight: 7, value: 20}, Want {name: "towel", weight: 18, value: 12}, Want {name: "socks", weight: 4, value: 50}, Want {name: "book", weight: 30, value: 10} ]; // This is a bottom-up dynamic programming solution to the 0-1 knap-sack problem. // maximize value // subject to weights <= max_weight fn knap_01_dp<'a>(xs: &[Want<'a>], max_weight: usize) -> Vec<Want<'a>>
// // best_value(xs_len, max_weight) is equal to the maximum value that we // can add to the bag. // // The problem with using this function is that it performs redudant // calculations. // // The dynamic programming solution is to precompute all of the values we // need and put them into a 2D array. // // In a similar vein, the top-down solution would be to memoize the // function then compute the results on demand. let zero_vec: Vec<usize> = repeat(0).take(max_weight + 1).collect(); let mut best_value: Vec<Vec<usize>> = repeat(zero_vec) .take(xs_len + 1).collect(); // loop over the items for i in 0..xs_len { // loop over the weights for w in 1..(max_weight + 1) { // do we have room in our knapsack? if xs[i].weight > w { // if we don't, then we'll say that the value doesn't change // when considering this item best_value[i + 1][w] = best_value[i][w].clone(); } else { // if we do, then we have to see if the value we gain by adding // the item, given the weight, is better than not adding the item best_value[i + 1][w] = max(best_value[i][w].clone(), best_value[i][w - xs[i].weight] + xs[i].value); } } } // a variable representing the weight left in the bag let mut left_weight = max_weight.clone(); // a possibly over-allocated dynamically sized vector to push results to let mut result = Vec::with_capacity(xs_len); // we built up the solution space through a forward pass over the data, // now we have to traverse backwards to get the solution for i in (1..xs_len+1).rev() { // We can check if an item should be added to the knap-sack by comparing // best_value with and without this item. If best_value added this // item then so should we. if best_value[i][left_weight]!= best_value[i - 1][left_weight] { result.push(xs[i - 1]); // we remove the weight of the object from the remaining weight // we can add to the bag left_weight -= xs[i - 1].weight; } } return result; } #[cfg(not(test))] fn main () { let xs = knap_01_dp(ITEMS, 400); // Print the items. We have to reverse the order because we solved the // problem backward. for i in xs.iter().rev() { println!("Item: {}, Weight: {}, Value: {}", i.name, i.weight, i.value); } // Print the sum of weights. let weights = xs.iter().fold(0, |a, &b| a + b.weight); println!("Total Weight: {}", weights); // Print the sum of the values. let values = xs.iter().fold(0, |a, &b| a + b.value); println!("Total Value: {}", values); } #[test] fn test_dp_results() { let dp_results = knap_01_dp(ITEMS, 400); let dp_weights= dp_results.iter().fold(0, |a, &b| a + b.weight); let dp_values = dp_results.iter().fold(0, |a, &b| a + b.value); assert_eq!(dp_weights, 396); assert_eq!(dp_values, 1030); }
{ // Save this value, so we don't have to make repeated calls. let xs_len = xs.len(); // Imagine we wrote a recursive function(item, max_weight) that returns a // usize corresponding to the maximum cumulative value by considering a // subset of items such that the combined weight <= max_weight. // // fn best_value(item: usize, max_weight: usize) -> usize{ // if item == 0 { // return 0; // } // if xs[item - 1].weight > max_weight { // return best_value(item - 1, max_weight, xs); // } // return max(best_value(item - 1, max_weight, xs), // best_value(item - 1, max_weight - xs[item - 1].weight, xs) // + xs[item - 1].value); // }
identifier_body
0-1.rs
// http://rosettacode.org/wiki/Knapsack_problem/0-1 use std::cmp::max; use std::iter::repeat; // This struct is used to store our items that we want in our knap-sack. // // Show is for displaying the fields. // allow(dead_code) removes a dead code warning when the name of the struct is not // used (as in this case happens in the tests) #[derive(Copy, Clone)] struct Want<'a> { #[allow(dead_code)] name: &'a str, weight: usize, value: usize } // Global, immutable allocation of our items. This is so we can reference // this in multiple functions. const ITEMS: &'static [Want<'static>] = &[ Want {name: "map", weight: 9, value: 150}, Want {name: "compass", weight: 13, value: 35}, Want {name: "water", weight: 153, value: 200}, Want {name: "sandwich", weight: 50, value: 160}, Want {name: "glucose", weight: 15, value: 60}, Want {name: "tin", weight: 68, value: 45}, Want {name: "banana", weight: 27, value: 60}, Want {name: "apple", weight: 39, value: 40}, Want {name: "cheese", weight: 23, value: 30}, Want {name: "beer", weight: 52, value: 10}, Want {name: "suntancream", weight: 11, value: 70}, Want {name: "camera", weight: 32, value: 30}, Want {name: "T-shirt", weight: 24, value: 15}, Want {name: "trousers", weight: 48, value: 10}, Want {name: "umbrella", weight: 73, value: 40}, Want {name: "waterproof trousers", weight: 42, value: 70}, Want {name: "waterproof overclothes", weight: 43, value: 75}, Want {name: "note-case", weight: 22, value: 80}, Want {name: "sunglasses", weight: 7, value: 20}, Want {name: "towel", weight: 18, value: 12}, Want {name: "socks", weight: 4, value: 50}, Want {name: "book", weight: 30, value: 10} ]; // This is a bottom-up dynamic programming solution to the 0-1 knap-sack problem. // maximize value // subject to weights <= max_weight fn knap_01_dp<'a>(xs: &[Want<'a>], max_weight: usize) -> Vec<Want<'a>> { // Save this value, so we don't have to make repeated calls. let xs_len = xs.len(); // Imagine we wrote a recursive function(item, max_weight) that returns a // usize corresponding to the maximum cumulative value by considering a // subset of items such that the combined weight <= max_weight. // // fn best_value(item: usize, max_weight: usize) -> usize{ // if item == 0 { // return 0; // } // if xs[item - 1].weight > max_weight { // return best_value(item - 1, max_weight, xs); // } // return max(best_value(item - 1, max_weight, xs), // best_value(item - 1, max_weight - xs[item - 1].weight, xs) // + xs[item - 1].value); // } // // best_value(xs_len, max_weight) is equal to the maximum value that we // can add to the bag. // // The problem with using this function is that it performs redudant // calculations. // // The dynamic programming solution is to precompute all of the values we // need and put them into a 2D array. // // In a similar vein, the top-down solution would be to memoize the // function then compute the results on demand. let zero_vec: Vec<usize> = repeat(0).take(max_weight + 1).collect(); let mut best_value: Vec<Vec<usize>> = repeat(zero_vec) .take(xs_len + 1).collect(); // loop over the items for i in 0..xs_len { // loop over the weights for w in 1..(max_weight + 1) { // do we have room in our knapsack? if xs[i].weight > w { // if we don't, then we'll say that the value doesn't change // when considering this item best_value[i + 1][w] = best_value[i][w].clone(); } else { // if we do, then we have to see if the value we gain by adding // the item, given the weight, is better than not adding the item best_value[i + 1][w] = max(best_value[i][w].clone(), best_value[i][w - xs[i].weight] + xs[i].value); } } } // a variable representing the weight left in the bag let mut left_weight = max_weight.clone(); // a possibly over-allocated dynamically sized vector to push results to let mut result = Vec::with_capacity(xs_len); // we built up the solution space through a forward pass over the data, // now we have to traverse backwards to get the solution for i in (1..xs_len+1).rev() { // We can check if an item should be added to the knap-sack by comparing // best_value with and without this item. If best_value added this // item then so should we. if best_value[i][left_weight]!= best_value[i - 1][left_weight]
} return result; } #[cfg(not(test))] fn main () { let xs = knap_01_dp(ITEMS, 400); // Print the items. We have to reverse the order because we solved the // problem backward. for i in xs.iter().rev() { println!("Item: {}, Weight: {}, Value: {}", i.name, i.weight, i.value); } // Print the sum of weights. let weights = xs.iter().fold(0, |a, &b| a + b.weight); println!("Total Weight: {}", weights); // Print the sum of the values. let values = xs.iter().fold(0, |a, &b| a + b.value); println!("Total Value: {}", values); } #[test] fn test_dp_results() { let dp_results = knap_01_dp(ITEMS, 400); let dp_weights= dp_results.iter().fold(0, |a, &b| a + b.weight); let dp_values = dp_results.iter().fold(0, |a, &b| a + b.value); assert_eq!(dp_weights, 396); assert_eq!(dp_values, 1030); }
{ result.push(xs[i - 1]); // we remove the weight of the object from the remaining weight // we can add to the bag left_weight -= xs[i - 1].weight; }
conditional_block
0-1.rs
// http://rosettacode.org/wiki/Knapsack_problem/0-1 use std::cmp::max; use std::iter::repeat; // This struct is used to store our items that we want in our knap-sack. // // Show is for displaying the fields. // allow(dead_code) removes a dead code warning when the name of the struct is not // used (as in this case happens in the tests) #[derive(Copy, Clone)] struct Want<'a> { #[allow(dead_code)] name: &'a str, weight: usize, value: usize } // Global, immutable allocation of our items. This is so we can reference // this in multiple functions. const ITEMS: &'static [Want<'static>] = &[ Want {name: "map", weight: 9, value: 150}, Want {name: "compass", weight: 13, value: 35}, Want {name: "water", weight: 153, value: 200}, Want {name: "sandwich", weight: 50, value: 160}, Want {name: "glucose", weight: 15, value: 60}, Want {name: "tin", weight: 68, value: 45}, Want {name: "banana", weight: 27, value: 60}, Want {name: "apple", weight: 39, value: 40}, Want {name: "cheese", weight: 23, value: 30}, Want {name: "beer", weight: 52, value: 10}, Want {name: "suntancream", weight: 11, value: 70}, Want {name: "camera", weight: 32, value: 30}, Want {name: "T-shirt", weight: 24, value: 15}, Want {name: "trousers", weight: 48, value: 10}, Want {name: "umbrella", weight: 73, value: 40}, Want {name: "waterproof trousers", weight: 42, value: 70}, Want {name: "waterproof overclothes", weight: 43, value: 75}, Want {name: "note-case", weight: 22, value: 80}, Want {name: "sunglasses", weight: 7, value: 20}, Want {name: "towel", weight: 18, value: 12}, Want {name: "socks", weight: 4, value: 50}, Want {name: "book", weight: 30, value: 10} ]; // This is a bottom-up dynamic programming solution to the 0-1 knap-sack problem. // maximize value // subject to weights <= max_weight fn knap_01_dp<'a>(xs: &[Want<'a>], max_weight: usize) -> Vec<Want<'a>> { // Save this value, so we don't have to make repeated calls. let xs_len = xs.len(); // Imagine we wrote a recursive function(item, max_weight) that returns a // usize corresponding to the maximum cumulative value by considering a // subset of items such that the combined weight <= max_weight. // // fn best_value(item: usize, max_weight: usize) -> usize{ // if item == 0 { // return 0; // } // if xs[item - 1].weight > max_weight { // return best_value(item - 1, max_weight, xs); // } // return max(best_value(item - 1, max_weight, xs), // best_value(item - 1, max_weight - xs[item - 1].weight, xs) // + xs[item - 1].value); // } // // best_value(xs_len, max_weight) is equal to the maximum value that we // can add to the bag. // // The problem with using this function is that it performs redudant // calculations. // // The dynamic programming solution is to precompute all of the values we // need and put them into a 2D array. // // In a similar vein, the top-down solution would be to memoize the // function then compute the results on demand. let zero_vec: Vec<usize> = repeat(0).take(max_weight + 1).collect(); let mut best_value: Vec<Vec<usize>> = repeat(zero_vec) .take(xs_len + 1).collect(); // loop over the items for i in 0..xs_len { // loop over the weights for w in 1..(max_weight + 1) { // do we have room in our knapsack? if xs[i].weight > w { // if we don't, then we'll say that the value doesn't change // when considering this item best_value[i + 1][w] = best_value[i][w].clone(); } else { // if we do, then we have to see if the value we gain by adding // the item, given the weight, is better than not adding the item best_value[i + 1][w] = max(best_value[i][w].clone(), best_value[i][w - xs[i].weight] + xs[i].value); } } } // a variable representing the weight left in the bag let mut left_weight = max_weight.clone(); // a possibly over-allocated dynamically sized vector to push results to let mut result = Vec::with_capacity(xs_len); // we built up the solution space through a forward pass over the data, // now we have to traverse backwards to get the solution for i in (1..xs_len+1).rev() { // We can check if an item should be added to the knap-sack by comparing // best_value with and without this item. If best_value added this // item then so should we. if best_value[i][left_weight]!= best_value[i - 1][left_weight] { result.push(xs[i - 1]); // we remove the weight of the object from the remaining weight // we can add to the bag left_weight -= xs[i - 1].weight; } } return result; } #[cfg(not(test))] fn
() { let xs = knap_01_dp(ITEMS, 400); // Print the items. We have to reverse the order because we solved the // problem backward. for i in xs.iter().rev() { println!("Item: {}, Weight: {}, Value: {}", i.name, i.weight, i.value); } // Print the sum of weights. let weights = xs.iter().fold(0, |a, &b| a + b.weight); println!("Total Weight: {}", weights); // Print the sum of the values. let values = xs.iter().fold(0, |a, &b| a + b.value); println!("Total Value: {}", values); } #[test] fn test_dp_results() { let dp_results = knap_01_dp(ITEMS, 400); let dp_weights= dp_results.iter().fold(0, |a, &b| a + b.weight); let dp_values = dp_results.iter().fold(0, |a, &b| a + b.value); assert_eq!(dp_weights, 396); assert_eq!(dp_values, 1030); }
main
identifier_name
mod.rs
extern crate time; extern crate url; extern crate rand; use self::url::{FORM_URLENCODED_ENCODE_SET, utf8_percent_encode}; use self::time::now_utc; use self::rand::{OsRng, Rng}; use std::fmt; pub mod session; pub mod temporary_credentials; #[derive(Copy, Debug, PartialEq, Eq, Clone)] #[unstable] pub enum HTTPMethod { GET, POST, DELETE, PUT, HEAD } impl fmt::Display for HTTPMethod { fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result{ let out = match *self { HTTPMethod::GET => "GET", HTTPMethod::POST => "POST", HTTPMethod::DELETE => "DELETE", HTTPMethod::PUT => "PUT", HTTPMethod::HEAD => "HEAD" }; write!(f, "{}", out) } } pub trait AuthorizationHeader { fn get_header(&self) -> String; } // TODO: add to crypto library? fn generate_nonce() -> String { OsRng::new().unwrap() .gen_ascii_chars() .take(32) .collect() } fn generate_timestamp() -> String { now_utc().to_timespec().sec.to_string() } pub trait BaseString { /// Returns a base string URI, ecnoded with [RFC3986]. This gets used to /// generate the `oauth_signature`. It takes a different path dependent /// on the signature type fn get_base_string(&self, method: HTTPMethod, base_url: &str, data: Vec<(&str, &str)>) -> String { // split URL at `?`, to sort parameters let split_url : Vec<&str> = base_url.rsplitn(1, '?').collect(); let (url, url_data) = match split_url.len() { 1 => (Some(split_url[0]), None), // no parameters in the request url 2 => (Some(split_url[1]), Some(split_url[0])), // if there are parameters _ => (None, None) // erronous input base_url }; format!("{}&{}&{}", method, utf8_percent_encode(url.unwrap(), FORM_URLENCODED_ENCODE_SET), utf8_percent_encode(self.get_base_parameters(data, url_data).as_slice(), FORM_URLENCODED_ENCODE_SET)) } /// Returns all the required parameters used in the OAuth request. It takes into account /// the signature method as well as which type of OAuth request you are making fn get_self_paramaters(&self) -> Vec<String>; /// Takes the required OAuth `self_parameters` and the input data and returns a String with /// all parameters in alphabetical order fn get_base_parameters(&self, data: Vec<(&str, &str)>, url_data : Option<&str>) -> String { let to_pair = | (key, value) : (&str, &str) | -> String { format!("{}={}", key, value) }; let mut params = self.get_self_paramaters(); params.append(&mut (data.into_iter().map(to_pair).collect::<Vec<String>>())); match url_data { None => {} Some(r) => { params.append(&mut r.split('&').map(|val : &str| -> String {val.to_string()}).collect()); }, }; params.sort(); // TODO: add a new url-encoding method to do the equivalent concat(params.as_slice(), "&").replace("+", "%20") .replace("*","%2A") } } /// Concatenate all values in `data`, seperated by `sep` /// /// ``` /// use rust_oauth::oauth1::client::concat; /// let values = vec!["cat".to_string(), "dog".to_string(), "bird".to_string()]; /// let concatenated = concat(values.as_slice(), " "); /// assert_eq!(concatenated, "cat dog bird".to_string()); /// ``` pub fn concat(data: &[String], sep : &str) -> String { match data { [] => String::new(), [ref param] => format!("{}", param), [ref param, rest..] => format!("{}{}{}", param, sep, concat(rest, sep)) } } #[cfg(test)] mod test { use super::{concat, generate_nonce}; #[test] fn concat_test_multiple_items() { let data = vec!["alpha".to_string(), "beta".to_string(), "gamma".to_string()]; assert_eq!(concat(data.as_slice(), "&"), "alpha&beta&gamma".to_string()) } #[test] fn concat_test_empty_vec() { let data = vec![]; assert_eq!(concat(data.as_slice(), "&"), String::new()) } #[test] fn concat_test_single()
#[test] fn generate_nonce_unique(){ let mut nonces = Vec::new(); for _ in 0..1000 { nonces.push(generate_nonce()) } let len = nonces.len(); nonces.dedup(); assert_eq!(len, nonces.len()); } }
{ let data = vec!["alpha".to_string()]; assert_eq!(concat(data.as_slice(), "&"), "alpha".to_string()) }
identifier_body
mod.rs
extern crate time; extern crate url; extern crate rand; use self::url::{FORM_URLENCODED_ENCODE_SET, utf8_percent_encode}; use self::time::now_utc; use self::rand::{OsRng, Rng}; use std::fmt; pub mod session; pub mod temporary_credentials; #[derive(Copy, Debug, PartialEq, Eq, Clone)] #[unstable] pub enum HTTPMethod { GET, POST, DELETE, PUT, HEAD } impl fmt::Display for HTTPMethod { fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result{ let out = match *self { HTTPMethod::GET => "GET", HTTPMethod::POST => "POST", HTTPMethod::DELETE => "DELETE", HTTPMethod::PUT => "PUT", HTTPMethod::HEAD => "HEAD" }; write!(f, "{}", out) } } pub trait AuthorizationHeader { fn get_header(&self) -> String; } // TODO: add to crypto library? fn generate_nonce() -> String { OsRng::new().unwrap() .gen_ascii_chars() .take(32) .collect() } fn generate_timestamp() -> String { now_utc().to_timespec().sec.to_string() }
pub trait BaseString { /// Returns a base string URI, ecnoded with [RFC3986]. This gets used to /// generate the `oauth_signature`. It takes a different path dependent /// on the signature type fn get_base_string(&self, method: HTTPMethod, base_url: &str, data: Vec<(&str, &str)>) -> String { // split URL at `?`, to sort parameters let split_url : Vec<&str> = base_url.rsplitn(1, '?').collect(); let (url, url_data) = match split_url.len() { 1 => (Some(split_url[0]), None), // no parameters in the request url 2 => (Some(split_url[1]), Some(split_url[0])), // if there are parameters _ => (None, None) // erronous input base_url }; format!("{}&{}&{}", method, utf8_percent_encode(url.unwrap(), FORM_URLENCODED_ENCODE_SET), utf8_percent_encode(self.get_base_parameters(data, url_data).as_slice(), FORM_URLENCODED_ENCODE_SET)) } /// Returns all the required parameters used in the OAuth request. It takes into account /// the signature method as well as which type of OAuth request you are making fn get_self_paramaters(&self) -> Vec<String>; /// Takes the required OAuth `self_parameters` and the input data and returns a String with /// all parameters in alphabetical order fn get_base_parameters(&self, data: Vec<(&str, &str)>, url_data : Option<&str>) -> String { let to_pair = | (key, value) : (&str, &str) | -> String { format!("{}={}", key, value) }; let mut params = self.get_self_paramaters(); params.append(&mut (data.into_iter().map(to_pair).collect::<Vec<String>>())); match url_data { None => {} Some(r) => { params.append(&mut r.split('&').map(|val : &str| -> String {val.to_string()}).collect()); }, }; params.sort(); // TODO: add a new url-encoding method to do the equivalent concat(params.as_slice(), "&").replace("+", "%20") .replace("*","%2A") } } /// Concatenate all values in `data`, seperated by `sep` /// /// ``` /// use rust_oauth::oauth1::client::concat; /// let values = vec!["cat".to_string(), "dog".to_string(), "bird".to_string()]; /// let concatenated = concat(values.as_slice(), " "); /// assert_eq!(concatenated, "cat dog bird".to_string()); /// ``` pub fn concat(data: &[String], sep : &str) -> String { match data { [] => String::new(), [ref param] => format!("{}", param), [ref param, rest..] => format!("{}{}{}", param, sep, concat(rest, sep)) } } #[cfg(test)] mod test { use super::{concat, generate_nonce}; #[test] fn concat_test_multiple_items() { let data = vec!["alpha".to_string(), "beta".to_string(), "gamma".to_string()]; assert_eq!(concat(data.as_slice(), "&"), "alpha&beta&gamma".to_string()) } #[test] fn concat_test_empty_vec() { let data = vec![]; assert_eq!(concat(data.as_slice(), "&"), String::new()) } #[test] fn concat_test_single() { let data = vec!["alpha".to_string()]; assert_eq!(concat(data.as_slice(), "&"), "alpha".to_string()) } #[test] fn generate_nonce_unique(){ let mut nonces = Vec::new(); for _ in 0..1000 { nonces.push(generate_nonce()) } let len = nonces.len(); nonces.dedup(); assert_eq!(len, nonces.len()); } }
random_line_split
mod.rs
extern crate time; extern crate url; extern crate rand; use self::url::{FORM_URLENCODED_ENCODE_SET, utf8_percent_encode}; use self::time::now_utc; use self::rand::{OsRng, Rng}; use std::fmt; pub mod session; pub mod temporary_credentials; #[derive(Copy, Debug, PartialEq, Eq, Clone)] #[unstable] pub enum HTTPMethod { GET, POST, DELETE, PUT, HEAD } impl fmt::Display for HTTPMethod { fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result{ let out = match *self { HTTPMethod::GET => "GET", HTTPMethod::POST => "POST", HTTPMethod::DELETE => "DELETE", HTTPMethod::PUT => "PUT", HTTPMethod::HEAD => "HEAD" }; write!(f, "{}", out) } } pub trait AuthorizationHeader { fn get_header(&self) -> String; } // TODO: add to crypto library? fn generate_nonce() -> String { OsRng::new().unwrap() .gen_ascii_chars() .take(32) .collect() } fn generate_timestamp() -> String { now_utc().to_timespec().sec.to_string() } pub trait BaseString { /// Returns a base string URI, ecnoded with [RFC3986]. This gets used to /// generate the `oauth_signature`. It takes a different path dependent /// on the signature type fn get_base_string(&self, method: HTTPMethod, base_url: &str, data: Vec<(&str, &str)>) -> String { // split URL at `?`, to sort parameters let split_url : Vec<&str> = base_url.rsplitn(1, '?').collect(); let (url, url_data) = match split_url.len() { 1 => (Some(split_url[0]), None), // no parameters in the request url 2 => (Some(split_url[1]), Some(split_url[0])), // if there are parameters _ => (None, None) // erronous input base_url }; format!("{}&{}&{}", method, utf8_percent_encode(url.unwrap(), FORM_URLENCODED_ENCODE_SET), utf8_percent_encode(self.get_base_parameters(data, url_data).as_slice(), FORM_URLENCODED_ENCODE_SET)) } /// Returns all the required parameters used in the OAuth request. It takes into account /// the signature method as well as which type of OAuth request you are making fn get_self_paramaters(&self) -> Vec<String>; /// Takes the required OAuth `self_parameters` and the input data and returns a String with /// all parameters in alphabetical order fn get_base_parameters(&self, data: Vec<(&str, &str)>, url_data : Option<&str>) -> String { let to_pair = | (key, value) : (&str, &str) | -> String { format!("{}={}", key, value) }; let mut params = self.get_self_paramaters(); params.append(&mut (data.into_iter().map(to_pair).collect::<Vec<String>>())); match url_data { None => {} Some(r) => { params.append(&mut r.split('&').map(|val : &str| -> String {val.to_string()}).collect()); }, }; params.sort(); // TODO: add a new url-encoding method to do the equivalent concat(params.as_slice(), "&").replace("+", "%20") .replace("*","%2A") } } /// Concatenate all values in `data`, seperated by `sep` /// /// ``` /// use rust_oauth::oauth1::client::concat; /// let values = vec!["cat".to_string(), "dog".to_string(), "bird".to_string()]; /// let concatenated = concat(values.as_slice(), " "); /// assert_eq!(concatenated, "cat dog bird".to_string()); /// ``` pub fn
(data: &[String], sep : &str) -> String { match data { [] => String::new(), [ref param] => format!("{}", param), [ref param, rest..] => format!("{}{}{}", param, sep, concat(rest, sep)) } } #[cfg(test)] mod test { use super::{concat, generate_nonce}; #[test] fn concat_test_multiple_items() { let data = vec!["alpha".to_string(), "beta".to_string(), "gamma".to_string()]; assert_eq!(concat(data.as_slice(), "&"), "alpha&beta&gamma".to_string()) } #[test] fn concat_test_empty_vec() { let data = vec![]; assert_eq!(concat(data.as_slice(), "&"), String::new()) } #[test] fn concat_test_single() { let data = vec!["alpha".to_string()]; assert_eq!(concat(data.as_slice(), "&"), "alpha".to_string()) } #[test] fn generate_nonce_unique(){ let mut nonces = Vec::new(); for _ in 0..1000 { nonces.push(generate_nonce()) } let len = nonces.len(); nonces.dedup(); assert_eq!(len, nonces.len()); } }
concat
identifier_name
mod.rs
pub use self::connected::{Connected, AutocommitOff, AutocommitOn, AutocommitMode}; pub use self::hdbc_wrapper::HDbcWrapper; pub use self::unconnected::Unconnected; use super::*; use sys::*; use std::ops::DerefMut; mod connected; mod unconnected; mod hdbc_wrapper; /// A `DataSource` is used to query and manipulate a data source. /// /// * The state of the connection /// * The current connection-level diagnostics /// * The handles of statements and descriptors currently allocated on the connection /// * The current settings of each connection attribute /// /// # States /// /// A `DataSource` is in one of two states `Connected` or `Unconnected`. These are modeled in the /// type at compile time. Every new `DataSource` starts out as `Unconnected`. To execute a query it /// needs to be `Connected`. You can achieve this by calling e.g. `connect` and capture the result /// in a new binding which will be of type `DataSource::<'env, Connected<'env>>`. /// /// See [Connection Handles in the ODBC Reference][1] /// [1]: https://docs.microsoft.com/sql/odbc/reference/develop-app/connection-handles #[derive(Debug)] pub struct DataSource<'env, S: HDbcWrapper<'env> = Unconnected<'env>> { /// Connection handle. Either `HDbc` for `Unconnected` or `Connected` for `Connected`. handle: S::Handle } impl<'env, Any> DataSource<'env, Any> where Any: HDbcWrapper<'env>, { /// Consumes the `DataSource`, returning the wrapped raw `SQLHDBC` /// /// Leaks the Connection Handle. This is usually done in order to pass ownership from Rust to /// another language. After calling this method, the caller is responsible for invoking /// `SQLFreeHandle`. pub fn into_raw(self) -> SQLHDBC { self.handle.into_hdbc().into_raw() } /// Provides access to the raw ODBC Connection Handle pub fn as_raw(&self) -> SQLHDBC { self.handle.as_raw() } /// May only be invoked with a valid Statement Handle which has been allocated using /// `SQLAllocHandle`. Special care must be taken that the Connection Handle passed is in a /// State which matches the type. pub unsafe fn from_raw(raw: SQLHDBC) -> Self { DataSource { handle: Any::from_hdbc(HDbc::from_raw(raw)) } } /// Express state transiton fn transit<Other: HDbcWrapper<'env>>(self) -> DataSource<'env, Other> { DataSource { handle: Other::from_hdbc(self.handle.into_hdbc()) } } } impl<'env> DataSource<'env, Unconnected<'env>> { /// Allocates a new `DataSource`. A `DataSource` may not outlive its parent `Environment`. /// /// See [Allocating a Connection Handle ODBC][1] /// [1]: https://docs.microsoft.com/sql/odbc/reference/develop-app/allocating-a-connection-handle-odbc pub fn with_parent<V>(parent: &'env Environment<V>) -> Return<Self> where V: Version, { HDbc::allocate(parent.as_henv()).map(|handle| { DataSource { handle: Unconnected::from_hdbc(handle) } }) } /// Establishes connections to a driver and a data source. The connection handle references /// storage of all information about the connection to the data source, including status, /// transaction state, and error information. /// /// * See [Connecting with SQLConnect][1] /// * See [SQLConnectFunction][2] /// /// # State transition /// On success this method changes the Connection handles state from `Allocated` to `Connected` ///. Since this state change is expressed in the type system, the method consumes self. And /// returns a new instance in the result type. /// /// # Arguments /// /// * `data_source_name` - Data source name. The data might be located on the same computer as /// the program, or on another computer somewhere on a network. /// * `user` - User identifier. /// * `pwd` - Authenticatien string (typically the password). /// [1]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqlconnect-function /// [2]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqlconnect-function pub fn connect<DSN, U, P>( mut self, data_source_name: &DSN, user: &U, pwd: &P, ) -> Return<Connection<'env, AutocommitOn>, DataSource<'env, Unconnected<'env>>> where DSN: SqlStr +?Sized, U: SqlStr +?Sized, P: SqlStr +?Sized, { match self.handle.connect(data_source_name, user, pwd) { Success(()) => Success(self.transit()), Info(()) => Info(self.transit()), Error(()) => Error(self.transit()), } } /// Connects to a data source using a connection string. /// /// For the syntax regarding the connections string see [SQLDriverConnect][1]. This method is /// equivalent of calling `odbc_sys::SQLDriverConnect` with the `SQL_DRIVER_NOPROMPT` parameter. /// /// See [Choosing a Data Source or Driver][2] /// [1]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqldriverconnect-function /// [2]: https://docs.microsoft.com/sql/odbc/reference/develop-app/choosing-a-data-source-or-driver pub fn connect_with_connection_string<C>( mut self, connection_string: &C, ) -> Return<Connection<'env, AutocommitOn>, Self> where C: SqlStr +?Sized, { // We do not care for now. let mut out_connection_string = []; match self.handle.driver_connect( connection_string, &mut out_connection_string, SQL_DRIVER_NOPROMPT, ) { Success(_) => Success(self.transit()), Info(_) => Info(self.transit()), Error(()) => Error(self.transit()), } } } impl<'env, AC: AutocommitMode> Connection<'env, AC> { /// Used by `Statement`s constructor pub(crate) fn as_hdbc(&self) -> &HDbc { &self.handle } /// When an application has finished using a data source, it calls `disconnect`. `disconnect` /// disconnects the driver from the data source. /// /// * See [Disconnecting from a Data Source or Driver][1] /// * See [SQLDisconnect Function][2] /// [1]: https://docs.microsoft.com/sql/odbc/reference/develop-app/disconnecting-from-a-data-source-or-driver /// [2]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqldisconnect-function pub fn
(mut self) -> Return<DataSource<'env, Unconnected<'env>>, Connection<'env, AC>> { match self.handle.disconnect() { Success(()) => Success(self.transit()), Info(()) => Info(self.transit()), Error(()) => Error(self.transit()), } } /// `true` if the data source is set to READ ONLY mode, `false` otherwise. pub fn is_read_only(&mut self) -> Return<bool> { self.handle.is_read_only() } } impl<'env> Connection<'env, AutocommitOff> { /// Set autocommit mode on, per ODBC spec triggers implicit commit of any running transaction pub fn enable_autocommit(mut self) -> Return<Connection<'env, AutocommitOn>, Self> { match self.handle.set_autocommit(true) { Success(_) => Success(self.transit()), Info(_) => Info(self.transit()), Error(()) => Error(self.transit()), } } /// Commit transaction if any, can be safely called and will be no-op if no transaction present or autocommit mode is enabled pub fn commit(&mut self) -> Return<()> { self.handle.commit() } /// Rollback transaction if any, can be safely called and will be no-op if no transaction present or autocommit mode is enabled pub fn rollback(&mut self) -> Return<()> { self.handle.rollback() } } impl<'env> Connection<'env, AutocommitOn> { /// Set autocommit mode off pub fn disable_autocommit(mut self) -> Return<Connection<'env, AutocommitOff>, Self> { match self.handle.set_autocommit(false) { Success(_) => Success(self.transit()), Info(_) => Info(self.transit()), Error(()) => Error(self.transit()), } } } impl<'env, S> Diagnostics for DataSource<'env, S> where S: HDbcWrapper<'env>, { fn diagnostics( &self, rec_number: SQLSMALLINT, message_text: &mut [SQLCHAR], ) -> ReturnOption<DiagResult> { self.handle.diagnostics(rec_number, message_text) } }
disconnect
identifier_name
mod.rs
pub use self::connected::{Connected, AutocommitOff, AutocommitOn, AutocommitMode}; pub use self::hdbc_wrapper::HDbcWrapper; pub use self::unconnected::Unconnected; use super::*; use sys::*; use std::ops::DerefMut; mod connected; mod unconnected; mod hdbc_wrapper; /// A `DataSource` is used to query and manipulate a data source. /// /// * The state of the connection /// * The current connection-level diagnostics /// * The handles of statements and descriptors currently allocated on the connection /// * The current settings of each connection attribute /// /// # States /// /// A `DataSource` is in one of two states `Connected` or `Unconnected`. These are modeled in the /// type at compile time. Every new `DataSource` starts out as `Unconnected`. To execute a query it /// needs to be `Connected`. You can achieve this by calling e.g. `connect` and capture the result
/// See [Connection Handles in the ODBC Reference][1] /// [1]: https://docs.microsoft.com/sql/odbc/reference/develop-app/connection-handles #[derive(Debug)] pub struct DataSource<'env, S: HDbcWrapper<'env> = Unconnected<'env>> { /// Connection handle. Either `HDbc` for `Unconnected` or `Connected` for `Connected`. handle: S::Handle } impl<'env, Any> DataSource<'env, Any> where Any: HDbcWrapper<'env>, { /// Consumes the `DataSource`, returning the wrapped raw `SQLHDBC` /// /// Leaks the Connection Handle. This is usually done in order to pass ownership from Rust to /// another language. After calling this method, the caller is responsible for invoking /// `SQLFreeHandle`. pub fn into_raw(self) -> SQLHDBC { self.handle.into_hdbc().into_raw() } /// Provides access to the raw ODBC Connection Handle pub fn as_raw(&self) -> SQLHDBC { self.handle.as_raw() } /// May only be invoked with a valid Statement Handle which has been allocated using /// `SQLAllocHandle`. Special care must be taken that the Connection Handle passed is in a /// State which matches the type. pub unsafe fn from_raw(raw: SQLHDBC) -> Self { DataSource { handle: Any::from_hdbc(HDbc::from_raw(raw)) } } /// Express state transiton fn transit<Other: HDbcWrapper<'env>>(self) -> DataSource<'env, Other> { DataSource { handle: Other::from_hdbc(self.handle.into_hdbc()) } } } impl<'env> DataSource<'env, Unconnected<'env>> { /// Allocates a new `DataSource`. A `DataSource` may not outlive its parent `Environment`. /// /// See [Allocating a Connection Handle ODBC][1] /// [1]: https://docs.microsoft.com/sql/odbc/reference/develop-app/allocating-a-connection-handle-odbc pub fn with_parent<V>(parent: &'env Environment<V>) -> Return<Self> where V: Version, { HDbc::allocate(parent.as_henv()).map(|handle| { DataSource { handle: Unconnected::from_hdbc(handle) } }) } /// Establishes connections to a driver and a data source. The connection handle references /// storage of all information about the connection to the data source, including status, /// transaction state, and error information. /// /// * See [Connecting with SQLConnect][1] /// * See [SQLConnectFunction][2] /// /// # State transition /// On success this method changes the Connection handles state from `Allocated` to `Connected` ///. Since this state change is expressed in the type system, the method consumes self. And /// returns a new instance in the result type. /// /// # Arguments /// /// * `data_source_name` - Data source name. The data might be located on the same computer as /// the program, or on another computer somewhere on a network. /// * `user` - User identifier. /// * `pwd` - Authenticatien string (typically the password). /// [1]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqlconnect-function /// [2]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqlconnect-function pub fn connect<DSN, U, P>( mut self, data_source_name: &DSN, user: &U, pwd: &P, ) -> Return<Connection<'env, AutocommitOn>, DataSource<'env, Unconnected<'env>>> where DSN: SqlStr +?Sized, U: SqlStr +?Sized, P: SqlStr +?Sized, { match self.handle.connect(data_source_name, user, pwd) { Success(()) => Success(self.transit()), Info(()) => Info(self.transit()), Error(()) => Error(self.transit()), } } /// Connects to a data source using a connection string. /// /// For the syntax regarding the connections string see [SQLDriverConnect][1]. This method is /// equivalent of calling `odbc_sys::SQLDriverConnect` with the `SQL_DRIVER_NOPROMPT` parameter. /// /// See [Choosing a Data Source or Driver][2] /// [1]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqldriverconnect-function /// [2]: https://docs.microsoft.com/sql/odbc/reference/develop-app/choosing-a-data-source-or-driver pub fn connect_with_connection_string<C>( mut self, connection_string: &C, ) -> Return<Connection<'env, AutocommitOn>, Self> where C: SqlStr +?Sized, { // We do not care for now. let mut out_connection_string = []; match self.handle.driver_connect( connection_string, &mut out_connection_string, SQL_DRIVER_NOPROMPT, ) { Success(_) => Success(self.transit()), Info(_) => Info(self.transit()), Error(()) => Error(self.transit()), } } } impl<'env, AC: AutocommitMode> Connection<'env, AC> { /// Used by `Statement`s constructor pub(crate) fn as_hdbc(&self) -> &HDbc { &self.handle } /// When an application has finished using a data source, it calls `disconnect`. `disconnect` /// disconnects the driver from the data source. /// /// * See [Disconnecting from a Data Source or Driver][1] /// * See [SQLDisconnect Function][2] /// [1]: https://docs.microsoft.com/sql/odbc/reference/develop-app/disconnecting-from-a-data-source-or-driver /// [2]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqldisconnect-function pub fn disconnect(mut self) -> Return<DataSource<'env, Unconnected<'env>>, Connection<'env, AC>> { match self.handle.disconnect() { Success(()) => Success(self.transit()), Info(()) => Info(self.transit()), Error(()) => Error(self.transit()), } } /// `true` if the data source is set to READ ONLY mode, `false` otherwise. pub fn is_read_only(&mut self) -> Return<bool> { self.handle.is_read_only() } } impl<'env> Connection<'env, AutocommitOff> { /// Set autocommit mode on, per ODBC spec triggers implicit commit of any running transaction pub fn enable_autocommit(mut self) -> Return<Connection<'env, AutocommitOn>, Self> { match self.handle.set_autocommit(true) { Success(_) => Success(self.transit()), Info(_) => Info(self.transit()), Error(()) => Error(self.transit()), } } /// Commit transaction if any, can be safely called and will be no-op if no transaction present or autocommit mode is enabled pub fn commit(&mut self) -> Return<()> { self.handle.commit() } /// Rollback transaction if any, can be safely called and will be no-op if no transaction present or autocommit mode is enabled pub fn rollback(&mut self) -> Return<()> { self.handle.rollback() } } impl<'env> Connection<'env, AutocommitOn> { /// Set autocommit mode off pub fn disable_autocommit(mut self) -> Return<Connection<'env, AutocommitOff>, Self> { match self.handle.set_autocommit(false) { Success(_) => Success(self.transit()), Info(_) => Info(self.transit()), Error(()) => Error(self.transit()), } } } impl<'env, S> Diagnostics for DataSource<'env, S> where S: HDbcWrapper<'env>, { fn diagnostics( &self, rec_number: SQLSMALLINT, message_text: &mut [SQLCHAR], ) -> ReturnOption<DiagResult> { self.handle.diagnostics(rec_number, message_text) } }
/// in a new binding which will be of type `DataSource::<'env, Connected<'env>>`. ///
random_line_split
mod.rs
pub use self::connected::{Connected, AutocommitOff, AutocommitOn, AutocommitMode}; pub use self::hdbc_wrapper::HDbcWrapper; pub use self::unconnected::Unconnected; use super::*; use sys::*; use std::ops::DerefMut; mod connected; mod unconnected; mod hdbc_wrapper; /// A `DataSource` is used to query and manipulate a data source. /// /// * The state of the connection /// * The current connection-level diagnostics /// * The handles of statements and descriptors currently allocated on the connection /// * The current settings of each connection attribute /// /// # States /// /// A `DataSource` is in one of two states `Connected` or `Unconnected`. These are modeled in the /// type at compile time. Every new `DataSource` starts out as `Unconnected`. To execute a query it /// needs to be `Connected`. You can achieve this by calling e.g. `connect` and capture the result /// in a new binding which will be of type `DataSource::<'env, Connected<'env>>`. /// /// See [Connection Handles in the ODBC Reference][1] /// [1]: https://docs.microsoft.com/sql/odbc/reference/develop-app/connection-handles #[derive(Debug)] pub struct DataSource<'env, S: HDbcWrapper<'env> = Unconnected<'env>> { /// Connection handle. Either `HDbc` for `Unconnected` or `Connected` for `Connected`. handle: S::Handle } impl<'env, Any> DataSource<'env, Any> where Any: HDbcWrapper<'env>, { /// Consumes the `DataSource`, returning the wrapped raw `SQLHDBC` /// /// Leaks the Connection Handle. This is usually done in order to pass ownership from Rust to /// another language. After calling this method, the caller is responsible for invoking /// `SQLFreeHandle`. pub fn into_raw(self) -> SQLHDBC { self.handle.into_hdbc().into_raw() } /// Provides access to the raw ODBC Connection Handle pub fn as_raw(&self) -> SQLHDBC { self.handle.as_raw() } /// May only be invoked with a valid Statement Handle which has been allocated using /// `SQLAllocHandle`. Special care must be taken that the Connection Handle passed is in a /// State which matches the type. pub unsafe fn from_raw(raw: SQLHDBC) -> Self { DataSource { handle: Any::from_hdbc(HDbc::from_raw(raw)) } } /// Express state transiton fn transit<Other: HDbcWrapper<'env>>(self) -> DataSource<'env, Other> { DataSource { handle: Other::from_hdbc(self.handle.into_hdbc()) } } } impl<'env> DataSource<'env, Unconnected<'env>> { /// Allocates a new `DataSource`. A `DataSource` may not outlive its parent `Environment`. /// /// See [Allocating a Connection Handle ODBC][1] /// [1]: https://docs.microsoft.com/sql/odbc/reference/develop-app/allocating-a-connection-handle-odbc pub fn with_parent<V>(parent: &'env Environment<V>) -> Return<Self> where V: Version, { HDbc::allocate(parent.as_henv()).map(|handle| { DataSource { handle: Unconnected::from_hdbc(handle) } }) } /// Establishes connections to a driver and a data source. The connection handle references /// storage of all information about the connection to the data source, including status, /// transaction state, and error information. /// /// * See [Connecting with SQLConnect][1] /// * See [SQLConnectFunction][2] /// /// # State transition /// On success this method changes the Connection handles state from `Allocated` to `Connected` ///. Since this state change is expressed in the type system, the method consumes self. And /// returns a new instance in the result type. /// /// # Arguments /// /// * `data_source_name` - Data source name. The data might be located on the same computer as /// the program, or on another computer somewhere on a network. /// * `user` - User identifier. /// * `pwd` - Authenticatien string (typically the password). /// [1]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqlconnect-function /// [2]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqlconnect-function pub fn connect<DSN, U, P>( mut self, data_source_name: &DSN, user: &U, pwd: &P, ) -> Return<Connection<'env, AutocommitOn>, DataSource<'env, Unconnected<'env>>> where DSN: SqlStr +?Sized, U: SqlStr +?Sized, P: SqlStr +?Sized, { match self.handle.connect(data_source_name, user, pwd) { Success(()) => Success(self.transit()), Info(()) => Info(self.transit()), Error(()) => Error(self.transit()), } } /// Connects to a data source using a connection string. /// /// For the syntax regarding the connections string see [SQLDriverConnect][1]. This method is /// equivalent of calling `odbc_sys::SQLDriverConnect` with the `SQL_DRIVER_NOPROMPT` parameter. /// /// See [Choosing a Data Source or Driver][2] /// [1]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqldriverconnect-function /// [2]: https://docs.microsoft.com/sql/odbc/reference/develop-app/choosing-a-data-source-or-driver pub fn connect_with_connection_string<C>( mut self, connection_string: &C, ) -> Return<Connection<'env, AutocommitOn>, Self> where C: SqlStr +?Sized, { // We do not care for now. let mut out_connection_string = []; match self.handle.driver_connect( connection_string, &mut out_connection_string, SQL_DRIVER_NOPROMPT, ) { Success(_) => Success(self.transit()), Info(_) => Info(self.transit()), Error(()) => Error(self.transit()), } } } impl<'env, AC: AutocommitMode> Connection<'env, AC> { /// Used by `Statement`s constructor pub(crate) fn as_hdbc(&self) -> &HDbc { &self.handle } /// When an application has finished using a data source, it calls `disconnect`. `disconnect` /// disconnects the driver from the data source. /// /// * See [Disconnecting from a Data Source or Driver][1] /// * See [SQLDisconnect Function][2] /// [1]: https://docs.microsoft.com/sql/odbc/reference/develop-app/disconnecting-from-a-data-source-or-driver /// [2]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqldisconnect-function pub fn disconnect(mut self) -> Return<DataSource<'env, Unconnected<'env>>, Connection<'env, AC>> { match self.handle.disconnect() { Success(()) => Success(self.transit()), Info(()) => Info(self.transit()), Error(()) => Error(self.transit()), } } /// `true` if the data source is set to READ ONLY mode, `false` otherwise. pub fn is_read_only(&mut self) -> Return<bool>
} impl<'env> Connection<'env, AutocommitOff> { /// Set autocommit mode on, per ODBC spec triggers implicit commit of any running transaction pub fn enable_autocommit(mut self) -> Return<Connection<'env, AutocommitOn>, Self> { match self.handle.set_autocommit(true) { Success(_) => Success(self.transit()), Info(_) => Info(self.transit()), Error(()) => Error(self.transit()), } } /// Commit transaction if any, can be safely called and will be no-op if no transaction present or autocommit mode is enabled pub fn commit(&mut self) -> Return<()> { self.handle.commit() } /// Rollback transaction if any, can be safely called and will be no-op if no transaction present or autocommit mode is enabled pub fn rollback(&mut self) -> Return<()> { self.handle.rollback() } } impl<'env> Connection<'env, AutocommitOn> { /// Set autocommit mode off pub fn disable_autocommit(mut self) -> Return<Connection<'env, AutocommitOff>, Self> { match self.handle.set_autocommit(false) { Success(_) => Success(self.transit()), Info(_) => Info(self.transit()), Error(()) => Error(self.transit()), } } } impl<'env, S> Diagnostics for DataSource<'env, S> where S: HDbcWrapper<'env>, { fn diagnostics( &self, rec_number: SQLSMALLINT, message_text: &mut [SQLCHAR], ) -> ReturnOption<DiagResult> { self.handle.diagnostics(rec_number, message_text) } }
{ self.handle.is_read_only() }
identifier_body
gradient.rs
extern crate meta_diff; fn
(nodes_before: usize, nodes_after: usize, source: &str){ let result = meta_diff::core::parseMetaFile(source); let mut graph = match result { Ok(g) => g, Err(msg) => {return assert!(false, "{}", msg);} }; assert!(graph.len() == nodes_before, "Number of the initial graph nodes expected: {}, was: {}", nodes_before, graph.len()); match graph.direct_gradient(){ Ok(_) => { if graph.len() == nodes_after { assert!(true); } else { match meta_diff::codegen::write_graphviz(&mut ::std::io::stdout(), &graph){ Ok(_) => (), Err(msg) => assert!(false, "{}", msg) } println!("{}",graph); assert!(false, "Number of the nodes after gradient - expected: {}, was: {}", nodes_after, graph.len()); } }, Err(msg) => assert!(false, "{}", msg) } } // fn grad_fail(fail_msg: &str, source: &str){ // let result = meta_diff::core::parseMetaFile(source); // match result { // Ok(_) => { // assert!(false, "Fail parsed, but should have failed."); // } // Err(msg) => { // assert!(format!("{}",msg) == fail_msg,format!("Parser failed message expected: {}, was: {}", fail_msg, msg)); // } // } // } parametarise_test!(grad_ok,{ 8,8, "function [d] = mat(a,b) c = a + b * a'; d = l2(c,0) * l1(c,0); end" },{ 14,37, "function [L] = mat(@w,x,y) h = tanh(w*vertcat(x,1)); h = tanh(w*vertcat(h,1)); L = l2(h-y,0); end" },{ 14,23, "function [L] = mat(@w,x,y) h = tanh(w*vertcat(x,1)); s = sinh(w*horzcat(h,1)); L = l1(h-y,0); end" },{ 10,18, "function [L] = mat(@w,x,y,@z) h = w + x dot y * z; L = sum(h^2,0); end" },{ 14,19, "function [L] = mat(@w,x,y) h = const(w*vertcat(x,1)); s = vdiag(w*horzcat(h,1)); L = l1(s-h,0); end" }); // parametarise_test!(grad_fail, // ["Error at 2:7: Use of undefined variable \'d\'", // "function [d] = mat(a,b) // c = d + b * a'; // d = l2(c,0) * l1(c,0); // end" ], // ["Error at 3:28: Can not have a variable with name \'sin\' since it is a built in function", // "function [L] = mat(@w,x,y) // h = tanh(w*vertcat(x,1)); // sin = tanh(w*vertcat(h,1)); // L = l2(h-y,0); // end"], // ["Error at 4:13: Comparison operators not supported!", // "function [L] = mat(@w,x,y) // h = tanh(w*vertcat(x,1)); // s = sinh(w*horzcat(h,1)); // L = l1(h>=y,0); // end"], // ["Error at 4:5: Output variable \'k\' has not been defined", // "function [L,k] = mat(@w,x,y,@z) // h = w + x dot y * z; // L = sum(h^2,0); // end"], // ["Error at 2:29: HorzCat takes at least two arguments", // "function [L] = mat(@w,x,y) // h = horzcat(w*-vertcat(x,1)); // s = diagV(w*horzcat(h,1)); // L = l1(s-h,0); // end"] // );
grad_ok
identifier_name
gradient.rs
extern crate meta_diff; fn grad_ok(nodes_before: usize, nodes_after: usize, source: &str){ let result = meta_diff::core::parseMetaFile(source); let mut graph = match result { Ok(g) => g, Err(msg) => {return assert!(false, "{}", msg);} }; assert!(graph.len() == nodes_before, "Number of the initial graph nodes expected: {}, was: {}", nodes_before, graph.len()); match graph.direct_gradient(){ Ok(_) => { if graph.len() == nodes_after { assert!(true); } else { match meta_diff::codegen::write_graphviz(&mut ::std::io::stdout(), &graph){ Ok(_) => (), Err(msg) => assert!(false, "{}", msg) } println!("{}",graph); assert!(false, "Number of the nodes after gradient - expected: {}, was: {}", nodes_after, graph.len()); } }, Err(msg) => assert!(false, "{}", msg) } } // fn grad_fail(fail_msg: &str, source: &str){ // let result = meta_diff::core::parseMetaFile(source); // match result { // Ok(_) => { // assert!(false, "Fail parsed, but should have failed."); // } // Err(msg) => { // assert!(format!("{}",msg) == fail_msg,format!("Parser failed message expected: {}, was: {}", fail_msg, msg)); // } // } // } parametarise_test!(grad_ok,{ 8,8, "function [d] = mat(a,b) c = a + b * a'; d = l2(c,0) * l1(c,0); end" },{ 14,37, "function [L] = mat(@w,x,y) h = tanh(w*vertcat(x,1)); h = tanh(w*vertcat(h,1)); L = l2(h-y,0); end" },{ 14,23, "function [L] = mat(@w,x,y) h = tanh(w*vertcat(x,1)); s = sinh(w*horzcat(h,1)); L = l1(h-y,0); end" },{ 10,18, "function [L] = mat(@w,x,y,@z) h = w + x dot y * z; L = sum(h^2,0); end" },{
end" }); // parametarise_test!(grad_fail, // ["Error at 2:7: Use of undefined variable \'d\'", // "function [d] = mat(a,b) // c = d + b * a'; // d = l2(c,0) * l1(c,0); // end" ], // ["Error at 3:28: Can not have a variable with name \'sin\' since it is a built in function", // "function [L] = mat(@w,x,y) // h = tanh(w*vertcat(x,1)); // sin = tanh(w*vertcat(h,1)); // L = l2(h-y,0); // end"], // ["Error at 4:13: Comparison operators not supported!", // "function [L] = mat(@w,x,y) // h = tanh(w*vertcat(x,1)); // s = sinh(w*horzcat(h,1)); // L = l1(h>=y,0); // end"], // ["Error at 4:5: Output variable \'k\' has not been defined", // "function [L,k] = mat(@w,x,y,@z) // h = w + x dot y * z; // L = sum(h^2,0); // end"], // ["Error at 2:29: HorzCat takes at least two arguments", // "function [L] = mat(@w,x,y) // h = horzcat(w*-vertcat(x,1)); // s = diagV(w*horzcat(h,1)); // L = l1(s-h,0); // end"] // );
14,19, "function [L] = mat(@w,x,y) h = const(w*vertcat(x,1)); s = vdiag(w*horzcat(h,1)); L = l1(s-h,0);
random_line_split
gradient.rs
extern crate meta_diff; fn grad_ok(nodes_before: usize, nodes_after: usize, source: &str){ let result = meta_diff::core::parseMetaFile(source); let mut graph = match result { Ok(g) => g, Err(msg) => {return assert!(false, "{}", msg);} }; assert!(graph.len() == nodes_before, "Number of the initial graph nodes expected: {}, was: {}", nodes_before, graph.len()); match graph.direct_gradient(){ Ok(_) => { if graph.len() == nodes_after
else { match meta_diff::codegen::write_graphviz(&mut ::std::io::stdout(), &graph){ Ok(_) => (), Err(msg) => assert!(false, "{}", msg) } println!("{}",graph); assert!(false, "Number of the nodes after gradient - expected: {}, was: {}", nodes_after, graph.len()); } }, Err(msg) => assert!(false, "{}", msg) } } // fn grad_fail(fail_msg: &str, source: &str){ // let result = meta_diff::core::parseMetaFile(source); // match result { // Ok(_) => { // assert!(false, "Fail parsed, but should have failed."); // } // Err(msg) => { // assert!(format!("{}",msg) == fail_msg,format!("Parser failed message expected: {}, was: {}", fail_msg, msg)); // } // } // } parametarise_test!(grad_ok,{ 8,8, "function [d] = mat(a,b) c = a + b * a'; d = l2(c,0) * l1(c,0); end" },{ 14,37, "function [L] = mat(@w,x,y) h = tanh(w*vertcat(x,1)); h = tanh(w*vertcat(h,1)); L = l2(h-y,0); end" },{ 14,23, "function [L] = mat(@w,x,y) h = tanh(w*vertcat(x,1)); s = sinh(w*horzcat(h,1)); L = l1(h-y,0); end" },{ 10,18, "function [L] = mat(@w,x,y,@z) h = w + x dot y * z; L = sum(h^2,0); end" },{ 14,19, "function [L] = mat(@w,x,y) h = const(w*vertcat(x,1)); s = vdiag(w*horzcat(h,1)); L = l1(s-h,0); end" }); // parametarise_test!(grad_fail, // ["Error at 2:7: Use of undefined variable \'d\'", // "function [d] = mat(a,b) // c = d + b * a'; // d = l2(c,0) * l1(c,0); // end" ], // ["Error at 3:28: Can not have a variable with name \'sin\' since it is a built in function", // "function [L] = mat(@w,x,y) // h = tanh(w*vertcat(x,1)); // sin = tanh(w*vertcat(h,1)); // L = l2(h-y,0); // end"], // ["Error at 4:13: Comparison operators not supported!", // "function [L] = mat(@w,x,y) // h = tanh(w*vertcat(x,1)); // s = sinh(w*horzcat(h,1)); // L = l1(h>=y,0); // end"], // ["Error at 4:5: Output variable \'k\' has not been defined", // "function [L,k] = mat(@w,x,y,@z) // h = w + x dot y * z; // L = sum(h^2,0); // end"], // ["Error at 2:29: HorzCat takes at least two arguments", // "function [L] = mat(@w,x,y) // h = horzcat(w*-vertcat(x,1)); // s = diagV(w*horzcat(h,1)); // L = l1(s-h,0); // end"] // );
{ assert!(true); }
conditional_block
gradient.rs
extern crate meta_diff; fn grad_ok(nodes_before: usize, nodes_after: usize, source: &str)
}, Err(msg) => assert!(false, "{}", msg) } } // fn grad_fail(fail_msg: &str, source: &str){ // let result = meta_diff::core::parseMetaFile(source); // match result { // Ok(_) => { // assert!(false, "Fail parsed, but should have failed."); // } // Err(msg) => { // assert!(format!("{}",msg) == fail_msg,format!("Parser failed message expected: {}, was: {}", fail_msg, msg)); // } // } // } parametarise_test!(grad_ok,{ 8,8, "function [d] = mat(a,b) c = a + b * a'; d = l2(c,0) * l1(c,0); end" },{ 14,37, "function [L] = mat(@w,x,y) h = tanh(w*vertcat(x,1)); h = tanh(w*vertcat(h,1)); L = l2(h-y,0); end" },{ 14,23, "function [L] = mat(@w,x,y) h = tanh(w*vertcat(x,1)); s = sinh(w*horzcat(h,1)); L = l1(h-y,0); end" },{ 10,18, "function [L] = mat(@w,x,y,@z) h = w + x dot y * z; L = sum(h^2,0); end" },{ 14,19, "function [L] = mat(@w,x,y) h = const(w*vertcat(x,1)); s = vdiag(w*horzcat(h,1)); L = l1(s-h,0); end" }); // parametarise_test!(grad_fail, // ["Error at 2:7: Use of undefined variable \'d\'", // "function [d] = mat(a,b) // c = d + b * a'; // d = l2(c,0) * l1(c,0); // end" ], // ["Error at 3:28: Can not have a variable with name \'sin\' since it is a built in function", // "function [L] = mat(@w,x,y) // h = tanh(w*vertcat(x,1)); // sin = tanh(w*vertcat(h,1)); // L = l2(h-y,0); // end"], // ["Error at 4:13: Comparison operators not supported!", // "function [L] = mat(@w,x,y) // h = tanh(w*vertcat(x,1)); // s = sinh(w*horzcat(h,1)); // L = l1(h>=y,0); // end"], // ["Error at 4:5: Output variable \'k\' has not been defined", // "function [L,k] = mat(@w,x,y,@z) // h = w + x dot y * z; // L = sum(h^2,0); // end"], // ["Error at 2:29: HorzCat takes at least two arguments", // "function [L] = mat(@w,x,y) // h = horzcat(w*-vertcat(x,1)); // s = diagV(w*horzcat(h,1)); // L = l1(s-h,0); // end"] // );
{ let result = meta_diff::core::parseMetaFile(source); let mut graph = match result { Ok(g) => g, Err(msg) => {return assert!(false, "{}", msg);} }; assert!(graph.len() == nodes_before, "Number of the initial graph nodes expected: {}, was: {}", nodes_before, graph.len()); match graph.direct_gradient(){ Ok(_) => { if graph.len() == nodes_after { assert!(true); } else { match meta_diff::codegen::write_graphviz(&mut ::std::io::stdout() , &graph){ Ok(_) => (), Err(msg) => assert!(false, "{}", msg) } println!("{}",graph); assert!(false, "Number of the nodes after gradient - expected: {}, was: {}", nodes_after, graph.len()); }
identifier_body
convolve3x3.rs
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ip.rsh" #pragma rs_fp_relaxed int32_t gWidth; int32_t gHeight; rs_allocation gIn; float gCoeffs[9]; uchar4 RS_KERNEL root(uint32_t x, uint32_t y) { uint32_t x1 = min((int32_t)x+1, gWidth-1);
uint32_t y2 = max((int32_t)y-1, 0); float4 sum = convert_float4(rsGetElementAt_uchar4(gIn, x1, y1)) * gCoeffs[0]; sum += convert_float4(rsGetElementAt_uchar4(gIn, x, y1)) * gCoeffs[1]; sum += convert_float4(rsGetElementAt_uchar4(gIn, x2, y1)) * gCoeffs[2]; sum += convert_float4(rsGetElementAt_uchar4(gIn, x1, y)) * gCoeffs[3]; sum += convert_float4(rsGetElementAt_uchar4(gIn, x, y)) * gCoeffs[4]; sum += convert_float4(rsGetElementAt_uchar4(gIn, x2, y)) * gCoeffs[5]; sum += convert_float4(rsGetElementAt_uchar4(gIn, x1, y2)) * gCoeffs[6]; sum += convert_float4(rsGetElementAt_uchar4(gIn, x, y2)) * gCoeffs[7]; sum += convert_float4(rsGetElementAt_uchar4(gIn, x2, y2)) * gCoeffs[8]; sum = clamp(sum, 0.f, 255.f); return convert_uchar4(sum); }
uint32_t x2 = max((int32_t)x-1, 0); uint32_t y1 = min((int32_t)y+1, gHeight-1);
random_line_split
callee.rs
{ llfn: ValueRef, } pub struct MethodData { llfn: ValueRef, llself: ValueRef, temp_cleanup: Option<ValueRef>, self_ty: ty::t, self_mode: ty::SelfMode, } pub enum CalleeData { Closure(Datum), Fn(FnData), Method(MethodData) } pub struct Callee { bcx: block, data: CalleeData } pub fn trans(bcx: block, expr: @ast::expr) -> Callee { let _icx = push_ctxt("trans_callee"); debug!("callee::trans(expr=%s)", expr.repr(bcx.tcx())); // pick out special kinds of expressions that can be called: match expr.node { ast::expr_path(_) => { return trans_def(bcx, bcx.def(expr.id), expr); } _ => {} } // any other expressions are closures: return datum_callee(bcx, expr); fn datum_callee(bcx: block, expr: @ast::expr) -> Callee { let DatumBlock {bcx, datum} = expr::trans_to_datum(bcx, expr); match ty::get(datum.ty).sty { ty::ty_bare_fn(*) => { let llval = datum.to_appropriate_llval(bcx); return Callee {bcx: bcx, data: Fn(FnData {llfn: llval})}; } ty::ty_closure(*) => { return Callee {bcx: bcx, data: Closure(datum)}; } _ => { bcx.tcx().sess.span_bug( expr.span, fmt!("Type of callee is neither bare-fn nor closure: %s", bcx.ty_to_str(datum.ty))); } } } fn fn_callee(bcx: block, fd: FnData) -> Callee { return Callee {bcx: bcx, data: Fn(fd)}; } fn trans_def(bcx: block, def: ast::def, ref_expr: @ast::expr) -> Callee { match def { ast::def_fn(did, _) | ast::def_static_method(did, None, _) => { fn_callee(bcx, trans_fn_ref(bcx, did, ref_expr.id)) } ast::def_static_method(impl_did, Some(trait_did), _) => { fn_callee(bcx, meth::trans_static_method_callee(bcx, impl_did, trait_did, ref_expr.id)) } ast::def_variant(tid, vid) => { // nullary variants are not callable assert!(ty::enum_variant_with_id(bcx.tcx(), tid, vid).args.len() > 0u); fn_callee(bcx, trans_fn_ref(bcx, vid, ref_expr.id)) } ast::def_struct(def_id) => { fn_callee(bcx, trans_fn_ref(bcx, def_id, ref_expr.id)) } ast::def_arg(*) | ast::def_local(*) | ast::def_binding(*) | ast::def_upvar(*) | ast::def_self(*) => { datum_callee(bcx, ref_expr) } ast::def_mod(*) | ast::def_foreign_mod(*) | ast::def_trait(*) | ast::def_static(*) | ast::def_ty(*) | ast::def_prim_ty(*) | ast::def_use(*) | ast::def_typaram_binder(*) | ast::def_region(*) | ast::def_label(*) | ast::def_ty_param(*) | ast::def_self_ty(*) | ast::def_method(*) => { bcx.tcx().sess.span_bug( ref_expr.span, fmt!("Cannot translate def %? \ to a callable thing!", def)); } } } } pub fn trans_fn_ref_to_callee(bcx: block, def_id: ast::def_id, ref_id: ast::node_id) -> Callee { Callee {bcx: bcx, data: Fn(trans_fn_ref(bcx, def_id, ref_id))} } pub fn trans_fn_ref(bcx: block, def_id: ast::def_id, ref_id: ast::node_id) -> FnData { /*! * * Translates a reference (with id `ref_id`) to the fn/method * with id `def_id` into a function pointer. This may require * monomorphization or inlining. */ let _icx = push_ctxt("trans_fn_ref"); let type_params = node_id_type_params(bcx, ref_id); let vtables = node_vtables(bcx, ref_id); debug!("trans_fn_ref(def_id=%s, ref_id=%?, type_params=%s, vtables=%s)", def_id.repr(bcx.tcx()), ref_id, type_params.repr(bcx.tcx()), vtables.repr(bcx.tcx())); trans_fn_ref_with_vtables(bcx, def_id, ref_id, type_params, vtables) } pub fn trans_fn_ref_with_vtables_to_callee( bcx: block, def_id: ast::def_id, ref_id: ast::node_id, type_params: &[ty::t], vtables: Option<typeck::vtable_res>) -> Callee { Callee {bcx: bcx, data: Fn(trans_fn_ref_with_vtables(bcx, def_id, ref_id, type_params, vtables))} } fn get_impl_resolutions(bcx: block, impl_id: ast::def_id) -> typeck::vtable_res { if impl_id.crate == ast::local_crate { *bcx.ccx().maps.vtable_map.get(&impl_id.node) } else { // XXX: This is a temporary hack to work around not properly // exporting information about resolutions for impls. // This doesn't actually work if the trait has param bounds, // but it does allow us to survive the case when it does not. let trait_ref = ty::impl_trait_ref(bcx.tcx(), impl_id).get(); @vec::from_elem(trait_ref.substs.tps.len(), @~[]) } } fn resolve_default_method_vtables(bcx: block, impl_id: ast::def_id, method: &ty::Method, substs: &ty::substs, impl_vtables: Option<typeck::vtable_res>) -> typeck::vtable_res { // Get the vtables that the impl implements the trait at let trait_vtables = get_impl_resolutions(bcx, impl_id); // Build up a param_substs that we are going to resolve the // trait_vtables under. let param_substs = Some(@param_substs { tys: copy substs.tps, self_ty: substs.self_ty, vtables: impl_vtables, self_vtable: None }); let trait_vtables_fixed = resolve_vtables_under_param_substs( bcx.tcx(), param_substs, trait_vtables); // Now we pull any vtables for parameters on the actual method. let num_method_vtables = method.generics.type_param_defs.len(); let method_vtables = match impl_vtables { Some(vtables) => { let num_impl_type_parameters = vtables.len() - num_method_vtables; vtables.tailn(num_impl_type_parameters).to_owned() }, None => vec::from_elem(num_method_vtables, @~[]) }; @(*trait_vtables_fixed + method_vtables) } pub fn trans_fn_ref_with_vtables( bcx: block, // def_id: ast::def_id, // def id of fn ref_id: ast::node_id, // node id of use of fn; may be zero if N/A type_params: &[ty::t], // values for fn's ty params vtables: Option<typeck::vtable_res>) -> FnData { //! // // Translates a reference to a fn/method item, monomorphizing and // inlining as it goes. // // # Parameters // // - `bcx`: the current block where the reference to the fn occurs // - `def_id`: def id of the fn or method item being referenced // - `ref_id`: node id of the reference to the fn/method, if applicable. // This parameter may be zero; but, if so, the resulting value may not // have the right type, so it must be cast before being used. // - `type_params`: values for each of the fn/method's type parameters // - `vtables`: values for each bound on each of the type parameters let _icx = push_ctxt("trans_fn_ref_with_vtables"); let ccx = bcx.ccx(); let tcx = ccx.tcx; debug!("trans_fn_ref_with_vtables(bcx=%s, def_id=%s, ref_id=%?, \ type_params=%s, vtables=%s)", bcx.to_str(), def_id.repr(bcx.tcx()), ref_id, type_params.repr(bcx.tcx()), vtables.repr(bcx.tcx())); assert!(type_params.iter().all(|t|!ty::type_needs_infer(*t))); // Polytype of the function item (may have type params) let fn_tpt = ty::lookup_item_type(tcx, def_id); // For simplicity, we want to use the Subst trait when composing // substitutions for default methods. The subst trait does // substitutions with regions, though, so we put a dummy self // region parameter in to keep it from failing. This is a hack. let substs = ty::substs { self_r: Some(ty::re_empty), self_ty: None, tps: /*bad*/ type_params.to_owned() }; // We need to do a bunch of special handling for default methods. // We need to modify the def_id and our substs in order to monomorphize // the function. let (def_id, opt_impl_did, substs, self_vtable, vtables) = match tcx.provided_method_sources.find(&def_id) { None => (def_id, None, substs, None, vtables), Some(source) => { // There are two relevant substitutions when compiling // default methods. First, there is the substitution for // the type parameters of the impl we are using and the // method we are calling. This substitution is the substs // argument we already have. // In order to compile a default method, though, we need // to consider another substitution: the substitution for // the type parameters on trait; the impl we are using // implements the trait at some particular type // parameters, and we need to substitute for those first. // So, what we need to do is find this substitution and // compose it with the one we already have. let trait_ref = ty::impl_trait_ref(tcx, source.impl_id) .expect("could not find trait_ref for impl with \ default methods"); let method = ty::method(tcx, source.method_id); // Get all of the type params for the receiver let param_defs = method.generics.type_param_defs; let receiver_substs = type_params.initn(param_defs.len()).to_owned(); let receiver_vtables = match vtables { None => @~[], Some(call_vtables) => { @call_vtables.initn(param_defs.len()).to_owned() } }; let self_vtable = typeck::vtable_static(source.impl_id, receiver_substs, receiver_vtables); // Compute the first substitution let first_subst = make_substs_for_receiver_types( tcx, source.impl_id, trait_ref, method); // And compose them let new_substs = first_subst.subst(tcx, &substs); let vtables = resolve_default_method_vtables(bcx, source.impl_id, method, &new_substs, vtables); debug!("trans_fn_with_vtables - default method: \ substs = %s, trait_subst = %s, \ first_subst = %s, new_subst = %s, \ self_vtable = %s, vtables = %s", substs.repr(tcx), trait_ref.substs.repr(tcx), first_subst.repr(tcx), new_substs.repr(tcx), self_vtable.repr(tcx), vtables.repr(tcx)); (source.method_id, Some(source.impl_id), new_substs, Some(self_vtable), Some(vtables)) } }; // Check whether this fn has an inlined copy and, if so, redirect // def_id to the local id of the inlined copy. let def_id = { if def_id.crate!= ast::local_crate { let may_translate = opt_impl_did.is_none(); inline::maybe_instantiate_inline(ccx, def_id, may_translate) } else { def_id } }; // We must monomorphise if the fn has type parameters, is a rust // intrinsic, or is a default method. In particular, if we see an // intrinsic that is inlined from a different crate, we want to reemit the // intrinsic instead of trying to call it in the other crate. let must_monomorphise; if type_params.len() > 0 || opt_impl_did.is_some() { must_monomorphise = true; } else if def_id.crate == ast::local_crate { let map_node = session::expect( ccx.sess, ccx.tcx.items.find(&def_id.node), || fmt!("local item should be in ast map")); match *map_node { ast_map::node_foreign_item(_, abis, _, _) => { must_monomorphise = abis.is_intrinsic() } _ => { must_monomorphise = false; } } } else { must_monomorphise = false; } // Create a monomorphic verison of generic functions if must_monomorphise { // Should be either intra-crate or inlined. assert_eq!(def_id.crate, ast::local_crate); let (val, must_cast) = monomorphize::monomorphic_fn(ccx, def_id, &substs, vtables, self_vtable, opt_impl_did, Some(ref_id)); let mut val = val; if must_cast && ref_id!= 0 { // Monotype of the REFERENCE to the function (type params // are subst'd) let ref_ty = common::node_id_type(bcx, ref_id); val = PointerCast( bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to()); } return FnData {llfn: val}; } // Find the actual function pointer. let val = { if def_id.crate == ast::local_crate { // Internal reference. get_item_val(ccx, def_id.node) } else { // External reference. trans_external_path(ccx, def_id, fn_tpt.ty) } }; return FnData {llfn: val}; } // ______________________________________________________________________ // Translating calls pub fn trans_call(in_cx: block, call_ex: @ast::expr, f: @ast::expr, args: CallArgs, id: ast::node_id, dest: expr::Dest) -> block { let _icx = push_ctxt("trans_call"); trans_call_inner(in_cx, call_ex.info(), expr_ty(in_cx, f), node_id_type(in_cx, id), |cx| trans(cx, f), args, dest, DontAutorefArg) } pub fn trans_method_call(in_cx: block, call_ex: @ast::expr, callee_id: ast::node_id, rcvr: @ast::expr, args: CallArgs, dest: expr::Dest) -> block { let _icx = push_ctxt("trans_method_call"); debug!("trans_method_call(call_ex=%s, rcvr=%s)", call_ex.repr(in_cx.tcx()), rcvr.repr(in_cx.tcx())); trans_call_inner( in_cx, call_ex.info(), node_id_type(in_cx, callee_id), expr_ty(in_cx, call_ex), |cx| { match cx.ccx().maps.method_map.find_copy(&call_ex.id) { Some(origin) => { debug!("origin for %s: %s", call_ex.repr(in_cx.tcx()), origin.repr(in_cx.tcx())); meth::trans_method_callee(cx, callee_id, rcvr, origin) } None => {
FnData
identifier_name
callee.rs
for impls. // This doesn't actually work if the trait has param bounds, // but it does allow us to survive the case when it does not. let trait_ref = ty::impl_trait_ref(bcx.tcx(), impl_id).get(); @vec::from_elem(trait_ref.substs.tps.len(), @~[]) } } fn resolve_default_method_vtables(bcx: block, impl_id: ast::def_id, method: &ty::Method, substs: &ty::substs, impl_vtables: Option<typeck::vtable_res>) -> typeck::vtable_res { // Get the vtables that the impl implements the trait at let trait_vtables = get_impl_resolutions(bcx, impl_id); // Build up a param_substs that we are going to resolve the // trait_vtables under. let param_substs = Some(@param_substs { tys: copy substs.tps, self_ty: substs.self_ty, vtables: impl_vtables, self_vtable: None }); let trait_vtables_fixed = resolve_vtables_under_param_substs( bcx.tcx(), param_substs, trait_vtables); // Now we pull any vtables for parameters on the actual method. let num_method_vtables = method.generics.type_param_defs.len(); let method_vtables = match impl_vtables { Some(vtables) => { let num_impl_type_parameters = vtables.len() - num_method_vtables; vtables.tailn(num_impl_type_parameters).to_owned() }, None => vec::from_elem(num_method_vtables, @~[]) }; @(*trait_vtables_fixed + method_vtables) } pub fn trans_fn_ref_with_vtables( bcx: block, // def_id: ast::def_id, // def id of fn ref_id: ast::node_id, // node id of use of fn; may be zero if N/A type_params: &[ty::t], // values for fn's ty params vtables: Option<typeck::vtable_res>) -> FnData { //! // // Translates a reference to a fn/method item, monomorphizing and // inlining as it goes. // // # Parameters // // - `bcx`: the current block where the reference to the fn occurs // - `def_id`: def id of the fn or method item being referenced // - `ref_id`: node id of the reference to the fn/method, if applicable. // This parameter may be zero; but, if so, the resulting value may not // have the right type, so it must be cast before being used. // - `type_params`: values for each of the fn/method's type parameters // - `vtables`: values for each bound on each of the type parameters let _icx = push_ctxt("trans_fn_ref_with_vtables"); let ccx = bcx.ccx(); let tcx = ccx.tcx; debug!("trans_fn_ref_with_vtables(bcx=%s, def_id=%s, ref_id=%?, \ type_params=%s, vtables=%s)", bcx.to_str(), def_id.repr(bcx.tcx()), ref_id, type_params.repr(bcx.tcx()), vtables.repr(bcx.tcx())); assert!(type_params.iter().all(|t|!ty::type_needs_infer(*t))); // Polytype of the function item (may have type params) let fn_tpt = ty::lookup_item_type(tcx, def_id); // For simplicity, we want to use the Subst trait when composing // substitutions for default methods. The subst trait does // substitutions with regions, though, so we put a dummy self // region parameter in to keep it from failing. This is a hack. let substs = ty::substs { self_r: Some(ty::re_empty), self_ty: None, tps: /*bad*/ type_params.to_owned() }; // We need to do a bunch of special handling for default methods. // We need to modify the def_id and our substs in order to monomorphize // the function. let (def_id, opt_impl_did, substs, self_vtable, vtables) = match tcx.provided_method_sources.find(&def_id) { None => (def_id, None, substs, None, vtables), Some(source) => { // There are two relevant substitutions when compiling // default methods. First, there is the substitution for // the type parameters of the impl we are using and the // method we are calling. This substitution is the substs // argument we already have. // In order to compile a default method, though, we need // to consider another substitution: the substitution for // the type parameters on trait; the impl we are using // implements the trait at some particular type // parameters, and we need to substitute for those first. // So, what we need to do is find this substitution and // compose it with the one we already have. let trait_ref = ty::impl_trait_ref(tcx, source.impl_id) .expect("could not find trait_ref for impl with \ default methods"); let method = ty::method(tcx, source.method_id); // Get all of the type params for the receiver let param_defs = method.generics.type_param_defs; let receiver_substs = type_params.initn(param_defs.len()).to_owned(); let receiver_vtables = match vtables { None => @~[], Some(call_vtables) => { @call_vtables.initn(param_defs.len()).to_owned() } }; let self_vtable = typeck::vtable_static(source.impl_id, receiver_substs, receiver_vtables); // Compute the first substitution let first_subst = make_substs_for_receiver_types( tcx, source.impl_id, trait_ref, method); // And compose them let new_substs = first_subst.subst(tcx, &substs); let vtables = resolve_default_method_vtables(bcx, source.impl_id, method, &new_substs, vtables); debug!("trans_fn_with_vtables - default method: \ substs = %s, trait_subst = %s, \ first_subst = %s, new_subst = %s, \ self_vtable = %s, vtables = %s", substs.repr(tcx), trait_ref.substs.repr(tcx), first_subst.repr(tcx), new_substs.repr(tcx), self_vtable.repr(tcx), vtables.repr(tcx)); (source.method_id, Some(source.impl_id), new_substs, Some(self_vtable), Some(vtables)) } }; // Check whether this fn has an inlined copy and, if so, redirect // def_id to the local id of the inlined copy. let def_id = { if def_id.crate!= ast::local_crate { let may_translate = opt_impl_did.is_none(); inline::maybe_instantiate_inline(ccx, def_id, may_translate) } else { def_id } }; // We must monomorphise if the fn has type parameters, is a rust // intrinsic, or is a default method. In particular, if we see an // intrinsic that is inlined from a different crate, we want to reemit the // intrinsic instead of trying to call it in the other crate. let must_monomorphise; if type_params.len() > 0 || opt_impl_did.is_some() { must_monomorphise = true; } else if def_id.crate == ast::local_crate { let map_node = session::expect( ccx.sess, ccx.tcx.items.find(&def_id.node), || fmt!("local item should be in ast map")); match *map_node { ast_map::node_foreign_item(_, abis, _, _) => { must_monomorphise = abis.is_intrinsic() } _ => { must_monomorphise = false; } } } else { must_monomorphise = false; } // Create a monomorphic verison of generic functions if must_monomorphise { // Should be either intra-crate or inlined. assert_eq!(def_id.crate, ast::local_crate); let (val, must_cast) = monomorphize::monomorphic_fn(ccx, def_id, &substs, vtables, self_vtable, opt_impl_did, Some(ref_id)); let mut val = val; if must_cast && ref_id!= 0 { // Monotype of the REFERENCE to the function (type params // are subst'd) let ref_ty = common::node_id_type(bcx, ref_id); val = PointerCast( bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to()); } return FnData {llfn: val}; } // Find the actual function pointer. let val = { if def_id.crate == ast::local_crate { // Internal reference. get_item_val(ccx, def_id.node) } else { // External reference. trans_external_path(ccx, def_id, fn_tpt.ty) } }; return FnData {llfn: val}; } // ______________________________________________________________________ // Translating calls pub fn trans_call(in_cx: block, call_ex: @ast::expr, f: @ast::expr, args: CallArgs, id: ast::node_id, dest: expr::Dest) -> block { let _icx = push_ctxt("trans_call"); trans_call_inner(in_cx, call_ex.info(), expr_ty(in_cx, f), node_id_type(in_cx, id), |cx| trans(cx, f), args, dest, DontAutorefArg) } pub fn trans_method_call(in_cx: block, call_ex: @ast::expr, callee_id: ast::node_id, rcvr: @ast::expr, args: CallArgs, dest: expr::Dest) -> block { let _icx = push_ctxt("trans_method_call"); debug!("trans_method_call(call_ex=%s, rcvr=%s)", call_ex.repr(in_cx.tcx()), rcvr.repr(in_cx.tcx())); trans_call_inner( in_cx, call_ex.info(), node_id_type(in_cx, callee_id), expr_ty(in_cx, call_ex), |cx| { match cx.ccx().maps.method_map.find_copy(&call_ex.id) { Some(origin) => { debug!("origin for %s: %s", call_ex.repr(in_cx.tcx()), origin.repr(in_cx.tcx())); meth::trans_method_callee(cx, callee_id, rcvr, origin) } None => { cx.tcx().sess.span_bug(call_ex.span, "method call expr wasn't in method map") } } }, args, dest, DontAutorefArg) } pub fn trans_lang_call(bcx: block, did: ast::def_id, args: &[ValueRef], dest: expr::Dest) -> block { let fty = if did.crate == ast::local_crate { ty::node_id_to_type(bcx.ccx().tcx, did.node) } else { csearch::get_type(bcx.ccx().tcx, did).ty }; let rty = ty::ty_fn_ret(fty); callee::trans_call_inner(bcx, None, fty, rty, |bcx| { trans_fn_ref_with_vtables_to_callee(bcx, did, 0, [], None) }, ArgVals(args), dest, DontAutorefArg) } pub fn trans_lang_call_with_type_params(bcx: block, did: ast::def_id, args: &[ValueRef], type_params: &[ty::t], dest: expr::Dest) -> block { let fty; if did.crate == ast::local_crate { fty = ty::node_id_to_type(bcx.tcx(), did.node); } else { fty = csearch::get_type(bcx.tcx(), did).ty; } let rty = ty::ty_fn_ret(fty); return callee::trans_call_inner( bcx, None, fty, rty, |bcx| { let callee =
type_params, None); let new_llval; match callee.data { Fn(fn_data) => { let substituted = ty::subst_tps(callee.bcx.tcx(), type_params, None, fty); let llfnty = type_of::type_of(callee.bcx.ccx(), substituted); new_llval = PointerCast(callee.bcx, fn_data.llfn, llfnty); } _ => fail!() } Callee { bcx: callee.bcx, data: Fn(FnData { llfn: new_llval }) } }, ArgVals(args), dest, DontAutorefArg); } pub fn body_contains_ret(body: &ast::blk) -> bool { let cx = @mut false; visit::visit_block(body, (cx, visit::mk_vt(@visit::Visitor { visit_item: |_i, (_cx, _v)| { }, visit_expr: |e: @ast::expr, (cx, v): (@mut bool, visit::vt<@mut bool>)| { if!*cx { match e.node { ast::expr_ret(_) => *cx = true, _ => visit::visit_expr(e, (cx, v)), } } }, ..*visit::default_visitor() }))); *cx } // See [Note-arg-mode] pub fn trans_call_inner(in_cx: block, call_info: Option<NodeInfo>, fn_expr_ty: ty::t, ret_ty: ty::t, get_callee: &fn(block) -> Callee, args: CallArgs, dest: expr::Dest, autoref_arg: AutorefArg) -> block { do base::with_scope(in_cx, call_info, "call") |cx| { let ret_in_loop = match args { ArgExprs(args) => { args.len() > 0u && match args.last().node { ast::expr_loop_body(@ast::expr { node: ast::expr_fn_block(_, ref body), _ }) => body_contains_ret(body), _ => false } } _ => false }; let callee = get_callee
trans_fn_ref_with_vtables_to_callee(bcx, did, 0,
random_line_split
callee.rs
impls. // This doesn't actually work if the trait has param bounds, // but it does allow us to survive the case when it does not. let trait_ref = ty::impl_trait_ref(bcx.tcx(), impl_id).get(); @vec::from_elem(trait_ref.substs.tps.len(), @~[]) } } fn resolve_default_method_vtables(bcx: block, impl_id: ast::def_id, method: &ty::Method, substs: &ty::substs, impl_vtables: Option<typeck::vtable_res>) -> typeck::vtable_res { // Get the vtables that the impl implements the trait at let trait_vtables = get_impl_resolutions(bcx, impl_id); // Build up a param_substs that we are going to resolve the // trait_vtables under. let param_substs = Some(@param_substs { tys: copy substs.tps, self_ty: substs.self_ty, vtables: impl_vtables, self_vtable: None }); let trait_vtables_fixed = resolve_vtables_under_param_substs( bcx.tcx(), param_substs, trait_vtables); // Now we pull any vtables for parameters on the actual method. let num_method_vtables = method.generics.type_param_defs.len(); let method_vtables = match impl_vtables { Some(vtables) => { let num_impl_type_parameters = vtables.len() - num_method_vtables; vtables.tailn(num_impl_type_parameters).to_owned() }, None => vec::from_elem(num_method_vtables, @~[]) }; @(*trait_vtables_fixed + method_vtables) } pub fn trans_fn_ref_with_vtables( bcx: block, // def_id: ast::def_id, // def id of fn ref_id: ast::node_id, // node id of use of fn; may be zero if N/A type_params: &[ty::t], // values for fn's ty params vtables: Option<typeck::vtable_res>) -> FnData { //! // // Translates a reference to a fn/method item, monomorphizing and // inlining as it goes. // // # Parameters // // - `bcx`: the current block where the reference to the fn occurs // - `def_id`: def id of the fn or method item being referenced // - `ref_id`: node id of the reference to the fn/method, if applicable. // This parameter may be zero; but, if so, the resulting value may not // have the right type, so it must be cast before being used. // - `type_params`: values for each of the fn/method's type parameters // - `vtables`: values for each bound on each of the type parameters let _icx = push_ctxt("trans_fn_ref_with_vtables"); let ccx = bcx.ccx(); let tcx = ccx.tcx; debug!("trans_fn_ref_with_vtables(bcx=%s, def_id=%s, ref_id=%?, \ type_params=%s, vtables=%s)", bcx.to_str(), def_id.repr(bcx.tcx()), ref_id, type_params.repr(bcx.tcx()), vtables.repr(bcx.tcx())); assert!(type_params.iter().all(|t|!ty::type_needs_infer(*t))); // Polytype of the function item (may have type params) let fn_tpt = ty::lookup_item_type(tcx, def_id); // For simplicity, we want to use the Subst trait when composing // substitutions for default methods. The subst trait does // substitutions with regions, though, so we put a dummy self // region parameter in to keep it from failing. This is a hack. let substs = ty::substs { self_r: Some(ty::re_empty), self_ty: None, tps: /*bad*/ type_params.to_owned() }; // We need to do a bunch of special handling for default methods. // We need to modify the def_id and our substs in order to monomorphize // the function. let (def_id, opt_impl_did, substs, self_vtable, vtables) = match tcx.provided_method_sources.find(&def_id) { None => (def_id, None, substs, None, vtables), Some(source) => { // There are two relevant substitutions when compiling // default methods. First, there is the substitution for // the type parameters of the impl we are using and the // method we are calling. This substitution is the substs // argument we already have. // In order to compile a default method, though, we need // to consider another substitution: the substitution for // the type parameters on trait; the impl we are using // implements the trait at some particular type // parameters, and we need to substitute for those first. // So, what we need to do is find this substitution and // compose it with the one we already have. let trait_ref = ty::impl_trait_ref(tcx, source.impl_id) .expect("could not find trait_ref for impl with \ default methods"); let method = ty::method(tcx, source.method_id); // Get all of the type params for the receiver let param_defs = method.generics.type_param_defs; let receiver_substs = type_params.initn(param_defs.len()).to_owned(); let receiver_vtables = match vtables { None => @~[], Some(call_vtables) => { @call_vtables.initn(param_defs.len()).to_owned() } }; let self_vtable = typeck::vtable_static(source.impl_id, receiver_substs, receiver_vtables); // Compute the first substitution let first_subst = make_substs_for_receiver_types( tcx, source.impl_id, trait_ref, method); // And compose them let new_substs = first_subst.subst(tcx, &substs); let vtables = resolve_default_method_vtables(bcx, source.impl_id, method, &new_substs, vtables); debug!("trans_fn_with_vtables - default method: \ substs = %s, trait_subst = %s, \ first_subst = %s, new_subst = %s, \ self_vtable = %s, vtables = %s", substs.repr(tcx), trait_ref.substs.repr(tcx), first_subst.repr(tcx), new_substs.repr(tcx), self_vtable.repr(tcx), vtables.repr(tcx)); (source.method_id, Some(source.impl_id), new_substs, Some(self_vtable), Some(vtables)) } }; // Check whether this fn has an inlined copy and, if so, redirect // def_id to the local id of the inlined copy. let def_id = { if def_id.crate!= ast::local_crate { let may_translate = opt_impl_did.is_none(); inline::maybe_instantiate_inline(ccx, def_id, may_translate) } else { def_id } }; // We must monomorphise if the fn has type parameters, is a rust // intrinsic, or is a default method. In particular, if we see an // intrinsic that is inlined from a different crate, we want to reemit the // intrinsic instead of trying to call it in the other crate. let must_monomorphise; if type_params.len() > 0 || opt_impl_did.is_some() { must_monomorphise = true; } else if def_id.crate == ast::local_crate { let map_node = session::expect( ccx.sess, ccx.tcx.items.find(&def_id.node), || fmt!("local item should be in ast map")); match *map_node { ast_map::node_foreign_item(_, abis, _, _) => { must_monomorphise = abis.is_intrinsic() } _ =>
} } else { must_monomorphise = false; } // Create a monomorphic verison of generic functions if must_monomorphise { // Should be either intra-crate or inlined. assert_eq!(def_id.crate, ast::local_crate); let (val, must_cast) = monomorphize::monomorphic_fn(ccx, def_id, &substs, vtables, self_vtable, opt_impl_did, Some(ref_id)); let mut val = val; if must_cast && ref_id!= 0 { // Monotype of the REFERENCE to the function (type params // are subst'd) let ref_ty = common::node_id_type(bcx, ref_id); val = PointerCast( bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to()); } return FnData {llfn: val}; } // Find the actual function pointer. let val = { if def_id.crate == ast::local_crate { // Internal reference. get_item_val(ccx, def_id.node) } else { // External reference. trans_external_path(ccx, def_id, fn_tpt.ty) } }; return FnData {llfn: val}; } // ______________________________________________________________________ // Translating calls pub fn trans_call(in_cx: block, call_ex: @ast::expr, f: @ast::expr, args: CallArgs, id: ast::node_id, dest: expr::Dest) -> block { let _icx = push_ctxt("trans_call"); trans_call_inner(in_cx, call_ex.info(), expr_ty(in_cx, f), node_id_type(in_cx, id), |cx| trans(cx, f), args, dest, DontAutorefArg) } pub fn trans_method_call(in_cx: block, call_ex: @ast::expr, callee_id: ast::node_id, rcvr: @ast::expr, args: CallArgs, dest: expr::Dest) -> block { let _icx = push_ctxt("trans_method_call"); debug!("trans_method_call(call_ex=%s, rcvr=%s)", call_ex.repr(in_cx.tcx()), rcvr.repr(in_cx.tcx())); trans_call_inner( in_cx, call_ex.info(), node_id_type(in_cx, callee_id), expr_ty(in_cx, call_ex), |cx| { match cx.ccx().maps.method_map.find_copy(&call_ex.id) { Some(origin) => { debug!("origin for %s: %s", call_ex.repr(in_cx.tcx()), origin.repr(in_cx.tcx())); meth::trans_method_callee(cx, callee_id, rcvr, origin) } None => { cx.tcx().sess.span_bug(call_ex.span, "method call expr wasn't in method map") } } }, args, dest, DontAutorefArg) } pub fn trans_lang_call(bcx: block, did: ast::def_id, args: &[ValueRef], dest: expr::Dest) -> block { let fty = if did.crate == ast::local_crate { ty::node_id_to_type(bcx.ccx().tcx, did.node) } else { csearch::get_type(bcx.ccx().tcx, did).ty }; let rty = ty::ty_fn_ret(fty); callee::trans_call_inner(bcx, None, fty, rty, |bcx| { trans_fn_ref_with_vtables_to_callee(bcx, did, 0, [], None) }, ArgVals(args), dest, DontAutorefArg) } pub fn trans_lang_call_with_type_params(bcx: block, did: ast::def_id, args: &[ValueRef], type_params: &[ty::t], dest: expr::Dest) -> block { let fty; if did.crate == ast::local_crate { fty = ty::node_id_to_type(bcx.tcx(), did.node); } else { fty = csearch::get_type(bcx.tcx(), did).ty; } let rty = ty::ty_fn_ret(fty); return callee::trans_call_inner( bcx, None, fty, rty, |bcx| { let callee = trans_fn_ref_with_vtables_to_callee(bcx, did, 0, type_params, None); let new_llval; match callee.data { Fn(fn_data) => { let substituted = ty::subst_tps(callee.bcx.tcx(), type_params, None, fty); let llfnty = type_of::type_of(callee.bcx.ccx(), substituted); new_llval = PointerCast(callee.bcx, fn_data.llfn, llfnty); } _ => fail!() } Callee { bcx: callee.bcx, data: Fn(FnData { llfn: new_llval }) } }, ArgVals(args), dest, DontAutorefArg); } pub fn body_contains_ret(body: &ast::blk) -> bool { let cx = @mut false; visit::visit_block(body, (cx, visit::mk_vt(@visit::Visitor { visit_item: |_i, (_cx, _v)| { }, visit_expr: |e: @ast::expr, (cx, v): (@mut bool, visit::vt<@mut bool>)| { if!*cx { match e.node { ast::expr_ret(_) => *cx = true, _ => visit::visit_expr(e, (cx, v)), } } }, ..*visit::default_visitor() }))); *cx } // See [Note-arg-mode] pub fn trans_call_inner(in_cx: block, call_info: Option<NodeInfo>, fn_expr_ty: ty::t, ret_ty: ty::t, get_callee: &fn(block) -> Callee, args: CallArgs, dest: expr::Dest, autoref_arg: AutorefArg) -> block { do base::with_scope(in_cx, call_info, "call") |cx| { let ret_in_loop = match args { ArgExprs(args) => { args.len() > 0u && match args.last().node { ast::expr_loop_body(@ast::expr { node: ast::expr_fn_block(_, ref body), _ }) => body_contains_ret(body), _ => false } } _ => false }; let callee = get
{ must_monomorphise = false; }
conditional_block
cabi_mips.rs
// Copyright 2012-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. #[allow(non_uppercase_pattern_statics)]; use std::libc::c_uint; use std::num; use lib::llvm::{llvm, Integer, Pointer, Float, Double, Struct, Array}; use lib::llvm::StructRetAttribute; use middle::trans::context::CrateContext; use middle::trans::context::task_llcx; use middle::trans::cabi::*; use middle::trans::type_::Type; fn align_up_to(off: uint, a: uint) -> uint { return (off + a - 1u) / a * a; } fn align(off: uint, ty: Type) -> uint { let a = ty_align(ty); return align_up_to(off, a); } fn ty_align(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { 1 } else { let str_tys = ty.field_types(); str_tys.iter().fold(1, |a, t| num::max(a, ty_align(*t))) } } Array => { let elt = ty.element_type(); ty_align(elt) } _ => fail!("ty_size: unhandled type") } } fn ty_size(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { let str_tys = ty.field_types(); str_tys.iter().fold(0, |s, t| s + ty_size(*t)) } else { let str_tys = ty.field_types(); let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t)); align(size, ty) } } Array => { let len = ty.array_length(); let elt = ty.element_type(); let eltsz = ty_size(elt); len * eltsz } _ => fail!("ty_size: unhandled type") } } fn classify_ret_ty(ty: Type) -> ArgType { if is_reg_ty(ty) { ArgType::direct(ty, None, None, None) } else { ArgType::indirect(ty, Some(StructRetAttribute)) } } fn classify_arg_ty(ty: Type, offset: &mut uint) -> ArgType { let orig_offset = *offset; let size = ty_size(ty) * 8; let mut align = ty_align(ty); align = num::min(num::max(align, 4), 8); *offset = align_up_to(*offset, align); *offset += align_up_to(size, align * 8) / 8; if is_reg_ty(ty) { ArgType::direct(ty, None, None, None) } else { ArgType::direct( ty, Some(struct_ty(ty)), padding_ty(align, orig_offset), None ) } } fn is_reg_ty(ty: Type) -> bool { return match ty.kind() { Integer | Pointer | Float | Double => true, _ => false }; } fn padding_ty(align: uint, offset: uint) -> Option<Type>
fn coerce_to_int(size: uint) -> ~[Type] { let int_ty = Type::i32(); let mut args = ~[]; let mut n = size / 32; while n > 0 { args.push(int_ty); n -= 1; } let r = size % 32; if r > 0 { unsafe { args.push(Type::from_ref(llvm::LLVMIntTypeInContext(task_llcx(), r as c_uint))); } } args } fn struct_ty(ty: Type) -> Type { let size = ty_size(ty) * 8; let fields = coerce_to_int(size); return Type::struct_(fields, false); } pub fn compute_abi_info(_ccx: &mut CrateContext, atys: &[Type], rty: Type, ret_def: bool) -> FnType { let ret_ty = if ret_def { classify_ret_ty(rty) } else { ArgType::direct(Type::void(), None, None, None) }; let sret = ret_ty.is_indirect(); let mut arg_tys = ~[]; let mut offset = if sret { 4 } else { 0 }; for aty in atys.iter() { let ty = classify_arg_ty(*aty, &mut offset); arg_tys.push(ty); }; return FnType { arg_tys: arg_tys, ret_ty: ret_ty, }; }
{ if ((align - 1 ) & offset) > 0 { return Some(Type::i32()); } return None; }
identifier_body
cabi_mips.rs
// Copyright 2012-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. #[allow(non_uppercase_pattern_statics)]; use std::libc::c_uint; use std::num; use lib::llvm::{llvm, Integer, Pointer, Float, Double, Struct, Array}; use lib::llvm::StructRetAttribute; use middle::trans::context::CrateContext; use middle::trans::context::task_llcx; use middle::trans::cabi::*; use middle::trans::type_::Type; fn align_up_to(off: uint, a: uint) -> uint { return (off + a - 1u) / a * a; } fn align(off: uint, ty: Type) -> uint { let a = ty_align(ty); return align_up_to(off, a); } fn ty_align(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { 1 } else { let str_tys = ty.field_types(); str_tys.iter().fold(1, |a, t| num::max(a, ty_align(*t))) } } Array => { let elt = ty.element_type(); ty_align(elt) } _ => fail!("ty_size: unhandled type") } } fn ty_size(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { let str_tys = ty.field_types(); str_tys.iter().fold(0, |s, t| s + ty_size(*t)) } else { let str_tys = ty.field_types(); let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t)); align(size, ty) } } Array => { let len = ty.array_length(); let elt = ty.element_type(); let eltsz = ty_size(elt); len * eltsz } _ => fail!("ty_size: unhandled type") } } fn classify_ret_ty(ty: Type) -> ArgType { if is_reg_ty(ty) { ArgType::direct(ty, None, None, None) } else { ArgType::indirect(ty, Some(StructRetAttribute)) } } fn classify_arg_ty(ty: Type, offset: &mut uint) -> ArgType { let orig_offset = *offset; let size = ty_size(ty) * 8; let mut align = ty_align(ty); align = num::min(num::max(align, 4), 8); *offset = align_up_to(*offset, align); *offset += align_up_to(size, align * 8) / 8; if is_reg_ty(ty) { ArgType::direct(ty, None, None, None) } else { ArgType::direct( ty, Some(struct_ty(ty)), padding_ty(align, orig_offset), None ) } } fn is_reg_ty(ty: Type) -> bool { return match ty.kind() { Integer | Pointer | Float | Double => true, _ => false }; } fn padding_ty(align: uint, offset: uint) -> Option<Type> { if ((align - 1 ) & offset) > 0 { return Some(Type::i32()); } return None; } fn
(size: uint) -> ~[Type] { let int_ty = Type::i32(); let mut args = ~[]; let mut n = size / 32; while n > 0 { args.push(int_ty); n -= 1; } let r = size % 32; if r > 0 { unsafe { args.push(Type::from_ref(llvm::LLVMIntTypeInContext(task_llcx(), r as c_uint))); } } args } fn struct_ty(ty: Type) -> Type { let size = ty_size(ty) * 8; let fields = coerce_to_int(size); return Type::struct_(fields, false); } pub fn compute_abi_info(_ccx: &mut CrateContext, atys: &[Type], rty: Type, ret_def: bool) -> FnType { let ret_ty = if ret_def { classify_ret_ty(rty) } else { ArgType::direct(Type::void(), None, None, None) }; let sret = ret_ty.is_indirect(); let mut arg_tys = ~[]; let mut offset = if sret { 4 } else { 0 }; for aty in atys.iter() { let ty = classify_arg_ty(*aty, &mut offset); arg_tys.push(ty); }; return FnType { arg_tys: arg_tys, ret_ty: ret_ty, }; }
coerce_to_int
identifier_name
cabi_mips.rs
// Copyright 2012-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. #[allow(non_uppercase_pattern_statics)]; use std::libc::c_uint; use std::num; use lib::llvm::{llvm, Integer, Pointer, Float, Double, Struct, Array}; use lib::llvm::StructRetAttribute; use middle::trans::context::CrateContext; use middle::trans::context::task_llcx; use middle::trans::cabi::*; use middle::trans::type_::Type; fn align_up_to(off: uint, a: uint) -> uint { return (off + a - 1u) / a * a; } fn align(off: uint, ty: Type) -> uint { let a = ty_align(ty); return align_up_to(off, a); } fn ty_align(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { 1 } else { let str_tys = ty.field_types(); str_tys.iter().fold(1, |a, t| num::max(a, ty_align(*t))) } } Array => { let elt = ty.element_type(); ty_align(elt) } _ => fail!("ty_size: unhandled type") } } fn ty_size(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } }
if ty.is_packed() { let str_tys = ty.field_types(); str_tys.iter().fold(0, |s, t| s + ty_size(*t)) } else { let str_tys = ty.field_types(); let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t)); align(size, ty) } } Array => { let len = ty.array_length(); let elt = ty.element_type(); let eltsz = ty_size(elt); len * eltsz } _ => fail!("ty_size: unhandled type") } } fn classify_ret_ty(ty: Type) -> ArgType { if is_reg_ty(ty) { ArgType::direct(ty, None, None, None) } else { ArgType::indirect(ty, Some(StructRetAttribute)) } } fn classify_arg_ty(ty: Type, offset: &mut uint) -> ArgType { let orig_offset = *offset; let size = ty_size(ty) * 8; let mut align = ty_align(ty); align = num::min(num::max(align, 4), 8); *offset = align_up_to(*offset, align); *offset += align_up_to(size, align * 8) / 8; if is_reg_ty(ty) { ArgType::direct(ty, None, None, None) } else { ArgType::direct( ty, Some(struct_ty(ty)), padding_ty(align, orig_offset), None ) } } fn is_reg_ty(ty: Type) -> bool { return match ty.kind() { Integer | Pointer | Float | Double => true, _ => false }; } fn padding_ty(align: uint, offset: uint) -> Option<Type> { if ((align - 1 ) & offset) > 0 { return Some(Type::i32()); } return None; } fn coerce_to_int(size: uint) -> ~[Type] { let int_ty = Type::i32(); let mut args = ~[]; let mut n = size / 32; while n > 0 { args.push(int_ty); n -= 1; } let r = size % 32; if r > 0 { unsafe { args.push(Type::from_ref(llvm::LLVMIntTypeInContext(task_llcx(), r as c_uint))); } } args } fn struct_ty(ty: Type) -> Type { let size = ty_size(ty) * 8; let fields = coerce_to_int(size); return Type::struct_(fields, false); } pub fn compute_abi_info(_ccx: &mut CrateContext, atys: &[Type], rty: Type, ret_def: bool) -> FnType { let ret_ty = if ret_def { classify_ret_ty(rty) } else { ArgType::direct(Type::void(), None, None, None) }; let sret = ret_ty.is_indirect(); let mut arg_tys = ~[]; let mut offset = if sret { 4 } else { 0 }; for aty in atys.iter() { let ty = classify_arg_ty(*aty, &mut offset); arg_tys.push(ty); }; return FnType { arg_tys: arg_tys, ret_ty: ret_ty, }; }
Pointer => 4, Float => 4, Double => 8, Struct => {
random_line_split
mod.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/. */ //! Computed values. use {Atom, Namespace}; use context::QuirksMode; use euclid::Size2D; use font_metrics::{FontMetricsProvider, get_metrics_provider_for_product}; use media_queries::Device; #[cfg(feature = "gecko")] use properties; use properties::{ComputedValues, LonghandId, StyleBuilder}; use rule_cache::RuleCacheConditions; #[cfg(feature = "servo")] use servo_url::ServoUrl; use std::{f32, fmt}; use std::cell::RefCell; #[cfg(feature = "servo")] use std::sync::Arc; use style_traits::ToCss; use style_traits::cursor::Cursor; use super::{CSSFloat, CSSInteger}; use super::generics::{GreaterThanOrEqualToOne, NonNegative}; use super::generics::grid::{GridLine as GenericGridLine, TrackBreadth as GenericTrackBreadth}; use super::generics::grid::{TrackSize as GenericTrackSize, TrackList as GenericTrackList}; use super::generics::grid::GridTemplateComponent as GenericGridTemplateComponent; use super::specified; pub use app_units::Au; pub use properties::animated_properties::TransitionProperty; #[cfg(feature = "gecko")] pub use self::align::{AlignItems, AlignJustifyContent, AlignJustifySelf, JustifyItems}; pub use self::angle::Angle; pub use self::background::{BackgroundSize, BackgroundRepeat}; pub use self::border::{BorderImageSlice, BorderImageWidth, BorderImageSideWidth}; pub use self::border::{BorderRadius, BorderCornerRadius, BorderSpacing}; pub use self::font::{FontSize, FontSizeAdjust, FontSynthesis, FontWeight, FontVariantAlternates}; pub use self::font::{FontFamily, FontLanguageOverride, FontVariantSettings, FontVariantEastAsian}; pub use self::font::{FontVariantLigatures, FontVariantNumeric, FontFeatureSettings}; pub use self::font::{MozScriptLevel, MozScriptMinSize, MozScriptSizeMultiplier, XTextZoom, XLang}; pub use self::box_::{AnimationIterationCount, AnimationName, OverscrollBehavior}; pub use self::box_::{OverflowClipBox, ScrollSnapType, VerticalAlign, WillChange}; pub use self::color::{Color, ColorPropertyValue, RGBAColor}; pub use self::effects::{BoxShadow, Filter, SimpleShadow}; pub use self::flex::FlexBasis; pub use self::image::{Gradient, GradientItem, Image, ImageLayer, LineDirection, MozImageRect}; #[cfg(feature = "gecko")] pub use self::gecko::ScrollSnapPoint; pub use self::rect::LengthOrNumberRect; pub use super::{Auto, Either, None_}; pub use super::specified::{BorderStyle, TextDecorationLine}; pub use self::length::{CalcLengthOrPercentage, Length, LengthOrNone, LengthOrNumber, LengthOrPercentage}; pub use self::length::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone, MaxLength, MozLength}; pub use self::length::{CSSPixelLength, NonNegativeLength, NonNegativeLengthOrPercentage}; pub use self::list::{ListStyleImage, Quotes}; pub use self::outline::OutlineStyle; pub use self::percentage::Percentage; pub use self::position::{Position, GridAutoFlow, GridTemplateAreas}; pub use self::svg::{SVGLength, SVGOpacity, SVGPaint, SVGPaintKind, SVGStrokeDashArray, SVGWidth}; pub use self::table::XSpan; pub use self::text::{InitialLetter, LetterSpacing, LineHeight, TextOverflow, WordSpacing}; pub use self::time::Time; pub use self::transform::{TimingFunction, Transform, TransformOperation, TransformOrigin}; pub use self::ui::MozForceBrokenImageIcon; #[cfg(feature = "gecko")] pub mod align; pub mod angle; pub mod background; pub mod basic_shape; pub mod border; #[path = "box.rs"] pub mod box_; pub mod color; pub mod effects; pub mod flex; pub mod font; pub mod image; #[cfg(feature = "gecko")] pub mod gecko; pub mod length; pub mod list; pub mod outline; pub mod percentage; pub mod position; pub mod rect; pub mod svg; pub mod table; pub mod text; pub mod time; pub mod transform; pub mod ui; /// A `Context` is all the data a specified value could ever need to compute /// itself and be transformed to a computed value. pub struct Context<'a> { /// Whether the current element is the root element. pub is_root_element: bool, /// Values accessed through this need to be in the properties "computed /// early": color, text-decoration, font-size, display, position, float, /// border-*-style, outline-style, font-family, writing-mode... pub builder: StyleBuilder<'a>, /// A cached computed system font value, for use by gecko. /// /// See properties/longhands/font.mako.rs #[cfg(feature = "gecko")] pub cached_system_font: Option<properties::longhands::system_font::ComputedSystemFont>, /// A dummy option for servo so initializing a computed::Context isn't /// painful. /// /// TODO(emilio): Make constructors for Context, and drop this. #[cfg(feature = "servo")] pub cached_system_font: Option<()>, /// A font metrics provider, used to access font metrics to implement /// font-relative units. pub font_metrics_provider: &'a FontMetricsProvider, /// Whether or not we are computing the media list in a media query pub in_media_query: bool, /// The quirks mode of this context. pub quirks_mode: QuirksMode, /// Whether this computation is being done for a SMIL animation. /// /// This is used to allow certain properties to generate out-of-range /// values, which SMIL allows. pub for_smil_animation: bool, /// The property we are computing a value for, if it is a non-inherited /// property. None if we are computed a value for an inherited property /// or not computing for a property at all (e.g. in a media query /// evaluation). pub for_non_inherited_property: Option<LonghandId>, /// The conditions to cache a rule node on the rule cache. /// /// FIXME(emilio): Drop the refcell. pub rule_cache_conditions: RefCell<&'a mut RuleCacheConditions>, } impl<'a> Context<'a> { /// Creates a suitable context for media query evaluation, in which /// font-relative units compute against the system_font, and executes `f` /// with it. pub fn for_media_query_evaluation<F, R>( device: &Device, quirks_mode: QuirksMode, f: F, ) -> R where F: FnOnce(&Context) -> R { let mut conditions = RuleCacheConditions::default(); let default_values = device.default_computed_values(); let provider = get_metrics_provider_for_product(); let context = Context { is_root_element: false, builder: StyleBuilder::for_derived_style(device, default_values, None, None), font_metrics_provider: &provider, cached_system_font: None, in_media_query: true, quirks_mode, for_smil_animation: false, for_non_inherited_property: None, rule_cache_conditions: RefCell::new(&mut conditions), }; f(&context) } /// Whether the current element is the root element. pub fn is_root_element(&self) -> bool { self.is_root_element } /// The current device. pub fn device(&self) -> &Device { self.builder.device } /// The current viewport size, used to resolve viewport units. pub fn viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> { self.builder.device.au_viewport_size_for_viewport_unit_resolution() } /// The default computed style we're getting our reset style from. pub fn default_style(&self) -> &ComputedValues { self.builder.default_style() } /// The current style. pub fn style(&self) -> &StyleBuilder { &self.builder } /// Apply text-zoom if enabled. #[cfg(feature = "gecko")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { // We disable zoom for <svg:text> by unsetting the // -x-text-zoom property, which leads to a false value // in mAllowZoom if self.style().get_font().gecko.mAllowZoom { self.device().zoom_text(Au::from(size)).into() } else { size } } /// (Servo doesn't do text-zoom) #[cfg(feature = "servo")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { size } } /// An iterator over a slice of computed values #[derive(Clone)] pub struct ComputedVecIter<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> { cx: &'cx Context<'cx_a>, values: &'a [S], } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ComputedVecIter<'a, 'cx, 'cx_a, S> { /// Construct an iterator from a slice of specified values and a context pub fn new(cx: &'cx Context<'cx_a>, values: &'a [S]) -> Self { ComputedVecIter { cx: cx, values: values, } } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ExactSizeIterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { fn len(&self) -> usize { self.values.len() } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> Iterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { type Item = S::ComputedValue; fn next(&mut self) -> Option<Self::Item> { if let Some((next, rest)) = self.values.split_first() { let ret = next.to_computed_value(self.cx); self.values = rest; Some(ret) } else { None } } fn size_hint(&self) -> (usize, Option<usize>) { (self.values.len(), Some(self.values.len())) } } /// A trait to represent the conversion between computed and specified values. /// /// This trait is derivable with `#[derive(ToComputedValue)]`. The derived /// implementation just calls `ToComputedValue::to_computed_value` on each field /// of the passed value, or `Clone::clone` if the field is annotated with /// `#[compute(clone)]`. pub trait ToComputedValue { /// The computed value type we're going to be converted to. type ComputedValue; /// Convert a specified value to a computed value, using itself and the data /// inside the `Context`. #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue; #[inline] /// Convert a computed value to specified value form. /// /// This will be used for recascading during animation. /// Such from_computed_valued values should recompute to the same value. fn from_computed_value(computed: &Self::ComputedValue) -> Self; } impl<A, B> ToComputedValue for (A, B) where A: ToComputedValue, B: ToComputedValue, { type ComputedValue = ( <A as ToComputedValue>::ComputedValue, <B as ToComputedValue>::ComputedValue, ); #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { (self.0.to_computed_value(context), self.1.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { (A::from_computed_value(&computed.0), B::from_computed_value(&computed.1)) } } impl<T> ToComputedValue for Option<T> where T: ToComputedValue { type ComputedValue = Option<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.as_ref().map(|item| item.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.as_ref().map(T::from_computed_value) } } impl<T> ToComputedValue for Size2D<T> where T: ToComputedValue { type ComputedValue = Size2D<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Size2D::new( self.width.to_computed_value(context), self.height.to_computed_value(context), ) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Size2D::new( T::from_computed_value(&computed.width), T::from_computed_value(&computed.height), ) } } impl<T> ToComputedValue for Vec<T> where T: ToComputedValue { type ComputedValue = Vec<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect() } } impl<T> ToComputedValue for Box<T> where T: ToComputedValue { type ComputedValue = Box<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Box::new(T::to_computed_value(self, context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Box::new(T::from_computed_value(computed)) } } impl<T> ToComputedValue for Box<[T]> where T: ToComputedValue { type ComputedValue = Box<[<T as ToComputedValue>::ComputedValue]>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect::<Vec<_>>().into_boxed_slice() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect::<Vec<_>>().into_boxed_slice() } } trivial_to_computed_value!(()); trivial_to_computed_value!(bool); trivial_to_computed_value!(f32); trivial_to_computed_value!(i32); trivial_to_computed_value!(u8); trivial_to_computed_value!(u16); trivial_to_computed_value!(u32); trivial_to_computed_value!(Atom); trivial_to_computed_value!(BorderStyle); trivial_to_computed_value!(Cursor); trivial_to_computed_value!(Namespace); trivial_to_computed_value!(String); trivial_to_computed_value!(Box<str>); /// A `<number>` value. pub type Number = CSSFloat; /// A wrapper of Number, but the value >= 0. pub type NonNegativeNumber = NonNegative<CSSFloat>; impl From<CSSFloat> for NonNegativeNumber { #[inline] fn from(number: CSSFloat) -> NonNegativeNumber { NonNegative::<CSSFloat>(number) } } impl From<NonNegativeNumber> for CSSFloat { #[inline] fn from(number: NonNegativeNumber) -> CSSFloat { number.0 } } /// A wrapper of Number, but the value >= 1. pub type GreaterThanOrEqualToOneNumber = GreaterThanOrEqualToOne<CSSFloat>; impl From<CSSFloat> for GreaterThanOrEqualToOneNumber { #[inline] fn from(number: CSSFloat) -> GreaterThanOrEqualToOneNumber { GreaterThanOrEqualToOne::<CSSFloat>(number) } } impl From<GreaterThanOrEqualToOneNumber> for CSSFloat { #[inline] fn from(number: GreaterThanOrEqualToOneNumber) -> CSSFloat { number.0 } } #[allow(missing_docs)] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToCss)] pub enum NumberOrPercentage { Percentage(Percentage), Number(Number), } impl ToComputedValue for specified::NumberOrPercentage { type ComputedValue = NumberOrPercentage; #[inline] fn to_computed_value(&self, context: &Context) -> NumberOrPercentage { match *self { specified::NumberOrPercentage::Percentage(percentage) => NumberOrPercentage::Percentage(percentage.to_computed_value(context)), specified::NumberOrPercentage::Number(number) => NumberOrPercentage::Number(number.to_computed_value(context)), } } #[inline] fn from_computed_value(computed: &NumberOrPercentage) -> Self { match *computed { NumberOrPercentage::Percentage(percentage) => specified::NumberOrPercentage::Percentage(ToComputedValue::from_computed_value(&percentage)), NumberOrPercentage::Number(number) => specified::NumberOrPercentage::Number(ToComputedValue::from_computed_value(&number)), } } } /// A type used for opacity. pub type Opacity = CSSFloat; /// A `<integer>` value. pub type Integer = CSSInteger; /// <integer> | auto pub type IntegerOrAuto = Either<CSSInteger, Auto>; impl IntegerOrAuto { /// Returns the integer value if it is an integer, otherwise return /// the given value. pub fn integer_or(&self, auto_value: CSSInteger) -> CSSInteger { match *self { Either::First(n) => n, Either::Second(Auto) => auto_value, } } } /// A wrapper of Integer, but only accept a value >= 1. pub type PositiveInteger = GreaterThanOrEqualToOne<CSSInteger>; impl From<CSSInteger> for PositiveInteger { #[inline] fn from(int: CSSInteger) -> PositiveInteger { GreaterThanOrEqualToOne::<CSSInteger>(int) } } /// PositiveInteger | auto pub type PositiveIntegerOrAuto = Either<PositiveInteger, Auto>; /// <length> | <percentage> | <number> pub type LengthOrPercentageOrNumber = Either<Number, LengthOrPercentage>; /// NonNegativeLengthOrPercentage | NonNegativeNumber pub type NonNegativeLengthOrPercentageOrNumber = Either<NonNegativeNumber, NonNegativeLengthOrPercentage>; #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, PartialEq)] /// A computed cliprect for clip and image-region pub struct ClipRect { pub top: Option<Length>, pub right: Option<Length>, pub bottom: Option<Length>, pub left: Option<Length>, } impl ToCss for ClipRect { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("rect(")?; if let Some(top) = self.top { top.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(right) = self.right { right.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(bottom) = self.bottom { bottom.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(left) = self.left { left.to_css(dest)?; } else { dest.write_str("auto")?; } dest.write_str(")") } } /// rect(...) | auto pub type ClipRectOrAuto = Either<ClipRect, Auto>; /// The computed value of a grid `<track-breadth>` pub type TrackBreadth = GenericTrackBreadth<LengthOrPercentage>; /// The computed value of a grid `<track-size>` pub type TrackSize = GenericTrackSize<LengthOrPercentage>; /// The computed value of a grid `<track-list>` /// (could also be `<auto-track-list>` or `<explicit-track-list>`) pub type TrackList = GenericTrackList<LengthOrPercentage, Integer>; /// The computed value of a `<grid-line>`. pub type GridLine = GenericGridLine<Integer>; /// `<grid-template-rows> | <grid-template-columns>` pub type GridTemplateComponent = GenericGridTemplateComponent<LengthOrPercentage, Integer>; impl ClipRectOrAuto { /// Return an auto (default for clip-rect and image-region) value pub fn auto() -> Self { Either::Second(Auto) } /// Check if it is auto pub fn is_auto(&self) -> bool { match *self { Either::Second(_) => true, _ => false } } } /// <color> | auto pub type ColorOrAuto = Either<Color, Auto>; /// The computed value of a CSS `url()`, resolved relative to the stylesheet URL. #[cfg(feature = "servo")] #[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum ComputedUrl { /// The `url()` was invalid or it wasn't specified by the user. Invalid(#[ignore_malloc_size_of = "Arc"] Arc<String>), /// The resolved `url()` relative to the stylesheet URL. Valid(ServoUrl), } /// TODO: Properly build ComputedUrl for gecko #[cfg(feature = "gecko")] pub type ComputedUrl = specified::url::SpecifiedUrl; #[cfg(feature = "servo")] impl ComputedUrl { /// Returns the resolved url if it was valid. pub fn url(&self) -> Option<&ServoUrl> { match *self { ComputedUrl::Valid(ref url) => Some(url), _ => None, } } } #[cfg(feature = "servo")] impl ToCss for ComputedUrl { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write
} /// <url> | <none> pub type UrlOrNone = Either<ComputedUrl, None_>;
{ let string = match *self { ComputedUrl::Valid(ref url) => url.as_str(), ComputedUrl::Invalid(ref invalid_string) => invalid_string, }; dest.write_str("url(")?; string.to_css(dest)?; dest.write_str(")") }
identifier_body
mod.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/. */ //! Computed values. use {Atom, Namespace}; use context::QuirksMode; use euclid::Size2D; use font_metrics::{FontMetricsProvider, get_metrics_provider_for_product}; use media_queries::Device; #[cfg(feature = "gecko")] use properties; use properties::{ComputedValues, LonghandId, StyleBuilder}; use rule_cache::RuleCacheConditions; #[cfg(feature = "servo")] use servo_url::ServoUrl; use std::{f32, fmt}; use std::cell::RefCell; #[cfg(feature = "servo")] use std::sync::Arc; use style_traits::ToCss; use style_traits::cursor::Cursor; use super::{CSSFloat, CSSInteger}; use super::generics::{GreaterThanOrEqualToOne, NonNegative}; use super::generics::grid::{GridLine as GenericGridLine, TrackBreadth as GenericTrackBreadth}; use super::generics::grid::{TrackSize as GenericTrackSize, TrackList as GenericTrackList}; use super::generics::grid::GridTemplateComponent as GenericGridTemplateComponent; use super::specified; pub use app_units::Au; pub use properties::animated_properties::TransitionProperty; #[cfg(feature = "gecko")] pub use self::align::{AlignItems, AlignJustifyContent, AlignJustifySelf, JustifyItems}; pub use self::angle::Angle; pub use self::background::{BackgroundSize, BackgroundRepeat}; pub use self::border::{BorderImageSlice, BorderImageWidth, BorderImageSideWidth}; pub use self::border::{BorderRadius, BorderCornerRadius, BorderSpacing}; pub use self::font::{FontSize, FontSizeAdjust, FontSynthesis, FontWeight, FontVariantAlternates}; pub use self::font::{FontFamily, FontLanguageOverride, FontVariantSettings, FontVariantEastAsian}; pub use self::font::{FontVariantLigatures, FontVariantNumeric, FontFeatureSettings}; pub use self::font::{MozScriptLevel, MozScriptMinSize, MozScriptSizeMultiplier, XTextZoom, XLang}; pub use self::box_::{AnimationIterationCount, AnimationName, OverscrollBehavior}; pub use self::box_::{OverflowClipBox, ScrollSnapType, VerticalAlign, WillChange}; pub use self::color::{Color, ColorPropertyValue, RGBAColor}; pub use self::effects::{BoxShadow, Filter, SimpleShadow}; pub use self::flex::FlexBasis; pub use self::image::{Gradient, GradientItem, Image, ImageLayer, LineDirection, MozImageRect}; #[cfg(feature = "gecko")] pub use self::gecko::ScrollSnapPoint; pub use self::rect::LengthOrNumberRect; pub use super::{Auto, Either, None_}; pub use super::specified::{BorderStyle, TextDecorationLine}; pub use self::length::{CalcLengthOrPercentage, Length, LengthOrNone, LengthOrNumber, LengthOrPercentage}; pub use self::length::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone, MaxLength, MozLength}; pub use self::length::{CSSPixelLength, NonNegativeLength, NonNegativeLengthOrPercentage}; pub use self::list::{ListStyleImage, Quotes}; pub use self::outline::OutlineStyle; pub use self::percentage::Percentage; pub use self::position::{Position, GridAutoFlow, GridTemplateAreas}; pub use self::svg::{SVGLength, SVGOpacity, SVGPaint, SVGPaintKind, SVGStrokeDashArray, SVGWidth}; pub use self::table::XSpan; pub use self::text::{InitialLetter, LetterSpacing, LineHeight, TextOverflow, WordSpacing}; pub use self::time::Time; pub use self::transform::{TimingFunction, Transform, TransformOperation, TransformOrigin}; pub use self::ui::MozForceBrokenImageIcon; #[cfg(feature = "gecko")] pub mod align; pub mod angle; pub mod background; pub mod basic_shape; pub mod border; #[path = "box.rs"] pub mod box_; pub mod color; pub mod effects; pub mod flex; pub mod font; pub mod image; #[cfg(feature = "gecko")] pub mod gecko; pub mod length; pub mod list; pub mod outline; pub mod percentage; pub mod position; pub mod rect; pub mod svg; pub mod table; pub mod text; pub mod time; pub mod transform; pub mod ui; /// A `Context` is all the data a specified value could ever need to compute /// itself and be transformed to a computed value. pub struct Context<'a> { /// Whether the current element is the root element. pub is_root_element: bool, /// Values accessed through this need to be in the properties "computed /// early": color, text-decoration, font-size, display, position, float, /// border-*-style, outline-style, font-family, writing-mode... pub builder: StyleBuilder<'a>, /// A cached computed system font value, for use by gecko. /// /// See properties/longhands/font.mako.rs #[cfg(feature = "gecko")] pub cached_system_font: Option<properties::longhands::system_font::ComputedSystemFont>, /// A dummy option for servo so initializing a computed::Context isn't /// painful. /// /// TODO(emilio): Make constructors for Context, and drop this. #[cfg(feature = "servo")] pub cached_system_font: Option<()>, /// A font metrics provider, used to access font metrics to implement /// font-relative units. pub font_metrics_provider: &'a FontMetricsProvider, /// Whether or not we are computing the media list in a media query pub in_media_query: bool, /// The quirks mode of this context. pub quirks_mode: QuirksMode, /// Whether this computation is being done for a SMIL animation. /// /// This is used to allow certain properties to generate out-of-range /// values, which SMIL allows. pub for_smil_animation: bool, /// The property we are computing a value for, if it is a non-inherited /// property. None if we are computed a value for an inherited property /// or not computing for a property at all (e.g. in a media query /// evaluation). pub for_non_inherited_property: Option<LonghandId>, /// The conditions to cache a rule node on the rule cache. /// /// FIXME(emilio): Drop the refcell. pub rule_cache_conditions: RefCell<&'a mut RuleCacheConditions>, } impl<'a> Context<'a> { /// Creates a suitable context for media query evaluation, in which /// font-relative units compute against the system_font, and executes `f` /// with it. pub fn for_media_query_evaluation<F, R>( device: &Device, quirks_mode: QuirksMode, f: F, ) -> R where F: FnOnce(&Context) -> R { let mut conditions = RuleCacheConditions::default(); let default_values = device.default_computed_values(); let provider = get_metrics_provider_for_product(); let context = Context { is_root_element: false, builder: StyleBuilder::for_derived_style(device, default_values, None, None), font_metrics_provider: &provider, cached_system_font: None, in_media_query: true, quirks_mode, for_smil_animation: false, for_non_inherited_property: None, rule_cache_conditions: RefCell::new(&mut conditions), }; f(&context) } /// Whether the current element is the root element. pub fn is_root_element(&self) -> bool { self.is_root_element } /// The current device. pub fn device(&self) -> &Device { self.builder.device } /// The current viewport size, used to resolve viewport units. pub fn viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> { self.builder.device.au_viewport_size_for_viewport_unit_resolution() } /// The default computed style we're getting our reset style from. pub fn default_style(&self) -> &ComputedValues { self.builder.default_style() } /// The current style. pub fn style(&self) -> &StyleBuilder { &self.builder } /// Apply text-zoom if enabled. #[cfg(feature = "gecko")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { // We disable zoom for <svg:text> by unsetting the // -x-text-zoom property, which leads to a false value // in mAllowZoom if self.style().get_font().gecko.mAllowZoom { self.device().zoom_text(Au::from(size)).into() } else { size } } /// (Servo doesn't do text-zoom) #[cfg(feature = "servo")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { size } } /// An iterator over a slice of computed values #[derive(Clone)] pub struct ComputedVecIter<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> { cx: &'cx Context<'cx_a>, values: &'a [S], } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ComputedVecIter<'a, 'cx, 'cx_a, S> { /// Construct an iterator from a slice of specified values and a context pub fn new(cx: &'cx Context<'cx_a>, values: &'a [S]) -> Self { ComputedVecIter { cx: cx, values: values, } } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ExactSizeIterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { fn len(&self) -> usize { self.values.len() } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> Iterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { type Item = S::ComputedValue; fn next(&mut self) -> Option<Self::Item> { if let Some((next, rest)) = self.values.split_first()
else { None } } fn size_hint(&self) -> (usize, Option<usize>) { (self.values.len(), Some(self.values.len())) } } /// A trait to represent the conversion between computed and specified values. /// /// This trait is derivable with `#[derive(ToComputedValue)]`. The derived /// implementation just calls `ToComputedValue::to_computed_value` on each field /// of the passed value, or `Clone::clone` if the field is annotated with /// `#[compute(clone)]`. pub trait ToComputedValue { /// The computed value type we're going to be converted to. type ComputedValue; /// Convert a specified value to a computed value, using itself and the data /// inside the `Context`. #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue; #[inline] /// Convert a computed value to specified value form. /// /// This will be used for recascading during animation. /// Such from_computed_valued values should recompute to the same value. fn from_computed_value(computed: &Self::ComputedValue) -> Self; } impl<A, B> ToComputedValue for (A, B) where A: ToComputedValue, B: ToComputedValue, { type ComputedValue = ( <A as ToComputedValue>::ComputedValue, <B as ToComputedValue>::ComputedValue, ); #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { (self.0.to_computed_value(context), self.1.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { (A::from_computed_value(&computed.0), B::from_computed_value(&computed.1)) } } impl<T> ToComputedValue for Option<T> where T: ToComputedValue { type ComputedValue = Option<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.as_ref().map(|item| item.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.as_ref().map(T::from_computed_value) } } impl<T> ToComputedValue for Size2D<T> where T: ToComputedValue { type ComputedValue = Size2D<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Size2D::new( self.width.to_computed_value(context), self.height.to_computed_value(context), ) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Size2D::new( T::from_computed_value(&computed.width), T::from_computed_value(&computed.height), ) } } impl<T> ToComputedValue for Vec<T> where T: ToComputedValue { type ComputedValue = Vec<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect() } } impl<T> ToComputedValue for Box<T> where T: ToComputedValue { type ComputedValue = Box<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Box::new(T::to_computed_value(self, context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Box::new(T::from_computed_value(computed)) } } impl<T> ToComputedValue for Box<[T]> where T: ToComputedValue { type ComputedValue = Box<[<T as ToComputedValue>::ComputedValue]>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect::<Vec<_>>().into_boxed_slice() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect::<Vec<_>>().into_boxed_slice() } } trivial_to_computed_value!(()); trivial_to_computed_value!(bool); trivial_to_computed_value!(f32); trivial_to_computed_value!(i32); trivial_to_computed_value!(u8); trivial_to_computed_value!(u16); trivial_to_computed_value!(u32); trivial_to_computed_value!(Atom); trivial_to_computed_value!(BorderStyle); trivial_to_computed_value!(Cursor); trivial_to_computed_value!(Namespace); trivial_to_computed_value!(String); trivial_to_computed_value!(Box<str>); /// A `<number>` value. pub type Number = CSSFloat; /// A wrapper of Number, but the value >= 0. pub type NonNegativeNumber = NonNegative<CSSFloat>; impl From<CSSFloat> for NonNegativeNumber { #[inline] fn from(number: CSSFloat) -> NonNegativeNumber { NonNegative::<CSSFloat>(number) } } impl From<NonNegativeNumber> for CSSFloat { #[inline] fn from(number: NonNegativeNumber) -> CSSFloat { number.0 } } /// A wrapper of Number, but the value >= 1. pub type GreaterThanOrEqualToOneNumber = GreaterThanOrEqualToOne<CSSFloat>; impl From<CSSFloat> for GreaterThanOrEqualToOneNumber { #[inline] fn from(number: CSSFloat) -> GreaterThanOrEqualToOneNumber { GreaterThanOrEqualToOne::<CSSFloat>(number) } } impl From<GreaterThanOrEqualToOneNumber> for CSSFloat { #[inline] fn from(number: GreaterThanOrEqualToOneNumber) -> CSSFloat { number.0 } } #[allow(missing_docs)] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToCss)] pub enum NumberOrPercentage { Percentage(Percentage), Number(Number), } impl ToComputedValue for specified::NumberOrPercentage { type ComputedValue = NumberOrPercentage; #[inline] fn to_computed_value(&self, context: &Context) -> NumberOrPercentage { match *self { specified::NumberOrPercentage::Percentage(percentage) => NumberOrPercentage::Percentage(percentage.to_computed_value(context)), specified::NumberOrPercentage::Number(number) => NumberOrPercentage::Number(number.to_computed_value(context)), } } #[inline] fn from_computed_value(computed: &NumberOrPercentage) -> Self { match *computed { NumberOrPercentage::Percentage(percentage) => specified::NumberOrPercentage::Percentage(ToComputedValue::from_computed_value(&percentage)), NumberOrPercentage::Number(number) => specified::NumberOrPercentage::Number(ToComputedValue::from_computed_value(&number)), } } } /// A type used for opacity. pub type Opacity = CSSFloat; /// A `<integer>` value. pub type Integer = CSSInteger; /// <integer> | auto pub type IntegerOrAuto = Either<CSSInteger, Auto>; impl IntegerOrAuto { /// Returns the integer value if it is an integer, otherwise return /// the given value. pub fn integer_or(&self, auto_value: CSSInteger) -> CSSInteger { match *self { Either::First(n) => n, Either::Second(Auto) => auto_value, } } } /// A wrapper of Integer, but only accept a value >= 1. pub type PositiveInteger = GreaterThanOrEqualToOne<CSSInteger>; impl From<CSSInteger> for PositiveInteger { #[inline] fn from(int: CSSInteger) -> PositiveInteger { GreaterThanOrEqualToOne::<CSSInteger>(int) } } /// PositiveInteger | auto pub type PositiveIntegerOrAuto = Either<PositiveInteger, Auto>; /// <length> | <percentage> | <number> pub type LengthOrPercentageOrNumber = Either<Number, LengthOrPercentage>; /// NonNegativeLengthOrPercentage | NonNegativeNumber pub type NonNegativeLengthOrPercentageOrNumber = Either<NonNegativeNumber, NonNegativeLengthOrPercentage>; #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, PartialEq)] /// A computed cliprect for clip and image-region pub struct ClipRect { pub top: Option<Length>, pub right: Option<Length>, pub bottom: Option<Length>, pub left: Option<Length>, } impl ToCss for ClipRect { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("rect(")?; if let Some(top) = self.top { top.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(right) = self.right { right.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(bottom) = self.bottom { bottom.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(left) = self.left { left.to_css(dest)?; } else { dest.write_str("auto")?; } dest.write_str(")") } } /// rect(...) | auto pub type ClipRectOrAuto = Either<ClipRect, Auto>; /// The computed value of a grid `<track-breadth>` pub type TrackBreadth = GenericTrackBreadth<LengthOrPercentage>; /// The computed value of a grid `<track-size>` pub type TrackSize = GenericTrackSize<LengthOrPercentage>; /// The computed value of a grid `<track-list>` /// (could also be `<auto-track-list>` or `<explicit-track-list>`) pub type TrackList = GenericTrackList<LengthOrPercentage, Integer>; /// The computed value of a `<grid-line>`. pub type GridLine = GenericGridLine<Integer>; /// `<grid-template-rows> | <grid-template-columns>` pub type GridTemplateComponent = GenericGridTemplateComponent<LengthOrPercentage, Integer>; impl ClipRectOrAuto { /// Return an auto (default for clip-rect and image-region) value pub fn auto() -> Self { Either::Second(Auto) } /// Check if it is auto pub fn is_auto(&self) -> bool { match *self { Either::Second(_) => true, _ => false } } } /// <color> | auto pub type ColorOrAuto = Either<Color, Auto>; /// The computed value of a CSS `url()`, resolved relative to the stylesheet URL. #[cfg(feature = "servo")] #[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum ComputedUrl { /// The `url()` was invalid or it wasn't specified by the user. Invalid(#[ignore_malloc_size_of = "Arc"] Arc<String>), /// The resolved `url()` relative to the stylesheet URL. Valid(ServoUrl), } /// TODO: Properly build ComputedUrl for gecko #[cfg(feature = "gecko")] pub type ComputedUrl = specified::url::SpecifiedUrl; #[cfg(feature = "servo")] impl ComputedUrl { /// Returns the resolved url if it was valid. pub fn url(&self) -> Option<&ServoUrl> { match *self { ComputedUrl::Valid(ref url) => Some(url), _ => None, } } } #[cfg(feature = "servo")] impl ToCss for ComputedUrl { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let string = match *self { ComputedUrl::Valid(ref url) => url.as_str(), ComputedUrl::Invalid(ref invalid_string) => invalid_string, }; dest.write_str("url(")?; string.to_css(dest)?; dest.write_str(")") } } /// <url> | <none> pub type UrlOrNone = Either<ComputedUrl, None_>;
{ let ret = next.to_computed_value(self.cx); self.values = rest; Some(ret) }
conditional_block
mod.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/. */ //! Computed values. use {Atom, Namespace}; use context::QuirksMode; use euclid::Size2D; use font_metrics::{FontMetricsProvider, get_metrics_provider_for_product}; use media_queries::Device; #[cfg(feature = "gecko")] use properties; use properties::{ComputedValues, LonghandId, StyleBuilder}; use rule_cache::RuleCacheConditions; #[cfg(feature = "servo")] use servo_url::ServoUrl; use std::{f32, fmt}; use std::cell::RefCell; #[cfg(feature = "servo")] use std::sync::Arc; use style_traits::ToCss; use style_traits::cursor::Cursor; use super::{CSSFloat, CSSInteger}; use super::generics::{GreaterThanOrEqualToOne, NonNegative}; use super::generics::grid::{GridLine as GenericGridLine, TrackBreadth as GenericTrackBreadth}; use super::generics::grid::{TrackSize as GenericTrackSize, TrackList as GenericTrackList}; use super::generics::grid::GridTemplateComponent as GenericGridTemplateComponent; use super::specified; pub use app_units::Au; pub use properties::animated_properties::TransitionProperty; #[cfg(feature = "gecko")] pub use self::align::{AlignItems, AlignJustifyContent, AlignJustifySelf, JustifyItems}; pub use self::angle::Angle; pub use self::background::{BackgroundSize, BackgroundRepeat}; pub use self::border::{BorderImageSlice, BorderImageWidth, BorderImageSideWidth}; pub use self::border::{BorderRadius, BorderCornerRadius, BorderSpacing}; pub use self::font::{FontSize, FontSizeAdjust, FontSynthesis, FontWeight, FontVariantAlternates}; pub use self::font::{FontFamily, FontLanguageOverride, FontVariantSettings, FontVariantEastAsian}; pub use self::font::{FontVariantLigatures, FontVariantNumeric, FontFeatureSettings}; pub use self::font::{MozScriptLevel, MozScriptMinSize, MozScriptSizeMultiplier, XTextZoom, XLang}; pub use self::box_::{AnimationIterationCount, AnimationName, OverscrollBehavior}; pub use self::box_::{OverflowClipBox, ScrollSnapType, VerticalAlign, WillChange}; pub use self::color::{Color, ColorPropertyValue, RGBAColor}; pub use self::effects::{BoxShadow, Filter, SimpleShadow}; pub use self::flex::FlexBasis; pub use self::image::{Gradient, GradientItem, Image, ImageLayer, LineDirection, MozImageRect}; #[cfg(feature = "gecko")] pub use self::gecko::ScrollSnapPoint; pub use self::rect::LengthOrNumberRect; pub use super::{Auto, Either, None_}; pub use super::specified::{BorderStyle, TextDecorationLine}; pub use self::length::{CalcLengthOrPercentage, Length, LengthOrNone, LengthOrNumber, LengthOrPercentage}; pub use self::length::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone, MaxLength, MozLength}; pub use self::length::{CSSPixelLength, NonNegativeLength, NonNegativeLengthOrPercentage}; pub use self::list::{ListStyleImage, Quotes}; pub use self::outline::OutlineStyle; pub use self::percentage::Percentage; pub use self::position::{Position, GridAutoFlow, GridTemplateAreas}; pub use self::svg::{SVGLength, SVGOpacity, SVGPaint, SVGPaintKind, SVGStrokeDashArray, SVGWidth}; pub use self::table::XSpan; pub use self::text::{InitialLetter, LetterSpacing, LineHeight, TextOverflow, WordSpacing}; pub use self::time::Time; pub use self::transform::{TimingFunction, Transform, TransformOperation, TransformOrigin}; pub use self::ui::MozForceBrokenImageIcon; #[cfg(feature = "gecko")] pub mod align; pub mod angle; pub mod background; pub mod basic_shape; pub mod border; #[path = "box.rs"] pub mod box_; pub mod color; pub mod effects; pub mod flex; pub mod font; pub mod image; #[cfg(feature = "gecko")] pub mod gecko; pub mod length; pub mod list; pub mod outline; pub mod percentage; pub mod position; pub mod rect; pub mod svg; pub mod table; pub mod text; pub mod time; pub mod transform; pub mod ui; /// A `Context` is all the data a specified value could ever need to compute /// itself and be transformed to a computed value. pub struct Context<'a> { /// Whether the current element is the root element. pub is_root_element: bool, /// Values accessed through this need to be in the properties "computed /// early": color, text-decoration, font-size, display, position, float, /// border-*-style, outline-style, font-family, writing-mode... pub builder: StyleBuilder<'a>, /// A cached computed system font value, for use by gecko. /// /// See properties/longhands/font.mako.rs #[cfg(feature = "gecko")] pub cached_system_font: Option<properties::longhands::system_font::ComputedSystemFont>, /// A dummy option for servo so initializing a computed::Context isn't /// painful. /// /// TODO(emilio): Make constructors for Context, and drop this. #[cfg(feature = "servo")] pub cached_system_font: Option<()>, /// A font metrics provider, used to access font metrics to implement /// font-relative units. pub font_metrics_provider: &'a FontMetricsProvider, /// Whether or not we are computing the media list in a media query pub in_media_query: bool, /// The quirks mode of this context. pub quirks_mode: QuirksMode, /// Whether this computation is being done for a SMIL animation. /// /// This is used to allow certain properties to generate out-of-range /// values, which SMIL allows. pub for_smil_animation: bool, /// The property we are computing a value for, if it is a non-inherited /// property. None if we are computed a value for an inherited property /// or not computing for a property at all (e.g. in a media query /// evaluation). pub for_non_inherited_property: Option<LonghandId>, /// The conditions to cache a rule node on the rule cache. /// /// FIXME(emilio): Drop the refcell. pub rule_cache_conditions: RefCell<&'a mut RuleCacheConditions>, } impl<'a> Context<'a> { /// Creates a suitable context for media query evaluation, in which /// font-relative units compute against the system_font, and executes `f` /// with it. pub fn for_media_query_evaluation<F, R>( device: &Device, quirks_mode: QuirksMode, f: F, ) -> R where F: FnOnce(&Context) -> R { let mut conditions = RuleCacheConditions::default(); let default_values = device.default_computed_values(); let provider = get_metrics_provider_for_product(); let context = Context { is_root_element: false, builder: StyleBuilder::for_derived_style(device, default_values, None, None), font_metrics_provider: &provider, cached_system_font: None, in_media_query: true, quirks_mode, for_smil_animation: false, for_non_inherited_property: None, rule_cache_conditions: RefCell::new(&mut conditions), }; f(&context) } /// Whether the current element is the root element. pub fn is_root_element(&self) -> bool { self.is_root_element } /// The current device. pub fn device(&self) -> &Device { self.builder.device } /// The current viewport size, used to resolve viewport units. pub fn viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> { self.builder.device.au_viewport_size_for_viewport_unit_resolution() } /// The default computed style we're getting our reset style from. pub fn default_style(&self) -> &ComputedValues { self.builder.default_style() } /// The current style. pub fn style(&self) -> &StyleBuilder { &self.builder } /// Apply text-zoom if enabled. #[cfg(feature = "gecko")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { // We disable zoom for <svg:text> by unsetting the // -x-text-zoom property, which leads to a false value // in mAllowZoom if self.style().get_font().gecko.mAllowZoom { self.device().zoom_text(Au::from(size)).into() } else { size } } /// (Servo doesn't do text-zoom) #[cfg(feature = "servo")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { size } } /// An iterator over a slice of computed values #[derive(Clone)] pub struct ComputedVecIter<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> { cx: &'cx Context<'cx_a>, values: &'a [S], } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ComputedVecIter<'a, 'cx, 'cx_a, S> { /// Construct an iterator from a slice of specified values and a context pub fn new(cx: &'cx Context<'cx_a>, values: &'a [S]) -> Self { ComputedVecIter { cx: cx, values: values, } } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ExactSizeIterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { fn len(&self) -> usize { self.values.len() } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> Iterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { type Item = S::ComputedValue; fn next(&mut self) -> Option<Self::Item> { if let Some((next, rest)) = self.values.split_first() { let ret = next.to_computed_value(self.cx); self.values = rest; Some(ret) } else { None } } fn size_hint(&self) -> (usize, Option<usize>) { (self.values.len(), Some(self.values.len())) } } /// A trait to represent the conversion between computed and specified values. /// /// This trait is derivable with `#[derive(ToComputedValue)]`. The derived /// implementation just calls `ToComputedValue::to_computed_value` on each field /// of the passed value, or `Clone::clone` if the field is annotated with /// `#[compute(clone)]`. pub trait ToComputedValue { /// The computed value type we're going to be converted to. type ComputedValue; /// Convert a specified value to a computed value, using itself and the data /// inside the `Context`. #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue; #[inline] /// Convert a computed value to specified value form. /// /// This will be used for recascading during animation. /// Such from_computed_valued values should recompute to the same value. fn from_computed_value(computed: &Self::ComputedValue) -> Self; } impl<A, B> ToComputedValue for (A, B) where A: ToComputedValue, B: ToComputedValue, { type ComputedValue = ( <A as ToComputedValue>::ComputedValue, <B as ToComputedValue>::ComputedValue, ); #[inline] fn
(&self, context: &Context) -> Self::ComputedValue { (self.0.to_computed_value(context), self.1.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { (A::from_computed_value(&computed.0), B::from_computed_value(&computed.1)) } } impl<T> ToComputedValue for Option<T> where T: ToComputedValue { type ComputedValue = Option<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.as_ref().map(|item| item.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.as_ref().map(T::from_computed_value) } } impl<T> ToComputedValue for Size2D<T> where T: ToComputedValue { type ComputedValue = Size2D<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Size2D::new( self.width.to_computed_value(context), self.height.to_computed_value(context), ) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Size2D::new( T::from_computed_value(&computed.width), T::from_computed_value(&computed.height), ) } } impl<T> ToComputedValue for Vec<T> where T: ToComputedValue { type ComputedValue = Vec<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect() } } impl<T> ToComputedValue for Box<T> where T: ToComputedValue { type ComputedValue = Box<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Box::new(T::to_computed_value(self, context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Box::new(T::from_computed_value(computed)) } } impl<T> ToComputedValue for Box<[T]> where T: ToComputedValue { type ComputedValue = Box<[<T as ToComputedValue>::ComputedValue]>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect::<Vec<_>>().into_boxed_slice() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect::<Vec<_>>().into_boxed_slice() } } trivial_to_computed_value!(()); trivial_to_computed_value!(bool); trivial_to_computed_value!(f32); trivial_to_computed_value!(i32); trivial_to_computed_value!(u8); trivial_to_computed_value!(u16); trivial_to_computed_value!(u32); trivial_to_computed_value!(Atom); trivial_to_computed_value!(BorderStyle); trivial_to_computed_value!(Cursor); trivial_to_computed_value!(Namespace); trivial_to_computed_value!(String); trivial_to_computed_value!(Box<str>); /// A `<number>` value. pub type Number = CSSFloat; /// A wrapper of Number, but the value >= 0. pub type NonNegativeNumber = NonNegative<CSSFloat>; impl From<CSSFloat> for NonNegativeNumber { #[inline] fn from(number: CSSFloat) -> NonNegativeNumber { NonNegative::<CSSFloat>(number) } } impl From<NonNegativeNumber> for CSSFloat { #[inline] fn from(number: NonNegativeNumber) -> CSSFloat { number.0 } } /// A wrapper of Number, but the value >= 1. pub type GreaterThanOrEqualToOneNumber = GreaterThanOrEqualToOne<CSSFloat>; impl From<CSSFloat> for GreaterThanOrEqualToOneNumber { #[inline] fn from(number: CSSFloat) -> GreaterThanOrEqualToOneNumber { GreaterThanOrEqualToOne::<CSSFloat>(number) } } impl From<GreaterThanOrEqualToOneNumber> for CSSFloat { #[inline] fn from(number: GreaterThanOrEqualToOneNumber) -> CSSFloat { number.0 } } #[allow(missing_docs)] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToCss)] pub enum NumberOrPercentage { Percentage(Percentage), Number(Number), } impl ToComputedValue for specified::NumberOrPercentage { type ComputedValue = NumberOrPercentage; #[inline] fn to_computed_value(&self, context: &Context) -> NumberOrPercentage { match *self { specified::NumberOrPercentage::Percentage(percentage) => NumberOrPercentage::Percentage(percentage.to_computed_value(context)), specified::NumberOrPercentage::Number(number) => NumberOrPercentage::Number(number.to_computed_value(context)), } } #[inline] fn from_computed_value(computed: &NumberOrPercentage) -> Self { match *computed { NumberOrPercentage::Percentage(percentage) => specified::NumberOrPercentage::Percentage(ToComputedValue::from_computed_value(&percentage)), NumberOrPercentage::Number(number) => specified::NumberOrPercentage::Number(ToComputedValue::from_computed_value(&number)), } } } /// A type used for opacity. pub type Opacity = CSSFloat; /// A `<integer>` value. pub type Integer = CSSInteger; /// <integer> | auto pub type IntegerOrAuto = Either<CSSInteger, Auto>; impl IntegerOrAuto { /// Returns the integer value if it is an integer, otherwise return /// the given value. pub fn integer_or(&self, auto_value: CSSInteger) -> CSSInteger { match *self { Either::First(n) => n, Either::Second(Auto) => auto_value, } } } /// A wrapper of Integer, but only accept a value >= 1. pub type PositiveInteger = GreaterThanOrEqualToOne<CSSInteger>; impl From<CSSInteger> for PositiveInteger { #[inline] fn from(int: CSSInteger) -> PositiveInteger { GreaterThanOrEqualToOne::<CSSInteger>(int) } } /// PositiveInteger | auto pub type PositiveIntegerOrAuto = Either<PositiveInteger, Auto>; /// <length> | <percentage> | <number> pub type LengthOrPercentageOrNumber = Either<Number, LengthOrPercentage>; /// NonNegativeLengthOrPercentage | NonNegativeNumber pub type NonNegativeLengthOrPercentageOrNumber = Either<NonNegativeNumber, NonNegativeLengthOrPercentage>; #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, PartialEq)] /// A computed cliprect for clip and image-region pub struct ClipRect { pub top: Option<Length>, pub right: Option<Length>, pub bottom: Option<Length>, pub left: Option<Length>, } impl ToCss for ClipRect { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("rect(")?; if let Some(top) = self.top { top.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(right) = self.right { right.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(bottom) = self.bottom { bottom.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(left) = self.left { left.to_css(dest)?; } else { dest.write_str("auto")?; } dest.write_str(")") } } /// rect(...) | auto pub type ClipRectOrAuto = Either<ClipRect, Auto>; /// The computed value of a grid `<track-breadth>` pub type TrackBreadth = GenericTrackBreadth<LengthOrPercentage>; /// The computed value of a grid `<track-size>` pub type TrackSize = GenericTrackSize<LengthOrPercentage>; /// The computed value of a grid `<track-list>` /// (could also be `<auto-track-list>` or `<explicit-track-list>`) pub type TrackList = GenericTrackList<LengthOrPercentage, Integer>; /// The computed value of a `<grid-line>`. pub type GridLine = GenericGridLine<Integer>; /// `<grid-template-rows> | <grid-template-columns>` pub type GridTemplateComponent = GenericGridTemplateComponent<LengthOrPercentage, Integer>; impl ClipRectOrAuto { /// Return an auto (default for clip-rect and image-region) value pub fn auto() -> Self { Either::Second(Auto) } /// Check if it is auto pub fn is_auto(&self) -> bool { match *self { Either::Second(_) => true, _ => false } } } /// <color> | auto pub type ColorOrAuto = Either<Color, Auto>; /// The computed value of a CSS `url()`, resolved relative to the stylesheet URL. #[cfg(feature = "servo")] #[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum ComputedUrl { /// The `url()` was invalid or it wasn't specified by the user. Invalid(#[ignore_malloc_size_of = "Arc"] Arc<String>), /// The resolved `url()` relative to the stylesheet URL. Valid(ServoUrl), } /// TODO: Properly build ComputedUrl for gecko #[cfg(feature = "gecko")] pub type ComputedUrl = specified::url::SpecifiedUrl; #[cfg(feature = "servo")] impl ComputedUrl { /// Returns the resolved url if it was valid. pub fn url(&self) -> Option<&ServoUrl> { match *self { ComputedUrl::Valid(ref url) => Some(url), _ => None, } } } #[cfg(feature = "servo")] impl ToCss for ComputedUrl { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let string = match *self { ComputedUrl::Valid(ref url) => url.as_str(), ComputedUrl::Invalid(ref invalid_string) => invalid_string, }; dest.write_str("url(")?; string.to_css(dest)?; dest.write_str(")") } } /// <url> | <none> pub type UrlOrNone = Either<ComputedUrl, None_>;
to_computed_value
identifier_name
mod.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/. */ //! Computed values. use {Atom, Namespace}; use context::QuirksMode; use euclid::Size2D; use font_metrics::{FontMetricsProvider, get_metrics_provider_for_product}; use media_queries::Device; #[cfg(feature = "gecko")] use properties; use properties::{ComputedValues, LonghandId, StyleBuilder}; use rule_cache::RuleCacheConditions; #[cfg(feature = "servo")] use servo_url::ServoUrl; use std::{f32, fmt}; use std::cell::RefCell; #[cfg(feature = "servo")] use std::sync::Arc; use style_traits::ToCss; use style_traits::cursor::Cursor; use super::{CSSFloat, CSSInteger}; use super::generics::{GreaterThanOrEqualToOne, NonNegative}; use super::generics::grid::{GridLine as GenericGridLine, TrackBreadth as GenericTrackBreadth}; use super::generics::grid::{TrackSize as GenericTrackSize, TrackList as GenericTrackList}; use super::generics::grid::GridTemplateComponent as GenericGridTemplateComponent; use super::specified; pub use app_units::Au; pub use properties::animated_properties::TransitionProperty; #[cfg(feature = "gecko")] pub use self::align::{AlignItems, AlignJustifyContent, AlignJustifySelf, JustifyItems}; pub use self::angle::Angle; pub use self::background::{BackgroundSize, BackgroundRepeat}; pub use self::border::{BorderImageSlice, BorderImageWidth, BorderImageSideWidth}; pub use self::border::{BorderRadius, BorderCornerRadius, BorderSpacing}; pub use self::font::{FontSize, FontSizeAdjust, FontSynthesis, FontWeight, FontVariantAlternates}; pub use self::font::{FontFamily, FontLanguageOverride, FontVariantSettings, FontVariantEastAsian}; pub use self::font::{FontVariantLigatures, FontVariantNumeric, FontFeatureSettings}; pub use self::font::{MozScriptLevel, MozScriptMinSize, MozScriptSizeMultiplier, XTextZoom, XLang}; pub use self::box_::{AnimationIterationCount, AnimationName, OverscrollBehavior}; pub use self::box_::{OverflowClipBox, ScrollSnapType, VerticalAlign, WillChange}; pub use self::color::{Color, ColorPropertyValue, RGBAColor}; pub use self::effects::{BoxShadow, Filter, SimpleShadow}; pub use self::flex::FlexBasis; pub use self::image::{Gradient, GradientItem, Image, ImageLayer, LineDirection, MozImageRect}; #[cfg(feature = "gecko")] pub use self::gecko::ScrollSnapPoint; pub use self::rect::LengthOrNumberRect; pub use super::{Auto, Either, None_}; pub use super::specified::{BorderStyle, TextDecorationLine}; pub use self::length::{CalcLengthOrPercentage, Length, LengthOrNone, LengthOrNumber, LengthOrPercentage}; pub use self::length::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone, MaxLength, MozLength}; pub use self::length::{CSSPixelLength, NonNegativeLength, NonNegativeLengthOrPercentage}; pub use self::list::{ListStyleImage, Quotes}; pub use self::outline::OutlineStyle; pub use self::percentage::Percentage; pub use self::position::{Position, GridAutoFlow, GridTemplateAreas}; pub use self::svg::{SVGLength, SVGOpacity, SVGPaint, SVGPaintKind, SVGStrokeDashArray, SVGWidth}; pub use self::table::XSpan; pub use self::text::{InitialLetter, LetterSpacing, LineHeight, TextOverflow, WordSpacing}; pub use self::time::Time; pub use self::transform::{TimingFunction, Transform, TransformOperation, TransformOrigin}; pub use self::ui::MozForceBrokenImageIcon; #[cfg(feature = "gecko")] pub mod align; pub mod angle; pub mod background; pub mod basic_shape; pub mod border; #[path = "box.rs"] pub mod box_; pub mod color; pub mod effects; pub mod flex; pub mod font; pub mod image; #[cfg(feature = "gecko")] pub mod gecko; pub mod length; pub mod list; pub mod outline; pub mod percentage; pub mod position; pub mod rect; pub mod svg; pub mod table; pub mod text; pub mod time; pub mod transform; pub mod ui; /// A `Context` is all the data a specified value could ever need to compute /// itself and be transformed to a computed value. pub struct Context<'a> { /// Whether the current element is the root element. pub is_root_element: bool, /// Values accessed through this need to be in the properties "computed /// early": color, text-decoration, font-size, display, position, float, /// border-*-style, outline-style, font-family, writing-mode... pub builder: StyleBuilder<'a>, /// A cached computed system font value, for use by gecko. /// /// See properties/longhands/font.mako.rs #[cfg(feature = "gecko")] pub cached_system_font: Option<properties::longhands::system_font::ComputedSystemFont>, /// A dummy option for servo so initializing a computed::Context isn't /// painful. /// /// TODO(emilio): Make constructors for Context, and drop this. #[cfg(feature = "servo")] pub cached_system_font: Option<()>, /// A font metrics provider, used to access font metrics to implement /// font-relative units. pub font_metrics_provider: &'a FontMetricsProvider, /// Whether or not we are computing the media list in a media query pub in_media_query: bool, /// The quirks mode of this context. pub quirks_mode: QuirksMode, /// Whether this computation is being done for a SMIL animation. /// /// This is used to allow certain properties to generate out-of-range /// values, which SMIL allows. pub for_smil_animation: bool, /// The property we are computing a value for, if it is a non-inherited /// property. None if we are computed a value for an inherited property /// or not computing for a property at all (e.g. in a media query /// evaluation). pub for_non_inherited_property: Option<LonghandId>, /// The conditions to cache a rule node on the rule cache. /// /// FIXME(emilio): Drop the refcell. pub rule_cache_conditions: RefCell<&'a mut RuleCacheConditions>, } impl<'a> Context<'a> { /// Creates a suitable context for media query evaluation, in which /// font-relative units compute against the system_font, and executes `f` /// with it. pub fn for_media_query_evaluation<F, R>( device: &Device, quirks_mode: QuirksMode, f: F, ) -> R where F: FnOnce(&Context) -> R { let mut conditions = RuleCacheConditions::default(); let default_values = device.default_computed_values(); let provider = get_metrics_provider_for_product(); let context = Context { is_root_element: false, builder: StyleBuilder::for_derived_style(device, default_values, None, None), font_metrics_provider: &provider, cached_system_font: None, in_media_query: true, quirks_mode, for_smil_animation: false, for_non_inherited_property: None, rule_cache_conditions: RefCell::new(&mut conditions), }; f(&context) } /// Whether the current element is the root element. pub fn is_root_element(&self) -> bool { self.is_root_element } /// The current device. pub fn device(&self) -> &Device { self.builder.device } /// The current viewport size, used to resolve viewport units. pub fn viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> { self.builder.device.au_viewport_size_for_viewport_unit_resolution() } /// The default computed style we're getting our reset style from. pub fn default_style(&self) -> &ComputedValues { self.builder.default_style() } /// The current style. pub fn style(&self) -> &StyleBuilder { &self.builder } /// Apply text-zoom if enabled. #[cfg(feature = "gecko")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { // We disable zoom for <svg:text> by unsetting the // -x-text-zoom property, which leads to a false value // in mAllowZoom if self.style().get_font().gecko.mAllowZoom { self.device().zoom_text(Au::from(size)).into() } else { size } } /// (Servo doesn't do text-zoom) #[cfg(feature = "servo")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { size } } /// An iterator over a slice of computed values #[derive(Clone)] pub struct ComputedVecIter<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> { cx: &'cx Context<'cx_a>, values: &'a [S], } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ComputedVecIter<'a, 'cx, 'cx_a, S> { /// Construct an iterator from a slice of specified values and a context pub fn new(cx: &'cx Context<'cx_a>, values: &'a [S]) -> Self { ComputedVecIter { cx: cx, values: values, } } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ExactSizeIterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { fn len(&self) -> usize { self.values.len() } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> Iterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { type Item = S::ComputedValue; fn next(&mut self) -> Option<Self::Item> { if let Some((next, rest)) = self.values.split_first() { let ret = next.to_computed_value(self.cx); self.values = rest; Some(ret) } else { None } } fn size_hint(&self) -> (usize, Option<usize>) { (self.values.len(), Some(self.values.len())) } } /// A trait to represent the conversion between computed and specified values. /// /// This trait is derivable with `#[derive(ToComputedValue)]`. The derived /// implementation just calls `ToComputedValue::to_computed_value` on each field /// of the passed value, or `Clone::clone` if the field is annotated with /// `#[compute(clone)]`. pub trait ToComputedValue { /// The computed value type we're going to be converted to. type ComputedValue; /// Convert a specified value to a computed value, using itself and the data /// inside the `Context`. #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue; #[inline] /// Convert a computed value to specified value form. /// /// This will be used for recascading during animation. /// Such from_computed_valued values should recompute to the same value. fn from_computed_value(computed: &Self::ComputedValue) -> Self; } impl<A, B> ToComputedValue for (A, B) where A: ToComputedValue, B: ToComputedValue, { type ComputedValue = ( <A as ToComputedValue>::ComputedValue, <B as ToComputedValue>::ComputedValue, ); #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { (self.0.to_computed_value(context), self.1.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { (A::from_computed_value(&computed.0), B::from_computed_value(&computed.1)) } } impl<T> ToComputedValue for Option<T> where T: ToComputedValue { type ComputedValue = Option<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.as_ref().map(|item| item.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.as_ref().map(T::from_computed_value) } } impl<T> ToComputedValue for Size2D<T> where T: ToComputedValue { type ComputedValue = Size2D<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Size2D::new( self.width.to_computed_value(context), self.height.to_computed_value(context), ) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Size2D::new( T::from_computed_value(&computed.width), T::from_computed_value(&computed.height), ) } } impl<T> ToComputedValue for Vec<T> where T: ToComputedValue { type ComputedValue = Vec<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect() } }
#[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Box::new(T::to_computed_value(self, context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Box::new(T::from_computed_value(computed)) } } impl<T> ToComputedValue for Box<[T]> where T: ToComputedValue { type ComputedValue = Box<[<T as ToComputedValue>::ComputedValue]>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect::<Vec<_>>().into_boxed_slice() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect::<Vec<_>>().into_boxed_slice() } } trivial_to_computed_value!(()); trivial_to_computed_value!(bool); trivial_to_computed_value!(f32); trivial_to_computed_value!(i32); trivial_to_computed_value!(u8); trivial_to_computed_value!(u16); trivial_to_computed_value!(u32); trivial_to_computed_value!(Atom); trivial_to_computed_value!(BorderStyle); trivial_to_computed_value!(Cursor); trivial_to_computed_value!(Namespace); trivial_to_computed_value!(String); trivial_to_computed_value!(Box<str>); /// A `<number>` value. pub type Number = CSSFloat; /// A wrapper of Number, but the value >= 0. pub type NonNegativeNumber = NonNegative<CSSFloat>; impl From<CSSFloat> for NonNegativeNumber { #[inline] fn from(number: CSSFloat) -> NonNegativeNumber { NonNegative::<CSSFloat>(number) } } impl From<NonNegativeNumber> for CSSFloat { #[inline] fn from(number: NonNegativeNumber) -> CSSFloat { number.0 } } /// A wrapper of Number, but the value >= 1. pub type GreaterThanOrEqualToOneNumber = GreaterThanOrEqualToOne<CSSFloat>; impl From<CSSFloat> for GreaterThanOrEqualToOneNumber { #[inline] fn from(number: CSSFloat) -> GreaterThanOrEqualToOneNumber { GreaterThanOrEqualToOne::<CSSFloat>(number) } } impl From<GreaterThanOrEqualToOneNumber> for CSSFloat { #[inline] fn from(number: GreaterThanOrEqualToOneNumber) -> CSSFloat { number.0 } } #[allow(missing_docs)] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToCss)] pub enum NumberOrPercentage { Percentage(Percentage), Number(Number), } impl ToComputedValue for specified::NumberOrPercentage { type ComputedValue = NumberOrPercentage; #[inline] fn to_computed_value(&self, context: &Context) -> NumberOrPercentage { match *self { specified::NumberOrPercentage::Percentage(percentage) => NumberOrPercentage::Percentage(percentage.to_computed_value(context)), specified::NumberOrPercentage::Number(number) => NumberOrPercentage::Number(number.to_computed_value(context)), } } #[inline] fn from_computed_value(computed: &NumberOrPercentage) -> Self { match *computed { NumberOrPercentage::Percentage(percentage) => specified::NumberOrPercentage::Percentage(ToComputedValue::from_computed_value(&percentage)), NumberOrPercentage::Number(number) => specified::NumberOrPercentage::Number(ToComputedValue::from_computed_value(&number)), } } } /// A type used for opacity. pub type Opacity = CSSFloat; /// A `<integer>` value. pub type Integer = CSSInteger; /// <integer> | auto pub type IntegerOrAuto = Either<CSSInteger, Auto>; impl IntegerOrAuto { /// Returns the integer value if it is an integer, otherwise return /// the given value. pub fn integer_or(&self, auto_value: CSSInteger) -> CSSInteger { match *self { Either::First(n) => n, Either::Second(Auto) => auto_value, } } } /// A wrapper of Integer, but only accept a value >= 1. pub type PositiveInteger = GreaterThanOrEqualToOne<CSSInteger>; impl From<CSSInteger> for PositiveInteger { #[inline] fn from(int: CSSInteger) -> PositiveInteger { GreaterThanOrEqualToOne::<CSSInteger>(int) } } /// PositiveInteger | auto pub type PositiveIntegerOrAuto = Either<PositiveInteger, Auto>; /// <length> | <percentage> | <number> pub type LengthOrPercentageOrNumber = Either<Number, LengthOrPercentage>; /// NonNegativeLengthOrPercentage | NonNegativeNumber pub type NonNegativeLengthOrPercentageOrNumber = Either<NonNegativeNumber, NonNegativeLengthOrPercentage>; #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, PartialEq)] /// A computed cliprect for clip and image-region pub struct ClipRect { pub top: Option<Length>, pub right: Option<Length>, pub bottom: Option<Length>, pub left: Option<Length>, } impl ToCss for ClipRect { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("rect(")?; if let Some(top) = self.top { top.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(right) = self.right { right.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(bottom) = self.bottom { bottom.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(left) = self.left { left.to_css(dest)?; } else { dest.write_str("auto")?; } dest.write_str(")") } } /// rect(...) | auto pub type ClipRectOrAuto = Either<ClipRect, Auto>; /// The computed value of a grid `<track-breadth>` pub type TrackBreadth = GenericTrackBreadth<LengthOrPercentage>; /// The computed value of a grid `<track-size>` pub type TrackSize = GenericTrackSize<LengthOrPercentage>; /// The computed value of a grid `<track-list>` /// (could also be `<auto-track-list>` or `<explicit-track-list>`) pub type TrackList = GenericTrackList<LengthOrPercentage, Integer>; /// The computed value of a `<grid-line>`. pub type GridLine = GenericGridLine<Integer>; /// `<grid-template-rows> | <grid-template-columns>` pub type GridTemplateComponent = GenericGridTemplateComponent<LengthOrPercentage, Integer>; impl ClipRectOrAuto { /// Return an auto (default for clip-rect and image-region) value pub fn auto() -> Self { Either::Second(Auto) } /// Check if it is auto pub fn is_auto(&self) -> bool { match *self { Either::Second(_) => true, _ => false } } } /// <color> | auto pub type ColorOrAuto = Either<Color, Auto>; /// The computed value of a CSS `url()`, resolved relative to the stylesheet URL. #[cfg(feature = "servo")] #[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum ComputedUrl { /// The `url()` was invalid or it wasn't specified by the user. Invalid(#[ignore_malloc_size_of = "Arc"] Arc<String>), /// The resolved `url()` relative to the stylesheet URL. Valid(ServoUrl), } /// TODO: Properly build ComputedUrl for gecko #[cfg(feature = "gecko")] pub type ComputedUrl = specified::url::SpecifiedUrl; #[cfg(feature = "servo")] impl ComputedUrl { /// Returns the resolved url if it was valid. pub fn url(&self) -> Option<&ServoUrl> { match *self { ComputedUrl::Valid(ref url) => Some(url), _ => None, } } } #[cfg(feature = "servo")] impl ToCss for ComputedUrl { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let string = match *self { ComputedUrl::Valid(ref url) => url.as_str(), ComputedUrl::Invalid(ref invalid_string) => invalid_string, }; dest.write_str("url(")?; string.to_css(dest)?; dest.write_str(")") } } /// <url> | <none> pub type UrlOrNone = Either<ComputedUrl, None_>;
impl<T> ToComputedValue for Box<T> where T: ToComputedValue { type ComputedValue = Box<<T as ToComputedValue>::ComputedValue>;
random_line_split
strings3.rs
// Ok, here are a bunch of values-- some are `Strings`, some are `&strs`. Your // task is to call one of these two functions on each value depending on what // you think each value is. That is, add either `string_slice` or `string` // before the parentheses on each line. If you're right, it will compile! fn string_slice(arg: &str)
fn string(arg: String) { println!("{}", arg); } fn main() { string_slice("blue"); string("red".to_string()); string(String::from("hi")); string("rust is fun!".to_owned()); string("nice weather".into()); string(format!("Interpolation {}", "Station")); string_slice(&String::from("abc")[0..1]); string_slice(" hello there ".trim()); string("Happy Monday!".to_string().replace("Mon", "Tues")); string("mY sHiFt KeY iS sTiCkY".to_lowercase()); }
{ println!("{}", arg); }
identifier_body
strings3.rs
// Ok, here are a bunch of values-- some are `Strings`, some are `&strs`. Your // task is to call one of these two functions on each value depending on what // you think each value is. That is, add either `string_slice` or `string` // before the parentheses on each line. If you're right, it will compile!
string("red".to_string()); string(String::from("hi")); string("rust is fun!".to_owned()); string("nice weather".into()); string(format!("Interpolation {}", "Station")); string_slice(&String::from("abc")[0..1]); string_slice(" hello there ".trim()); string("Happy Monday!".to_string().replace("Mon", "Tues")); string("mY sHiFt KeY iS sTiCkY".to_lowercase()); }
fn string_slice(arg: &str) { println!("{}", arg); } fn string(arg: String) { println!("{}", arg); } fn main() { string_slice("blue");
random_line_split
strings3.rs
// Ok, here are a bunch of values-- some are `Strings`, some are `&strs`. Your // task is to call one of these two functions on each value depending on what // you think each value is. That is, add either `string_slice` or `string` // before the parentheses on each line. If you're right, it will compile! fn string_slice(arg: &str) { println!("{}", arg); } fn
(arg: String) { println!("{}", arg); } fn main() { string_slice("blue"); string("red".to_string()); string(String::from("hi")); string("rust is fun!".to_owned()); string("nice weather".into()); string(format!("Interpolation {}", "Station")); string_slice(&String::from("abc")[0..1]); string_slice(" hello there ".trim()); string("Happy Monday!".to_string().replace("Mon", "Tues")); string("mY sHiFt KeY iS sTiCkY".to_lowercase()); }
string
identifier_name
mod.rs
Self::Utf8Error(Some(Box::new(e))) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::UnexpectedBitWidth { expected, actual } => write!( f, "Error reading flexbuffer: Expected bitwidth: {:?}, found bitwidth: {:?}", expected, actual ), Self::UnexpectedFlexbufferType { expected, actual } => write!( f, "Error reading flexbuffer: Expected type: {:?}, found type: {:?}", expected, actual ), _ => write!(f, "Error reading flexbuffer: {:?}", self), } } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error +'static)> { if let Self::Utf8Error(Some(e)) = self { Some(e) } else { None } } } pub trait ReadLE: crate::private::Sealed + std::marker::Sized { const VECTOR_TYPE: FlexBufferType; const WIDTH: BitWidth; } macro_rules! rle { ($T: ty, $VECTOR_TYPE: ident, $WIDTH: ident) => { impl ReadLE for $T { const VECTOR_TYPE: FlexBufferType = FlexBufferType::$VECTOR_TYPE; const WIDTH: BitWidth = BitWidth::$WIDTH; } }; } rle!(u8, VectorUInt, W8); rle!(u16, VectorUInt, W16); rle!(u32, VectorUInt, W32); rle!(u64, VectorUInt, W64); rle!(i8, VectorInt, W8); rle!(i16, VectorInt, W16); rle!(i32, VectorInt, W32); rle!(i64, VectorInt, W64); rle!(f32, VectorFloat, W32); rle!(f64, VectorFloat, W64); macro_rules! as_default { ($as: ident, $get: ident, $T: ty) => { pub fn $as(&self) -> $T { self.$get().unwrap_or_default() } }; } /// `Reader`s allow access to data stored in a Flexbuffer. /// /// Each reader represents a single address in the buffer so data is read lazily. Start a reader /// by calling `get_root` on your flexbuffer `&[u8]`. /// /// - The `get_T` methods return a `Result<T, Error>`. They return an OK value if and only if the /// flexbuffer type matches `T`. This is analogous to the behavior of Rust's json library, though /// with Result instead of Option. /// - The `as_T` methods will try their best to return to a value of type `T` /// (by casting or even parsing a string if necessary) but ultimately returns `T::default` if it /// fails. This behavior is analogous to that of flexbuffers C++. pub struct Reader<B> { fxb_type: FlexBufferType, width: BitWidth, address: usize, buffer: B, } impl<B: Buffer> Clone for Reader<B> { fn clone(&self) -> Self { Reader { fxb_type: self.fxb_type, width: self.width, address: self.address, buffer: self.buffer.shallow_copy(), } } } impl<B: Buffer> Default for Reader<B> { fn default() -> Self { Reader { fxb_type: FlexBufferType::default(), width: BitWidth::default(), address: usize::default(), buffer: B::empty(), } } } // manual implementation of Debug because buffer slice can't be automatically displayed impl<B> std::fmt::Debug for Reader<B> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // skips buffer field f.debug_struct("Reader") .field("fxb_type", &self.fxb_type) .field("width", &self.width) .field("address", &self.address) .finish() } } macro_rules! try_cast_fn { ($name: ident, $full_width: ident, $Ty: ident) => { pub fn $name(&self) -> $Ty { self.$full_width().try_into().unwrap_or_default() } } } fn safe_sub(a: usize, b: usize) -> Result<usize, Error> { a.checked_sub(b).ok_or(Error::FlexbufferOutOfBounds) } fn deref_offset(buffer: &[u8], address: usize, width: BitWidth) -> Result<usize, Error> { let off = read_usize(buffer, address, width); safe_sub(address, off) } impl<B: Buffer> Reader<B> { fn new( buffer: B, mut address: usize, mut fxb_type: FlexBufferType, width: BitWidth, parent_width: BitWidth, ) -> Result<Self, Error> { if fxb_type.is_reference() { address = deref_offset(&buffer, address, parent_width)?; // Indirects were dereferenced. if let Some(t) = fxb_type.to_direct() { fxb_type = t; } } Ok(Reader { address, fxb_type, width, buffer, }) } /// Parses the flexbuffer from the given buffer. Assumes the flexbuffer root is the last byte /// of the buffer. pub fn get_root(buffer: B) -> Result<Self, Error> { let end = buffer.len(); if end < 3 { return Err(Error::FlexbufferOutOfBounds); } // Last byte is the root width. let root_width = BitWidth::from_nbytes(buffer[end - 1]).ok_or(Error::InvalidRootWidth)?; // Second last byte is root type. let (fxb_type, width) = unpack_type(buffer[end - 2])?; // Location of root data. (BitWidth bits before root type) let address = safe_sub(end - 2, root_width.n_bytes())?; Self::new(buffer, address, fxb_type, width, root_width) } /// Convenience function to get the underlying buffer. By using `shallow_copy`, this preserves /// the lifetime that the underlying buffer has. pub fn buffer(&self) -> B { self.buffer.shallow_copy() } /// Returns the FlexBufferType of this Reader. pub fn flexbuffer_type(&self) -> FlexBufferType { self.fxb_type } /// Returns the bitwidth of this Reader. pub fn bitwidth(&self) -> BitWidth { self.width } /// Returns the length of the Flexbuffer. If the type has no length, or if an error occurs, /// 0 is returned. pub fn length(&self) -> usize { if let Some(len) = self.fxb_type.fixed_length_vector_length() { len } else if self.fxb_type.has_length_slot() && self.address >= self.width.n_bytes() { read_usize(&self.buffer, self.address - self.width.n_bytes(), self.width) } else { 0 } } /// Returns true if the flexbuffer is aligned to 8 bytes. This guarantees, for valid /// flexbuffers, that the data is correctly aligned in memory and slices can be read directly /// e.g. with `get_f64s` or `get_i16s`. #[inline] pub fn is_aligned(&self) -> bool { (self.buffer.as_ptr() as usize).rem(8) == 0 } as_default!(as_vector, get_vector, VectorReader<B>); as_default!(as_map, get_map, MapReader<B>); fn expect_type(&self, ty: FlexBufferType) -> Result<(), Error> { if self.fxb_type == ty { Ok(()) } else { Err(Error::UnexpectedFlexbufferType { expected: ty, actual: self.fxb_type, }) } } fn expect_bw(&self, bw: BitWidth) -> Result<(), Error> { if self.width == bw { Ok(()) } else { Err(Error::UnexpectedBitWidth { expected: bw, actual: self.width, }) } } /// Directly reads a slice of type `T` where `T` is one of `u8,u16,u32,u64,i8,i16,i32,i64,f32,f64`. /// Returns Err if the type, bitwidth, or memory alignment does not match. Since the bitwidth is /// dynamic, its better to use a VectorReader unless you know your data and performance is critical. #[cfg(target_endian = "little")] #[deprecated( since = "0.3.0", note = "This function is unsafe - if this functionality is needed use `Reader::buffer::align_to`" )] pub fn get_slice<T: ReadLE>(&self) -> Result<&[T], Error> { if self.flexbuffer_type().typed_vector_type()!= T::VECTOR_TYPE.typed_vector_type() { self.expect_type(T::VECTOR_TYPE)?; } if self.bitwidth().n_bytes()!= std::mem::size_of::<T>() { self.expect_bw(T::WIDTH)?; } let end = self.address + self.length() * std::mem::size_of::<T>(); let slice: &[u8] = self .buffer .get(self.address..end) .ok_or(Error::FlexbufferOutOfBounds)?; // `align_to` is required because the point of this function is to directly hand back a // slice of scalars. This can fail because Rust's default allocator is not 16byte aligned // (though in practice this only happens for small buffers). let (pre, mid, suf) = unsafe { slice.align_to::<T>() }; if pre.is_empty() && suf.is_empty() { Ok(mid) } else { Err(Error::AlignmentError) } } /// Returns the value of the reader if it is a boolean. /// Otherwise Returns error. pub fn get_bool(&self) -> Result<bool, Error> { self.expect_type(FlexBufferType::Bool)?; Ok( self.buffer[self.address..self.address + self.width.n_bytes()] .iter() .any(|&b| b!= 0), ) } /// Gets the length of the key if this type is a key. /// /// Otherwise, returns an error. #[inline] fn get_key_len(&self) -> Result<usize, Error> { self.expect_type(FlexBufferType::Key)?; let (length, _) = self.buffer[self.address..] .iter() .enumerate() .find(|(_, &b)| b == b'\0') .unwrap_or((0, &0)); Ok(length) } /// Retrieves the string value up until the first `\0` character. pub fn get_key(&self) -> Result<B::BufferString, Error> { let bytes = self.buffer .slice(self.address..self.address + self.get_key_len()?) .ok_or(Error::IndexOutOfBounds)?; Ok(bytes.buffer_str()?) } pub fn get_blob(&self) -> Result<Blob<B>, Error> { self.expect_type(FlexBufferType::Blob)?; Ok(Blob( self.buffer .slice(self.address..self.address + self.length()) .ok_or(Error::IndexOutOfBounds)? )) } pub fn as_blob(&self) -> Blob<B> { self.get_blob().unwrap_or(Blob(B::empty())) } /// Retrieves str pointer, errors if invalid UTF-8, or the provided index /// is out of bounds. pub fn get_str(&self) -> Result<B::BufferString, Error> { self.expect_type(FlexBufferType::String)?; let bytes = self.buffer.slice(self.address..self.address + self.length()); Ok(bytes.ok_or(Error::ReadUsizeOverflowed)?.buffer_str()?) }
return Err(Error::FlexbufferOutOfBounds); } let keys_offset_address = self.address - 3 * self.width.n_bytes(); let keys_width = { let kw_addr = self.address - 2 * self.width.n_bytes(); let kw = read_usize(&self.buffer, kw_addr, self.width); BitWidth::from_nbytes(kw).ok_or(Error::InvalidMapKeysVectorWidth) }?; Ok((keys_offset_address, keys_width)) } pub fn get_map(&self) -> Result<MapReader<B>, Error> { let (keys_offset_address, keys_width) = self.get_map_info()?; let keys_address = deref_offset(&self.buffer, keys_offset_address, self.width)?; // TODO(cneo): Check that vectors length equals keys length. Ok(MapReader { buffer: self.buffer.shallow_copy(), values_address: self.address, values_width: self.width, keys_address, keys_width, length: self.length(), }) } /// Tries to read a FlexBufferType::UInt. Returns Err if the type is not a UInt or if the /// address is out of bounds. pub fn get_u64(&self) -> Result<u64, Error> { self.expect_type(FlexBufferType::UInt)?; let cursor = self .buffer .get(self.address..self.address + self.width.n_bytes()); match self.width { BitWidth::W8 => cursor.map(|s| s[0] as u8).map(Into::into), BitWidth::W16 => cursor .and_then(|s| s.try_into().ok()) .map(<u16>::from_le_bytes) .map(Into::into), BitWidth::W32 => cursor .and_then(|s| s.try_into().ok()) .map(<u32>::from_le_bytes) .map(Into::into), BitWidth::W64 => cursor .and_then(|s| s.try_into().ok()) .map(<u64>::from_le_bytes), } .ok_or(Error::FlexbufferOutOfBounds) } /// Tries to read a FlexBufferType::Int. Returns Err if the type is not a UInt or if the /// address is out of bounds. pub fn get_i64(&self) -> Result<i64, Error> { self.expect_type(FlexBufferType::Int)?; let cursor = self .buffer .get(self.address..self.address + self.width.n_bytes()); match self.width { BitWidth::W8 => cursor.map(|s| s[0] as i8).map(Into::into), BitWidth::W16 => cursor .and_then(|s| s.try_into().ok()) .map(<i16>::from_le_bytes) .map(Into::into), BitWidth::W32 => cursor .and_then(|s| s.try_into().ok()) .map(<i32>::from_le_bytes) .map(Into::into), BitWidth::W64 => cursor .and_then(|s| s.try_into().ok()) .map(<i64>::from_le_bytes), } .ok_or(Error::FlexbufferOutOfBounds) } /// Tries to read a FlexBufferType::Float. Returns Err if the type is not a UInt, if the /// address is out of bounds, or if its a f16 or f8 (not currently supported). pub fn get_f64(&self) -> Result<f64, Error> { self.expect_type(FlexBufferType::Float)?; let cursor = self .buffer .get(self.address..self.address + self.width.n_bytes()); match self.width { BitWidth::W8 | BitWidth::W16 => return Err(Error::InvalidPackedType), BitWidth::W32 => cursor .and_then(|s| s.try_into().ok()) .map(f32_from_le_bytes) .map(Into::into), BitWidth::W64 => cursor .and_then(|s| s.try_into().ok()) .map(f64_from_le_bytes), } .ok_or(Error::FlexbufferOutOfBounds) } pub fn as_bool(&self) -> bool { use FlexBufferType::*; match self.fxb_type { Bool => self.get_bool().unwrap_or_default(), UInt => self.as_u64()!= 0, Int => self.as_i64()!= 0, Float => self.as_f64().abs() > std::f64::EPSILON, String | Key =>!self.as_str().is_empty(), Null => false, Blob => self.length()!= 0, ty if ty.is_vector() => self.length()!= 0, _ => unreachable!(), } } /// Returns a u64, casting if necessary. For Maps and Vectors, their length is /// returned. If anything fails, 0 is returned. pub fn as_u64(&self) -> u64 { match self.fxb_type { FlexBufferType::UInt => self.get_u64().unwrap_or_default(), FlexBufferType::Int => self .get_i64() .unwrap_or_default() .try_into() .unwrap_or_default(), FlexBufferType::Float => self.get_f64().unwrap_or_default() as u64, FlexBufferType::String => { if let Ok(s) = self.get_str() { if let Ok(f) = u64::from_str(&s) { return f; } } 0 } _ if self.fxb_type.is_vector() => self.length() as u64, _ => 0, } } try_cast_fn!(as_u32, as_u64, u32); try_cast_fn!(as_u16, as_u64, u16); try_cast_fn!(as_u8, as_u64, u8); /// Returns an i64, casting if necessary. For Maps and Vectors, their length is /// returned. If anything fails, 0 is returned. pub fn as_i64(&self) -> i64 { match self.fxb_type { FlexBufferType::Int => self.get_i64().unwrap_or_default(), FlexBufferType::UInt => self .get_u64() .unwrap_or_default() .try_into() .unwrap_or_default(), FlexBufferType::Float => self.get_f64().unwrap_or_default() as i64, FlexBufferType::String => { if let Ok(s) = self.get_str() { if let Ok(f) = i64::from_str(&s) { return f; } } 0 } _ if self.fxb_type.is_vector() => self.length() as i64, _ => 0, } } try_cast_fn!(as_i32, as_i64, i32); try_cast_fn!(as_i16, as_i64, i16); try_cast_fn!(as_i8, as_i64, i8); /// Returns an f64, casting if necessary. For Maps and Vectors, their length is /// returned. If anything fails, 0 is returned. pub fn as_f64(&self) -> f64 { match self.fxb_type { FlexBufferType::Int => self.get_i64().unwrap_or_default() as f64, FlexBufferType::UInt => self.get_u64().unwrap_or_default() as f64, FlexBufferType::Float => self.get_f64().unwrap_or_default(), FlexBufferType::String => { if let Ok(s)
fn get_map_info(&self) -> Result<(usize, BitWidth), Error> { self.expect_type(FlexBufferType::Map)?; if 3 * self.width.n_bytes() >= self.address {
random_line_split
mod.rs
Self::Utf8Error(Some(Box::new(e))) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::UnexpectedBitWidth { expected, actual } => write!( f, "Error reading flexbuffer: Expected bitwidth: {:?}, found bitwidth: {:?}", expected, actual ), Self::UnexpectedFlexbufferType { expected, actual } => write!( f, "Error reading flexbuffer: Expected type: {:?}, found type: {:?}", expected, actual ), _ => write!(f, "Error reading flexbuffer: {:?}", self), } } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error +'static)> { if let Self::Utf8Error(Some(e)) = self { Some(e) } else { None } } } pub trait ReadLE: crate::private::Sealed + std::marker::Sized { const VECTOR_TYPE: FlexBufferType; const WIDTH: BitWidth; } macro_rules! rle { ($T: ty, $VECTOR_TYPE: ident, $WIDTH: ident) => { impl ReadLE for $T { const VECTOR_TYPE: FlexBufferType = FlexBufferType::$VECTOR_TYPE; const WIDTH: BitWidth = BitWidth::$WIDTH; } }; } rle!(u8, VectorUInt, W8); rle!(u16, VectorUInt, W16); rle!(u32, VectorUInt, W32); rle!(u64, VectorUInt, W64); rle!(i8, VectorInt, W8); rle!(i16, VectorInt, W16); rle!(i32, VectorInt, W32); rle!(i64, VectorInt, W64); rle!(f32, VectorFloat, W32); rle!(f64, VectorFloat, W64); macro_rules! as_default { ($as: ident, $get: ident, $T: ty) => { pub fn $as(&self) -> $T { self.$get().unwrap_or_default() } }; } /// `Reader`s allow access to data stored in a Flexbuffer. /// /// Each reader represents a single address in the buffer so data is read lazily. Start a reader /// by calling `get_root` on your flexbuffer `&[u8]`. /// /// - The `get_T` methods return a `Result<T, Error>`. They return an OK value if and only if the /// flexbuffer type matches `T`. This is analogous to the behavior of Rust's json library, though /// with Result instead of Option. /// - The `as_T` methods will try their best to return to a value of type `T` /// (by casting or even parsing a string if necessary) but ultimately returns `T::default` if it /// fails. This behavior is analogous to that of flexbuffers C++. pub struct Reader<B> { fxb_type: FlexBufferType, width: BitWidth, address: usize, buffer: B, } impl<B: Buffer> Clone for Reader<B> { fn clone(&self) -> Self { Reader { fxb_type: self.fxb_type, width: self.width, address: self.address, buffer: self.buffer.shallow_copy(), } } } impl<B: Buffer> Default for Reader<B> { fn default() -> Self { Reader { fxb_type: FlexBufferType::default(), width: BitWidth::default(), address: usize::default(), buffer: B::empty(), } } } // manual implementation of Debug because buffer slice can't be automatically displayed impl<B> std::fmt::Debug for Reader<B> { fn
(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // skips buffer field f.debug_struct("Reader") .field("fxb_type", &self.fxb_type) .field("width", &self.width) .field("address", &self.address) .finish() } } macro_rules! try_cast_fn { ($name: ident, $full_width: ident, $Ty: ident) => { pub fn $name(&self) -> $Ty { self.$full_width().try_into().unwrap_or_default() } } } fn safe_sub(a: usize, b: usize) -> Result<usize, Error> { a.checked_sub(b).ok_or(Error::FlexbufferOutOfBounds) } fn deref_offset(buffer: &[u8], address: usize, width: BitWidth) -> Result<usize, Error> { let off = read_usize(buffer, address, width); safe_sub(address, off) } impl<B: Buffer> Reader<B> { fn new( buffer: B, mut address: usize, mut fxb_type: FlexBufferType, width: BitWidth, parent_width: BitWidth, ) -> Result<Self, Error> { if fxb_type.is_reference() { address = deref_offset(&buffer, address, parent_width)?; // Indirects were dereferenced. if let Some(t) = fxb_type.to_direct() { fxb_type = t; } } Ok(Reader { address, fxb_type, width, buffer, }) } /// Parses the flexbuffer from the given buffer. Assumes the flexbuffer root is the last byte /// of the buffer. pub fn get_root(buffer: B) -> Result<Self, Error> { let end = buffer.len(); if end < 3 { return Err(Error::FlexbufferOutOfBounds); } // Last byte is the root width. let root_width = BitWidth::from_nbytes(buffer[end - 1]).ok_or(Error::InvalidRootWidth)?; // Second last byte is root type. let (fxb_type, width) = unpack_type(buffer[end - 2])?; // Location of root data. (BitWidth bits before root type) let address = safe_sub(end - 2, root_width.n_bytes())?; Self::new(buffer, address, fxb_type, width, root_width) } /// Convenience function to get the underlying buffer. By using `shallow_copy`, this preserves /// the lifetime that the underlying buffer has. pub fn buffer(&self) -> B { self.buffer.shallow_copy() } /// Returns the FlexBufferType of this Reader. pub fn flexbuffer_type(&self) -> FlexBufferType { self.fxb_type } /// Returns the bitwidth of this Reader. pub fn bitwidth(&self) -> BitWidth { self.width } /// Returns the length of the Flexbuffer. If the type has no length, or if an error occurs, /// 0 is returned. pub fn length(&self) -> usize { if let Some(len) = self.fxb_type.fixed_length_vector_length() { len } else if self.fxb_type.has_length_slot() && self.address >= self.width.n_bytes() { read_usize(&self.buffer, self.address - self.width.n_bytes(), self.width) } else { 0 } } /// Returns true if the flexbuffer is aligned to 8 bytes. This guarantees, for valid /// flexbuffers, that the data is correctly aligned in memory and slices can be read directly /// e.g. with `get_f64s` or `get_i16s`. #[inline] pub fn is_aligned(&self) -> bool { (self.buffer.as_ptr() as usize).rem(8) == 0 } as_default!(as_vector, get_vector, VectorReader<B>); as_default!(as_map, get_map, MapReader<B>); fn expect_type(&self, ty: FlexBufferType) -> Result<(), Error> { if self.fxb_type == ty { Ok(()) } else { Err(Error::UnexpectedFlexbufferType { expected: ty, actual: self.fxb_type, }) } } fn expect_bw(&self, bw: BitWidth) -> Result<(), Error> { if self.width == bw { Ok(()) } else { Err(Error::UnexpectedBitWidth { expected: bw, actual: self.width, }) } } /// Directly reads a slice of type `T` where `T` is one of `u8,u16,u32,u64,i8,i16,i32,i64,f32,f64`. /// Returns Err if the type, bitwidth, or memory alignment does not match. Since the bitwidth is /// dynamic, its better to use a VectorReader unless you know your data and performance is critical. #[cfg(target_endian = "little")] #[deprecated( since = "0.3.0", note = "This function is unsafe - if this functionality is needed use `Reader::buffer::align_to`" )] pub fn get_slice<T: ReadLE>(&self) -> Result<&[T], Error> { if self.flexbuffer_type().typed_vector_type()!= T::VECTOR_TYPE.typed_vector_type() { self.expect_type(T::VECTOR_TYPE)?; } if self.bitwidth().n_bytes()!= std::mem::size_of::<T>() { self.expect_bw(T::WIDTH)?; } let end = self.address + self.length() * std::mem::size_of::<T>(); let slice: &[u8] = self .buffer .get(self.address..end) .ok_or(Error::FlexbufferOutOfBounds)?; // `align_to` is required because the point of this function is to directly hand back a // slice of scalars. This can fail because Rust's default allocator is not 16byte aligned // (though in practice this only happens for small buffers). let (pre, mid, suf) = unsafe { slice.align_to::<T>() }; if pre.is_empty() && suf.is_empty() { Ok(mid) } else { Err(Error::AlignmentError) } } /// Returns the value of the reader if it is a boolean. /// Otherwise Returns error. pub fn get_bool(&self) -> Result<bool, Error> { self.expect_type(FlexBufferType::Bool)?; Ok( self.buffer[self.address..self.address + self.width.n_bytes()] .iter() .any(|&b| b!= 0), ) } /// Gets the length of the key if this type is a key. /// /// Otherwise, returns an error. #[inline] fn get_key_len(&self) -> Result<usize, Error> { self.expect_type(FlexBufferType::Key)?; let (length, _) = self.buffer[self.address..] .iter() .enumerate() .find(|(_, &b)| b == b'\0') .unwrap_or((0, &0)); Ok(length) } /// Retrieves the string value up until the first `\0` character. pub fn get_key(&self) -> Result<B::BufferString, Error> { let bytes = self.buffer .slice(self.address..self.address + self.get_key_len()?) .ok_or(Error::IndexOutOfBounds)?; Ok(bytes.buffer_str()?) } pub fn get_blob(&self) -> Result<Blob<B>, Error> { self.expect_type(FlexBufferType::Blob)?; Ok(Blob( self.buffer .slice(self.address..self.address + self.length()) .ok_or(Error::IndexOutOfBounds)? )) } pub fn as_blob(&self) -> Blob<B> { self.get_blob().unwrap_or(Blob(B::empty())) } /// Retrieves str pointer, errors if invalid UTF-8, or the provided index /// is out of bounds. pub fn get_str(&self) -> Result<B::BufferString, Error> { self.expect_type(FlexBufferType::String)?; let bytes = self.buffer.slice(self.address..self.address + self.length()); Ok(bytes.ok_or(Error::ReadUsizeOverflowed)?.buffer_str()?) } fn get_map_info(&self) -> Result<(usize, BitWidth), Error> { self.expect_type(FlexBufferType::Map)?; if 3 * self.width.n_bytes() >= self.address { return Err(Error::FlexbufferOutOfBounds); } let keys_offset_address = self.address - 3 * self.width.n_bytes(); let keys_width = { let kw_addr = self.address - 2 * self.width.n_bytes(); let kw = read_usize(&self.buffer, kw_addr, self.width); BitWidth::from_nbytes(kw).ok_or(Error::InvalidMapKeysVectorWidth) }?; Ok((keys_offset_address, keys_width)) } pub fn get_map(&self) -> Result<MapReader<B>, Error> { let (keys_offset_address, keys_width) = self.get_map_info()?; let keys_address = deref_offset(&self.buffer, keys_offset_address, self.width)?; // TODO(cneo): Check that vectors length equals keys length. Ok(MapReader { buffer: self.buffer.shallow_copy(), values_address: self.address, values_width: self.width, keys_address, keys_width, length: self.length(), }) } /// Tries to read a FlexBufferType::UInt. Returns Err if the type is not a UInt or if the /// address is out of bounds. pub fn get_u64(&self) -> Result<u64, Error> { self.expect_type(FlexBufferType::UInt)?; let cursor = self .buffer .get(self.address..self.address + self.width.n_bytes()); match self.width { BitWidth::W8 => cursor.map(|s| s[0] as u8).map(Into::into), BitWidth::W16 => cursor .and_then(|s| s.try_into().ok()) .map(<u16>::from_le_bytes) .map(Into::into), BitWidth::W32 => cursor .and_then(|s| s.try_into().ok()) .map(<u32>::from_le_bytes) .map(Into::into), BitWidth::W64 => cursor .and_then(|s| s.try_into().ok()) .map(<u64>::from_le_bytes), } .ok_or(Error::FlexbufferOutOfBounds) } /// Tries to read a FlexBufferType::Int. Returns Err if the type is not a UInt or if the /// address is out of bounds. pub fn get_i64(&self) -> Result<i64, Error> { self.expect_type(FlexBufferType::Int)?; let cursor = self .buffer .get(self.address..self.address + self.width.n_bytes()); match self.width { BitWidth::W8 => cursor.map(|s| s[0] as i8).map(Into::into), BitWidth::W16 => cursor .and_then(|s| s.try_into().ok()) .map(<i16>::from_le_bytes) .map(Into::into), BitWidth::W32 => cursor .and_then(|s| s.try_into().ok()) .map(<i32>::from_le_bytes) .map(Into::into), BitWidth::W64 => cursor .and_then(|s| s.try_into().ok()) .map(<i64>::from_le_bytes), } .ok_or(Error::FlexbufferOutOfBounds) } /// Tries to read a FlexBufferType::Float. Returns Err if the type is not a UInt, if the /// address is out of bounds, or if its a f16 or f8 (not currently supported). pub fn get_f64(&self) -> Result<f64, Error> { self.expect_type(FlexBufferType::Float)?; let cursor = self .buffer .get(self.address..self.address + self.width.n_bytes()); match self.width { BitWidth::W8 | BitWidth::W16 => return Err(Error::InvalidPackedType), BitWidth::W32 => cursor .and_then(|s| s.try_into().ok()) .map(f32_from_le_bytes) .map(Into::into), BitWidth::W64 => cursor .and_then(|s| s.try_into().ok()) .map(f64_from_le_bytes), } .ok_or(Error::FlexbufferOutOfBounds) } pub fn as_bool(&self) -> bool { use FlexBufferType::*; match self.fxb_type { Bool => self.get_bool().unwrap_or_default(), UInt => self.as_u64()!= 0, Int => self.as_i64()!= 0, Float => self.as_f64().abs() > std::f64::EPSILON, String | Key =>!self.as_str().is_empty(), Null => false, Blob => self.length()!= 0, ty if ty.is_vector() => self.length()!= 0, _ => unreachable!(), } } /// Returns a u64, casting if necessary. For Maps and Vectors, their length is /// returned. If anything fails, 0 is returned. pub fn as_u64(&self) -> u64 { match self.fxb_type { FlexBufferType::UInt => self.get_u64().unwrap_or_default(), FlexBufferType::Int => self .get_i64() .unwrap_or_default() .try_into() .unwrap_or_default(), FlexBufferType::Float => self.get_f64().unwrap_or_default() as u64, FlexBufferType::String => { if let Ok(s) = self.get_str() { if let Ok(f) = u64::from_str(&s) { return f; } } 0 } _ if self.fxb_type.is_vector() => self.length() as u64, _ => 0, } } try_cast_fn!(as_u32, as_u64, u32); try_cast_fn!(as_u16, as_u64, u16); try_cast_fn!(as_u8, as_u64, u8); /// Returns an i64, casting if necessary. For Maps and Vectors, their length is /// returned. If anything fails, 0 is returned. pub fn as_i64(&self) -> i64 { match self.fxb_type { FlexBufferType::Int => self.get_i64().unwrap_or_default(), FlexBufferType::UInt => self .get_u64() .unwrap_or_default() .try_into() .unwrap_or_default(), FlexBufferType::Float => self.get_f64().unwrap_or_default() as i64, FlexBufferType::String => { if let Ok(s) = self.get_str() { if let Ok(f) = i64::from_str(&s) { return f; } } 0 } _ if self.fxb_type.is_vector() => self.length() as i64, _ => 0, } } try_cast_fn!(as_i32, as_i64, i32); try_cast_fn!(as_i16, as_i64, i16); try_cast_fn!(as_i8, as_i64, i8); /// Returns an f64, casting if necessary. For Maps and Vectors, their length is /// returned. If anything fails, 0 is returned. pub fn as_f64(&self) -> f64 { match self.fxb_type { FlexBufferType::Int => self.get_i64().unwrap_or_default() as f64, FlexBufferType::UInt => self.get_u64().unwrap_or_default() as f64, FlexBufferType::Float => self.get_f64().unwrap_or_default(), FlexBufferType::String => { if let Ok(
fmt
identifier_name
mod.rs
Self::Utf8Error(Some(Box::new(e))) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::UnexpectedBitWidth { expected, actual } => write!( f, "Error reading flexbuffer: Expected bitwidth: {:?}, found bitwidth: {:?}", expected, actual ), Self::UnexpectedFlexbufferType { expected, actual } => write!( f, "Error reading flexbuffer: Expected type: {:?}, found type: {:?}", expected, actual ), _ => write!(f, "Error reading flexbuffer: {:?}", self), } } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error +'static)> { if let Self::Utf8Error(Some(e)) = self { Some(e) } else { None } } } pub trait ReadLE: crate::private::Sealed + std::marker::Sized { const VECTOR_TYPE: FlexBufferType; const WIDTH: BitWidth; } macro_rules! rle { ($T: ty, $VECTOR_TYPE: ident, $WIDTH: ident) => { impl ReadLE for $T { const VECTOR_TYPE: FlexBufferType = FlexBufferType::$VECTOR_TYPE; const WIDTH: BitWidth = BitWidth::$WIDTH; } }; } rle!(u8, VectorUInt, W8); rle!(u16, VectorUInt, W16); rle!(u32, VectorUInt, W32); rle!(u64, VectorUInt, W64); rle!(i8, VectorInt, W8); rle!(i16, VectorInt, W16); rle!(i32, VectorInt, W32); rle!(i64, VectorInt, W64); rle!(f32, VectorFloat, W32); rle!(f64, VectorFloat, W64); macro_rules! as_default { ($as: ident, $get: ident, $T: ty) => { pub fn $as(&self) -> $T { self.$get().unwrap_or_default() } }; } /// `Reader`s allow access to data stored in a Flexbuffer. /// /// Each reader represents a single address in the buffer so data is read lazily. Start a reader /// by calling `get_root` on your flexbuffer `&[u8]`. /// /// - The `get_T` methods return a `Result<T, Error>`. They return an OK value if and only if the /// flexbuffer type matches `T`. This is analogous to the behavior of Rust's json library, though /// with Result instead of Option. /// - The `as_T` methods will try their best to return to a value of type `T` /// (by casting or even parsing a string if necessary) but ultimately returns `T::default` if it /// fails. This behavior is analogous to that of flexbuffers C++. pub struct Reader<B> { fxb_type: FlexBufferType, width: BitWidth, address: usize, buffer: B, } impl<B: Buffer> Clone for Reader<B> { fn clone(&self) -> Self { Reader { fxb_type: self.fxb_type, width: self.width, address: self.address, buffer: self.buffer.shallow_copy(), } } } impl<B: Buffer> Default for Reader<B> { fn default() -> Self { Reader { fxb_type: FlexBufferType::default(), width: BitWidth::default(), address: usize::default(), buffer: B::empty(), } } } // manual implementation of Debug because buffer slice can't be automatically displayed impl<B> std::fmt::Debug for Reader<B> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // skips buffer field f.debug_struct("Reader") .field("fxb_type", &self.fxb_type) .field("width", &self.width) .field("address", &self.address) .finish() } } macro_rules! try_cast_fn { ($name: ident, $full_width: ident, $Ty: ident) => { pub fn $name(&self) -> $Ty { self.$full_width().try_into().unwrap_or_default() } } } fn safe_sub(a: usize, b: usize) -> Result<usize, Error> { a.checked_sub(b).ok_or(Error::FlexbufferOutOfBounds) } fn deref_offset(buffer: &[u8], address: usize, width: BitWidth) -> Result<usize, Error> { let off = read_usize(buffer, address, width); safe_sub(address, off) } impl<B: Buffer> Reader<B> { fn new( buffer: B, mut address: usize, mut fxb_type: FlexBufferType, width: BitWidth, parent_width: BitWidth, ) -> Result<Self, Error> { if fxb_type.is_reference() { address = deref_offset(&buffer, address, parent_width)?; // Indirects were dereferenced. if let Some(t) = fxb_type.to_direct() { fxb_type = t; } } Ok(Reader { address, fxb_type, width, buffer, }) } /// Parses the flexbuffer from the given buffer. Assumes the flexbuffer root is the last byte /// of the buffer. pub fn get_root(buffer: B) -> Result<Self, Error> { let end = buffer.len(); if end < 3 { return Err(Error::FlexbufferOutOfBounds); } // Last byte is the root width. let root_width = BitWidth::from_nbytes(buffer[end - 1]).ok_or(Error::InvalidRootWidth)?; // Second last byte is root type. let (fxb_type, width) = unpack_type(buffer[end - 2])?; // Location of root data. (BitWidth bits before root type) let address = safe_sub(end - 2, root_width.n_bytes())?; Self::new(buffer, address, fxb_type, width, root_width) } /// Convenience function to get the underlying buffer. By using `shallow_copy`, this preserves /// the lifetime that the underlying buffer has. pub fn buffer(&self) -> B { self.buffer.shallow_copy() } /// Returns the FlexBufferType of this Reader. pub fn flexbuffer_type(&self) -> FlexBufferType { self.fxb_type } /// Returns the bitwidth of this Reader. pub fn bitwidth(&self) -> BitWidth { self.width } /// Returns the length of the Flexbuffer. If the type has no length, or if an error occurs, /// 0 is returned. pub fn length(&self) -> usize { if let Some(len) = self.fxb_type.fixed_length_vector_length() { len } else if self.fxb_type.has_length_slot() && self.address >= self.width.n_bytes() { read_usize(&self.buffer, self.address - self.width.n_bytes(), self.width) } else { 0 } } /// Returns true if the flexbuffer is aligned to 8 bytes. This guarantees, for valid /// flexbuffers, that the data is correctly aligned in memory and slices can be read directly /// e.g. with `get_f64s` or `get_i16s`. #[inline] pub fn is_aligned(&self) -> bool { (self.buffer.as_ptr() as usize).rem(8) == 0 } as_default!(as_vector, get_vector, VectorReader<B>); as_default!(as_map, get_map, MapReader<B>); fn expect_type(&self, ty: FlexBufferType) -> Result<(), Error> { if self.fxb_type == ty { Ok(()) } else { Err(Error::UnexpectedFlexbufferType { expected: ty, actual: self.fxb_type, }) } } fn expect_bw(&self, bw: BitWidth) -> Result<(), Error> { if self.width == bw { Ok(()) } else { Err(Error::UnexpectedBitWidth { expected: bw, actual: self.width, }) } } /// Directly reads a slice of type `T` where `T` is one of `u8,u16,u32,u64,i8,i16,i32,i64,f32,f64`. /// Returns Err if the type, bitwidth, or memory alignment does not match. Since the bitwidth is /// dynamic, its better to use a VectorReader unless you know your data and performance is critical. #[cfg(target_endian = "little")] #[deprecated( since = "0.3.0", note = "This function is unsafe - if this functionality is needed use `Reader::buffer::align_to`" )] pub fn get_slice<T: ReadLE>(&self) -> Result<&[T], Error>
Err(Error::AlignmentError) } } /// Returns the value of the reader if it is a boolean. /// Otherwise Returns error. pub fn get_bool(&self) -> Result<bool, Error> { self.expect_type(FlexBufferType::Bool)?; Ok( self.buffer[self.address..self.address + self.width.n_bytes()] .iter() .any(|&b| b!= 0), ) } /// Gets the length of the key if this type is a key. /// /// Otherwise, returns an error. #[inline] fn get_key_len(&self) -> Result<usize, Error> { self.expect_type(FlexBufferType::Key)?; let (length, _) = self.buffer[self.address..] .iter() .enumerate() .find(|(_, &b)| b == b'\0') .unwrap_or((0, &0)); Ok(length) } /// Retrieves the string value up until the first `\0` character. pub fn get_key(&self) -> Result<B::BufferString, Error> { let bytes = self.buffer .slice(self.address..self.address + self.get_key_len()?) .ok_or(Error::IndexOutOfBounds)?; Ok(bytes.buffer_str()?) } pub fn get_blob(&self) -> Result<Blob<B>, Error> { self.expect_type(FlexBufferType::Blob)?; Ok(Blob( self.buffer .slice(self.address..self.address + self.length()) .ok_or(Error::IndexOutOfBounds)? )) } pub fn as_blob(&self) -> Blob<B> { self.get_blob().unwrap_or(Blob(B::empty())) } /// Retrieves str pointer, errors if invalid UTF-8, or the provided index /// is out of bounds. pub fn get_str(&self) -> Result<B::BufferString, Error> { self.expect_type(FlexBufferType::String)?; let bytes = self.buffer.slice(self.address..self.address + self.length()); Ok(bytes.ok_or(Error::ReadUsizeOverflowed)?.buffer_str()?) } fn get_map_info(&self) -> Result<(usize, BitWidth), Error> { self.expect_type(FlexBufferType::Map)?; if 3 * self.width.n_bytes() >= self.address { return Err(Error::FlexbufferOutOfBounds); } let keys_offset_address = self.address - 3 * self.width.n_bytes(); let keys_width = { let kw_addr = self.address - 2 * self.width.n_bytes(); let kw = read_usize(&self.buffer, kw_addr, self.width); BitWidth::from_nbytes(kw).ok_or(Error::InvalidMapKeysVectorWidth) }?; Ok((keys_offset_address, keys_width)) } pub fn get_map(&self) -> Result<MapReader<B>, Error> { let (keys_offset_address, keys_width) = self.get_map_info()?; let keys_address = deref_offset(&self.buffer, keys_offset_address, self.width)?; // TODO(cneo): Check that vectors length equals keys length. Ok(MapReader { buffer: self.buffer.shallow_copy(), values_address: self.address, values_width: self.width, keys_address, keys_width, length: self.length(), }) } /// Tries to read a FlexBufferType::UInt. Returns Err if the type is not a UInt or if the /// address is out of bounds. pub fn get_u64(&self) -> Result<u64, Error> { self.expect_type(FlexBufferType::UInt)?; let cursor = self .buffer .get(self.address..self.address + self.width.n_bytes()); match self.width { BitWidth::W8 => cursor.map(|s| s[0] as u8).map(Into::into), BitWidth::W16 => cursor .and_then(|s| s.try_into().ok()) .map(<u16>::from_le_bytes) .map(Into::into), BitWidth::W32 => cursor .and_then(|s| s.try_into().ok()) .map(<u32>::from_le_bytes) .map(Into::into), BitWidth::W64 => cursor .and_then(|s| s.try_into().ok()) .map(<u64>::from_le_bytes), } .ok_or(Error::FlexbufferOutOfBounds) } /// Tries to read a FlexBufferType::Int. Returns Err if the type is not a UInt or if the /// address is out of bounds. pub fn get_i64(&self) -> Result<i64, Error> { self.expect_type(FlexBufferType::Int)?; let cursor = self .buffer .get(self.address..self.address + self.width.n_bytes()); match self.width { BitWidth::W8 => cursor.map(|s| s[0] as i8).map(Into::into), BitWidth::W16 => cursor .and_then(|s| s.try_into().ok()) .map(<i16>::from_le_bytes) .map(Into::into), BitWidth::W32 => cursor .and_then(|s| s.try_into().ok()) .map(<i32>::from_le_bytes) .map(Into::into), BitWidth::W64 => cursor .and_then(|s| s.try_into().ok()) .map(<i64>::from_le_bytes), } .ok_or(Error::FlexbufferOutOfBounds) } /// Tries to read a FlexBufferType::Float. Returns Err if the type is not a UInt, if the /// address is out of bounds, or if its a f16 or f8 (not currently supported). pub fn get_f64(&self) -> Result<f64, Error> { self.expect_type(FlexBufferType::Float)?; let cursor = self .buffer .get(self.address..self.address + self.width.n_bytes()); match self.width { BitWidth::W8 | BitWidth::W16 => return Err(Error::InvalidPackedType), BitWidth::W32 => cursor .and_then(|s| s.try_into().ok()) .map(f32_from_le_bytes) .map(Into::into), BitWidth::W64 => cursor .and_then(|s| s.try_into().ok()) .map(f64_from_le_bytes), } .ok_or(Error::FlexbufferOutOfBounds) } pub fn as_bool(&self) -> bool { use FlexBufferType::*; match self.fxb_type { Bool => self.get_bool().unwrap_or_default(), UInt => self.as_u64()!= 0, Int => self.as_i64()!= 0, Float => self.as_f64().abs() > std::f64::EPSILON, String | Key =>!self.as_str().is_empty(), Null => false, Blob => self.length()!= 0, ty if ty.is_vector() => self.length()!= 0, _ => unreachable!(), } } /// Returns a u64, casting if necessary. For Maps and Vectors, their length is /// returned. If anything fails, 0 is returned. pub fn as_u64(&self) -> u64 { match self.fxb_type { FlexBufferType::UInt => self.get_u64().unwrap_or_default(), FlexBufferType::Int => self .get_i64() .unwrap_or_default() .try_into() .unwrap_or_default(), FlexBufferType::Float => self.get_f64().unwrap_or_default() as u64, FlexBufferType::String => { if let Ok(s) = self.get_str() { if let Ok(f) = u64::from_str(&s) { return f; } } 0 } _ if self.fxb_type.is_vector() => self.length() as u64, _ => 0, } } try_cast_fn!(as_u32, as_u64, u32); try_cast_fn!(as_u16, as_u64, u16); try_cast_fn!(as_u8, as_u64, u8); /// Returns an i64, casting if necessary. For Maps and Vectors, their length is /// returned. If anything fails, 0 is returned. pub fn as_i64(&self) -> i64 { match self.fxb_type { FlexBufferType::Int => self.get_i64().unwrap_or_default(), FlexBufferType::UInt => self .get_u64() .unwrap_or_default() .try_into() .unwrap_or_default(), FlexBufferType::Float => self.get_f64().unwrap_or_default() as i64, FlexBufferType::String => { if let Ok(s) = self.get_str() { if let Ok(f) = i64::from_str(&s) { return f; } } 0 } _ if self.fxb_type.is_vector() => self.length() as i64, _ => 0, } } try_cast_fn!(as_i32, as_i64, i32); try_cast_fn!(as_i16, as_i64, i16); try_cast_fn!(as_i8, as_i64, i8); /// Returns an f64, casting if necessary. For Maps and Vectors, their length is /// returned. If anything fails, 0 is returned. pub fn as_f64(&self) -> f64 { match self.fxb_type { FlexBufferType::Int => self.get_i64().unwrap_or_default() as f64, FlexBufferType::UInt => self.get_u64().unwrap_or_default() as f64, FlexBufferType::Float => self.get_f64().unwrap_or_default(), FlexBufferType::String => { if let Ok(
{ if self.flexbuffer_type().typed_vector_type() != T::VECTOR_TYPE.typed_vector_type() { self.expect_type(T::VECTOR_TYPE)?; } if self.bitwidth().n_bytes() != std::mem::size_of::<T>() { self.expect_bw(T::WIDTH)?; } let end = self.address + self.length() * std::mem::size_of::<T>(); let slice: &[u8] = self .buffer .get(self.address..end) .ok_or(Error::FlexbufferOutOfBounds)?; // `align_to` is required because the point of this function is to directly hand back a // slice of scalars. This can fail because Rust's default allocator is not 16byte aligned // (though in practice this only happens for small buffers). let (pre, mid, suf) = unsafe { slice.align_to::<T>() }; if pre.is_empty() && suf.is_empty() { Ok(mid) } else {
identifier_body
issue-17233.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. // run-pass const X1: &'static [u8] = &[b'1']; const X2: &'static [u8] = b"1"; const X3: &'static [u8; 1] = &[b'1']; const X4: &'static [u8; 1] = b"1"; static Y1: u8 = X1[0]; static Y2: u8 = X2[0]; static Y3: u8 = X3[0]; static Y4: u8 = X4[0]; fn
() { assert_eq!(Y1, Y2); assert_eq!(Y1, Y3); assert_eq!(Y1, Y4); }
main
identifier_name
issue-17233.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. // run-pass const X1: &'static [u8] = &[b'1']; const X2: &'static [u8] = b"1"; const X3: &'static [u8; 1] = &[b'1']; const X4: &'static [u8; 1] = b"1"; static Y1: u8 = X1[0]; static Y2: u8 = X2[0]; static Y3: u8 = X3[0]; static Y4: u8 = X4[0]; fn main()
{ assert_eq!(Y1, Y2); assert_eq!(Y1, Y3); assert_eq!(Y1, Y4); }
identifier_body
issue-17233.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. // run-pass const X1: &'static [u8] = &[b'1']; const X2: &'static [u8] = b"1"; const X3: &'static [u8; 1] = &[b'1']; const X4: &'static [u8; 1] = b"1"; static Y1: u8 = X1[0]; static Y2: u8 = X2[0]; static Y3: u8 = X3[0]; static Y4: u8 = X4[0]; fn main() { assert_eq!(Y1, Y2); assert_eq!(Y1, Y3); assert_eq!(Y1, Y4); }
random_line_split
build.rs
use std::path::Path; use std::process::Command; static AFL_SRC_PATH: &str = "AFLplusplus"; // https://github.com/rust-fuzz/afl.rs/issues/148 #[cfg(target_os = "macos")] static AR_CMD: &str = "/usr/bin/ar"; #[cfg(not(target_os = "macos"))] static AR_CMD: &str = "ar"; #[path = "src/common.rs"] mod common; fn main() { build_afl(&common::afl_dir()); build_afl_llvm_runtime(); } fn build_afl(out_dir: &Path) { let mut command = Command::new("make"); command .current_dir(AFL_SRC_PATH) .args(&["clean", "all", "install"]) // skip the checks for the legacy x86 afl-gcc compiler .env("AFL_NO_X86", "1") // build just the runtime to avoid troubles with Xcode clang on macOS .env("NO_BUILD", "1") .env("DESTDIR", out_dir) .env("PREFIX", ""); let status = command.status().expect("could not run'make'"); assert!(status.success()); } fn build_afl_llvm_runtime()
{ std::fs::copy( Path::new(&AFL_SRC_PATH).join("afl-compiler-rt.o"), common::object_file_path(), ) .expect("Couldn't copy object file"); let status = Command::new(AR_CMD) .arg("r") .arg(common::archive_file_path()) .arg(common::object_file_path()) .status() .expect("could not run 'ar'"); assert!(status.success()); }
identifier_body
build.rs
use std::path::Path; use std::process::Command; static AFL_SRC_PATH: &str = "AFLplusplus"; // https://github.com/rust-fuzz/afl.rs/issues/148 #[cfg(target_os = "macos")] static AR_CMD: &str = "/usr/bin/ar"; #[cfg(not(target_os = "macos"))] static AR_CMD: &str = "ar"; #[path = "src/common.rs"] mod common; fn main() { build_afl(&common::afl_dir()); build_afl_llvm_runtime(); } fn build_afl(out_dir: &Path) { let mut command = Command::new("make"); command .current_dir(AFL_SRC_PATH) .args(&["clean", "all", "install"]) // skip the checks for the legacy x86 afl-gcc compiler .env("AFL_NO_X86", "1") // build just the runtime to avoid troubles with Xcode clang on macOS .env("NO_BUILD", "1") .env("DESTDIR", out_dir) .env("PREFIX", ""); let status = command.status().expect("could not run'make'"); assert!(status.success()); } fn
() { std::fs::copy( Path::new(&AFL_SRC_PATH).join("afl-compiler-rt.o"), common::object_file_path(), ) .expect("Couldn't copy object file"); let status = Command::new(AR_CMD) .arg("r") .arg(common::archive_file_path()) .arg(common::object_file_path()) .status() .expect("could not run 'ar'"); assert!(status.success()); }
build_afl_llvm_runtime
identifier_name
build.rs
use std::path::Path; use std::process::Command; static AFL_SRC_PATH: &str = "AFLplusplus"; // https://github.com/rust-fuzz/afl.rs/issues/148 #[cfg(target_os = "macos")] static AR_CMD: &str = "/usr/bin/ar"; #[cfg(not(target_os = "macos"))] static AR_CMD: &str = "ar"; #[path = "src/common.rs"] mod common; fn main() { build_afl(&common::afl_dir()); build_afl_llvm_runtime(); } fn build_afl(out_dir: &Path) { let mut command = Command::new("make"); command .current_dir(AFL_SRC_PATH) .args(&["clean", "all", "install"]) // skip the checks for the legacy x86 afl-gcc compiler .env("AFL_NO_X86", "1") // build just the runtime to avoid troubles with Xcode clang on macOS .env("NO_BUILD", "1") .env("DESTDIR", out_dir) .env("PREFIX", ""); let status = command.status().expect("could not run'make'"); assert!(status.success());
} fn build_afl_llvm_runtime() { std::fs::copy( Path::new(&AFL_SRC_PATH).join("afl-compiler-rt.o"), common::object_file_path(), ) .expect("Couldn't copy object file"); let status = Command::new(AR_CMD) .arg("r") .arg(common::archive_file_path()) .arg(common::object_file_path()) .status() .expect("could not run 'ar'"); assert!(status.success()); }
random_line_split
colors.rs
use palette; use palette::pixel::RgbPixel; pub type Rgb = [f32; 3]; pub type Srgb = [f32; 3]; fn normalize(color: Srgb) -> Srgb { [color[0] / 255.0, color[1] / 255.0, color[2] / 255.0] } fn srgb_to_rgb(color: Srgb) -> Rgb { let srgb = palette::pixel::Srgb::new(color[0], color[1], color[2]); let rgb = palette::Rgb::from(srgb); [rgb.red, rgb.green, rgb.blue] } fn
(color: &str) -> Srgb { let rgba = palette::named::from_str(color) .expect(&format!("unknown color: {}", color)) .to_rgba(); srgb_to_rgb([rgba.0, rgba.1, rgba.2]) } lazy_static! { pub static ref BLACK: Rgb = str_to_rgb("black"); pub static ref CYAN: Rgb = str_to_rgb("cyan"); pub static ref BROWN: Rgb = str_to_rgb("saddlebrown"); pub static ref BLUE: Rgb = str_to_rgb("blue"); pub static ref RED: Rgb = str_to_rgb("red"); pub static ref GREEN: Rgb = str_to_rgb("green"); pub static ref YELLOW: Rgb = str_to_rgb("yellow"); pub static ref WHITE: Rgb = str_to_rgb("white"); pub static ref YOGA_TEAL: Rgb = srgb_to_rgb(normalize([151.0, 220.0, 207.0])); pub static ref YOGA_GRAY: Rgb = srgb_to_rgb(normalize([48.0, 56.0, 70.0])); }
str_to_rgb
identifier_name
colors.rs
use palette; use palette::pixel::RgbPixel; pub type Rgb = [f32; 3]; pub type Srgb = [f32; 3]; fn normalize(color: Srgb) -> Srgb { [color[0] / 255.0, color[1] / 255.0, color[2] / 255.0] } fn srgb_to_rgb(color: Srgb) -> Rgb { let srgb = palette::pixel::Srgb::new(color[0], color[1], color[2]); let rgb = palette::Rgb::from(srgb); [rgb.red, rgb.green, rgb.blue] } fn str_to_rgb(color: &str) -> Srgb { let rgba = palette::named::from_str(color) .expect(&format!("unknown color: {}", color)) .to_rgba(); srgb_to_rgb([rgba.0, rgba.1, rgba.2])
lazy_static! { pub static ref BLACK: Rgb = str_to_rgb("black"); pub static ref CYAN: Rgb = str_to_rgb("cyan"); pub static ref BROWN: Rgb = str_to_rgb("saddlebrown"); pub static ref BLUE: Rgb = str_to_rgb("blue"); pub static ref RED: Rgb = str_to_rgb("red"); pub static ref GREEN: Rgb = str_to_rgb("green"); pub static ref YELLOW: Rgb = str_to_rgb("yellow"); pub static ref WHITE: Rgb = str_to_rgb("white"); pub static ref YOGA_TEAL: Rgb = srgb_to_rgb(normalize([151.0, 220.0, 207.0])); pub static ref YOGA_GRAY: Rgb = srgb_to_rgb(normalize([48.0, 56.0, 70.0])); }
}
random_line_split
colors.rs
use palette; use palette::pixel::RgbPixel; pub type Rgb = [f32; 3]; pub type Srgb = [f32; 3]; fn normalize(color: Srgb) -> Srgb { [color[0] / 255.0, color[1] / 255.0, color[2] / 255.0] } fn srgb_to_rgb(color: Srgb) -> Rgb { let srgb = palette::pixel::Srgb::new(color[0], color[1], color[2]); let rgb = palette::Rgb::from(srgb); [rgb.red, rgb.green, rgb.blue] } fn str_to_rgb(color: &str) -> Srgb
lazy_static! { pub static ref BLACK: Rgb = str_to_rgb("black"); pub static ref CYAN: Rgb = str_to_rgb("cyan"); pub static ref BROWN: Rgb = str_to_rgb("saddlebrown"); pub static ref BLUE: Rgb = str_to_rgb("blue"); pub static ref RED: Rgb = str_to_rgb("red"); pub static ref GREEN: Rgb = str_to_rgb("green"); pub static ref YELLOW: Rgb = str_to_rgb("yellow"); pub static ref WHITE: Rgb = str_to_rgb("white"); pub static ref YOGA_TEAL: Rgb = srgb_to_rgb(normalize([151.0, 220.0, 207.0])); pub static ref YOGA_GRAY: Rgb = srgb_to_rgb(normalize([48.0, 56.0, 70.0])); }
{ let rgba = palette::named::from_str(color) .expect(&format!("unknown color: {}", color)) .to_rgba(); srgb_to_rgb([rgba.0, rgba.1, rgba.2]) }
identifier_body
trait-bounds-sugar.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. // Tests for "default" bounds inferred for traits with no bounds list. trait Foo {} fn a(_x: ~Foo:Send) { } fn b(_x: &'static Foo)
fn c(x: ~Foo:Share) { a(x); //~ ERROR expected bounds `Send` } fn d(x: &'static Foo:Share) { b(x); //~ ERROR expected bounds `'static` } fn main() {}
{ // should be same as &'static Foo:'static }
identifier_body
trait-bounds-sugar.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. // Tests for "default" bounds inferred for traits with no bounds list. trait Foo {} fn
(_x: ~Foo:Send) { } fn b(_x: &'static Foo) { // should be same as &'static Foo:'static } fn c(x: ~Foo:Share) { a(x); //~ ERROR expected bounds `Send` } fn d(x: &'static Foo:Share) { b(x); //~ ERROR expected bounds `'static` } fn main() {}
a
identifier_name
trait-bounds-sugar.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. // Tests for "default" bounds inferred for traits with no bounds list. trait Foo {} fn a(_x: ~Foo:Send) { }
fn b(_x: &'static Foo) { // should be same as &'static Foo:'static } fn c(x: ~Foo:Share) { a(x); //~ ERROR expected bounds `Send` } fn d(x: &'static Foo:Share) { b(x); //~ ERROR expected bounds `'static` } fn main() {}
random_line_split
address-of.rs
// EMIT_MIR address_of.address_of_reborrow.SimplifyCfg-initial.after.mir fn
() { let y = &[0; 10]; let mut z = &mut [0; 10]; y as *const _; y as *const [i32; 10]; y as *const dyn Send; y as *const [i32]; y as *const i32; // This is a cast, not a coercion let p: *const _ = y; let p: *const [i32; 10] = y; let p: *const dyn Send = y; let p: *const [i32] = y; z as *const _; z as *const [i32; 10]; z as *const dyn Send; z as *const [i32]; let p: *const _ = z; let p: *const [i32; 10] = z; let p: *const dyn Send = z; let p: *const [i32] = z; z as *mut _; z as *mut [i32; 10]; z as *mut dyn Send; z as *mut [i32]; let p: *mut _ = z; let p: *mut [i32; 10] = z; let p: *mut dyn Send = z; let p: *mut [i32] = z; } // The normal borrows here should be preserved // EMIT_MIR address_of.borrow_and_cast.SimplifyCfg-initial.after.mir fn borrow_and_cast(mut x: i32) { let p = &x as *const i32; let q = &mut x as *const i32; let r = &mut x as *mut i32; } fn main() {}
address_of_reborrow
identifier_name
address-of.rs
// EMIT_MIR address_of.address_of_reborrow.SimplifyCfg-initial.after.mir fn address_of_reborrow()
let p: *const _ = z; let p: *const [i32; 10] = z; let p: *const dyn Send = z; let p: *const [i32] = z; z as *mut _; z as *mut [i32; 10]; z as *mut dyn Send; z as *mut [i32]; let p: *mut _ = z; let p: *mut [i32; 10] = z; let p: *mut dyn Send = z; let p: *mut [i32] = z; } // The normal borrows here should be preserved // EMIT_MIR address_of.borrow_and_cast.SimplifyCfg-initial.after.mir fn borrow_and_cast(mut x: i32) { let p = &x as *const i32; let q = &mut x as *const i32; let r = &mut x as *mut i32; } fn main() {}
{ let y = &[0; 10]; let mut z = &mut [0; 10]; y as *const _; y as *const [i32; 10]; y as *const dyn Send; y as *const [i32]; y as *const i32; // This is a cast, not a coercion let p: *const _ = y; let p: *const [i32; 10] = y; let p: *const dyn Send = y; let p: *const [i32] = y; z as *const _; z as *const [i32; 10]; z as *const dyn Send; z as *const [i32];
identifier_body
address-of.rs
// EMIT_MIR address_of.address_of_reborrow.SimplifyCfg-initial.after.mir fn address_of_reborrow() { let y = &[0; 10]; let mut z = &mut [0; 10]; y as *const _; y as *const [i32; 10]; y as *const dyn Send; y as *const [i32]; y as *const i32; // This is a cast, not a coercion let p: *const _ = y; let p: *const [i32; 10] = y; let p: *const dyn Send = y; let p: *const [i32] = y; z as *const _; z as *const [i32; 10]; z as *const dyn Send; z as *const [i32]; let p: *const _ = z; let p: *const [i32; 10] = z; let p: *const dyn Send = z; let p: *const [i32] = z; z as *mut _;
let p: *mut _ = z; let p: *mut [i32; 10] = z; let p: *mut dyn Send = z; let p: *mut [i32] = z; } // The normal borrows here should be preserved // EMIT_MIR address_of.borrow_and_cast.SimplifyCfg-initial.after.mir fn borrow_and_cast(mut x: i32) { let p = &x as *const i32; let q = &mut x as *const i32; let r = &mut x as *mut i32; } fn main() {}
z as *mut [i32; 10]; z as *mut dyn Send; z as *mut [i32];
random_line_split
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // - Neither the name of "The Computer Language Benchmarks Game" nor // the name of "The Computer Language Shootout Benchmarks" nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. // no-pretty-expanded use std::string::String; use std::fmt; fn print_complements() { let all = [Blue, Red, Yellow]; for aa in all.iter() { for bb in all.iter() { println!("{} + {} -> {}", *aa, *bb, transform(*aa, *bb)); } } } enum Color { Red, Yellow, Blue } impl fmt::Show for Color { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let str = match *self { Red => "red", Yellow => "yellow", Blue => "blue", }; write!(f, "{}", str) } } struct CreatureInfo { name: uint, color: Color } fn show_color_list(set: Vec<Color>) -> String { let mut out = String::new(); for col in set.iter() { out.push(' '); out.push_str(col.to_string().as_slice()); } out } fn show_digit(nn: uint) -> &'static str { match nn { 0 => {" zero"} 1 => {" one"} 2 => {" two"} 3 => {" three"} 4 => {" four"} 5 => {" five"} 6 => {" six"} 7 => {" seven"} 8 => {" eight"} 9 => {" nine"} _ => {panic!("expected digits from 0 to 9...")} } } struct Number(uint); impl fmt::Show for Number { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut out = vec![]; let Number(mut num) = *self; if num == 0 { out.push(show_digit(0)) }; while num!= 0 { let dig = num % 10; num = num / 10; let s = show_digit(dig); out.push(s); } for s in out.iter().rev() { try!(write!(f, "{}", s)) } Ok(()) } } fn transform(aa: Color, bb: Color) -> Color { match (aa, bb) { (Red, Red ) => { Red } (Red, Yellow) => { Blue } (Red, Blue ) => { Yellow } (Yellow, Red ) => { Blue } (Yellow, Yellow) => { Yellow } (Yellow, Blue ) => { Red } (Blue, Red ) => { Yellow } (Blue, Yellow) => { Red } (Blue, Blue ) => { Blue } } } fn
( name: uint, mut color: Color, from_rendezvous: Receiver<CreatureInfo>, to_rendezvous: Sender<CreatureInfo>, to_rendezvous_log: Sender<String> ) { let mut creatures_met = 0i32; let mut evil_clones_met = 0; let mut rendezvous = from_rendezvous.iter(); loop { // ask for a pairing to_rendezvous.send(CreatureInfo {name: name, color: color}); // log and change, or quit match rendezvous.next() { Some(other_creature) => { color = transform(color, other_creature.color); // track some statistics creatures_met += 1; if other_creature.name == name { evil_clones_met += 1; } } None => break } } // log creatures met and evil clones of self let report = format!("{}{}", creatures_met, Number(evil_clones_met)); to_rendezvous_log.send(report); } fn rendezvous(nn: uint, set: Vec<Color>) { // these ports will allow us to hear from the creatures let (to_rendezvous, from_creatures) = channel::<CreatureInfo>(); // these channels will be passed to the creatures so they can talk to us let (to_rendezvous_log, from_creatures_log) = channel::<String>(); // these channels will allow us to talk to each creature by 'name'/index let mut to_creature: Vec<Sender<CreatureInfo>> = set.iter().enumerate().map(|(ii, &col)| { // create each creature as a listener with a port, and // give us a channel to talk to each let to_rendezvous = to_rendezvous.clone(); let to_rendezvous_log = to_rendezvous_log.clone(); let (to_creature, from_rendezvous) = channel(); spawn(proc() { creature(ii, col, from_rendezvous, to_rendezvous, to_rendezvous_log); }); to_creature }).collect(); let mut creatures_met = 0; // set up meetings... for _ in range(0, nn) { let fst_creature = from_creatures.recv(); let snd_creature = from_creatures.recv(); creatures_met += 2; to_creature[fst_creature.name].send(snd_creature); to_creature[snd_creature.name].send(fst_creature); } // tell each creature to stop drop(to_creature); // print each color in the set println!("{}", show_color_list(set)); // print each creature's stats drop(to_rendezvous_log); for rep in from_creatures_log.iter() { println!("{}", rep); } // print the total number of creatures met println!("{}\n", Number(creatures_met)); } fn main() { let nn = if std::os::getenv("RUST_BENCH").is_some() { 200000 } else { std::os::args().as_slice() .get(1) .and_then(|arg| from_str(arg.as_slice())) .unwrap_or(600) }; print_complements(); println!(""); rendezvous(nn, vec!(Blue, Red, Yellow)); rendezvous(nn, vec!(Blue, Red, Yellow, Red, Yellow, Blue, Red, Yellow, Red, Blue)); }
creature
identifier_name
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // - Neither the name of "The Computer Language Benchmarks Game" nor // the name of "The Computer Language Shootout Benchmarks" nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. // no-pretty-expanded use std::string::String; use std::fmt; fn print_complements() { let all = [Blue, Red, Yellow]; for aa in all.iter() { for bb in all.iter() { println!("{} + {} -> {}", *aa, *bb, transform(*aa, *bb)); } } } enum Color { Red, Yellow, Blue } impl fmt::Show for Color { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let str = match *self { Red => "red", Yellow => "yellow", Blue => "blue", }; write!(f, "{}", str) } } struct CreatureInfo { name: uint, color: Color } fn show_color_list(set: Vec<Color>) -> String { let mut out = String::new(); for col in set.iter() { out.push(' '); out.push_str(col.to_string().as_slice()); } out } fn show_digit(nn: uint) -> &'static str { match nn { 0 =>
1 => {" one"} 2 => {" two"} 3 => {" three"} 4 => {" four"} 5 => {" five"} 6 => {" six"} 7 => {" seven"} 8 => {" eight"} 9 => {" nine"} _ => {panic!("expected digits from 0 to 9...")} } } struct Number(uint); impl fmt::Show for Number { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut out = vec![]; let Number(mut num) = *self; if num == 0 { out.push(show_digit(0)) }; while num!= 0 { let dig = num % 10; num = num / 10; let s = show_digit(dig); out.push(s); } for s in out.iter().rev() { try!(write!(f, "{}", s)) } Ok(()) } } fn transform(aa: Color, bb: Color) -> Color { match (aa, bb) { (Red, Red ) => { Red } (Red, Yellow) => { Blue } (Red, Blue ) => { Yellow } (Yellow, Red ) => { Blue } (Yellow, Yellow) => { Yellow } (Yellow, Blue ) => { Red } (Blue, Red ) => { Yellow } (Blue, Yellow) => { Red } (Blue, Blue ) => { Blue } } } fn creature( name: uint, mut color: Color, from_rendezvous: Receiver<CreatureInfo>, to_rendezvous: Sender<CreatureInfo>, to_rendezvous_log: Sender<String> ) { let mut creatures_met = 0i32; let mut evil_clones_met = 0; let mut rendezvous = from_rendezvous.iter(); loop { // ask for a pairing to_rendezvous.send(CreatureInfo {name: name, color: color}); // log and change, or quit match rendezvous.next() { Some(other_creature) => { color = transform(color, other_creature.color); // track some statistics creatures_met += 1; if other_creature.name == name { evil_clones_met += 1; } } None => break } } // log creatures met and evil clones of self let report = format!("{}{}", creatures_met, Number(evil_clones_met)); to_rendezvous_log.send(report); } fn rendezvous(nn: uint, set: Vec<Color>) { // these ports will allow us to hear from the creatures let (to_rendezvous, from_creatures) = channel::<CreatureInfo>(); // these channels will be passed to the creatures so they can talk to us let (to_rendezvous_log, from_creatures_log) = channel::<String>(); // these channels will allow us to talk to each creature by 'name'/index let mut to_creature: Vec<Sender<CreatureInfo>> = set.iter().enumerate().map(|(ii, &col)| { // create each creature as a listener with a port, and // give us a channel to talk to each let to_rendezvous = to_rendezvous.clone(); let to_rendezvous_log = to_rendezvous_log.clone(); let (to_creature, from_rendezvous) = channel(); spawn(proc() { creature(ii, col, from_rendezvous, to_rendezvous, to_rendezvous_log); }); to_creature }).collect(); let mut creatures_met = 0; // set up meetings... for _ in range(0, nn) { let fst_creature = from_creatures.recv(); let snd_creature = from_creatures.recv(); creatures_met += 2; to_creature[fst_creature.name].send(snd_creature); to_creature[snd_creature.name].send(fst_creature); } // tell each creature to stop drop(to_creature); // print each color in the set println!("{}", show_color_list(set)); // print each creature's stats drop(to_rendezvous_log); for rep in from_creatures_log.iter() { println!("{}", rep); } // print the total number of creatures met println!("{}\n", Number(creatures_met)); } fn main() { let nn = if std::os::getenv("RUST_BENCH").is_some() { 200000 } else { std::os::args().as_slice() .get(1) .and_then(|arg| from_str(arg.as_slice())) .unwrap_or(600) }; print_complements(); println!(""); rendezvous(nn, vec!(Blue, Red, Yellow)); rendezvous(nn, vec!(Blue, Red, Yellow, Red, Yellow, Blue, Red, Yellow, Red, Blue)); }
{" zero"}
conditional_block
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // - Neither the name of "The Computer Language Benchmarks Game" nor // the name of "The Computer Language Shootout Benchmarks" nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. // no-pretty-expanded use std::string::String; use std::fmt; fn print_complements() { let all = [Blue, Red, Yellow]; for aa in all.iter() { for bb in all.iter() { println!("{} + {} -> {}", *aa, *bb, transform(*aa, *bb)); } } } enum Color { Red, Yellow, Blue } impl fmt::Show for Color { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let str = match *self { Red => "red", Yellow => "yellow", Blue => "blue", }; write!(f, "{}", str) } } struct CreatureInfo { name: uint, color: Color } fn show_color_list(set: Vec<Color>) -> String { let mut out = String::new(); for col in set.iter() { out.push(' '); out.push_str(col.to_string().as_slice()); } out } fn show_digit(nn: uint) -> &'static str { match nn { 0 => {" zero"} 1 => {" one"} 2 => {" two"} 3 => {" three"} 4 => {" four"} 5 => {" five"} 6 => {" six"} 7 => {" seven"} 8 => {" eight"} 9 => {" nine"} _ => {panic!("expected digits from 0 to 9...")} } } struct Number(uint); impl fmt::Show for Number { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut out = vec![]; let Number(mut num) = *self; if num == 0 { out.push(show_digit(0)) }; while num!= 0 { let dig = num % 10; num = num / 10; let s = show_digit(dig); out.push(s); } for s in out.iter().rev() { try!(write!(f, "{}", s)) } Ok(()) } } fn transform(aa: Color, bb: Color) -> Color { match (aa, bb) { (Red, Red ) => { Red } (Red, Yellow) => { Blue } (Red, Blue ) => { Yellow } (Yellow, Red ) => { Blue } (Yellow, Yellow) => { Yellow } (Yellow, Blue ) => { Red } (Blue, Red ) => { Yellow } (Blue, Yellow) => { Red } (Blue, Blue ) => { Blue } } } fn creature( name: uint, mut color: Color, from_rendezvous: Receiver<CreatureInfo>, to_rendezvous: Sender<CreatureInfo>, to_rendezvous_log: Sender<String> ) { let mut creatures_met = 0i32; let mut evil_clones_met = 0; let mut rendezvous = from_rendezvous.iter(); loop { // ask for a pairing to_rendezvous.send(CreatureInfo {name: name, color: color}); // log and change, or quit match rendezvous.next() { Some(other_creature) => { color = transform(color, other_creature.color); // track some statistics creatures_met += 1; if other_creature.name == name { evil_clones_met += 1; } } None => break } } // log creatures met and evil clones of self let report = format!("{}{}", creatures_met, Number(evil_clones_met)); to_rendezvous_log.send(report); } fn rendezvous(nn: uint, set: Vec<Color>) { // these ports will allow us to hear from the creatures let (to_rendezvous, from_creatures) = channel::<CreatureInfo>(); // these channels will be passed to the creatures so they can talk to us let (to_rendezvous_log, from_creatures_log) = channel::<String>(); // these channels will allow us to talk to each creature by 'name'/index let mut to_creature: Vec<Sender<CreatureInfo>> = set.iter().enumerate().map(|(ii, &col)| { // create each creature as a listener with a port, and // give us a channel to talk to each let to_rendezvous = to_rendezvous.clone(); let to_rendezvous_log = to_rendezvous_log.clone(); let (to_creature, from_rendezvous) = channel(); spawn(proc() { creature(ii, col, from_rendezvous, to_rendezvous, to_rendezvous_log); }); to_creature }).collect(); let mut creatures_met = 0; // set up meetings... for _ in range(0, nn) { let fst_creature = from_creatures.recv();
to_creature[fst_creature.name].send(snd_creature); to_creature[snd_creature.name].send(fst_creature); } // tell each creature to stop drop(to_creature); // print each color in the set println!("{}", show_color_list(set)); // print each creature's stats drop(to_rendezvous_log); for rep in from_creatures_log.iter() { println!("{}", rep); } // print the total number of creatures met println!("{}\n", Number(creatures_met)); } fn main() { let nn = if std::os::getenv("RUST_BENCH").is_some() { 200000 } else { std::os::args().as_slice() .get(1) .and_then(|arg| from_str(arg.as_slice())) .unwrap_or(600) }; print_complements(); println!(""); rendezvous(nn, vec!(Blue, Red, Yellow)); rendezvous(nn, vec!(Blue, Red, Yellow, Red, Yellow, Blue, Red, Yellow, Red, Blue)); }
let snd_creature = from_creatures.recv(); creatures_met += 2;
random_line_split
astar.rs
use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::{BinaryHeap, HashMap}; use std::hash::Hash; use super::visit::{EdgeRef, GraphBase, IntoEdges, VisitMap, Visitable}; use crate::scored::MinScored; use crate::algo::Measure; /// \[Generic\] A* shortest path algorithm. /// /// Computes the shortest path from `start` to `finish`, including the total path cost. /// /// `finish` is implicitly given via the `is_goal` callback, which should return `true` if the /// given node is the finish node. /// /// The function `edge_cost` should return the cost for a particular edge. Edge costs must be /// non-negative. /// /// The function `estimate_cost` should return the estimated cost to the finish for a particular /// node. For the algorithm to find the actual shortest path, it should be admissible, meaning that /// it should never overestimate the actual cost to get to the nearest goal node. Estimate costs /// must also be non-negative. /// /// The graph should be `Visitable` and implement `IntoEdges`. /// /// # Example /// ``` /// use petgraph::Graph; /// use petgraph::algo::astar; /// /// let mut g = Graph::new(); /// let a = g.add_node((0., 0.)); /// let b = g.add_node((2., 0.)); /// let c = g.add_node((1., 1.)); /// let d = g.add_node((0., 2.)); /// let e = g.add_node((3., 3.)); /// let f = g.add_node((4., 2.)); /// g.extend_with_edges(&[ /// (a, b, 2), /// (a, d, 4), /// (b, c, 1), /// (b, f, 7), /// (c, e, 5), /// (e, f, 1), /// (d, e, 1), /// ]); /// /// // Graph represented with the weight of each edge /// // Edges with '*' are part of the optimal path. /// // /// // 2 1 /// // a ----- b ----- c /// // | 4* | 7 | /// // d f | 5 /// // | 1* | 1* | /// // \------ e ------/ /// /// let path = astar(&g, a, |finish| finish == f, |e| *e.weight(), |_| 0); /// assert_eq!(path, Some((6, vec![a, d, e, f]))); /// ``` /// /// Returns the total cost + the path of subsequent `NodeId` from start to finish, if one was /// found. pub fn astar<G, F, H, K, IsGoal>( graph: G, start: G::NodeId, mut is_goal: IsGoal, mut edge_cost: F, mut estimate_cost: H, ) -> Option<(K, Vec<G::NodeId>)> where G: IntoEdges + Visitable, IsGoal: FnMut(G::NodeId) -> bool, G::NodeId: Eq + Hash, F: FnMut(G::EdgeRef) -> K, H: FnMut(G::NodeId) -> K, K: Measure + Copy, { let mut visited = graph.visit_map(); let mut visit_next = BinaryHeap::new(); let mut scores = HashMap::new(); let mut path_tracker = PathTracker::<G>::new(); let zero_score = K::default(); scores.insert(start, zero_score); visit_next.push(MinScored(estimate_cost(start), start)); while let Some(MinScored(_, node)) = visit_next.pop() { if is_goal(node) { let path = path_tracker.reconstruct_path_to(node); let cost = scores[&node]; return Some((cost, path)); } // Don't visit the same node several times, as the first time it was visited it was using // the shortest available path. if!visited.visit(node) { continue; } // This lookup can be unwrapped without fear of panic since the node was necessarily scored // before adding him to `visit_next`. let node_score = scores[&node]; for edge in graph.edges(node) { let next = edge.target(); if visited.is_visited(&next) { continue; } let mut next_score = node_score + edge_cost(edge); match scores.entry(next) { Occupied(ent) => { let old_score = *ent.get(); if next_score < old_score { *ent.into_mut() = next_score; path_tracker.set_predecessor(next, node); } else { next_score = old_score; } } Vacant(ent) => { ent.insert(next_score); path_tracker.set_predecessor(next, node); } } let next_estimate_score = next_score + estimate_cost(next); visit_next.push(MinScored(next_estimate_score, next)); } } None } struct PathTracker<G> where G: GraphBase, G::NodeId: Eq + Hash, { came_from: HashMap<G::NodeId, G::NodeId>, } impl<G> PathTracker<G> where G: GraphBase, G::NodeId: Eq + Hash, { fn new() -> PathTracker<G> { PathTracker { came_from: HashMap::new(), } } fn set_predecessor(&mut self, node: G::NodeId, previous: G::NodeId) { self.came_from.insert(node, previous); } fn reconstruct_path_to(&self, last: G::NodeId) -> Vec<G::NodeId> { let mut path = vec![last]; let mut current = last; while let Some(&previous) = self.came_from.get(&current) { path.push(previous); current = previous; } path.reverse(); path
} }
random_line_split
astar.rs
use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::{BinaryHeap, HashMap}; use std::hash::Hash; use super::visit::{EdgeRef, GraphBase, IntoEdges, VisitMap, Visitable}; use crate::scored::MinScored; use crate::algo::Measure; /// \[Generic\] A* shortest path algorithm. /// /// Computes the shortest path from `start` to `finish`, including the total path cost. /// /// `finish` is implicitly given via the `is_goal` callback, which should return `true` if the /// given node is the finish node. /// /// The function `edge_cost` should return the cost for a particular edge. Edge costs must be /// non-negative. /// /// The function `estimate_cost` should return the estimated cost to the finish for a particular /// node. For the algorithm to find the actual shortest path, it should be admissible, meaning that /// it should never overestimate the actual cost to get to the nearest goal node. Estimate costs /// must also be non-negative. /// /// The graph should be `Visitable` and implement `IntoEdges`. /// /// # Example /// ``` /// use petgraph::Graph; /// use petgraph::algo::astar; /// /// let mut g = Graph::new(); /// let a = g.add_node((0., 0.)); /// let b = g.add_node((2., 0.)); /// let c = g.add_node((1., 1.)); /// let d = g.add_node((0., 2.)); /// let e = g.add_node((3., 3.)); /// let f = g.add_node((4., 2.)); /// g.extend_with_edges(&[ /// (a, b, 2), /// (a, d, 4), /// (b, c, 1), /// (b, f, 7), /// (c, e, 5), /// (e, f, 1), /// (d, e, 1), /// ]); /// /// // Graph represented with the weight of each edge /// // Edges with '*' are part of the optimal path. /// // /// // 2 1 /// // a ----- b ----- c /// // | 4* | 7 | /// // d f | 5 /// // | 1* | 1* | /// // \------ e ------/ /// /// let path = astar(&g, a, |finish| finish == f, |e| *e.weight(), |_| 0); /// assert_eq!(path, Some((6, vec![a, d, e, f]))); /// ``` /// /// Returns the total cost + the path of subsequent `NodeId` from start to finish, if one was /// found. pub fn astar<G, F, H, K, IsGoal>( graph: G, start: G::NodeId, mut is_goal: IsGoal, mut edge_cost: F, mut estimate_cost: H, ) -> Option<(K, Vec<G::NodeId>)> where G: IntoEdges + Visitable, IsGoal: FnMut(G::NodeId) -> bool, G::NodeId: Eq + Hash, F: FnMut(G::EdgeRef) -> K, H: FnMut(G::NodeId) -> K, K: Measure + Copy, { let mut visited = graph.visit_map(); let mut visit_next = BinaryHeap::new(); let mut scores = HashMap::new(); let mut path_tracker = PathTracker::<G>::new(); let zero_score = K::default(); scores.insert(start, zero_score); visit_next.push(MinScored(estimate_cost(start), start)); while let Some(MinScored(_, node)) = visit_next.pop() { if is_goal(node) { let path = path_tracker.reconstruct_path_to(node); let cost = scores[&node]; return Some((cost, path)); } // Don't visit the same node several times, as the first time it was visited it was using // the shortest available path. if!visited.visit(node) { continue; } // This lookup can be unwrapped without fear of panic since the node was necessarily scored // before adding him to `visit_next`. let node_score = scores[&node]; for edge in graph.edges(node) { let next = edge.target(); if visited.is_visited(&next) { continue; } let mut next_score = node_score + edge_cost(edge); match scores.entry(next) { Occupied(ent) => { let old_score = *ent.get(); if next_score < old_score { *ent.into_mut() = next_score; path_tracker.set_predecessor(next, node); } else { next_score = old_score; } } Vacant(ent) => { ent.insert(next_score); path_tracker.set_predecessor(next, node); } } let next_estimate_score = next_score + estimate_cost(next); visit_next.push(MinScored(next_estimate_score, next)); } } None } struct PathTracker<G> where G: GraphBase, G::NodeId: Eq + Hash, { came_from: HashMap<G::NodeId, G::NodeId>, } impl<G> PathTracker<G> where G: GraphBase, G::NodeId: Eq + Hash, { fn new() -> PathTracker<G> { PathTracker { came_from: HashMap::new(), } } fn set_predecessor(&mut self, node: G::NodeId, previous: G::NodeId) { self.came_from.insert(node, previous); } fn
(&self, last: G::NodeId) -> Vec<G::NodeId> { let mut path = vec![last]; let mut current = last; while let Some(&previous) = self.came_from.get(&current) { path.push(previous); current = previous; } path.reverse(); path } }
reconstruct_path_to
identifier_name
astar.rs
use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::{BinaryHeap, HashMap}; use std::hash::Hash; use super::visit::{EdgeRef, GraphBase, IntoEdges, VisitMap, Visitable}; use crate::scored::MinScored; use crate::algo::Measure; /// \[Generic\] A* shortest path algorithm. /// /// Computes the shortest path from `start` to `finish`, including the total path cost. /// /// `finish` is implicitly given via the `is_goal` callback, which should return `true` if the /// given node is the finish node. /// /// The function `edge_cost` should return the cost for a particular edge. Edge costs must be /// non-negative. /// /// The function `estimate_cost` should return the estimated cost to the finish for a particular /// node. For the algorithm to find the actual shortest path, it should be admissible, meaning that /// it should never overestimate the actual cost to get to the nearest goal node. Estimate costs /// must also be non-negative. /// /// The graph should be `Visitable` and implement `IntoEdges`. /// /// # Example /// ``` /// use petgraph::Graph; /// use petgraph::algo::astar; /// /// let mut g = Graph::new(); /// let a = g.add_node((0., 0.)); /// let b = g.add_node((2., 0.)); /// let c = g.add_node((1., 1.)); /// let d = g.add_node((0., 2.)); /// let e = g.add_node((3., 3.)); /// let f = g.add_node((4., 2.)); /// g.extend_with_edges(&[ /// (a, b, 2), /// (a, d, 4), /// (b, c, 1), /// (b, f, 7), /// (c, e, 5), /// (e, f, 1), /// (d, e, 1), /// ]); /// /// // Graph represented with the weight of each edge /// // Edges with '*' are part of the optimal path. /// // /// // 2 1 /// // a ----- b ----- c /// // | 4* | 7 | /// // d f | 5 /// // | 1* | 1* | /// // \------ e ------/ /// /// let path = astar(&g, a, |finish| finish == f, |e| *e.weight(), |_| 0); /// assert_eq!(path, Some((6, vec![a, d, e, f]))); /// ``` /// /// Returns the total cost + the path of subsequent `NodeId` from start to finish, if one was /// found. pub fn astar<G, F, H, K, IsGoal>( graph: G, start: G::NodeId, mut is_goal: IsGoal, mut edge_cost: F, mut estimate_cost: H, ) -> Option<(K, Vec<G::NodeId>)> where G: IntoEdges + Visitable, IsGoal: FnMut(G::NodeId) -> bool, G::NodeId: Eq + Hash, F: FnMut(G::EdgeRef) -> K, H: FnMut(G::NodeId) -> K, K: Measure + Copy, { let mut visited = graph.visit_map(); let mut visit_next = BinaryHeap::new(); let mut scores = HashMap::new(); let mut path_tracker = PathTracker::<G>::new(); let zero_score = K::default(); scores.insert(start, zero_score); visit_next.push(MinScored(estimate_cost(start), start)); while let Some(MinScored(_, node)) = visit_next.pop() { if is_goal(node) { let path = path_tracker.reconstruct_path_to(node); let cost = scores[&node]; return Some((cost, path)); } // Don't visit the same node several times, as the first time it was visited it was using // the shortest available path. if!visited.visit(node) { continue; } // This lookup can be unwrapped without fear of panic since the node was necessarily scored // before adding him to `visit_next`. let node_score = scores[&node]; for edge in graph.edges(node) { let next = edge.target(); if visited.is_visited(&next) { continue; } let mut next_score = node_score + edge_cost(edge); match scores.entry(next) { Occupied(ent) => { let old_score = *ent.get(); if next_score < old_score { *ent.into_mut() = next_score; path_tracker.set_predecessor(next, node); } else { next_score = old_score; } } Vacant(ent) => { ent.insert(next_score); path_tracker.set_predecessor(next, node); } } let next_estimate_score = next_score + estimate_cost(next); visit_next.push(MinScored(next_estimate_score, next)); } } None } struct PathTracker<G> where G: GraphBase, G::NodeId: Eq + Hash, { came_from: HashMap<G::NodeId, G::NodeId>, } impl<G> PathTracker<G> where G: GraphBase, G::NodeId: Eq + Hash, { fn new() -> PathTracker<G> { PathTracker { came_from: HashMap::new(), } } fn set_predecessor(&mut self, node: G::NodeId, previous: G::NodeId)
fn reconstruct_path_to(&self, last: G::NodeId) -> Vec<G::NodeId> { let mut path = vec![last]; let mut current = last; while let Some(&previous) = self.came_from.get(&current) { path.push(previous); current = previous; } path.reverse(); path } }
{ self.came_from.insert(node, previous); }
identifier_body
lib.rs
//! `gel` is an extension of sebcrozet's `nalgebra` crate, designed to facilitate OpenGL //! mathematics. extern crate num; extern crate nalgebra; extern crate glium; extern crate rustc_serialize; use std::mem; use std::ptr; use glium::program::BlockLayout; use glium::uniforms::{ AsUniformValue, UniformValue, UniformBlock, LayoutMismatchError, }; pub use num::{ One, Zero, }; pub use nalgebra::*; /// A trait for objects able to be extended. pub trait Extend<N> { type Output; fn extend(&self, N) -> Self::Output; } /// A trait for objects able to be truncated. pub trait Truncate { type Output; fn truncate(&self) -> Self::Output; } /// A trait for objects able to construct view matrices. pub trait LookAt<N> { fn look_at(camera: &Vec3<N>, target: &Vec3<N>, up: &Vec3<N>) -> Self; } macro_rules! impl_extend { ($t_in:ident, $t_out:ident, {$($compN:ident),*} + $ext:ident) => { impl<N> Extend<N> for $t_in<N> where N: Copy { type Output = $t_out<N>; fn extend(&self, elem: N) -> Self::Output { unsafe { let mut res: Self::Output = mem::uninitialized(); $(ptr::write(&mut res.$compN, self.$compN);)* ptr::write(&mut res.$ext, elem); res } } } } } macro_rules! impl_truncate { ($t_in:ident, $t_out:ident, {$($compN:ident),*}) => { impl<N> Truncate for $t_in<N> where N: Copy { type Output = $t_out<N>; fn truncate(&self) -> Self::Output { $t_out::new($(self.$compN),*) } } } } impl_extend!(Vec0, Vec1, {} + x); impl_extend!(Vec1, Vec2, {x} + y); impl_extend!(Vec2, Vec3, {x, y} + z); impl_extend!(Vec3, Vec4, {x, y, z} + w); impl_extend!(Vec4, Vec5, {x, y, z, w} + a); impl_extend!(Vec5, Vec6, {x, y, z, w, a} + b); impl_extend!(Pnt0, Pnt1, {} + x); impl_extend!(Pnt1, Pnt2, {x} + y); impl_extend!(Pnt2, Pnt3, {x, y} + z); impl_extend!(Pnt3, Pnt4, {x, y, z} + w); impl_extend!(Pnt4, Pnt5, {x, y, z, w} + a); impl_extend!(Pnt5, Pnt6, {x, y, z, w, a} + b); impl_truncate!(Vec1, Vec0, {}); impl_truncate!(Vec2, Vec1, {x}); impl_truncate!(Vec3, Vec2, {x, y}); impl_truncate!(Vec4, Vec3, {x, y, z}); impl_truncate!(Vec5, Vec4, {x, y, z, w}); impl_truncate!(Vec6, Vec5, {x, y, z, w, a}); impl_truncate!(Pnt1, Pnt0, {}); impl_truncate!(Pnt2, Pnt1, {x}); impl_truncate!(Pnt3, Pnt2, {x, y}); impl_truncate!(Pnt4, Pnt3, {x, y, z}); impl_truncate!(Pnt5, Pnt4, {x, y, z, w}); impl_truncate!(Pnt6, Pnt5, {x, y, z, w, a}); impl<N> LookAt<N> for Rot3<N> where N: BaseFloat { fn look_at(camera: &Vec3<N>, target: &Vec3<N>, up: &Vec3<N>) -> Self { let zaxis = (*target - *camera).normalize(); let xaxis = zaxis.cross(up).normalize(); let yaxis = xaxis.cross(&zaxis); let mat = Mat3::new(xaxis.x, xaxis.y, xaxis.z, yaxis.x, yaxis.y, yaxis.z, -zaxis.x, -zaxis.y, -zaxis.z); unsafe { Rot3::new_with_mat(mat) } } } impl<N> LookAt<N> for Iso3<N> where N: BaseFloat { fn look_at(camera: &Vec3<N>, target: &Vec3<N>, up: &Vec3<N>) -> Self { let zaxis = (*target - *camera).normalize(); let xaxis = zaxis.cross(up).normalize(); let yaxis = xaxis.cross(&zaxis); let mat = Mat3::new(xaxis.x, xaxis.y, xaxis.z, yaxis.x, yaxis.y, yaxis.z, -zaxis.x, -zaxis.y, -zaxis.z); let rotmat = unsafe { Rot3::new_with_mat(mat) }; let tx = -(camera.dot(&xaxis)); let ty = -(camera.dot(&yaxis)); let tz = camera.dot(&zaxis); let trans = Vec3::new(tx, ty, tz); Iso3::new_with_rotmat(trans, rotmat) } } impl<N> LookAt<N> for Mat4<N> where N: BaseFloat { fn look_at(camera: &Vec3<N>, target: &Vec3<N>, up: &Vec3<N>) -> Self { let zaxis = (*target - *camera).normalize(); let xaxis = zaxis.cross(up).normalize(); let yaxis = xaxis.cross(&zaxis); let tx = -(camera.dot(&xaxis)); let ty = -(camera.dot(&yaxis)); let tz = camera.dot(&zaxis); let one = N::one(); let zero = N::zero(); Mat4::new( xaxis.x, xaxis.y, xaxis.z, tx, yaxis.x, yaxis.y, yaxis.z, ty, -zaxis.x, -zaxis.y, -zaxis.z, tz, zero, zero, zero, one,) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, RustcDecodable, RustcEncodable)] pub struct Perspective<N> { mat: Mat4<N>, } impl<N> Perspective<N> where N: BaseFloat { pub fn new(fov: N, aspect: N, znear: N, zfar: N) -> Perspective<N> { let one = N::one(); let two = one + one; let tan_half_fov = (fov / two).tan(); let mut mat = Mat4::zero(); mat.m11 = one / (aspect * tan_half_fov); mat.m22 = one / (tan_half_fov); mat.m33 = -(zfar + znear) / (zfar - znear); mat.m43 = -one; mat.m34 = -(two * zfar * znear) / (zfar - znear); Perspective { mat: mat, } } pub fn aspect(&self) -> N { self.mat.m22 / self.mat.m11 } pub fn set_aspect(&mut self, aspect: N) { self.mat.m11 = self.mat.m22 / aspect; } pub fn as_mat<'a>(&'a self) -> &'a Mat4<N> { &self.mat } } impl<N> Perspective<N> where N: BaseFloat + Clone { pub fn to_mat(&self) -> Mat4<N> { self.mat.clone() } } impl AsUniformValue for Perspective<f32> { fn as_uniform_value(&self) -> UniformValue { let val = self.to_mat(); UniformValue::Mat4(unsafe { mem::transmute(val) }) } } impl UniformBlock for Perspective<f32> { fn matches(layout: &BlockLayout, base_offset: usize) -> Result<(), LayoutMismatchError> { Mat4::matches(layout, base_offset) } fn build_layout(base_offset: usize) -> glium::program::BlockLayout { Mat4::build_layout(base_offset) } } pub trait FloatExt: BaseFloat { fn radians(self) -> Self { self * (Self::pi() / <Self as Cast<f64>>::from(180.0)) } fn degrees(self) -> Self { self * (<Self as Cast<f64>>::from(180.0) / Self::pi()) } } impl FloatExt for f32 {} impl FloatExt for f64 {} pub fn radians<N>(n: N) -> N where N: FloatExt { n.radians() } pub fn
<N>(n: N) -> N where N: FloatExt { n.degrees() } pub fn extend<T, N>(base: T, elem: N) -> T::Output where T: Extend<N> { base.extend(elem) } pub fn truncate<T>(base: T) -> T::Output where T: Truncate { base.truncate() } #[cfg(test)] mod tests { use super::*; macro_rules! test_extend { ($t_in:ident, $t_out:ident, $elt:ident) => {{ let x = $t_in::zero(); let mut t = $t_out::zero(); t.$elt = one::<f32>(); let n = x.extend(one()); assert!(n.approx_eq(&t)); }} } #[test] fn test_extend() { test_extend!(Vec0, Vec1, x); test_extend!(Vec1, Vec2, y); test_extend!(Vec2, Vec3, z); test_extend!(Vec3, Vec4, w); test_extend!(Vec4, Vec5, a); test_extend!(Vec5, Vec6, b); } #[test] fn test_radians() { let x = 360.0; let t = f32::two_pi(); let n = x.radians(); assert!(n.approx_eq(&t)); } #[test] fn test_degrees() { let x = f32::two_pi(); let t = 360.0; let n = x.degrees(); assert!(n.approx_eq(&t)); } }
degrees
identifier_name
lib.rs
//! `gel` is an extension of sebcrozet's `nalgebra` crate, designed to facilitate OpenGL //! mathematics. extern crate num; extern crate nalgebra; extern crate glium; extern crate rustc_serialize; use std::mem; use std::ptr; use glium::program::BlockLayout; use glium::uniforms::{ AsUniformValue, UniformValue, UniformBlock, LayoutMismatchError, }; pub use num::{ One, Zero, }; pub use nalgebra::*; /// A trait for objects able to be extended. pub trait Extend<N> { type Output; fn extend(&self, N) -> Self::Output; } /// A trait for objects able to be truncated. pub trait Truncate { type Output; fn truncate(&self) -> Self::Output; } /// A trait for objects able to construct view matrices. pub trait LookAt<N> { fn look_at(camera: &Vec3<N>, target: &Vec3<N>, up: &Vec3<N>) -> Self; } macro_rules! impl_extend { ($t_in:ident, $t_out:ident, {$($compN:ident),*} + $ext:ident) => { impl<N> Extend<N> for $t_in<N> where N: Copy { type Output = $t_out<N>; fn extend(&self, elem: N) -> Self::Output { unsafe { let mut res: Self::Output = mem::uninitialized(); $(ptr::write(&mut res.$compN, self.$compN);)* ptr::write(&mut res.$ext, elem); res } } } } } macro_rules! impl_truncate { ($t_in:ident, $t_out:ident, {$($compN:ident),*}) => { impl<N> Truncate for $t_in<N> where N: Copy { type Output = $t_out<N>; fn truncate(&self) -> Self::Output { $t_out::new($(self.$compN),*) } } } } impl_extend!(Vec0, Vec1, {} + x); impl_extend!(Vec1, Vec2, {x} + y); impl_extend!(Vec2, Vec3, {x, y} + z); impl_extend!(Vec3, Vec4, {x, y, z} + w); impl_extend!(Vec4, Vec5, {x, y, z, w} + a); impl_extend!(Vec5, Vec6, {x, y, z, w, a} + b); impl_extend!(Pnt0, Pnt1, {} + x); impl_extend!(Pnt1, Pnt2, {x} + y); impl_extend!(Pnt2, Pnt3, {x, y} + z); impl_extend!(Pnt3, Pnt4, {x, y, z} + w); impl_extend!(Pnt4, Pnt5, {x, y, z, w} + a); impl_extend!(Pnt5, Pnt6, {x, y, z, w, a} + b); impl_truncate!(Vec1, Vec0, {}); impl_truncate!(Vec2, Vec1, {x}); impl_truncate!(Vec3, Vec2, {x, y}); impl_truncate!(Vec4, Vec3, {x, y, z}); impl_truncate!(Vec5, Vec4, {x, y, z, w}); impl_truncate!(Vec6, Vec5, {x, y, z, w, a}); impl_truncate!(Pnt1, Pnt0, {}); impl_truncate!(Pnt2, Pnt1, {x}); impl_truncate!(Pnt3, Pnt2, {x, y}); impl_truncate!(Pnt4, Pnt3, {x, y, z}); impl_truncate!(Pnt5, Pnt4, {x, y, z, w}); impl_truncate!(Pnt6, Pnt5, {x, y, z, w, a}); impl<N> LookAt<N> for Rot3<N> where N: BaseFloat { fn look_at(camera: &Vec3<N>, target: &Vec3<N>, up: &Vec3<N>) -> Self { let zaxis = (*target - *camera).normalize(); let xaxis = zaxis.cross(up).normalize(); let yaxis = xaxis.cross(&zaxis); let mat = Mat3::new(xaxis.x, xaxis.y, xaxis.z, yaxis.x, yaxis.y, yaxis.z, -zaxis.x, -zaxis.y, -zaxis.z); unsafe { Rot3::new_with_mat(mat) } } } impl<N> LookAt<N> for Iso3<N> where N: BaseFloat { fn look_at(camera: &Vec3<N>, target: &Vec3<N>, up: &Vec3<N>) -> Self { let zaxis = (*target - *camera).normalize(); let xaxis = zaxis.cross(up).normalize(); let yaxis = xaxis.cross(&zaxis); let mat = Mat3::new(xaxis.x, xaxis.y, xaxis.z, yaxis.x, yaxis.y, yaxis.z, -zaxis.x, -zaxis.y, -zaxis.z); let rotmat = unsafe { Rot3::new_with_mat(mat) }; let tx = -(camera.dot(&xaxis)); let ty = -(camera.dot(&yaxis)); let tz = camera.dot(&zaxis); let trans = Vec3::new(tx, ty, tz); Iso3::new_with_rotmat(trans, rotmat) } } impl<N> LookAt<N> for Mat4<N> where N: BaseFloat { fn look_at(camera: &Vec3<N>, target: &Vec3<N>, up: &Vec3<N>) -> Self { let zaxis = (*target - *camera).normalize(); let xaxis = zaxis.cross(up).normalize(); let yaxis = xaxis.cross(&zaxis); let tx = -(camera.dot(&xaxis)); let ty = -(camera.dot(&yaxis)); let tz = camera.dot(&zaxis); let one = N::one(); let zero = N::zero(); Mat4::new( xaxis.x, xaxis.y, xaxis.z, tx, yaxis.x, yaxis.y, yaxis.z, ty, -zaxis.x, -zaxis.y, -zaxis.z, tz, zero, zero, zero, one,) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, RustcDecodable, RustcEncodable)] pub struct Perspective<N> { mat: Mat4<N>, } impl<N> Perspective<N> where N: BaseFloat { pub fn new(fov: N, aspect: N, znear: N, zfar: N) -> Perspective<N>
pub fn aspect(&self) -> N { self.mat.m22 / self.mat.m11 } pub fn set_aspect(&mut self, aspect: N) { self.mat.m11 = self.mat.m22 / aspect; } pub fn as_mat<'a>(&'a self) -> &'a Mat4<N> { &self.mat } } impl<N> Perspective<N> where N: BaseFloat + Clone { pub fn to_mat(&self) -> Mat4<N> { self.mat.clone() } } impl AsUniformValue for Perspective<f32> { fn as_uniform_value(&self) -> UniformValue { let val = self.to_mat(); UniformValue::Mat4(unsafe { mem::transmute(val) }) } } impl UniformBlock for Perspective<f32> { fn matches(layout: &BlockLayout, base_offset: usize) -> Result<(), LayoutMismatchError> { Mat4::matches(layout, base_offset) } fn build_layout(base_offset: usize) -> glium::program::BlockLayout { Mat4::build_layout(base_offset) } } pub trait FloatExt: BaseFloat { fn radians(self) -> Self { self * (Self::pi() / <Self as Cast<f64>>::from(180.0)) } fn degrees(self) -> Self { self * (<Self as Cast<f64>>::from(180.0) / Self::pi()) } } impl FloatExt for f32 {} impl FloatExt for f64 {} pub fn radians<N>(n: N) -> N where N: FloatExt { n.radians() } pub fn degrees<N>(n: N) -> N where N: FloatExt { n.degrees() } pub fn extend<T, N>(base: T, elem: N) -> T::Output where T: Extend<N> { base.extend(elem) } pub fn truncate<T>(base: T) -> T::Output where T: Truncate { base.truncate() } #[cfg(test)] mod tests { use super::*; macro_rules! test_extend { ($t_in:ident, $t_out:ident, $elt:ident) => {{ let x = $t_in::zero(); let mut t = $t_out::zero(); t.$elt = one::<f32>(); let n = x.extend(one()); assert!(n.approx_eq(&t)); }} } #[test] fn test_extend() { test_extend!(Vec0, Vec1, x); test_extend!(Vec1, Vec2, y); test_extend!(Vec2, Vec3, z); test_extend!(Vec3, Vec4, w); test_extend!(Vec4, Vec5, a); test_extend!(Vec5, Vec6, b); } #[test] fn test_radians() { let x = 360.0; let t = f32::two_pi(); let n = x.radians(); assert!(n.approx_eq(&t)); } #[test] fn test_degrees() { let x = f32::two_pi(); let t = 360.0; let n = x.degrees(); assert!(n.approx_eq(&t)); } }
{ let one = N::one(); let two = one + one; let tan_half_fov = (fov / two).tan(); let mut mat = Mat4::zero(); mat.m11 = one / (aspect * tan_half_fov); mat.m22 = one / (tan_half_fov); mat.m33 = -(zfar + znear) / (zfar - znear); mat.m43 = -one; mat.m34 = -(two * zfar * znear) / (zfar - znear); Perspective { mat: mat, } }
identifier_body
lib.rs
//! `gel` is an extension of sebcrozet's `nalgebra` crate, designed to facilitate OpenGL //! mathematics. extern crate num; extern crate nalgebra; extern crate glium; extern crate rustc_serialize; use std::mem; use std::ptr; use glium::program::BlockLayout; use glium::uniforms::{ AsUniformValue, UniformValue, UniformBlock, LayoutMismatchError, }; pub use num::{ One, Zero, }; pub use nalgebra::*; /// A trait for objects able to be extended. pub trait Extend<N> { type Output; fn extend(&self, N) -> Self::Output; } /// A trait for objects able to be truncated. pub trait Truncate { type Output; fn truncate(&self) -> Self::Output; } /// A trait for objects able to construct view matrices. pub trait LookAt<N> { fn look_at(camera: &Vec3<N>, target: &Vec3<N>, up: &Vec3<N>) -> Self; } macro_rules! impl_extend { ($t_in:ident, $t_out:ident, {$($compN:ident),*} + $ext:ident) => { impl<N> Extend<N> for $t_in<N> where N: Copy { type Output = $t_out<N>; fn extend(&self, elem: N) -> Self::Output { unsafe { let mut res: Self::Output = mem::uninitialized(); $(ptr::write(&mut res.$compN, self.$compN);)* ptr::write(&mut res.$ext, elem); res } } } } } macro_rules! impl_truncate { ($t_in:ident, $t_out:ident, {$($compN:ident),*}) => { impl<N> Truncate for $t_in<N> where N: Copy { type Output = $t_out<N>; fn truncate(&self) -> Self::Output { $t_out::new($(self.$compN),*) } } } } impl_extend!(Vec0, Vec1, {} + x); impl_extend!(Vec1, Vec2, {x} + y); impl_extend!(Vec2, Vec3, {x, y} + z); impl_extend!(Vec3, Vec4, {x, y, z} + w); impl_extend!(Vec4, Vec5, {x, y, z, w} + a); impl_extend!(Vec5, Vec6, {x, y, z, w, a} + b); impl_extend!(Pnt0, Pnt1, {} + x); impl_extend!(Pnt1, Pnt2, {x} + y); impl_extend!(Pnt2, Pnt3, {x, y} + z); impl_extend!(Pnt3, Pnt4, {x, y, z} + w); impl_extend!(Pnt4, Pnt5, {x, y, z, w} + a); impl_extend!(Pnt5, Pnt6, {x, y, z, w, a} + b); impl_truncate!(Vec1, Vec0, {}); impl_truncate!(Vec2, Vec1, {x}); impl_truncate!(Vec3, Vec2, {x, y}); impl_truncate!(Vec4, Vec3, {x, y, z}); impl_truncate!(Vec5, Vec4, {x, y, z, w}); impl_truncate!(Vec6, Vec5, {x, y, z, w, a}); impl_truncate!(Pnt1, Pnt0, {}); impl_truncate!(Pnt2, Pnt1, {x}); impl_truncate!(Pnt3, Pnt2, {x, y}); impl_truncate!(Pnt4, Pnt3, {x, y, z}); impl_truncate!(Pnt5, Pnt4, {x, y, z, w}); impl_truncate!(Pnt6, Pnt5, {x, y, z, w, a}); impl<N> LookAt<N> for Rot3<N> where N: BaseFloat { fn look_at(camera: &Vec3<N>, target: &Vec3<N>, up: &Vec3<N>) -> Self { let zaxis = (*target - *camera).normalize(); let xaxis = zaxis.cross(up).normalize(); let yaxis = xaxis.cross(&zaxis); let mat = Mat3::new(xaxis.x, xaxis.y, xaxis.z, yaxis.x, yaxis.y, yaxis.z, -zaxis.x, -zaxis.y, -zaxis.z); unsafe { Rot3::new_with_mat(mat) } } } impl<N> LookAt<N> for Iso3<N> where N: BaseFloat { fn look_at(camera: &Vec3<N>, target: &Vec3<N>, up: &Vec3<N>) -> Self { let zaxis = (*target - *camera).normalize(); let xaxis = zaxis.cross(up).normalize(); let yaxis = xaxis.cross(&zaxis);
yaxis.x, yaxis.y, yaxis.z, -zaxis.x, -zaxis.y, -zaxis.z); let rotmat = unsafe { Rot3::new_with_mat(mat) }; let tx = -(camera.dot(&xaxis)); let ty = -(camera.dot(&yaxis)); let tz = camera.dot(&zaxis); let trans = Vec3::new(tx, ty, tz); Iso3::new_with_rotmat(trans, rotmat) } } impl<N> LookAt<N> for Mat4<N> where N: BaseFloat { fn look_at(camera: &Vec3<N>, target: &Vec3<N>, up: &Vec3<N>) -> Self { let zaxis = (*target - *camera).normalize(); let xaxis = zaxis.cross(up).normalize(); let yaxis = xaxis.cross(&zaxis); let tx = -(camera.dot(&xaxis)); let ty = -(camera.dot(&yaxis)); let tz = camera.dot(&zaxis); let one = N::one(); let zero = N::zero(); Mat4::new( xaxis.x, xaxis.y, xaxis.z, tx, yaxis.x, yaxis.y, yaxis.z, ty, -zaxis.x, -zaxis.y, -zaxis.z, tz, zero, zero, zero, one,) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, RustcDecodable, RustcEncodable)] pub struct Perspective<N> { mat: Mat4<N>, } impl<N> Perspective<N> where N: BaseFloat { pub fn new(fov: N, aspect: N, znear: N, zfar: N) -> Perspective<N> { let one = N::one(); let two = one + one; let tan_half_fov = (fov / two).tan(); let mut mat = Mat4::zero(); mat.m11 = one / (aspect * tan_half_fov); mat.m22 = one / (tan_half_fov); mat.m33 = -(zfar + znear) / (zfar - znear); mat.m43 = -one; mat.m34 = -(two * zfar * znear) / (zfar - znear); Perspective { mat: mat, } } pub fn aspect(&self) -> N { self.mat.m22 / self.mat.m11 } pub fn set_aspect(&mut self, aspect: N) { self.mat.m11 = self.mat.m22 / aspect; } pub fn as_mat<'a>(&'a self) -> &'a Mat4<N> { &self.mat } } impl<N> Perspective<N> where N: BaseFloat + Clone { pub fn to_mat(&self) -> Mat4<N> { self.mat.clone() } } impl AsUniformValue for Perspective<f32> { fn as_uniform_value(&self) -> UniformValue { let val = self.to_mat(); UniformValue::Mat4(unsafe { mem::transmute(val) }) } } impl UniformBlock for Perspective<f32> { fn matches(layout: &BlockLayout, base_offset: usize) -> Result<(), LayoutMismatchError> { Mat4::matches(layout, base_offset) } fn build_layout(base_offset: usize) -> glium::program::BlockLayout { Mat4::build_layout(base_offset) } } pub trait FloatExt: BaseFloat { fn radians(self) -> Self { self * (Self::pi() / <Self as Cast<f64>>::from(180.0)) } fn degrees(self) -> Self { self * (<Self as Cast<f64>>::from(180.0) / Self::pi()) } } impl FloatExt for f32 {} impl FloatExt for f64 {} pub fn radians<N>(n: N) -> N where N: FloatExt { n.radians() } pub fn degrees<N>(n: N) -> N where N: FloatExt { n.degrees() } pub fn extend<T, N>(base: T, elem: N) -> T::Output where T: Extend<N> { base.extend(elem) } pub fn truncate<T>(base: T) -> T::Output where T: Truncate { base.truncate() } #[cfg(test)] mod tests { use super::*; macro_rules! test_extend { ($t_in:ident, $t_out:ident, $elt:ident) => {{ let x = $t_in::zero(); let mut t = $t_out::zero(); t.$elt = one::<f32>(); let n = x.extend(one()); assert!(n.approx_eq(&t)); }} } #[test] fn test_extend() { test_extend!(Vec0, Vec1, x); test_extend!(Vec1, Vec2, y); test_extend!(Vec2, Vec3, z); test_extend!(Vec3, Vec4, w); test_extend!(Vec4, Vec5, a); test_extend!(Vec5, Vec6, b); } #[test] fn test_radians() { let x = 360.0; let t = f32::two_pi(); let n = x.radians(); assert!(n.approx_eq(&t)); } #[test] fn test_degrees() { let x = f32::two_pi(); let t = 360.0; let n = x.degrees(); assert!(n.approx_eq(&t)); } }
let mat = Mat3::new(xaxis.x, xaxis.y, xaxis.z,
random_line_split
serial.rs
// Copyright Dan Schatzberg, 2015. This file is part of Genesis. // Genesis is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Genesis 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 Affero General Public License for more details. // You should have received a copy of the GNU Affero General Public License // along with Genesis. If not, see <http://www.gnu.org/licenses/>. #![allow(dead_code)] use super::ioport; const PORT_BASE: u16 = 0x3F8; // when DLAB = 0 const DATA_REG: u16 = 0; const INT_ENABLE: u16 = 1; // when DLAB = 1 const BAUD_DIV_LSB: u16 = 0; const BAUD_DIV_MSB: u16 = 1; const LINE_CTRL_REG: u16 = 3; const LINE_CTRL_REG_CHARLEN8: u8 = 1 | 1 << 1; const LINE_CTRL_REG_DLAB: u8 = 1 << 7; const LINE_STATUS_REG: u16 = 5; const LINE_STATUS_REG_THR_EMPTY: u8 = 1 << 5; /// Initialize the Serial Port pub fn init() { assert_has_not_been_called!("serial::init() function \ must only be called once"); unsafe { ioport::out(PORT_BASE + INT_ENABLE, 0u8); // disable interrupts // enable dlab ioport::out(PORT_BASE + LINE_CTRL_REG, LINE_CTRL_REG_DLAB); // XXX: hard coded 115200 baud ioport::out(PORT_BASE + BAUD_DIV_LSB, 1u8); ioport::out(PORT_BASE + BAUD_DIV_MSB, 0u8); // XXX: hard coded as 8N1 (8 bits, no parity, one stop bit) ioport::out(PORT_BASE + LINE_CTRL_REG, LINE_CTRL_REG_CHARLEN8); } } unsafe fn
() -> bool { ioport::inb(PORT_BASE + LINE_STATUS_REG) & LINE_STATUS_REG_THR_EMPTY!= 0 } unsafe fn putc(c: u8) { while!is_transmit_empty() {} ioport::out(PORT_BASE + DATA_REG, c); } /// Write `str` to the Serial Port pub unsafe fn write_str(s: &str) { for c in s.bytes() { putc(c); } }
is_transmit_empty
identifier_name
serial.rs
// Copyright Dan Schatzberg, 2015. This file is part of Genesis. // Genesis is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Genesis 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 Affero General Public License for more details. // You should have received a copy of the GNU Affero General Public License // along with Genesis. If not, see <http://www.gnu.org/licenses/>. #![allow(dead_code)] use super::ioport; const PORT_BASE: u16 = 0x3F8; // when DLAB = 0 const DATA_REG: u16 = 0; const INT_ENABLE: u16 = 1; // when DLAB = 1 const BAUD_DIV_LSB: u16 = 0; const BAUD_DIV_MSB: u16 = 1; const LINE_CTRL_REG: u16 = 3; const LINE_CTRL_REG_CHARLEN8: u8 = 1 | 1 << 1; const LINE_CTRL_REG_DLAB: u8 = 1 << 7; const LINE_STATUS_REG: u16 = 5; const LINE_STATUS_REG_THR_EMPTY: u8 = 1 << 5; /// Initialize the Serial Port pub fn init() { assert_has_not_been_called!("serial::init() function \ must only be called once"); unsafe { ioport::out(PORT_BASE + INT_ENABLE, 0u8); // disable interrupts // enable dlab ioport::out(PORT_BASE + LINE_CTRL_REG, LINE_CTRL_REG_DLAB); // XXX: hard coded 115200 baud ioport::out(PORT_BASE + BAUD_DIV_LSB, 1u8); ioport::out(PORT_BASE + BAUD_DIV_MSB, 0u8); // XXX: hard coded as 8N1 (8 bits, no parity, one stop bit) ioport::out(PORT_BASE + LINE_CTRL_REG, LINE_CTRL_REG_CHARLEN8); } } unsafe fn is_transmit_empty() -> bool { ioport::inb(PORT_BASE + LINE_STATUS_REG) & LINE_STATUS_REG_THR_EMPTY!= 0 } unsafe fn putc(c: u8) { while!is_transmit_empty() {} ioport::out(PORT_BASE + DATA_REG, c); } /// Write `str` to the Serial Port pub unsafe fn write_str(s: &str) {
for c in s.bytes() { putc(c); } }
random_line_split
serial.rs
// Copyright Dan Schatzberg, 2015. This file is part of Genesis. // Genesis is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Genesis 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 Affero General Public License for more details. // You should have received a copy of the GNU Affero General Public License // along with Genesis. If not, see <http://www.gnu.org/licenses/>. #![allow(dead_code)] use super::ioport; const PORT_BASE: u16 = 0x3F8; // when DLAB = 0 const DATA_REG: u16 = 0; const INT_ENABLE: u16 = 1; // when DLAB = 1 const BAUD_DIV_LSB: u16 = 0; const BAUD_DIV_MSB: u16 = 1; const LINE_CTRL_REG: u16 = 3; const LINE_CTRL_REG_CHARLEN8: u8 = 1 | 1 << 1; const LINE_CTRL_REG_DLAB: u8 = 1 << 7; const LINE_STATUS_REG: u16 = 5; const LINE_STATUS_REG_THR_EMPTY: u8 = 1 << 5; /// Initialize the Serial Port pub fn init() { assert_has_not_been_called!("serial::init() function \ must only be called once"); unsafe { ioport::out(PORT_BASE + INT_ENABLE, 0u8); // disable interrupts // enable dlab ioport::out(PORT_BASE + LINE_CTRL_REG, LINE_CTRL_REG_DLAB); // XXX: hard coded 115200 baud ioport::out(PORT_BASE + BAUD_DIV_LSB, 1u8); ioport::out(PORT_BASE + BAUD_DIV_MSB, 0u8); // XXX: hard coded as 8N1 (8 bits, no parity, one stop bit) ioport::out(PORT_BASE + LINE_CTRL_REG, LINE_CTRL_REG_CHARLEN8); } } unsafe fn is_transmit_empty() -> bool
unsafe fn putc(c: u8) { while!is_transmit_empty() {} ioport::out(PORT_BASE + DATA_REG, c); } /// Write `str` to the Serial Port pub unsafe fn write_str(s: &str) { for c in s.bytes() { putc(c); } }
{ ioport::inb(PORT_BASE + LINE_STATUS_REG) & LINE_STATUS_REG_THR_EMPTY != 0 }
identifier_body
to_device.rs
//! Common types for the Send-To-Device Messaging //! //! [send-to-device]: https://spec.matrix.org/v1.2/client-server-api/#send-to-device-messaging use std::{ convert::TryFrom, fmt::{Display, Formatter, Result as FmtResult}, }; use serde::{ de::{self, Unexpected}, Deserialize, Deserializer, Serialize, Serializer, }; use crate::DeviceId; /// Represents one or all of a user's devices. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] #[allow(clippy::exhaustive_enums)] pub enum DeviceIdOrAllDevices { /// Represents a device Id for one of a user's devices. DeviceId(Box<DeviceId>), /// Represents all devices for a user. AllDevices, } impl Display for DeviceIdOrAllDevices { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { match self { DeviceIdOrAllDevices::DeviceId(device_id) => write!(f, "{}", device_id), DeviceIdOrAllDevices::AllDevices => write!(f, "*"), } } } impl From<Box<DeviceId>> for DeviceIdOrAllDevices { fn from(d: Box<DeviceId>) -> Self { DeviceIdOrAllDevices::DeviceId(d) } } impl TryFrom<&str> for DeviceIdOrAllDevices { type Error = &'static str; fn try_from(device_id_or_all_devices: &str) -> Result<Self, Self::Error> { if device_id_or_all_devices.is_empty() { Err("Device identifier cannot be empty") } else if "*" == device_id_or_all_devices { Ok(DeviceIdOrAllDevices::AllDevices) } else { Ok(DeviceIdOrAllDevices::DeviceId(device_id_or_all_devices.into())) } } } impl Serialize for DeviceIdOrAllDevices { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self { Self::DeviceId(device_id) => device_id.serialize(serializer), Self::AllDevices => serializer.serialize_str("*"), } } } impl<'de> Deserialize<'de> for DeviceIdOrAllDevices { fn
<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let s = ruma_serde::deserialize_cow_str(deserializer)?; DeviceIdOrAllDevices::try_from(s.as_ref()).map_err(|_| { de::Error::invalid_value(Unexpected::Str(&s), &"a valid device identifier or '*'") }) } }
deserialize
identifier_name
to_device.rs
//! Common types for the Send-To-Device Messaging //! //! [send-to-device]: https://spec.matrix.org/v1.2/client-server-api/#send-to-device-messaging use std::{ convert::TryFrom, fmt::{Display, Formatter, Result as FmtResult}, }; use serde::{ de::{self, Unexpected}, Deserialize, Deserializer, Serialize, Serializer, }; use crate::DeviceId; /// Represents one or all of a user's devices. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] #[allow(clippy::exhaustive_enums)] pub enum DeviceIdOrAllDevices { /// Represents a device Id for one of a user's devices. DeviceId(Box<DeviceId>), /// Represents all devices for a user. AllDevices, } impl Display for DeviceIdOrAllDevices { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult
} impl From<Box<DeviceId>> for DeviceIdOrAllDevices { fn from(d: Box<DeviceId>) -> Self { DeviceIdOrAllDevices::DeviceId(d) } } impl TryFrom<&str> for DeviceIdOrAllDevices { type Error = &'static str; fn try_from(device_id_or_all_devices: &str) -> Result<Self, Self::Error> { if device_id_or_all_devices.is_empty() { Err("Device identifier cannot be empty") } else if "*" == device_id_or_all_devices { Ok(DeviceIdOrAllDevices::AllDevices) } else { Ok(DeviceIdOrAllDevices::DeviceId(device_id_or_all_devices.into())) } } } impl Serialize for DeviceIdOrAllDevices { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self { Self::DeviceId(device_id) => device_id.serialize(serializer), Self::AllDevices => serializer.serialize_str("*"), } } } impl<'de> Deserialize<'de> for DeviceIdOrAllDevices { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let s = ruma_serde::deserialize_cow_str(deserializer)?; DeviceIdOrAllDevices::try_from(s.as_ref()).map_err(|_| { de::Error::invalid_value(Unexpected::Str(&s), &"a valid device identifier or '*'") }) } }
{ match self { DeviceIdOrAllDevices::DeviceId(device_id) => write!(f, "{}", device_id), DeviceIdOrAllDevices::AllDevices => write!(f, "*"), } }
identifier_body
to_device.rs
//! Common types for the Send-To-Device Messaging //! //! [send-to-device]: https://spec.matrix.org/v1.2/client-server-api/#send-to-device-messaging use std::{ convert::TryFrom, fmt::{Display, Formatter, Result as FmtResult}, }; use serde::{ de::{self, Unexpected}, Deserialize, Deserializer, Serialize, Serializer, }; use crate::DeviceId; /// Represents one or all of a user's devices. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] #[allow(clippy::exhaustive_enums)] pub enum DeviceIdOrAllDevices { /// Represents a device Id for one of a user's devices. DeviceId(Box<DeviceId>), /// Represents all devices for a user. AllDevices, } impl Display for DeviceIdOrAllDevices { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { match self { DeviceIdOrAllDevices::DeviceId(device_id) => write!(f, "{}", device_id), DeviceIdOrAllDevices::AllDevices => write!(f, "*"), } } } impl From<Box<DeviceId>> for DeviceIdOrAllDevices { fn from(d: Box<DeviceId>) -> Self { DeviceIdOrAllDevices::DeviceId(d) } } impl TryFrom<&str> for DeviceIdOrAllDevices { type Error = &'static str; fn try_from(device_id_or_all_devices: &str) -> Result<Self, Self::Error> { if device_id_or_all_devices.is_empty() { Err("Device identifier cannot be empty") } else if "*" == device_id_or_all_devices { Ok(DeviceIdOrAllDevices::AllDevices) } else
} } impl Serialize for DeviceIdOrAllDevices { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self { Self::DeviceId(device_id) => device_id.serialize(serializer), Self::AllDevices => serializer.serialize_str("*"), } } } impl<'de> Deserialize<'de> for DeviceIdOrAllDevices { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let s = ruma_serde::deserialize_cow_str(deserializer)?; DeviceIdOrAllDevices::try_from(s.as_ref()).map_err(|_| { de::Error::invalid_value(Unexpected::Str(&s), &"a valid device identifier or '*'") }) } }
{ Ok(DeviceIdOrAllDevices::DeviceId(device_id_or_all_devices.into())) }
conditional_block
to_device.rs
//! Common types for the Send-To-Device Messaging //! //! [send-to-device]: https://spec.matrix.org/v1.2/client-server-api/#send-to-device-messaging use std::{ convert::TryFrom, fmt::{Display, Formatter, Result as FmtResult}, }; use serde::{ de::{self, Unexpected}, Deserialize, Deserializer, Serialize, Serializer, }; use crate::DeviceId; /// Represents one or all of a user's devices. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] #[allow(clippy::exhaustive_enums)] pub enum DeviceIdOrAllDevices { /// Represents a device Id for one of a user's devices. DeviceId(Box<DeviceId>), /// Represents all devices for a user. AllDevices, } impl Display for DeviceIdOrAllDevices {
match self { DeviceIdOrAllDevices::DeviceId(device_id) => write!(f, "{}", device_id), DeviceIdOrAllDevices::AllDevices => write!(f, "*"), } } } impl From<Box<DeviceId>> for DeviceIdOrAllDevices { fn from(d: Box<DeviceId>) -> Self { DeviceIdOrAllDevices::DeviceId(d) } } impl TryFrom<&str> for DeviceIdOrAllDevices { type Error = &'static str; fn try_from(device_id_or_all_devices: &str) -> Result<Self, Self::Error> { if device_id_or_all_devices.is_empty() { Err("Device identifier cannot be empty") } else if "*" == device_id_or_all_devices { Ok(DeviceIdOrAllDevices::AllDevices) } else { Ok(DeviceIdOrAllDevices::DeviceId(device_id_or_all_devices.into())) } } } impl Serialize for DeviceIdOrAllDevices { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self { Self::DeviceId(device_id) => device_id.serialize(serializer), Self::AllDevices => serializer.serialize_str("*"), } } } impl<'de> Deserialize<'de> for DeviceIdOrAllDevices { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let s = ruma_serde::deserialize_cow_str(deserializer)?; DeviceIdOrAllDevices::try_from(s.as_ref()).map_err(|_| { de::Error::invalid_value(Unexpected::Str(&s), &"a valid device identifier or '*'") }) } }
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
random_line_split
lib.rs
//! af-cuda-interop package is to used only when the application intends to mix //! arrayfire code with raw CUDA code. use arrayfire::{handle_error_general, AfError}; use cuda_runtime_sys::cudaStream_t; use libc::c_int; extern "C" { fn afcu_get_native_id(native_id: *mut c_int, id: c_int) -> c_int; fn afcu_set_native_id(native_id: c_int) -> c_int; fn afcu_get_stream(out: *mut cudaStream_t, id: c_int) -> c_int; } /// Get active device's id in CUDA context /// /// # Parameters /// /// - `id` is the integer identifier of concerned CUDA device as per ArrayFire context /// /// # Return Values /// /// Integer identifier of device in CUDA context pub fn get_device_native_id(id: i32) -> i32 { unsafe { let mut temp: i32 = 0; let err_val = afcu_get_native_id(&mut temp as *mut c_int, id); handle_error_general(AfError::from(err_val)); temp } } /// Set active device using CUDA context's id /// /// # Parameters /// /// - `id` is the identifier of GPU in CUDA context pub fn set_device_native_id(native_id: i32) { unsafe { let err_val = afcu_set_native_id(native_id); handle_error_general(AfError::from(err_val)); } } /// Get CUDA stream of active CUDA device /// /// # Parameters /// /// - `id` is the identifier of device in ArrayFire context /// /// # Return Values /// /// [cudaStream_t](https://docs.rs/cuda-runtime-sys/0.3.0-alpha.1/cuda_runtime_sys/type.cudaStream_t.html) handle. pub fn get_stream(native_id: i32) -> cudaStream_t
{ unsafe { let mut ret_val: cudaStream_t = std::ptr::null_mut(); let err_val = afcu_get_stream(&mut ret_val as *mut cudaStream_t, native_id); handle_error_general(AfError::from(err_val)); ret_val } }
identifier_body
lib.rs
//! af-cuda-interop package is to used only when the application intends to mix //! arrayfire code with raw CUDA code. use arrayfire::{handle_error_general, AfError}; use cuda_runtime_sys::cudaStream_t; use libc::c_int; extern "C" { fn afcu_get_native_id(native_id: *mut c_int, id: c_int) -> c_int; fn afcu_set_native_id(native_id: c_int) -> c_int; fn afcu_get_stream(out: *mut cudaStream_t, id: c_int) -> c_int; } /// Get active device's id in CUDA context /// /// # Parameters /// /// - `id` is the integer identifier of concerned CUDA device as per ArrayFire context /// /// # Return Values /// /// Integer identifier of device in CUDA context pub fn
(id: i32) -> i32 { unsafe { let mut temp: i32 = 0; let err_val = afcu_get_native_id(&mut temp as *mut c_int, id); handle_error_general(AfError::from(err_val)); temp } } /// Set active device using CUDA context's id /// /// # Parameters /// /// - `id` is the identifier of GPU in CUDA context pub fn set_device_native_id(native_id: i32) { unsafe { let err_val = afcu_set_native_id(native_id); handle_error_general(AfError::from(err_val)); } } /// Get CUDA stream of active CUDA device /// /// # Parameters /// /// - `id` is the identifier of device in ArrayFire context /// /// # Return Values /// /// [cudaStream_t](https://docs.rs/cuda-runtime-sys/0.3.0-alpha.1/cuda_runtime_sys/type.cudaStream_t.html) handle. pub fn get_stream(native_id: i32) -> cudaStream_t { unsafe { let mut ret_val: cudaStream_t = std::ptr::null_mut(); let err_val = afcu_get_stream(&mut ret_val as *mut cudaStream_t, native_id); handle_error_general(AfError::from(err_val)); ret_val } }
get_device_native_id
identifier_name
lib.rs
//! af-cuda-interop package is to used only when the application intends to mix //! arrayfire code with raw CUDA code. use arrayfire::{handle_error_general, AfError}; use cuda_runtime_sys::cudaStream_t; use libc::c_int; extern "C" { fn afcu_get_native_id(native_id: *mut c_int, id: c_int) -> c_int; fn afcu_set_native_id(native_id: c_int) -> c_int; fn afcu_get_stream(out: *mut cudaStream_t, id: c_int) -> c_int; } /// Get active device's id in CUDA context /// /// # Parameters /// /// - `id` is the integer identifier of concerned CUDA device as per ArrayFire context /// /// # Return Values /// /// Integer identifier of device in CUDA context pub fn get_device_native_id(id: i32) -> i32 { unsafe { let mut temp: i32 = 0; let err_val = afcu_get_native_id(&mut temp as *mut c_int, id); handle_error_general(AfError::from(err_val)); temp
} /// Set active device using CUDA context's id /// /// # Parameters /// /// - `id` is the identifier of GPU in CUDA context pub fn set_device_native_id(native_id: i32) { unsafe { let err_val = afcu_set_native_id(native_id); handle_error_general(AfError::from(err_val)); } } /// Get CUDA stream of active CUDA device /// /// # Parameters /// /// - `id` is the identifier of device in ArrayFire context /// /// # Return Values /// /// [cudaStream_t](https://docs.rs/cuda-runtime-sys/0.3.0-alpha.1/cuda_runtime_sys/type.cudaStream_t.html) handle. pub fn get_stream(native_id: i32) -> cudaStream_t { unsafe { let mut ret_val: cudaStream_t = std::ptr::null_mut(); let err_val = afcu_get_stream(&mut ret_val as *mut cudaStream_t, native_id); handle_error_general(AfError::from(err_val)); ret_val } }
}
random_line_split
lib.rs
//! # Boxcars //! //! Boxcars is a [Rocket League](http://www.rocketleaguegame.com/) replay parser library written in //! Rust. //! //! ## Features //! //! - ✔ Safe: Stable Rust with no unsafe //! - ✔ Fast: Parse a hundred replays per second per CPU core //! - ✔ Fuzzed: Extensively fuzzed against potential malicious input //! - ✔ Ergonomic: Serialization support is provided through [serde](https://github.com/serde-rs/serde) //! //! See where Boxcars in used: //! //! - Inside the [rrrocket CLI app](https://github.com/nickbabcock/rrrocket) to turn Rocket League Replays into JSON //! - Compiled to [WebAssembly and embedded in a web page](https://rl.nickb.dev/) //! - Underpins the python analyzer of the [popular calculated.gg site](https://calculated.gg/) //! //! ## Quick Start //! //! Below is an example to output the replay structure to json: //! //! ```rust //! use boxcars::{ParseError, Replay}; //! use std::error; //! use std::fs; //! use std::io::{self, Read}; //! //! fn parse_rl(data: &[u8]) -> Result<Replay, ParseError> { //! boxcars::ParserBuilder::new(data) //! .must_parse_network_data() //! .parse() //! } //! //! fn run(filename: &str) -> Result<(), Box<dyn error::Error>> { //! let filename = "assets/replays/good/rumble.replay"; //! let buffer = fs::read(filename)?; //! let replay = parse_rl(&buffer)?; //! serde_json::to_writer(&mut io::stdout(), &replay)?; //! Ok(()) //! }
//! //! The above example will parse both the header and network data of a replay file, and return an //! error if there is an issue either header or network data. Since the network data will often //! change with each Rocket League patch, the default behavior is to ignore any errors from the //! network data and still be able to return header information. //! //! ## Variations //! //! If you're only interested the header (where tidbits like goals and scores are stored) then you //! can achieve an 1000x speedup by directing boxcars to only parse the header. //! //! - By skipping network data one can parse and aggregate thousands of replays in //! under a second to provide an immediate response to the user. Then a full //! parsing of the replay data can provide additional insights when given time. //! - By ignoring network data errors, boxcars can still provide details about //! newly patched replays based on the header. //! //! Boxcars will also check for replay corruption on error, but this can be configured to always //! check for corruption or never check. #[macro_use] extern crate serde; #[macro_use] mod macros; pub use self::errors::{AttributeError, FrameContext, FrameError, NetworkError, ParseError}; pub use self::models::*; pub use self::network::attributes::Attribute; pub use self::network::*; pub use self::parser::{CrcCheck, NetworkParse, ParserBuilder}; mod core_parser; pub mod crc; mod data; mod errors; mod header; mod models; mod network; mod parser; mod parsing_utils; mod serde_utils;
//! //! # let filename = "assets/replays/good/rumble.replay"; //! # run(filename).unwrap(); //! ```
random_line_split
memory.rs
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::time::Duration; use data_encoding::{Encoding, HEXLOWER_PERMISSIVE}; use crate::config::{DEFAULT_BATCH_SIZE, DEFAULT_STATUS_INTERVAL}; use crate::config::ServerConfig; use crate::key::KmsProtection; const HEX: Encoding = HEXLOWER_PERMISSIVE; /// A purely in-memory Roughenough config for testing purposes. /// /// This is useful for testing or fuzzing a server without the need to create additional files. pub struct MemoryConfig { pub port: u16, pub interface: String, pub seed: Vec<u8>, pub batch_size: u8, pub status_interval: Duration, pub kms_protection: KmsProtection, pub health_check_port: Option<u16>, pub client_stats: bool, pub fault_percentage: u8, } impl MemoryConfig { pub fn new(port: u16) -> Self { let seed = b"a32049da0ffde0ded92ce10a0230d35fe615ec8461c14986baa63fe3b3bac3db"; MemoryConfig { port, interface: "127.0.0.1".to_string(), seed: HEX.decode(seed).unwrap(), batch_size: DEFAULT_BATCH_SIZE, status_interval: DEFAULT_STATUS_INTERVAL, kms_protection: KmsProtection::Plaintext, health_check_port: None, client_stats: false, fault_percentage: 0, } } } impl ServerConfig for MemoryConfig { fn interface(&self) -> &str { self.interface.as_ref() } fn port(&self) -> u16 { self.port } fn seed(&self) -> Vec<u8> { self.seed.clone() } fn batch_size(&self) -> u8 { self.batch_size } fn status_interval(&self) -> Duration { self.status_interval } fn kms_protection(&self) -> &KmsProtection { &self.kms_protection } fn health_check_port(&self) -> Option<u16> { self.health_check_port } fn client_stats_enabled(&self) -> bool { self.client_stats } fn fault_percentage(&self) -> u8 { self.fault_percentage } }
// Copyright 2017-2021 int08h LLC //
random_line_split
memory.rs
// Copyright 2017-2021 int08h LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::time::Duration; use data_encoding::{Encoding, HEXLOWER_PERMISSIVE}; use crate::config::{DEFAULT_BATCH_SIZE, DEFAULT_STATUS_INTERVAL}; use crate::config::ServerConfig; use crate::key::KmsProtection; const HEX: Encoding = HEXLOWER_PERMISSIVE; /// A purely in-memory Roughenough config for testing purposes. /// /// This is useful for testing or fuzzing a server without the need to create additional files. pub struct
{ pub port: u16, pub interface: String, pub seed: Vec<u8>, pub batch_size: u8, pub status_interval: Duration, pub kms_protection: KmsProtection, pub health_check_port: Option<u16>, pub client_stats: bool, pub fault_percentage: u8, } impl MemoryConfig { pub fn new(port: u16) -> Self { let seed = b"a32049da0ffde0ded92ce10a0230d35fe615ec8461c14986baa63fe3b3bac3db"; MemoryConfig { port, interface: "127.0.0.1".to_string(), seed: HEX.decode(seed).unwrap(), batch_size: DEFAULT_BATCH_SIZE, status_interval: DEFAULT_STATUS_INTERVAL, kms_protection: KmsProtection::Plaintext, health_check_port: None, client_stats: false, fault_percentage: 0, } } } impl ServerConfig for MemoryConfig { fn interface(&self) -> &str { self.interface.as_ref() } fn port(&self) -> u16 { self.port } fn seed(&self) -> Vec<u8> { self.seed.clone() } fn batch_size(&self) -> u8 { self.batch_size } fn status_interval(&self) -> Duration { self.status_interval } fn kms_protection(&self) -> &KmsProtection { &self.kms_protection } fn health_check_port(&self) -> Option<u16> { self.health_check_port } fn client_stats_enabled(&self) -> bool { self.client_stats } fn fault_percentage(&self) -> u8 { self.fault_percentage } }
MemoryConfig
identifier_name
memory.rs
// Copyright 2017-2021 int08h LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::time::Duration; use data_encoding::{Encoding, HEXLOWER_PERMISSIVE}; use crate::config::{DEFAULT_BATCH_SIZE, DEFAULT_STATUS_INTERVAL}; use crate::config::ServerConfig; use crate::key::KmsProtection; const HEX: Encoding = HEXLOWER_PERMISSIVE; /// A purely in-memory Roughenough config for testing purposes. /// /// This is useful for testing or fuzzing a server without the need to create additional files. pub struct MemoryConfig { pub port: u16, pub interface: String, pub seed: Vec<u8>, pub batch_size: u8, pub status_interval: Duration, pub kms_protection: KmsProtection, pub health_check_port: Option<u16>, pub client_stats: bool, pub fault_percentage: u8, } impl MemoryConfig { pub fn new(port: u16) -> Self { let seed = b"a32049da0ffde0ded92ce10a0230d35fe615ec8461c14986baa63fe3b3bac3db"; MemoryConfig { port, interface: "127.0.0.1".to_string(), seed: HEX.decode(seed).unwrap(), batch_size: DEFAULT_BATCH_SIZE, status_interval: DEFAULT_STATUS_INTERVAL, kms_protection: KmsProtection::Plaintext, health_check_port: None, client_stats: false, fault_percentage: 0, } } } impl ServerConfig for MemoryConfig { fn interface(&self) -> &str { self.interface.as_ref() } fn port(&self) -> u16 { self.port } fn seed(&self) -> Vec<u8> { self.seed.clone() } fn batch_size(&self) -> u8 { self.batch_size } fn status_interval(&self) -> Duration { self.status_interval } fn kms_protection(&self) -> &KmsProtection
fn health_check_port(&self) -> Option<u16> { self.health_check_port } fn client_stats_enabled(&self) -> bool { self.client_stats } fn fault_percentage(&self) -> u8 { self.fault_percentage } }
{ &self.kms_protection }
identifier_body
key-value-expansion.rs
// Regression tests for issue #55414, expansion happens in the value of a key-value attribute, // and the expanded expression is more complex than simply a macro call. // aux-build:key-value-expansion.rs #![feature(rustc_attrs)] extern crate key_value_expansion; // Minimized test case. macro_rules! bug { ($expr:expr) => { #[rustc_dummy = $expr] // Any key-value attribute, not necessarily `doc` struct S; }; } // Any expressions containing macro call `X` that's more complex than `X` itself. // Parentheses will work. bug!((column!())); //~ ERROR unexpected token: `(7u32)` // Original test case. macro_rules! bug { () => { bug!("bug" + stringify!(found)); //~ ERROR unexpected token: `"bug" + "found"` }; ($test:expr) => { #[doc = $test] struct Test {} }; } bug!();
// Test case from #66804. macro_rules! doc_comment { ($x:expr) => { #[doc = $x] extern {} }; } macro_rules! some_macro { ($t1: ty) => { doc_comment! {format!("{coor}", coor = stringify!($t1)).as_str()} //~^ ERROR unexpected token: `{ }; } some_macro!(u8); fn main() {}
random_line_split
key-value-expansion.rs
// Regression tests for issue #55414, expansion happens in the value of a key-value attribute, // and the expanded expression is more complex than simply a macro call. // aux-build:key-value-expansion.rs #![feature(rustc_attrs)] extern crate key_value_expansion; // Minimized test case. macro_rules! bug { ($expr:expr) => { #[rustc_dummy = $expr] // Any key-value attribute, not necessarily `doc` struct S; }; } // Any expressions containing macro call `X` that's more complex than `X` itself. // Parentheses will work. bug!((column!())); //~ ERROR unexpected token: `(7u32)` // Original test case. macro_rules! bug { () => { bug!("bug" + stringify!(found)); //~ ERROR unexpected token: `"bug" + "found"` }; ($test:expr) => { #[doc = $test] struct Test {} }; } bug!(); // Test case from #66804. macro_rules! doc_comment { ($x:expr) => { #[doc = $x] extern {} }; } macro_rules! some_macro { ($t1: ty) => { doc_comment! {format!("{coor}", coor = stringify!($t1)).as_str()} //~^ ERROR unexpected token: `{ }; } some_macro!(u8); fn
() {}
main
identifier_name
key-value-expansion.rs
// Regression tests for issue #55414, expansion happens in the value of a key-value attribute, // and the expanded expression is more complex than simply a macro call. // aux-build:key-value-expansion.rs #![feature(rustc_attrs)] extern crate key_value_expansion; // Minimized test case. macro_rules! bug { ($expr:expr) => { #[rustc_dummy = $expr] // Any key-value attribute, not necessarily `doc` struct S; }; } // Any expressions containing macro call `X` that's more complex than `X` itself. // Parentheses will work. bug!((column!())); //~ ERROR unexpected token: `(7u32)` // Original test case. macro_rules! bug { () => { bug!("bug" + stringify!(found)); //~ ERROR unexpected token: `"bug" + "found"` }; ($test:expr) => { #[doc = $test] struct Test {} }; } bug!(); // Test case from #66804. macro_rules! doc_comment { ($x:expr) => { #[doc = $x] extern {} }; } macro_rules! some_macro { ($t1: ty) => { doc_comment! {format!("{coor}", coor = stringify!($t1)).as_str()} //~^ ERROR unexpected token: `{ }; } some_macro!(u8); fn main()
{}
identifier_body
workspace.rs
//! Workspace module for Xt. //! Handles workspaces and their associated buffers. // This file is part of Xt. // This is the Xt text editor; it edits text. // Copyright (C) 2016-2018 The Xt Developers // This program is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see // <http://www.gnu.org/licenses/>. extern crate slog; use logging::init_logger; use server::buffer::Buffer; /// Workspace struct #[derive(Debug)] pub struct Workspace { /// Human-readable name for workspace. pub hname: String, /// Logger instance for workspace. /// Derived from root Logger. pub logger: slog::Logger, /// Vector of Buffer structs. pub buffers: Vec<Buffer>, } impl Workspace { /// Create a new workspace. pub fn new<S: Into<String>>(hname: S) -> Workspace
}
{ let hname = hname.into(); let logger = init_logger().new(o!("workspace" => hname.clone())); Workspace { hname: hname, logger: logger, buffers: Vec::new(), } }
identifier_body
workspace.rs
//! Workspace module for Xt. //! Handles workspaces and their associated buffers. // This file is part of Xt. // This is the Xt text editor; it edits text. // Copyright (C) 2016-2018 The Xt Developers // This program is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see // <http://www.gnu.org/licenses/>. extern crate slog; use logging::init_logger; use server::buffer::Buffer; /// Workspace struct #[derive(Debug)] pub struct
{ /// Human-readable name for workspace. pub hname: String, /// Logger instance for workspace. /// Derived from root Logger. pub logger: slog::Logger, /// Vector of Buffer structs. pub buffers: Vec<Buffer>, } impl Workspace { /// Create a new workspace. pub fn new<S: Into<String>>(hname: S) -> Workspace { let hname = hname.into(); let logger = init_logger().new(o!("workspace" => hname.clone())); Workspace { hname: hname, logger: logger, buffers: Vec::new(), } } }
Workspace
identifier_name
workspace.rs
//! Workspace module for Xt. //! Handles workspaces and their associated buffers.
// This program is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see // <http://www.gnu.org/licenses/>. extern crate slog; use logging::init_logger; use server::buffer::Buffer; /// Workspace struct #[derive(Debug)] pub struct Workspace { /// Human-readable name for workspace. pub hname: String, /// Logger instance for workspace. /// Derived from root Logger. pub logger: slog::Logger, /// Vector of Buffer structs. pub buffers: Vec<Buffer>, } impl Workspace { /// Create a new workspace. pub fn new<S: Into<String>>(hname: S) -> Workspace { let hname = hname.into(); let logger = init_logger().new(o!("workspace" => hname.clone())); Workspace { hname: hname, logger: logger, buffers: Vec::new(), } } }
// This file is part of Xt. // This is the Xt text editor; it edits text. // Copyright (C) 2016-2018 The Xt Developers
random_line_split
lib.rs
#![crate_name = "rusoto"] #![crate_type = "lib"] #![cfg_attr(feature = "unstable", feature(custom_derive, plugin))] #![cfg_attr(feature = "unstable", plugin(serde_macros))] #![cfg_attr(feature = "nightly-testing", plugin(clippy))] #![cfg_attr(feature = "nightly-testing", allow(cyclomatic_complexity, used_underscore_binding, ptr_arg, suspicious_else_formatting))] #![allow(dead_code)] #![cfg_attr(not(feature = "unstable"), deny(warnings))] //! Rusoto is an [AWS](https://aws.amazon.com/) SDK for Rust. //! A high level overview is available in `README.md` at https://github.com/rusoto/rusoto. //! //! # Example //! //! The following code shows a simple example of using Rusoto's DynamoDB API to //! list the names of all tables in a database. //! //! ```rust,ignore //! use std::default::Default; //! //! use rusoto::{DefaultCredentialsProvider, Region}; //! use rusoto::dynamodb::{DynamoDbClient, ListTablesInput}; //! //! let provider = DefaultCredentialsProvider::new().unwrap(); //! let client = DynamoDbClient::new(provider, Region::UsEast1); //! let list_tables_input: ListTablesInput = Default::default(); //! //! match client.list_tables(&list_tables_input) { //! Ok(output) => { //! match output.table_names { //! Some(table_name_list) => { //! println!("Tables in database:"); //! //! for table_name in table_name_list {
//! } //! }, //! Err(error) => { //! println!("Error: {:?}", error); //! }, //! } extern crate chrono; extern crate hyper; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate md5; extern crate regex; extern crate ring; extern crate rustc_serialize; extern crate serde; extern crate serde_json; extern crate time; extern crate url; extern crate xml; pub use credential::{ AwsCredentials, ChainProvider, CredentialsError, EnvironmentProvider, IamProvider, ProfileProvider, ProvideAwsCredentials, DefaultCredentialsProvider, DefaultCredentialsProviderSync, }; pub use region::{ParseRegionError, Region}; pub use request::{DispatchSignedRequest, HttpResponse, HttpDispatchError}; pub use signature::SignedRequest; mod credential; mod param; mod region; mod request; mod xmlerror; mod xmlutil; mod serialization; #[macro_use] mod signature; #[cfg(test)] mod mock; #[cfg(feature = "acm")] pub mod acm; #[cfg(feature = "cloudhsm")] pub mod cloudhsm; #[cfg(feature = "cloudtrail")] pub mod cloudtrail; #[cfg(feature = "codecommit")] pub mod codecommit; #[cfg(feature = "codedeploy")] pub mod codedeploy; #[cfg(feature = "codepipeline")] pub mod codepipeline; #[cfg(feature = "cognito-identity")] pub mod cognitoidentity; #[cfg(feature = "config")] pub mod config; #[cfg(feature = "datapipeline")] pub mod datapipeline; #[cfg(feature = "devicefarm")] pub mod devicefarm; #[cfg(feature = "directconnect")] pub mod directconnect; #[cfg(feature = "ds")] pub mod ds; #[cfg(feature = "dynamodb")] pub mod dynamodb; #[cfg(feature = "dynamodbstreams")] pub mod dynamodbstreams; #[cfg(feature = "ec2")] pub mod ec2; #[cfg(feature = "ecr")] pub mod ecr; #[cfg(feature = "ecs")] pub mod ecs; #[cfg(feature = "emr")] pub mod emr; #[cfg(feature = "elastictranscoder")] pub mod elastictranscoder; #[cfg(feature = "events")] pub mod events; #[cfg(feature = "firehose")] pub mod firehose; #[cfg(feature = "iam")] pub mod iam; #[cfg(feature = "inspector")] pub mod inspector; #[cfg(feature = "iot")] pub mod iot; #[cfg(feature = "kinesis")] pub mod kinesis; #[cfg(feature = "kms")] pub mod kms; #[cfg(feature = "logs")] pub mod logs; #[cfg(feature = "machinelearning")] pub mod machinelearning; #[cfg(feature = "marketplacecommerceanalytics")] pub mod marketplacecommerceanalytics; #[cfg(feature = "opsworks")] pub mod opsworks; #[cfg(feature = "route53domains")] pub mod route53domains; #[cfg(feature = "s3")] pub mod s3; #[cfg(feature = "sqs")] pub mod sqs; #[cfg(feature = "ssm")] pub mod ssm; #[cfg(feature = "storagegateway")] pub mod storagegateway; #[cfg(feature = "swf")] pub mod swf; #[cfg(feature = "waf")] pub mod waf; #[cfg(feature = "workspaces")] pub mod workspaces; /* #[cfg(feature = "gamelift")] pub mod gamelift; #[cfg(feature = "support")] pub mod support; */
//! println!("{}", table_name); //! } //! }, //! None => println!("No tables in database!"),
random_line_split
local-drop-glue.rs
// // We specify -C incremental here because we want to test the partitioning for // incremental compilation // We specify opt-level=0 because `drop_in_place` is `Internal` when optimizing // compile-flags:-Zprint-mono-items=lazy -Cincremental=tmp/partitioning-tests/local-drop-glue // compile-flags:-Zinline-in-all-cgus -Copt-level=0 #![allow(dead_code)] #![crate_type = "rlib"] //~ MONO_ITEM fn std::ptr::drop_in_place::<Struct> - shim(Some(Struct)) @@ local_drop_glue-fallback.cgu[External] struct Struct { _a: u32, } impl Drop for Struct { //~ MONO_ITEM fn <Struct as std::ops::Drop>::drop @@ local_drop_glue-fallback.cgu[External] fn drop(&mut self) {} }
struct Outer { _a: Struct, } //~ MONO_ITEM fn user @@ local_drop_glue[External] pub fn user() { let _ = Outer { _a: Struct { _a: 0 } }; } pub mod mod1 { use super::Struct; //~ MONO_ITEM fn std::ptr::drop_in_place::<mod1::Struct2> - shim(Some(mod1::Struct2)) @@ local_drop_glue-fallback.cgu[External] struct Struct2 { _a: Struct, //~ MONO_ITEM fn std::ptr::drop_in_place::<(u32, Struct)> - shim(Some((u32, Struct))) @@ local_drop_glue-fallback.cgu[Internal] _b: (u32, Struct), } //~ MONO_ITEM fn mod1::user @@ local_drop_glue-mod1[External] pub fn user() { let _ = Struct2 { _a: Struct { _a: 0 }, _b: (0, Struct { _a: 0 }) }; } }
//~ MONO_ITEM fn std::ptr::drop_in_place::<Outer> - shim(Some(Outer)) @@ local_drop_glue-fallback.cgu[External]
random_line_split
local-drop-glue.rs
// // We specify -C incremental here because we want to test the partitioning for // incremental compilation // We specify opt-level=0 because `drop_in_place` is `Internal` when optimizing // compile-flags:-Zprint-mono-items=lazy -Cincremental=tmp/partitioning-tests/local-drop-glue // compile-flags:-Zinline-in-all-cgus -Copt-level=0 #![allow(dead_code)] #![crate_type = "rlib"] //~ MONO_ITEM fn std::ptr::drop_in_place::<Struct> - shim(Some(Struct)) @@ local_drop_glue-fallback.cgu[External] struct
{ _a: u32, } impl Drop for Struct { //~ MONO_ITEM fn <Struct as std::ops::Drop>::drop @@ local_drop_glue-fallback.cgu[External] fn drop(&mut self) {} } //~ MONO_ITEM fn std::ptr::drop_in_place::<Outer> - shim(Some(Outer)) @@ local_drop_glue-fallback.cgu[External] struct Outer { _a: Struct, } //~ MONO_ITEM fn user @@ local_drop_glue[External] pub fn user() { let _ = Outer { _a: Struct { _a: 0 } }; } pub mod mod1 { use super::Struct; //~ MONO_ITEM fn std::ptr::drop_in_place::<mod1::Struct2> - shim(Some(mod1::Struct2)) @@ local_drop_glue-fallback.cgu[External] struct Struct2 { _a: Struct, //~ MONO_ITEM fn std::ptr::drop_in_place::<(u32, Struct)> - shim(Some((u32, Struct))) @@ local_drop_glue-fallback.cgu[Internal] _b: (u32, Struct), } //~ MONO_ITEM fn mod1::user @@ local_drop_glue-mod1[External] pub fn user() { let _ = Struct2 { _a: Struct { _a: 0 }, _b: (0, Struct { _a: 0 }) }; } }
Struct
identifier_name