hexsha
stringlengths
40
40
size
int64
2
1.05M
content
stringlengths
2
1.05M
avg_line_length
float64
1.33
100
max_line_length
int64
1
1k
alphanum_fraction
float64
0.25
1
76cea497b5b6c5b05aac34a3bd3fa464ec6be79e
659
/// Graph kind determines if `digraph` or `graph` is used as keyword /// for the graph. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum Kind { Digraph, Graph, } impl Kind { /// The edgeop syntax to use for this graph kind. pub(crate) fn edgeop(&self) -> &'static str { match *self { Self::Digraph => "->", Self::Graph => "--", } } } impl std::fmt::Display for Kind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let s = match *self { Self::Digraph => "digraph", Self::Graph => "graph", }; write!(f, "{s}") } }
22.724138
72
0.506829
29c624575c3c2328af0f0f0997bbcbe156bc1190
61,369
//! A classic liveness analysis based on dataflow over the AST. Computes, //! for each local variable in a function, whether that variable is live //! at a given point. Program execution points are identified by their //! IDs. //! //! # Basic idea //! //! The basic model is that each local variable is assigned an index. We //! represent sets of local variables using a vector indexed by this //! index. The value in the vector is either 0, indicating the variable //! is dead, or the ID of an expression that uses the variable. //! //! We conceptually walk over the AST in reverse execution order. If we //! find a use of a variable, we add it to the set of live variables. If //! we find an assignment to a variable, we remove it from the set of live //! variables. When we have to merge two flows, we take the union of //! those two flows -- if the variable is live on both paths, we simply //! pick one ID. In the event of loops, we continue doing this until a //! fixed point is reached. //! //! ## Checking initialization //! //! At the function entry point, all variables must be dead. If this is //! not the case, we can report an error using the ID found in the set of //! live variables, which identifies a use of the variable which is not //! dominated by an assignment. //! //! ## Checking moves //! //! After each explicit move, the variable must be dead. //! //! ## Computing last uses //! //! Any use of the variable where the variable is dead afterwards is a //! last use. //! //! # Implementation details //! //! The actual implementation contains two (nested) walks over the AST. //! The outer walk has the job of building up the ir_maps instance for the //! enclosing function. On the way down the tree, it identifies those AST //! nodes and variable IDs that will be needed for the liveness analysis //! and assigns them contiguous IDs. The liveness ID for an AST node is //! called a `live_node` (it's a newtype'd `u32`) and the ID for a variable //! is called a `variable` (another newtype'd `u32`). //! //! On the way back up the tree, as we are about to exit from a function //! declaration we allocate a `liveness` instance. Now that we know //! precisely how many nodes and variables we need, we can allocate all //! the various arrays that we will need to precisely the right size. We then //! perform the actual propagation on the `liveness` instance. //! //! This propagation is encoded in the various `propagate_through_*()` //! methods. It effectively does a reverse walk of the AST; whenever we //! reach a loop node, we iterate until a fixed point is reached. //! //! ## The `RWU` struct //! //! At each live node `N`, we track three pieces of information for each //! variable `V` (these are encapsulated in the `RWU` struct): //! //! - `reader`: the `LiveNode` ID of some node which will read the value //! that `V` holds on entry to `N`. Formally: a node `M` such //! that there exists a path `P` from `N` to `M` where `P` does not //! write `V`. If the `reader` is `invalid_node()`, then the current //! value will never be read (the variable is dead, essentially). //! //! - `writer`: the `LiveNode` ID of some node which will write the //! variable `V` and which is reachable from `N`. Formally: a node `M` //! such that there exists a path `P` from `N` to `M` and `M` writes //! `V`. If the `writer` is `invalid_node()`, then there is no writer //! of `V` that follows `N`. //! //! - `used`: a boolean value indicating whether `V` is *used*. We //! distinguish a *read* from a *use* in that a *use* is some read that //! is not just used to generate a new value. For example, `x += 1` is //! a read but not a use. This is used to generate better warnings. //! //! ## Special Variables //! //! We generate various special variables for various, well, special purposes. //! These are described in the `specials` struct: //! //! - `exit_ln`: a live node that is generated to represent every 'exit' from //! the function, whether it be by explicit return, panic, or other means. //! //! - `fallthrough_ln`: a live node that represents a fallthrough //! //! - `clean_exit_var`: a synthetic variable that is only 'read' from the //! fallthrough node. It is only live if the function could converge //! via means other than an explicit `return` expression. That is, it is //! only dead if the end of the function's block can never be reached. //! It is the responsibility of typeck to ensure that there are no //! `return` expressions in a function declared as diverging. use self::LoopKind::*; use self::LiveNodeKind::*; use self::VarKind::*; use crate::hir::def::*; use crate::hir::Node; use crate::ty::{self, TyCtxt}; use crate::ty::query::Providers; use crate::lint; use crate::util::nodemap::{HirIdMap, HirIdSet}; use errors::Applicability; use std::collections::{BTreeMap, VecDeque}; use std::{fmt, u32}; use std::io::prelude::*; use std::io; use std::rc::Rc; use syntax::ast::{self, NodeId}; use syntax::ptr::P; use syntax::symbol::{kw, sym}; use syntax_pos::Span; use crate::hir; use crate::hir::{Expr, HirId}; use crate::hir::def_id::DefId; use crate::hir::intravisit::{self, Visitor, FnKind, NestedVisitorMap}; /// For use with `propagate_through_loop`. enum LoopKind<'a> { /// An endless `loop` loop. LoopLoop, /// A `while` loop, with the given expression as condition. WhileLoop(&'a Expr), } #[derive(Copy, Clone, PartialEq)] struct Variable(u32); #[derive(Copy, Clone, PartialEq)] struct LiveNode(u32); impl Variable { fn get(&self) -> usize { self.0 as usize } } impl LiveNode { fn get(&self) -> usize { self.0 as usize } } #[derive(Copy, Clone, PartialEq, Debug)] enum LiveNodeKind { UpvarNode(Span), ExprNode(Span), VarDefNode(Span), ExitNode } fn live_node_kind_to_string(lnk: LiveNodeKind, tcx: TyCtxt<'_>) -> String { let cm = tcx.sess.source_map(); match lnk { UpvarNode(s) => { format!("Upvar node [{}]", cm.span_to_string(s)) } ExprNode(s) => { format!("Expr node [{}]", cm.span_to_string(s)) } VarDefNode(s) => { format!("Var def node [{}]", cm.span_to_string(s)) } ExitNode => "Exit node".to_owned(), } } impl<'tcx> Visitor<'tcx> for IrMaps<'tcx> { fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> { NestedVisitorMap::OnlyBodies(&self.tcx.hir()) } fn visit_fn(&mut self, fk: FnKind<'tcx>, fd: &'tcx hir::FnDecl, b: hir::BodyId, s: Span, id: HirId) { visit_fn(self, fk, fd, b, s, id); } fn visit_local(&mut self, l: &'tcx hir::Local) { visit_local(self, l); } fn visit_expr(&mut self, ex: &'tcx Expr) { visit_expr(self, ex); } fn visit_arm(&mut self, a: &'tcx hir::Arm) { visit_arm(self, a); } } fn check_mod_liveness<'tcx>(tcx: TyCtxt<'tcx>, module_def_id: DefId) { tcx.hir().visit_item_likes_in_module( module_def_id, &mut IrMaps::new(tcx, module_def_id).as_deep_visitor(), ); } pub fn provide(providers: &mut Providers<'_>) { *providers = Providers { check_mod_liveness, ..*providers }; } impl fmt::Debug for LiveNode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "ln({})", self.get()) } } impl fmt::Debug for Variable { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "v({})", self.get()) } } // ______________________________________________________________________ // Creating ir_maps // // This is the first pass and the one that drives the main // computation. It walks up and down the IR once. On the way down, // we count for each function the number of variables as well as // liveness nodes. A liveness node is basically an expression or // capture clause that does something of interest: either it has // interesting control flow or it uses/defines a local variable. // // On the way back up, at each function node we create liveness sets // (we now know precisely how big to make our various vectors and so // forth) and then do the data-flow propagation to compute the set // of live variables at each program point. // // Finally, we run back over the IR one last time and, using the // computed liveness, check various safety conditions. For example, // there must be no live nodes at the definition site for a variable // unless it has an initializer. Similarly, each non-mutable local // variable must not be assigned if there is some successor // assignment. And so forth. impl LiveNode { fn is_valid(&self) -> bool { self.0 != u32::MAX } } fn invalid_node() -> LiveNode { LiveNode(u32::MAX) } struct CaptureInfo { ln: LiveNode, var_hid: HirId } #[derive(Copy, Clone, Debug)] struct LocalInfo { id: HirId, name: ast::Name, is_shorthand: bool, } #[derive(Copy, Clone, Debug)] enum VarKind { Arg(HirId, ast::Name), Local(LocalInfo), CleanExit } struct IrMaps<'tcx> { tcx: TyCtxt<'tcx>, body_owner: DefId, num_live_nodes: usize, num_vars: usize, live_node_map: HirIdMap<LiveNode>, variable_map: HirIdMap<Variable>, capture_info_map: HirIdMap<Rc<Vec<CaptureInfo>>>, var_kinds: Vec<VarKind>, lnks: Vec<LiveNodeKind>, } impl IrMaps<'tcx> { fn new(tcx: TyCtxt<'tcx>, body_owner: DefId) -> IrMaps<'tcx> { IrMaps { tcx, body_owner, num_live_nodes: 0, num_vars: 0, live_node_map: HirIdMap::default(), variable_map: HirIdMap::default(), capture_info_map: Default::default(), var_kinds: Vec::new(), lnks: Vec::new(), } } fn add_live_node(&mut self, lnk: LiveNodeKind) -> LiveNode { let ln = LiveNode(self.num_live_nodes as u32); self.lnks.push(lnk); self.num_live_nodes += 1; debug!("{:?} is of kind {}", ln, live_node_kind_to_string(lnk, self.tcx)); ln } fn add_live_node_for_node(&mut self, hir_id: HirId, lnk: LiveNodeKind) { let ln = self.add_live_node(lnk); self.live_node_map.insert(hir_id, ln); debug!("{:?} is node {:?}", ln, hir_id); } fn add_variable(&mut self, vk: VarKind) -> Variable { let v = Variable(self.num_vars as u32); self.var_kinds.push(vk); self.num_vars += 1; match vk { Local(LocalInfo { id: node_id, .. }) | Arg(node_id, _) => { self.variable_map.insert(node_id, v); }, CleanExit => {} } debug!("{:?} is {:?}", v, vk); v } fn variable(&self, hir_id: HirId, span: Span) -> Variable { match self.variable_map.get(&hir_id) { Some(&var) => var, None => { span_bug!(span, "no variable registered for id {:?}", hir_id); } } } fn variable_name(&self, var: Variable) -> String { match self.var_kinds[var.get()] { Local(LocalInfo { name, .. }) | Arg(_, name) => { name.to_string() }, CleanExit => "<clean-exit>".to_owned() } } fn variable_is_shorthand(&self, var: Variable) -> bool { match self.var_kinds[var.get()] { Local(LocalInfo { is_shorthand, .. }) => is_shorthand, Arg(..) | CleanExit => false } } fn set_captures(&mut self, hir_id: HirId, cs: Vec<CaptureInfo>) { self.capture_info_map.insert(hir_id, Rc::new(cs)); } fn lnk(&self, ln: LiveNode) -> LiveNodeKind { self.lnks[ln.get()] } } fn visit_fn<'a, 'tcx: 'a>( ir: &mut IrMaps<'tcx>, fk: FnKind<'tcx>, decl: &'tcx hir::FnDecl, body_id: hir::BodyId, sp: Span, id: hir::HirId, ) { debug!("visit_fn"); // swap in a new set of IR maps for this function body: let def_id = ir.tcx.hir().local_def_id_from_hir_id(id); let mut fn_maps = IrMaps::new(ir.tcx, def_id); // Don't run unused pass for #[derive()] if let FnKind::Method(..) = fk { let parent = ir.tcx.hir().get_parent_item(id); if let Some(Node::Item(i)) = ir.tcx.hir().find_by_hir_id(parent) { if i.attrs.iter().any(|a| a.check_name(sym::automatically_derived)) { return; } } } debug!("creating fn_maps: {:p}", &fn_maps); let body = ir.tcx.hir().body(body_id); for arg in &body.arguments { let is_shorthand = match arg.pat.node { crate::hir::PatKind::Struct(..) => true, _ => false, }; arg.pat.each_binding(|_bm, hir_id, _x, ident| { debug!("adding argument {:?}", hir_id); let var = if is_shorthand { Local(LocalInfo { id: hir_id, name: ident.name, is_shorthand: true, }) } else { Arg(hir_id, ident.name) }; fn_maps.add_variable(var); }) }; // gather up the various local variables, significant expressions, // and so forth: intravisit::walk_fn(&mut fn_maps, fk, decl, body_id, sp, id); // compute liveness let mut lsets = Liveness::new(&mut fn_maps, body_id); let entry_ln = lsets.compute(&body.value); // check for various error conditions lsets.visit_body(body); lsets.warn_about_unused_args(body, entry_ln); } fn add_from_pat<'tcx>(ir: &mut IrMaps<'tcx>, pat: &P<hir::Pat>) { // For struct patterns, take note of which fields used shorthand // (`x` rather than `x: x`). let mut shorthand_field_ids = HirIdSet::default(); let mut pats = VecDeque::new(); pats.push_back(pat); while let Some(pat) = pats.pop_front() { use crate::hir::PatKind::*; match pat.node { Binding(_, _, _, ref inner_pat) => { pats.extend(inner_pat.iter()); } Struct(_, ref fields, _) => { for field in fields { if field.node.is_shorthand { shorthand_field_ids.insert(field.node.pat.hir_id); } } } Ref(ref inner_pat, _) | Box(ref inner_pat) => { pats.push_back(inner_pat); } TupleStruct(_, ref inner_pats, _) | Tuple(ref inner_pats, _) => { pats.extend(inner_pats.iter()); } Slice(ref pre_pats, ref inner_pat, ref post_pats) => { pats.extend(pre_pats.iter()); pats.extend(inner_pat.iter()); pats.extend(post_pats.iter()); } _ => {} } } pat.each_binding(|_bm, hir_id, _sp, ident| { ir.add_live_node_for_node(hir_id, VarDefNode(ident.span)); ir.add_variable(Local(LocalInfo { id: hir_id, name: ident.name, is_shorthand: shorthand_field_ids.contains(&hir_id) })); }); } fn visit_local<'tcx>(ir: &mut IrMaps<'tcx>, local: &'tcx hir::Local) { add_from_pat(ir, &local.pat); intravisit::walk_local(ir, local); } fn visit_arm<'tcx>(ir: &mut IrMaps<'tcx>, arm: &'tcx hir::Arm) { for pat in &arm.pats { add_from_pat(ir, pat); } intravisit::walk_arm(ir, arm); } fn visit_expr<'tcx>(ir: &mut IrMaps<'tcx>, expr: &'tcx Expr) { match expr.node { // live nodes required for uses or definitions of variables: hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => { debug!("expr {}: path that leads to {:?}", expr.hir_id, path.res); if let Res::Local(var_hir_id) = path.res { let upvars = ir.tcx.upvars(ir.body_owner); if !upvars.map_or(false, |upvars| upvars.contains_key(&var_hir_id)) { ir.add_live_node_for_node(expr.hir_id, ExprNode(expr.span)); } } intravisit::walk_expr(ir, expr); } hir::ExprKind::Closure(..) => { // Interesting control flow (for loops can contain labeled // breaks or continues) ir.add_live_node_for_node(expr.hir_id, ExprNode(expr.span)); // Make a live_node for each captured variable, with the span // being the location that the variable is used. This results // in better error messages than just pointing at the closure // construction site. let mut call_caps = Vec::new(); let closure_def_id = ir.tcx.hir().local_def_id_from_hir_id(expr.hir_id); if let Some(upvars) = ir.tcx.upvars(closure_def_id) { let parent_upvars = ir.tcx.upvars(ir.body_owner); call_caps.extend(upvars.iter().filter_map(|(&var_id, upvar)| { let has_parent = parent_upvars .map_or(false, |upvars| upvars.contains_key(&var_id)); if !has_parent { let upvar_ln = ir.add_live_node(UpvarNode(upvar.span)); Some(CaptureInfo { ln: upvar_ln, var_hid: var_id }) } else { None } })); } ir.set_captures(expr.hir_id, call_caps); let old_body_owner = ir.body_owner; ir.body_owner = closure_def_id; intravisit::walk_expr(ir, expr); ir.body_owner = old_body_owner; } // live nodes required for interesting control flow: hir::ExprKind::Match(..) | hir::ExprKind::While(..) | hir::ExprKind::Loop(..) => { ir.add_live_node_for_node(expr.hir_id, ExprNode(expr.span)); intravisit::walk_expr(ir, expr); } hir::ExprKind::Binary(op, ..) if op.node.is_lazy() => { ir.add_live_node_for_node(expr.hir_id, ExprNode(expr.span)); intravisit::walk_expr(ir, expr); } // otherwise, live nodes are not required: hir::ExprKind::Index(..) | hir::ExprKind::Field(..) | hir::ExprKind::Array(..) | hir::ExprKind::Call(..) | hir::ExprKind::MethodCall(..) | hir::ExprKind::Tup(..) | hir::ExprKind::Binary(..) | hir::ExprKind::AddrOf(..) | hir::ExprKind::Cast(..) | hir::ExprKind::DropTemps(..) | hir::ExprKind::Unary(..) | hir::ExprKind::Break(..) | hir::ExprKind::Continue(_) | hir::ExprKind::Lit(_) | hir::ExprKind::Ret(..) | hir::ExprKind::Block(..) | hir::ExprKind::Assign(..) | hir::ExprKind::AssignOp(..) | hir::ExprKind::Struct(..) | hir::ExprKind::Repeat(..) | hir::ExprKind::InlineAsm(..) | hir::ExprKind::Box(..) | hir::ExprKind::Yield(..) | hir::ExprKind::Type(..) | hir::ExprKind::Err | hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => { intravisit::walk_expr(ir, expr); } } } // ______________________________________________________________________ // Computing liveness sets // // Actually we compute just a bit more than just liveness, but we use // the same basic propagation framework in all cases. #[derive(Clone, Copy)] struct RWU { reader: LiveNode, writer: LiveNode, used: bool } /// Conceptually, this is like a `Vec<RWU>`. But the number of `RWU`s can get /// very large, so it uses a more compact representation that takes advantage /// of the fact that when the number of `RWU`s is large, most of them have an /// invalid reader and an invalid writer. struct RWUTable { /// Each entry in `packed_rwus` is either INV_INV_FALSE, INV_INV_TRUE, or /// an index into `unpacked_rwus`. In the common cases, this compacts the /// 65 bits of data into 32; in the uncommon cases, it expands the 65 bits /// in 96. /// /// More compact representations are possible -- e.g., use only 2 bits per /// packed `RWU` and make the secondary table a HashMap that maps from /// indices to `RWU`s -- but this one strikes a good balance between size /// and speed. packed_rwus: Vec<u32>, unpacked_rwus: Vec<RWU>, } // A constant representing `RWU { reader: invalid_node(); writer: invalid_node(); used: false }`. const INV_INV_FALSE: u32 = u32::MAX; // A constant representing `RWU { reader: invalid_node(); writer: invalid_node(); used: true }`. const INV_INV_TRUE: u32 = u32::MAX - 1; impl RWUTable { fn new(num_rwus: usize) -> RWUTable { Self { packed_rwus: vec![INV_INV_FALSE; num_rwus], unpacked_rwus: vec![], } } fn get(&self, idx: usize) -> RWU { let packed_rwu = self.packed_rwus[idx]; match packed_rwu { INV_INV_FALSE => RWU { reader: invalid_node(), writer: invalid_node(), used: false }, INV_INV_TRUE => RWU { reader: invalid_node(), writer: invalid_node(), used: true }, _ => self.unpacked_rwus[packed_rwu as usize], } } fn get_reader(&self, idx: usize) -> LiveNode { let packed_rwu = self.packed_rwus[idx]; match packed_rwu { INV_INV_FALSE | INV_INV_TRUE => invalid_node(), _ => self.unpacked_rwus[packed_rwu as usize].reader, } } fn get_writer(&self, idx: usize) -> LiveNode { let packed_rwu = self.packed_rwus[idx]; match packed_rwu { INV_INV_FALSE | INV_INV_TRUE => invalid_node(), _ => self.unpacked_rwus[packed_rwu as usize].writer, } } fn get_used(&self, idx: usize) -> bool { let packed_rwu = self.packed_rwus[idx]; match packed_rwu { INV_INV_FALSE => false, INV_INV_TRUE => true, _ => self.unpacked_rwus[packed_rwu as usize].used, } } #[inline] fn copy_packed(&mut self, dst_idx: usize, src_idx: usize) { self.packed_rwus[dst_idx] = self.packed_rwus[src_idx]; } fn assign_unpacked(&mut self, idx: usize, rwu: RWU) { if rwu.reader == invalid_node() && rwu.writer == invalid_node() { // When we overwrite an indexing entry in `self.packed_rwus` with // `INV_INV_{TRUE,FALSE}` we don't remove the corresponding entry // from `self.unpacked_rwus`; it's not worth the effort, and we // can't have entries shifting around anyway. self.packed_rwus[idx] = if rwu.used { INV_INV_TRUE } else { INV_INV_FALSE } } else { // Add a new RWU to `unpacked_rwus` and make `packed_rwus[idx]` // point to it. self.packed_rwus[idx] = self.unpacked_rwus.len() as u32; self.unpacked_rwus.push(rwu); } } fn assign_inv_inv(&mut self, idx: usize) { self.packed_rwus[idx] = if self.get_used(idx) { INV_INV_TRUE } else { INV_INV_FALSE }; } } #[derive(Copy, Clone)] struct Specials { exit_ln: LiveNode, fallthrough_ln: LiveNode, clean_exit_var: Variable } const ACC_READ: u32 = 1; const ACC_WRITE: u32 = 2; const ACC_USE: u32 = 4; struct Liveness<'a, 'tcx: 'a> { ir: &'a mut IrMaps<'tcx>, tables: &'a ty::TypeckTables<'tcx>, s: Specials, successors: Vec<LiveNode>, rwu_table: RWUTable, // mappings from loop node ID to LiveNode // ("break" label should map to loop node ID, // it probably doesn't now) break_ln: HirIdMap<LiveNode>, cont_ln: HirIdMap<LiveNode>, } impl<'a, 'tcx> Liveness<'a, 'tcx> { fn new(ir: &'a mut IrMaps<'tcx>, body: hir::BodyId) -> Liveness<'a, 'tcx> { // Special nodes and variables: // - exit_ln represents the end of the fn, either by return or panic // - implicit_ret_var is a pseudo-variable that represents // an implicit return let specials = Specials { exit_ln: ir.add_live_node(ExitNode), fallthrough_ln: ir.add_live_node(ExitNode), clean_exit_var: ir.add_variable(CleanExit) }; let tables = ir.tcx.body_tables(body); let num_live_nodes = ir.num_live_nodes; let num_vars = ir.num_vars; Liveness { ir, tables, s: specials, successors: vec![invalid_node(); num_live_nodes], rwu_table: RWUTable::new(num_live_nodes * num_vars), break_ln: Default::default(), cont_ln: Default::default(), } } fn live_node(&self, hir_id: HirId, span: Span) -> LiveNode { match self.ir.live_node_map.get(&hir_id) { Some(&ln) => ln, None => { // This must be a mismatch between the ir_map construction // above and the propagation code below; the two sets of // code have to agree about which AST nodes are worth // creating liveness nodes for. span_bug!( span, "no live node registered for node {:?}", hir_id); } } } fn variable(&self, hir_id: HirId, span: Span) -> Variable { self.ir.variable(hir_id, span) } fn pat_bindings<F>(&mut self, pat: &hir::Pat, mut f: F) where F: FnMut(&mut Liveness<'a, 'tcx>, LiveNode, Variable, Span, HirId), { pat.each_binding(|_bm, hir_id, sp, n| { let ln = self.live_node(hir_id, sp); let var = self.variable(hir_id, n.span); f(self, ln, var, n.span, hir_id); }) } fn arm_pats_bindings<F>(&mut self, pat: Option<&hir::Pat>, f: F) where F: FnMut(&mut Liveness<'a, 'tcx>, LiveNode, Variable, Span, HirId), { if let Some(pat) = pat { self.pat_bindings(pat, f); } } fn define_bindings_in_pat(&mut self, pat: &hir::Pat, succ: LiveNode) -> LiveNode { self.define_bindings_in_arm_pats(Some(pat), succ) } fn define_bindings_in_arm_pats(&mut self, pat: Option<&hir::Pat>, succ: LiveNode) -> LiveNode { let mut succ = succ; self.arm_pats_bindings(pat, |this, ln, var, _sp, _id| { this.init_from_succ(ln, succ); this.define(ln, var); succ = ln; }); succ } fn idx(&self, ln: LiveNode, var: Variable) -> usize { ln.get() * self.ir.num_vars + var.get() } fn live_on_entry(&self, ln: LiveNode, var: Variable) -> Option<LiveNodeKind> { assert!(ln.is_valid()); let reader = self.rwu_table.get_reader(self.idx(ln, var)); if reader.is_valid() { Some(self.ir.lnk(reader)) } else { None } } // Is this variable live on entry to any of its successor nodes? fn live_on_exit(&self, ln: LiveNode, var: Variable) -> Option<LiveNodeKind> { let successor = self.successors[ln.get()]; self.live_on_entry(successor, var) } fn used_on_entry(&self, ln: LiveNode, var: Variable) -> bool { assert!(ln.is_valid()); self.rwu_table.get_used(self.idx(ln, var)) } fn assigned_on_entry(&self, ln: LiveNode, var: Variable) -> Option<LiveNodeKind> { assert!(ln.is_valid()); let writer = self.rwu_table.get_writer(self.idx(ln, var)); if writer.is_valid() { Some(self.ir.lnk(writer)) } else { None } } fn assigned_on_exit(&self, ln: LiveNode, var: Variable) -> Option<LiveNodeKind> { let successor = self.successors[ln.get()]; self.assigned_on_entry(successor, var) } fn indices2<F>(&mut self, ln: LiveNode, succ_ln: LiveNode, mut op: F) where F: FnMut(&mut Liveness<'a, 'tcx>, usize, usize), { let node_base_idx = self.idx(ln, Variable(0)); let succ_base_idx = self.idx(succ_ln, Variable(0)); for var_idx in 0..self.ir.num_vars { op(self, node_base_idx + var_idx, succ_base_idx + var_idx); } } fn write_vars<F>(&self, wr: &mut dyn Write, ln: LiveNode, mut test: F) -> io::Result<()> where F: FnMut(usize) -> LiveNode, { let node_base_idx = self.idx(ln, Variable(0)); for var_idx in 0..self.ir.num_vars { let idx = node_base_idx + var_idx; if test(idx).is_valid() { write!(wr, " {:?}", Variable(var_idx as u32))?; } } Ok(()) } #[allow(unused_must_use)] fn ln_str(&self, ln: LiveNode) -> String { let mut wr = Vec::new(); { let wr = &mut wr as &mut dyn Write; write!(wr, "[ln({:?}) of kind {:?} reads", ln.get(), self.ir.lnk(ln)); self.write_vars(wr, ln, |idx| self.rwu_table.get_reader(idx)); write!(wr, " writes"); self.write_vars(wr, ln, |idx| self.rwu_table.get_writer(idx)); write!(wr, " precedes {:?}]", self.successors[ln.get()]); } String::from_utf8(wr).unwrap() } fn init_empty(&mut self, ln: LiveNode, succ_ln: LiveNode) { self.successors[ln.get()] = succ_ln; // It is not necessary to initialize the RWUs here because they are all // set to INV_INV_FALSE when they are created, and the sets only grow // during iterations. } fn init_from_succ(&mut self, ln: LiveNode, succ_ln: LiveNode) { // more efficient version of init_empty() / merge_from_succ() self.successors[ln.get()] = succ_ln; self.indices2(ln, succ_ln, |this, idx, succ_idx| { this.rwu_table.copy_packed(idx, succ_idx); }); debug!("init_from_succ(ln={}, succ={})", self.ln_str(ln), self.ln_str(succ_ln)); } fn merge_from_succ(&mut self, ln: LiveNode, succ_ln: LiveNode, first_merge: bool) -> bool { if ln == succ_ln { return false; } let mut changed = false; self.indices2(ln, succ_ln, |this, idx, succ_idx| { let mut rwu = this.rwu_table.get(idx); let succ_rwu = this.rwu_table.get(succ_idx); if succ_rwu.reader.is_valid() && !rwu.reader.is_valid() { rwu.reader = succ_rwu.reader; changed = true } if succ_rwu.writer.is_valid() && !rwu.writer.is_valid() { rwu.writer = succ_rwu.writer; changed = true } if succ_rwu.used && !rwu.used { rwu.used = true; changed = true; } if changed { this.rwu_table.assign_unpacked(idx, rwu); } }); debug!("merge_from_succ(ln={:?}, succ={}, first_merge={}, changed={})", ln, self.ln_str(succ_ln), first_merge, changed); return changed; } // Indicates that a local variable was *defined*; we know that no // uses of the variable can precede the definition (resolve checks // this) so we just clear out all the data. fn define(&mut self, writer: LiveNode, var: Variable) { let idx = self.idx(writer, var); self.rwu_table.assign_inv_inv(idx); debug!("{:?} defines {:?} (idx={}): {}", writer, var, idx, self.ln_str(writer)); } // Either read, write, or both depending on the acc bitset fn acc(&mut self, ln: LiveNode, var: Variable, acc: u32) { debug!("{:?} accesses[{:x}] {:?}: {}", ln, acc, var, self.ln_str(ln)); let idx = self.idx(ln, var); let mut rwu = self.rwu_table.get(idx); if (acc & ACC_WRITE) != 0 { rwu.reader = invalid_node(); rwu.writer = ln; } // Important: if we both read/write, must do read second // or else the write will override. if (acc & ACC_READ) != 0 { rwu.reader = ln; } if (acc & ACC_USE) != 0 { rwu.used = true; } self.rwu_table.assign_unpacked(idx, rwu); } fn compute(&mut self, body: &hir::Expr) -> LiveNode { debug!("compute: using id for body, {}", self.ir.tcx.hir().hir_to_pretty_string(body.hir_id)); // the fallthrough exit is only for those cases where we do not // explicitly return: let s = self.s; self.init_from_succ(s.fallthrough_ln, s.exit_ln); self.acc(s.fallthrough_ln, s.clean_exit_var, ACC_READ); let entry_ln = self.propagate_through_expr(body, s.fallthrough_ln); // hack to skip the loop unless debug! is enabled: debug!("^^ liveness computation results for body {} (entry={:?})", { for ln_idx in 0..self.ir.num_live_nodes { debug!("{:?}", self.ln_str(LiveNode(ln_idx as u32))); } body.hir_id }, entry_ln); entry_ln } fn propagate_through_block(&mut self, blk: &hir::Block, succ: LiveNode) -> LiveNode { if blk.targeted_by_break { self.break_ln.insert(blk.hir_id, succ); } let succ = self.propagate_through_opt_expr(blk.expr.as_ref().map(|e| &**e), succ); blk.stmts.iter().rev().fold(succ, |succ, stmt| { self.propagate_through_stmt(stmt, succ) }) } fn propagate_through_stmt(&mut self, stmt: &hir::Stmt, succ: LiveNode) -> LiveNode { match stmt.node { hir::StmtKind::Local(ref local) => { // Note: we mark the variable as defined regardless of whether // there is an initializer. Initially I had thought to only mark // the live variable as defined if it was initialized, and then we // could check for uninit variables just by scanning what is live // at the start of the function. But that doesn't work so well for // immutable variables defined in a loop: // loop { let x; x = 5; } // because the "assignment" loops back around and generates an error. // // So now we just check that variables defined w/o an // initializer are not live at the point of their // initialization, which is mildly more complex than checking // once at the func header but otherwise equivalent. let succ = self.propagate_through_opt_expr(local.init.as_ref().map(|e| &**e), succ); self.define_bindings_in_pat(&local.pat, succ) } hir::StmtKind::Item(..) => succ, hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => { self.propagate_through_expr(&expr, succ) } } } fn propagate_through_exprs(&mut self, exprs: &[Expr], succ: LiveNode) -> LiveNode { exprs.iter().rev().fold(succ, |succ, expr| { self.propagate_through_expr(&expr, succ) }) } fn propagate_through_opt_expr(&mut self, opt_expr: Option<&Expr>, succ: LiveNode) -> LiveNode { opt_expr.map_or(succ, |expr| self.propagate_through_expr(expr, succ)) } fn propagate_through_expr(&mut self, expr: &Expr, succ: LiveNode) -> LiveNode { debug!("propagate_through_expr: {}", self.ir.tcx.hir().hir_to_pretty_string(expr.hir_id)); match expr.node { // Interesting cases with control flow or which gen/kill hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => { self.access_path(expr.hir_id, path, succ, ACC_READ | ACC_USE) } hir::ExprKind::Field(ref e, _) => { self.propagate_through_expr(&e, succ) } hir::ExprKind::Closure(..) => { debug!("{} is an ExprKind::Closure", self.ir.tcx.hir().hir_to_pretty_string(expr.hir_id)); // the construction of a closure itself is not important, // but we have to consider the closed over variables. let caps = self.ir.capture_info_map.get(&expr.hir_id).cloned().unwrap_or_else(|| span_bug!(expr.span, "no registered caps")); caps.iter().rev().fold(succ, |succ, cap| { self.init_from_succ(cap.ln, succ); let var = self.variable(cap.var_hid, expr.span); self.acc(cap.ln, var, ACC_READ | ACC_USE); cap.ln }) } hir::ExprKind::While(ref cond, ref blk, _) => { self.propagate_through_loop(expr, WhileLoop(&cond), &blk, succ) } // Note that labels have been resolved, so we don't need to look // at the label ident hir::ExprKind::Loop(ref blk, _, _) => { self.propagate_through_loop(expr, LoopLoop, &blk, succ) } hir::ExprKind::Match(ref e, ref arms, _) => { // // (e) // | // v // (expr) // / | \ // | | | // v v v // (..arms..) // | | | // v v v // ( succ ) // // let ln = self.live_node(expr.hir_id, expr.span); self.init_empty(ln, succ); let mut first_merge = true; for arm in arms { let body_succ = self.propagate_through_expr(&arm.body, succ); let guard_succ = self.propagate_through_opt_expr( arm.guard.as_ref().map(|hir::Guard::If(e)| &**e), body_succ ); // only consider the first pattern; any later patterns must have // the same bindings, and we also consider the first pattern to be // the "authoritative" set of ids let arm_succ = self.define_bindings_in_arm_pats(arm.pats.first().map(|p| &**p), guard_succ); self.merge_from_succ(ln, arm_succ, first_merge); first_merge = false; }; self.propagate_through_expr(&e, ln) } hir::ExprKind::Ret(ref o_e) => { // ignore succ and subst exit_ln: let exit_ln = self.s.exit_ln; self.propagate_through_opt_expr(o_e.as_ref().map(|e| &**e), exit_ln) } hir::ExprKind::Break(label, ref opt_expr) => { // Find which label this break jumps to let target = match label.target_id { Ok(hir_id) => self.break_ln.get(&hir_id), Err(err) => span_bug!(expr.span, "loop scope error: {}", err), }.cloned(); // Now that we know the label we're going to, // look it up in the break loop nodes table match target { Some(b) => self.propagate_through_opt_expr(opt_expr.as_ref().map(|e| &**e), b), None => span_bug!(expr.span, "break to unknown label") } } hir::ExprKind::Continue(label) => { // Find which label this expr continues to let sc = label.target_id.unwrap_or_else(|err| span_bug!(expr.span, "loop scope error: {}", err)); // Now that we know the label we're going to, // look it up in the continue loop nodes table self.cont_ln.get(&sc).cloned().unwrap_or_else(|| span_bug!(expr.span, "continue to unknown label")) } hir::ExprKind::Assign(ref l, ref r) => { // see comment on places in // propagate_through_place_components() let succ = self.write_place(&l, succ, ACC_WRITE); let succ = self.propagate_through_place_components(&l, succ); self.propagate_through_expr(&r, succ) } hir::ExprKind::AssignOp(_, ref l, ref r) => { // an overloaded assign op is like a method call if self.tables.is_method_call(expr) { let succ = self.propagate_through_expr(&l, succ); self.propagate_through_expr(&r, succ) } else { // see comment on places in // propagate_through_place_components() let succ = self.write_place(&l, succ, ACC_WRITE|ACC_READ); let succ = self.propagate_through_expr(&r, succ); self.propagate_through_place_components(&l, succ) } } // Uninteresting cases: just propagate in rev exec order hir::ExprKind::Array(ref exprs) => { self.propagate_through_exprs(exprs, succ) } hir::ExprKind::Struct(_, ref fields, ref with_expr) => { let succ = self.propagate_through_opt_expr(with_expr.as_ref().map(|e| &**e), succ); fields.iter().rev().fold(succ, |succ, field| { self.propagate_through_expr(&field.expr, succ) }) } hir::ExprKind::Call(ref f, ref args) => { let m = self.ir.tcx.hir().get_module_parent_by_hir_id(expr.hir_id); let succ = if self.ir.tcx.is_ty_uninhabited_from(m, self.tables.expr_ty(expr)) { self.s.exit_ln } else { succ }; let succ = self.propagate_through_exprs(args, succ); self.propagate_through_expr(&f, succ) } hir::ExprKind::MethodCall(.., ref args) => { let m = self.ir.tcx.hir().get_module_parent_by_hir_id(expr.hir_id); let succ = if self.ir.tcx.is_ty_uninhabited_from(m, self.tables.expr_ty(expr)) { self.s.exit_ln } else { succ }; self.propagate_through_exprs(args, succ) } hir::ExprKind::Tup(ref exprs) => { self.propagate_through_exprs(exprs, succ) } hir::ExprKind::Binary(op, ref l, ref r) if op.node.is_lazy() => { let r_succ = self.propagate_through_expr(&r, succ); let ln = self.live_node(expr.hir_id, expr.span); self.init_from_succ(ln, succ); self.merge_from_succ(ln, r_succ, false); self.propagate_through_expr(&l, ln) } hir::ExprKind::Index(ref l, ref r) | hir::ExprKind::Binary(_, ref l, ref r) => { let r_succ = self.propagate_through_expr(&r, succ); self.propagate_through_expr(&l, r_succ) } hir::ExprKind::Box(ref e) | hir::ExprKind::AddrOf(_, ref e) | hir::ExprKind::Cast(ref e, _) | hir::ExprKind::Type(ref e, _) | hir::ExprKind::DropTemps(ref e) | hir::ExprKind::Unary(_, ref e) | hir::ExprKind::Yield(ref e) | hir::ExprKind::Repeat(ref e, _) => { self.propagate_through_expr(&e, succ) } hir::ExprKind::InlineAsm(ref ia, ref outputs, ref inputs) => { let succ = ia.outputs.iter().zip(outputs).rev().fold(succ, |succ, (o, output)| { // see comment on places // in propagate_through_place_components() if o.is_indirect { self.propagate_through_expr(output, succ) } else { let acc = if o.is_rw { ACC_WRITE|ACC_READ } else { ACC_WRITE }; let succ = self.write_place(output, succ, acc); self.propagate_through_place_components(output, succ) }}); // Inputs are executed first. Propagate last because of rev order self.propagate_through_exprs(inputs, succ) } hir::ExprKind::Lit(..) | hir::ExprKind::Err | hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => { succ } // Note that labels have been resolved, so we don't need to look // at the label ident hir::ExprKind::Block(ref blk, _) => { self.propagate_through_block(&blk, succ) } } } fn propagate_through_place_components(&mut self, expr: &Expr, succ: LiveNode) -> LiveNode { // # Places // // In general, the full flow graph structure for an // assignment/move/etc can be handled in one of two ways, // depending on whether what is being assigned is a "tracked // value" or not. A tracked value is basically a local // variable or argument. // // The two kinds of graphs are: // // Tracked place Untracked place // ----------------------++----------------------- // || // | || | // v || v // (rvalue) || (rvalue) // | || | // v || v // (write of place) || (place components) // | || | // v || v // (succ) || (succ) // || // ----------------------++----------------------- // // I will cover the two cases in turn: // // # Tracked places // // A tracked place is a local variable/argument `x`. In // these cases, the link_node where the write occurs is linked // to node id of `x`. The `write_place()` routine generates // the contents of this node. There are no subcomponents to // consider. // // # Non-tracked places // // These are places like `x[5]` or `x.f`. In that case, we // basically ignore the value which is written to but generate // reads for the components---`x` in these two examples. The // components reads are generated by // `propagate_through_place_components()` (this fn). // // # Illegal places // // It is still possible to observe assignments to non-places; // these errors are detected in the later pass borrowck. We // just ignore such cases and treat them as reads. match expr.node { hir::ExprKind::Path(_) => succ, hir::ExprKind::Field(ref e, _) => self.propagate_through_expr(&e, succ), _ => self.propagate_through_expr(expr, succ) } } // see comment on propagate_through_place() fn write_place(&mut self, expr: &Expr, succ: LiveNode, acc: u32) -> LiveNode { match expr.node { hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => { self.access_path(expr.hir_id, path, succ, acc) } // We do not track other places, so just propagate through // to their subcomponents. Also, it may happen that // non-places occur here, because those are detected in the // later pass borrowck. _ => succ } } fn access_var(&mut self, hir_id: HirId, nid: NodeId, succ: LiveNode, acc: u32, span: Span) -> LiveNode { let ln = self.live_node(hir_id, span); if acc != 0 { self.init_from_succ(ln, succ); let var_hid = self.ir.tcx.hir().node_to_hir_id(nid); let var = self.variable(var_hid, span); self.acc(ln, var, acc); } ln } fn access_path(&mut self, hir_id: HirId, path: &hir::Path, succ: LiveNode, acc: u32) -> LiveNode { match path.res { Res::Local(hid) => { let upvars = self.ir.tcx.upvars(self.ir.body_owner); if !upvars.map_or(false, |upvars| upvars.contains_key(&hid)) { let nid = self.ir.tcx.hir().hir_to_node_id(hid); self.access_var(hir_id, nid, succ, acc, path.span) } else { succ } } _ => succ } } fn propagate_through_loop(&mut self, expr: &Expr, kind: LoopKind<'_>, body: &hir::Block, succ: LiveNode) -> LiveNode { /* We model control flow like this: (cond) <--+ | | v | +-- (expr) | | | | | v | | (body) ---+ | | v (succ) */ // first iteration: let mut first_merge = true; let ln = self.live_node(expr.hir_id, expr.span); self.init_empty(ln, succ); match kind { LoopLoop => {} _ => { // If this is not a `loop` loop, then it's possible we bypass // the body altogether. Otherwise, the only way is via a `break` // in the loop body. self.merge_from_succ(ln, succ, first_merge); first_merge = false; } } debug!("propagate_through_loop: using id for loop body {} {}", expr.hir_id, self.ir.tcx.hir().hir_to_pretty_string(body.hir_id)); self.break_ln.insert(expr.hir_id, succ); let cond_ln = match kind { LoopLoop => ln, WhileLoop(ref cond) => self.propagate_through_expr(&cond, ln), }; self.cont_ln.insert(expr.hir_id, cond_ln); let body_ln = self.propagate_through_block(body, cond_ln); // repeat until fixed point is reached: while self.merge_from_succ(ln, body_ln, first_merge) { first_merge = false; let new_cond_ln = match kind { LoopLoop => ln, WhileLoop(ref cond) => { self.propagate_through_expr(&cond, ln) } }; assert_eq!(cond_ln, new_cond_ln); assert_eq!(body_ln, self.propagate_through_block(body, cond_ln)); } cond_ln } } // _______________________________________________________________________ // Checking for error conditions impl<'a, 'tcx> Visitor<'tcx> for Liveness<'a, 'tcx> { fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> { NestedVisitorMap::None } fn visit_local(&mut self, l: &'tcx hir::Local) { check_local(self, l); } fn visit_expr(&mut self, ex: &'tcx Expr) { check_expr(self, ex); } fn visit_arm(&mut self, a: &'tcx hir::Arm) { check_arm(self, a); } } fn check_local<'a, 'tcx>(this: &mut Liveness<'a, 'tcx>, local: &'tcx hir::Local) { match local.init { Some(_) => { this.warn_about_unused_or_dead_vars_in_pat(&local.pat); }, None => { this.pat_bindings(&local.pat, |this, ln, var, sp, id| { let span = local.pat.simple_ident().map_or(sp, |ident| ident.span); this.warn_about_unused(vec![span], id, ln, var); }) } } intravisit::walk_local(this, local); } fn check_arm<'a, 'tcx>(this: &mut Liveness<'a, 'tcx>, arm: &'tcx hir::Arm) { // Only consider the variable from the first pattern; any later patterns must have // the same bindings, and we also consider the first pattern to be the "authoritative" set of // ids. However, we should take the spans of variables with the same name from the later // patterns so the suggestions to prefix with underscores will apply to those too. let mut vars: BTreeMap<String, (LiveNode, Variable, HirId, Vec<Span>)> = Default::default(); for pat in &arm.pats { this.arm_pats_bindings(Some(&*pat), |this, ln, var, sp, id| { let name = this.ir.variable_name(var); vars.entry(name) .and_modify(|(.., spans)| { spans.push(sp); }) .or_insert_with(|| { (ln, var, id, vec![sp]) }); }); } for (_, (ln, var, id, spans)) in vars { this.warn_about_unused(spans, id, ln, var); } intravisit::walk_arm(this, arm); } fn check_expr<'a, 'tcx>(this: &mut Liveness<'a, 'tcx>, expr: &'tcx Expr) { match expr.node { hir::ExprKind::Assign(ref l, _) => { this.check_place(&l); intravisit::walk_expr(this, expr); } hir::ExprKind::AssignOp(_, ref l, _) => { if !this.tables.is_method_call(expr) { this.check_place(&l); } intravisit::walk_expr(this, expr); } hir::ExprKind::InlineAsm(ref ia, ref outputs, ref inputs) => { for input in inputs { this.visit_expr(input); } // Output operands must be places for (o, output) in ia.outputs.iter().zip(outputs) { if !o.is_indirect { this.check_place(output); } this.visit_expr(output); } intravisit::walk_expr(this, expr); } // no correctness conditions related to liveness hir::ExprKind::Call(..) | hir::ExprKind::MethodCall(..) | hir::ExprKind::Match(..) | hir::ExprKind::While(..) | hir::ExprKind::Loop(..) | hir::ExprKind::Index(..) | hir::ExprKind::Field(..) | hir::ExprKind::Array(..) | hir::ExprKind::Tup(..) | hir::ExprKind::Binary(..) | hir::ExprKind::Cast(..) | hir::ExprKind::DropTemps(..) | hir::ExprKind::Unary(..) | hir::ExprKind::Ret(..) | hir::ExprKind::Break(..) | hir::ExprKind::Continue(..) | hir::ExprKind::Lit(_) | hir::ExprKind::Block(..) | hir::ExprKind::AddrOf(..) | hir::ExprKind::Struct(..) | hir::ExprKind::Repeat(..) | hir::ExprKind::Closure(..) | hir::ExprKind::Path(_) | hir::ExprKind::Yield(..) | hir::ExprKind::Box(..) | hir::ExprKind::Type(..) | hir::ExprKind::Err => { intravisit::walk_expr(this, expr); } } } impl<'a, 'tcx> Liveness<'a, 'tcx> { fn check_place(&mut self, expr: &'tcx Expr) { match expr.node { hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => { if let Res::Local(var_hid) = path.res { let upvars = self.ir.tcx.upvars(self.ir.body_owner); if !upvars.map_or(false, |upvars| upvars.contains_key(&var_hid)) { // Assignment to an immutable variable or argument: only legal // if there is no later assignment. If this local is actually // mutable, then check for a reassignment to flag the mutability // as being used. let ln = self.live_node(expr.hir_id, expr.span); let var = self.variable(var_hid, expr.span); self.warn_about_dead_assign(expr.span, expr.hir_id, ln, var); } } } _ => { // For other kinds of places, no checks are required, // and any embedded expressions are actually rvalues intravisit::walk_expr(self, expr); } } } fn should_warn(&self, var: Variable) -> Option<String> { let name = self.ir.variable_name(var); if name.is_empty() || name.as_bytes()[0] == b'_' { None } else { Some(name) } } fn warn_about_unused_args(&self, body: &hir::Body, entry_ln: LiveNode) { for arg in &body.arguments { arg.pat.each_binding(|_bm, hir_id, _, ident| { let sp = ident.span; let var = self.variable(hir_id, sp); // Ignore unused self. if ident.name != kw::SelfLower { if !self.warn_about_unused(vec![sp], hir_id, entry_ln, var) { if self.live_on_entry(entry_ln, var).is_none() { self.report_dead_assign(hir_id, sp, var, true); } } } }) } } fn warn_about_unused_or_dead_vars_in_pat(&mut self, pat: &hir::Pat) { self.pat_bindings(pat, |this, ln, var, sp, id| { if !this.warn_about_unused(vec![sp], id, ln, var) { this.warn_about_dead_assign(sp, id, ln, var); } }) } fn warn_about_unused(&self, spans: Vec<Span>, hir_id: HirId, ln: LiveNode, var: Variable) -> bool { if !self.used_on_entry(ln, var) { let r = self.should_warn(var); if let Some(name) = r { // annoying: for parameters in funcs like `fn(x: i32) // {ret}`, there is only one node, so asking about // assigned_on_exit() is not meaningful. let is_assigned = if ln == self.s.exit_ln { false } else { self.assigned_on_exit(ln, var).is_some() }; if is_assigned { self.ir.tcx.lint_hir_note( lint::builtin::UNUSED_VARIABLES, hir_id, spans, &format!("variable `{}` is assigned to, but never used", name), &format!("consider using `_{}` instead", name), ); } else if name != "self" { let mut err = self.ir.tcx.struct_span_lint_hir( lint::builtin::UNUSED_VARIABLES, hir_id, spans.clone(), &format!("unused variable: `{}`", name), ); if self.ir.variable_is_shorthand(var) { if let Node::Binding(pat) = self.ir.tcx.hir().get_by_hir_id(hir_id) { // Handle `ref` and `ref mut`. let spans = spans.iter() .map(|_span| (pat.span, format!("{}: _", name))) .collect(); err.multipart_suggestion( "try ignoring the field", spans, Applicability::MachineApplicable, ); } } else { err.multipart_suggestion( "consider prefixing with an underscore", spans.iter().map(|span| (*span, format!("_{}", name))).collect(), Applicability::MachineApplicable, ); } err.emit() } } true } else { false } } fn warn_about_dead_assign(&self, sp: Span, hir_id: HirId, ln: LiveNode, var: Variable) { if self.live_on_exit(ln, var).is_none() { self.report_dead_assign(hir_id, sp, var, false); } } fn report_dead_assign(&self, hir_id: HirId, sp: Span, var: Variable, is_argument: bool) { if let Some(name) = self.should_warn(var) { if is_argument { self.ir.tcx.struct_span_lint_hir(lint::builtin::UNUSED_ASSIGNMENTS, hir_id, sp, &format!("value passed to `{}` is never read", name)) .help("maybe it is overwritten before being read?") .emit(); } else { self.ir.tcx.struct_span_lint_hir(lint::builtin::UNUSED_ASSIGNMENTS, hir_id, sp, &format!("value assigned to `{}` is never read", name)) .help("maybe it is overwritten before being read?") .emit(); } } } }
36.442399
100
0.535319
0ece418e7d61382997011d1c7fc92393db48c2d6
23,181
// COPY OF 'src/rust/cli/client.rs' // DO NOT EDIT use clap::{App, SubCommand}; use mime::Mime; use crate::oauth2::{ApplicationSecret, ConsoleApplicationSecret}; use serde_json as json; use serde_json::value::Value; use std::env; use std::error::Error as StdError; use std::fmt; use std::fs; use std::io; use std::io::{stdout, Read, Write}; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::string::ToString; use std::default::Default; const FIELD_SEP: char = '.'; pub enum ComplexType { Pod, Vec, Map, } // Null, // Bool(bool), // I64(i64), // U64(u64), // F64(f64), // String(String), pub enum JsonType { Boolean, Int, Uint, Float, String, } pub struct JsonTypeInfo { pub jtype: JsonType, pub ctype: ComplexType, } // Based on @erickt user comment. Thanks for the idea ! // Remove all keys whose values are null from given value (changed in place) pub fn remove_json_null_values(value: &mut Value) { match *value { Value::Object(ref mut map) => { let mut for_removal = Vec::new(); for (key, mut value) in map.iter_mut() { if value.is_null() { for_removal.push(key.clone()); } else { remove_json_null_values(&mut value); } } for key in &for_removal { map.remove(key); } } json::value::Value::Array(ref mut arr) => { let mut i = 0; while i < arr.len() { if arr[i].is_null() { arr.remove(i); } else { remove_json_null_values(&mut arr[i]); i += 1; } } } _ => {} } } fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { let mut candidate: Option<(f64, &str)> = None; for pv in possible_values { let confidence = strsim::jaro_winkler(v, pv); if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { candidate = Some((confidence, pv)); } } match candidate { None => None, Some((_, candidate)) => Some(candidate), } } pub enum CallType { Upload(UploadProtocol), Standard, } arg_enum! { pub enum UploadProtocol { Simple, // Resumable // This seems to be lost during the async conversion } } impl AsRef<str> for UploadProtocol { fn as_ref(&self) -> &str { match *self { UploadProtocol::Simple => "simple", // UploadProtocol::Resumable => "resumable", } } } impl AsRef<str> for CallType { fn as_ref(&self) -> &str { match *self { CallType::Upload(ref proto) => proto.as_ref(), CallType::Standard => "standard-request", } } } #[derive(Clone, Default)] pub struct FieldCursor(Vec<String>); impl ToString for FieldCursor { fn to_string(&self) -> String { self.0.join(".") } } impl From<&'static str> for FieldCursor { fn from(value: &'static str) -> FieldCursor { let mut res = FieldCursor::default(); res.set(value).unwrap(); res } } fn assure_entry<'a>(m: &'a mut json::Map<String, Value>, k: &str) -> &'a mut Value { if m.contains_key(k) { return m.get_mut(k).expect("value to exist"); } m.insert(k.to_owned(), Value::Object(Default::default())); m.get_mut(k).expect("value to exist") } impl FieldCursor { pub fn set(&mut self, value: &str) -> Result<(), CLIError> { if value.is_empty() { return Err(CLIError::Field(FieldError::Empty)); } let mut first_is_field_sep = false; let mut char_count: usize = 0; let mut last_c = FIELD_SEP; let mut num_conscutive_field_seps = 0; let mut field = String::new(); let mut fields = self.0.clone(); let push_field = |fs: &mut Vec<String>, f: &mut String| { if !f.is_empty() { fs.push(f.clone()); f.truncate(0); } }; for (cid, c) in value.chars().enumerate() { char_count += 1; if c == FIELD_SEP { if cid == 0 { first_is_field_sep = true; } num_conscutive_field_seps += 1; if cid > 0 && last_c == FIELD_SEP { if fields.pop().is_none() { return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))); } } else { push_field(&mut fields, &mut field); } } else { num_conscutive_field_seps = 0; if cid == 1 && first_is_field_sep { fields.truncate(0); } field.push(c); } last_c = c; } push_field(&mut fields, &mut field); if char_count == 1 && first_is_field_sep { fields.truncate(0); } if char_count > 1 && num_conscutive_field_seps == 1 { return Err(CLIError::Field(FieldError::TrailingFieldSep( value.to_string(), ))); } self.0 = fields; Ok(()) } pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option<String> { if value.is_empty() { return None; } let mut last_c = FIELD_SEP; let mut field = String::new(); let mut output = String::new(); let push_field = |fs: &mut String, f: &mut String| { if !f.is_empty() { fs.push_str(match did_you_mean(&f, possible_values) { Some(candidate) => candidate, None => &f, }); f.truncate(0); } }; for (cid, c) in value.chars().enumerate() { if c == FIELD_SEP { if last_c != FIELD_SEP { push_field(&mut output, &mut field); } output.push(c); } else { field.push(c); } last_c = c; } push_field(&mut output, &mut field); if output == value { None } else { Some(output) } } pub fn set_json_value( &self, mut object: &mut Value, value: &str, type_info: JsonTypeInfo, err: &mut InvalidOptionsError, orig_cursor: &FieldCursor, ) { assert!(!self.0.is_empty()); for field in &self.0[..self.0.len() - 1] { let tmp = object; object = match *tmp { Value::Object(ref mut mapping) => assure_entry(mapping, &field), _ => panic!("We don't expect non-object Values here ..."), }; } match *object { Value::Object(ref mut mapping) => { let field = &self.0[self.0.len() - 1]; let to_jval = |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| -> Value { match jtype { JsonType::Boolean => { Value::Bool(arg_from_str(value, err, &field, "boolean")) } JsonType::Int => Value::Number( json::Number::from_f64(arg_from_str(value, err, &field, "int")) .expect("valid f64"), ), JsonType::Uint => Value::Number( json::Number::from_f64(arg_from_str(value, err, &field, "uint")) .expect("valid f64"), ), JsonType::Float => Value::Number( json::Number::from_f64(arg_from_str(value, err, &field, "float")) .expect("valid f64"), ), JsonType::String => Value::String(value.to_owned()), } }; match type_info.ctype { ComplexType::Pod => { if mapping .insert(field.to_owned(), to_jval(value, type_info.jtype, err)) .is_some() { err.issues.push(CLIError::Field(FieldError::Duplicate( orig_cursor.to_string(), ))); } } ComplexType::Vec => match *assure_entry(mapping, field) { Value::Array(ref mut values) => { values.push(to_jval(value, type_info.jtype, err)) } _ => unreachable!(), }, ComplexType::Map => { let (key, value) = parse_kv_arg(value, err, true); let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); match *assure_entry(mapping, &field) { Value::Object(ref mut value_map) => { if value_map.insert(key.to_owned(), jval).is_some() { err.issues.push(CLIError::Field(FieldError::Duplicate( orig_cursor.to_string(), ))); } } _ => unreachable!(), } } } } _ => unreachable!(), } } pub fn num_fields(&self) -> usize { self.0.len() } } pub fn parse_kv_arg<'a>( kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool, ) -> (&'a str, Option<&'a str>) { let mut add_err = || { err.issues .push(CLIError::InvalidKeyValueSyntax(kv.to_string(), for_hashmap)) }; match kv.find('=') { None => { add_err(); (kv, None) } Some(pos) => { let key = &kv[..pos]; if kv.len() <= pos + 1 { add_err(); return (key, Some("")); } (key, Some(&kv[pos + 1..])) } } } pub fn calltype_from_str( name: &str, valid_protocols: Vec<String>, err: &mut InvalidOptionsError, ) -> CallType { CallType::Upload(match UploadProtocol::from_str(name) { Ok(up) => up, Err(msg) => { err.issues.push(CLIError::InvalidUploadProtocol( name.to_string(), valid_protocols, )); UploadProtocol::Simple } }) } pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option<fs::File> { match fs::File::open(file_path) { Ok(f) => Some(f), Err(io_err) => { err.issues.push(CLIError::Input(InputError::Io(( file_path.to_string(), io_err, )))); None } } } pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option<Mime> { match mime.parse() { Ok(m) => Some(m), Err(_) => { err.issues .push(CLIError::Input(InputError::Mime(mime.to_string()))); None } } } pub fn writer_from_opts(arg: Option<&str>) -> Result<Box<dyn Write>, io::Error> { let f = arg.unwrap_or("-"); match f { "-" => Ok(Box::new(stdout())), _ => match fs::OpenOptions::new() .create(true) .truncate(true) .write(true) .open(f) { Ok(f) => Ok(Box::new(f)), Err(io_err) => Err(io_err), }, } } pub fn arg_from_str<'a, T>( arg: &str, err: &mut InvalidOptionsError, arg_name: &'a str, arg_type: &'a str, ) -> T where T: FromStr + Default, <T as FromStr>::Err: fmt::Display, { match FromStr::from_str(arg) { Err(perr) => { err.issues.push(CLIError::ParseError( arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr), )); Default::default() } Ok(v) => v, } } #[derive(Debug)] pub enum ApplicationSecretError { DecoderError((String, json::Error)), FormatError(String), } impl fmt::Display for ApplicationSecretError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { ApplicationSecretError::DecoderError((ref path, ref err)) => writeln!( f, "Could not decode file at '{}' with error: {}.", path, err ), ApplicationSecretError::FormatError(ref path) => writeln!( f, "'installed' field is unset in secret file at '{}'.", path ), } } } #[derive(Debug)] pub enum ConfigurationError { DirectoryCreationFailed((String, io::Error)), DirectoryUnset, HomeExpansionFailed(String), Secret(ApplicationSecretError), Io((String, io::Error)), } impl fmt::Display for ConfigurationError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) => writeln!( f, "Directory '{}' could not be created with error: {}.", dir, err ), ConfigurationError::DirectoryUnset => writeln!(f, "--config-dir was unset or empty."), ConfigurationError::HomeExpansionFailed(ref dir) => writeln!( f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir ), ConfigurationError::Secret(ref err) => writeln!(f, "Secret -> {}", err), ConfigurationError::Io((ref path, ref err)) => writeln!( f, "IO operation failed on path '{}' with error: {}.", path, err ), } } } #[derive(Debug)] pub enum InputError { Io((String, io::Error)), Mime(String), } impl fmt::Display for InputError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { InputError::Io((ref file_path, ref io_err)) => writeln!( f, "Failed to open '{}' for reading with error: {}.", file_path, io_err ), InputError::Mime(ref mime) => writeln!(f, "'{}' is not a known mime-type.", mime), } } } #[derive(Debug)] pub enum FieldError { PopOnEmpty(String), TrailingFieldSep(String), Unknown(String, Option<String>, Option<String>), Duplicate(String), Empty, } impl fmt::Display for FieldError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { FieldError::PopOnEmpty(ref field) => { writeln!(f, "'{}': Cannot move up on empty field cursor.", field) } FieldError::TrailingFieldSep(ref field) => writeln!( f, "'{}': Single field separator may not be last character.", field ), FieldError::Unknown(ref field, ref suggestion, ref value) => { let suffix = match *suggestion { Some(ref s) => { let kv = match *value { Some(ref v) => format!("{}={}", s, v), None => s.clone(), }; format!(" Did you mean '{}' ?", kv) } None => String::new(), }; writeln!(f, "Field '{}' does not exist.{}", field, suffix) } FieldError::Duplicate(ref cursor) => { writeln!(f, "Value at '{}' was already set", cursor) } FieldError::Empty => writeln!(f, "Field names must not be empty."), } } } #[derive(Debug)] pub enum CLIError { Configuration(ConfigurationError), ParseError(String, String, String, String), UnknownParameter(String, Vec<&'static str>), InvalidUploadProtocol(String, Vec<String>), InvalidKeyValueSyntax(String, bool), Input(InputError), Field(FieldError), MissingCommandError, MissingMethodError(String), } impl fmt::Display for CLIError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), CLIError::Input(ref err) => write!(f, "Input -> {}", err), CLIError::Field(ref err) => write!(f, "Field -> {}", err), CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) => writeln!( f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ") ), CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) => writeln!( f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", arg_name, value, type_name, err_desc ), CLIError::UnknownParameter(ref param_name, ref possible_values) => { let suffix = match did_you_mean(param_name, &possible_values) { Some(v) => format!(" Did you mean '{}' ?", v), None => String::new(), }; writeln!(f, "Parameter '{}' is unknown.{}", param_name, suffix) } CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { let hashmap_info = if is_hashmap { "hashmap " } else { "" }; writeln!( f, "'{}' does not match {}pattern <key>=<value>.", kv, hashmap_info ) } CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), CLIError::MissingMethodError(ref cmd) => writeln!( f, "Please specify the method to call on the '{}' command.", cmd ), } } } #[derive(Debug)] pub struct InvalidOptionsError { pub issues: Vec<CLIError>, pub exit_code: i32, } impl fmt::Display for InvalidOptionsError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { for issue in &self.issues { issue.fmt(f)?; } Ok(()) } } impl InvalidOptionsError { pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { InvalidOptionsError { issues: vec![err], exit_code, } } pub fn new() -> InvalidOptionsError { InvalidOptionsError { issues: Vec::new(), exit_code: 1, } } } pub fn assure_config_dir_exists(dir: &str) -> Result<String, CLIError> { let trdir = dir.trim(); if trdir.is_empty() { return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)); } let expanded_config_dir = if trdir.as_bytes()[0] == b'~' { match env::var("HOME") .ok() .or_else(|| env::var("UserProfile").ok()) { None => { return Err(CLIError::Configuration( ConfigurationError::HomeExpansionFailed(trdir.to_string()), )) } Some(mut user) => { user.push_str(&trdir[1..]); user } } } else { trdir.to_string() }; if let Err(err) = fs::create_dir(&expanded_config_dir) { if err.kind() != io::ErrorKind::AlreadyExists { return Err(CLIError::Configuration( ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)), )); } } Ok(expanded_config_dir) } pub fn application_secret_from_directory( dir: &str, secret_basename: &str, json_console_secret: &str, ) -> Result<ApplicationSecret, CLIError> { let secret_path = Path::new(dir).join(secret_basename); let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); let secret_io_error = |io_err: io::Error| { Err(CLIError::Configuration(ConfigurationError::Io(( secret_str(), io_err, )))) }; for _ in 0..2 { match fs::File::open(&secret_path) { Err(mut err) => { if err.kind() == io::ErrorKind::NotFound { // Write our built-in one - user may adjust the written file at will err = match fs::OpenOptions::new() .create(true) .write(true) .truncate(true) .open(&secret_path) { Err(cfe) => cfe, Ok(mut f) => { // Assure we convert 'ugly' json string into pretty one let console_secret: ConsoleApplicationSecret = json::from_str(json_console_secret).unwrap(); match json::to_writer_pretty(&mut f, &console_secret) { Err(serde_err) => { panic!("Unexpected serde error: {:#?}", serde_err) } Ok(_) => continue, } } }; // fall through to IO error handling } return secret_io_error(err); } Ok(f) => match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { Err(json_err) => { return Err(CLIError::Configuration(ConfigurationError::Secret( ApplicationSecretError::DecoderError((secret_str(), json_err)), ))) } Ok(console_secret) => match console_secret.installed { Some(secret) => return Ok(secret), None => { return Err(CLIError::Configuration(ConfigurationError::Secret( ApplicationSecretError::FormatError(secret_str()), ))) } }, }, } } unreachable!(); }
30.949266
100
0.470428
79bfdf92f633a4e2e635eb146f1ebc3f8d4972b1
4,235
// Copyright (c) 2017 Stefan Lankes, RWTH Aachen University // Colin Finck, RWTH Aachen University // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. #![allow(dead_code)] use arch::x86_64::kernel::gdt; use core::sync::atomic::{AtomicBool, Ordering}; use x86::bits64::paging::VAddr; use x86::dtables::{self, DescriptorTablePointer}; use x86::segmentation::{SegmentSelector, SystemDescriptorTypes64}; use x86::Ring; /// An interrupt gate descriptor. /// /// See Intel manual 3a for details, specifically section "6.14.1 64-Bit Mode /// IDT" and "Figure 6-7. 64-Bit IDT Gate Descriptors". #[derive(Debug, Clone, Copy)] #[repr(C, packed)] struct IdtEntry { /// Lower 16 bits of ISR. pub base_lo: u16, /// Segment selector. pub selector: SegmentSelector, /// This must always be zero. pub ist_index: u8, /// Flags. pub flags: u8, /// The upper 48 bits of ISR (the last 16 bits must be zero). pub base_hi: u64, /// Must be zero. pub reserved1: u16, } enum Type { InterruptGate, TrapGate, } impl Type { pub fn pack(self) -> u8 { match self { Type::InterruptGate => SystemDescriptorTypes64::InterruptGate as u8, Type::TrapGate => SystemDescriptorTypes64::TrapGate as u8, } } } impl IdtEntry { /// A "missing" IdtEntry. /// /// If the CPU tries to invoke a missing interrupt, it will instead /// send a General Protection fault (13), with the interrupt number and /// some other data stored in the error code. pub const MISSING: IdtEntry = IdtEntry { base_lo: 0, selector: SegmentSelector::from_raw(0), ist_index: 0, flags: 0, base_hi: 0, reserved1: 0, }; /// Create a new IdtEntry pointing at `handler`, which must be a function /// with interrupt calling conventions. (This must be currently defined in /// assembly language.) The `gdt_code_selector` value must be the offset of /// code segment entry in the GDT. /// /// The "Present" flag set, which is the most common case. If you need /// something else, you can construct it manually. pub fn new( handler: VAddr, gdt_code_selector: SegmentSelector, dpl: Ring, ty: Type, ist_index: u8, ) -> IdtEntry { assert!(ist_index < 0b1000); IdtEntry { base_lo: ((handler.as_usize() as u64) & 0xFFFF) as u16, base_hi: handler.as_usize() as u64 >> 16, selector: gdt_code_selector, ist_index: ist_index, flags: dpl as u8 | ty.pack() | (1 << 7), reserved1: 0, } } } /// Declare an IDT of 256 entries. /// Although not all entries are used, the rest exists as a bit /// of a trap. If any undefined IDT entry is hit, it will cause /// an "Unhandled Interrupt" exception. pub const IDT_ENTRIES: usize = 256; static mut IDT: [IdtEntry; IDT_ENTRIES] = [IdtEntry::MISSING; IDT_ENTRIES]; static mut IDTP: DescriptorTablePointer<IdtEntry> = DescriptorTablePointer { base: 0 as *const IdtEntry, limit: 0, }; pub fn install() { static IDT_INIT: AtomicBool = AtomicBool::new(false); unsafe { let is_init = IDT_INIT.swap(true, Ordering::SeqCst); if !is_init { // TODO: As soon as https://github.com/rust-lang/rust/issues/44580 is implemented, it should be possible to // implement "new" as "const fn" and do this call already in the initialization of IDTP. IDTP = DescriptorTablePointer::new_from_slice(&IDT); }; dtables::lidt(&IDTP); } } /// Set an entry in the IDT. /// /// # Arguments /// /// * `index` - 8-bit index of the interrupt gate to set. /// * `handler` - Handler function to call for this interrupt/exception. /// * `ist_index` - Index of the Interrupt Stack Table (IST) to switch to. /// A zero value means that the stack won't be switched, a value of 1 refers to the first IST entry, etc. pub fn set_gate(index: u8, handler: usize, ist_index: u8) { let sel = SegmentSelector::new(gdt::GDT_KERNEL_CODE, Ring::Ring0); let entry = IdtEntry::new( VAddr::from_usize(handler), sel, Ring::Ring0, Type::InterruptGate, ist_index, ); unsafe { IDT[index as usize] = entry; } }
29.409722
121
0.687367
901882ab4abe441552b4651307a0ee150c353112
3,043
use iced::{ text_input::{self, State, TextInput}, Column, Container, Length, }; use crate::ui::{color, component::text}; #[derive(Debug, Clone)] pub struct Value<T> { pub value: T, pub valid: bool, } impl std::default::Default for Value<String> { fn default() -> Self { Self { value: "".to_string(), valid: true, } } } pub struct Form<'a, Message> { input: TextInput<'a, Message>, warning: Option<&'a str>, valid: bool, } impl<'a, Message: 'a> Form<'a, Message> where Message: Clone, { /// Creates a new [`Form`]. /// /// It expects: /// - some [`iced::text_input::State`] /// - a placeholder /// - the current value /// - a function that produces a message when the [`Form`] changes pub fn new<F>( state: &'a mut State, placeholder: &str, value: &Value<String>, on_change: F, ) -> Self where F: 'static + Fn(String) -> Message, { Self { input: TextInput::new(state, placeholder, &value.value, on_change), warning: None, valid: value.valid, } } /// Sets the [`Form`] with a warning message pub fn warning(mut self, warning: &'a str) -> Self { self.warning = Some(warning); self } /// Sets the padding of the [`Form`]. pub fn padding(mut self, units: u16) -> Self { self.input = self.input.padding(units); self } /// Sets the [`Form`] with a text size pub fn size(mut self, size: u16) -> Self { self.input = self.input.size(size); self } pub fn render(self) -> Container<'a, Message> { if !self.valid { if let Some(message) = self.warning { return Container::new( Column::with_children(vec![ self.input.style(InvalidFormStyle).into(), text::small(&message).color(color::WARNING).into(), ]) .width(Length::Fill) .spacing(5), ) .width(Length::Fill); } } Container::new(self.input).width(Length::Fill) } } struct InvalidFormStyle; impl text_input::StyleSheet for InvalidFormStyle { fn active(&self) -> text_input::Style { text_input::Style { background: iced::Background::Color(color::FOREGROUND), border_radius: 5.0, border_width: 1.0, border_color: color::WARNING, } } fn focused(&self) -> text_input::Style { text_input::Style { border_color: color::WARNING, ..self.active() } } fn placeholder_color(&self) -> iced::Color { iced::Color::from_rgb(0.7, 0.7, 0.7) } fn value_color(&self) -> iced::Color { iced::Color::from_rgb(0.3, 0.3, 0.3) } fn selection_color(&self) -> iced::Color { iced::Color::from_rgb(0.8, 0.8, 1.0) } }
24.739837
79
0.516267
f4b8afc677c69a058e39ff21d2840062572c0184
1,326
macro_rules! accessor { (type : $type:ty {get=$getter:ident} ) => { fn $getter(&self) -> $type ; }; (type : $type:ty {set=$setter:ident} ) => { fn $setter(&mut self, value:$type) ; }; (type : $type:ty {get=$getter:ident, set=$setter:ident} ) => { accessor!(type:$type {get=$getter}); accessor!(type:$type {set=$setter}); }; } macro_rules! accessor_impl { ($name:ident : $type:ty {get=$getter:ident} ) => { fn $getter(&self) -> $type { self.$name } }; ($name:ident : $type:ty {set=$setter:ident} ) => { fn $setter(&mut self, value: $type) { self.$name = value; } }; ($name:ident : $type:ty {get=$getter:ident, set=$setter:ident} ) => { accessor_impl!($name:$type {get=$getter}); accessor_impl!($name:$type {set=$setter}); }; } trait Horizontal { accessor!(type:i64 {get=get_x, set=set_x}); fn count_up(&mut self) -> i64 { let next = self.get_x() + 1; self.set_x(next); self.get_x() } } struct Point { x: i64, } impl Horizontal for Point { accessor_impl!(x:i64 {get = get_x, set = set_x}); } fn main() { println!("Hello, world!"); let mut p = Point { x: 0 }; p.x += 1; p.count_up(); println!("x: {}", p.x); }
25.018868
73
0.50905
ccc57e5eaff30e6efd863b5e08c362446b50553f
19,643
//! TODO(doc): @doitian use ckb_build_info::Version; use ckb_resource::{DEFAULT_P2P_PORT, DEFAULT_RPC_PORT, DEFAULT_SPEC}; use clap::{App, AppSettings, Arg, ArgGroup, ArgMatches, SubCommand}; /// TODO(doc): @doitian pub const CMD_RUN: &str = "run"; /// TODO(doc): @doitian pub const CMD_MINER: &str = "miner"; /// TODO(doc): @doitian pub const CMD_EXPORT: &str = "export"; /// TODO(doc): @doitian pub const CMD_IMPORT: &str = "import"; /// TODO(doc): @doitian pub const CMD_INIT: &str = "init"; /// TODO(doc): @doitian pub const CMD_REPLAY: &str = "replay"; /// TODO(doc): @doitian pub const CMD_STATS: &str = "stats"; /// TODO(doc): @doitian pub const CMD_LIST_HASHES: &str = "list-hashes"; /// TODO(doc): @doitian pub const CMD_RESET_DATA: &str = "reset-data"; /// TODO(doc): @doitian pub const CMD_PEERID: &str = "peer-id"; /// TODO(doc): @doitian pub const CMD_GEN_SECRET: &str = "gen"; /// TODO(doc): @doitian pub const CMD_FROM_SECRET: &str = "from-secret"; /// TODO(doc): @doitian pub const CMD_MIGRATE: &str = "migrate"; /// TODO(doc): @doitian pub const ARG_CONFIG_DIR: &str = "config-dir"; /// TODO(doc): @doitian pub const ARG_FORMAT: &str = "format"; /// TODO(doc): @doitian pub const ARG_TARGET: &str = "target"; /// TODO(doc): @doitian pub const ARG_SOURCE: &str = "source"; /// TODO(doc): @doitian pub const ARG_DATA: &str = "data"; /// TODO(doc): @doitian pub const ARG_LIST_CHAINS: &str = "list-chains"; /// TODO(doc): @doitian pub const ARG_INTERACTIVE: &str = "interactive"; /// TODO(doc): @doitian pub const ARG_CHAIN: &str = "chain"; /// TODO(doc): @doitian pub const ARG_IMPORT_SPEC: &str = "import-spec"; /// TODO(doc): @doitian pub const ARG_P2P_PORT: &str = "p2p-port"; /// TODO(doc): @doitian pub const ARG_RPC_PORT: &str = "rpc-port"; /// TODO(doc): @doitian pub const ARG_FORCE: &str = "force"; /// TODO(doc): @doitian pub const ARG_LOG_TO: &str = "log-to"; /// TODO(doc): @doitian pub const ARG_BUNDLED: &str = "bundled"; /// TODO(doc): @doitian pub const ARG_BA_CODE_HASH: &str = "ba-code-hash"; /// TODO(doc): @doitian pub const ARG_BA_ARG: &str = "ba-arg"; /// TODO(doc): @doitian pub const ARG_BA_HASH_TYPE: &str = "ba-hash-type"; /// TODO(doc): @doitian pub const ARG_BA_MESSAGE: &str = "ba-message"; /// TODO(doc): @doitian pub const ARG_BA_ADVANCED: &str = "ba-advanced"; /// TODO(doc): @doitian pub const ARG_FROM: &str = "from"; /// TODO(doc): @doitian pub const ARG_TO: &str = "to"; /// TODO(doc): @doitian pub const ARG_ALL: &str = "all"; /// TODO(doc): @doitian pub const ARG_LIMIT: &str = "limit"; /// TODO(doc): @doitian pub const ARG_DATABASE: &str = "database"; /// TODO(doc): @doitian pub const ARG_NETWORK: &str = "network"; /// TODO(doc): @doitian pub const ARG_NETWORK_PEER_STORE: &str = "network-peer-store"; /// TODO(doc): @doitian pub const ARG_NETWORK_SECRET_KEY: &str = "network-secret-key"; /// TODO(doc): @doitian pub const ARG_LOGS: &str = "logs"; /// TODO(doc): @doitian pub const ARG_TMP_TARGET: &str = "tmp-target"; /// TODO(doc): @doitian pub const ARG_SECRET_PATH: &str = "secret-path"; /// TODO(doc): @doitian pub const ARG_PROFILE: &str = "profile"; /// TODO(doc): @doitian pub const ARG_SANITY_CHECK: &str = "sanity-check"; /// TODO(doc): @doitian pub const ARG_FULL_VERIFICATION: &str = "full-verification"; /// Present `skip-spec-check` arg to `run` skip spec check on setup pub const ARG_SKIP_CHAIN_SPEC_CHECK: &str = "skip-spec-check"; /// Present `overwrite-spec` arg to force overriding the chain spec in the database with the present configured chain spec pub const ARG_OVERWRITE_CHAIN_SPEC: &str = "overwrite-spec"; /// assume valid target cli arg name pub const ARG_ASSUME_VALID_TARGET: &str = "assume-valid-target"; /// Migrate check flag arg pub const ARG_MIGRATE_CHECK: &str = "check"; /// TODO(doc): @doitian const GROUP_BA: &str = "ba"; fn basic_app<'b>() -> App<'static, 'b> { App::new("ckb") .author("Nervos Core Dev <dev@nervos.org>") .about("Nervos CKB - The Common Knowledge Base") .setting(AppSettings::SubcommandRequiredElseHelp) .arg( Arg::with_name(ARG_CONFIG_DIR) .global(true) .short("C") .value_name("path") .takes_value(true) .help( "Runs as if ckb was started in <path> instead of the current working directory.", ), ) .subcommand(run()) .subcommand(miner()) .subcommand(export()) .subcommand(import()) .subcommand(list_hashes()) .subcommand(init()) .subcommand(replay()) .subcommand(stats()) .subcommand(reset_data()) .subcommand(peer_id()) .subcommand(migrate()) } /// TODO(doc): @doitian pub fn get_matches(version: &Version) -> ArgMatches<'static> { basic_app() .version(version.short().as_str()) .long_version(version.long().as_str()) .get_matches() } fn run() -> App<'static, 'static> { SubCommand::with_name(CMD_RUN) .about("Runs ckb node") .arg( Arg::with_name(ARG_BA_ADVANCED) .long(ARG_BA_ADVANCED) .help("Allows any block assembler code hash and args"), ) .arg( Arg::with_name(ARG_SKIP_CHAIN_SPEC_CHECK) .long(ARG_SKIP_CHAIN_SPEC_CHECK) .help("Skips checking the chain spec with the hash stored in the database"), ).arg( Arg::with_name(ARG_OVERWRITE_CHAIN_SPEC) .long(ARG_OVERWRITE_CHAIN_SPEC) .help("Overwrites the chain spec in the database with the present configured chain spec") ).arg( Arg::with_name(ARG_ASSUME_VALID_TARGET) .long(ARG_ASSUME_VALID_TARGET) .takes_value(true) .validator(is_hex) .help("This parameter specifies the hash of a block. \ When the height does not reach this block's height, the execution of the script will be disabled, \ that is, skip verifying the script content. \ \ It should be noted that when this option is enabled, the header is first synchronized to \ the highest currently found. During this period, if the assume valid target is found, \ the download of the block starts; \ If the timestamp of the best known header is already within 24 hours of the current time and the assume valid target is not found, the target will automatically become invalid, and the download of the block will be started with verify") ) } fn miner() -> App<'static, 'static> { SubCommand::with_name(CMD_MINER) .about("Runs ckb miner") .arg( Arg::with_name(ARG_LIMIT) .short("l") .long(ARG_LIMIT) .takes_value(true) .help( "Exit after how many nonces found; \ 0 means the miner will never exit. [default: 0]", ), ) } fn reset_data() -> App<'static, 'static> { SubCommand::with_name(CMD_RESET_DATA) .about( "Truncate the database directory\n\ Example:\n\ ckb reset-data --force --database", ) .arg( Arg::with_name(ARG_FORCE) .short("f") .long(ARG_FORCE) .help("Delete data without interactive prompt"), ) .arg( Arg::with_name(ARG_ALL) .long(ARG_ALL) .help("Delete the whole data directory"), ) .arg( Arg::with_name(ARG_DATABASE) .long(ARG_DATABASE) .help("Delete only `data/db`"), ) .arg( Arg::with_name(ARG_NETWORK) .long(ARG_NETWORK) .help("Delete both peer store and secret key"), ) .arg( Arg::with_name(ARG_NETWORK_PEER_STORE) .long(ARG_NETWORK_PEER_STORE) .help("Delete only `data/network/peer_store`"), ) .arg( Arg::with_name(ARG_NETWORK_SECRET_KEY) .long(ARG_NETWORK_SECRET_KEY) .help("Delete only `data/network/secret_key`"), ) .arg( Arg::with_name(ARG_LOGS) .long(ARG_LOGS) .help("Delete only `data/logs`"), ) } pub(crate) fn stats() -> App<'static, 'static> { SubCommand::with_name(CMD_STATS) .about( "Statics chain information\n\ Example:\n\ ckb -C <dir> stats --from 1 --to 500", ) .arg( Arg::with_name(ARG_FROM) .long(ARG_FROM) .takes_value(true) .help("Specifies from block number."), ) .arg( Arg::with_name(ARG_TO) .long(ARG_TO) .takes_value(true) .help("Specifies to block number."), ) } fn replay() -> App<'static, 'static> { SubCommand::with_name(CMD_REPLAY) .about("replay ckb process block") .help(" --tmp-target <tmp> --profile 1 10,\n --tmp-target <tmp> --sanity-check,\n ") .arg(Arg::with_name(ARG_TMP_TARGET).long(ARG_TMP_TARGET).takes_value(true).required(true).help( "Specifies a target path, prof command make a temporary directory inside of target and the directory will be automatically deleted when finished", )) .arg(Arg::with_name(ARG_PROFILE).long(ARG_PROFILE).help( "Enable profile", )) .arg( Arg::with_name(ARG_FROM) .help("Specifies profile from block number."), ) .arg( Arg::with_name(ARG_TO) .help("Specifies profile to block number."), ) .arg( Arg::with_name(ARG_SANITY_CHECK).long(ARG_SANITY_CHECK).help("Enable sanity check") ) .arg( Arg::with_name(ARG_FULL_VERIFICATION).long(ARG_FULL_VERIFICATION).help("Enable sanity check") ) .group( ArgGroup::with_name("mode") .args(&[ARG_PROFILE, ARG_SANITY_CHECK]) .required(true) ) } fn export() -> App<'static, 'static> { SubCommand::with_name(CMD_EXPORT) .about("Exports ckb data") .arg( Arg::with_name(ARG_TARGET) .short("t") .long(ARG_TARGET) .value_name("path") .required(true) .index(1) .help("Specifies the export target path."), ) } fn import() -> App<'static, 'static> { SubCommand::with_name(CMD_IMPORT) .about("Imports ckb data") .arg( Arg::with_name(ARG_SOURCE) .short("s") .long(ARG_SOURCE) .value_name("path") .required(true) .index(1) .help("Specifies the exported data path."), ) } fn migrate() -> App<'static, 'static> { SubCommand::with_name(CMD_MIGRATE) .about("Runs ckb migration") .arg( Arg::with_name(ARG_MIGRATE_CHECK) .long(ARG_MIGRATE_CHECK) .help( "Perform database version check without migrating, \ if migration is in need ExitCode(0) is returned,\ otherwise ExitCode(64) is returned", ), ) } fn list_hashes() -> App<'static, 'static> { SubCommand::with_name(CMD_LIST_HASHES) .about("Lists well known hashes") .arg( Arg::with_name(ARG_BUNDLED) .short("b") .long(ARG_BUNDLED) .help( "Lists hashes of the bundled chain specs instead of the current effective one.", ), ) } fn init() -> App<'static, 'static> { SubCommand::with_name(CMD_INIT) .about("Creates a CKB direcotry or reinitializes an existing one") .arg( Arg::with_name(ARG_INTERACTIVE) .short("i") .long(ARG_INTERACTIVE) .help("Interactive mode"), ) .arg( Arg::with_name(ARG_LIST_CHAINS) .short("l") .long(ARG_LIST_CHAINS) .help("Lists available options for --chain"), ) .arg( Arg::with_name(ARG_CHAIN) .short("c") .long(ARG_CHAIN) .default_value(DEFAULT_SPEC) .help("Initializes CKB direcotry for <chain>"), ) .arg( Arg::with_name(ARG_IMPORT_SPEC) .long(ARG_IMPORT_SPEC) .takes_value(true) .help( "Uses the specifiec file as chain spec. Specially, \ The dash \"-\" denotes importing the spec from stdin encoded in base64", ), ) .arg( Arg::with_name(ARG_LOG_TO) .long(ARG_LOG_TO) .possible_values(&["file", "stdout", "both"]) .default_value("both") .help("Configures where the logs should print"), ) .arg( Arg::with_name(ARG_FORCE) .short("f") .long(ARG_FORCE) .help("Forces overwriting existing files"), ) .arg( Arg::with_name(ARG_RPC_PORT) .long(ARG_RPC_PORT) .default_value(DEFAULT_RPC_PORT) .help("Replaces CKB RPC port in the created config file"), ) .arg( Arg::with_name(ARG_P2P_PORT) .long(ARG_P2P_PORT) .default_value(DEFAULT_P2P_PORT) .help("Replaces CKB P2P port in the created config file"), ) .arg( Arg::with_name(ARG_BA_CODE_HASH) .long(ARG_BA_CODE_HASH) .value_name("code_hash") .validator(is_hex) .takes_value(true) .help( "Sets code_hash in [block_assembler] \ [default: secp256k1 if --ba-arg is present]", ), ) .arg( Arg::with_name(ARG_BA_ARG) .long(ARG_BA_ARG) .value_name("arg") .validator(is_hex) .multiple(true) .number_of_values(1) .help("Sets args in [block_assembler]"), ) .arg( Arg::with_name(ARG_BA_HASH_TYPE) .long(ARG_BA_HASH_TYPE) .value_name("hash_type") .takes_value(true) .possible_values(&["data", "type"]) .default_value("type") .help("Sets hash type in [block_assembler]"), ) .group( ArgGroup::with_name(GROUP_BA) .args(&[ARG_BA_CODE_HASH, ARG_BA_ARG]) .multiple(true), ) .arg( Arg::with_name(ARG_BA_MESSAGE) .long(ARG_BA_MESSAGE) .value_name("message") .validator(is_hex) .requires(GROUP_BA) .help("Sets message in [block_assembler]"), ) .arg( Arg::with_name("export-specs") .long("export-specs") .hidden(true), ) .arg(Arg::with_name("list-specs").long("list-specs").hidden(true)) .arg( Arg::with_name("spec") .short("s") .long("spec") .takes_value(true) .hidden(true), ) } fn peer_id() -> App<'static, 'static> { SubCommand::with_name(CMD_PEERID) .about("About peer id, base on Secp256k1") .subcommand( SubCommand::with_name(CMD_FROM_SECRET) .about("Generate peer id from secret file") .arg( Arg::with_name(ARG_SECRET_PATH) .takes_value(true) .long(ARG_SECRET_PATH) .required(true) .help("Generate peer id from secret file path"), ), ) .subcommand( SubCommand::with_name(CMD_GEN_SECRET) .about("Generate random key to file") .arg( Arg::with_name(ARG_SECRET_PATH) .long(ARG_SECRET_PATH) .required(true) .takes_value(true) .help("Generate peer id to file path"), ), ) } fn is_hex(hex: String) -> Result<(), String> { let tmp = hex.as_bytes(); if tmp.len() < 2 { Err("Must be a 0x-prefixed hexadecimal string".to_string()) } else if tmp.len() & 1 != 0 { Err("Hexadecimal strings must be of even length".to_string()) } else if tmp[..2] == b"0x"[..] { for byte in &tmp[2..] { match byte { b'A'..=b'F' | b'a'..=b'f' | b'0'..=b'9' => continue, invalid_char => { return Err(format!("Hex has invalid char: {}", invalid_char)); } } } Ok(()) } else { Err("Must 0x-prefixed hexadecimal string".to_string()) } } #[cfg(test)] mod tests { use super::*; #[test] fn ba_message_requires_ba_arg_or_ba_code_hash() { let ok_ba_arg = basic_app().get_matches_from_safe(&[ "ckb", "init", "--ba-message", "0x00", "--ba-arg", "0x00", ]); let ok_ba_code_hash = basic_app().get_matches_from_safe(&[ "ckb", "init", "--ba-message", "0x00", "--ba-code-hash", "0x00", ]); let err = basic_app().get_matches_from_safe(&["ckb", "init", "--ba-message", "0x00"]); assert!( ok_ba_arg.is_ok(), "--ba-message is ok with --ba-arg, but gets error: {:?}", ok_ba_arg.err() ); assert!( ok_ba_code_hash.is_ok(), "--ba-message is ok with --ba-code-hash, but gets error: {:?}", ok_ba_code_hash.err() ); assert!( err.is_err(), "--ba-message requires --ba-arg or --ba-code-hash" ); let err = err.err().unwrap(); assert_eq!(clap::ErrorKind::MissingRequiredArgument, err.kind); assert!(err .message .contains("The following required arguments were not provided")); assert!(err.message.contains("--ba-arg")); assert!(err.message.contains("--ba-code-hash")); } #[test] fn ba_arg_and_ba_code_hash() { let ok_matches = basic_app().get_matches_from_safe(&[ "ckb", "init", "--ba-code-hash", "0x00", "--ba-arg", "0x00", ]); assert!( ok_matches.is_ok(), "--ba-code-hash is OK with --ba-arg, but gets error: {:?}", ok_matches.err() ); } #[test] fn ba_advanced() { let matches = basic_app() .get_matches_from_safe(&["ckb", "run", "--ba-advanced"]) .unwrap(); let sub_matches = matches.subcommand().1.unwrap(); assert_eq!(1, sub_matches.occurrences_of(ARG_BA_ADVANCED)); } }
33.406463
158
0.53052
23b51bd905be80e3b9f144900ccbb90509271246
603
use rocket::serde::{Deserialize, Serialize}; use sqlx::FromRow; #[derive(Serialize)] pub struct Message { pub message: &'static str, } #[allow(non_snake_case)] #[derive(Clone, Debug, PartialEq, Deserialize, Serialize, FromRow)] #[serde(crate = "rocket::serde")] pub struct Fortune { pub id: i32, pub message: String } #[allow(non_snake_case)] #[derive(Clone, Debug, PartialEq, Deserialize, Serialize, FromRow)] #[serde(crate = "rocket::serde")] pub struct World { pub id: i32, #[sqlx(rename = "randomnumber")] #[serde(rename = "randomNumber")] pub random_number: i32 }
20.793103
67
0.676617
21c57685063b898be64e233d95bf358495753b8c
14,768
// Take a look at the license at the top of the repository in the LICENSE file. use crate::Align; use crate::Container; use crate::IconSize; use crate::Image; use glib::object::{IsA, ObjectExt}; use glib::signal::{connect_raw, SignalHandlerId}; use glib::translate::*; use glib::Cast; use glib::ToValue; use std::boxed::Box as Box_; use std::mem::transmute; pub trait ImageExtManual: 'static { #[doc(alias = "icon-size")] fn icon_size(&self) -> IconSize; #[doc(alias = "icon-size")] fn set_icon_size(&self, icon_size: IconSize); #[doc(alias = "icon-size")] fn connect_icon_size_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<Image>> ImageExtManual for O { fn icon_size(&self) -> IconSize { unsafe { from_glib(self.as_ref().property::<i32>("icon-size")) } } fn set_icon_size(&self, icon_size: IconSize) { self.as_ref() .set_property("icon-size", &icon_size.into_glib()); } fn connect_icon_size_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_icon_size_trampoline<P: IsA<Image>, F: Fn(&P) + 'static>( this: *mut ffi::GtkImage, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(Image::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::icon-size\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_icon_size_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } } impl Image { // rustdoc-stripper-ignore-next /// Creates a new builder-style object to construct a [`Image`]. /// /// This method returns an instance of [`ImageBuilder`] which can be used to create a [`Image`]. pub fn builder() -> ImageBuilder { ImageBuilder::default() } } #[derive(Clone, Default)] // rustdoc-stripper-ignore-next /// A builder for generating a [`Image`]. pub struct ImageBuilder { file: Option<String>, gicon: Option<gio::Icon>, icon_name: Option<String>, icon_size: Option<i32>, pixbuf: Option<gdk_pixbuf::Pixbuf>, pixbuf_animation: Option<gdk_pixbuf::PixbufAnimation>, pixel_size: Option<i32>, resource: Option<String>, surface: Option<cairo::Surface>, use_fallback: Option<bool>, app_paintable: Option<bool>, can_default: Option<bool>, can_focus: Option<bool>, events: Option<gdk::EventMask>, expand: Option<bool>, #[cfg(any(feature = "v3_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v3_20")))] focus_on_click: Option<bool>, halign: Option<Align>, has_default: Option<bool>, has_focus: Option<bool>, has_tooltip: Option<bool>, height_request: Option<i32>, hexpand: Option<bool>, hexpand_set: Option<bool>, is_focus: Option<bool>, margin: Option<i32>, margin_bottom: Option<i32>, margin_end: Option<i32>, margin_start: Option<i32>, margin_top: Option<i32>, name: Option<String>, no_show_all: Option<bool>, opacity: Option<f64>, parent: Option<Container>, receives_default: Option<bool>, sensitive: Option<bool>, tooltip_markup: Option<String>, tooltip_text: Option<String>, valign: Option<Align>, vexpand: Option<bool>, vexpand_set: Option<bool>, visible: Option<bool>, width_request: Option<i32>, } impl ImageBuilder { // rustdoc-stripper-ignore-next /// Create a new [`ImageBuilder`]. pub fn new() -> Self { Self::default() } // rustdoc-stripper-ignore-next /// Build the [`Image`]. pub fn build(self) -> Image { let mut properties: Vec<(&str, &dyn ToValue)> = vec![]; if let Some(ref file) = self.file { properties.push(("file", file)); } if let Some(ref gicon) = self.gicon { properties.push(("gicon", gicon)); } if let Some(ref icon_name) = self.icon_name { properties.push(("icon-name", icon_name)); } if let Some(ref icon_size) = self.icon_size { properties.push(("icon-size", icon_size)); } if let Some(ref pixbuf) = self.pixbuf { properties.push(("pixbuf", pixbuf)); } if let Some(ref pixbuf_animation) = self.pixbuf_animation { properties.push(("pixbuf-animation", pixbuf_animation)); } if let Some(ref pixel_size) = self.pixel_size { properties.push(("pixel-size", pixel_size)); } if let Some(ref resource) = self.resource { properties.push(("resource", resource)); } if let Some(ref surface) = self.surface { properties.push(("surface", surface)); } if let Some(ref use_fallback) = self.use_fallback { properties.push(("use-fallback", use_fallback)); } if let Some(ref app_paintable) = self.app_paintable { properties.push(("app-paintable", app_paintable)); } if let Some(ref can_default) = self.can_default { properties.push(("can-default", can_default)); } if let Some(ref can_focus) = self.can_focus { properties.push(("can-focus", can_focus)); } if let Some(ref events) = self.events { properties.push(("events", events)); } if let Some(ref expand) = self.expand { properties.push(("expand", expand)); } #[cfg(any(feature = "v3_20", feature = "dox"))] if let Some(ref focus_on_click) = self.focus_on_click { properties.push(("focus-on-click", focus_on_click)); } if let Some(ref halign) = self.halign { properties.push(("halign", halign)); } if let Some(ref has_default) = self.has_default { properties.push(("has-default", has_default)); } if let Some(ref has_focus) = self.has_focus { properties.push(("has-focus", has_focus)); } if let Some(ref has_tooltip) = self.has_tooltip { properties.push(("has-tooltip", has_tooltip)); } if let Some(ref height_request) = self.height_request { properties.push(("height-request", height_request)); } if let Some(ref hexpand) = self.hexpand { properties.push(("hexpand", hexpand)); } if let Some(ref hexpand_set) = self.hexpand_set { properties.push(("hexpand-set", hexpand_set)); } if let Some(ref is_focus) = self.is_focus { properties.push(("is-focus", is_focus)); } if let Some(ref margin) = self.margin { properties.push(("margin", margin)); } if let Some(ref margin_bottom) = self.margin_bottom { properties.push(("margin-bottom", margin_bottom)); } if let Some(ref margin_end) = self.margin_end { properties.push(("margin-end", margin_end)); } if let Some(ref margin_start) = self.margin_start { properties.push(("margin-start", margin_start)); } if let Some(ref margin_top) = self.margin_top { properties.push(("margin-top", margin_top)); } if let Some(ref name) = self.name { properties.push(("name", name)); } if let Some(ref no_show_all) = self.no_show_all { properties.push(("no-show-all", no_show_all)); } if let Some(ref opacity) = self.opacity { properties.push(("opacity", opacity)); } if let Some(ref parent) = self.parent { properties.push(("parent", parent)); } if let Some(ref receives_default) = self.receives_default { properties.push(("receives-default", receives_default)); } if let Some(ref sensitive) = self.sensitive { properties.push(("sensitive", sensitive)); } if let Some(ref tooltip_markup) = self.tooltip_markup { properties.push(("tooltip-markup", tooltip_markup)); } if let Some(ref tooltip_text) = self.tooltip_text { properties.push(("tooltip-text", tooltip_text)); } if let Some(ref valign) = self.valign { properties.push(("valign", valign)); } if let Some(ref vexpand) = self.vexpand { properties.push(("vexpand", vexpand)); } if let Some(ref vexpand_set) = self.vexpand_set { properties.push(("vexpand-set", vexpand_set)); } if let Some(ref visible) = self.visible { properties.push(("visible", visible)); } if let Some(ref width_request) = self.width_request { properties.push(("width-request", width_request)); } glib::Object::new::<Image>(&properties).expect("Failed to create an instance of Image") } pub fn file(mut self, file: &str) -> Self { self.file = Some(file.to_string()); self } pub fn gicon<P: IsA<gio::Icon>>(mut self, gicon: &P) -> Self { self.gicon = Some(gicon.clone().upcast()); self } pub fn icon_name(mut self, icon_name: &str) -> Self { self.icon_name = Some(icon_name.to_string()); self } pub fn icon_size(mut self, icon_size: IconSize) -> Self { self.icon_size = Some(icon_size.into_glib()); self } pub fn pixbuf(mut self, pixbuf: &gdk_pixbuf::Pixbuf) -> Self { self.pixbuf = Some(pixbuf.clone()); self } pub fn pixbuf_animation<P: IsA<gdk_pixbuf::PixbufAnimation>>( mut self, pixbuf_animation: &P, ) -> Self { self.pixbuf_animation = Some(pixbuf_animation.clone().upcast()); self } pub fn pixel_size(mut self, pixel_size: i32) -> Self { self.pixel_size = Some(pixel_size); self } pub fn resource(mut self, resource: &str) -> Self { self.resource = Some(resource.to_string()); self } pub fn surface(mut self, surface: &cairo::Surface) -> Self { self.surface = Some(surface.clone()); self } pub fn use_fallback(mut self, use_fallback: bool) -> Self { self.use_fallback = Some(use_fallback); self } pub fn app_paintable(mut self, app_paintable: bool) -> Self { self.app_paintable = Some(app_paintable); self } pub fn can_default(mut self, can_default: bool) -> Self { self.can_default = Some(can_default); self } pub fn can_focus(mut self, can_focus: bool) -> Self { self.can_focus = Some(can_focus); self } pub fn events(mut self, events: gdk::EventMask) -> Self { self.events = Some(events); self } pub fn expand(mut self, expand: bool) -> Self { self.expand = Some(expand); self } #[cfg(any(feature = "v3_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v3_20")))] pub fn focus_on_click(mut self, focus_on_click: bool) -> Self { self.focus_on_click = Some(focus_on_click); self } pub fn halign(mut self, halign: Align) -> Self { self.halign = Some(halign); self } pub fn has_default(mut self, has_default: bool) -> Self { self.has_default = Some(has_default); self } pub fn has_focus(mut self, has_focus: bool) -> Self { self.has_focus = Some(has_focus); self } pub fn has_tooltip(mut self, has_tooltip: bool) -> Self { self.has_tooltip = Some(has_tooltip); self } pub fn height_request(mut self, height_request: i32) -> Self { self.height_request = Some(height_request); self } pub fn hexpand(mut self, hexpand: bool) -> Self { self.hexpand = Some(hexpand); self } pub fn hexpand_set(mut self, hexpand_set: bool) -> Self { self.hexpand_set = Some(hexpand_set); self } #[allow(clippy::wrong_self_convention)] pub fn is_focus(mut self, is_focus: bool) -> Self { self.is_focus = Some(is_focus); self } pub fn margin(mut self, margin: i32) -> Self { self.margin = Some(margin); self } pub fn margin_bottom(mut self, margin_bottom: i32) -> Self { self.margin_bottom = Some(margin_bottom); self } pub fn margin_end(mut self, margin_end: i32) -> Self { self.margin_end = Some(margin_end); self } pub fn margin_start(mut self, margin_start: i32) -> Self { self.margin_start = Some(margin_start); self } pub fn margin_top(mut self, margin_top: i32) -> Self { self.margin_top = Some(margin_top); self } pub fn name(mut self, name: &str) -> Self { self.name = Some(name.to_string()); self } pub fn no_show_all(mut self, no_show_all: bool) -> Self { self.no_show_all = Some(no_show_all); self } pub fn opacity(mut self, opacity: f64) -> Self { self.opacity = Some(opacity); self } pub fn parent<P: IsA<Container>>(mut self, parent: &P) -> Self { self.parent = Some(parent.clone().upcast()); self } pub fn receives_default(mut self, receives_default: bool) -> Self { self.receives_default = Some(receives_default); self } pub fn sensitive(mut self, sensitive: bool) -> Self { self.sensitive = Some(sensitive); self } pub fn tooltip_markup(mut self, tooltip_markup: &str) -> Self { self.tooltip_markup = Some(tooltip_markup.to_string()); self } pub fn tooltip_text(mut self, tooltip_text: &str) -> Self { self.tooltip_text = Some(tooltip_text.to_string()); self } pub fn valign(mut self, valign: Align) -> Self { self.valign = Some(valign); self } pub fn vexpand(mut self, vexpand: bool) -> Self { self.vexpand = Some(vexpand); self } pub fn vexpand_set(mut self, vexpand_set: bool) -> Self { self.vexpand_set = Some(vexpand_set); self } pub fn visible(mut self, visible: bool) -> Self { self.visible = Some(visible); self } pub fn width_request(mut self, width_request: i32) -> Self { self.width_request = Some(width_request); self } }
31.02521
100
0.578345
9c43cbc67406cc0639c0bab2a35dacc8ca5c5b29
3,417
// بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيم // This file is part of Setheum. // Copyright (C) 2019-2021 Setheum Labs. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // 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 <https://www.gnu.org/licenses/>. use codec::{Decode, Encode}; use sp_runtime::{ traits::{Lazy, Verify}, AccountId32, MultiSigner, RuntimeDebug, }; use sp_core::{crypto::Public, ecdsa, ed25519, sr25519}; use sp_std::{convert::TryFrom, prelude::*}; #[derive(Eq, PartialEq, Clone, Encode, Decode, RuntimeDebug)] pub enum SetheumMultiSignature { /// An Ed25519 signature. Ed25519(ed25519::Signature), /// An Sr25519 signature. Sr25519(sr25519::Signature), /// An ECDSA/SECP256k1 signature. Ecdsa(ecdsa::Signature), // An Ethereum compatible SECP256k1 signature. Ethereum([u8; 65]), // An Ethereum SECP256k1 signature using Eip712 for message encoding. SetheumEip712([u8; 65]), } impl From<ed25519::Signature> for SetheumMultiSignature { fn from(x: ed25519::Signature) -> Self { Self::Ed25519(x) } } impl TryFrom<SetheumMultiSignature> for ed25519::Signature { type Error = (); fn try_from(m: SetheumMultiSignature) -> Result<Self, Self::Error> { if let SetheumMultiSignature::Ed25519(x) = m { Ok(x) } else { Err(()) } } } impl From<sr25519::Signature> for SetheumMultiSignature { fn from(x: sr25519::Signature) -> Self { Self::Sr25519(x) } } impl TryFrom<SetheumMultiSignature> for sr25519::Signature { type Error = (); fn try_from(m: SetheumMultiSignature) -> Result<Self, Self::Error> { if let SetheumMultiSignature::Sr25519(x) = m { Ok(x) } else { Err(()) } } } impl From<ecdsa::Signature> for SetheumMultiSignature { fn from(x: ecdsa::Signature) -> Self { Self::Ecdsa(x) } } impl TryFrom<SetheumMultiSignature> for ecdsa::Signature { type Error = (); fn try_from(m: SetheumMultiSignature) -> Result<Self, Self::Error> { if let SetheumMultiSignature::Ecdsa(x) = m { Ok(x) } else { Err(()) } } } impl Default for SetheumMultiSignature { fn default() -> Self { Self::Ed25519(Default::default()) } } impl Verify for SetheumMultiSignature { type Signer = MultiSigner; fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &AccountId32) -> bool { match (self, signer) { (Self::Ed25519(ref sig), who) => sig.verify(msg, &ed25519::Public::from_slice(who.as_ref())), (Self::Sr25519(ref sig), who) => sig.verify(msg, &sr25519::Public::from_slice(who.as_ref())), (Self::Ecdsa(ref sig), who) => { let m = sp_io::hashing::blake2_256(msg.get()); match sp_io::crypto::secp256k1_ecdsa_recover_compressed(sig.as_ref(), &m) { Ok(pubkey) => &sp_io::hashing::blake2_256(pubkey.as_ref()) == <dyn AsRef<[u8; 32]>>::as_ref(who), _ => false, } } _ => false, // Arbitrary message verification is not supported } } }
28.714286
102
0.689786
619573765c2877a4fbe4726055f1f58acbfd6467
13,284
//! Provides a automatically resized orthographic camera. use amethyst_core::cgmath::Ortho; use amethyst_core::specs::{ Component, DenseVecStorage, Join, ReadExpect, ReadStorage, System, WriteStorage, }; use amethyst_core::Axis2; use amethyst_renderer::{Camera, ScreenDimensions}; /// The coordinates that `CameraOrtho` will keep visible in the window #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Copy)] pub struct CameraOrthoWorldCoordinates { /// Left x coordinate pub left: f32, /// Right x coordinate pub right: f32, /// Bottom y coordinate pub bottom: f32, /// Top y coordinate pub top: f32, } impl CameraOrthoWorldCoordinates { /// Creates coordinates with (0,0) at the bottom left, and (1,1) at the top right pub fn normalized() -> CameraOrthoWorldCoordinates { CameraOrthoWorldCoordinates { left: 0.0, right: 1.0, bottom: 0.0, top: 1.0, } } /// Returns width / height of the desired camera coordinates. pub fn aspect_ratio(&self) -> f32 { self.width() / self.height() } /// Returns size of the x-axis. pub fn width(&self) -> f32 { self.right - self.left } /// Returns size of the y-axis. pub fn height(&self) -> f32 { self.top - self.bottom } } impl Default for CameraOrthoWorldCoordinates { fn default() -> Self { Self::normalized() } } /// `Component` attached to the camera's entity that allows automatically adjusting the camera's matrix according /// to preferences in the "mode" and "world_coordinates" fields. /// It adjusts the camera so that the camera's world coordinates are always visible. /// You must add the `CameraNormalOrthoSystem` to your dispatcher for this to take effect (no dependencies required). #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct CameraOrtho { /// How the camera's matrix is changed when the window's aspect ratio changes. /// See `CameraNormalizeMode` for more info. pub mode: CameraNormalizeMode, /// The world coordinates that this camera will keep visible as the window size changes pub world_coordinates: CameraOrthoWorldCoordinates, } impl CameraOrtho { /// Creates a Camera that maintains window coordinates of (0,0) in the bottom left, and (1,1) at the top right pub fn normalized(mode: CameraNormalizeMode) -> CameraOrtho { CameraOrtho { mode, world_coordinates: Default::default(), } } /// Get the camera matrix offsets according to the specified options. pub fn camera_offsets(&self, window_aspect_ratio: f32) -> (f32, f32, f32, f32) { self.mode .camera_offsets(window_aspect_ratio, &self.world_coordinates) } } impl Component for CameraOrtho { type Storage = DenseVecStorage<Self>; } /// Settings that decide how to scale the camera's matrix when the aspect ratio changes. #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq)] pub enum CameraNormalizeMode { /// Using the aspect ratio from the world coordinates for this camera, tries to adjust the matrix values of the /// camera so that the orthogonal direction to the stretch_direction always have a world size of 1. /// /// This means that the direction opposite to stretch_direction /// will always be between 0.0 to 1.0 in world coordinates. /// Scene space can be lost (or gained) on the specified stretch_direction however. /// /// Example (using a normalized ortho camera): /// If you use Lossy with the stretch_direction of Axis::X, /// this means that a mesh or image going from the world coordinates (0, 0) to (1, 1) /// would take the whole screen size if the window dimension width is equal to its height. /// /// If the window gets stretched on the x axis, the mesh or image will stay centered and /// the background clear color (or things that were previously outside of the window) will now /// be shown on the left and right sides of the mesh or image. /// /// If you shrink the window on the x axis instead, the left and right parts of the images will go /// off screen and will NOT be shown. /// /// If you want the whole world space between (0, 0) and (1, 1) to be shown at ALL times, consider using /// `CameraNormalizeMode::Contain` instead. Lossy { /// The direction along which the camera will stretch and possibly have a length not equal /// to one. stretch_direction: Axis2, }, /// Scales the render dynamically to ensure the `CameraOrthoWorldCoordinates` are always visible. /// There may still be additional space in addition to the specific coordinates, but it will never hide anything. /// /// If you have a non-default `Transform` on your camera, /// it will just translate those coordinates by the translation of the `Transform`. Contain, } impl CameraNormalizeMode { /// Get the camera matrix offsets according to the specified options. fn camera_offsets( &self, window_aspect_ratio: f32, desired_coordinates: &CameraOrthoWorldCoordinates, ) -> (f32, f32, f32, f32) { match self { &CameraNormalizeMode::Lossy { ref stretch_direction, } => match stretch_direction { Axis2::X => CameraNormalizeMode::lossy_x(window_aspect_ratio, desired_coordinates), Axis2::Y => CameraNormalizeMode::lossy_y(window_aspect_ratio, desired_coordinates), }, &CameraNormalizeMode::Contain => { let desired_aspect_ratio = desired_coordinates.aspect_ratio(); if window_aspect_ratio > desired_aspect_ratio { CameraNormalizeMode::lossy_x(window_aspect_ratio, desired_coordinates) } else if window_aspect_ratio < desired_aspect_ratio { CameraNormalizeMode::lossy_y(window_aspect_ratio, desired_coordinates) } else { ( desired_coordinates.left, desired_coordinates.right, desired_coordinates.bottom, desired_coordinates.top, ) } } } } fn lossy_x( window_aspect_ratio: f32, desired_coordinates: &CameraOrthoWorldCoordinates, ) -> (f32, f32, f32, f32) { let offset = (window_aspect_ratio * desired_coordinates.height() - desired_coordinates.width()) / 2.0; ( desired_coordinates.left - offset, desired_coordinates.right + offset, desired_coordinates.bottom, desired_coordinates.top, ) } fn lossy_y( window_aspect_ratio: f32, desired_coordinates: &CameraOrthoWorldCoordinates, ) -> (f32, f32, f32, f32) { let offset = (desired_coordinates.width() / window_aspect_ratio - desired_coordinates.height()) / 2.0; ( desired_coordinates.left, desired_coordinates.right, desired_coordinates.bottom - offset, desired_coordinates.top + offset, ) } } impl Default for CameraNormalizeMode { fn default() -> Self { CameraNormalizeMode::Contain } } /// System that automatically changes the camera matrix according to the settings in /// the `CameraOrtho` attached to the camera entity. #[derive(Default)] pub struct CameraOrthoSystem { aspect_ratio_cache: f32, } impl<'a> System<'a> for CameraOrthoSystem { type SystemData = ( ReadExpect<'a, ScreenDimensions>, WriteStorage<'a, Camera>, ReadStorage<'a, CameraOrtho>, ); fn run(&mut self, (dimensions, mut cameras, ortho_cameras): Self::SystemData) { let aspect = dimensions.aspect_ratio(); if aspect != self.aspect_ratio_cache { self.aspect_ratio_cache = aspect; for (mut camera, ortho_camera) in (&mut cameras, &ortho_cameras).join() { let offsets = ortho_camera.camera_offsets(aspect); // Find the previous near and far would require // solving a linear system of two equation from // https://docs.rs/cgmath/0.16.1/src/cgmath/projection.rs.html#246-278 camera.proj = Ortho { left: offsets.0, right: offsets.1, bottom: offsets.2, top: offsets.3, near: 0.1, far: 2000.0, }.into(); } } } } #[cfg(test)] mod test { use super::Axis2; use ortho_camera::{CameraNormalizeMode, CameraOrtho, CameraOrthoWorldCoordinates}; // TODO: Disabled until someone fixes the formula (if possible). /*#[test] fn near_far_from_camera() { use amethyst_core::cgmath::{Ortho, Matrix4}; let mat4 = Matrix4::from(Ortho { left: 0.0, right: 1.0, bottom: 0.0, top: 1.0, near: 0.1, far: 2000.0, }); let x = mat4.z.z; // c2r2 let y = mat4.w.z; // c3r2 let near = (y + 1.0) / x; let far = (x - 1.0) / y; assert_ulps_eq!((near as f32 * 100.0).round() / 100.0, 0.1); assert_ulps_eq!((far as f32 * 100.0).round() / 100.0, 2000.0); }*/ #[test] fn normal_camera_large_lossy_horizontal() { let aspect = 2.0 / 1.0; let cam = CameraOrtho::normalized(CameraNormalizeMode::Lossy { stretch_direction: Axis2::X, }); assert_eq!((-0.5, 1.5, 0.0, 1.0), cam.camera_offsets(aspect)); } #[test] fn normal_camera_large_lossy_vertical() { let aspect = 2.0 / 1.0; let cam = CameraOrtho::normalized(CameraNormalizeMode::Lossy { stretch_direction: Axis2::Y, }); assert_eq!((0.0, 1.0, 0.25, 0.75), cam.camera_offsets(aspect)); } #[test] fn normal_camera_high_lossy_horizontal() { let aspect = 1.0 / 2.0; let cam = CameraOrtho::normalized(CameraNormalizeMode::Lossy { stretch_direction: Axis2::X, }); assert_eq!((0.25, 0.75, 0.0, 1.0), cam.camera_offsets(aspect)); } #[test] fn normal_camera_high_lossy_vertical() { let aspect = 1.0 / 2.0; let cam = CameraOrtho::normalized(CameraNormalizeMode::Lossy { stretch_direction: Axis2::Y, }); assert_eq!((0.0, 1.0, -0.5, 1.5), cam.camera_offsets(aspect)); } #[test] fn normal_camera_square_lossy_horizontal() { let aspect = 1.0 / 1.0; let cam = CameraOrtho::normalized(CameraNormalizeMode::Lossy { stretch_direction: Axis2::X, }); assert_eq!((0.0, 1.0, 0.0, 1.0), cam.camera_offsets(aspect)); } #[test] fn normal_camera_square_lossy_vertical() { let aspect = 1.0 / 1.0; let cam = CameraOrtho::normalized(CameraNormalizeMode::Lossy { stretch_direction: Axis2::Y, }); assert_eq!((0.0, 1.0, 0.0, 1.0), cam.camera_offsets(aspect)); } #[test] fn normal_camera_large_contain() { let aspect = 2.0 / 1.0; let cam = CameraOrtho::normalized(CameraNormalizeMode::Contain); assert_eq!((-0.5, 1.5, 0.0, 1.0), cam.camera_offsets(aspect)); } #[test] fn normal_camera_high_contain() { let aspect = 1.0 / 2.0; let cam = CameraOrtho::normalized(CameraNormalizeMode::Contain); assert_eq!((0.0, 1.0, -0.5, 1.5), cam.camera_offsets(aspect)); } #[test] fn normal_camera_square_contain() { let aspect = 1.0 / 1.0; let cam = CameraOrtho::normalized(CameraNormalizeMode::Contain); assert_eq!((0.0, 1.0, 0.0, 1.0), cam.camera_offsets(aspect)); } #[test] fn camera_square_contain() { let aspect = 1.0 / 1.0; let cam = CameraOrtho { mode: CameraNormalizeMode::Contain, world_coordinates: CameraOrthoWorldCoordinates { left: 0.0, right: 2.0, top: 2.0, bottom: 0.0, }, }; assert_eq!((0.0, 2.0, 0.0, 2.0), cam.camera_offsets(aspect)); } #[test] fn camera_large_contain() { let aspect = 2.0 / 1.0; let cam = CameraOrtho { mode: CameraNormalizeMode::Contain, world_coordinates: CameraOrthoWorldCoordinates { left: 0.0, right: 2.0, top: 2.0, bottom: 0.0, }, }; assert_eq!((-1.0, 3.0, 0.0, 2.0), cam.camera_offsets(aspect)); } #[test] fn camera_high_contain() { let aspect = 1.0 / 2.0; let cam = CameraOrtho { mode: CameraNormalizeMode::Contain, world_coordinates: CameraOrthoWorldCoordinates { left: 0.0, right: 2.0, top: 2.0, bottom: 0.0, }, }; assert_eq!((0.0, 2.0, -1.0, 3.0), cam.camera_offsets(aspect)); } }
35.050132
117
0.599368
ccefc5f1b6c339a5b45675601e92fc5d56c78431
30,938
//! Internal details to be used by instance.rs only use std::borrow::{Borrow, BorrowMut}; use std::ptr::NonNull; use std::sync::{Arc, RwLock}; use wasmer::{HostEnvInitError, Instance as WasmerInstance, Memory, Val, WasmerEnv}; use wasmer_middlewares::metering::{get_remaining_points, set_remaining_points, MeteringPoints}; use crate::backend::{BackendApi, GasInfo, Querier, Storage}; use crate::errors::{VmError, VmResult}; /// Never can never be instantiated. /// Replace this with the [never primitive type](https://doc.rust-lang.org/std/primitive.never.html) when stable. #[derive(Debug)] pub enum Never {} /** gas config data */ #[derive(Clone, PartialEq, Debug)] pub struct GasConfig { /// Gas costs of VM (not Backend) provided functionality /// secp256k1 signature verification cost pub secp256k1_verify_cost: u64, /// secp256k1 public key recovery cost pub secp256k1_recover_pubkey_cost: u64, /// ed25519 signature verification cost pub ed25519_verify_cost: u64, /// ed25519 batch signature verification cost pub ed25519_batch_verify_cost: u64, /// ed25519 batch signature verification cost (single public key) pub ed25519_batch_verify_one_pubkey_cost: u64, } impl GasConfig { // Base crypto-verify gas cost: 1000 Cosmos SDK * 100 CosmWasm factor const BASE_CRYPTO_COST: u64 = 100_000; // secp256k1 cost factor (reference) const SECP256K1_VERIFY_FACTOR: (u64, u64) = (154, 154); // ~154 us in crypto benchmarks // Gas cost factors, relative to secp256k1_verify cost const SECP256K1_RECOVER_PUBKEY_FACTOR: (u64, u64) = (162, 154); // 162 us / 154 us ~ 1.05 const ED25519_VERIFY_FACTOR: (u64, u64) = (63, 154); // 63 us / 154 us ~ 0.41 // Gas cost factors, relative to ed25519_verify cost // From https://docs.rs/ed25519-zebra/2.2.0/ed25519_zebra/batch/index.html const ED255219_BATCH_VERIFY_FACTOR: (u64, u64) = ( GasConfig::ED25519_VERIFY_FACTOR.0, GasConfig::ED25519_VERIFY_FACTOR.1 * 2, ); // 0.41 / 2. ~ 0.21 const ED255219_BATCH_VERIFY_ONE_PUBKEY_FACTOR: (u64, u64) = ( GasConfig::ED25519_VERIFY_FACTOR.0, GasConfig::ED25519_VERIFY_FACTOR.1 * 4, ); // 0.41 / 4. ~ 0.1 fn calc_crypto_cost(factor: (u64, u64)) -> u64 { (GasConfig::BASE_CRYPTO_COST * factor.0) / factor.1 } } impl Default for GasConfig { fn default() -> Self { Self { secp256k1_verify_cost: GasConfig::calc_crypto_cost(GasConfig::SECP256K1_VERIFY_FACTOR), secp256k1_recover_pubkey_cost: GasConfig::calc_crypto_cost( GasConfig::SECP256K1_RECOVER_PUBKEY_FACTOR, ), ed25519_verify_cost: GasConfig::calc_crypto_cost(GasConfig::ED25519_VERIFY_FACTOR), ed25519_batch_verify_cost: GasConfig::calc_crypto_cost( GasConfig::ED255219_BATCH_VERIFY_FACTOR, ), ed25519_batch_verify_one_pubkey_cost: GasConfig::calc_crypto_cost( GasConfig::ED255219_BATCH_VERIFY_ONE_PUBKEY_FACTOR, ), } } } /** context data **/ #[derive(Clone, PartialEq, Debug, Default)] pub struct GasState { /// Gas limit for the computation, including internally and externally used gas. /// This is set when the Environment is created and never mutated. pub gas_limit: u64, /// Tracking the gas used in the Cosmos SDK, in CosmWasm gas units. pub externally_used_gas: u64, } impl GasState { fn with_limit(gas_limit: u64) -> Self { Self { gas_limit, externally_used_gas: 0, } } } /// A environment that provides access to the ContextData. /// The environment is clonable but clones access the same underlying data. pub struct Environment<A: BackendApi, S: Storage, Q: Querier> { pub api: A, pub print_debug: bool, pub gas_config: GasConfig, data: Arc<RwLock<ContextData<S, Q>>>, } unsafe impl<A: BackendApi, S: Storage, Q: Querier> Send for Environment<A, S, Q> {} unsafe impl<A: BackendApi, S: Storage, Q: Querier> Sync for Environment<A, S, Q> {} impl<A: BackendApi, S: Storage, Q: Querier> Clone for Environment<A, S, Q> { fn clone(&self) -> Self { Environment { api: self.api, print_debug: self.print_debug, gas_config: self.gas_config.clone(), data: self.data.clone(), } } } impl<A: BackendApi, S: Storage, Q: Querier> WasmerEnv for Environment<A, S, Q> { fn init_with_instance(&mut self, _instance: &WasmerInstance) -> Result<(), HostEnvInitError> { Ok(()) } } impl<A: BackendApi, S: Storage, Q: Querier> Environment<A, S, Q> { pub fn new(api: A, gas_limit: u64, print_debug: bool) -> Self { Environment { api, print_debug, gas_config: GasConfig::default(), data: Arc::new(RwLock::new(ContextData::new(gas_limit))), } } fn with_context_data_mut<C, R>(&self, callback: C) -> R where C: FnOnce(&mut ContextData<S, Q>) -> R, { let mut guard = self.data.as_ref().write().unwrap(); let context_data = guard.borrow_mut(); callback(context_data) } fn with_context_data<C, R>(&self, callback: C) -> R where C: FnOnce(&ContextData<S, Q>) -> R, { let guard = self.data.as_ref().read().unwrap(); let context_data = guard.borrow(); callback(context_data) } pub fn with_gas_state<C, R>(&self, callback: C) -> R where C: FnOnce(&GasState) -> R, { self.with_context_data(|context_data| callback(&context_data.gas_state)) } pub fn with_gas_state_mut<C, R>(&self, callback: C) -> R where C: FnOnce(&mut GasState) -> R, { self.with_context_data_mut(|context_data| callback(&mut context_data.gas_state)) } pub fn with_wasmer_instance<C, R>(&self, callback: C) -> VmResult<R> where C: FnOnce(&WasmerInstance) -> VmResult<R>, { self.with_context_data(|context_data| match context_data.wasmer_instance { Some(instance_ptr) => { let instance_ref = unsafe { instance_ptr.as_ref() }; callback(instance_ref) } None => Err(VmError::uninitialized_context_data("wasmer_instance")), }) } /// Calls a function with the given name and arguments. /// The number of return values is variable and controlled by the guest. /// Usually we expect 0 or 1 return values. Use [`Self::call_function0`] /// or [`Self::call_function1`] to ensure the number of return values is checked. fn call_function(&self, name: &str, args: &[Val]) -> VmResult<Box<[Val]>> { // Clone function before calling it to avoid dead locks let func = self.with_wasmer_instance(|instance| { let func = instance.exports.get_function(name)?; Ok(func.clone()) })?; func.call(args).map_err(|runtime_err| -> VmError { self.with_wasmer_instance::<_, Never>(|instance| { let err: VmError = match get_remaining_points(instance) { MeteringPoints::Remaining(_) => VmError::from(runtime_err), MeteringPoints::Exhausted => VmError::gas_depletion(), }; Err(err) }) .unwrap_err() // with_wasmer_instance can only succeed if the callback succeeds }) } pub fn call_function0(&self, name: &str, args: &[Val]) -> VmResult<()> { let result = self.call_function(name, args)?; let expected = 0; let actual = result.len(); if actual != expected { return Err(VmError::result_mismatch(name, expected, actual)); } Ok(()) } pub fn call_function1(&self, name: &str, args: &[Val]) -> VmResult<Val> { let result = self.call_function(name, args)?; let expected = 1; let actual = result.len(); if actual != expected { return Err(VmError::result_mismatch(name, expected, actual)); } Ok(result[0].clone()) } pub fn with_storage_from_context<C, T>(&self, callback: C) -> VmResult<T> where C: FnOnce(&mut S) -> VmResult<T>, { self.with_context_data_mut(|context_data| match context_data.storage.as_mut() { Some(data) => callback(data), None => Err(VmError::uninitialized_context_data("storage")), }) } pub fn with_querier_from_context<C, T>(&self, callback: C) -> VmResult<T> where C: FnOnce(&mut Q) -> VmResult<T>, { self.with_context_data_mut(|context_data| match context_data.querier.as_mut() { Some(querier) => callback(querier), None => Err(VmError::uninitialized_context_data("querier")), }) } /// Creates a back reference from a contact to its partent instance pub fn set_wasmer_instance(&self, wasmer_instance: Option<NonNull<WasmerInstance>>) { self.with_context_data_mut(|context_data| { context_data.wasmer_instance = wasmer_instance; }); } /// Returns true iff the storage is set to readonly mode pub fn is_storage_readonly(&self) -> bool { self.with_context_data(|context_data| context_data.storage_readonly) } pub fn set_storage_readonly(&self, new_value: bool) { self.with_context_data_mut(|context_data| { context_data.storage_readonly = new_value; }) } pub fn get_gas_left(&self) -> u64 { self.with_wasmer_instance(|instance| { Ok(match get_remaining_points(instance) { MeteringPoints::Remaining(count) => count, MeteringPoints::Exhausted => 0, }) }) .expect("Wasmer instance is not set. This is a bug in the lifecycle.") } pub fn set_gas_left(&self, new_value: u64) { self.with_wasmer_instance(|instance| { set_remaining_points(instance, new_value); Ok(()) }) .expect("Wasmer instance is not set. This is a bug in the lifecycle.") } /// Decreases gas left by the given amount. /// If the amount exceeds the available gas, the remaining gas is set to 0 and /// an VmError::GasDepletion error is returned. #[allow(unused)] // used in tests pub fn decrease_gas_left(&self, amount: u64) -> VmResult<()> { self.with_wasmer_instance(|instance| { let remaining = match get_remaining_points(instance) { MeteringPoints::Remaining(count) => count, MeteringPoints::Exhausted => 0, }; if amount > remaining { set_remaining_points(instance, 0); Err(VmError::gas_depletion()) } else { set_remaining_points(instance, remaining - amount); Ok(()) } }) } pub fn memory(&self) -> Memory { self.with_wasmer_instance(|instance| { let first: Option<Memory> = instance .exports .iter() .memories() .next() .map(|pair| pair.1.clone()); // Every contract in CosmWasm must have exactly one exported memory. // This is ensured by `check_wasm`/`check_wasm_memories`, which is called for every // contract added to the Cache as well as in integration tests. // It is possible to bypass this check when using `Instance::from_code` but then you // learn the hard way when this panics, or when trying to upload the contract to chain. let memory = first.expect("A contract must have exactly one exported memory."); Ok(memory) }) .expect("Wasmer instance is not set. This is a bug in the lifecycle.") } /// Moves owned instances of storage and querier into the env. /// Should be followed by exactly one call to move_out when the instance is finished. pub fn move_in(&self, storage: S, querier: Q) { self.with_context_data_mut(|context_data| { context_data.storage = Some(storage); context_data.querier = Some(querier); }); } /// Returns the original storage and querier as owned instances, and closes any remaining /// iterators. This is meant to be called when recycling the instance. pub fn move_out(&self) -> (Option<S>, Option<Q>) { self.with_context_data_mut(|context_data| { (context_data.storage.take(), context_data.querier.take()) }) } } pub struct ContextData<S: Storage, Q: Querier> { gas_state: GasState, storage: Option<S>, storage_readonly: bool, querier: Option<Q>, /// A non-owning link to the wasmer instance wasmer_instance: Option<NonNull<WasmerInstance>>, } impl<S: Storage, Q: Querier> ContextData<S, Q> { pub fn new(gas_limit: u64) -> Self { ContextData::<S, Q> { gas_state: GasState::with_limit(gas_limit), storage: None, storage_readonly: true, querier: None, wasmer_instance: None, } } } pub fn process_gas_info<A: BackendApi, S: Storage, Q: Querier>( env: &Environment<A, S, Q>, info: GasInfo, ) -> VmResult<()> { let gas_left = env.get_gas_left(); let new_limit = env.with_gas_state_mut(|gas_state| { gas_state.externally_used_gas += info.externally_used; // These lines reduce the amount of gas available to wasmer // so it can not consume gas that was consumed externally. gas_left .saturating_sub(info.externally_used) .saturating_sub(info.cost) }); // This tells wasmer how much more gas it can consume from this point in time. env.set_gas_left(new_limit); if info.externally_used + info.cost > gas_left { Err(VmError::gas_depletion()) } else { Ok(()) } } #[cfg(test)] mod tests { use super::*; use crate::backend::Storage; use crate::conversion::ref_to_u32; use crate::errors::VmError; use crate::size::Size; use crate::testing::{MockApi, MockQuerier, MockStorage}; use crate::wasm_backend::compile; use cosmwasm_std::{ coins, from_binary, to_vec, AllBalanceResponse, BankQuery, Empty, QueryRequest, }; use wasmer::{imports, Function, Instance as WasmerInstance}; static CONTRACT: &[u8] = include_bytes!("../testdata/hackatom.wasm"); // prepared data const INIT_KEY: &[u8] = b"foo"; const INIT_VALUE: &[u8] = b"bar"; // this account has some coins const INIT_ADDR: &str = "someone"; const INIT_AMOUNT: u128 = 500; const INIT_DENOM: &str = "TOKEN"; const TESTING_GAS_LIMIT: u64 = 500_000; const DEFAULT_QUERY_GAS_LIMIT: u64 = 300_000; const TESTING_MEMORY_LIMIT: Option<Size> = Some(Size::mebi(16)); fn make_instance( gas_limit: u64, ) -> ( Environment<MockApi, MockStorage, MockQuerier>, Box<WasmerInstance>, ) { let env = Environment::new(MockApi::default(), gas_limit, false); let module = compile(&CONTRACT, TESTING_MEMORY_LIMIT).unwrap(); let store = module.store(); // we need stubs for all required imports let import_obj = imports! { "env" => { "db_read" => Function::new_native(&store, |_a: u32| -> u32 { 0 }), "db_write" => Function::new_native(&store, |_a: u32, _b: u32| {}), "db_remove" => Function::new_native(&store, |_a: u32| {}), "db_scan" => Function::new_native(&store, |_a: u32, _b: u32, _c: i32| -> u32 { 0 }), "db_next" => Function::new_native(&store, |_a: u32| -> u32 { 0 }), "query_chain" => Function::new_native(&store, |_a: u32| -> u32 { 0 }), "addr_validate" => Function::new_native(&store, |_a: u32| -> u32 { 0 }), "addr_canonicalize" => Function::new_native(&store, |_a: u32, _b: u32| -> u32 { 0 }), "addr_humanize" => Function::new_native(&store, |_a: u32, _b: u32| -> u32 { 0 }), "secp256k1_verify" => Function::new_native(&store, |_a: u32, _b: u32, _c: u32| -> u32 { 0 }), "secp256k1_recover_pubkey" => Function::new_native(&store, |_a: u32, _b: u32, _c: u32| -> u64 { 0 }), "ed25519_verify" => Function::new_native(&store, |_a: u32, _b: u32, _c: u32| -> u32 { 0 }), "ed25519_batch_verify" => Function::new_native(&store, |_a: u32, _b: u32, _c: u32| -> u32 { 0 }), "debug" => Function::new_native(&store, |_a: u32| {}), }, }; let instance = Box::from(WasmerInstance::new(&module, &import_obj).unwrap()); let instance_ptr = NonNull::from(instance.as_ref()); env.set_wasmer_instance(Some(instance_ptr)); env.set_gas_left(gas_limit); (env, instance) } fn leave_default_data(env: &Environment<MockApi, MockStorage, MockQuerier>) { // create some mock data let mut storage = MockStorage::new(); storage .set(INIT_KEY, INIT_VALUE) .0 .expect("error setting value"); let querier: MockQuerier<Empty> = MockQuerier::new(&[(INIT_ADDR, &coins(INIT_AMOUNT, INIT_DENOM))]); env.move_in(storage, querier); } #[test] fn move_out_works() { let (env, _instance) = make_instance(TESTING_GAS_LIMIT); // empty data on start let (inits, initq) = env.move_out(); assert!(inits.is_none()); assert!(initq.is_none()); // store it on the instance leave_default_data(&env); let (s, q) = env.move_out(); assert!(s.is_some()); assert!(q.is_some()); assert_eq!( s.unwrap().get(INIT_KEY).0.unwrap(), Some(INIT_VALUE.to_vec()) ); // now is empty again let (ends, endq) = env.move_out(); assert!(ends.is_none()); assert!(endq.is_none()); } #[test] fn process_gas_info_works_for_cost() { let (env, _instance) = make_instance(100); assert_eq!(env.get_gas_left(), 100); // Consume all the Gas that we allocated process_gas_info(&env, GasInfo::with_cost(70)).unwrap(); assert_eq!(env.get_gas_left(), 30); process_gas_info(&env, GasInfo::with_cost(4)).unwrap(); assert_eq!(env.get_gas_left(), 26); process_gas_info(&env, GasInfo::with_cost(6)).unwrap(); assert_eq!(env.get_gas_left(), 20); process_gas_info(&env, GasInfo::with_cost(20)).unwrap(); assert_eq!(env.get_gas_left(), 0); // Using one more unit of gas triggers a failure match process_gas_info(&env, GasInfo::with_cost(1)).unwrap_err() { VmError::GasDepletion { .. } => {} err => panic!("unexpected error: {:?}", err), } } #[test] fn process_gas_info_works_for_externally_used() { let (env, _instance) = make_instance(100); assert_eq!(env.get_gas_left(), 100); // Consume all the Gas that we allocated process_gas_info(&env, GasInfo::with_externally_used(70)).unwrap(); assert_eq!(env.get_gas_left(), 30); process_gas_info(&env, GasInfo::with_externally_used(4)).unwrap(); assert_eq!(env.get_gas_left(), 26); process_gas_info(&env, GasInfo::with_externally_used(6)).unwrap(); assert_eq!(env.get_gas_left(), 20); process_gas_info(&env, GasInfo::with_externally_used(20)).unwrap(); assert_eq!(env.get_gas_left(), 0); // Using one more unit of gas triggers a failure match process_gas_info(&env, GasInfo::with_externally_used(1)).unwrap_err() { VmError::GasDepletion { .. } => {} err => panic!("unexpected error: {:?}", err), } } #[test] fn process_gas_info_works_for_cost_and_externally_used() { let (env, _instance) = make_instance(100); assert_eq!(env.get_gas_left(), 100); let gas_state = env.with_gas_state(|gas_state| gas_state.clone()); assert_eq!(gas_state.gas_limit, 100); assert_eq!(gas_state.externally_used_gas, 0); process_gas_info(&env, GasInfo::new(17, 4)).unwrap(); assert_eq!(env.get_gas_left(), 79); let gas_state = env.with_gas_state(|gas_state| gas_state.clone()); assert_eq!(gas_state.gas_limit, 100); assert_eq!(gas_state.externally_used_gas, 4); process_gas_info(&env, GasInfo::new(9, 0)).unwrap(); assert_eq!(env.get_gas_left(), 70); let gas_state = env.with_gas_state(|gas_state| gas_state.clone()); assert_eq!(gas_state.gas_limit, 100); assert_eq!(gas_state.externally_used_gas, 4); process_gas_info(&env, GasInfo::new(0, 70)).unwrap(); assert_eq!(env.get_gas_left(), 0); let gas_state = env.with_gas_state(|gas_state| gas_state.clone()); assert_eq!(gas_state.gas_limit, 100); assert_eq!(gas_state.externally_used_gas, 74); // More cost fail but do not change stats match process_gas_info(&env, GasInfo::new(1, 0)).unwrap_err() { VmError::GasDepletion { .. } => {} err => panic!("unexpected error: {:?}", err), } assert_eq!(env.get_gas_left(), 0); let gas_state = env.with_gas_state(|gas_state| gas_state.clone()); assert_eq!(gas_state.gas_limit, 100); assert_eq!(gas_state.externally_used_gas, 74); // More externally used fails and changes stats match process_gas_info(&env, GasInfo::new(0, 1)).unwrap_err() { VmError::GasDepletion { .. } => {} err => panic!("unexpected error: {:?}", err), } assert_eq!(env.get_gas_left(), 0); let gas_state = env.with_gas_state(|gas_state| gas_state.clone()); assert_eq!(gas_state.gas_limit, 100); assert_eq!(gas_state.externally_used_gas, 75); } #[test] fn process_gas_info_zeros_gas_left_when_exceeded() { // with_externally_used { let (env, _instance) = make_instance(100); let result = process_gas_info(&env, GasInfo::with_externally_used(120)); match result.unwrap_err() { VmError::GasDepletion { .. } => {} err => panic!("unexpected error: {:?}", err), } assert_eq!(env.get_gas_left(), 0); let gas_state = env.with_gas_state(|gas_state| gas_state.clone()); assert_eq!(gas_state.gas_limit, 100); assert_eq!(gas_state.externally_used_gas, 120); } // with_cost { let (env, _instance) = make_instance(100); let result = process_gas_info(&env, GasInfo::with_cost(120)); match result.unwrap_err() { VmError::GasDepletion { .. } => {} err => panic!("unexpected error: {:?}", err), } assert_eq!(env.get_gas_left(), 0); let gas_state = env.with_gas_state(|gas_state| gas_state.clone()); assert_eq!(gas_state.gas_limit, 100); assert_eq!(gas_state.externally_used_gas, 0); } } #[test] fn process_gas_info_works_correctly_with_gas_consumption_in_wasmer() { let (env, _instance) = make_instance(100); assert_eq!(env.get_gas_left(), 100); // Some gas was consumed externally process_gas_info(&env, GasInfo::with_externally_used(50)).unwrap(); assert_eq!(env.get_gas_left(), 50); process_gas_info(&env, GasInfo::with_externally_used(4)).unwrap(); assert_eq!(env.get_gas_left(), 46); // Consume 20 gas directly in wasmer env.decrease_gas_left(20).unwrap(); assert_eq!(env.get_gas_left(), 26); process_gas_info(&env, GasInfo::with_externally_used(6)).unwrap(); assert_eq!(env.get_gas_left(), 20); process_gas_info(&env, GasInfo::with_externally_used(20)).unwrap(); assert_eq!(env.get_gas_left(), 0); // Using one more unit of gas triggers a failure match process_gas_info(&env, GasInfo::with_externally_used(1)).unwrap_err() { VmError::GasDepletion { .. } => {} err => panic!("unexpected error: {:?}", err), } } #[test] fn is_storage_readonly_defaults_to_true() { let (env, _instance) = make_instance(TESTING_GAS_LIMIT); leave_default_data(&env); assert!(env.is_storage_readonly()); } #[test] fn set_storage_readonly_can_change_flag() { let (env, _instance) = make_instance(TESTING_GAS_LIMIT); leave_default_data(&env); // change env.set_storage_readonly(false); assert!(!env.is_storage_readonly()); // still false env.set_storage_readonly(false); assert!(!env.is_storage_readonly()); // change back env.set_storage_readonly(true); assert!(env.is_storage_readonly()); } #[test] fn call_function_works() { let (env, _instance) = make_instance(TESTING_GAS_LIMIT); leave_default_data(&env); let result = env.call_function("allocate", &[10u32.into()]).unwrap(); let ptr = ref_to_u32(&result[0]).unwrap(); assert!(ptr > 0); } #[test] fn call_function_fails_for_missing_instance() { let (env, _instance) = make_instance(TESTING_GAS_LIMIT); leave_default_data(&env); // Clear context's wasmer_instance env.set_wasmer_instance(None); let res = env.call_function("allocate", &[]); match res.unwrap_err() { VmError::UninitializedContextData { kind, .. } => assert_eq!(kind, "wasmer_instance"), err => panic!("Unexpected error: {:?}", err), } } #[test] fn call_function_fails_for_missing_function() { let (env, _instance) = make_instance(TESTING_GAS_LIMIT); leave_default_data(&env); let res = env.call_function("doesnt_exist", &[]); match res.unwrap_err() { VmError::ResolveErr { msg, .. } => { assert_eq!(msg, "Could not get export: Missing export doesnt_exist"); } err => panic!("Unexpected error: {:?}", err), } } #[test] fn call_function0_works() { let (env, _instance) = make_instance(TESTING_GAS_LIMIT); leave_default_data(&env); env.call_function0("interface_version_7", &[]).unwrap(); } #[test] fn call_function0_errors_for_wrong_result_count() { let (env, _instance) = make_instance(TESTING_GAS_LIMIT); leave_default_data(&env); let result = env.call_function0("allocate", &[10u32.into()]); match result.unwrap_err() { VmError::ResultMismatch { function_name, expected, actual, } => { assert_eq!(function_name, "allocate"); assert_eq!(expected, 0); assert_eq!(actual, 1); } err => panic!("unexpected error: {:?}", err), } } #[test] fn call_function1_works() { let (env, _instance) = make_instance(TESTING_GAS_LIMIT); leave_default_data(&env); let result = env.call_function1("allocate", &[10u32.into()]).unwrap(); let ptr = ref_to_u32(&result).unwrap(); assert!(ptr > 0); } #[test] fn call_function1_errors_for_wrong_result_count() { let (env, _instance) = make_instance(TESTING_GAS_LIMIT); leave_default_data(&env); let result = env.call_function1("allocate", &[10u32.into()]).unwrap(); let ptr = ref_to_u32(&result).unwrap(); assert!(ptr > 0); let result = env.call_function1("deallocate", &[ptr.into()]); match result.unwrap_err() { VmError::ResultMismatch { function_name, expected, actual, } => { assert_eq!(function_name, "deallocate"); assert_eq!(expected, 1); assert_eq!(actual, 0); } err => panic!("unexpected error: {:?}", err), } } #[test] fn with_storage_from_context_set_get() { let (env, _instance) = make_instance(TESTING_GAS_LIMIT); leave_default_data(&env); let val = env .with_storage_from_context::<_, _>(|store| { Ok(store.get(INIT_KEY).0.expect("error getting value")) }) .unwrap(); assert_eq!(val, Some(INIT_VALUE.to_vec())); let set_key: &[u8] = b"more"; let set_value: &[u8] = b"data"; env.with_storage_from_context::<_, _>(|store| { store .set(set_key, set_value) .0 .expect("error setting value"); Ok(()) }) .unwrap(); env.with_storage_from_context::<_, _>(|store| { assert_eq!(store.get(INIT_KEY).0.unwrap(), Some(INIT_VALUE.to_vec())); assert_eq!(store.get(set_key).0.unwrap(), Some(set_value.to_vec())); Ok(()) }) .unwrap(); } #[test] #[should_panic(expected = "A panic occurred in the callback.")] fn with_storage_from_context_handles_panics() { let (env, _instance) = make_instance(TESTING_GAS_LIMIT); leave_default_data(&env); env.with_storage_from_context::<_, ()>(|_store| { panic!("A panic occurred in the callback.") }) .unwrap(); } #[test] fn with_querier_from_context_works() { let (env, _instance) = make_instance(TESTING_GAS_LIMIT); leave_default_data(&env); let res = env .with_querier_from_context::<_, _>(|querier| { let req: QueryRequest<Empty> = QueryRequest::Bank(BankQuery::AllBalances { address: INIT_ADDR.to_string(), }); let (result, _gas_info) = querier.query_raw(&to_vec(&req).unwrap(), DEFAULT_QUERY_GAS_LIMIT); Ok(result.unwrap()) }) .unwrap() .unwrap() .unwrap(); let balance: AllBalanceResponse = from_binary(&res).unwrap(); assert_eq!(balance.amount, coins(INIT_AMOUNT, INIT_DENOM)); } #[test] #[should_panic(expected = "A panic occurred in the callback.")] fn with_querier_from_context_handles_panics() { let (env, _instance) = make_instance(TESTING_GAS_LIMIT); leave_default_data(&env); env.with_querier_from_context::<_, ()>(|_querier| { panic!("A panic occurred in the callback.") }) .unwrap(); } }
36.743468
117
0.59713
90634ac2d5ef485489f2458c3d981e9f1f6c0c71
2,777
//! `fake::Kernel`'s implementation of the Command system call. use crate::kernel::thread_local::get_kernel; use crate::{command_return, ExpectedSyscall, SyscallLogEntry}; use libtock_platform::{ErrorCode, Register}; use std::convert::TryInto; pub(super) fn command( driver_id: Register, command_id: Register, argument0: Register, argument1: Register, ) -> [Register; 4] { let driver_id = driver_id.try_into().expect("Too large driver ID"); let command_id = command_id.try_into().expect("Too large command ID"); let argument0 = argument0.try_into().expect("Too large argument 0"); let argument1 = argument1.try_into().expect("Too large argument 1"); let kernel = get_kernel().expect("Command called but no fake::Kernel exists"); kernel.log_syscall(SyscallLogEntry::Command { driver_id, command_id, argument0, argument1, }); // Check for an expected syscall entry. Sets override_return to None if the // expected syscall queue is empty or if it expected this syscall but did // not specify a return override. Panics if a different syscall was expected // (either a non-Command syscall, or a Command call with different // arguments). #[allow(unreachable_patterns)] // TODO: Remove when 2nd syscall done. let override_return = match kernel.pop_expected_syscall() { None => None, Some(ExpectedSyscall::Command { driver_id: expected_driver_id, command_id: expected_command_id, argument0: expected_argument0, argument1: expected_argument1, override_return, }) => { assert_eq!( driver_id, expected_driver_id, "expected different driver_id" ); assert_eq!( command_id, expected_command_id, "expected different command_id" ); assert_eq!( argument0, expected_argument0, "expected different argument0" ); assert_eq!( argument1, expected_argument1, "expected different argument1" ); override_return } Some(expected_syscall) => expected_syscall.panic_wrong_call("Command"), }; // TODO: Add the Driver trait and implement driver support. let driver_return = command_return::failure(ErrorCode::NoSupport); // Convert the override return value (or the driver return value if no // override is present) into the representative register values. let (return_variant, r1, r2, r3) = override_return.unwrap_or(driver_return).raw_values(); let r0: u32 = return_variant.into(); [r0.into(), r1.into(), r2.into(), r3.into()] }
39.671429
93
0.64206
8fcf60c75fd7941ec34f8e6c366de60ed1b336ce
3,586
use casper_engine_test_support::{ internal::{ exec_with_return, ExecuteRequestBuilder, WasmTestBuilder, DEFAULT_BLOCK_TIME, DEFAULT_RUN_GENESIS_REQUEST, }, DEFAULT_ACCOUNT_ADDR, }; use casper_execution_engine::core::engine_state::EngineConfig; use casper_types::{ account::AccountHash, contracts::NamedKeys, runtime_args, ContractHash, ContractPackageHash, RuntimeArgs, URef, U512, }; const CONTRACT_TRANSFER_TO_ACCOUNT: &str = "transfer_to_account_u512.wasm"; const TRANSFER_AMOUNT: u64 = 250_000_000 + 1000; const SYSTEM_ADDR: AccountHash = AccountHash::new([0u8; 32]); const DEPLOY_HASH_2: [u8; 32] = [2u8; 32]; // one named_key for each validator and three for the purses const EXPECTED_KNOWN_KEYS_LEN: usize = 2; const POS_PAYMENT_PURSE: &str = "pos_payment_purse"; const POS_REWARDS_PURSE: &str = "pos_rewards_purse"; const ARG_MINT_PACKAGE_HASH: &str = "mint_contract_package_hash"; #[ignore] #[test] fn should_run_pos_install_contract() { let mut builder = WasmTestBuilder::default(); let engine_config = EngineConfig::new().with_use_system_contracts(cfg!(feature = "use-system-contracts")); let exec_request = ExecuteRequestBuilder::standard( *DEFAULT_ACCOUNT_ADDR, CONTRACT_TRANSFER_TO_ACCOUNT, runtime_args! { "target" =>SYSTEM_ADDR, "amount" => U512::from(TRANSFER_AMOUNT) }, ) .build(); builder.run_genesis(&DEFAULT_RUN_GENESIS_REQUEST); builder.exec(exec_request).commit().expect_success(); let mint_hash = builder.get_mint_contract_hash(); let mint_package_stored_value = builder .query(None, mint_hash.into(), &[]) .expect("should query mint hash"); let mint_package = mint_package_stored_value .as_contract() .expect("should be contract"); let mint_package_hash = mint_package.contract_package_hash(); let res = exec_with_return::exec( engine_config, &mut builder, SYSTEM_ADDR, "pos_install.wasm", DEFAULT_BLOCK_TIME, DEPLOY_HASH_2, "install", runtime_args! { ARG_MINT_PACKAGE_HASH => mint_package_hash, }, vec![], ); let ((_pos_package_hash, pos_hash), _ret_urefs, effect): ( (ContractPackageHash, ContractHash), _, _, ) = res.expect("should run successfully"); let prestate = builder.get_post_state_hash(); builder.commit_effects(prestate, effect.transforms); // should return a hash //assert_eq!(ret_value, ret_urefs[0]); // should have written a contract under that uref let contract = builder .get_contract(pos_hash) .expect("should have a contract"); let named_keys = contract.named_keys(); assert_eq!(named_keys.len(), EXPECTED_KNOWN_KEYS_LEN); // payment purse has correct balance let payment_purse = get_purse(named_keys, POS_PAYMENT_PURSE).expect( "should find payment purse in named_keys", ); let payment_purse_balance = builder.get_purse_balance(payment_purse); assert_eq!(payment_purse_balance, U512::zero()); // rewards purse has correct balance let rewards_purse = get_purse(named_keys, POS_REWARDS_PURSE).expect( "should find rewards purse in named_keys", ); let rewards_purse_balance = builder.get_purse_balance(rewards_purse); assert_eq!(rewards_purse_balance, U512::zero()); } fn get_purse(named_keys: &NamedKeys, name: &str) -> Option<URef> { named_keys .get(name) .expect("should have named key") .into_uref() }
31.734513
96
0.693252
0ae9a002b40732afb947e0f4be0ee8d7cd0f0f10
1,328
mod client_cfg; mod protocol; mod utils; use protocol::remote_executor_client::RemoteExecutorClient; use protocol::Command; use tonic::transport::Channel; use client_cfg::{parse_config, Start, SubCommand}; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let (opts, cfg) = parse_config(); let channel = Channel::from_shared(format!("http://{}", cfg.addr))? .connect() .await?; let client = RemoteExecutorClient::new(channel); // let client = RemoteExe match opts.subcmd { SubCommand::Start(start) => send_start(client, start).await?, SubCommand::Stop(_) => unimplemented!(), SubCommand::List => unimplemented!(), SubCommand::Status(_) => unimplemented!(), SubCommand::Log(_) => unimplemented!(), }; Ok(()) } async fn send_start( mut client: RemoteExecutorClient<tonic::transport::Channel>, start: Start, ) -> Result<(), tonic::Status> { let cmd = Command { command: start.cmd }; let resp = client.start(cmd).await?; match &resp.get_ref().id { None => { return Err(tonic::Status::invalid_argument( "Response did not contain task ID", )) } Some(task_id) => println!("Started task with ID: {}", task_id.uuid), }; Ok(()) }
27.666667
76
0.605422
561d6403f25ea96d5be92d42c7ee0b02169e796d
10,889
//! @brief Example Rust-based BPF program that issues a cross-program-invocation #![allow(unreachable_code)] extern crate solana_sdk; use solana_bpf_rust_invoked::instruction::*; use solana_sdk::{ account_info::AccountInfo, entrypoint, entrypoint::{ProgramResult, MAX_PERMITTED_DATA_INCREASE}, info, program::{invoke, invoke_signed}, program_error::ProgramError, pubkey::{Pubkey, PubkeyError}, system_instruction, }; const TEST_SUCCESS: u8 = 1; const TEST_PRIVILEGE_ESCALATION_SIGNER: u8 = 2; const TEST_PRIVILEGE_ESCALATION_WRITABLE: u8 = 3; // const MINT_INDEX: usize = 0; const ARGUMENT_INDEX: usize = 1; const INVOKED_PROGRAM_INDEX: usize = 2; const INVOKED_ARGUMENT_INDEX: usize = 3; const INVOKED_PROGRAM_DUP_INDEX: usize = 4; // const ARGUMENT_DUP_INDEX: usize = 5; const DERIVED_KEY1_INDEX: usize = 6; const DERIVED_KEY2_INDEX: usize = 7; const DERIVED_KEY3_INDEX: usize = 8; // const SYSTEM_PROGRAM_INDEX: usize = 9; const FROM_INDEX: usize = 10; entrypoint!(process_instruction); fn process_instruction( program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8], ) -> ProgramResult { info!("invoke Rust program"); let nonce1 = instruction_data[1]; let nonce2 = instruction_data[2]; let nonce3 = instruction_data[3]; match instruction_data[0] { TEST_SUCCESS => { info!("Call system program create account"); { let from_lamports = accounts[FROM_INDEX].lamports(); let to_lamports = accounts[DERIVED_KEY1_INDEX].lamports(); assert_eq!(accounts[DERIVED_KEY1_INDEX].data_len(), 0); assert!(solana_sdk::system_program::check_id( accounts[DERIVED_KEY1_INDEX].owner )); let instruction = system_instruction::create_account( accounts[FROM_INDEX].key, accounts[DERIVED_KEY1_INDEX].key, 42, MAX_PERMITTED_DATA_INCREASE as u64, program_id, ); invoke_signed(&instruction, accounts, &[&[b"You pass butter", &[nonce1]]])?; assert_eq!(accounts[FROM_INDEX].lamports(), from_lamports - 42); assert_eq!(accounts[DERIVED_KEY1_INDEX].lamports(), to_lamports + 42); assert_eq!(program_id, accounts[DERIVED_KEY1_INDEX].owner); assert_eq!( accounts[DERIVED_KEY1_INDEX].data_len(), MAX_PERMITTED_DATA_INCREASE ); let mut data = accounts[DERIVED_KEY1_INDEX].try_borrow_mut_data()?; assert_eq!(data[MAX_PERMITTED_DATA_INCREASE - 1], 0); data[MAX_PERMITTED_DATA_INCREASE - 1] = 0x0f; assert_eq!(data[MAX_PERMITTED_DATA_INCREASE - 1], 0x0f); for i in 0..20 { data[i] = i as u8; } } info!("Call system program transfer"); { let from_lamports = accounts[FROM_INDEX].lamports(); let to_lamports = accounts[DERIVED_KEY1_INDEX].lamports(); let instruction = system_instruction::transfer( accounts[FROM_INDEX].key, accounts[DERIVED_KEY1_INDEX].key, 1, ); invoke(&instruction, accounts)?; assert_eq!(accounts[FROM_INDEX].lamports(), from_lamports - 1); assert_eq!(accounts[DERIVED_KEY1_INDEX].lamports(), to_lamports + 1); } info!("Test data translation"); { { let mut data = accounts[ARGUMENT_INDEX].try_borrow_mut_data()?; for i in 0..100 { data[i as usize] = i; } } let instruction = create_instruction( *accounts[INVOKED_PROGRAM_INDEX].key, &[ (accounts[ARGUMENT_INDEX].key, true, true), (accounts[INVOKED_ARGUMENT_INDEX].key, true, true), (accounts[INVOKED_PROGRAM_INDEX].key, false, false), (accounts[INVOKED_PROGRAM_DUP_INDEX].key, false, false), ], vec![TEST_VERIFY_TRANSLATIONS, 1, 2, 3, 4, 5], ); invoke(&instruction, accounts)?; } info!("Test return error"); { let instruction = create_instruction( *accounts[INVOKED_PROGRAM_INDEX].key, &[(accounts[ARGUMENT_INDEX].key, true, true)], vec![TEST_RETURN_ERROR], ); assert_eq!( invoke(&instruction, accounts), Err(ProgramError::Custom(42)) ); } info!("Test create_program_address"); { assert_eq!( &Pubkey::create_program_address(&[b"You pass butter", &[nonce1]], program_id)?, accounts[DERIVED_KEY1_INDEX].key ); assert_eq!( Pubkey::create_program_address(&[b"You pass butter"], &Pubkey::default()) .unwrap_err(), PubkeyError::InvalidSeeds ); } info!("Test derived signers"); { assert!(!accounts[DERIVED_KEY1_INDEX].is_signer); assert!(!accounts[DERIVED_KEY2_INDEX].is_signer); assert!(!accounts[DERIVED_KEY3_INDEX].is_signer); let invoked_instruction = create_instruction( *accounts[INVOKED_PROGRAM_INDEX].key, &[ (accounts[INVOKED_PROGRAM_INDEX].key, false, false), (accounts[DERIVED_KEY1_INDEX].key, true, true), (accounts[DERIVED_KEY2_INDEX].key, true, false), (accounts[DERIVED_KEY3_INDEX].key, false, false), ], vec![TEST_DERIVED_SIGNERS, nonce2, nonce3], ); invoke_signed( &invoked_instruction, accounts, &[&[b"You pass butter", &[nonce1]]], )?; let invoked_instruction = create_instruction( *accounts[INVOKED_PROGRAM_INDEX].key, &[ (accounts[DERIVED_KEY1_INDEX].key, true, false), (accounts[DERIVED_KEY2_INDEX].key, true, true), (accounts[DERIVED_KEY3_INDEX].key, false, true), ], vec![TEST_VERIFY_NESTED_SIGNERS], ); invoke_signed( &invoked_instruction, accounts, &[ &[b"Lil'", b"Bits", &[nonce2]], &[accounts[DERIVED_KEY2_INDEX].key.as_ref(), &[nonce3]], ], )?; } info!("Test readonly with writable account"); { let invoked_instruction = create_instruction( *accounts[INVOKED_PROGRAM_INDEX].key, &[(accounts[ARGUMENT_INDEX].key, false, true)], vec![TEST_VERIFY_WRITER], ); invoke(&invoked_instruction, accounts)?; } info!("Test nested invoke"); { assert!(accounts[ARGUMENT_INDEX].is_signer); **accounts[ARGUMENT_INDEX].lamports.borrow_mut() -= 5; **accounts[INVOKED_ARGUMENT_INDEX].lamports.borrow_mut() += 5; info!("First invoke"); let instruction = create_instruction( *accounts[INVOKED_PROGRAM_INDEX].key, &[ (accounts[ARGUMENT_INDEX].key, true, true), (accounts[INVOKED_ARGUMENT_INDEX].key, true, true), ], vec![TEST_NESTED_INVOKE], ); invoke(&instruction, accounts)?; info!("2nd invoke from first program"); invoke(&instruction, accounts)?; info!(line!(), 0, 0, 0, accounts[ARGUMENT_INDEX].lamports()); assert_eq!(accounts[ARGUMENT_INDEX].lamports(), 42 - 5 + 1 + 1); assert_eq!(accounts[INVOKED_ARGUMENT_INDEX].lamports(), 10 + 5 - 1 - 1); } info!("Verify data values are retained and updated"); { let data = accounts[ARGUMENT_INDEX].try_borrow_data()?; for i in 0..100 { assert_eq!(data[i as usize], i); } let data = accounts[INVOKED_ARGUMENT_INDEX].try_borrow_data()?; for i in 0..10 { assert_eq!(data[i as usize], i); } } } TEST_PRIVILEGE_ESCALATION_SIGNER => { info!("Test privilege escalation signer"); let mut invoked_instruction = create_instruction( *accounts[INVOKED_PROGRAM_INDEX].key, &[(accounts[DERIVED_KEY3_INDEX].key, false, false)], vec![TEST_VERIFY_PRIVILEGE_ESCALATION], ); invoke(&invoked_instruction, accounts)?; invoked_instruction.accounts[0].is_signer = true; assert_eq!( invoke(&invoked_instruction, accounts), Err(ProgramError::Custom(0x0b9f_0002)) ); } TEST_PRIVILEGE_ESCALATION_WRITABLE => { info!("Test privilege escalation writable"); let mut invoked_instruction = create_instruction( *accounts[INVOKED_PROGRAM_INDEX].key, &[(accounts[DERIVED_KEY3_INDEX].key, false, false)], vec![TEST_VERIFY_PRIVILEGE_ESCALATION], ); invoke(&invoked_instruction, accounts)?; invoked_instruction.accounts[0].is_writable = true; assert_eq!( invoke(&invoked_instruction, accounts), Err(ProgramError::Custom(0x0b9f_0002)) ); } _ => panic!(), } Ok(()) } #[cfg(test)] mod test { use super::*; // Pull in syscall stubs when building for non-BPF targets solana_sdk::program_stubs!(); #[test] fn create_program_address_is_defined() { assert_eq!( Pubkey::create_program_address(&[b"You pass butter"], &Pubkey::default()).unwrap_err(), PubkeyError::InvalidSeeds ); } }
38.477032
99
0.520158
6469e4f5d405a328e6145c297c486a0ce5b617ce
25,645
//! `ndarray` for NumPy users. //! //! This is an introductory guide to `ndarray` for people with experience using //! NumPy, although it may also be useful to others. For a more general //! introduction to `ndarray`'s array type `ArrayBase`, see the [`ArrayBase` //! docs][ArrayBase]. //! //! # Contents //! //! * [Similarities](#similarities) //! * [Some key differences](#some-key-differences) //! * [The ndarray ecosystem](#the-ndarray-ecosystem) //! * [Other Rust array/matrix crates](#other-rust-arraymatrix-crates) //! * [Rough `ndarray`–NumPy equivalents](#rough-ndarraynumpy-equivalents) //! //! * [Array creation](#array-creation) //! * [Indexing and slicing](#indexing-and-slicing) //! * [Shape and strides](#shape-and-strides) //! * [Mathematics](#mathematics) //! * [Array manipulation](#array-manipulation) //! * [Iteration](#iteration) //! * [Convenience methods for 2-D arrays](#convenience-methods-for-2-d-arrays) //! //! # Similarities //! //! `ndarray`'s array type ([`ArrayBase`][ArrayBase]), is very similar to //! NumPy's array type (`numpy.ndarray`): //! //! * Arrays have a single element type. //! * Arrays can have arbitrarily many dimensions. //! * Arrays can have arbitrary strides. //! * Indexing starts at zero, not one. //! * The default memory layout is row-major, and the default iterators follow //! row-major order (also called "logical order" in the documentation). //! * Arithmetic operators work elementwise. (For example, `a * b` performs //! elementwise multiplication, not matrix multiplication.) //! * Owned arrays are contiguous in memory. //! * Many operations, such as slicing, are very cheap because they can return //! a view of an array instead of copying the data. //! //! NumPy has many features that `ndarray` doesn't have yet, such as: //! //! * [index arrays](https://docs.scipy.org/doc/numpy/user/basics.indexing.html#index-arrays) //! * [mask index arrays](https://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays) //! * co-broadcasting (`ndarray` only supports broadcasting the right-hand array in a binary operation.) //! //! # Some key differences //! //! <table> //! <tr> //! <th> //! //! NumPy //! //! </th> //! <th> //! //! `ndarray` //! //! </th> //! </tr> //! //! <tr> //! <td> //! //! In NumPy, there is no distinction between owned arrays, views, and mutable //! views. There can be multiple arrays (instances of `numpy.ndarray`) that //! mutably reference the same data. //! //! </td> //! <td> //! //! In `ndarray`, all arrays are instances of [`ArrayBase`][ArrayBase], but //! `ArrayBase` is generic over the ownership of the data. [`Array`][Array] //! owns its data; [`ArrayView`][ArrayView] is a view; //! [`ArrayViewMut`][ArrayViewMut] is a mutable view; [`CowArray`][CowArray] //! either owns its data or is a view (with copy-on-write mutation of the view //! variant); and [`ArcArray`][ArcArray] has a reference-counted pointer to its //! data (with copy-on-write mutation). Arrays and views follow Rust's aliasing //! rules. //! //! </td> //! </tr> //! //! <tr> //! <td> //! //! In NumPy, all arrays are dynamic-dimensional. //! //! </td> //! <td> //! //! In `ndarray`, you can create fixed-dimension arrays, such as //! [`Array2`][Array2]. This takes advantage of the type system to help you //! write correct code and also avoids small heap allocations for the shape and //! strides. //! //! </td> //! </tr> //! //! <tr> //! <td> //! //! When slicing in NumPy, the indices are `start`, `start + step`, `start + //! 2*step`, … until reaching `end` (exclusive). //! //! </td> //! <td> //! //! When slicing in `ndarray`, the axis is first sliced with `start..end`. Then if //! `step` is positive, the first index is the front of the slice; if `step` is //! negative, the first index is the back of the slice. This means that the //! behavior is the same as NumPy except when `step < -1`. See the docs for the //! [`s![]` macro][s!] for more details. //! //! </td> //! </tr> //! </table> //! //! # The ndarray ecosystem //! //! `ndarray` does not provide advanced linear algebra routines out of the box (e.g. SVD decomposition). //! Most of the routines that you can find in `scipy.linalg`/`numpy.linalg` are provided by another crate, //! [`ndarray-linalg`](https://crates.io/crates/ndarray-linalg). //! //! The same holds for statistics: `ndarray` provides some basic functionalities (e.g. `mean`) //! but more advanced routines can be found in [`ndarray-stats`](https://crates.io/crates/ndarray-stats). //! //! If you are looking to generate random arrays instead, check out [`ndarray-rand`](https://crates.io/crates/ndarray-rand). //! //! It is also possible to serialize `NumPy` arrays in `.npy`/`.npz` format and deserialize them as `ndarray` arrays (and vice versa) //! using [`ndarray-npy`](https://crates.io/crates/ndarray-npy). //! //! # Other Rust array/matrix crates //! //! Of the array/matrix types in Rust crates, the `ndarray` array type is probably //! the most similar to NumPy's arrays and is the most flexible. However, if your //! use-case is constrained to linear algebra on 1-D and 2-D vectors and matrices, //! it might be worth considering other crates: //! //! * [`nalgebra`](https://crates.io/crates/nalgebra) provides 1-D and 2-D //! column-major vector and matrix types for linear algebra. Vectors and matrices //! can have constant or dynamic shapes, and `nalgebra` uses the type system to //! provide compile-time checking of shapes, not just the number of dimensions. //! `nalgebra` provides convenient functionality for geometry (e.g. coordinate //! transformations) and linear algebra. //! * [`cgmath`](https://crates.io/crates/cgmath) provides 1-D and 2-D column-major //! types of shape 4×4 or smaller. It's primarily designed for computer graphics //! and provides convenient functionality for geometry (e.g. coordinate //! transformations). Similar to `nalgebra`, `cgmath` uses the type system to //! provide compile-time checking of shapes. //! * [`rulinalg`](https://crates.io/crates/rulinalg) provides 1-D and 2-D //! row-major vector and matrix types with dynamic shapes. Similar to `ndarray`, //! `rulinalg` provides compile-time checking of the number of dimensions, but //! not shapes. `rulinalg` provides pure-Rust implementations of linear algebra //! operations. //! * If there's another crate that should be listed here, please let us know. //! //! In contrast to these crates, `ndarray` provides an *n*-dimensional array type, //! so it's not restricted to 1-D and 2-D vectors and matrices. Also, operators //! operate elementwise by default, so the multiplication operator `*` performs //! elementwise multiplication instead of matrix multiplication. (You have to //! specifically call `.dot()` if you want matrix multiplication.) //! //! # Rough `ndarray`–NumPy equivalents //! //! These tables provide some rough equivalents of NumPy operations in `ndarray`. //! There are a variety of other methods that aren't included in these tables, //! including shape-manipulation, array creation, and iteration routines. //! //! It's assumed that you've imported NumPy like this: //! //! ```python //! import numpy as np //! ``` //! //! and `ndarray` like this: //! //! ``` //! use ndarray::prelude::*; //! # //! # fn main() {} //! ``` //! //! ## Array creation //! //! This table contains ways to create arrays from scratch. For creating arrays by //! operations on other arrays (e.g. arithmetic), see the other tables. Also see //! the [`::from_vec()`][::from_vec()], [`::from_iter()`][::from_iter()], //! [`::default()`][::default()], [`::from_shape_fn()`][::from_shape_fn()], and //! [`::from_shape_vec_unchecked()`][::from_shape_vec_unchecked()] methods. //! //! NumPy | `ndarray` | Notes //! ------|-----------|------ //! `np.array([[1.,2.,3.], [4.,5.,6.]])` | [`array![[1.,2.,3.], [4.,5.,6.]]`][array!] or [`arr2(&[[1.,2.,3.], [4.,5.,6.]])`][arr2()] | 2×3 floating-point array literal //! `np.arange(0., 10., 0.5)` or `np.r_[:10.:0.5]` | [`Array::range(0., 10., 0.5)`][::range()] | create a 1-D array with values `0.`, `0.5`, …, `9.5` //! `np.linspace(0., 10., 11)` or `np.r_[:10.:11j]` | [`Array::linspace(0., 10., 11)`][::linspace()] | create a 1-D array with 11 elements with values `0.`, …, `10.` //! `np.logspace(2.0, 3.0, num=4, base=10.0)` | [`Array::logspace(10.0, 2.0, 3.0, 4)`][::logspace()] | create a 1-D array with 4 elements with values `100.`, `215.4`, `464.1`, `1000.` //! `np.geomspace(1., 1000., num=4)` | [`Array::geomspace(1e0, 1e3, 4)`][::geomspace()] | create a 1-D array with 4 elements with values `1.`, `10.`, `100.`, `1000.` //! `np.ones((3, 4, 5))` | [`Array::ones((3, 4, 5))`][::ones()] | create a 3×4×5 array filled with ones (inferring the element type) //! `np.zeros((3, 4, 5))` | [`Array::zeros((3, 4, 5))`][::zeros()] | create a 3×4×5 array filled with zeros (inferring the element type) //! `np.zeros((3, 4, 5), order='F')` | [`Array::zeros((3, 4, 5).f())`][::zeros()] | create a 3×4×5 array with Fortran (column-major) memory layout filled with zeros (inferring the element type) //! `np.zeros_like(a, order='C')` | [`Array::zeros(a.raw_dim())`][::zeros()] | create an array of zeros of the shape shape as `a`, with row-major memory layout (unlike NumPy, this infers the element type from context instead of duplicating `a`'s element type) //! `np.full((3, 4), 7.)` | [`Array::from_elem((3, 4), 7.)`][::from_elem()] | create a 3×4 array filled with the value `7.` //! `np.eye(3)` | [`Array::eye(3)`][::eye()] | create a 3×3 identity matrix (inferring the element type) //! `np.diag(np.array([1, 2, 3]))` | [`Array2::from_diag(&arr1(&[1, 2, 3]))`][::from_diag()] | create a 3×3 matrix with `[1, 2, 3]` as diagonal and zeros elsewhere (inferring the element type) //! `np.array([1, 2, 3, 4]).reshape((2, 2))` | [`Array::from_shape_vec((2, 2), vec![1, 2, 3, 4])?`][::from_shape_vec()] | create a 2×2 array from the elements in the list/`Vec` //! `np.array([1, 2, 3, 4]).reshape((2, 2), order='F')` | [`Array::from_shape_vec((2, 2).f(), vec![1, 2, 3, 4])?`][::from_shape_vec()] | create a 2×2 array from the elements in the list/`Vec` using Fortran (column-major) order //! `np.random` | See the [`ndarray-rand`](https://crates.io/crates/ndarray-rand) crate. | create arrays of random numbers //! //! Note that the examples in the table rely on the compiler inferring the //! element type and dimensionality from context, which is usually sufficient. //! However, if the compiler cannot infer the types, you can specify them //! manually. These are examples of creating a 3-D Fortran-layout array of //! `f64`s: //! //! ``` //! # use ndarray::prelude::*; //! # //! // This is an example where the compiler can infer the element type //! // because `f64::sin` can only be called on `f64` elements: //! let arr1 = Array::zeros((3, 2, 4).f()); //! arr1.mapv(f64::sin); //! //! // Specify just the element type and infer the dimensionality: //! let arr2 = Array::<f64, _>::zeros((3, 2, 4).f()); //! let arr3: Array<f64, _> = Array::zeros((3, 2, 4).f()); //! //! // Specify both the element type and dimensionality: //! let arr4 = Array3::<f64>::zeros((3, 2, 4).f()); //! let arr5: Array3<f64> = Array::zeros((3, 2, 4).f()); //! let arr6 = Array::<f64, Ix3>::zeros((3, 2, 4).f()); //! let arr7: Array<f64, Ix3> = Array::zeros((3, 2, 4).f()); //! ``` //! //! ## Indexing and slicing //! //! A few notes: //! //! * Indices start at 0. For example, "row 1" is the second row in the array. //! //! * Some methods have multiple variants in terms of ownership and mutability. //! Only the non-mutable methods that take the array by reference are listed in //! this table. For example, [`.slice()`][.slice()] also has corresponding //! methods [`.slice_mut()`][.slice_mut()], [`.slice_move()`][.slice_move()], and //! [`.slice_collapse()`][.slice_collapse()]. //! //! * The behavior of slicing is slightly different from NumPy for slices with //! `step < -1`. See the docs for the [`s![]` macro][s!] for more details. //! //! NumPy | `ndarray` | Notes //! ------|-----------|------ //! `a[-1]` | [`a[a.len() - 1]`][.index()] | access the last element in 1-D array `a` //! `a[1, 4]` | [`a[[1, 4]]`][.index()] | access the element in row 1, column 4 //! `a[1]` or `a[1, :, :]` | [`a.slice(s![1, .., ..])`][.slice()] or [`a.index_axis(Axis(0), 1)`][.index_axis()] | get a 2-D subview of a 3-D array at index 1 of axis 0 //! `a[0:5]` or `a[:5]` or `a[0:5, :]` | [`a.slice(s![0..5, ..])`][.slice()] or [`a.slice(s![..5, ..])`][.slice()] or [`a.slice_axis(Axis(0), Slice::from(0..5))`][.slice_axis()] | get the first 5 rows of a 2-D array //! `a[-5:]` or `a[-5:, :]` | [`a.slice(s![-5.., ..])`][.slice()] or [`a.slice_axis(Axis(0), Slice::from(-5..))`][.slice_axis()] | get the last 5 rows of a 2-D array //! `a[:3, 4:9]` | [`a.slice(s![..3, 4..9])`][.slice()] | columns 4, 5, 6, 7, and 8 of the first 3 rows //! `a[1:4:2, ::-1]` | [`a.slice(s![1..4;2, ..;-1])`][.slice()] | rows 1 and 3 with the columns in reverse order //! //! ## Shape and strides //! //! Note that [`a.shape()`][.shape()], [`a.dim()`][.dim()], and //! [`a.raw_dim()`][.raw_dim()] all return the shape of the array, but as //! different types. `a.shape()` returns the shape as `&[Ix]`, (where //! [`Ix`][Ix] is `usize`) which is useful for general operations on the shape. //! `a.dim()` returns the shape as `D::Pattern`, which is useful for //! pattern-matching shapes. `a.raw_dim()` returns the shape as `D`, which is //! useful for creating other arrays of the same shape. //! //! NumPy | `ndarray` | Notes //! ------|-----------|------ //! `np.ndim(a)` or `a.ndim` | [`a.ndim()`][.ndim()] | get the number of dimensions of array `a` //! `np.size(a)` or `a.size` | [`a.len()`][.len()] | get the number of elements in array `a` //! `np.shape(a)` or `a.shape` | [`a.shape()`][.shape()] or [`a.dim()`][.dim()] | get the shape of array `a` //! `a.shape[axis]` | [`a.len_of(Axis(axis))`][.len_of()] | get the length of an axis //! `a.strides` | [`a.strides()`][.strides()] | get the strides of array `a` //! `np.size(a) == 0` or `a.size == 0` | [`a.is_empty()`][.is_empty()] | check if the array has zero elements //! //! ## Mathematics //! //! Note that [`.mapv()`][.mapv()] has corresponding methods [`.map()`][.map()], //! [`.mapv_into()`][.mapv_into()], [`.map_inplace()`][.map_inplace()], and //! [`.mapv_inplace()`][.mapv_inplace()]. Also look at [`.fold()`][.fold()], //! [`.visit()`][.visit()], [`.fold_axis()`][.fold_axis()], and //! [`.map_axis()`][.map_axis()]. //! //! <table> //! <tr><th> //! //! NumPy //! //! </th><th> //! //! `ndarray` //! //! </th><th> //! //! Notes //! //! </th></tr> //! //! <tr><td> //! //! `a.transpose()` or `a.T` //! //! </td><td> //! //! [`a.t()`][.t()] or [`a.reversed_axes()`][.reversed_axes()] //! //! </td><td> //! //! transpose of array `a` (view for `.t()` or by-move for `.reversed_axes()`) //! //! </td></tr> //! //! <tr><td> //! //! `mat1.dot(mat2)` //! //! </td><td> //! //! [`mat1.dot(&mat2)`][matrix-* dot] //! //! </td><td> //! //! 2-D matrix multiply //! //! </td></tr> //! //! <tr><td> //! //! `mat.dot(vec)` //! //! </td><td> //! //! [`mat.dot(&vec)`][matrix-* dot] //! //! </td><td> //! //! 2-D matrix dot 1-D column vector //! //! </td></tr> //! //! <tr><td> //! //! `vec.dot(mat)` //! //! </td><td> //! //! [`vec.dot(&mat)`][vec-* dot] //! //! </td><td> //! //! 1-D row vector dot 2-D matrix //! //! </td></tr> //! //! <tr><td> //! //! `vec1.dot(vec2)` //! //! </td><td> //! //! [`vec1.dot(&vec2)`][vec-* dot] //! //! </td><td> //! //! vector dot product //! //! </td></tr> //! //! <tr><td> //! //! `a * b`, `a + b`, etc. //! //! </td><td> //! //! [`a * b`, `a + b`, etc.](../../struct.ArrayBase.html#arithmetic-operations) //! //! </td><td> //! //! element-wise arithmetic operations //! //! </td></tr> //! //! <tr><td> //! //! `a**3` //! //! </td><td> //! //! [`a.mapv(|a| a.powi(3))`][.mapv()] //! //! </td><td> //! //! element-wise power of 3 //! //! </td></tr> //! //! <tr><td> //! //! `np.sqrt(a)` //! //! </td><td> //! //! [`a.mapv(f64::sqrt)`][.mapv()] //! //! </td><td> //! //! element-wise square root for `f64` array //! //! </td></tr> //! //! <tr><td> //! //! `(a>0.5)` //! //! </td><td> //! //! [`a.mapv(|a| a > 0.5)`][.mapv()] //! //! </td><td> //! //! array of `bool`s of same shape as `a` with `true` where `a > 0.5` and `false` elsewhere //! //! </td></tr> //! //! <tr><td> //! //! `np.sum(a)` or `a.sum()` //! //! </td><td> //! //! [`a.sum()`][.sum()] //! //! </td><td> //! //! sum the elements in `a` //! //! </td></tr> //! //! <tr><td> //! //! `np.sum(a, axis=2)` or `a.sum(axis=2)` //! //! </td><td> //! //! [`a.sum_axis(Axis(2))`][.sum_axis()] //! //! </td><td> //! //! sum the elements in `a` along axis 2 //! //! </td></tr> //! //! <tr><td> //! //! `np.mean(a)` or `a.mean()` //! //! </td><td> //! //! [`a.mean().unwrap()`][.mean()] //! </td><td> //! //! calculate the mean of the elements in `f64` array `a` //! //! </td></tr> //! //! <tr><td> //! //! `np.mean(a, axis=2)` or `a.mean(axis=2)` //! //! </td><td> //! //! [`a.mean_axis(Axis(2))`][.mean_axis()] //! //! </td><td> //! //! calculate the mean of the elements in `a` along axis 2 //! //! </td></tr> //! //! <tr><td> //! //! `np.allclose(a, b, atol=1e-8)` //! //! </td><td> //! //! [`a.abs_diff_eq(&b, 1e-8)`][.abs_diff_eq()] //! //! </td><td> //! //! check if the arrays' elementwise differences are within an absolute tolerance (it requires the `approx` feature-flag) //! //! </td></tr> //! //! <tr><td> //! //! `np.diag(a)` //! //! </td><td> //! //! [`a.diag()`][.diag()] //! //! </td><td> //! //! view the diagonal of `a` //! //! </td></tr> //! //! <tr><td> //! //! `np.linalg` //! //! </td><td> //! //! See [`ndarray-linalg`](https://crates.io/crates/ndarray-linalg) //! //! </td><td> //! //! linear algebra (matrix inverse, solving, decompositions, etc.) //! //! </td></tr> //! </table> //! //! ## Array manipulation //! //! NumPy | `ndarray` | Notes //! ------|-----------|------ //! `a[:] = 3.` | [`a.fill(3.)`][.fill()] | set all array elements to the same scalar value //! `a[:] = b` | [`a.assign(&b)`][.assign()] | copy the data from array `b` into array `a` //! `np.concatenate((a,b), axis=1)` | [`stack![Axis(1), a, b]`][stack!] or [`stack(Axis(1), &[a.view(), b.view()])`][stack()] | concatenate arrays `a` and `b` along axis 1 //! `a[:,np.newaxis]` or `np.expand_dims(a, axis=1)` | [`a.insert_axis(Axis(1))`][.insert_axis()] | create an array from `a`, inserting a new axis 1 //! `a.transpose()` or `a.T` | [`a.t()`][.t()] or [`a.reversed_axes()`][.reversed_axes()] | transpose of array `a` (view for `.t()` or by-move for `.reversed_axes()`) //! `np.diag(a)` | [`a.diag()`][.diag()] | view the diagonal of `a` //! `a.flatten()` | [`use std::iter::FromIterator; Array::from_iter(a.iter().cloned())`][::from_iter()] | create a 1-D array by flattening `a` //! //! ## Iteration //! //! `ndarray` has lots of interesting iterators/producers that implement the //! [`NdProducer`][NdProducer] trait, which is a generalization of `Iterator` //! to multiple dimensions. This makes it possible to correctly and efficiently //! zip together slices/subviews of arrays in multiple dimensions with //! [`Zip`][Zip] or [`azip!()`][azip!]. The purpose of this is similar to //! [`np.nditer`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.nditer.html), //! but [`Zip`][Zip] is implemented and used somewhat differently. //! //! This table lists some of the iterators/producers which have a direct //! equivalent in NumPy. For a more complete introduction to producers and //! iterators, see [*Loops, Producers, and //! Iterators*](../../struct.ArrayBase.html#loops-producers-and-iterators). //! Note that there are also variants of these iterators (with a `_mut` suffix) //! that yield `ArrayViewMut` instead of `ArrayView`. //! //! NumPy | `ndarray` | Notes //! ------|-----------|------ //! `a.flat` | [`a.iter()`][.iter()] | iterator over the array elements in logical order //! `np.ndenumerate(a)` | [`a.indexed_iter()`][.indexed_iter()] | flat iterator yielding the index along with each element reference //! `iter(a)` | [`a.outer_iter()`][.outer_iter()] or [`a.axis_iter(Axis(0))`][.axis_iter()] | iterator over the first (outermost) axis, yielding each subview //! //! ## Convenience methods for 2-D arrays //! //! NumPy | `ndarray` | Notes //! ------|-----------|------ //! `len(a)` or `a.shape[0]` | [`a.nrows()`][.nrows()] | get the number of rows in a 2-D array //! `a.shape[1]` | [`a.ncols()`][.ncols()] | get the number of columns in a 2-D array //! `a[1]` or `a[1,:]` | [`a.row(1)`][.row()] or [`a.row_mut(1)`][.row_mut()] | view (or mutable view) of row 1 in a 2-D array //! `a[:,4]` | [`a.column(4)`][.column()] or [`a.column_mut(4)`][.column_mut()] | view (or mutable view) of column 4 in a 2-D array //! `a.shape[0] == a.shape[1]` | [`a.is_square()`][.is_square()] | check if the array is square //! //! [.abs_diff_eq()]: ../../struct.ArrayBase.html#impl-AbsDiffEq<ArrayBase<S2%2C%20D>> //! [ArcArray]: ../../type.ArcArray.html //! [arr2()]: ../../fn.arr2.html //! [array!]: ../../macro.array.html //! [Array]: ../../type.Array.html //! [Array2]: ../../type.Array2.html //! [ArrayBase]: ../../struct.ArrayBase.html //! [ArrayView]: ../../type.ArrayView.html //! [ArrayViewMut]: ../../type.ArrayViewMut.html //! [.assign()]: ../../struct.ArrayBase.html#method.assign //! [.axis_iter()]: ../../struct.ArrayBase.html#method.axis_iter //! [azip!]: ../../macro.azip.html //! [.ncols()]: ../../struct.ArrayBase.html#method.ncols //! [.column()]: ../../struct.ArrayBase.html#method.column //! [.column_mut()]: ../../struct.ArrayBase.html#method.column_mut //! [CowArray]: ../../type.CowArray.html //! [::default()]: ../../struct.ArrayBase.html#method.default //! [.diag()]: ../../struct.ArrayBase.html#method.diag //! [.dim()]: ../../struct.ArrayBase.html#method.dim //! [::eye()]: ../../struct.ArrayBase.html#method.eye //! [.fill()]: ../../struct.ArrayBase.html#method.fill //! [.fold()]: ../../struct.ArrayBase.html#method.fold //! [.fold_axis()]: ../../struct.ArrayBase.html#method.fold_axis //! [::from_elem()]: ../../struct.ArrayBase.html#method.from_elem //! [::from_iter()]: ../../struct.ArrayBase.html#method.from_iter //! [::from_diag()]: ../../struct.ArrayBase.html#method.from_diag //! [::from_shape_fn()]: ../../struct.ArrayBase.html#method.from_shape_fn //! [::from_shape_vec()]: ../../struct.ArrayBase.html#method.from_shape_vec //! [::from_shape_vec_unchecked()]: ../../struct.ArrayBase.html#method.from_shape_vec_unchecked //! [::from_vec()]: ../../struct.ArrayBase.html#method.from_vec //! [.index()]: ../../struct.ArrayBase.html#impl-Index<I> //! [.indexed_iter()]: ../../struct.ArrayBase.html#method.indexed_iter //! [.insert_axis()]: ../../struct.ArrayBase.html#method.insert_axis //! [.is_empty()]: ../../struct.ArrayBase.html#method.is_empty //! [.is_square()]: ../../struct.ArrayBase.html#method.is_square //! [.iter()]: ../../struct.ArrayBase.html#method.iter //! [Ix]: ../../type.Ix.html //! [.len()]: ../../struct.ArrayBase.html#method.len //! [.len_of()]: ../../struct.ArrayBase.html#method.len_of //! [::linspace()]: ../../struct.ArrayBase.html#method.linspace //! [::logspace()]: ../../struct.ArrayBase.html#method.logspace //! [::geomspace()]: ../../struct.ArrayBase.html#method.geomspace //! [.map()]: ../../struct.ArrayBase.html#method.map //! [.map_axis()]: ../../struct.ArrayBase.html#method.map_axis //! [.map_inplace()]: ../../struct.ArrayBase.html#method.map_inplace //! [.mapv()]: ../../struct.ArrayBase.html#method.mapv //! [.mapv_inplace()]: ../../struct.ArrayBase.html#method.mapv_inplace //! [.mapv_into()]: ../../struct.ArrayBase.html#method.mapv_into //! [matrix-* dot]: ../../struct.ArrayBase.html#method.dot-1 //! [.mean()]: ../../struct.ArrayBase.html#method.mean //! [.mean_axis()]: ../../struct.ArrayBase.html#method.mean_axis //! [.ndim()]: ../../struct.ArrayBase.html#method.ndim //! [NdProducer]: ../../trait.NdProducer.html //! [::ones()]: ../../struct.ArrayBase.html#method.ones //! [.outer_iter()]: ../../struct.ArrayBase.html#method.outer_iter //! [::range()]: ../../struct.ArrayBase.html#method.range //! [.raw_dim()]: ../../struct.ArrayBase.html#method.raw_dim //! [.reversed_axes()]: ../../struct.ArrayBase.html#method.reversed_axes //! [.row()]: ../../struct.ArrayBase.html#method.row //! [.row_mut()]: ../../struct.ArrayBase.html#method.row_mut //! [.nrows()]: ../../struct.ArrayBase.html#method.nrows //! [s!]: ../../macro.s.html //! [.sum()]: ../../struct.ArrayBase.html#method.sum //! [.slice()]: ../../struct.ArrayBase.html#method.slice //! [.slice_axis()]: ../../struct.ArrayBase.html#method.slice_axis //! [.slice_collapse()]: ../../struct.ArrayBase.html#method.slice_collapse //! [.slice_move()]: ../../struct.ArrayBase.html#method.slice_move //! [.slice_mut()]: ../../struct.ArrayBase.html#method.slice_mut //! [.shape()]: ../../struct.ArrayBase.html#method.shape //! [stack!]: ../../macro.stack.html //! [stack()]: ../../fn.stack.html //! [.strides()]: ../../struct.ArrayBase.html#method.strides //! [.index_axis()]: ../../struct.ArrayBase.html#method.index_axis //! [.sum_axis()]: ../../struct.ArrayBase.html#method.sum_axis //! [.t()]: ../../struct.ArrayBase.html#method.t //! [::uninitialized()]: ../../struct.ArrayBase.html#method.uninitialized //! [vec-* dot]: ../../struct.ArrayBase.html#method.dot //! [.visit()]: ../../struct.ArrayBase.html#method.visit //! [::zeros()]: ../../struct.ArrayBase.html#method.zeros //! [Zip]: ../../struct.Zip.html pub mod coord_transform; pub mod rk_step; pub mod simple_math;
39.092988
259
0.598869
1acff7cb7e5bbe545cd6df5c16fa4e6416056bb5
4,333
use crate::ast::{DataType, Expression, Node}; use std::fmt; pub type Statement = Node<Statements>; impl Statement { pub fn to_string(&self) -> String { self.node.to_string() } } impl fmt::Display for Statement { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.to_string()) } } #[derive(Clone, Debug)] pub enum Statements { Expression(Box<Expression>), Function { name: Box<Expression>, arguments: Vec<Expression>, return_type: Box<DataType>, body: Vec<Statement>, }, Interface(String, Vec<Expression>), Return(Option<Expression>), Variable { is_mutable: bool, name: String, data_type: Option<DataType>, value: Option<Expression>, }, } impl Statements { pub fn get_expression(&self) -> Option<Box<Expression>> { match self { Self::Expression(value) => Some(value.clone()), _ => None, } } pub fn get_function( &self, ) -> Option<( Box<Expression>, Vec<Expression>, Box<DataType>, Vec<Statement>, )> { match self { Self::Function { name, arguments, return_type, body, } => Some(( name.clone(), arguments.clone(), return_type.clone(), body.clone(), )), _ => None, } } pub fn get_interface(&self) -> Option<(String, Vec<Expression>)> { match self { Self::Interface(name, properties) => { Some((name.clone(), properties.clone())) } _ => None, } } pub fn get_return(&self) -> Option<Option<Expression>> { match self { Self::Return(value) => Some(value.clone()), _ => None, } } pub fn get_variable( &self, ) -> Option<(bool, String, Option<DataType>, Option<Expression>)> { match self { Self::Variable { is_mutable, name, data_type, value, } => Some(( is_mutable.clone(), name.clone(), data_type.clone(), value.clone(), )), _ => None, } } pub fn to_string(&self) -> String { match self { Self::Expression(value) => value.to_string(), Self::Function { name, arguments, return_type, body, } => format!( "func {} ({}): {} {{\n{}\n}}", name, arguments .iter() .map(|arg| arg.to_string()) .collect::<Vec<String>>() .join(", "), return_type, body.iter() .map(|stmt| stmt.to_string()) .collect::<Vec<String>>() .join("\n"), ), Self::Interface(name, properties) => format!( "interface {} {{\n{}\n}}", name, properties .iter() .map(|prop| prop.to_string()) .collect::<Vec<String>>() .join(";\n"), ), Self::Return(value) => format!( "return{};", match value { Some(value) => format!(" {}", value), None => String::new(), }, ), Self::Variable { is_mutable, name, data_type, value, } => format!( "{} {}{}{};", if *is_mutable { "let" } else { "const" }, name, match data_type { Some(data_type) => format!(": {}", data_type), None => String::new(), }, match value { Some(value) => format!(" = {}", value), None => String::new(), }, ), } } }
25.946108
71
0.394415
01044ffb4718e8d8832258d3bca526c031535bc1
184,475
// Copyright 2018 sqlparser-rs contributors. All rights reserved. // Copyright Materialize, Inc. and contributors. All rights reserved. // // This file is derived from the sqlparser-rs project, available at // https://github.com/andygrove/sqlparser-rs. It was incorporated // directly into Materialize on December 21, 2019. // // 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 in the LICENSE file at the // root of this repository, or online 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. //! SQL Parser use std::error::Error; use std::fmt; use itertools::Itertools; use tracing::warn; use mz_ore::collections::CollectionExt; use mz_ore::option::OptionExt; use mz_ore::stack::{CheckedRecursion, RecursionGuard, RecursionLimitError}; use crate::ast::*; use crate::keywords::*; use crate::lexer::{self, Token}; // NOTE(benesch): this recursion limit was chosen based on the maximum amount of // nesting I've ever seen in a production SQL query (i.e., about a dozen) times // a healthy factor to be conservative. const RECURSION_LIMIT: usize = 128; // Use `Parser::expected` instead, if possible macro_rules! parser_err { ($parser:expr, $pos:expr, $MSG:expr) => { Err($parser.error($pos, $MSG.to_string())) }; ($parser:expr, $pos:expr, $($arg:tt)*) => { Err($parser.error($pos, format!($($arg)*))) }; } /// Parses a SQL string containing zero or more SQL statements. pub fn parse_statements(sql: &str) -> Result<Vec<Statement<Raw>>, ParserError> { let tokens = lexer::lex(sql)?; Parser::new(sql, tokens).parse_statements() } /// Parses a SQL string containing one SQL expression. pub fn parse_expr(sql: &str) -> Result<Expr<Raw>, ParserError> { let tokens = lexer::lex(sql)?; let mut parser = Parser::new(sql, tokens); let expr = parser.parse_expr()?; if parser.next_token().is_some() { parser_err!( parser, parser.peek_prev_pos(), "extra token after expression" ) } else { Ok(expr) } } /// Parses a SQL string containing a single data type. pub fn parse_data_type(sql: &str) -> Result<UnresolvedDataType, ParserError> { let tokens = lexer::lex(sql)?; let mut parser = Parser::new(sql, tokens); let data_type = parser.parse_data_type()?; if parser.next_token().is_some() { parser_err!( parser, parser.peek_prev_pos(), "extra token after data type" ) } else { Ok(data_type) } } macro_rules! maybe { ($e:expr) => {{ if let Some(v) = $e { return Ok(v); } }}; } #[derive(PartialEq)] enum IsOptional { Optional, Mandatory, } use IsOptional::*; enum IsLateral { Lateral, NotLateral, } use IsLateral::*; #[derive(Debug, Clone, PartialEq)] pub struct ParserError { /// The error message. pub message: String, /// The byte position with which the error is associated. pub pos: usize, } impl fmt::Display for ParserError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.message) } } impl Error for ParserError {} impl From<RecursionLimitError> for ParserError { fn from(_: RecursionLimitError) -> ParserError { ParserError { pos: 0, message: format!( "statement exceeds nested expression limit of {}", RECURSION_LIMIT ), } } } impl ParserError { /// Constructs an error with the provided message at the provided position. pub(crate) fn new<S>(pos: usize, message: S) -> ParserError where S: Into<String>, { ParserError { pos, message: message.into(), } } } /// SQL Parser struct Parser<'a> { sql: &'a str, tokens: Vec<(Token, usize)>, /// The index of the first unprocessed token in `self.tokens` index: usize, recursion_guard: RecursionGuard, } /// Defines a number of precedence classes operators follow. Since this enum derives Ord, the /// precedence classes are ordered from weakest binding at the top to tightest binding at the /// bottom. #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] enum Precedence { Zero, Or, And, PrefixNot, Is, Cmp, Like, Other, PlusMinus, MultiplyDivide, PostfixCollateAt, PrefixPlusMinus, PostfixSubscriptCast, } #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] enum SetPrecedence { Zero, UnionExcept, Intersect, } impl<'a> Parser<'a> { /// Parse the specified tokens fn new(sql: &'a str, tokens: Vec<(Token, usize)>) -> Self { Parser { sql, tokens, index: 0, recursion_guard: RecursionGuard::with_limit(RECURSION_LIMIT), } } fn error(&self, pos: usize, message: String) -> ParserError { ParserError { pos, message } } fn parse_statements(&mut self) -> Result<Vec<Statement<Raw>>, ParserError> { let mut stmts = Vec::new(); let mut expecting_statement_delimiter = false; loop { // ignore empty statements (between successive statement delimiters) while self.consume_token(&Token::Semicolon) { expecting_statement_delimiter = false; } if self.peek_token().is_none() { break; } else if expecting_statement_delimiter { return self.expected(self.peek_pos(), "end of statement", self.peek_token()); } let statement = self.parse_statement()?; stmts.push(statement); expecting_statement_delimiter = true; } Ok(stmts) } /// Parse a single top-level statement (such as SELECT, INSERT, CREATE, etc.), /// stopping before the statement separator, if any. fn parse_statement(&mut self) -> Result<Statement<Raw>, ParserError> { match self.next_token() { Some(t) => match t { Token::Keyword(SELECT) | Token::Keyword(WITH) | Token::Keyword(VALUES) => { self.prev_token(); Ok(Statement::Select(SelectStatement { query: self.parse_query()?, as_of: self.parse_optional_as_of()?, })) } Token::Keyword(CREATE) => Ok(self.parse_create()?), Token::Keyword(DISCARD) => Ok(self.parse_discard()?), Token::Keyword(DROP) => Ok(self.parse_drop()?), Token::Keyword(DELETE) => Ok(self.parse_delete()?), Token::Keyword(INSERT) => Ok(self.parse_insert()?), Token::Keyword(UPDATE) => Ok(self.parse_update()?), Token::Keyword(ALTER) => Ok(self.parse_alter()?), Token::Keyword(COPY) => Ok(self.parse_copy()?), Token::Keyword(SET) => Ok(self.parse_set()?), Token::Keyword(SHOW) => Ok(self.parse_show()?), Token::Keyword(START) => Ok(self.parse_start_transaction()?), // `BEGIN` is a nonstandard but common alias for the // standard `START TRANSACTION` statement. It is supported // by at least PostgreSQL and MySQL. Token::Keyword(BEGIN) => Ok(self.parse_begin()?), Token::Keyword(COMMIT) => Ok(self.parse_commit()?), Token::Keyword(ROLLBACK) => Ok(self.parse_rollback()?), Token::Keyword(TAIL) => Ok(self.parse_tail()?), Token::Keyword(EXPLAIN) => Ok(self.parse_explain()?), Token::Keyword(DECLARE) => Ok(self.parse_declare()?), Token::Keyword(FETCH) => Ok(self.parse_fetch()?), Token::Keyword(CLOSE) => Ok(self.parse_close()?), Token::Keyword(PREPARE) => Ok(self.parse_prepare()?), Token::Keyword(EXECUTE) => Ok(self.parse_execute()?), Token::Keyword(DEALLOCATE) => Ok(self.parse_deallocate()?), Token::Keyword(RAISE) => Ok(self.parse_raise()?), Token::Keyword(kw) => parser_err!( self, self.peek_prev_pos(), format!("Unexpected keyword {} at the beginning of a statement", kw) ), Token::LParen => { self.prev_token(); Ok(Statement::Select(SelectStatement { query: self.parse_query()?, as_of: None, // Only the outermost SELECT may have an AS OF clause. })) } unexpected => self.expected( self.peek_prev_pos(), "a keyword at the beginning of a statement", Some(unexpected), ), }, None => self.expected(self.peek_prev_pos(), "SQL statement", None), } } /// Parse a new expression fn parse_expr(&mut self) -> Result<Expr<Raw>, ParserError> { self.parse_subexpr(Precedence::Zero) } /// Parse tokens until the precedence changes fn parse_subexpr(&mut self, precedence: Precedence) -> Result<Expr<Raw>, ParserError> { let expr = self.checked_recur_mut(|parser| parser.parse_prefix())?; self.parse_subexpr_seeded(precedence, expr) } fn parse_subexpr_seeded( &mut self, precedence: Precedence, mut expr: Expr<Raw>, ) -> Result<Expr<Raw>, ParserError> { self.checked_recur_mut(|parser| { loop { let next_precedence = parser.get_next_precedence(); if precedence >= next_precedence { break; } expr = parser.parse_infix(expr, next_precedence)?; } Ok(expr) }) } /// Parse an expression prefix fn parse_prefix(&mut self) -> Result<Expr<Raw>, ParserError> { // PostgreSQL allows any string literal to be preceded by a type name, // indicating that the string literal represents a literal of that type. // Some examples: // // DATE '2020-05-20' // TIMESTAMP WITH TIME ZONE '2020-05-20 7:43:54' // BOOL 'true' // // The first two are standard SQL, while the latter is a PostgreSQL // extension. Complicating matters is the fact that INTERVAL string // literals may optionally be followed by some special keywords, e.g.: // // INTERVAL '7' DAY // // Note also that naively `SELECT date` looks like a syntax error // because the `date` type name is not followed by a string literal, but // in fact is a valid expression that should parse as the column name // "date". maybe!(self.maybe_parse(|parser| { let data_type = parser.parse_data_type()?; if data_type.to_string().as_str() == "interval" { parser.parse_literal_interval() } else { Ok(Expr::Cast { expr: Box::new(Expr::Value(Value::String(parser.parse_literal_string()?))), data_type, }) } })); let tok = self .next_token() .ok_or_else(|| self.error(self.peek_prev_pos(), "Unexpected EOF".to_string()))?; let expr = match tok { Token::Keyword(TRUE) | Token::Keyword(FALSE) | Token::Keyword(NULL) => { self.prev_token(); Ok(Expr::Value(self.parse_value()?)) } Token::Keyword(ARRAY) => self.parse_array(), Token::Keyword(LIST) => self.parse_list(), Token::Keyword(CASE) => self.parse_case_expr(), Token::Keyword(CAST) => self.parse_cast_expr(), Token::Keyword(COALESCE) => { self.parse_homogenizing_function(HomogenizingFunction::Coalesce) } Token::Keyword(GREATEST) => { self.parse_homogenizing_function(HomogenizingFunction::Greatest) } Token::Keyword(LEAST) => self.parse_homogenizing_function(HomogenizingFunction::Least), Token::Keyword(NULLIF) => self.parse_nullif_expr(), Token::Keyword(EXISTS) => self.parse_exists_expr(), Token::Keyword(EXTRACT) => self.parse_extract_expr(), Token::Keyword(INTERVAL) => self.parse_literal_interval(), Token::Keyword(NOT) => Ok(Expr::Not { expr: Box::new(self.parse_subexpr(Precedence::PrefixNot)?), }), Token::Keyword(ROW) => self.parse_row_expr(), Token::Keyword(TRIM) => self.parse_trim_expr(), Token::Keyword(POSITION) if self.peek_token() == Some(Token::LParen) => { self.parse_position_expr() } Token::Keyword(SUBSTRING) => self.parse_substring_expr(), Token::Keyword(kw) if kw.is_reserved() => { return Err(self.error( self.peek_prev_pos(), "expected expression, but found reserved keyword".into(), )); } Token::Keyword(id) => self.parse_qualified_identifier(id.into_ident()), Token::Ident(id) => self.parse_qualified_identifier(Ident::new(id)), Token::Op(op) if op == "-" => { if let Some(Token::Number(n)) = self.peek_token() { let n = match n.parse::<f64>() { Ok(n) => n, Err(_) => { return Err( self.error(self.peek_prev_pos(), format!("invalid number {}", n)) ) } }; if n != 0.0 { self.prev_token(); return Ok(Expr::Value(self.parse_value()?)); } } Ok(Expr::Op { op: Op::bare(op), expr1: Box::new(self.parse_subexpr(Precedence::PrefixPlusMinus)?), expr2: None, }) } Token::Op(op) if op == "+" => Ok(Expr::Op { op: Op::bare(op), expr1: Box::new(self.parse_subexpr(Precedence::PrefixPlusMinus)?), expr2: None, }), Token::Op(op) if op == "~" => Ok(Expr::Op { op: Op::bare(op), expr1: Box::new(self.parse_subexpr(Precedence::Other)?), expr2: None, }), Token::Number(_) | Token::String(_) | Token::HexString(_) => { self.prev_token(); Ok(Expr::Value(self.parse_value()?)) } Token::Parameter(n) => Ok(Expr::Parameter(n)), Token::LParen => { let expr = self.parse_parenthesized_expr()?; self.expect_token(&Token::RParen)?; Ok(expr) } unexpected => self.expected(self.peek_prev_pos(), "an expression", Some(unexpected)), }?; Ok(expr) } /// Parses an expression that appears in parentheses, like `(1 + 1)` or /// `(SELECT 1)`. Assumes that the opening parenthesis has already been /// parsed. Parses up to the closing parenthesis without consuming it. fn parse_parenthesized_expr(&mut self) -> Result<Expr<Raw>, ParserError> { // The SQL grammar has an irritating ambiguity that presents here. // Consider these two expression fragments: // // SELECT (((SELECT 2)) + 3) // SELECT (((SELECT 2)) UNION SELECT 2) // ^ ^ // (1) (2) // When we see the parenthesis marked (1), we have no way to know ahead // of time whether that parenthesis is part of a `SetExpr::Query` inside // of an `Expr::Subquery` or whether it introduces an `Expr::Nested`. // The approach taken here avoids backtracking by deferring the decision // of whether to parse as a subquery or a nested expression until we get // to the point marked (2) above. Once there, we know that the presence // of a set operator implies that the parentheses belonged to a the // subquery; otherwise, they belonged to the expression. // // See also PostgreSQL's comments on the matter: // https://github.com/postgres/postgres/blob/42c63ab/src/backend/parser/gram.y#L11125-L11136 enum Either { Query(Query<Raw>), Expr(Expr<Raw>), } impl Either { fn into_expr(self) -> Expr<Raw> { match self { Either::Query(query) => Expr::Subquery(Box::new(query)), Either::Expr(expr) => expr, } } fn nest(self) -> Either { // Need to be careful to maintain expression nesting to preserve // operator precedence. But there are no precedence concerns for // queries, so we flatten to match parse_query's behavior. match self { Either::Expr(expr) => Either::Expr(Expr::Nested(Box::new(expr))), Either::Query(_) => self, } } } // Recursive helper for parsing parenthesized expressions. Each call // handles one layer of parentheses. Before every call, the parser must // be positioned after an opening parenthesis; upon non-error return, // the parser will be positioned before the corresponding close // parenthesis. Somewhat weirdly, the returned expression semantically // includes the opening/closing parentheses, even though this function // is not responsible for parsing them. fn parse(parser: &mut Parser) -> Result<Either, ParserError> { if parser.peek_keyword(SELECT) || parser.peek_keyword(WITH) { // Easy case one: unambiguously a subquery. Ok(Either::Query(parser.parse_query()?)) } else if !parser.consume_token(&Token::LParen) { // Easy case two: unambiguously an expression. let exprs = parser.parse_comma_separated(Parser::parse_expr)?; if exprs.len() == 1 { Ok(Either::Expr(Expr::Nested(Box::new(exprs.into_element())))) } else { Ok(Either::Expr(Expr::Row { exprs })) } } else { // Hard case: we have an open parenthesis, and we need to decide // whether it belongs to the query or the expression. // Parse to the closing parenthesis. let either = parser.checked_recur_mut(parse)?; parser.expect_token(&Token::RParen)?; // Decide if we need to associate any tokens after the closing // parenthesis with what we've parsed so far. match (either, parser.peek_token()) { // The next token is another closing parenthesis. Can't // resolve the ambiguity yet. Return to let our caller // handle it. (either, Some(Token::RParen)) => Ok(either.nest()), // The next token is a comma, which means `either` was the // first expression in an implicit row constructor. (either, Some(Token::Comma)) => { let mut exprs = vec![either.into_expr()]; while parser.consume_token(&Token::Comma) { exprs.push(parser.parse_expr()?); } Ok(Either::Expr(Expr::Row { exprs })) } // We have a subquery and the next token is a set operator. // That implies we have a partially-parsed subquery (or a // syntax error). Hop into parsing a set expression where // our subquery is the LHS of the set operator. (Either::Query(query), Some(Token::Keyword(kw))) if matches!(kw, UNION | INTERSECT | EXCEPT) => { let query = SetExpr::Query(Box::new(query)); let ctes = vec![]; let body = parser.parse_query_body_seeded(SetPrecedence::Zero, query)?; Ok(Either::Query(parser.parse_query_tail(ctes, body)?)) } // The next token is something else. That implies we have a // partially-parsed expression (or a syntax error). Hop into // parsing an expression where `either` is the expression // prefix. (either, _) => { let prefix = either.into_expr(); let expr = parser.parse_subexpr_seeded(Precedence::Zero, prefix)?; Ok(Either::Expr(expr).nest()) } } } } Ok(parse(self)?.into_expr()) } fn parse_function(&mut self, name: UnresolvedObjectName) -> Result<Expr<Raw>, ParserError> { self.expect_token(&Token::LParen)?; let distinct = matches!( self.parse_at_most_one_keyword(&[ALL, DISTINCT], &format!("function: {}", name))?, Some(DISTINCT), ); let args = self.parse_optional_args(true)?; if distinct && matches!(args, FunctionArgs::Star) { return Err(self.error( self.peek_prev_pos() - 1, "DISTINCT * not supported as function args".to_string(), )); } let filter = if self.parse_keyword(FILTER) { self.expect_token(&Token::LParen)?; self.expect_keyword(WHERE)?; let expr = self.parse_expr()?; self.expect_token(&Token::RParen)?; Some(Box::new(expr)) } else { None }; let over = if self.parse_keyword(OVER) { // TBD: support window names (`OVER mywin`) in place of inline specification self.expect_token(&Token::LParen)?; let partition_by = if self.parse_keywords(&[PARTITION, BY]) { // a list of possibly-qualified column names self.parse_comma_separated(Parser::parse_expr)? } else { vec![] }; let order_by = if self.parse_keywords(&[ORDER, BY]) { self.parse_comma_separated(Parser::parse_order_by_expr)? } else { vec![] }; let window_frame = if !self.consume_token(&Token::RParen) { let window_frame = self.parse_window_frame()?; self.expect_token(&Token::RParen)?; Some(window_frame) } else { None }; Some(WindowSpec { partition_by, order_by, window_frame, }) } else { None }; Ok(Expr::Function(Function { name, args, filter, over, distinct, })) } fn parse_window_frame(&mut self) -> Result<WindowFrame, ParserError> { let units = match self.expect_one_of_keywords(&[ROWS, RANGE, GROUPS])? { ROWS => WindowFrameUnits::Rows, RANGE => WindowFrameUnits::Range, GROUPS => WindowFrameUnits::Groups, _ => unreachable!(), }; let (start_bound, end_bound) = if self.parse_keyword(BETWEEN) { let start_bound = self.parse_window_frame_bound()?; self.expect_keyword(AND)?; let end_bound = Some(self.parse_window_frame_bound()?); (start_bound, end_bound) } else { (self.parse_window_frame_bound()?, None) }; Ok(WindowFrame { units, start_bound, end_bound, }) } /// Parse `CURRENT ROW` or `{ <positive number> | UNBOUNDED } { PRECEDING | FOLLOWING }` fn parse_window_frame_bound(&mut self) -> Result<WindowFrameBound, ParserError> { if self.parse_keywords(&[CURRENT, ROW]) { Ok(WindowFrameBound::CurrentRow) } else { let rows = if self.parse_keyword(UNBOUNDED) { None } else { Some(self.parse_literal_uint()?) }; if self.parse_keyword(PRECEDING) { Ok(WindowFrameBound::Preceding(rows)) } else if self.parse_keyword(FOLLOWING) { Ok(WindowFrameBound::Following(rows)) } else { self.expected(self.peek_pos(), "PRECEDING or FOLLOWING", self.peek_token()) } } } fn parse_case_expr(&mut self) -> Result<Expr<Raw>, ParserError> { let mut operand = None; if !self.parse_keyword(WHEN) { operand = Some(Box::new(self.parse_expr()?)); self.expect_keyword(WHEN)?; } let mut conditions = vec![]; let mut results = vec![]; loop { conditions.push(self.parse_expr()?); self.expect_keyword(THEN)?; results.push(self.parse_expr()?); if !self.parse_keyword(WHEN) { break; } } let else_result = if self.parse_keyword(ELSE) { Some(Box::new(self.parse_expr()?)) } else { None }; self.expect_keyword(END)?; Ok(Expr::Case { operand, conditions, results, else_result, }) } /// Parse a SQL CAST function e.g. `CAST(expr AS FLOAT)` fn parse_cast_expr(&mut self) -> Result<Expr<Raw>, ParserError> { self.expect_token(&Token::LParen)?; let expr = self.parse_expr()?; self.expect_keyword(AS)?; let data_type = self.parse_data_type()?; self.expect_token(&Token::RParen)?; Ok(Expr::Cast { expr: Box::new(expr), data_type, }) } /// Parse a SQL EXISTS expression e.g. `WHERE EXISTS(SELECT ...)`. fn parse_exists_expr(&mut self) -> Result<Expr<Raw>, ParserError> { self.expect_token(&Token::LParen)?; let exists_node = Expr::Exists(Box::new(self.parse_query()?)); self.expect_token(&Token::RParen)?; Ok(exists_node) } fn parse_homogenizing_function( &mut self, function: HomogenizingFunction, ) -> Result<Expr<Raw>, ParserError> { self.expect_token(&Token::LParen)?; let exprs = self.parse_comma_separated(Parser::parse_expr)?; self.expect_token(&Token::RParen)?; Ok(Expr::HomogenizingFunction { function, exprs }) } fn parse_nullif_expr(&mut self) -> Result<Expr<Raw>, ParserError> { self.expect_token(&Token::LParen)?; let l_expr = Box::new(self.parse_expr()?); self.expect_token(&Token::Comma)?; let r_expr = Box::new(self.parse_expr()?); self.expect_token(&Token::RParen)?; Ok(Expr::NullIf { l_expr, r_expr }) } fn parse_extract_expr(&mut self) -> Result<Expr<Raw>, ParserError> { self.expect_token(&Token::LParen)?; let field = match self.next_token() { Some(Token::Keyword(kw)) => kw.into_ident().into_string(), Some(Token::Ident(id)) => Ident::new(id).into_string(), Some(Token::String(s)) => s, t => self.expected(self.peek_prev_pos(), "extract field token", t)?, }; self.expect_keyword(FROM)?; let expr = self.parse_expr()?; self.expect_token(&Token::RParen)?; Ok(Expr::Function(Function { name: UnresolvedObjectName::unqualified("extract"), args: FunctionArgs::args(vec![Expr::Value(Value::String(field)), expr]), filter: None, over: None, distinct: false, })) } fn parse_row_expr(&mut self) -> Result<Expr<Raw>, ParserError> { self.expect_token(&Token::LParen)?; if self.consume_token(&Token::RParen) { Ok(Expr::Row { exprs: vec![] }) } else { let exprs = self.parse_comma_separated(Parser::parse_expr)?; self.expect_token(&Token::RParen)?; Ok(Expr::Row { exprs }) } } fn parse_composite_type_definition(&mut self) -> Result<Vec<ColumnDef<Raw>>, ParserError> { self.expect_token(&Token::LParen)?; let fields = self.parse_comma_separated(|parser| { Ok(ColumnDef { name: parser.parse_identifier()?, data_type: parser.parse_data_type()?, collation: None, options: vec![], }) })?; self.expect_token(&Token::RParen)?; Ok(fields) } // Parse calls to trim(), which can take the form: // - trim(side 'chars' from 'string') // - trim('chars' from 'string') // - trim(side from 'string') // - trim(from 'string') // - trim('string') // - trim(side 'string') fn parse_trim_expr(&mut self) -> Result<Expr<Raw>, ParserError> { self.expect_token(&Token::LParen)?; let name = match self.parse_one_of_keywords(&[BOTH, LEADING, TRAILING]) { None | Some(BOTH) => "btrim", Some(LEADING) => "ltrim", Some(TRAILING) => "rtrim", _ => unreachable!(), }; let mut exprs = Vec::new(); if self.parse_keyword(FROM) { // 'string' exprs.push(self.parse_expr()?); } else { // Either 'chars' or 'string' exprs.push(self.parse_expr()?); if self.parse_keyword(FROM) { // 'string'; previous must be 'chars' // Swap 'chars' and 'string' for compatibility with btrim, ltrim, and rtrim. exprs.insert(0, self.parse_expr()?); } } self.expect_token(&Token::RParen)?; Ok(Expr::Function(Function { name: UnresolvedObjectName::unqualified(name), args: FunctionArgs::args(exprs), filter: None, over: None, distinct: false, })) } // Parse calls to position(), which has the special form position('string' in 'string'). fn parse_position_expr(&mut self) -> Result<Expr<Raw>, ParserError> { self.expect_token(&Token::LParen)?; // we must be greater-equal the precedence of IN, which is Like to avoid // parsing away the IN as part of the sub expression let needle = self.parse_subexpr(Precedence::Like)?; self.expect_token(&Token::Keyword(IN))?; let haystack = self.parse_expr()?; self.expect_token(&Token::RParen)?; Ok(Expr::Function(Function { name: UnresolvedObjectName::unqualified("position"), args: FunctionArgs::args(vec![needle, haystack]), filter: None, over: None, distinct: false, })) } /// Parse an INTERVAL literal. /// /// Some syntactically valid intervals: /// /// 1. `INTERVAL '1' DAY` /// 2. `INTERVAL '1-1' YEAR TO MONTH` /// 3. `INTERVAL '1' SECOND` /// 4. `INTERVAL '1:1' MINUTE TO SECOND /// 5. `INTERVAL '1:1:1.1' HOUR TO SECOND (5)` /// 6. `INTERVAL '1.111' SECOND (2)` /// fn parse_literal_interval(&mut self) -> Result<Expr<Raw>, ParserError> { // The first token in an interval is a string literal which specifies // the duration of the interval. let value = self.parse_literal_string()?; // Determine the range of TimeUnits, whether explicit (`INTERVAL ... DAY TO MINUTE`) or // implicit (in which all date fields are eligible). let (precision_high, precision_low, fsec_max_precision) = match self.expect_one_of_keywords(&[ YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, ]) { Ok(d) => { let d_pos = self.peek_prev_pos(); if self.parse_keyword(TO) { let e = self.expect_one_of_keywords(&[ YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, ])?; let high: DateTimeField = d .as_str() .parse() .map_err(|e| self.error(self.peek_prev_pos(), e))?; let low: DateTimeField = e .as_str() .parse() .map_err(|e| self.error(self.peek_prev_pos(), e))?; // Check for invalid ranges, i.e. precision_high is the same // as or a less significant DateTimeField than // precision_low. if high >= low { return parser_err!( self, d_pos, "Invalid field range in INTERVAL '{}' {} TO {}; the value in the \ position of {} should be more significant than {}.", value, d, e, d, e, ); } let fsec_max_precision = if low == DateTimeField::Second { self.parse_optional_precision()? } else { None }; (high, low, fsec_max_precision) } else { let low: DateTimeField = d .as_str() .parse() .map_err(|e| self.error(self.peek_prev_pos(), e))?; let fsec_max_precision = if low == DateTimeField::Second { self.parse_optional_precision()? } else { None }; (DateTimeField::Year, low, fsec_max_precision) } } Err(_) => (DateTimeField::Year, DateTimeField::Second, None), }; Ok(Expr::Value(Value::Interval(IntervalValue { value, precision_high, precision_low, fsec_max_precision, }))) } /// Parse an operator following an expression fn parse_infix( &mut self, expr: Expr<Raw>, precedence: Precedence, ) -> Result<Expr<Raw>, ParserError> { let tok = self.next_token().unwrap(); // safe as EOF's precedence is the lowest let regular_binary_operator = match &tok { Token::Op(s) => Some(Op::bare(s)), Token::Eq => Some(Op::bare("=")), Token::Star => Some(Op::bare("*")), Token::Keyword(OPERATOR) => { self.expect_token(&Token::LParen)?; let op = self.parse_operator()?; self.expect_token(&Token::RParen)?; Some(op) } _ => None, }; if let Some(op) = regular_binary_operator { if let Some(kw) = self.parse_one_of_keywords(&[ANY, SOME, ALL]) { self.expect_token(&Token::LParen)?; let expr = if self.parse_one_of_keywords(&[SELECT, VALUES]).is_some() { self.prev_token(); let subquery = self.parse_query()?; if kw == ALL { Expr::AllSubquery { left: Box::new(expr), op, right: Box::new(subquery), } } else { Expr::AnySubquery { left: Box::new(expr), op, right: Box::new(subquery), } } } else { let right = self.parse_expr()?; if kw == ALL { Expr::AllExpr { left: Box::new(expr), op, right: Box::new(right), } } else { Expr::AnyExpr { left: Box::new(expr), op, right: Box::new(right), } } }; self.expect_token(&Token::RParen)?; Ok(expr) } else { Ok(Expr::Op { op, expr1: Box::new(expr), expr2: Some(Box::new(self.parse_subexpr(precedence)?)), }) } } else if let Token::Keyword(kw) = tok { match kw { IS => { let negated = self.parse_keyword(NOT); if let Some(construct) = self.parse_one_of_keywords(&[NULL, TRUE, FALSE, UNKNOWN]) { Ok(Expr::IsExpr { expr: Box::new(expr), negated, construct: match construct { NULL => IsExprConstruct::Null, TRUE => IsExprConstruct::True, FALSE => IsExprConstruct::False, UNKNOWN => IsExprConstruct::Unknown, _ => unreachable!(), }, }) } else { self.expected( self.peek_pos(), "NULL, NOT NULL, TRUE, NOT TRUE, FALSE, NOT FALSE, UNKNOWN, NOT UNKNOWN after IS", self.peek_token(), ) } } ISNULL => Ok(Expr::IsExpr { expr: Box::new(expr), negated: false, construct: IsExprConstruct::Null, }), NOT | IN | LIKE | ILIKE | BETWEEN => { self.prev_token(); let negated = self.parse_keyword(NOT); if self.parse_keyword(IN) { self.parse_in(expr, negated) } else if self.parse_keyword(BETWEEN) { self.parse_between(expr, negated) } else if self.parse_keyword(LIKE) { self.parse_like(expr, false, negated) } else if self.parse_keyword(ILIKE) { self.parse_like(expr, true, negated) } else { self.expected( self.peek_pos(), "IN, BETWEEN, LIKE, or ILIKE after NOT", self.peek_token(), ) } } AND => Ok(Expr::And { left: Box::new(expr), right: Box::new(self.parse_subexpr(precedence)?), }), OR => Ok(Expr::Or { left: Box::new(expr), right: Box::new(self.parse_subexpr(precedence)?), }), AT => { self.expect_keywords(&[TIME, ZONE])?; Ok(Expr::Function(Function { name: UnresolvedObjectName(vec!["timezone".into()]), args: FunctionArgs::args(vec![self.parse_subexpr(precedence)?, expr]), filter: None, over: None, distinct: false, })) } COLLATE => Ok(Expr::Collate { expr: Box::new(expr), collation: self.parse_object_name()?, }), // Can only happen if `get_next_precedence` got out of sync with this function _ => panic!("No infix parser for token {:?}", tok), } } else if Token::DoubleColon == tok { self.parse_pg_cast(expr) } else if Token::LBracket == tok { self.prev_token(); self.parse_subscript(expr) } else if Token::Dot == tok { match self.next_token() { Some(Token::Ident(id)) => Ok(Expr::FieldAccess { expr: Box::new(expr), field: Ident::new(id), }), // Per PostgreSQL, even reserved keywords are ok after a field // access operator. Some(Token::Keyword(kw)) => Ok(Expr::FieldAccess { expr: Box::new(expr), field: kw.into_ident(), }), Some(Token::Star) => Ok(Expr::WildcardAccess(Box::new(expr))), unexpected => self.expected( self.peek_prev_pos(), "an identifier or a '*' after '.'", unexpected, ), } } else { // Can only happen if `get_next_precedence` got out of sync with this function panic!("No infix parser for token {:?}", tok) } } /// Parse subscript expression, i.e. either an index value or slice range. fn parse_subscript(&mut self, expr: Expr<Raw>) -> Result<Expr<Raw>, ParserError> { let mut positions = Vec::new(); while self.consume_token(&Token::LBracket) { let start = if self.peek_token() == Some(Token::Colon) { None } else { Some(self.parse_expr()?) }; let (end, explicit_slice) = if self.consume_token(&Token::Colon) { // Presence of a colon means these positions were explicit ( // Terminated expr if self.peek_token() == Some(Token::RBracket) { None } else { Some(self.parse_expr()?) }, true, ) } else { (None, false) }; assert!( start.is_some() || explicit_slice, "user typed something between brackets" ); assert!( explicit_slice || end.is_none(), "if end is some, must have an explicit slice" ); positions.push(SubscriptPosition { start, end, explicit_slice, }); self.expect_token(&Token::RBracket)?; } Ok(Expr::Subscript { expr: Box::new(expr), positions, }) } // Parse calls to substring(), which can take the form: // - substring('string', 'int') // - substring('string', 'int', 'int') // - substring('string' FROM 'int') // - substring('string' FROM 'int' FOR 'int') // - substring('string' FOR 'int') fn parse_substring_expr(&mut self) -> Result<Expr<Raw>, ParserError> { self.expect_token(&Token::LParen)?; let mut exprs = vec![self.parse_expr()?]; if self.parse_keyword(FROM) { // 'string' FROM 'int' exprs.push(self.parse_expr()?); if self.parse_keyword(FOR) { // 'string' FROM 'int' FOR 'int' exprs.push(self.parse_expr()?); } } else if self.parse_keyword(FOR) { // 'string' FOR 'int' exprs.push(Expr::Value(Value::Number(String::from("1")))); exprs.push(self.parse_expr()?); } else { // 'string', 'int' // or // 'string', 'int', 'int' self.expect_token(&Token::Comma)?; exprs.extend(self.parse_comma_separated(Parser::parse_expr)?); } self.expect_token(&Token::RParen)?; Ok(Expr::Function(Function { name: UnresolvedObjectName::unqualified("substring"), args: FunctionArgs::args(exprs), filter: None, over: None, distinct: false, })) } /// Parse an operator reference. /// /// Examples: /// * `+` /// * `OPERATOR(schema.+)` /// * `OPERATOR("foo"."bar"."baz".@>)` fn parse_operator(&mut self) -> Result<Op, ParserError> { let mut namespace = vec![]; loop { match self.next_token() { Some(Token::Keyword(kw)) => namespace.push(kw.into_ident()), Some(Token::Ident(id)) => namespace.push(Ident::new(id)), Some(Token::Op(op)) => return Ok(Op { namespace, op }), Some(Token::Star) => { let op = String::from("*"); return Ok(Op { namespace, op }); } tok => self.expected(self.peek_prev_pos(), "operator", tok)?, } self.expect_token(&Token::Dot)?; } } /// Parses the parens following the `[ NOT ] IN` operator fn parse_in(&mut self, expr: Expr<Raw>, negated: bool) -> Result<Expr<Raw>, ParserError> { self.expect_token(&Token::LParen)?; let in_op = if self .parse_one_of_keywords(&[SELECT, VALUES, WITH]) .is_some() { self.prev_token(); Expr::InSubquery { expr: Box::new(expr), subquery: Box::new(self.parse_query()?), negated, } } else { Expr::InList { expr: Box::new(expr), list: self.parse_comma_separated(Parser::parse_expr)?, negated, } }; self.expect_token(&Token::RParen)?; Ok(in_op) } /// Parses `BETWEEN <low> AND <high>`, assuming the `BETWEEN` keyword was already consumed fn parse_between(&mut self, expr: Expr<Raw>, negated: bool) -> Result<Expr<Raw>, ParserError> { // Stop parsing subexpressions for <low> and <high> on tokens with // precedence lower than that of `BETWEEN`, such as `AND`, `IS`, etc. let low = self.parse_subexpr(Precedence::Like)?; self.expect_keyword(AND)?; let high = self.parse_subexpr(Precedence::Like)?; Ok(Expr::Between { expr: Box::new(expr), negated, low: Box::new(low), high: Box::new(high), }) } /// Parses `LIKE <pattern> [ ESCAPE <char> ]`, assuming the `LIKE` keyword was already consumed fn parse_like( &mut self, expr: Expr<Raw>, case_insensitive: bool, negated: bool, ) -> Result<Expr<Raw>, ParserError> { let pattern = self.parse_subexpr(Precedence::Like)?; let escape = if self.parse_keyword(ESCAPE) { Some(Box::new(self.parse_subexpr(Precedence::Like)?)) } else { None }; Ok(Expr::Like { expr: Box::new(expr), pattern: Box::new(pattern), escape, case_insensitive, negated, }) } /// Parse a postgresql casting style which is in the form of `expr::datatype` fn parse_pg_cast(&mut self, expr: Expr<Raw>) -> Result<Expr<Raw>, ParserError> { Ok(Expr::Cast { expr: Box::new(expr), data_type: self.parse_data_type()?, }) } /// Get the precedence of the next token fn get_next_precedence(&self) -> Precedence { if let Some(token) = self.peek_token() { match &token { Token::Keyword(OR) => Precedence::Or, Token::Keyword(AND) => Precedence::And, Token::Keyword(NOT) => match &self.peek_nth_token(1) { // The precedence of NOT varies depending on keyword that // follows it. If it is followed by IN, BETWEEN, or LIKE, // it takes on the precedence of those tokens. Otherwise it // is not an infix operator, and therefore has zero // precedence. Some(Token::Keyword(IN)) => Precedence::Like, Some(Token::Keyword(BETWEEN)) => Precedence::Like, Some(Token::Keyword(ILIKE)) => Precedence::Like, Some(Token::Keyword(LIKE)) => Precedence::Like, _ => Precedence::Zero, }, Token::Keyword(IS) | Token::Keyword(ISNULL) => Precedence::Is, Token::Keyword(IN) => Precedence::Like, Token::Keyword(BETWEEN) => Precedence::Like, Token::Keyword(ILIKE) => Precedence::Like, Token::Keyword(LIKE) => Precedence::Like, Token::Keyword(OPERATOR) => Precedence::Other, Token::Op(s) => match s.as_str() { "<" | "<=" | "<>" | "!=" | ">" | ">=" => Precedence::Cmp, "+" | "-" => Precedence::PlusMinus, "/" | "%" => Precedence::MultiplyDivide, _ => Precedence::Other, }, Token::Eq => Precedence::Cmp, Token::Star => Precedence::MultiplyDivide, Token::Keyword(COLLATE) | Token::Keyword(AT) => Precedence::PostfixCollateAt, Token::DoubleColon | Token::LBracket | Token::Dot => { Precedence::PostfixSubscriptCast } _ => Precedence::Zero, } } else { Precedence::Zero } } /// Return the first non-whitespace token that has not yet been processed /// (or None if reached end-of-file) fn peek_token(&self) -> Option<Token> { self.peek_nth_token(0) } fn peek_keyword(&mut self, kw: Keyword) -> bool { match self.peek_token() { Some(Token::Keyword(k)) => k == kw, _ => false, } } fn peek_keywords(&mut self, keywords: &[Keyword]) -> bool { for (i, keyword) in keywords.iter().enumerate() { match self.peek_nth_token(i) { Some(Token::Keyword(k)) => { if k != *keyword { return false; } } _ => return false, } } true } /// Return the nth token that has not yet been processed. fn peek_nth_token(&self, n: usize) -> Option<Token> { self.tokens.get(self.index + n).map(|(t, _)| t.clone()) } /// Return the next token that has not yet been processed, or None if /// reached end-of-file, and mark it as processed. OK to call repeatedly /// after reaching EOF. fn next_token(&mut self) -> Option<Token> { let token = self .tokens .get(self.index) .map(|(token, _range)| token.clone()); self.index += 1; token } /// Push back the last one non-whitespace token. Must be called after /// `next_token()`, otherwise might panic. OK to call after /// `next_token()` indicates an EOF. fn prev_token(&mut self) { assert!(self.index > 0); self.index -= 1; } /// Return the byte position within the query string at which the /// next token starts. fn peek_pos(&self) -> usize { match self.tokens.get(self.index) { Some((_token, pos)) => *pos, None => self.sql.len(), } } /// Return the byte position within the query string at which the previous /// token starts. /// /// Must be called after `next_token()`, otherwise might panic. /// OK to call after `next_token()` indicates an EOF. fn peek_prev_pos(&self) -> usize { assert!(self.index > 0); match self.tokens.get(self.index - 1) { Some((_token, pos)) => *pos, None => self.sql.len(), } } /// Report unexpected token fn expected<D, T>( &self, pos: usize, expected: D, found: Option<Token>, ) -> Result<T, ParserError> where D: fmt::Display, { parser_err!( self, pos, "Expected {}, found {}", expected, found.display_or("EOF"), ) } /// Look for an expected keyword and consume it if it exists #[must_use] fn parse_keyword(&mut self, kw: Keyword) -> bool { if self.peek_keyword(kw) { self.next_token(); true } else { false } } /// Look for an expected sequence of keywords and consume them if they exist #[must_use] fn parse_keywords(&mut self, keywords: &[Keyword]) -> bool { if self.peek_keywords(keywords) { self.index += keywords.len(); true } else { false } } fn parse_at_most_one_keyword( &mut self, keywords: &[Keyword], location: &str, ) -> Result<Option<Keyword>, ParserError> { match self.parse_one_of_keywords(keywords) { Some(first) => { let remaining_keywords = keywords .iter() .cloned() .filter(|k| *k != first) .collect::<Vec<_>>(); if let Some(second) = self.parse_one_of_keywords(remaining_keywords.as_slice()) { let second_pos = self.peek_prev_pos(); parser_err!( self, second_pos, "Cannot specify both {} and {} in {}", first, second, location, ) } else { Ok(Some(first)) } } None => Ok(None), } } /// Look for one of the given keywords and return the one that matches. #[must_use] fn parse_one_of_keywords(&mut self, kws: &[Keyword]) -> Option<Keyword> { match self.peek_token() { Some(Token::Keyword(k)) => kws.iter().find(|kw| **kw == k).map(|kw| { self.next_token(); *kw }), _ => None, } } /// Bail out if the current token is not one of the expected keywords, or consume it if it is fn expect_one_of_keywords(&mut self, keywords: &[Keyword]) -> Result<Keyword, ParserError> { if let Some(keyword) = self.parse_one_of_keywords(keywords) { Ok(keyword) } else { self.expected( self.peek_pos(), &format!("one of {}", keywords.iter().join(" or ")), self.peek_token(), ) } } /// Bail out if the current token is not an expected keyword, or consume it if it is fn expect_keyword(&mut self, expected: Keyword) -> Result<(), ParserError> { if self.parse_keyword(expected) { Ok(()) } else { self.expected(self.peek_pos(), expected, self.peek_token()) } } /// Bail out if the following tokens are not the expected sequence of /// keywords, or consume them if they are. fn expect_keywords(&mut self, expected: &[Keyword]) -> Result<(), ParserError> { for kw in expected { self.expect_keyword(*kw)?; } Ok(()) } /// Consume the next token if it matches the expected token, otherwise return false #[must_use] fn consume_token(&mut self, expected: &Token) -> bool { match &self.peek_token() { Some(t) if *t == *expected => { self.next_token(); true } _ => false, } } /// Bail out if the current token is not an expected keyword, or consume it if it is fn expect_token(&mut self, expected: &Token) -> Result<(), ParserError> { if self.consume_token(expected) { Ok(()) } else { self.expected(self.peek_pos(), expected, self.peek_token()) } } /// Parse a comma-separated list of 1+ items accepted by `F` fn parse_comma_separated<T, F>(&mut self, mut f: F) -> Result<Vec<T>, ParserError> where F: FnMut(&mut Self) -> Result<T, ParserError>, { let mut values = vec![]; loop { values.push(f(self)?); if !self.consume_token(&Token::Comma) { break; } } Ok(values) } #[must_use] fn maybe_parse<T, F>(&mut self, mut f: F) -> Option<T> where F: FnMut(&mut Self) -> Result<T, ParserError>, { let index = self.index; if let Ok(t) = f(self) { Some(t) } else { self.index = index; None } } /// Parse a SQL CREATE statement fn parse_create(&mut self) -> Result<Statement<Raw>, ParserError> { if self.peek_keyword(DATABASE) { self.parse_create_database() } else if self.peek_keyword(SCHEMA) { self.parse_create_schema() } else if self.peek_keyword(SINK) { self.parse_create_sink() } else if self.peek_keyword(TYPE) { self.parse_create_type() } else if self.peek_keyword(ROLE) || self.peek_keyword(USER) { self.parse_create_role() } else if self.peek_keyword(CLUSTER) { self.parse_create_cluster() } else if self.peek_keyword(INDEX) || self.peek_keywords(&[DEFAULT, INDEX]) { self.parse_create_index() } else if self.peek_keyword(SOURCE) || self.peek_keywords(&[MATERIALIZED, SOURCE]) { self.parse_create_source() } else if self.peek_keyword(TABLE) || self.peek_keywords(&[TEMP, TABLE]) || self.peek_keywords(&[TEMPORARY, TABLE]) { self.parse_create_table() } else if self.peek_keyword(SECRET) { self.parse_create_secret() } else if self.peek_keyword(CONNECTOR) { self.parse_create_connector() } else { let index = self.index; // go over optional modifiers let _ = self.parse_keywords(&[OR, REPLACE]); let _ = self.parse_one_of_keywords(&[TEMP, TEMPORARY]); let _ = self.parse_keyword(MATERIALIZED); if self.parse_keyword(VIEW) { self.index = index; self.parse_create_view() } else if self.parse_keyword(VIEWS) { self.index = index; self.parse_create_views() } else { self.expected( self.peek_pos(), "DATABASE, SCHEMA, ROLE, USER, TYPE, INDEX, SINK, SOURCE, TABLE, SECRET or [OR REPLACE] [TEMPORARY] [MATERIALIZED] VIEW or VIEWS after CREATE", self.peek_token(), ) } } } fn parse_create_database(&mut self) -> Result<Statement<Raw>, ParserError> { self.expect_keyword(DATABASE)?; let if_not_exists = self.parse_if_not_exists()?; let name = self.parse_database_name()?; Ok(Statement::CreateDatabase(CreateDatabaseStatement { name, if_not_exists, })) } fn parse_create_schema(&mut self) -> Result<Statement<Raw>, ParserError> { self.expect_keyword(SCHEMA)?; let if_not_exists = self.parse_if_not_exists()?; let name = self.parse_schema_name()?; Ok(Statement::CreateSchema(CreateSchemaStatement { name, if_not_exists, })) } fn parse_format(&mut self) -> Result<Format<Raw>, ParserError> { let format = if self.parse_keyword(AVRO) { self.expect_keyword(USING)?; Format::Avro(self.parse_avro_schema()?) } else if self.parse_keyword(PROTOBUF) { Format::Protobuf(self.parse_protobuf_schema()?) } else if self.parse_keyword(REGEX) { let regex = self.parse_literal_string()?; Format::Regex(regex) } else if self.parse_keyword(CSV) { self.expect_keyword(WITH)?; let columns = if self.parse_keyword(HEADER) || self.parse_keyword(HEADERS) { CsvColumns::Header { names: self.parse_parenthesized_column_list(Optional)?, } } else { let n_cols = self.parse_literal_uint()? as usize; self.expect_keyword(COLUMNS)?; CsvColumns::Count(n_cols) }; let delimiter = if self.parse_keywords(&[DELIMITED, BY]) { let s = self.parse_literal_string()?; match s.len() { 1 => Ok(s.chars().next().unwrap()), _ => self.expected(self.peek_pos(), "one-character string", self.peek_token()), }? } else { ',' }; Format::Csv { columns, delimiter } } else if self.parse_keyword(JSON) { Format::Json } else if self.parse_keyword(TEXT) { Format::Text } else if self.parse_keyword(BYTES) { Format::Bytes } else { return self.expected( self.peek_pos(), "AVRO, PROTOBUF, REGEX, CSV, JSON, TEXT, or BYTES", self.peek_token(), ); }; Ok(format) } fn parse_avro_schema(&mut self) -> Result<AvroSchema<Raw>, ParserError> { let avro_schema = if self.parse_keywords(&[CONFLUENT, SCHEMA, REGISTRY]) { let csr_connector = self.parse_csr_connector_avro()?; AvroSchema::Csr { csr_connector } } else if self.parse_keyword(SCHEMA) { self.prev_token(); let schema = self.parse_schema()?; // Look ahead to avoid erroring on `WITH SNAPSHOT`; we only want to // accept `WITH (...)` here. let with_options = if self.peek_nth_token(1) == Some(Token::LParen) { self.expect_keyword(WITH)?; self.parse_with_options(false)? } else { vec![] }; AvroSchema::InlineSchema { schema, with_options, } } else { return self.expected( self.peek_pos(), "CONFLUENT SCHEMA REGISTRY or SCHEMA", self.peek_token(), ); }; Ok(avro_schema) } fn parse_protobuf_schema(&mut self) -> Result<ProtobufSchema<Raw>, ParserError> { if self.parse_keywords(&[USING, CONFLUENT, SCHEMA, REGISTRY]) { let csr_connector = self.parse_csr_connector_proto()?; Ok(ProtobufSchema::Csr { csr_connector }) } else if self.parse_keyword(MESSAGE) { let message_name = self.parse_literal_string()?; self.expect_keyword(USING)?; let schema = self.parse_schema()?; Ok(ProtobufSchema::InlineSchema { message_name, schema, }) } else { return self.expected( self.peek_pos(), "CONFLUENT SCHEMA REGISTRY or MESSAGE", self.peek_token(), ); } } fn parse_csr_connector_avro(&mut self) -> Result<CsrConnectorAvro<Raw>, ParserError> { let url = self.parse_literal_string()?; let seed = if self.parse_keyword(SEED) { let key_schema = if self.parse_keyword(KEY) { self.expect_keyword(SCHEMA)?; Some(self.parse_literal_string()?) } else { None }; self.expect_keywords(&[VALUE, SCHEMA])?; let value_schema = self.parse_literal_string()?; Some(CsrSeed { key_schema, value_schema, }) } else { None }; // Look ahead to avoid erroring on `WITH SNAPSHOT`; we only want to // accept `WITH (...)` here. let with_options = if self.peek_nth_token(1) == Some(Token::LParen) { self.parse_opt_with_options()? } else { vec![] }; Ok(CsrConnectorAvro { url, seed, with_options, }) } fn parse_csr_connector_proto(&mut self) -> Result<CsrConnectorProto<Raw>, ParserError> { let url = self.parse_literal_string()?; let seed = if self.parse_keyword(SEED) { if self.parse_keyword(COMPILED) { let key = if self.parse_keyword(KEY) { self.expect_keyword(SCHEMA)?; let schema = self.parse_literal_string()?; self.expect_keyword(MESSAGE)?; let message_name = self.parse_literal_string()?; Some(CsrSeedCompiledEncoding { schema, message_name, }) } else { None }; self.expect_keywords(&[VALUE, SCHEMA])?; let value_schema = self.parse_literal_string()?; self.expect_keyword(MESSAGE)?; let value_message_name = self.parse_literal_string()?; Some(CsrSeedCompiledOrLegacy::Compiled(CsrSeedCompiled { value: CsrSeedCompiledEncoding { schema: value_schema, message_name: value_message_name, }, key, })) } else { let key_schema = if self.parse_keyword(KEY) { self.expect_keyword(SCHEMA)?; Some(self.parse_literal_string()?) } else { None }; self.expect_keywords(&[VALUE, SCHEMA])?; let value_schema = self.parse_literal_string()?; Some(CsrSeedCompiledOrLegacy::Legacy(CsrSeed { value_schema, key_schema, })) } } else { None }; // Look ahead to avoid erroring on `WITH SNAPSHOT`; we only want to // accept `WITH (...)` here. let with_options = if self.peek_nth_token(1) == Some(Token::LParen) { self.parse_opt_with_options()? } else { vec![] }; Ok(CsrConnectorProto { url, seed, with_options, }) } fn parse_schema(&mut self) -> Result<Schema, ParserError> { self.expect_keyword(SCHEMA)?; let schema = if self.parse_keyword(FILE) { Schema::File(self.parse_literal_string()?.into()) } else { Schema::Inline(self.parse_literal_string()?) }; Ok(schema) } fn parse_envelope(&mut self) -> Result<Envelope, ParserError> { let envelope = if self.parse_keyword(NONE) { Envelope::None } else if self.parse_keyword(DEBEZIUM) { let debezium_mode = if self.parse_keyword(UPSERT) { DbzMode::Upsert } else { DbzMode::Plain }; Envelope::Debezium(debezium_mode) } else if self.parse_keyword(UPSERT) { Envelope::Upsert } else if self.parse_keyword(MATERIALIZE) { Envelope::CdcV2 } else { return self.expected( self.peek_pos(), "NONE, DEBEZIUM, UPSERT, or MATERIALIZE", self.peek_token(), ); }; Ok(envelope) } fn parse_compression(&mut self) -> Result<Compression, ParserError> { let compression = if self.parse_keyword(NONE) { Compression::None } else if self.parse_keyword(GZIP) { Compression::Gzip } else { return self.expected(self.peek_pos(), "NONE or GZIP", self.peek_token()); }; Ok(compression) } fn parse_create_connector(&mut self) -> Result<Statement<Raw>, ParserError> { self.expect_keyword(CONNECTOR)?; let if_not_exists = self.parse_if_not_exists()?; let name = self.parse_object_name()?; self.expect_keyword(FOR)?; let connector = match self.expect_one_of_keywords(&[KAFKA])? { Keyword::Kafka => { self.expect_keyword(BROKER)?; let broker = self.parse_literal_string()?; let with_options = self.parse_opt_with_options()?; CreateConnector::Kafka { broker, with_options, } } _ => unreachable!(), }; Ok(Statement::CreateConnector(CreateConnectorStatement { name, connector, if_not_exists, })) } fn parse_create_source(&mut self) -> Result<Statement<Raw>, ParserError> { let materialized = self.parse_keyword(MATERIALIZED); self.expect_keyword(SOURCE)?; let if_not_exists = self.parse_if_not_exists()?; let name = self.parse_object_name()?; let (col_names, key_constraint) = self.parse_source_columns()?; self.expect_keyword(FROM)?; let connector = self.parse_create_source_connector()?; let with_options = self.parse_opt_with_options()?; // legacy upsert format syntax allows setting the key format after the keyword UPSERT, so we // may mutate this variable in the next block let mut format = match self.parse_one_of_keywords(&[KEY, FORMAT]) { Some(KEY) => { self.expect_keyword(FORMAT)?; let key = self.parse_format()?; self.expect_keywords(&[VALUE, FORMAT])?; let value = self.parse_format()?; CreateSourceFormat::KeyValue { key, value } } Some(FORMAT) => CreateSourceFormat::Bare(self.parse_format()?), Some(_) => unreachable!("parse_one_of_keywords returns None for this"), None => CreateSourceFormat::None, }; let include_metadata = self.parse_source_include_metadata()?; let envelope = if self.parse_keyword(ENVELOPE) { let envelope = self.parse_envelope()?; if matches!(envelope, Envelope::Upsert) { // TODO: remove support for explicit UPSERT FORMAT after a period of deprecation if self.parse_keyword(FORMAT) { warn!("UPSERT FORMAT has been deprecated, use the new KEY FORMAT syntax"); if let CreateSourceFormat::Bare(value) = format { let key = self.parse_format()?; format = CreateSourceFormat::KeyValue { key, value }; } else { self.error( self.index, "ENVELOPE UPSERT FORMAT conflicts with earlier KEY FORMAT specification".into(), ); } } } Some(envelope) } else { None }; Ok(Statement::CreateSource(CreateSourceStatement { name, col_names, connector, with_options, format, include_metadata, envelope, if_not_exists, materialized, key_constraint, })) } /// Parses the column section of a CREATE SOURCE statement which can be /// empty or a comma-separated list of column identifiers and a single key /// constraint, e.g. /// /// (col_0, col_i, ..., col_n, key_constraint) fn parse_source_columns(&mut self) -> Result<(Vec<Ident>, Option<KeyConstraint>), ParserError> { if self.consume_token(&Token::LParen) { let mut columns = vec![]; let mut key_constraints = vec![]; loop { let pos = self.peek_pos(); if let Some(key_constraint) = self.parse_key_constraint()? { if !key_constraints.is_empty() { return parser_err!(self, pos, "Multiple key constraints not allowed"); } key_constraints.push(key_constraint); } else { columns.push(self.parse_identifier()?); } if !self.consume_token(&Token::Comma) { break; } } self.expect_token(&Token::RParen)?; Ok((columns, key_constraints.into_iter().next())) } else { Ok((vec![], None)) } } /// Parses a key constraint. fn parse_key_constraint(&mut self) -> Result<Option<KeyConstraint>, ParserError> { // PRIMARY KEY (col_1, ..., col_n) NOT ENFORCED if self.parse_keywords(&[PRIMARY, KEY]) { let columns = self.parse_parenthesized_column_list(Mandatory)?; self.expect_keywords(&[NOT, ENFORCED])?; Ok(Some(KeyConstraint::PrimaryKeyNotEnforced { columns })) } else { Ok(None) } } fn parse_create_sink(&mut self) -> Result<Statement<Raw>, ParserError> { self.expect_keyword(SINK)?; let if_not_exists = self.parse_if_not_exists()?; let name = self.parse_object_name()?; let in_cluster = self.parse_optional_in_cluster()?; self.expect_keyword(FROM)?; let from = self.parse_raw_name()?; self.expect_keyword(INTO)?; let connector = self.parse_create_sink_connector()?; let mut with_options = vec![]; if self.parse_keyword(WITH) { if let Some(Token::LParen) = self.next_token() { self.prev_token(); self.prev_token(); with_options = self.parse_opt_with_options()?; } } let format = if self.parse_keyword(FORMAT) { Some(self.parse_format()?) } else { None }; let envelope = if self.parse_keyword(ENVELOPE) { Some(self.parse_envelope()?) } else { None }; let with_snapshot = if self.parse_keyword(WITH) { self.expect_keyword(SNAPSHOT)?; true } else if self.parse_keyword(WITHOUT) { self.expect_keyword(SNAPSHOT)?; false } else { // If neither WITH nor WITHOUT SNAPSHOT is provided, // default to WITH SNAPSHOT. true }; let as_of = self.parse_optional_as_of()?; Ok(Statement::CreateSink(CreateSinkStatement { name, in_cluster, from, connector, with_options, format, envelope, with_snapshot, as_of, if_not_exists, })) } fn parse_create_source_connector(&mut self) -> Result<CreateSourceConnector<Raw>, ParserError> { match self .expect_one_of_keywords(&[FILE, KAFKA, KINESIS, AVRO, S3, PERSIST, POSTGRES, PUBNUB])? { PUBNUB => { self.expect_keywords(&[SUBSCRIBE, KEY])?; let subscribe_key = self.parse_literal_string()?; self.expect_keyword(CHANNEL)?; let channel = self.parse_literal_string()?; Ok(CreateSourceConnector::PubNub { subscribe_key, channel, }) } POSTGRES => { self.expect_keyword(CONNECTION)?; let conn = self.parse_literal_string()?; self.expect_keyword(PUBLICATION)?; let publication = self.parse_literal_string()?; let slot = if self.parse_keyword(SLOT) { Some(self.parse_literal_string()?) } else { None }; let details = if self.parse_keyword(DETAILS) { Some(self.parse_literal_string()?) } else { None }; Ok(CreateSourceConnector::Postgres { conn, publication, slot, details, }) } PERSIST => { self.expect_keyword(CONSENSUS)?; let consensus_uri = self.parse_literal_string()?; self.expect_keyword(BLOB)?; let blob_uri = self.parse_literal_string()?; self.expect_keyword(SHARD)?; let shard_id = self.parse_literal_string()?; // TODO: fail if/when we have constraints let (columns, _constraints) = self.parse_columns(Mandatory)?; Ok(CreateSourceConnector::Persist { consensus_uri, blob_uri, collection_id: shard_id, columns, }) } FILE => { let path = self.parse_literal_string()?; let compression = if self.parse_keyword(COMPRESSION) { self.parse_compression()? } else { Compression::None }; Ok(CreateSourceConnector::File { path, compression }) } KAFKA => { let connector = match self.expect_one_of_keywords(&[BROKER, CONNECTOR])? { BROKER => KafkaConnector::Inline { broker: self.parse_literal_string()?, }, CONNECTOR => KafkaConnector::Reference { connector: self.parse_object_name()?, }, _ => unreachable!(), }; self.expect_keyword(TOPIC)?; let topic = self.parse_literal_string()?; // one token of lookahead: // * `KEY (` means we're parsing a list of columns for the key // * `KEY FORMAT` means there is no key, we'll parse a KeyValueFormat later let key = if self.peek_keyword(KEY) && self.peek_nth_token(1) != Some(Token::Keyword(FORMAT)) { let _ = self.expect_keyword(KEY); Some(self.parse_parenthesized_column_list(Mandatory)?) } else { None }; Ok(CreateSourceConnector::Kafka(KafkaSourceConnector { connector, topic, key, })) } KINESIS => { self.expect_keyword(ARN)?; let arn = self.parse_literal_string()?; Ok(CreateSourceConnector::Kinesis { arn }) } S3 => { // FROM S3 DISCOVER OBJECTS // (MATCHING '<pattern>')? // USING // (BUCKET SCAN '<bucket>' | SQS NOTIFICATIONS '<channel>')+ self.expect_keywords(&[DISCOVER, OBJECTS])?; let pattern = if self.parse_keyword(MATCHING) { Some(self.parse_literal_string()?) } else { None }; self.expect_keyword(USING)?; let mut key_sources = Vec::new(); while let Some(keyword) = self.parse_one_of_keywords(&[BUCKET, SQS]) { match keyword { BUCKET => { self.expect_keyword(SCAN)?; let bucket = self.parse_literal_string()?; key_sources.push(S3KeySource::Scan { bucket }); } SQS => { self.expect_keyword(NOTIFICATIONS)?; let queue = self.parse_literal_string()?; key_sources.push(S3KeySource::SqsNotifications { queue }); } key => unreachable!( "Keyword {} is not expected after DISCOVER OBJECTS USING", key ), } if !self.consume_token(&Token::Comma) { break; } } let compression = if self.parse_keyword(COMPRESSION) { self.parse_compression()? } else { Compression::None }; Ok(CreateSourceConnector::S3 { key_sources, pattern, compression, }) } _ => unreachable!(), } } fn parse_create_sink_connector(&mut self) -> Result<CreateSinkConnector<Raw>, ParserError> { match self.expect_one_of_keywords(&[KAFKA, AVRO, PERSIST])? { KAFKA => { self.expect_keyword(BROKER)?; let broker = self.parse_literal_string()?; self.expect_keyword(TOPIC)?; let topic = self.parse_literal_string()?; // one token of lookahead: // * `KEY (` means we're parsing a list of columns for the key // * `KEY FORMAT` means there is no key, we'll parse a KeyValueFormat later let key = if self.peek_keyword(KEY) && self.peek_nth_token(1) != Some(Token::Keyword(FORMAT)) { let _ = self.expect_keyword(KEY); let key_columns = self.parse_parenthesized_column_list(Mandatory)?; let not_enforced = if self.peek_keywords(&[NOT, ENFORCED]) { let _ = self.expect_keywords(&[NOT, ENFORCED])?; true } else { false }; Some(KafkaSinkKey { key_columns, not_enforced, }) } else { None }; let consistency = self.parse_kafka_consistency()?; Ok(CreateSinkConnector::Kafka { broker, topic, key, consistency, }) } PERSIST => { // TODO(aljoscha): We should not require (or allow) passing in consensus/blob // configuration on the sink. Instead, we need to pick up the config that was given // to materialized/storaged when starting up. self.expect_keyword(CONSENSUS)?; let consensus_uri = self.parse_literal_string()?; self.expect_keyword(BLOB)?; let blob_uri = self.parse_literal_string()?; let shard_id = if self.peek_keyword(SHARD) { let _ = self.expect_keyword(SHARD)?; self.parse_literal_string()? } else { // TODO(aljoscha): persist/storage sinks should have a human-readable // collection name and STORAGE needs to keep track of which shard IDs they map // to. Also, the lifecycle of collections created by a sink should be tracked // separate from the sink. And we can expose something like a `mz_collections` // to allow querying them. let shard_id = mz_persist_client::ShardId::new(); format!("{}", shard_id) }; Ok(CreateSinkConnector::Persist { consensus_uri, blob_uri, shard_id, }) } _ => unreachable!(), } } fn parse_kafka_consistency(&mut self) -> Result<Option<KafkaConsistency<Raw>>, ParserError> { if self.parse_keyword(CONSISTENCY) { // We would prefer for all consistency parameters to be // parenthesized, but for backwards compatibility we support an // unparenthesized syntax that has some ambiguity issues // (see #8231). // // Bad: // CONSISTENCY TOPIC 'foo' CONSISTENCY FORMAT 'bar' WITH (format_option = 'blah') // Good: // CONSISTENCY (TOPIC 'foo' FORMAT 'bar' WITH (format_option = 'blah')) let parenthesized = self.consume_token(&Token::LParen); self.expect_keyword(TOPIC)?; let topic = self.parse_literal_string()?; let topic_format = if (parenthesized && self.parse_keyword(FORMAT)) || (!parenthesized && self.parse_keywords(&[CONSISTENCY, FORMAT])) { Some(self.parse_format()?) } else { None }; if parenthesized { self.expect_token(&Token::RParen)?; } Ok(Some(KafkaConsistency { topic, topic_format, })) } else { Ok(None) } } fn parse_create_view(&mut self) -> Result<Statement<Raw>, ParserError> { let mut if_exists = if self.parse_keyword(OR) { self.expect_keyword(REPLACE)?; IfExistsBehavior::Replace } else { IfExistsBehavior::Error }; let temporary = self.parse_keyword(TEMPORARY) | self.parse_keyword(TEMP); let materialized = self.parse_keyword(MATERIALIZED); self.expect_keyword(VIEW)?; if if_exists == IfExistsBehavior::Error && self.parse_if_not_exists()? { if_exists = IfExistsBehavior::Skip; } let definition = self.parse_view_definition()?; Ok(Statement::CreateView(CreateViewStatement { temporary, materialized, if_exists, definition, })) } fn parse_view_definition(&mut self) -> Result<ViewDefinition<Raw>, ParserError> { // Many dialects support `OR REPLACE` | `OR ALTER` right after `CREATE`, but we don't (yet). // ANSI SQL and Postgres support RECURSIVE here, but we don't support it either. let name = self.parse_object_name()?; let columns = self.parse_parenthesized_column_list(Optional)?; let with_options = self.parse_opt_with_options()?; self.expect_keyword(AS)?; let query = self.parse_query()?; // Optional `WITH [ CASCADED | LOCAL ] CHECK OPTION` is widely supported here. Ok(ViewDefinition { name, columns, with_options, query, }) } fn parse_create_views(&mut self) -> Result<Statement<Raw>, ParserError> { let mut if_exists = if self.parse_keyword(OR) { self.expect_keyword(REPLACE)?; IfExistsBehavior::Replace } else { IfExistsBehavior::Error }; let temporary = self.parse_keyword(TEMPORARY) | self.parse_keyword(TEMP); let materialized = self.parse_keyword(MATERIALIZED); self.expect_keyword(VIEWS)?; if if_exists == IfExistsBehavior::Error && self.parse_if_not_exists()? { if_exists = IfExistsBehavior::Skip; } let definitions = if self.parse_keywords(&[FROM, SOURCE]) { let name = self.parse_raw_name()?; let targets = if self.consume_token(&Token::LParen) { let targets = self.parse_comma_separated(|parser| { let name = parser.parse_object_name()?; let alias = if parser.parse_keyword(AS) { Some(parser.parse_object_name()?) } else { None }; Ok(CreateViewsSourceTarget { name, alias }) })?; self.expect_token(&Token::RParen)?; Some(targets) } else { None }; CreateViewsDefinitions::Source { name, targets } } else { let views = self.parse_comma_separated(|parser| { parser.expect_token(&Token::LParen)?; let view = parser.parse_view_definition()?; parser.expect_token(&Token::RParen)?; Ok(view) })?; CreateViewsDefinitions::Literal(views) }; Ok(Statement::CreateViews(CreateViewsStatement { temporary, materialized, if_exists, definitions, })) } fn parse_create_index(&mut self) -> Result<Statement<Raw>, ParserError> { let default_index = self.parse_keyword(DEFAULT); self.expect_keyword(INDEX)?; let if_not_exists = self.parse_if_not_exists()?; let name = if self.peek_keyword(IN) || self.peek_keyword(ON) { if if_not_exists && !default_index { return self.expected(self.peek_pos(), "index name", self.peek_token()); } None } else { Some(self.parse_identifier()?) }; let in_cluster = self.parse_optional_in_cluster()?; self.expect_keyword(ON)?; let on_name = self.parse_raw_name()?; // Arrangements are the only index type we support, so we can just ignore this if self.parse_keyword(USING) { self.expect_keyword(ARRANGEMENT)?; } let key_parts = if default_index { None } else { self.expect_token(&Token::LParen)?; if self.consume_token(&Token::RParen) { Some(vec![]) } else { let key_parts = self .parse_comma_separated(Parser::parse_order_by_expr)? .into_iter() .map(|x| x.expr) .collect::<Vec<_>>(); self.expect_token(&Token::RParen)?; Some(key_parts) } }; let with_options = self.parse_opt_with_options()?; Ok(Statement::CreateIndex(CreateIndexStatement { name, in_cluster, on_name, key_parts, with_options, if_not_exists, })) } fn parse_raw_ident(&mut self) -> Result<RawIdent, ParserError> { if self.consume_token(&Token::LBracket) { let id = match self.next_token() { Some(Token::Ident(id)) => id, Some(Token::Number(n)) => n, _ => return parser_err!(self, self.peek_prev_pos(), "expected id"), }; self.expect_token(&Token::RBracket)?; Ok(RawIdent::Resolved(id)) } else { Ok(RawIdent::Unresolved(self.parse_identifier()?)) } } fn parse_optional_in_cluster(&mut self) -> Result<Option<RawIdent>, ParserError> { if self.parse_keywords(&[IN, CLUSTER]) { Ok(Some(self.parse_raw_ident()?)) } else { Ok(None) } } fn parse_create_role(&mut self) -> Result<Statement<Raw>, ParserError> { let is_user = match self.expect_one_of_keywords(&[ROLE, USER])? { ROLE => false, USER => true, _ => unreachable!(), }; let name = self.parse_identifier()?; let _ = self.parse_keyword(WITH); let mut options = vec![]; loop { match self.parse_one_of_keywords(&[SUPERUSER, NOSUPERUSER, LOGIN, NOLOGIN]) { None => break, Some(SUPERUSER) => options.push(CreateRoleOption::SuperUser), Some(NOSUPERUSER) => options.push(CreateRoleOption::NoSuperUser), Some(LOGIN) => options.push(CreateRoleOption::Login), Some(NOLOGIN) => options.push(CreateRoleOption::NoLogin), Some(_) => unreachable!(), } } Ok(Statement::CreateRole(CreateRoleStatement { is_user, name, options, })) } fn parse_create_secret(&mut self) -> Result<Statement<Raw>, ParserError> { self.expect_keyword(SECRET)?; let if_not_exists = self.parse_if_not_exists()?; let name = self.parse_object_name()?; self.expect_keyword(AS)?; let value = self.parse_expr()?; Ok(Statement::CreateSecret(CreateSecretStatement { name, if_not_exists, value, })) } fn parse_create_type(&mut self) -> Result<Statement<Raw>, ParserError> { self.expect_keyword(TYPE)?; let name = self.parse_object_name()?; self.expect_keyword(AS)?; match self.parse_one_of_keywords(&[LIST, MAP]) { Some(as_type) => { self.expect_token(&Token::LParen)?; let with_options = self.parse_comma_separated(Parser::parse_data_type_option)?; self.expect_token(&Token::RParen)?; let as_type = match as_type { LIST => CreateTypeAs::List { with_options }, MAP => CreateTypeAs::Map { with_options }, _ => unreachable!(), }; Ok(Statement::CreateType(CreateTypeStatement { name, as_type })) } None => { let column_defs = self.parse_composite_type_definition()?; Ok(Statement::CreateType(CreateTypeStatement { name, as_type: CreateTypeAs::Record { column_defs }, })) } } } fn parse_data_type_option(&mut self) -> Result<WithOption<Raw>, ParserError> { let key = self.parse_identifier()?; self.expect_token(&Token::Eq)?; Ok(WithOption { key, value: Some(WithOptionValue::DataType(self.parse_data_type()?)), }) } fn parse_create_cluster(&mut self) -> Result<Statement<Raw>, ParserError> { self.next_token(); let name = self.parse_identifier()?; let _ = self.parse_keyword(WITH); let options = if matches!(self.peek_token(), Some(Token::Semicolon) | None) { vec![] } else { self.parse_comma_separated(Parser::parse_cluster_option)? }; Ok(Statement::CreateCluster(CreateClusterStatement { name, options, })) } fn parse_cluster_option(&mut self) -> Result<ClusterOption<Raw>, ParserError> { match self.expect_one_of_keywords(&[REMOTE, SIZE, INTROSPECTION])? { REMOTE => { let name = self.parse_identifier()?; self.expect_token(&Token::LParen)?; let hosts = self.parse_comma_separated(Self::parse_with_option_value)?; self.expect_token(&Token::RParen)?; Ok(ClusterOption::Remote { name, hosts }) } SIZE => { let _ = self.consume_token(&Token::Eq); Ok(ClusterOption::Size(self.parse_with_option_value()?)) } INTROSPECTION => match self.expect_one_of_keywords(&[DEBUGGING, GRANULARITY])? { DEBUGGING => { let _ = self.consume_token(&Token::Eq); Ok(ClusterOption::IntrospectionDebugging( self.parse_with_option_value()?, )) } GRANULARITY => { let _ = self.consume_token(&Token::Eq); Ok(ClusterOption::IntrospectionGranularity( self.parse_with_option_value()?, )) } _ => unreachable!(), }, _ => unreachable!(), } } fn parse_if_exists(&mut self) -> Result<bool, ParserError> { if self.parse_keyword(IF) { self.expect_keyword(EXISTS)?; Ok(true) } else { Ok(false) } } fn parse_if_not_exists(&mut self) -> Result<bool, ParserError> { if self.parse_keyword(IF) { self.expect_keywords(&[NOT, EXISTS])?; Ok(true) } else { Ok(false) } } fn parse_source_include_metadata(&mut self) -> Result<Vec<SourceIncludeMetadata>, ParserError> { if self.parse_keyword(INCLUDE) { self.parse_comma_separated(|parser| { let ty = match parser .expect_one_of_keywords(&[KEY, TIMESTAMP, PARTITION, TOPIC, OFFSET, HEADERS])? { KEY => SourceIncludeMetadataType::Key, TIMESTAMP => SourceIncludeMetadataType::Timestamp, PARTITION => SourceIncludeMetadataType::Partition, TOPIC => SourceIncludeMetadataType::Topic, OFFSET => SourceIncludeMetadataType::Offset, HEADERS => SourceIncludeMetadataType::Headers, _ => unreachable!("only explicitly allowed items can be parsed"), }; let alias = parser .parse_keyword(AS) .then(|| parser.parse_identifier()) .transpose()?; Ok(SourceIncludeMetadata { ty, alias }) }) } else { Ok(vec![]) } } fn parse_discard(&mut self) -> Result<Statement<Raw>, ParserError> { let target = match self.expect_one_of_keywords(&[ALL, PLANS, SEQUENCES, TEMP, TEMPORARY])? { ALL => DiscardTarget::All, PLANS => DiscardTarget::Plans, SEQUENCES => DiscardTarget::Sequences, TEMP | TEMPORARY => DiscardTarget::Temp, _ => unreachable!(), }; Ok(Statement::Discard(DiscardStatement { target })) } fn parse_drop(&mut self) -> Result<Statement<Raw>, ParserError> { let materialized = self.parse_keyword(MATERIALIZED); let object_type = match self.parse_one_of_keywords(&[ DATABASE, INDEX, ROLE, CLUSTER, SECRET, SCHEMA, SINK, SOURCE, TABLE, TYPE, USER, VIEW, CONNECTOR, ]) { Some(DATABASE) => { let if_exists = self.parse_if_exists()?; let name = self.parse_database_name()?; let restrict = matches!( self.parse_at_most_one_keyword(&[CASCADE, RESTRICT], "DROP")?, Some(RESTRICT), ); return Ok(Statement::DropDatabase(DropDatabaseStatement { if_exists, name, restrict, })); } Some(SCHEMA) => { let if_exists = self.parse_if_exists()?; let name = self.parse_schema_name()?; let cascade = matches!( self.parse_at_most_one_keyword(&[CASCADE, RESTRICT], "DROP")?, Some(CASCADE), ); return Ok(Statement::DropSchema(DropSchemaStatement { name, if_exists, cascade, })); } Some(ROLE) | Some(USER) => { let if_exists = self.parse_if_exists()?; let names = self.parse_comma_separated(Parser::parse_object_name)?; return Ok(Statement::DropRoles(DropRolesStatement { if_exists, names, })); } Some(CLUSTER) => { let if_exists = self.parse_if_exists()?; let names = self.parse_comma_separated(Parser::parse_object_name)?; let cascade = matches!( self.parse_at_most_one_keyword(&[CASCADE, RESTRICT], "DROP")?, Some(CASCADE), ); return Ok(Statement::DropClusters(DropClustersStatement { if_exists, names, cascade, })); } Some(INDEX) => ObjectType::Index, Some(SINK) => ObjectType::Sink, Some(SOURCE) => ObjectType::Source, Some(TABLE) => ObjectType::Table, Some(TYPE) => ObjectType::Type, Some(VIEW) => ObjectType::View, Some(SECRET) => ObjectType::Secret, Some(CONNECTOR) => ObjectType::Connector, _ => { return self.expected( self.peek_pos(), "DATABASE, INDEX, ROLE, CLUSTER, SECRET, SCHEMA, SINK, SOURCE, \ TABLE, TYPE, USER, VIEW after DROP", self.peek_token(), ); } }; let if_exists = self.parse_if_exists()?; let names = self.parse_comma_separated(Parser::parse_raw_name)?; let cascade = matches!( self.parse_at_most_one_keyword(&[CASCADE, RESTRICT], "DROP")?, Some(CASCADE), ); Ok(Statement::DropObjects(DropObjectsStatement { materialized, object_type, if_exists, names, cascade, })) } fn parse_create_table(&mut self) -> Result<Statement<Raw>, ParserError> { let temporary = self.parse_keyword(TEMPORARY) | self.parse_keyword(TEMP); self.expect_keyword(TABLE)?; let if_not_exists = self.parse_if_not_exists()?; let table_name = self.parse_object_name()?; // parse optional column list (schema) let (columns, constraints) = self.parse_columns(Mandatory)?; let with_options = self.parse_opt_with_options()?; Ok(Statement::CreateTable(CreateTableStatement { name: table_name, columns, constraints, with_options, if_not_exists, temporary, })) } fn parse_columns( &mut self, optional: IsOptional, ) -> Result<(Vec<ColumnDef<Raw>>, Vec<TableConstraint<Raw>>), ParserError> { let mut columns = vec![]; let mut constraints = vec![]; if !self.consume_token(&Token::LParen) { if optional == Optional { return Ok((columns, constraints)); } else { return self.expected( self.peek_pos(), "a list of columns in parentheses", self.peek_token(), ); } } if self.consume_token(&Token::RParen) { // Tables with zero columns are a PostgreSQL extension. return Ok((columns, constraints)); } loop { if let Some(constraint) = self.parse_optional_table_constraint()? { constraints.push(constraint); } else if let Some(column_name) = self.consume_identifier() { let data_type = self.parse_data_type()?; let collation = if self.parse_keyword(COLLATE) { Some(self.parse_object_name()?) } else { None }; let mut options = vec![]; loop { match self.peek_token() { None | Some(Token::Comma) | Some(Token::RParen) => break, _ => options.push(self.parse_column_option_def()?), } } columns.push(ColumnDef { name: column_name, data_type, collation, options, }); } else { return self.expected( self.peek_pos(), "column name or constraint definition", self.peek_token(), ); } if self.consume_token(&Token::Comma) { // Continue. } else if self.consume_token(&Token::RParen) { break; } else { return self.expected( self.peek_pos(), "',' or ')' after column definition", self.peek_token(), ); } } Ok((columns, constraints)) } fn parse_column_option_def(&mut self) -> Result<ColumnOptionDef<Raw>, ParserError> { let name = if self.parse_keyword(CONSTRAINT) { Some(self.parse_identifier()?) } else { None }; let option = if self.parse_keywords(&[NOT, NULL]) { ColumnOption::NotNull } else if self.parse_keyword(NULL) { ColumnOption::Null } else if self.parse_keyword(DEFAULT) { ColumnOption::Default(self.parse_expr()?) } else if self.parse_keywords(&[PRIMARY, KEY]) { ColumnOption::Unique { is_primary: true } } else if self.parse_keyword(UNIQUE) { ColumnOption::Unique { is_primary: false } } else if self.parse_keyword(REFERENCES) { let foreign_table = self.parse_object_name()?; let referred_columns = self.parse_parenthesized_column_list(Mandatory)?; ColumnOption::ForeignKey { foreign_table, referred_columns, } } else if self.parse_keyword(CHECK) { self.expect_token(&Token::LParen)?; let expr = self.parse_expr()?; self.expect_token(&Token::RParen)?; ColumnOption::Check(expr) } else { return self.expected(self.peek_pos(), "column option", self.peek_token()); }; Ok(ColumnOptionDef { name, option }) } fn parse_optional_table_constraint( &mut self, ) -> Result<Option<TableConstraint<Raw>>, ParserError> { let name = if self.parse_keyword(CONSTRAINT) { Some(self.parse_identifier()?) } else { None }; match self.next_token() { Some(Token::Keyword(kw @ PRIMARY)) | Some(Token::Keyword(kw @ UNIQUE)) => { let is_primary = kw == PRIMARY; if is_primary { self.expect_keyword(KEY)?; } let columns = self.parse_parenthesized_column_list(Mandatory)?; Ok(Some(TableConstraint::Unique { name, columns, is_primary, })) } Some(Token::Keyword(FOREIGN)) => { self.expect_keyword(KEY)?; let columns = self.parse_parenthesized_column_list(Mandatory)?; self.expect_keyword(REFERENCES)?; let foreign_table = self.parse_raw_name()?; let referred_columns = self.parse_parenthesized_column_list(Mandatory)?; Ok(Some(TableConstraint::ForeignKey { name, columns, foreign_table, referred_columns, })) } Some(Token::Keyword(CHECK)) => { self.expect_token(&Token::LParen)?; let expr = Box::new(self.parse_expr()?); self.expect_token(&Token::RParen)?; Ok(Some(TableConstraint::Check { name, expr })) } unexpected => { if name.is_some() { self.expected( self.peek_prev_pos(), "PRIMARY, UNIQUE, FOREIGN, or CHECK", unexpected, ) } else { self.prev_token(); Ok(None) } } } } fn parse_opt_with_options(&mut self) -> Result<Vec<WithOption<Raw>>, ParserError> { if self.parse_keyword(WITH) { self.parse_with_options(true) } else { Ok(vec![]) } } fn parse_with_options( &mut self, require_equals: bool, ) -> Result<Vec<WithOption<Raw>>, ParserError> { self.expect_token(&Token::LParen)?; let options = self.parse_comma_separated(|parser| parser.parse_with_option(require_equals))?; self.expect_token(&Token::RParen)?; Ok(options) } /// If require_equals is true, parse options of the form `KEY = VALUE` or just /// `KEY`. If require_equals is false, additionally support `KEY VALUE` (but still the others). fn parse_with_option(&mut self, require_equals: bool) -> Result<WithOption<Raw>, ParserError> { let key = self.parse_identifier()?; let has_eq = self.consume_token(&Token::Eq); // No = was encountered and require_equals is false, so the next token might be // a value and might not. The only valid things that indicate no value would // be `)` for end-of-options or `,` for another-option. Either of those means // there's no value, anything else means we expect a valid value. let has_value = !matches!(self.peek_token(), Some(Token::RParen) | Some(Token::Comma)); if has_value && !has_eq && require_equals { return self.expected(self.peek_pos(), Token::Eq, self.peek_token()); } let value = if has_value { Some(self.parse_with_option_value()?) } else { None }; Ok(WithOption { key, value }) } fn parse_with_option_value(&mut self) -> Result<WithOptionValue<Raw>, ParserError> { if let Some(value) = self.maybe_parse(Parser::parse_value) { Ok(WithOptionValue::Value(value)) } else if let Some(object_name) = self.maybe_parse(Parser::parse_object_name) { Ok(WithOptionValue::ObjectName(object_name)) } else { return self.expected(self.peek_pos(), "option value", self.peek_token()); } } fn parse_alter(&mut self) -> Result<Statement<Raw>, ParserError> { let object_type = match self .expect_one_of_keywords(&[SINK, SOURCE, VIEW, TABLE, INDEX, SECRET, CLUSTER])? { SINK => ObjectType::Sink, SOURCE => ObjectType::Source, VIEW => ObjectType::View, TABLE => ObjectType::Table, INDEX => return self.parse_alter_index(), SECRET => return self.parse_alter_secret(), CLUSTER => return self.parse_alter_cluster(), _ => unreachable!(), }; let if_exists = self.parse_if_exists()?; let name = self.parse_raw_name()?; self.expect_keywords(&[RENAME, TO])?; let to_item_name = self.parse_identifier()?; Ok(Statement::AlterObjectRename(AlterObjectRenameStatement { object_type, if_exists, name, to_item_name, })) } fn parse_alter_index(&mut self) -> Result<Statement<Raw>, ParserError> { let if_exists = self.parse_if_exists()?; let name = self.parse_raw_name()?; Ok(match self.expect_one_of_keywords(&[RESET, SET, RENAME])? { RESET => { self.expect_token(&Token::LParen)?; let reset_options = self.parse_comma_separated(Parser::parse_identifier)?; self.expect_token(&Token::RParen)?; Statement::AlterIndex(AlterIndexStatement { index_name: name, if_exists, action: AlterIndexAction::ResetOptions(reset_options), }) } SET => { if self.parse_keyword(ENABLED) { Statement::AlterIndex(AlterIndexStatement { index_name: name, if_exists, action: AlterIndexAction::Enable, }) } else { let set_options = self.parse_with_options(true)?; Statement::AlterIndex(AlterIndexStatement { index_name: name, if_exists, action: AlterIndexAction::SetOptions(set_options), }) } } RENAME => { self.expect_keyword(TO)?; let to_item_name = self.parse_identifier()?; Statement::AlterObjectRename(AlterObjectRenameStatement { object_type: ObjectType::Index, if_exists, name, to_item_name, }) } _ => unreachable!(), }) } fn parse_alter_secret(&mut self) -> Result<Statement<Raw>, ParserError> { let if_exists = self.parse_if_exists()?; let name = self.parse_raw_name()?; Ok(match self.expect_one_of_keywords(&[AS, RENAME])? { AS => { let value = self.parse_expr()?; Statement::AlterSecret(AlterSecretStatement { name, if_exists, value, }) } RENAME => { self.expect_keyword(TO)?; let to_item_name = self.parse_identifier()?; Statement::AlterObjectRename(AlterObjectRenameStatement { object_type: ObjectType::Secret, if_exists, name, to_item_name, }) } _ => unreachable!(), }) } fn parse_alter_cluster(&mut self) -> Result<Statement<Raw>, ParserError> { let if_exists = self.parse_if_exists()?; let name = self.parse_identifier()?; let _ = self.parse_keyword(WITH); let options = if matches!(self.peek_token(), Some(Token::Semicolon) | None) { vec![] } else { self.parse_comma_separated(Parser::parse_cluster_option)? }; Ok(Statement::AlterCluster(AlterClusterStatement { name, if_exists, options, })) } /// Parse a copy statement fn parse_copy(&mut self) -> Result<Statement<Raw>, ParserError> { let relation = if self.consume_token(&Token::LParen) { let query = self.parse_statement()?; self.expect_token(&Token::RParen)?; match query { Statement::Select(stmt) => CopyRelation::Select(stmt), Statement::Tail(stmt) => CopyRelation::Tail(stmt), _ => return parser_err!(self, self.peek_prev_pos(), "unsupported query in COPY"), } } else { let name = self.parse_raw_name()?; let columns = self.parse_parenthesized_column_list(Optional)?; CopyRelation::Table { name, columns } }; let (direction, target) = match self.expect_one_of_keywords(&[FROM, TO])? { FROM => { if let CopyRelation::Table { .. } = relation { // Ok. } else { return parser_err!( self, self.peek_prev_pos(), "queries not allowed in COPY FROM" ); } self.expect_keyword(STDIN)?; (CopyDirection::From, CopyTarget::Stdin) } TO => { self.expect_keyword(STDOUT)?; (CopyDirection::To, CopyTarget::Stdout) } _ => unreachable!(), }; let mut options = vec![]; // WITH must be followed by LParen. The WITH in COPY is optional for backward // compat with Postgres but is required elsewhere, which is why we don't use // parse_with_options here. let has_options = if self.parse_keyword(WITH) { self.expect_token(&Token::LParen)?; true } else { self.consume_token(&Token::LParen) }; if has_options { self.prev_token(); options = self.parse_with_options(false)?; } Ok(Statement::Copy(CopyStatement { relation, direction, target, options, })) } /// Parse a literal value (numbers, strings, date/time, booleans) fn parse_value(&mut self) -> Result<Value, ParserError> { match self.next_token() { Some(t) => match t { Token::Keyword(TRUE) => Ok(Value::Boolean(true)), Token::Keyword(FALSE) => Ok(Value::Boolean(false)), Token::Keyword(NULL) => Ok(Value::Null), Token::Keyword(kw) => { return parser_err!( self, self.peek_prev_pos(), format!("No value parser for keyword {}", kw) ); } Token::Op(ref op) if op == "-" => match self.next_token() { Some(Token::Number(n)) => Ok(Value::Number(format!("-{}", n))), other => self.expected(self.peek_prev_pos(), "literal int", other), }, Token::Number(ref n) => Ok(Value::Number(n.to_string())), Token::String(ref s) => Ok(Value::String(s.to_string())), Token::HexString(ref s) => Ok(Value::HexString(s.to_string())), Token::LBracket => self.parse_value_array(), _ => parser_err!( self, self.peek_prev_pos(), format!("Unsupported value: {:?}", t) ), }, None => parser_err!( self, self.peek_prev_pos(), "Expecting a value, but found EOF" ), } } fn parse_boolean_value(&mut self) -> Result<bool, ParserError> { match self.next_token() { Some(t) => match t { Token::Keyword(TRUE) => Ok(true), Token::Keyword(FALSE) => Ok(false), _ => self.expected(self.peek_prev_pos(), "boolean value", Some(t)), }, None => self.expected(self.peek_prev_pos(), "boolean value", None), } } fn parse_value_array(&mut self) -> Result<Value, ParserError> { let mut values = vec![]; loop { if let Some(Token::RBracket) = self.peek_token() { break; } values.push(self.parse_value()?); if !self.consume_token(&Token::Comma) { break; } } self.expect_token(&Token::RBracket)?; Ok(Value::Array(values)) } fn parse_array(&mut self) -> Result<Expr<Raw>, ParserError> { if self.consume_token(&Token::LParen) { let subquery = self.parse_query()?; self.expect_token(&Token::RParen)?; Ok(Expr::ArraySubquery(Box::new(subquery))) } else { self.parse_sequence(Self::parse_array).map(Expr::Array) } } fn parse_list(&mut self) -> Result<Expr<Raw>, ParserError> { if self.consume_token(&Token::LParen) { let subquery = self.parse_query()?; self.expect_token(&Token::RParen)?; Ok(Expr::ListSubquery(Box::new(subquery))) } else { self.parse_sequence(Self::parse_list).map(Expr::List) } } fn parse_sequence<F>(&mut self, mut f: F) -> Result<Vec<Expr<Raw>>, ParserError> where F: FnMut(&mut Self) -> Result<Expr<Raw>, ParserError>, { self.expect_token(&Token::LBracket)?; let mut exprs = vec![]; loop { if let Some(Token::RBracket) = self.peek_token() { break; } let expr = if let Some(Token::LBracket) = self.peek_token() { f(self)? } else { self.parse_expr()? }; exprs.push(expr); if !self.consume_token(&Token::Comma) { break; } } self.expect_token(&Token::RBracket)?; Ok(exprs) } fn parse_number_value(&mut self) -> Result<Value, ParserError> { match self.parse_value()? { v @ Value::Number(_) => Ok(v), _ => { self.prev_token(); self.expected(self.peek_pos(), "literal number", self.peek_token()) } } } /// Parse a signed literal integer. fn parse_literal_int(&mut self) -> Result<i64, ParserError> { match self.next_token() { Some(Token::Number(s)) => s.parse::<i64>().map_err(|e| { self.error( self.peek_prev_pos(), format!("Could not parse '{}' as i64: {}", s, e), ) }), other => self.expected(self.peek_prev_pos(), "literal integer", other), } } /// Parse an unsigned literal integer. fn parse_literal_uint(&mut self) -> Result<u64, ParserError> { match self.next_token() { Some(Token::Number(s)) => s.parse::<u64>().map_err(|e| { self.error( self.peek_prev_pos(), format!("Could not parse '{}' as u64: {}", s, e), ) }), other => self.expected(self.peek_prev_pos(), "literal unsigned integer", other), } } /// Parse a literal string fn parse_literal_string(&mut self) -> Result<String, ParserError> { match self.next_token() { Some(Token::String(ref s)) => Ok(s.clone()), other => self.expected(self.peek_prev_pos(), "literal string", other), } } /// Parse a SQL datatype (in the context of a CREATE TABLE statement for example) fn parse_data_type(&mut self) -> Result<UnresolvedDataType, ParserError> { let other = |name: &str| UnresolvedDataType::Other { name: RawObjectName::Name(UnresolvedObjectName::unqualified(name)), typ_mod: vec![], }; let mut data_type = match self.next_token() { Some(Token::Keyword(kw)) => match kw { // Text-like types CHAR | CHARACTER => { let name = if self.parse_keyword(VARYING) { "varchar" } else { "bpchar" }; UnresolvedDataType::Other { name: RawObjectName::Name(UnresolvedObjectName::unqualified(name)), typ_mod: self.parse_typ_mod()?, } } BPCHAR => UnresolvedDataType::Other { name: RawObjectName::Name(UnresolvedObjectName::unqualified("bpchar")), typ_mod: self.parse_typ_mod()?, }, VARCHAR => UnresolvedDataType::Other { name: RawObjectName::Name(UnresolvedObjectName::unqualified("varchar")), typ_mod: self.parse_typ_mod()?, }, STRING => other("text"), // Number-like types BIGINT => other("int8"), SMALLINT => other("int2"), DEC | DECIMAL => UnresolvedDataType::Other { name: RawObjectName::Name(UnresolvedObjectName::unqualified("numeric")), typ_mod: self.parse_typ_mod()?, }, DOUBLE => { let _ = self.parse_keyword(PRECISION); other("float8") } FLOAT => match self.parse_optional_precision()?.unwrap_or(53) { v if v == 0 || v > 53 => { return Err(self.error( self.peek_prev_pos(), "precision for type float must be within ([1-53])".into(), )) } v if v < 25 => other("float4"), _ => other("float8"), }, INT | INTEGER => other("int4"), REAL => other("float4"), // Time-like types TIME => { if self.parse_keyword(WITH) { self.expect_keywords(&[TIME, ZONE])?; other("timetz") } else { if self.parse_keyword(WITHOUT) { self.expect_keywords(&[TIME, ZONE])?; } other("time") } } TIMESTAMP => { if self.parse_keyword(WITH) { self.expect_keywords(&[TIME, ZONE])?; other("timestamptz") } else { if self.parse_keyword(WITHOUT) { self.expect_keywords(&[TIME, ZONE])?; } other("timestamp") } } // MZ "proprietary" types MAP => { return self.parse_map(); } // Misc. BOOLEAN => other("bool"), BYTES => other("bytea"), JSON => other("jsonb"), _ => { self.prev_token(); UnresolvedDataType::Other { name: RawObjectName::Name(self.parse_object_name()?), typ_mod: self.parse_typ_mod()?, } } }, Some(Token::Ident(_) | Token::LBracket) => { self.prev_token(); UnresolvedDataType::Other { name: self.parse_raw_name()?, typ_mod: self.parse_typ_mod()?, } } other => self.expected(self.peek_prev_pos(), "a data type name", other)?, }; loop { match self.peek_token() { Some(Token::Keyword(LIST)) => { self.next_token(); data_type = UnresolvedDataType::List(Box::new(data_type)); } Some(Token::LBracket) => { // Handle array suffixes. Note that `int[]`, `int[][][]`, // and `int[2][2]` all parse to the same "int array" type. self.next_token(); let _ = self.maybe_parse(|parser| parser.parse_number_value()); self.expect_token(&Token::RBracket)?; if !matches!(data_type, UnresolvedDataType::Array(_)) { data_type = UnresolvedDataType::Array(Box::new(data_type)); } } _ => break, } } Ok(data_type) } fn parse_typ_mod(&mut self) -> Result<Vec<i64>, ParserError> { if self.consume_token(&Token::LParen) { let typ_mod = self.parse_comma_separated(Parser::parse_literal_int)?; self.expect_token(&Token::RParen)?; Ok(typ_mod) } else { Ok(vec![]) } } /// Parse `AS identifier` (or simply `identifier` if it's not a reserved keyword) /// Some examples with aliases: `SELECT 1 foo`, `SELECT COUNT(*) AS cnt`, /// `SELECT ... FROM t1 foo, t2 bar`, `SELECT ... FROM (...) AS bar` fn parse_optional_alias<F>(&mut self, is_reserved: F) -> Result<Option<Ident>, ParserError> where F: FnOnce(Keyword) -> bool, { let after_as = self.parse_keyword(AS); match self.next_token() { // Do not accept `AS OF`, which is reserved for providing timestamp information // to queries. Some(Token::Keyword(OF)) => { self.prev_token(); self.prev_token(); Ok(None) } // Accept any other identifier after `AS` (though many dialects have restrictions on // keywords that may appear here). If there's no `AS`: don't parse keywords, // which may start a construct allowed in this position, to be parsed as aliases. // (For example, in `FROM t1 JOIN` the `JOIN` will always be parsed as a keyword, // not an alias.) Some(Token::Keyword(kw)) if after_as || !is_reserved(kw) => Ok(Some(kw.into_ident())), Some(Token::Ident(id)) => Ok(Some(Ident::new(id))), not_an_ident => { if after_as { return self.expected( self.peek_prev_pos(), "an identifier after AS", not_an_ident, ); } self.prev_token(); Ok(None) // no alias found } } } /// Parse `AS identifier` when the AS is describing a table-valued object, /// like in `... FROM generate_series(1, 10) AS t (col)`. In this case /// the alias is allowed to optionally name the columns in the table, in /// addition to the table itself. fn parse_optional_table_alias(&mut self) -> Result<Option<TableAlias>, ParserError> { match self.parse_optional_alias(Keyword::is_reserved_in_table_alias)? { Some(name) => { let columns = self.parse_parenthesized_column_list(Optional)?; Ok(Some(TableAlias { name, columns, strict: false, })) } None => Ok(None), } } fn parse_raw_name(&mut self) -> Result<RawObjectName, ParserError> { if self.consume_token(&Token::LBracket) { let id = match self.next_token() { Some(Token::Ident(id)) => id, _ => return parser_err!(self, self.peek_prev_pos(), "expected id"), }; self.expect_keyword(AS)?; let name = self.parse_object_name()?; // TODO(justin): is there a more idiomatic way to detect a fully-qualified name? if name.0.len() < 2 { return parser_err!( self, self.peek_prev_pos(), "table name in square brackets must be fully qualified" ); } self.expect_token(&Token::RBracket)?; Ok(RawObjectName::Id(id, name)) } else { Ok(RawObjectName::Name(self.parse_object_name()?)) } } /// Parse a possibly quoted database identifier, e.g. /// `foo` or `"mydatabase"` fn parse_database_name(&mut self) -> Result<UnresolvedDatabaseName, ParserError> { Ok(UnresolvedDatabaseName(self.parse_identifier()?)) } /// Parse a possibly qualified, possibly quoted schema identifier, e.g. /// `foo` or `mydatabase."schema"` fn parse_schema_name(&mut self) -> Result<UnresolvedSchemaName, ParserError> { Ok(UnresolvedSchemaName(self.parse_identifiers()?)) } /// Parse a possibly qualified, possibly quoted object identifier, e.g. /// `foo` or `myschema."table"` fn parse_object_name(&mut self) -> Result<UnresolvedObjectName, ParserError> { Ok(UnresolvedObjectName(self.parse_identifiers()?)) } ///Parse one or more simple one-word identifiers separated by a '.' fn parse_identifiers(&mut self) -> Result<Vec<Ident>, ParserError> { let mut idents = vec![]; loop { idents.push(self.parse_identifier()?); if !self.consume_token(&Token::Dot) { break; } } Ok(idents) } /// Parse a simple one-word identifier (possibly quoted, possibly a keyword) fn parse_identifier(&mut self) -> Result<Ident, ParserError> { match self.consume_identifier() { Some(id) => { if id.as_str().is_empty() { return parser_err!( self, self.peek_prev_pos(), "zero-length delimited identifier", ); } Ok(id) } None => self.expected(self.peek_pos(), "identifier", self.peek_token()), } } fn consume_identifier(&mut self) -> Option<Ident> { match self.peek_token() { Some(Token::Keyword(kw)) => { self.next_token(); Some(kw.into_ident()) } Some(Token::Ident(id)) => { self.next_token(); Some(Ident::new(id)) } _ => None, } } fn parse_qualified_identifier(&mut self, id: Ident) -> Result<Expr<Raw>, ParserError> { let mut id_parts = vec![id]; match self.peek_token() { Some(Token::LParen) | Some(Token::Dot) => { let mut ends_with_wildcard = false; while self.consume_token(&Token::Dot) { match self.next_token() { Some(Token::Keyword(kw)) => id_parts.push(kw.into_ident()), Some(Token::Ident(id)) => id_parts.push(Ident::new(id)), Some(Token::Star) => { ends_with_wildcard = true; break; } unexpected => { return self.expected( self.peek_prev_pos(), "an identifier or a '*' after '.'", unexpected, ); } } } if ends_with_wildcard { Ok(Expr::QualifiedWildcard(id_parts)) } else if self.consume_token(&Token::LParen) { self.prev_token(); self.parse_function(UnresolvedObjectName(id_parts)) } else { Ok(Expr::Identifier(id_parts)) } } _ => Ok(Expr::Identifier(id_parts)), } } /// Parse a parenthesized comma-separated list of unqualified, possibly quoted identifiers fn parse_parenthesized_column_list( &mut self, optional: IsOptional, ) -> Result<Vec<Ident>, ParserError> { if self.consume_token(&Token::LParen) { let cols = self.parse_comma_separated(Parser::parse_identifier)?; self.expect_token(&Token::RParen)?; Ok(cols) } else if optional == Optional { Ok(vec![]) } else { self.expected( self.peek_pos(), "a list of columns in parentheses", self.peek_token(), ) } } fn parse_optional_precision(&mut self) -> Result<Option<u64>, ParserError> { if self.consume_token(&Token::LParen) { let n = self.parse_literal_uint()?; self.expect_token(&Token::RParen)?; Ok(Some(n)) } else { Ok(None) } } fn parse_map(&mut self) -> Result<UnresolvedDataType, ParserError> { self.expect_token(&Token::LBracket)?; let key_type = Box::new(self.parse_data_type()?); self.expect_token(&Token::Op("=>".to_owned()))?; let value_type = Box::new(self.parse_data_type()?); self.expect_token(&Token::RBracket)?; Ok(UnresolvedDataType::Map { key_type, value_type, }) } fn parse_delete(&mut self) -> Result<Statement<Raw>, ParserError> { self.expect_keyword(FROM)?; let table_name = RawObjectName::Name(self.parse_object_name()?); let alias = self.parse_optional_table_alias()?; let using = if self.parse_keyword(USING) { self.parse_comma_separated(Parser::parse_table_and_joins)? } else { vec![] }; let selection = if self.parse_keyword(WHERE) { Some(self.parse_expr()?) } else { None }; Ok(Statement::Delete(DeleteStatement { table_name, alias, using, selection, })) } /// Parse a query expression, i.e. a `SELECT` statement optionally /// preceeded with some `WITH` CTE declarations and optionally followed /// by `ORDER BY`. Unlike some other parse_... methods, this one doesn't /// expect the initial keyword to be already consumed fn parse_query(&mut self) -> Result<Query<Raw>, ParserError> { self.checked_recur_mut(|parser| { let ctes = if parser.parse_keyword(WITH) { // TODO: optional RECURSIVE parser.parse_comma_separated(Parser::parse_cte)? } else { vec![] }; let body = parser.parse_query_body(SetPrecedence::Zero)?; parser.parse_query_tail(ctes, body) }) } fn parse_query_tail( &mut self, ctes: Vec<Cte<Raw>>, body: SetExpr<Raw>, ) -> Result<Query<Raw>, ParserError> { let (inner_ctes, inner_order_by, inner_limit, inner_offset, body) = match body { SetExpr::Query(query) => { let Query { ctes, body, order_by, limit, offset, } = *query; (ctes, order_by, limit, offset, body) } _ => (vec![], vec![], None, None, body), }; let ctes = if ctes.is_empty() { inner_ctes } else if !inner_ctes.is_empty() { return parser_err!(self, self.peek_pos(), "multiple WITH clauses not allowed"); } else { ctes }; let order_by = if self.parse_keywords(&[ORDER, BY]) { if !inner_order_by.is_empty() { return parser_err!( self, self.peek_prev_pos(), "multiple ORDER BY clauses not allowed" ); } self.parse_comma_separated(Parser::parse_order_by_expr)? } else { inner_order_by }; let mut limit = if self.parse_keyword(LIMIT) { if inner_limit.is_some() { return parser_err!( self, self.peek_prev_pos(), "multiple LIMIT/FETCH clauses not allowed" ); } if self.parse_keyword(ALL) { None } else { Some(Limit { with_ties: false, quantity: self.parse_expr()?, }) } } else { inner_limit }; let offset = if self.parse_keyword(OFFSET) { if inner_offset.is_some() { return parser_err!( self, self.peek_prev_pos(), "multiple OFFSET clauses not allowed" ); } let value = self.parse_expr()?; let _ = self.parse_one_of_keywords(&[ROW, ROWS]); Some(value) } else { inner_offset }; if limit.is_none() && self.parse_keyword(FETCH) { self.expect_one_of_keywords(&[FIRST, NEXT])?; let quantity = if self.parse_one_of_keywords(&[ROW, ROWS]).is_some() { Expr::Value(Value::Number('1'.into())) } else { let quantity = self.parse_expr()?; self.expect_one_of_keywords(&[ROW, ROWS])?; quantity }; let with_ties = if self.parse_keyword(ONLY) { false } else if self.parse_keywords(&[WITH, TIES]) { true } else { return self.expected( self.peek_pos(), "one of ONLY or WITH TIES", self.peek_token(), ); }; limit = Some(Limit { with_ties, quantity, }); } Ok(Query { ctes, body, order_by, limit, offset, }) } /// Parse a CTE (`alias [( col1, col2, ... )] AS (subquery)`) fn parse_cte(&mut self) -> Result<Cte<Raw>, ParserError> { let alias = TableAlias { name: self.parse_identifier()?, columns: self.parse_parenthesized_column_list(Optional)?, strict: false, }; self.expect_keyword(AS)?; self.expect_token(&Token::LParen)?; let query = self.parse_query()?; self.expect_token(&Token::RParen)?; Ok(Cte { alias, query, id: (), }) } /// Parse a "query body", which is an expression with roughly the /// following grammar: /// ```text /// query_body ::= restricted_select | '(' subquery ')' | set_operation /// restricted_select ::= 'SELECT' [expr_list] [ from ] [ where ] [ groupby_having ] /// subquery ::= query_body [ order_by_limit ] /// set_operation ::= query_body { 'UNION' | 'EXCEPT' | 'INTERSECT' } [ 'ALL' ] query_body /// ``` fn parse_query_body(&mut self, precedence: SetPrecedence) -> Result<SetExpr<Raw>, ParserError> { // We parse the expression using a Pratt parser, as in `parse_expr()`. // Start by parsing a restricted SELECT or a `(subquery)`: let expr = if self.parse_keyword(SELECT) { SetExpr::Select(Box::new(self.parse_select()?)) } else if self.consume_token(&Token::LParen) { // CTEs are not allowed here, but the parser currently accepts them let subquery = self.parse_query()?; self.expect_token(&Token::RParen)?; SetExpr::Query(Box::new(subquery)) } else if self.parse_keyword(VALUES) { SetExpr::Values(self.parse_values()?) } else { return self.expected( self.peek_pos(), "SELECT, VALUES, or a subquery in the query body", self.peek_token(), ); }; self.parse_query_body_seeded(precedence, expr) } fn parse_query_body_seeded( &mut self, precedence: SetPrecedence, mut expr: SetExpr<Raw>, ) -> Result<SetExpr<Raw>, ParserError> { loop { // The query can be optionally followed by a set operator: let next_token = self.peek_token(); let op = self.parse_set_operator(&next_token); let next_precedence = match op { // UNION and EXCEPT have the same binding power and evaluate left-to-right Some(SetOperator::Union) | Some(SetOperator::Except) => SetPrecedence::UnionExcept, // INTERSECT has higher precedence than UNION/EXCEPT Some(SetOperator::Intersect) => SetPrecedence::Intersect, // Unexpected token or EOF => stop parsing the query body None => break, }; if precedence >= next_precedence { break; } self.next_token(); // skip past the set operator let all = self.parse_keyword(ALL); let distinct = self.parse_keyword(DISTINCT); if all && distinct { return parser_err!( self, self.peek_prev_pos(), "Cannot specify both ALL and DISTINCT in set operation" ); } expr = SetExpr::SetOperation { left: Box::new(expr), op: op.unwrap(), all, right: Box::new(self.parse_query_body(next_precedence)?), }; } Ok(expr) } fn parse_set_operator(&mut self, token: &Option<Token>) -> Option<SetOperator> { match token { Some(Token::Keyword(UNION)) => Some(SetOperator::Union), Some(Token::Keyword(EXCEPT)) => Some(SetOperator::Except), Some(Token::Keyword(INTERSECT)) => Some(SetOperator::Intersect), _ => None, } } /// Parse a restricted `SELECT` statement (no CTEs / `UNION` / `ORDER BY`), /// assuming the initial `SELECT` was already consumed fn parse_select(&mut self) -> Result<Select<Raw>, ParserError> { let all = self.parse_keyword(ALL); let distinct = self.parse_keyword(DISTINCT); if all && distinct { return parser_err!( self, self.peek_prev_pos(), "Cannot specify both ALL and DISTINCT in SELECT" ); } let distinct = if distinct && self.parse_keyword(ON) { self.expect_token(&Token::LParen)?; let exprs = self.parse_comma_separated(Parser::parse_expr)?; self.expect_token(&Token::RParen)?; Some(Distinct::On(exprs)) } else if distinct { Some(Distinct::EntireRow) } else { None }; let projection = match self.peek_token() { // An empty target list is permissible to match PostgreSQL, which // permits these for symmetry with zero column tables. Some(Token::Keyword(kw)) if kw.is_reserved() => vec![], Some(Token::Semicolon) | Some(Token::RParen) | None => vec![], _ => self.parse_comma_separated(Parser::parse_select_item)?, }; // Note that for keywords to be properly handled here, they need to be // added to `RESERVED_FOR_COLUMN_ALIAS` / `RESERVED_FOR_TABLE_ALIAS`, // otherwise they may be parsed as an alias as part of the `projection` // or `from`. let from = if self.parse_keyword(FROM) { self.parse_comma_separated(Parser::parse_table_and_joins)? } else { vec![] }; let selection = if self.parse_keyword(WHERE) { Some(self.parse_expr()?) } else { None }; let group_by = if self.parse_keywords(&[GROUP, BY]) { self.parse_comma_separated(Parser::parse_expr)? } else { vec![] }; let having = if self.parse_keyword(HAVING) { Some(self.parse_expr()?) } else { None }; let options = if self.parse_keyword(OPTION) { self.parse_with_options(true)? } else { vec![] }; Ok(Select { distinct, projection, from, selection, group_by, having, options, }) } fn parse_set(&mut self) -> Result<Statement<Raw>, ParserError> { let modifier = self.parse_one_of_keywords(&[SESSION, LOCAL]); let mut variable = self.parse_identifier()?; let mut normal = self.consume_token(&Token::Eq) || self.parse_keyword(TO); if !normal { match variable.as_str().parse() { Ok(TIME) => { self.expect_keyword(ZONE)?; variable = Ident::new("timezone"); normal = true; } Ok(NAMES) => { variable = Ident::new("client_encoding"); normal = true; } Ok(SCHEMA) => { variable = Ident::new("search_path"); normal = true; } _ => {} } } if normal { let token = self.peek_token(); let value = match (self.parse_value(), token) { (Ok(value), _) => SetVariableValue::Literal(value), (Err(_), Some(Token::Keyword(kw))) => SetVariableValue::Ident(kw.into_ident()), (Err(_), Some(Token::Ident(id))) => SetVariableValue::Ident(Ident::new(id)), (Err(_), other) => self.expected(self.peek_pos(), "variable value", other)?, }; Ok(Statement::SetVariable(SetVariableStatement { local: modifier == Some(LOCAL), variable, value, })) } else if // SET TRANSACTION transaction_mode (variable.as_str().parse() == Ok(TRANSACTION) && modifier.is_none()) || // SET SESSION CHARACTERISTICS AS TRANSACTION transaction_mode (modifier == Some(SESSION) && variable.as_str().parse() == Ok(CHARACTERISTICS) && self.parse_keywords(&[AS, TRANSACTION])) { Ok(Statement::SetTransaction(SetTransactionStatement { modes: self.parse_transaction_modes()?, })) } else { self.expected(self.peek_pos(), "equals sign or TO", self.peek_token()) } } fn parse_show(&mut self) -> Result<Statement<Raw>, ParserError> { if self.parse_keyword(DATABASES) { return Ok(Statement::ShowDatabases(ShowDatabasesStatement { filter: self.parse_show_statement_filter()?, })); } let extended = self.parse_keyword(EXTENDED); if extended { self.expect_one_of_keywords(&[ COLUMNS, CONNECTORS, FULL, INDEX, INDEXES, KEYS, OBJECTS, SCHEMAS, TABLES, TYPES, ])?; self.prev_token(); } let full = self.parse_keyword(FULL); if full { if extended { self.expect_one_of_keywords(&[COLUMNS, OBJECTS, SCHEMAS, TABLES, TYPES])?; } else { self.expect_one_of_keywords(&[ COLUMNS, CONNECTORS, MATERIALIZED, OBJECTS, ROLES, SCHEMAS, SINKS, SOURCES, TABLES, TYPES, VIEWS, ])?; } self.prev_token(); } let materialized = self.parse_keyword(MATERIALIZED); if materialized { self.expect_one_of_keywords(&[SOURCES, VIEWS])?; self.prev_token(); } if self.parse_one_of_keywords(&[COLUMNS, FIELDS]).is_some() { self.parse_show_columns(extended, full) } else if self.parse_keyword(SCHEMAS) { let from = if self.parse_keyword(FROM) { Some(self.parse_database_name()?) } else { None }; Ok(Statement::ShowSchemas(ShowSchemasStatement { from, extended, full, filter: self.parse_show_statement_filter()?, })) } else if let Some(object_type) = self.parse_one_of_keywords(&[ OBJECTS, ROLES, CLUSTERS, SINKS, SOURCES, TABLES, TYPES, USERS, VIEWS, SECRETS, CONNECTORS, ]) { let object_type = match object_type { OBJECTS => ObjectType::Object, ROLES | USERS => ObjectType::Role, CLUSTERS => ObjectType::Cluster, SINKS => ObjectType::Sink, SOURCES => ObjectType::Source, TABLES => ObjectType::Table, TYPES => ObjectType::Type, VIEWS => ObjectType::View, SECRETS => ObjectType::Secret, CONNECTORS => ObjectType::Connector, _ => unreachable!(), }; let (from, in_cluster) = match self.parse_one_of_keywords(&[FROM, IN]) { Some(kw) => { if kw == IN && self.peek_keyword(CLUSTER) { if matches!(object_type, ObjectType::Sink) { // put `IN` back self.prev_token(); (None, self.parse_optional_in_cluster()?) } else { return parser_err!( self, self.peek_pos(), "expected object name, found 'cluster'" ); } } else { let from = self.parse_schema_name()?; let in_cluster = self.parse_optional_in_cluster()?; (Some(from), in_cluster) } } None => (None, None), }; Ok(Statement::ShowObjects(ShowObjectsStatement { object_type, extended, full, materialized, from, in_cluster, filter: self.parse_show_statement_filter()?, })) } else if self .parse_one_of_keywords(&[INDEX, INDEXES, KEYS]) .is_some() { match self.parse_one_of_keywords(&[FROM, IN, ON]) { Some(kw) => { let (table_name, in_cluster) = if kw == IN && self.peek_keyword(CLUSTER) { // put `IN` back self.prev_token(); (None, self.parse_optional_in_cluster()?) } else { let table_name = self.parse_raw_name()?; let in_cluster = self.parse_optional_in_cluster()?; (Some(table_name), in_cluster) }; let filter = if self.parse_keyword(WHERE) { Some(ShowStatementFilter::Where(self.parse_expr()?)) } else { None }; Ok(Statement::ShowIndexes(ShowIndexesStatement { table_name, in_cluster, extended, filter, })) } None => self.expected( self.peek_pos(), "FROM or IN after SHOW INDEXES", self.peek_token(), ), } } else if self.parse_keywords(&[CREATE, VIEW]) { Ok(Statement::ShowCreateView(ShowCreateViewStatement { view_name: self.parse_raw_name()?, })) } else if self.parse_keywords(&[CREATE, SOURCE]) { Ok(Statement::ShowCreateSource(ShowCreateSourceStatement { source_name: self.parse_raw_name()?, })) } else if self.parse_keywords(&[CREATE, TABLE]) { Ok(Statement::ShowCreateTable(ShowCreateTableStatement { table_name: self.parse_raw_name()?, })) } else if self.parse_keywords(&[CREATE, SINK]) { Ok(Statement::ShowCreateSink(ShowCreateSinkStatement { sink_name: self.parse_raw_name()?, })) } else if self.parse_keywords(&[CREATE, INDEX]) { Ok(Statement::ShowCreateIndex(ShowCreateIndexStatement { index_name: self.parse_raw_name()?, })) } else if self.parse_keywords(&[CREATE, CONNECTOR]) { Ok(Statement::ShowCreateConnector( ShowCreateConnectorStatement { connector_name: self.parse_raw_name()?, }, )) } else { let variable = if self.parse_keywords(&[TRANSACTION, ISOLATION, LEVEL]) { Ident::new("transaction_isolation") } else if self.parse_keywords(&[TIME, ZONE]) { Ident::new("timezone") } else { self.parse_identifier()? }; Ok(Statement::ShowVariable(ShowVariableStatement { variable })) } } fn parse_show_columns( &mut self, extended: bool, full: bool, ) -> Result<Statement<Raw>, ParserError> { self.expect_one_of_keywords(&[FROM, IN])?; let table_name = self.parse_raw_name()?; // MySQL also supports FROM <database> here. In other words, MySQL // allows both FROM <table> FROM <database> and FROM <database>.<table>, // while we only support the latter for now. let filter = self.parse_show_statement_filter()?; Ok(Statement::ShowColumns(ShowColumnsStatement { extended, full, table_name, filter, })) } fn parse_show_statement_filter( &mut self, ) -> Result<Option<ShowStatementFilter<Raw>>, ParserError> { if self.parse_keyword(LIKE) { Ok(Some(ShowStatementFilter::Like( self.parse_literal_string()?, ))) } else if self.parse_keyword(WHERE) { Ok(Some(ShowStatementFilter::Where(self.parse_expr()?))) } else { Ok(None) } } fn parse_table_and_joins(&mut self) -> Result<TableWithJoins<Raw>, ParserError> { let relation = self.parse_table_factor()?; // Note that for keywords to be properly handled here, they need to be // added to `RESERVED_FOR_TABLE_ALIAS`, otherwise they may be parsed as // a table alias. let mut joins = vec![]; loop { let join = if self.parse_keyword(CROSS) { self.expect_keyword(JOIN)?; Join { relation: self.parse_table_factor()?, join_operator: JoinOperator::CrossJoin, } } else { let natural = self.parse_keyword(NATURAL); let peek_keyword = if let Some(Token::Keyword(kw)) = self.peek_token() { Some(kw) } else { None }; let join_operator_type = match peek_keyword { Some(INNER) | Some(JOIN) => { let _ = self.parse_keyword(INNER); self.expect_keyword(JOIN)?; JoinOperator::Inner } Some(kw @ LEFT) | Some(kw @ RIGHT) | Some(kw @ FULL) => { let _ = self.next_token(); let _ = self.parse_keyword(OUTER); self.expect_keyword(JOIN)?; match kw { LEFT => JoinOperator::LeftOuter, RIGHT => JoinOperator::RightOuter, FULL => JoinOperator::FullOuter, _ => unreachable!(), } } Some(OUTER) => { return self.expected( self.peek_pos(), "LEFT, RIGHT, or FULL", self.peek_token(), ) } None if natural => { return self.expected( self.peek_pos(), "a join type after NATURAL", self.peek_token(), ); } _ => break, }; let relation = self.parse_table_factor()?; let join_constraint = self.parse_join_constraint(natural)?; Join { relation, join_operator: join_operator_type(join_constraint), } }; joins.push(join); } Ok(TableWithJoins { relation, joins }) } /// A table name or a parenthesized subquery, followed by optional `[AS] alias` fn parse_table_factor(&mut self) -> Result<TableFactor<Raw>, ParserError> { if self.parse_keyword(LATERAL) { // LATERAL must always be followed by a subquery or table function. if self.consume_token(&Token::LParen) { return self.parse_derived_table_factor(Lateral); } else if self.parse_keywords(&[ROWS, FROM]) { return Ok(self.parse_rows_from()?); } else { let name = self.parse_object_name()?; self.expect_token(&Token::LParen)?; let args = self.parse_optional_args(false)?; let alias = self.parse_optional_table_alias()?; let with_ordinality = self.parse_keywords(&[WITH, ORDINALITY]); return Ok(TableFactor::Function { function: TableFunction { name, args }, alias, with_ordinality, }); } } if self.consume_token(&Token::LParen) { // A left paren introduces either a derived table (i.e., a subquery) // or a nested join. It's nearly impossible to determine ahead of // time which it is... so we just try to parse both. // // Here's an example that demonstrates the complexity: // /-------------------------------------------------------\ // | /-----------------------------------\ | // SELECT * FROM ( ( ( (SELECT 1) UNION (SELECT 2) ) AS t1 NATURAL JOIN t2 ) ) // ^ ^ ^ ^ // | | | | // | | | | // | | | (4) belongs to a SetExpr::Query inside the subquery // | | (3) starts a derived table (subquery) // | (2) starts a nested join // (1) an additional set of parens around a nested join // // Check if the recently consumed '(' started a derived table, in // which case we've parsed the subquery, followed by the closing // ')', and the alias of the derived table. In the example above // this is case (3), and the next token would be `NATURAL`. maybe!(self.maybe_parse(|parser| parser.parse_derived_table_factor(NotLateral))); // The '(' we've recently consumed does not start a derived table. // For valid input this can happen either when the token following // the paren can't start a query (e.g. `foo` in `FROM (foo NATURAL // JOIN bar)`, or when the '(' we've consumed is followed by another // '(' that starts a derived table, like (3), or another nested join // (2). // // Ignore the error and back up to where we were before. Either // we'll be able to parse a valid nested join, or we won't, and // we'll return that error instead. let table_and_joins = self.parse_table_and_joins()?; match table_and_joins.relation { TableFactor::NestedJoin { .. } => (), _ => { if table_and_joins.joins.is_empty() { // The SQL spec prohibits derived tables and bare // tables from appearing alone in parentheses. self.expected(self.peek_pos(), "joined table", self.peek_token())? } } } self.expect_token(&Token::RParen)?; Ok(TableFactor::NestedJoin { join: Box::new(table_and_joins), alias: self.parse_optional_table_alias()?, }) } else if self.parse_keywords(&[ROWS, FROM]) { Ok(self.parse_rows_from()?) } else { let name = self.parse_raw_name()?; match name { RawObjectName::Name(name) if self.consume_token(&Token::LParen) => { let args = self.parse_optional_args(false)?; let alias = self.parse_optional_table_alias()?; let with_ordinality = self.parse_keywords(&[WITH, ORDINALITY]); Ok(TableFactor::Function { function: TableFunction { name, args }, alias, with_ordinality, }) } _ => Ok(TableFactor::Table { name, alias: self.parse_optional_table_alias()?, }), } } } fn parse_rows_from(&mut self) -> Result<TableFactor<Raw>, ParserError> { self.expect_token(&Token::LParen)?; let functions = self.parse_comma_separated(Parser::parse_table_function)?; self.expect_token(&Token::RParen)?; let alias = self.parse_optional_table_alias()?; let with_ordinality = self.parse_keywords(&[WITH, ORDINALITY]); Ok(TableFactor::RowsFrom { functions, alias, with_ordinality, }) } fn parse_table_function(&mut self) -> Result<TableFunction<Raw>, ParserError> { let name = self.parse_object_name()?; self.expect_token(&Token::LParen)?; Ok(TableFunction { name, args: self.parse_optional_args(false)?, }) } fn parse_derived_table_factor( &mut self, lateral: IsLateral, ) -> Result<TableFactor<Raw>, ParserError> { let subquery = Box::new(self.parse_query()?); self.expect_token(&Token::RParen)?; let alias = self.parse_optional_table_alias()?; Ok(TableFactor::Derived { lateral: match lateral { Lateral => true, NotLateral => false, }, subquery, alias, }) } fn parse_join_constraint(&mut self, natural: bool) -> Result<JoinConstraint<Raw>, ParserError> { if natural { Ok(JoinConstraint::Natural) } else if self.parse_keyword(ON) { let constraint = self.parse_expr()?; Ok(JoinConstraint::On(constraint)) } else if self.parse_keyword(USING) { let columns = self.parse_parenthesized_column_list(Mandatory)?; Ok(JoinConstraint::Using(columns)) } else { self.expected( self.peek_pos(), "ON, or USING after JOIN", self.peek_token(), ) } } /// Parse an INSERT statement fn parse_insert(&mut self) -> Result<Statement<Raw>, ParserError> { self.expect_keyword(INTO)?; let table_name = self.parse_raw_name()?; let columns = self.parse_parenthesized_column_list(Optional)?; let source = if self.parse_keywords(&[DEFAULT, VALUES]) { InsertSource::DefaultValues } else { InsertSource::Query(self.parse_query()?) }; Ok(Statement::Insert(InsertStatement { table_name, columns, source, })) } fn parse_update(&mut self) -> Result<Statement<Raw>, ParserError> { let table_name = RawObjectName::Name(self.parse_object_name()?); self.expect_keyword(SET)?; let assignments = self.parse_comma_separated(Parser::parse_assignment)?; let selection = if self.parse_keyword(WHERE) { Some(self.parse_expr()?) } else { None }; Ok(Statement::Update(UpdateStatement { table_name, assignments, selection, })) } /// Parse a `var = expr` assignment, used in an UPDATE statement fn parse_assignment(&mut self) -> Result<Assignment<Raw>, ParserError> { let id = self.parse_identifier()?; self.expect_token(&Token::Eq)?; let value = self.parse_expr()?; Ok(Assignment { id, value }) } fn parse_optional_args( &mut self, allow_order_by: bool, ) -> Result<FunctionArgs<Raw>, ParserError> { if self.consume_token(&Token::Star) { self.expect_token(&Token::RParen)?; Ok(FunctionArgs::Star) } else if self.consume_token(&Token::RParen) { Ok(FunctionArgs::args(vec![])) } else { let args = self.parse_comma_separated(Parser::parse_expr)?; // ORDER BY can only appear after at least one argument, and not after a // star. We can ignore checking for it in the other branches. See: // https://www.postgresql.org/docs/current/sql-expressions.html#SYNTAX-AGGREGATES let order_by = if allow_order_by && self.parse_keywords(&[ORDER, BY]) { self.parse_comma_separated(Parser::parse_order_by_expr)? } else { vec![] }; self.expect_token(&Token::RParen)?; Ok(FunctionArgs::Args { args, order_by }) } } /// Parse `AS OF`, if present. fn parse_optional_as_of(&mut self) -> Result<Option<Expr<Raw>>, ParserError> { if self.parse_keyword(AS) { self.expect_keyword(OF)?; match self.parse_expr() { Ok(expr) => Ok(Some(expr)), Err(e) => { self.expected(e.pos, "a timestamp value after 'AS OF'", self.peek_token()) } } } else { Ok(None) } } /// Parse a comma-delimited list of projections after SELECT fn parse_select_item(&mut self) -> Result<SelectItem<Raw>, ParserError> { if self.consume_token(&Token::Star) { return Ok(SelectItem::Wildcard); } Ok(SelectItem::Expr { expr: self.parse_expr()?, alias: self.parse_optional_alias(Keyword::is_reserved_in_column_alias)?, }) } /// Parse an expression, optionally followed by ASC or DESC (used in ORDER BY) fn parse_order_by_expr(&mut self) -> Result<OrderByExpr<Raw>, ParserError> { let expr = self.parse_expr()?; let asc = if self.parse_keyword(ASC) { Some(true) } else if self.parse_keyword(DESC) { Some(false) } else { None }; Ok(OrderByExpr { expr, asc }) } fn parse_values(&mut self) -> Result<Values<Raw>, ParserError> { let values = self.parse_comma_separated(|parser| { parser.expect_token(&Token::LParen)?; let exprs = parser.parse_comma_separated(Parser::parse_expr)?; parser.expect_token(&Token::RParen)?; Ok(exprs) })?; Ok(Values(values)) } fn parse_start_transaction(&mut self) -> Result<Statement<Raw>, ParserError> { self.expect_keyword(TRANSACTION)?; Ok(Statement::StartTransaction(StartTransactionStatement { modes: self.parse_transaction_modes()?, })) } fn parse_begin(&mut self) -> Result<Statement<Raw>, ParserError> { let _ = self.parse_one_of_keywords(&[TRANSACTION, WORK]); Ok(Statement::StartTransaction(StartTransactionStatement { modes: self.parse_transaction_modes()?, })) } fn parse_transaction_modes(&mut self) -> Result<Vec<TransactionMode>, ParserError> { let mut modes = vec![]; let mut required = false; loop { let mode = if self.parse_keywords(&[ISOLATION, LEVEL]) { let iso_level = if self.parse_keywords(&[READ, UNCOMMITTED]) { TransactionIsolationLevel::ReadUncommitted } else if self.parse_keywords(&[READ, COMMITTED]) { TransactionIsolationLevel::ReadCommitted } else if self.parse_keywords(&[REPEATABLE, READ]) { TransactionIsolationLevel::RepeatableRead } else if self.parse_keyword(SERIALIZABLE) { TransactionIsolationLevel::Serializable } else { self.expected(self.peek_pos(), "isolation level", self.peek_token())? }; TransactionMode::IsolationLevel(iso_level) } else if self.parse_keywords(&[READ, ONLY]) { TransactionMode::AccessMode(TransactionAccessMode::ReadOnly) } else if self.parse_keywords(&[READ, WRITE]) { TransactionMode::AccessMode(TransactionAccessMode::ReadWrite) } else if required { self.expected(self.peek_pos(), "transaction mode", self.peek_token())? } else { break; }; modes.push(mode); // ANSI requires a comma after each transaction mode, but // PostgreSQL, for historical reasons, does not. We follow // PostgreSQL in making the comma optional, since that is strictly // more general. required = self.consume_token(&Token::Comma); } Ok(modes) } fn parse_commit(&mut self) -> Result<Statement<Raw>, ParserError> { Ok(Statement::Commit(CommitStatement { chain: self.parse_commit_rollback_chain()?, })) } fn parse_rollback(&mut self) -> Result<Statement<Raw>, ParserError> { Ok(Statement::Rollback(RollbackStatement { chain: self.parse_commit_rollback_chain()?, })) } fn parse_commit_rollback_chain(&mut self) -> Result<bool, ParserError> { let _ = self.parse_one_of_keywords(&[TRANSACTION, WORK]); if self.parse_keyword(AND) { let chain = !self.parse_keyword(NO); self.expect_keyword(CHAIN)?; Ok(chain) } else { Ok(false) } } fn parse_tail(&mut self) -> Result<Statement<Raw>, ParserError> { let relation = if self.consume_token(&Token::LParen) { let query = self.parse_query()?; self.expect_token(&Token::RParen)?; TailRelation::Query(query) } else { TailRelation::Name(self.parse_raw_name()?) }; let options = self.parse_opt_with_options()?; let as_of = self.parse_optional_as_of()?; Ok(Statement::Tail(TailStatement { relation, options, as_of, })) } /// Parse an `EXPLAIN` statement, assuming that the `EXPLAIN` token /// has already been consumed. fn parse_explain(&mut self) -> Result<Statement<Raw>, ParserError> { // (TYPED)? let typed = self.parse_keyword(TYPED); let mut timing = false; // options: ( '(' TIMING (true|false) ')' )? if let Some(Token::LParen) = self.peek_token() { // Check whether a valid option is after the parentheses, since the // parentheses may belong to the actual query to be explained. match self.peek_nth_token(1) { Some(Token::Keyword(TIMING)) => { self.next_token(); // Consume the LParen self.parse_comma_separated(|s| match s.expect_one_of_keywords(&[TIMING])? { TIMING => { timing = s.parse_boolean_value()?; Ok(()) } _ => unreachable!(), })?; self.expect_token(&Token::RParen)?; } _ => {} } } // (RAW | DECORRELATED | OPTIMIZED | PHYSICAL)? PLAN let stage = match self.parse_one_of_keywords(&[ RAW, DECORRELATED, OPTIMIZED, PHYSICAL, PLAN, QUERY, TIMESTAMP, ]) { Some(RAW) => { self.expect_keywords(&[PLAN, FOR])?; ExplainStage::RawPlan } Some(QUERY) => { self.expect_keywords(&[GRAPH, FOR])?; ExplainStage::QueryGraph } Some(DECORRELATED) => { self.expect_keywords(&[PLAN, FOR])?; ExplainStage::DecorrelatedPlan } Some(OPTIMIZED) => { if self.parse_keyword(QUERY) { self.expect_keywords(&[GRAPH, FOR])?; ExplainStage::OptimizedQueryGraph } else { self.expect_keywords(&[PLAN, FOR])?; ExplainStage::OptimizedPlan } } Some(PLAN) => { self.expect_keyword(FOR)?; ExplainStage::OptimizedPlan } Some(PHYSICAL) => { self.expect_keywords(&[PLAN, FOR])?; ExplainStage::PhysicalPlan } Some(TIMESTAMP) => { self.expect_keywords(&[FOR])?; ExplainStage::Timestamp } None => ExplainStage::OptimizedPlan, _ => unreachable!(), }; // VIEW view_name | query let explainee = if self.parse_keyword(VIEW) { Explainee::View(self.parse_raw_name()?) } else { Explainee::Query(self.parse_query()?) }; let options = ExplainOptions { typed, timing }; Ok(Statement::Explain(ExplainStatement { stage, explainee, options, })) } /// Parse a `DECLARE` statement, assuming that the `DECLARE` token /// has already been consumed. fn parse_declare(&mut self) -> Result<Statement<Raw>, ParserError> { let name = self.parse_identifier()?; self.expect_keyword(CURSOR)?; // WITHOUT HOLD is optional and the default behavior so we can ignore it. let _ = self.parse_keywords(&[WITHOUT, HOLD]); self.expect_keyword(FOR)?; let stmt = self.parse_statement()?; Ok(Statement::Declare(DeclareStatement { name, stmt: Box::new(stmt), })) } /// Parse a `CLOSE` statement, assuming that the `CLOSE` token /// has already been consumed. fn parse_close(&mut self) -> Result<Statement<Raw>, ParserError> { let name = self.parse_identifier()?; Ok(Statement::Close(CloseStatement { name })) } /// Parse a `PREPARE` statement, assuming that the `PREPARE` token /// has already been consumed. fn parse_prepare(&mut self) -> Result<Statement<Raw>, ParserError> { let name = self.parse_identifier()?; self.expect_keyword(AS)?; let pos = self.peek_pos(); // let stmt = match self.parse_statement()? { stmt @ Statement::Select(_) | stmt @ Statement::Insert(_) | stmt @ Statement::Delete(_) | stmt @ Statement::Update(_) => stmt, _ => return parser_err!(self, pos, "unpreparable statement"), }; Ok(Statement::Prepare(PrepareStatement { name, stmt: Box::new(stmt), })) } /// Parse a `EXECUTE` statement, assuming that the `EXECUTE` token /// has already been consumed. fn parse_execute(&mut self) -> Result<Statement<Raw>, ParserError> { let name = self.parse_identifier()?; let params = if self.consume_token(&Token::LParen) { let params = self.parse_comma_separated(Parser::parse_expr)?; self.expect_token(&Token::RParen)?; params } else { Vec::new() }; Ok(Statement::Execute(ExecuteStatement { name, params })) } /// Parse a `DEALLOCATE` statement, assuming that the `DEALLOCATE` token /// has already been consumed. fn parse_deallocate(&mut self) -> Result<Statement<Raw>, ParserError> { let _ = self.parse_keyword(PREPARE); let name = if self.parse_keyword(ALL) { None } else { Some(self.parse_identifier()?) }; Ok(Statement::Deallocate(DeallocateStatement { name })) } /// Parse a `FETCH` statement, assuming that the `FETCH` token /// has already been consumed. fn parse_fetch(&mut self) -> Result<Statement<Raw>, ParserError> { let _ = self.parse_keyword(FORWARD); let count = if let Some(count) = self.maybe_parse(Parser::parse_literal_uint) { Some(FetchDirection::ForwardCount(count)) } else if self.parse_keyword(ALL) { Some(FetchDirection::ForwardAll) } else { None }; let _ = self.parse_keyword(FROM); let name = self.parse_identifier()?; let options = self.parse_opt_with_options()?; Ok(Statement::Fetch(FetchStatement { name, count, options, })) } /// Parse a `RAISE` statement, assuming that the `RAISE` token /// has already been consumed. fn parse_raise(&mut self) -> Result<Statement<Raw>, ParserError> { let severity = match self.parse_one_of_keywords(&[DEBUG, INFO, LOG, NOTICE, WARNING]) { Some(DEBUG) => NoticeSeverity::Debug, Some(INFO) => NoticeSeverity::Info, Some(LOG) => NoticeSeverity::Log, Some(NOTICE) => NoticeSeverity::Notice, Some(WARNING) => NoticeSeverity::Warning, Some(_) => unreachable!(), None => self.expected(self.peek_pos(), "severity level", self.peek_token())?, }; Ok(Statement::Raise(RaiseStatement { severity })) } } impl CheckedRecursion for Parser<'_> { fn recursion_guard(&self) -> &RecursionGuard { &self.recursion_guard } }
37.989086
163
0.5028
f8da3711036c28a43a9786142068fe129fdb84ae
3,132
pub mod channel; pub mod emoji; pub mod guild; pub mod integration; pub mod interaction; pub mod member; pub mod message; pub mod presence; pub mod reaction; pub mod role; pub mod stage_instance; pub mod sticker; pub mod thread; pub mod voice_state; use crate::{config::ResourceType, InMemoryCache, UpdateCache}; use std::{borrow::Cow, collections::BTreeSet}; use twilight_model::{ gateway::payload::incoming::{Ready, UnavailableGuild, UserUpdate}, id::{marker::GuildMarker, Id}, user::{CurrentUser, User}, }; impl InMemoryCache { fn cache_current_user(&self, current_user: CurrentUser) { self.current_user .lock() .expect("current user poisoned") .replace(current_user); } pub(crate) fn cache_user(&self, user: Cow<'_, User>, guild_id: Option<Id<GuildMarker>>) { match self.users.get_mut(&user.id) { Some(u) if u.value() == user.as_ref() => { if let Some(guild_id) = guild_id { self.user_guilds .entry(user.id) .or_default() .insert(guild_id); } return; } Some(_) | None => {} } let user = user.into_owned(); let user_id = user.id; self.users.insert(user_id, user); if let Some(guild_id) = guild_id { let mut guild_id_set = BTreeSet::new(); guild_id_set.insert(guild_id); self.user_guilds.insert(user_id, guild_id_set); } } fn unavailable_guild(&self, guild_id: Id<GuildMarker>) { self.unavailable_guilds.insert(guild_id); self.guilds.remove(&guild_id); } } impl UpdateCache for Ready { fn update(&self, cache: &InMemoryCache) { if cache.wants(ResourceType::USER_CURRENT) { cache.cache_current_user(self.user.clone()); } if cache.wants(ResourceType::GUILD) { for guild in &self.guilds { cache.unavailable_guild(guild.id); } } } } impl UpdateCache for UnavailableGuild { fn update(&self, cache: &InMemoryCache) { if !cache.wants(ResourceType::GUILD) { return; } cache.guilds.remove(&self.id); cache.unavailable_guilds.insert(self.id); } } impl UpdateCache for UserUpdate { fn update(&self, cache: &InMemoryCache) { if !cache.wants(ResourceType::USER_CURRENT) { return; } cache.cache_current_user(self.0.clone()); } } #[cfg(test)] mod tests { use super::*; use crate::test; /// Test retrieval of the current user, notably that it doesn't simply /// panic or do anything funny. This is the only synchronous mutex that we /// might have trouble with across await points if we're not careful. #[test] fn test_current_user_retrieval() { let cache = InMemoryCache::new(); assert!(cache.current_user().is_none()); cache.cache_current_user(test::current_user(1)); assert!(cache.current_user().is_some()); } }
27.234783
93
0.592273
0eed07521f229af8a7da5cd1e08bc49f02cd2557
1,207
// Copyright 2021 Datafuse Labs. // // 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::sync::Arc; use common_datavalues::DataSchema; use common_datavalues::DataSchemaRef; #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] pub struct RenameTablePlan { pub tenant: String, pub entities: Vec<RenameTableEntity>, } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] pub struct RenameTableEntity { pub if_exists: bool, pub db: String, pub table_name: String, pub new_db: String, pub new_table_name: String, } impl RenameTablePlan { pub fn schema(&self) -> DataSchemaRef { Arc::new(DataSchema::empty()) } }
30.175
75
0.724938
71293436874b1816d9dc6e53fb560bce0ce975fd
3,313
use std::cmp; use na::{DMatrix, DVector, Matrix3x4, Matrix4, Matrix4x3, Vector4}; use nl::LU; quickcheck! { fn lup(m: DMatrix<f64>) -> bool { if m.len() != 0 { let lup = LU::new(m.clone()); let l = lup.l(); let u = lup.u(); let mut computed1 = &l * &u; lup.permute(&mut computed1); let computed2 = lup.p() * l * u; relative_eq!(computed1, m, epsilon = 1.0e-7) && relative_eq!(computed2, m, epsilon = 1.0e-7) } else { true } } fn lu_static(m: Matrix3x4<f64>) -> bool { let lup = LU::new(m); let l = lup.l(); let u = lup.u(); let mut computed1 = l * u; lup.permute(&mut computed1); let computed2 = lup.p() * l * u; relative_eq!(computed1, m, epsilon = 1.0e-7) && relative_eq!(computed2, m, epsilon = 1.0e-7) } fn lu_solve(n: usize, nb: usize) -> bool { if n != 0 { let n = cmp::min(n, 25); // To avoid slowing down the test too much. let nb = cmp::min(nb, 25); // To avoid slowing down the test too much. let m = DMatrix::<f64>::new_random(n, n); let lup = LU::new(m.clone()); let b1 = DVector::new_random(n); let b2 = DMatrix::new_random(n, nb); let sol1 = lup.solve(&b1).unwrap(); let sol2 = lup.solve(&b2).unwrap(); let tr_sol1 = lup.solve_transpose(&b1).unwrap(); let tr_sol2 = lup.solve_transpose(&b2).unwrap(); relative_eq!(&m * sol1, b1, epsilon = 1.0e-7) && relative_eq!(&m * sol2, b2, epsilon = 1.0e-7) && relative_eq!(m.transpose() * tr_sol1, b1, epsilon = 1.0e-7) && relative_eq!(m.transpose() * tr_sol2, b2, epsilon = 1.0e-7) } else { true } } fn lu_solve_static(m: Matrix4<f64>) -> bool { let lup = LU::new(m); let b1 = Vector4::new_random(); let b2 = Matrix4x3::new_random(); let sol1 = lup.solve(&b1).unwrap(); let sol2 = lup.solve(&b2).unwrap(); let tr_sol1 = lup.solve_transpose(&b1).unwrap(); let tr_sol2 = lup.solve_transpose(&b2).unwrap(); relative_eq!(m * sol1, b1, epsilon = 1.0e-7) && relative_eq!(m * sol2, b2, epsilon = 1.0e-7) && relative_eq!(m.transpose() * tr_sol1, b1, epsilon = 1.0e-7) && relative_eq!(m.transpose() * tr_sol2, b2, epsilon = 1.0e-7) } fn lu_inverse(n: usize) -> bool { if n != 0 { let n = cmp::min(n, 25); // To avoid slowing down the test too much. let m = DMatrix::<f64>::new_random(n, n); if let Some(m1) = LU::new(m.clone()).inverse() { let id1 = &m * &m1; let id2 = &m1 * &m; return id1.is_identity(1.0e-7) && id2.is_identity(1.0e-7); } } return true; } fn lu_inverse_static(m: Matrix4<f64>) -> bool { match LU::new(m.clone()).inverse() { Some(m1) => { let id1 = &m * &m1; let id2 = &m1 * &m; id1.is_identity(1.0e-5) && id2.is_identity(1.0e-5) }, None => true } } }
30.675926
82
0.480531
b98f230dc5ce804ff0de0dbb314b9508e6fee806
1,173
//! A dummy optimization printing the basic block data structures use crate::asm::Body; use crate::Compiler; #[derive(Default)] pub struct Pass; impl super::Pass for Pass { fn name(&self) -> &'static str { "print_structure" } #[allow(clippy::cognitive_complexity)] fn apply<'a>(&mut self, cx: &'a Compiler, body: &mut Body<'a>) { if trace_span!("").is_disabled() { return; } for (block_id, block) in body.blocks.iter().enumerate() { trace!("# Block {}", block_id); for stmt in block.stmts.iter() { let relexed = stmt.relex(cx); trace!(" # {}", relexed); trace!(" # write: {:?}", stmt.write_registers(cx)); trace!(" # read: {:?}", stmt.read_registers(cx)); trace!(" # barrier: {:?}", stmt.is_barrier(cx)); trace!( " # memory (R/W): {:?}/{:?}", stmt.memory_read(cx), stmt.memory_write(cx) ); } trace!(" # {:?}", block.terminator.elem); } } }
31.702703
74
0.457801
7aaf2180044c0b2c81ded40881c749a32e537697
321
fn main() { let mut total = 0; let mut last = 0; let mut tmp = 0; let mut current = 1; while current <= 4000000 { tmp = current; current = last + current; last = tmp; if current % 2 == 0 { total += current; }; }; println!("{}", total); }
16.894737
33
0.442368
bbc1b789c0e46e057284aa96fc39c1724bbe8f26
12,781
#![allow(clippy::inconsistent_digit_grouping, clippy::unusual_byte_groupings)] extern crate autocfg; extern crate cc; #[cfg(feature = "vendored")] extern crate openssl_src; extern crate pkg_config; #[cfg(target_env = "msvc")] extern crate vcpkg; use std::collections::HashSet; use std::env; use std::ffi::OsString; use std::path::{Path, PathBuf}; mod cfgs; mod find_normal; #[cfg(feature = "vendored")] mod find_vendored; #[derive(PartialEq)] enum Version { Openssl3xx, Openssl11x, Openssl10x, Libressl, } fn env_inner(name: &str) -> Option<OsString> { let var = env::var_os(name); println!("cargo:rerun-if-env-changed={}", name); match var { Some(ref v) => println!("{} = {}", name, v.to_string_lossy()), None => println!("{} unset", name), } var } fn env(name: &str) -> Option<OsString> { let prefix = env::var("TARGET").unwrap().to_uppercase().replace("-", "_"); let prefixed = format!("{}_{}", prefix, name); env_inner(&prefixed).or_else(|| env_inner(name)) } fn find_openssl(target: &str) -> (PathBuf, PathBuf) { #[cfg(feature = "vendored")] { // vendor if the feature is present, unless // OPENSSL_NO_VENDOR exists and isn't `0` if env("OPENSSL_NO_VENDOR").map_or(true, |s| s == "0") { return find_vendored::get_openssl(target); } } find_normal::get_openssl(target) } fn main() { check_rustc_versions(); let target = env::var("TARGET").unwrap(); let (lib_dir, include_dir) = find_openssl(&target); if !Path::new(&lib_dir).exists() { panic!( "OpenSSL library directory does not exist: {}", lib_dir.to_string_lossy() ); } if !Path::new(&include_dir).exists() { panic!( "OpenSSL include directory does not exist: {}", include_dir.to_string_lossy() ); } println!( "cargo:rustc-link-search=native={}", lib_dir.to_string_lossy() ); println!("cargo:include={}", include_dir.to_string_lossy()); let version = validate_headers(&[include_dir]); let libs_env = env("OPENSSL_LIBS"); let libs = match libs_env.as_ref().and_then(|s| s.to_str()) { Some(v) => { if v.is_empty() { vec![] } else { v.split(':').collect() } } None => match version { Version::Openssl10x if target.contains("windows") => vec!["ssleay32", "libeay32"], Version::Openssl3xx | Version::Openssl11x if target.contains("windows-msvc") => { vec!["libssl", "libcrypto"] } _ => vec!["ssl", "crypto"], }, }; let kind = determine_mode(Path::new(&lib_dir), &libs); for lib in libs.into_iter() { println!("cargo:rustc-link-lib={}={}", kind, lib); } // https://github.com/openssl/openssl/pull/15086 if version == Version::Openssl3xx && kind == "static" && (env::var("CARGO_CFG_TARGET_OS").unwrap() == "linux" || env::var("CARGO_CFG_TARGET_OS").unwrap() == "android") && env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap() == "32" { println!("cargo:rustc-link-lib=dylib=atomic"); } if kind == "static" && target.contains("windows") { println!("cargo:rustc-link-lib=dylib=gdi32"); println!("cargo:rustc-link-lib=dylib=user32"); println!("cargo:rustc-link-lib=dylib=crypt32"); println!("cargo:rustc-link-lib=dylib=ws2_32"); println!("cargo:rustc-link-lib=dylib=advapi32"); } } fn check_rustc_versions() { let cfg = autocfg::new(); if cfg.probe_rustc_version(1, 31) { println!("cargo:rustc-cfg=const_fn"); } } /// Validates the header files found in `include_dir` and then returns the /// version string of OpenSSL. #[allow(clippy::manual_strip)] // we need to support pre-1.45.0 fn validate_headers(include_dirs: &[PathBuf]) -> Version { // This `*-sys` crate only works with OpenSSL 1.0.1, 1.0.2, 1.1.0, 1.1.1 and 3.0.0. // To correctly expose the right API from this crate, take a look at // `opensslv.h` to see what version OpenSSL claims to be. // // OpenSSL has a number of build-time configuration options which affect // various structs and such. Since OpenSSL 1.1.0 this isn't really a problem // as the library is much more FFI-friendly, but 1.0.{1,2} suffer this problem. // // To handle all this conditional compilation we slurp up the configuration // file of OpenSSL, `opensslconf.h`, and then dump out everything it defines // as our own #[cfg] directives. That way the `ossl10x.rs` bindings can // account for compile differences and such. println!("cargo:rerun-if-changed=build/expando.c"); let mut gcc = cc::Build::new(); for include_dir in include_dirs { gcc.include(include_dir); } let expanded = match gcc.file("build/expando.c").try_expand() { Ok(expanded) => expanded, Err(e) => { panic!( " Header expansion error: {:?} Failed to find OpenSSL development headers. You can try fixing this setting the `OPENSSL_DIR` environment variable pointing to your OpenSSL installation or installing OpenSSL headers package specific to your distribution: # On Ubuntu sudo apt-get install libssl-dev # On Arch Linux sudo pacman -S openssl # On Fedora sudo dnf install openssl-devel See rust-openssl README for more information: https://github.com/sfackler/rust-openssl#linux ", e ); } }; let expanded = String::from_utf8(expanded).unwrap(); let mut enabled = vec![]; let mut openssl_version = None; let mut libressl_version = None; for line in expanded.lines() { let line = line.trim(); let openssl_prefix = "RUST_VERSION_OPENSSL_"; let new_openssl_prefix = "RUST_VERSION_NEW_OPENSSL_"; let libressl_prefix = "RUST_VERSION_LIBRESSL_"; let conf_prefix = "RUST_CONF_"; if line.starts_with(openssl_prefix) { let version = &line[openssl_prefix.len()..]; openssl_version = Some(parse_version(version)); } else if line.starts_with(new_openssl_prefix) { let version = &line[new_openssl_prefix.len()..]; openssl_version = Some(parse_new_version(version)); } else if line.starts_with(libressl_prefix) { let version = &line[libressl_prefix.len()..]; libressl_version = Some(parse_version(version)); } else if line.starts_with(conf_prefix) { enabled.push(&line[conf_prefix.len()..]); } } for enabled in &enabled { println!("cargo:rustc-cfg=osslconf=\"{}\"", enabled); } println!("cargo:conf={}", enabled.join(",")); for cfg in cfgs::get(openssl_version, libressl_version) { println!("cargo:rustc-cfg={}", cfg); } if let Some(libressl_version) = libressl_version { println!("cargo:libressl_version_number={:x}", libressl_version); let major = (libressl_version >> 28) as u8; let minor = (libressl_version >> 20) as u8; let fix = (libressl_version >> 12) as u8; let (major, minor, fix) = match (major, minor, fix) { (2, 5, 0) => ('2', '5', '0'), (2, 5, 1) => ('2', '5', '1'), (2, 5, 2) => ('2', '5', '2'), (2, 5, _) => ('2', '5', 'x'), (2, 6, 0) => ('2', '6', '0'), (2, 6, 1) => ('2', '6', '1'), (2, 6, 2) => ('2', '6', '2'), (2, 6, _) => ('2', '6', 'x'), (2, 7, _) => ('2', '7', 'x'), (2, 8, 0) => ('2', '8', '0'), (2, 8, 1) => ('2', '8', '1'), (2, 8, _) => ('2', '8', 'x'), (2, 9, 0) => ('2', '9', '0'), (2, 9, _) => ('2', '9', 'x'), (3, 0, 0) => ('3', '0', '0'), (3, 0, 1) => ('3', '0', '1'), (3, 0, _) => ('3', '0', 'x'), (3, 1, 0) => ('3', '1', '0'), (3, 1, _) => ('3', '1', 'x'), (3, 2, 0) => ('3', '2', '0'), (3, 2, 1) => ('3', '2', '1'), (3, 2, _) => ('3', '2', 'x'), (3, 3, 0) => ('3', '3', '0'), (3, 3, 1) => ('3', '3', '1'), (3, 3, _) => ('3', '3', 'x'), (3, 4, 0) => ('3', '4', '0'), (3, 4, 1) => ('3', '4', '1'), _ => version_error(), }; println!("cargo:libressl=true"); println!("cargo:libressl_version={}{}{}", major, minor, fix); println!("cargo:version=101"); Version::Libressl } else { let openssl_version = openssl_version.unwrap(); println!("cargo:version_number={:x}", openssl_version); if openssl_version >= 0x4_00_00_00_0 { version_error() } else if openssl_version >= 0x3_00_00_00_0 { Version::Openssl3xx } else if openssl_version >= 0x1_01_01_00_0 { println!("cargo:version=111"); Version::Openssl11x } else if openssl_version >= 0x1_01_00_06_0 { println!("cargo:version=110"); println!("cargo:patch=f"); Version::Openssl11x } else if openssl_version >= 0x1_01_00_00_0 { println!("cargo:version=110"); Version::Openssl11x } else if openssl_version >= 0x1_00_02_00_0 { println!("cargo:version=102"); Version::Openssl10x } else if openssl_version >= 0x1_00_01_00_0 { println!("cargo:version=101"); Version::Openssl10x } else { version_error() } } } fn version_error() -> ! { panic!( " This crate is only compatible with OpenSSL (version 1.0.1 through 1.1.1, or 3.0.0), or LibreSSL 2.5 through 3.4.1, but a different version of OpenSSL was found. The build is now aborting due to this version mismatch. " ); } // parses a string that looks like "0x100020cfL" #[allow(deprecated)] // trim_right_matches is now trim_end_matches #[allow(clippy::match_like_matches_macro)] // matches macro requires rust 1.42.0 fn parse_version(version: &str) -> u64 { // cut off the 0x prefix assert!(version.starts_with("0x")); let version = &version[2..]; // and the type specifier suffix let version = version.trim_right_matches(|c: char| match c { '0'..='9' | 'a'..='f' | 'A'..='F' => false, _ => true, }); u64::from_str_radix(version, 16).unwrap() } // parses a string that looks like 3_0_0 fn parse_new_version(version: &str) -> u64 { println!("version: {}", version); let mut it = version.split('_'); let major = it.next().unwrap().parse::<u64>().unwrap(); let minor = it.next().unwrap().parse::<u64>().unwrap(); let patch = it.next().unwrap().parse::<u64>().unwrap(); (major << 28) | (minor << 20) | (patch << 4) } /// Given a libdir for OpenSSL (where artifacts are located) as well as the name /// of the libraries we're linking to, figure out whether we should link them /// statically or dynamically. fn determine_mode(libdir: &Path, libs: &[&str]) -> &'static str { // First see if a mode was explicitly requested let kind = env("OPENSSL_STATIC"); match kind.as_ref().and_then(|s| s.to_str()) { Some("0") => return "dylib", Some(_) => return "static", None => {} } // Next, see what files we actually have to link against, and see what our // possibilities even are. let files = libdir .read_dir() .unwrap() .map(|e| e.unwrap()) .map(|e| e.file_name()) .filter_map(|e| e.into_string().ok()) .collect::<HashSet<_>>(); let can_static = libs .iter() .all(|l| files.contains(&format!("lib{}.a", l)) || files.contains(&format!("{}.lib", l))); let can_dylib = libs.iter().all(|l| { files.contains(&format!("lib{}.so", l)) || files.contains(&format!("{}.dll", l)) || files.contains(&format!("lib{}.dylib", l)) }); match (can_static, can_dylib) { (true, false) => return "static", (false, true) => return "dylib", (false, false) => { panic!( "OpenSSL libdir at `{}` does not contain the required files \ to either statically or dynamically link OpenSSL", libdir.display() ); } (true, true) => {} } // Ok, we've got not explicit preference and can *either* link statically or // link dynamically. In the interest of "security upgrades" and/or "best // practices with security libs", let's link dynamically. "dylib" }
33.545932
99
0.557468
ccf2485f6d3c16eb503517e94b745e6291e3c2b2
242
#[cfg(all(feature = "curl-client", not(target_arch = "wasm32")))] pub(crate) use super::isahc::IsahcClient as NativeClient; #[cfg(all(feature = "wasm-client", target_arch = "wasm32"))] pub(crate) use super::wasm::WasmClient as NativeClient;
40.333333
65
0.714876
ab398a9a7240b3cf49556cc43442d4c7bc7f9710
6,160
// Non-conventional componentwise operators. use num::{Signed, Zero}; use std::ops::{Add, Mul}; use alga::general::{ClosedDiv, ClosedMul}; use base::allocator::{Allocator, SameShapeAllocator}; use base::constraint::{SameNumberOfColumns, SameNumberOfRows, ShapeConstraint}; use base::dimension::Dim; use base::storage::{Storage, StorageMut}; use base::{DefaultAllocator, Matrix, MatrixMN, MatrixSum, Scalar}; /// The type of the result of a matrix componentwise operation. pub type MatrixComponentOp<N, R1, C1, R2, C2> = MatrixSum<N, R1, C1, R2, C2>; impl<N: Scalar, R: Dim, C: Dim, S: Storage<N, R, C>> Matrix<N, R, C, S> { /// Computes the componentwise absolute value. #[inline] pub fn abs(&self) -> MatrixMN<N, R, C> where N: Signed, DefaultAllocator: Allocator<N, R, C>, { let mut res = self.clone_owned(); for e in res.iter_mut() { *e = e.abs(); } res } // FIXME: add other operators like component_ln, component_pow, etc. ? } macro_rules! component_binop_impl( ($($binop: ident, $binop_mut: ident, $binop_assign: ident, $cmpy: ident, $Trait: ident . $op: ident . $op_assign: ident, $desc:expr, $desc_cmpy:expr, $desc_mut:expr);* $(;)*) => {$( impl<N: Scalar, R1: Dim, C1: Dim, SA: Storage<N, R1, C1>> Matrix<N, R1, C1, SA> { #[doc = $desc] #[inline] pub fn $binop<R2, C2, SB>(&self, rhs: &Matrix<N, R2, C2, SB>) -> MatrixComponentOp<N, R1, C1, R2, C2> where N: $Trait, R2: Dim, C2: Dim, SB: Storage<N, R2, C2>, DefaultAllocator: SameShapeAllocator<N, R1, C1, R2, C2>, ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2> { assert_eq!(self.shape(), rhs.shape(), "Componentwise mul/div: mismatched matrix dimensions."); let mut res = self.clone_owned_sum(); for j in 0 .. res.ncols() { for i in 0 .. res.nrows() { unsafe { res.get_unchecked_mut(i, j).$op_assign(*rhs.get_unchecked(i, j)); } } } res } } impl<N: Scalar, R1: Dim, C1: Dim, SA: StorageMut<N, R1, C1>> Matrix<N, R1, C1, SA> { // componentwise binop plus Y. #[doc = $desc_cmpy] #[inline] pub fn $cmpy<R2, C2, SB, R3, C3, SC>(&mut self, alpha: N, a: &Matrix<N, R2, C2, SB>, b: &Matrix<N, R3, C3, SC>, beta: N) where N: $Trait + Zero + Mul<N, Output = N> + Add<N, Output = N>, R2: Dim, C2: Dim, R3: Dim, C3: Dim, SB: Storage<N, R2, C2>, SC: Storage<N, R3, C3>, ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2> + SameNumberOfRows<R1, R3> + SameNumberOfColumns<C1, C3> { assert_eq!(self.shape(), a.shape(), "Componentwise mul/div: mismatched matrix dimensions."); assert_eq!(self.shape(), b.shape(), "Componentwise mul/div: mismatched matrix dimensions."); if beta.is_zero() { for j in 0 .. self.ncols() { for i in 0 .. self.nrows() { unsafe { let res = alpha * a.get_unchecked(i, j).$op(*b.get_unchecked(i, j)); *self.get_unchecked_mut(i, j) = res; } } } } else { for j in 0 .. self.ncols() { for i in 0 .. self.nrows() { unsafe { let res = alpha * a.get_unchecked(i, j).$op(*b.get_unchecked(i, j)); *self.get_unchecked_mut(i, j) = beta * *self.get_unchecked(i, j) + res; } } } } } #[doc = $desc_mut] #[inline] pub fn $binop_assign<R2, C2, SB>(&mut self, rhs: &Matrix<N, R2, C2, SB>) where N: $Trait, R2: Dim, C2: Dim, SB: Storage<N, R2, C2>, ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2> { assert_eq!(self.shape(), rhs.shape(), "Componentwise mul/div: mismatched matrix dimensions."); for j in 0 .. self.ncols() { for i in 0 .. self.nrows() { unsafe { self.get_unchecked_mut(i, j).$op_assign(*rhs.get_unchecked(i, j)); } } } } #[doc = $desc_mut] #[inline] #[deprecated(note = "This is renamed using the `_assign` sufix instead of the `_mut` suffix.")] pub fn $binop_mut<R2, C2, SB>(&mut self, rhs: &Matrix<N, R2, C2, SB>) where N: $Trait, R2: Dim, C2: Dim, SB: Storage<N, R2, C2>, ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2> { self.$binop_assign(rhs) } } )*} ); component_binop_impl!( component_mul, component_mul_mut, component_mul_assign, cmpy, ClosedMul.mul.mul_assign, "Componentwise matrix multiplication.", "Computes componentwise `self[i] = alpha * a[i] * b[i] + beta * self[i]`.", "Inplace componentwise matrix multiplication."; component_div, component_div_mut, component_div_assign, cdpy, ClosedDiv.div.div_assign, "Componentwise matrix division.", "Computes componentwise `self[i] = alpha * a[i] / b[i] + beta * self[i]`.", "Inplace componentwise matrix division."; // FIXME: add other operators like bitshift, etc. ? );
41.904762
185
0.483766
913f488127c0d110fc41828b52f18dde2474d12b
5,459
// Copyright 2018 The proptest developers // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(never_type)] use proptest::prelude::Arbitrary; use proptest_derive::Arbitrary; #[derive(Debug, Arbitrary)] enum T1 { V1, } #[derive(Debug, Arbitrary)] enum T2 { V1(), V2 {}, } #[derive(Debug, Arbitrary)] enum T3 { V1(), V2 {}, V3, } #[derive(Debug, Arbitrary)] enum T4 { V1, V2(), V3, V4 {}, } #[derive(Debug, Arbitrary)] enum T5 { V1, V2, V3, V4 {}, V5(), } #[derive(Debug, Arbitrary)] enum T6 { V1(), V2, V3 {}, V4, V5, V6, } #[derive(Debug, Arbitrary)] enum T7 { V1, V2, V3, V4 {}, V5, V6, V7(), } #[derive(Debug, Arbitrary)] enum T8 { V1, V2, V3(), V4, V5, V6 {}, V7, V8, } #[derive(Debug, Arbitrary)] enum T9 { V1, V2, V3, V4, V5 {}, V6(), V7, V8, V9, } #[derive(Debug, Arbitrary)] enum T10 { V1, V2, V3, V4, V5 {}, V6(), V7, V8, V9, V10, } #[derive(Debug, Arbitrary)] enum T11 { V1, V2, V3, V4, V5 {}, V6(), V7, V8, V9, V10, V11, } #[derive(Debug, Arbitrary)] enum T12 { V1, V2, V3, V4, V5 {}, V6(), V7, V8, V9, V10, V11, V12, } #[derive(Debug, Arbitrary)] enum T13 { V1, V2, V3, V4, V5 {}, V6(), V7, V8, V9, V10, V11, V12, V13, } #[derive(Debug, Arbitrary)] enum T14 { V1, V2, V3, V4, V5 {}, V6(), V7, V8, V9, V10, V11, V12, V13, V14, } #[derive(Debug, Arbitrary)] enum T15 { V1, V2, V3, V4, V5 {}, V6(), V7, V8, V9, V10, V11, V12, V13, V14, V15, } #[derive(Debug, Arbitrary)] enum T16 { V1, V2, V3, V4, V5 {}, V6(), V7, V8, V9, V10, V11, V12, V13, V14, V15, V16, } #[derive(Debug, Arbitrary)] enum T17 { V1, V2, V3, V4, V5 {}, V6(), V7, V8, V9, V10, V11, V12, V13, V14, V15, V16, V17, } #[derive(Debug, Arbitrary)] enum T18 { V1, V2, V3, V4, V5 {}, V6(), V7, V8, V9, V10, V11, V12, V13, V14, V15, V16, V17, V18, } #[derive(Debug, Arbitrary)] enum T19 { V1, V2, V3, V4, V5 {}, V6(), V7, V8, V9, V10, V11, V12, V13, V14, V15, V16, V17, V18, V19, } #[derive(Debug, Arbitrary)] enum T20 { V1, V2, V3, V4, V5 {}, V6(), V7, V8, V9, V10, V11, V12, V13, V14, V15, V16, V17, V18, V19, V20, } #[derive(Debug, Arbitrary)] enum T21 { V1, V2, V3, V4, V5 {}, V6(), V7, V8, V9, V10, V11, V12, V13, V14, V15, V16, V17, V18, V19, V20, V21, } #[derive(Debug, Arbitrary)] enum T22 { V1, V2, V3, V4, V5 {}, V6(), V7, V8, V9, V10, V11, V12, V13, V14, V15, V16, V17, V18, V19, V20, V21, V22, } #[derive(Debug, Arbitrary)] enum T23 { V1, V2, V3, V4, V5 {}, V6(), V7, V8, V9, V10, V11, V12, V13, V14, V15, V16, V17, V18, V19, V20, V21, V22, V23, } #[derive(Debug, Arbitrary)] enum T24 { V1, V2, V3, V4, V5 {}, V6(), V7, V8, V9, V10, V11, V12, V13, V14, V15, V16, V17, V18, V19, V20, V21, V22, V23, V24, } #[derive(Debug, Arbitrary)] enum T25 { V1, V2, V3, V4, V5 {}, V6(), V7, V8, V9, V10, V11, V12, V13, V14, V15, V16, V17, V18, V19, V20, V21, V22, V23, V24, V25, } #[derive(Clone, Debug, Arbitrary)] enum Alan { A(usize), B(String), C(()), D(u32), E(f64), F(char), } #[derive(Clone, Debug, Arbitrary)] enum SameType { A(usize), B(usize), } #[test] fn asserting_arbitrary() { fn assert_arbitrary<T: Arbitrary>() {} assert_arbitrary::<T1>(); assert_arbitrary::<T2>(); assert_arbitrary::<T3>(); assert_arbitrary::<T4>(); assert_arbitrary::<T5>(); assert_arbitrary::<T6>(); assert_arbitrary::<T7>(); assert_arbitrary::<T8>(); assert_arbitrary::<T9>(); assert_arbitrary::<T10>(); assert_arbitrary::<T11>(); assert_arbitrary::<T12>(); assert_arbitrary::<T13>(); assert_arbitrary::<T14>(); assert_arbitrary::<T15>(); assert_arbitrary::<T16>(); assert_arbitrary::<T17>(); assert_arbitrary::<T18>(); assert_arbitrary::<T19>(); assert_arbitrary::<T20>(); assert_arbitrary::<T21>(); assert_arbitrary::<T22>(); assert_arbitrary::<T23>(); assert_arbitrary::<T24>(); assert_arbitrary::<T25>(); assert_arbitrary::<Alan>(); assert_arbitrary::<SameType>(); }
11.209446
68
0.449167
8aa79a0eea983f8a4046c61e42a67b5cd0738920
3,337
use anyhow::Result; /// Starts an executable file in a cross-platform way. /// /// This is the Windows version. #[cfg(windows)] pub fn start_executable<I, S>(exe_path: &str, exe_arguments: I) -> Result<bool> where I: IntoIterator<Item = S>, S: AsRef<str>, { // Fold parameter list into a String let exe_parameter = exe_arguments .into_iter() .fold(String::new(), |a: String, b| a + " " + b.as_ref() + ""); windows::win32_spawn_process_runas(exe_path, &exe_parameter) } /// Starts an executable file in a cross-platform way. /// /// This is the non-Windows version. #[cfg(not(windows))] pub fn start_executable<I, S>(exe_path: &str, exe_arguments: I) -> Result<bool> where I: IntoIterator<Item = S>, S: AsRef<str>, { use std::process::Command; let exe_arguments: Vec<String> = exe_arguments .into_iter() .map(|e| e.as_ref().into()) .collect(); Command::new(exe_path) .args(exe_arguments) .spawn() .map(|_| Ok(true))? } // Note: Taken from the rustup project #[cfg(windows)] mod windows { use anyhow::{anyhow, Result}; use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; fn to_u16s<S: AsRef<OsStr>>(s: S) -> Result<Vec<u16>> { fn inner(s: &OsStr) -> Result<Vec<u16>> { let mut maybe_result: Vec<u16> = s.encode_wide().collect(); if maybe_result.iter().any(|&u| u == 0) { return Err(anyhow!("strings passed to WinAPI cannot contain NULs")); } maybe_result.push(0); Ok(maybe_result) } inner(s.as_ref()) } /// This function is required to start processes that require elevation, from /// a non-elevated process. pub fn win32_spawn_process_runas<S>(path: S, parameter: S) -> Result<bool> where S: AsRef<OsStr>, { use std::ptr; use winapi::ctypes::c_int; use winapi::shared::minwindef::{BOOL, ULONG}; use winapi::um::shellapi::SHELLEXECUTEINFOW; extern "system" { pub fn ShellExecuteExW(pExecInfo: *mut SHELLEXECUTEINFOW) -> BOOL; } const SEE_MASK_CLASSNAME: ULONG = 1; const SW_SHOW: c_int = 5; // Note: It seems `path` has to be absolute for the class overwrite to work let exe_path = std::env::current_dir()?.join(path.as_ref()); let exe_path = to_u16s(exe_path.to_str().unwrap_or(""))?; let parameter = to_u16s(parameter)?; let operation = to_u16s("runas")?; let class = to_u16s("exefile")?; let mut execute_info = SHELLEXECUTEINFOW { cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32, fMask: SEE_MASK_CLASSNAME, hwnd: ptr::null_mut(), lpVerb: operation.as_ptr(), lpFile: exe_path.as_ptr(), lpParameters: parameter.as_ptr(), lpDirectory: ptr::null_mut(), nShow: SW_SHOW, hInstApp: ptr::null_mut(), lpIDList: ptr::null_mut(), lpClass: class.as_ptr(), hkeyClass: ptr::null_mut(), dwHotKey: 0, hMonitor: ptr::null_mut(), hProcess: ptr::null_mut(), }; let result = unsafe { ShellExecuteExW(&mut execute_info) }; Ok(result != 0) } }
32.398058
84
0.580461
b9dcd083c0b8c9b176883851952e7cbdd3007cd9
73,807
use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs}; use rustc_ast::attr; use rustc_ast::ptr::P as AstP; use rustc_ast::*; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_data_structures::thin_vec::ThinVec; use rustc_errors::struct_span_err; use rustc_hir as hir; use rustc_hir::def::Res; use rustc_hir::definitions::DefPathData; use rustc_session::parse::feature_err; use rustc_span::hygiene::ExpnId; use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned}; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::{hygiene::ForLoopLoc, DUMMY_SP}; impl<'hir> LoweringContext<'_, 'hir> { fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> &'hir [hir::Expr<'hir>] { self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x))) } pub(super) fn lower_expr(&mut self, e: &Expr) -> &'hir hir::Expr<'hir> { self.arena.alloc(self.lower_expr_mut(e)) } pub(super) fn lower_expr_mut(&mut self, e: &Expr) -> hir::Expr<'hir> { ensure_sufficient_stack(|| { let kind = match e.kind { ExprKind::Box(ref inner) => hir::ExprKind::Box(self.lower_expr(inner)), ExprKind::Array(ref exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)), ExprKind::ConstBlock(ref anon_const) => { let anon_const = self.lower_anon_const(anon_const); hir::ExprKind::ConstBlock(anon_const) } ExprKind::Repeat(ref expr, ref count) => { let expr = self.lower_expr(expr); let count = self.lower_anon_const(count); hir::ExprKind::Repeat(expr, count) } ExprKind::Tup(ref elts) => hir::ExprKind::Tup(self.lower_exprs(elts)), ExprKind::Call(ref f, ref args) => { if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f) { self.lower_legacy_const_generics((**f).clone(), args.clone(), &legacy_args) } else { let f = self.lower_expr(f); hir::ExprKind::Call(f, self.lower_exprs(args)) } } ExprKind::MethodCall(ref seg, ref args, span) => { let hir_seg = self.arena.alloc(self.lower_path_segment( e.span, seg, ParamMode::Optional, 0, ParenthesizedGenericArgs::Err, ImplTraitContext::disallowed(), None, )); let args = self.lower_exprs(args); hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args, span) } ExprKind::Binary(binop, ref lhs, ref rhs) => { let binop = self.lower_binop(binop); let lhs = self.lower_expr(lhs); let rhs = self.lower_expr(rhs); hir::ExprKind::Binary(binop, lhs, rhs) } ExprKind::Unary(op, ref ohs) => { let op = self.lower_unop(op); let ohs = self.lower_expr(ohs); hir::ExprKind::Unary(op, ohs) } ExprKind::Lit(ref l) => hir::ExprKind::Lit(respan(l.span, l.kind.clone())), ExprKind::Cast(ref expr, ref ty) => { let expr = self.lower_expr(expr); let ty = self.lower_ty(ty, ImplTraitContext::disallowed()); hir::ExprKind::Cast(expr, ty) } ExprKind::Type(ref expr, ref ty) => { let expr = self.lower_expr(expr); let ty = self.lower_ty(ty, ImplTraitContext::disallowed()); hir::ExprKind::Type(expr, ty) } ExprKind::AddrOf(k, m, ref ohs) => { let ohs = self.lower_expr(ohs); hir::ExprKind::AddrOf(k, m, ohs) } ExprKind::Let(ref pat, ref scrutinee) => { self.lower_expr_let(e.span, pat, scrutinee) } ExprKind::If(ref cond, ref then, ref else_opt) => match cond.kind { ExprKind::Let(ref pat, ref scrutinee) => { self.lower_expr_if_let(e.span, pat, scrutinee, then, else_opt.as_deref()) } ExprKind::Paren(ref paren) => match paren.peel_parens().kind { ExprKind::Let(ref pat, ref scrutinee) => { // A user has written `if (let Some(x) = foo) {`, we want to avoid // confusing them with mentions of nightly features. // If this logic is changed, you will also likely need to touch // `unused::UnusedParens::check_expr`. self.if_let_expr_with_parens(cond, &paren.peel_parens()); self.lower_expr_if_let( e.span, pat, scrutinee, then, else_opt.as_deref(), ) } _ => self.lower_expr_if(cond, then, else_opt.as_deref()), }, _ => self.lower_expr_if(cond, then, else_opt.as_deref()), }, ExprKind::While(ref cond, ref body, opt_label) => self .with_loop_scope(e.id, |this| { this.lower_expr_while_in_loop_scope(e.span, cond, body, opt_label) }), ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| { hir::ExprKind::Loop( this.lower_block(body, false), opt_label, hir::LoopSource::Loop, DUMMY_SP, ) }), ExprKind::TryBlock(ref body) => self.lower_expr_try_block(body), ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match( self.lower_expr(expr), self.arena.alloc_from_iter(arms.iter().map(|x| self.lower_arm(x))), hir::MatchSource::Normal, ), ExprKind::Async(capture_clause, closure_node_id, ref block) => self .make_async_expr( capture_clause, closure_node_id, None, block.span, hir::AsyncGeneratorKind::Block, |this| this.with_new_scopes(|this| this.lower_block_expr(block)), ), ExprKind::Await(ref expr) => self.lower_expr_await(e.span, expr), ExprKind::Closure( capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span, ) => { if let Async::Yes { closure_id, .. } = asyncness { self.lower_expr_async_closure( capture_clause, closure_id, decl, body, fn_decl_span, ) } else { self.lower_expr_closure( capture_clause, movability, decl, body, fn_decl_span, ) } } ExprKind::Block(ref blk, opt_label) => { hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label) } ExprKind::Assign(ref el, ref er, span) => { self.lower_expr_assign(el, er, span, e.span) } ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp( self.lower_binop(op), self.lower_expr(el), self.lower_expr(er), ), ExprKind::Field(ref el, ident) => hir::ExprKind::Field(self.lower_expr(el), ident), ExprKind::Index(ref el, ref er) => { hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er)) } ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => { self.lower_expr_range_closed(e.span, e1, e2) } ExprKind::Range(ref e1, ref e2, lims) => { self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims) } ExprKind::Underscore => { self.sess .struct_span_err( e.span, "in expressions, `_` can only be used on the left-hand side of an assignment", ) .span_label(e.span, "`_` not allowed here") .emit(); hir::ExprKind::Err } ExprKind::Path(ref qself, ref path) => { let qpath = self.lower_qpath( e.id, qself, path, ParamMode::Optional, ImplTraitContext::disallowed(), ); hir::ExprKind::Path(qpath) } ExprKind::Break(opt_label, ref opt_expr) => { let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x)); hir::ExprKind::Break(self.lower_jump_destination(e.id, opt_label), opt_expr) } ExprKind::Continue(opt_label) => { hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label)) } ExprKind::Ret(ref e) => { let e = e.as_ref().map(|x| self.lower_expr(x)); hir::ExprKind::Ret(e) } ExprKind::InlineAsm(ref asm) => { hir::ExprKind::InlineAsm(self.lower_inline_asm(e.span, asm)) } ExprKind::LlvmInlineAsm(ref asm) => self.lower_expr_llvm_asm(asm), ExprKind::Struct(ref se) => { let rest = match &se.rest { StructRest::Base(e) => Some(self.lower_expr(e)), StructRest::Rest(sp) => { self.sess .struct_span_err(*sp, "base expression required after `..`") .span_label(*sp, "add a base expression here") .emit(); Some(&*self.arena.alloc(self.expr_err(*sp))) } StructRest::None => None, }; hir::ExprKind::Struct( self.arena.alloc(self.lower_qpath( e.id, &se.qself, &se.path, ParamMode::Optional, ImplTraitContext::disallowed(), )), self.arena .alloc_from_iter(se.fields.iter().map(|x| self.lower_expr_field(x))), rest, ) } ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()), ExprKind::Err => hir::ExprKind::Err, ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr), ExprKind::Paren(ref ex) => { let mut ex = self.lower_expr_mut(ex); // Include parens in span, but only if it is a super-span. if e.span.contains(ex.span) { ex.span = e.span; } // Merge attributes into the inner expression. if !e.attrs.is_empty() { let old_attrs = self.attrs.get(&ex.hir_id).map(|la| *la).unwrap_or(&[]); self.attrs.insert( ex.hir_id, &*self.arena.alloc_from_iter( e.attrs .iter() .map(|a| self.lower_attr(a)) .chain(old_attrs.iter().cloned()), ), ); } return ex; } // Desugar `ExprForLoop` // from: `[opt_ident]: for <pat> in <head> <body>` ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => { return self.lower_expr_for(e, pat, head, body, opt_label); } ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span), }; let hir_id = self.lower_node_id(e.id); self.lower_attrs(hir_id, &e.attrs); hir::Expr { hir_id, kind, span: e.span } }) } fn lower_unop(&mut self, u: UnOp) -> hir::UnOp { match u { UnOp::Deref => hir::UnOp::Deref, UnOp::Not => hir::UnOp::Not, UnOp::Neg => hir::UnOp::Neg, } } fn lower_binop(&mut self, b: BinOp) -> hir::BinOp { Spanned { node: match b.node { BinOpKind::Add => hir::BinOpKind::Add, BinOpKind::Sub => hir::BinOpKind::Sub, BinOpKind::Mul => hir::BinOpKind::Mul, BinOpKind::Div => hir::BinOpKind::Div, BinOpKind::Rem => hir::BinOpKind::Rem, BinOpKind::And => hir::BinOpKind::And, BinOpKind::Or => hir::BinOpKind::Or, BinOpKind::BitXor => hir::BinOpKind::BitXor, BinOpKind::BitAnd => hir::BinOpKind::BitAnd, BinOpKind::BitOr => hir::BinOpKind::BitOr, BinOpKind::Shl => hir::BinOpKind::Shl, BinOpKind::Shr => hir::BinOpKind::Shr, BinOpKind::Eq => hir::BinOpKind::Eq, BinOpKind::Lt => hir::BinOpKind::Lt, BinOpKind::Le => hir::BinOpKind::Le, BinOpKind::Ne => hir::BinOpKind::Ne, BinOpKind::Ge => hir::BinOpKind::Ge, BinOpKind::Gt => hir::BinOpKind::Gt, }, span: b.span, } } fn lower_legacy_const_generics( &mut self, mut f: Expr, args: Vec<AstP<Expr>>, legacy_args_idx: &[usize], ) -> hir::ExprKind<'hir> { let path = match f.kind { ExprKind::Path(None, ref mut path) => path, _ => unreachable!(), }; // Split the arguments into const generics and normal arguments let mut real_args = vec![]; let mut generic_args = vec![]; for (idx, arg) in args.into_iter().enumerate() { if legacy_args_idx.contains(&idx) { let parent_def_id = self.current_hir_id_owner.0; let node_id = self.resolver.next_node_id(); // Add a definition for the in-band const def. self.resolver.create_def( parent_def_id, node_id, DefPathData::AnonConst, ExpnId::root(), arg.span, ); let anon_const = AnonConst { id: node_id, value: arg }; generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const))); } else { real_args.push(arg); } } // Add generic args to the last element of the path. let last_segment = path.segments.last_mut().unwrap(); assert!(last_segment.args.is_none()); last_segment.args = Some(AstP(GenericArgs::AngleBracketed(AngleBracketedArgs { span: DUMMY_SP, args: generic_args, }))); // Now lower everything as normal. let f = self.lower_expr(&f); hir::ExprKind::Call(f, self.lower_exprs(&real_args)) } fn if_let_expr_with_parens(&mut self, cond: &Expr, paren: &Expr) { let start = cond.span.until(paren.span); let end = paren.span.shrink_to_hi().until(cond.span.shrink_to_hi()); self.sess .struct_span_err( vec![start, end], "invalid parentheses around `let` expression in `if let`", ) .multipart_suggestion( "`if let` needs to be written without parentheses", vec![(start, String::new()), (end, String::new())], rustc_errors::Applicability::MachineApplicable, ) .emit(); // Ideally, we'd remove the feature gating of a `let` expression since we are already // complaining about it here, but `feature_gate::check_crate` has already run by now: // self.sess.parse_sess.gated_spans.ungate_last(sym::let_chains, paren.span); } /// Emit an error and lower `ast::ExprKind::Let(pat, scrutinee)` into: /// ```rust /// match scrutinee { pats => true, _ => false } /// ``` fn lower_expr_let(&mut self, span: Span, pat: &Pat, scrutinee: &Expr) -> hir::ExprKind<'hir> { // If we got here, the `let` expression is not allowed. if self.sess.opts.unstable_features.is_nightly_build() { self.sess .struct_span_err(span, "`let` expressions are not supported here") .note( "only supported directly without parentheses in conditions of `if`- and \ `while`-expressions, as well as in `let` chains within parentheses", ) .emit(); } else { self.sess .struct_span_err(span, "expected expression, found statement (`let`)") .note("variable declaration using `let` is a statement") .emit(); } // For better recovery, we emit: // ``` // match scrutinee { pat => true, _ => false } // ``` // While this doesn't fully match the user's intent, it has key advantages: // 1. We can avoid using `abort_if_errors`. // 2. We can typeck both `pat` and `scrutinee`. // 3. `pat` is allowed to be refutable. // 4. The return type of the block is `bool` which seems like what the user wanted. let scrutinee = self.lower_expr(scrutinee); let then_arm = { let pat = self.lower_pat(pat); let expr = self.expr_bool(span, true); self.arm(pat, expr) }; let else_arm = { let pat = self.pat_wild(span); let expr = self.expr_bool(span, false); self.arm(pat, expr) }; hir::ExprKind::Match( scrutinee, arena_vec![self; then_arm, else_arm], hir::MatchSource::Normal, ) } fn lower_expr_if( &mut self, cond: &Expr, then: &Block, else_opt: Option<&Expr>, ) -> hir::ExprKind<'hir> { macro_rules! make_if { ($opt:expr) => {{ let cond = self.lower_expr(cond); let then_expr = self.lower_block_expr(then); hir::ExprKind::If(cond, self.arena.alloc(then_expr), $opt) }}; } if let Some(rslt) = else_opt { make_if!(Some(self.lower_expr(rslt))) } else { make_if!(None) } } fn lower_expr_if_let( &mut self, span: Span, pat: &Pat, scrutinee: &Expr, then: &Block, else_opt: Option<&Expr>, ) -> hir::ExprKind<'hir> { // FIXME(#53667): handle lowering of && and parens. // `_ => else_block` where `else_block` is `{}` if there's `None`: let else_pat = self.pat_wild(span); let (else_expr, contains_else_clause) = match else_opt { None => (self.expr_block_empty(span.shrink_to_hi()), false), Some(els) => (self.lower_expr(els), true), }; let else_arm = self.arm(else_pat, else_expr); // Handle then + scrutinee: let scrutinee = self.lower_expr(scrutinee); let then_pat = self.lower_pat(pat); let then_expr = self.lower_block_expr(then); let then_arm = self.arm(then_pat, self.arena.alloc(then_expr)); let desugar = hir::MatchSource::IfLetDesugar { contains_else_clause }; hir::ExprKind::Match(scrutinee, arena_vec![self; then_arm, else_arm], desugar) } fn lower_expr_while_in_loop_scope( &mut self, span: Span, cond: &Expr, body: &Block, opt_label: Option<Label>, ) -> hir::ExprKind<'hir> { // FIXME(#53667): handle lowering of && and parens. // Note that the block AND the condition are evaluated in the loop scope. // This is done to allow `break` from inside the condition of the loop. // `_ => break`: let else_arm = { let else_pat = self.pat_wild(span); let else_expr = self.expr_break(span, ThinVec::new()); self.arm(else_pat, else_expr) }; // Handle then + scrutinee: let (then_pat, scrutinee, desugar, source) = match cond.kind { ExprKind::Let(ref pat, ref scrutinee) => { // to: // // [opt_ident]: loop { // match <sub_expr> { // <pat> => <body>, // _ => break // } // } let scrutinee = self.with_loop_condition_scope(|t| t.lower_expr(scrutinee)); let pat = self.lower_pat(pat); (pat, scrutinee, hir::MatchSource::WhileLetDesugar, hir::LoopSource::WhileLet) } _ => { // We desugar: `'label: while $cond $body` into: // // ``` // 'label: loop { // match drop-temps { $cond } { // true => $body, // _ => break, // } // } // ``` // Lower condition: let cond = self.with_loop_condition_scope(|this| this.lower_expr(cond)); let span_block = self.mark_span_with_reason(DesugaringKind::CondTemporary, cond.span, None); // Wrap in a construct equivalent to `{ let _t = $cond; _t }` // to preserve drop semantics since `while cond { ... }` does not // let temporaries live outside of `cond`. let cond = self.expr_drop_temps(span_block, cond, ThinVec::new()); // `true => <then>`: let pat = self.pat_bool(span, true); (pat, cond, hir::MatchSource::WhileDesugar, hir::LoopSource::While) } }; let then_expr = self.lower_block_expr(body); let then_arm = self.arm(then_pat, self.arena.alloc(then_expr)); // `match <scrutinee> { ... }` let match_expr = self.expr_match(span, scrutinee, arena_vec![self; then_arm, else_arm], desugar); // `[opt_ident]: loop { ... }` hir::ExprKind::Loop( self.block_expr(self.arena.alloc(match_expr)), opt_label, source, span.with_hi(cond.span.hi()), ) } /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_output(<expr>) }`, /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_output(()) }` /// and save the block id to use it as a break target for desugaring of the `?` operator. fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> { self.with_catch_scope(body.id, |this| { let mut block = this.lower_block_noalloc(body, true); // Final expression of the block (if present) or `()` with span at the end of block let (try_span, tail_expr) = if let Some(expr) = block.expr.take() { ( this.mark_span_with_reason( DesugaringKind::TryBlock, expr.span, this.allow_try_trait.clone(), ), expr, ) } else { let try_span = this.mark_span_with_reason( DesugaringKind::TryBlock, this.sess.source_map().end_point(body.span), this.allow_try_trait.clone(), ); (try_span, this.expr_unit(try_span)) }; let ok_wrapped_span = this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None); // `::std::ops::Try::from_output($tail_expr)` block.expr = Some(this.wrap_in_try_constructor( hir::LangItem::TryTraitFromOutput, try_span, tail_expr, ok_wrapped_span, )); hir::ExprKind::Block(this.arena.alloc(block), None) }) } fn wrap_in_try_constructor( &mut self, lang_item: hir::LangItem, method_span: Span, expr: &'hir hir::Expr<'hir>, overall_span: Span, ) -> &'hir hir::Expr<'hir> { let constructor = self.arena.alloc(self.expr_lang_item_path(method_span, lang_item, ThinVec::new())); self.expr_call(overall_span, constructor, std::slice::from_ref(expr)) } fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> { let pat = self.lower_pat(&arm.pat); let guard = arm.guard.as_ref().map(|cond| { if let ExprKind::Let(ref pat, ref scrutinee) = cond.kind { hir::Guard::IfLet(self.lower_pat(pat), self.lower_expr(scrutinee)) } else { hir::Guard::If(self.lower_expr(cond)) } }); let hir_id = self.next_id(); self.lower_attrs(hir_id, &arm.attrs); hir::Arm { hir_id, pat, guard, body: self.lower_expr(&arm.body), span: arm.span } } /// Lower an `async` construct to a generator that is then wrapped so it implements `Future`. /// /// This results in: /// /// ```text /// std::future::from_generator(static move? |_task_context| -> <ret_ty> { /// <body> /// }) /// ``` pub(super) fn make_async_expr( &mut self, capture_clause: CaptureBy, closure_node_id: NodeId, ret_ty: Option<AstP<Ty>>, span: Span, async_gen_kind: hir::AsyncGeneratorKind, body: impl FnOnce(&mut Self) -> hir::Expr<'hir>, ) -> hir::ExprKind<'hir> { let output = match ret_ty { Some(ty) => hir::FnRetTy::Return(self.lower_ty(&ty, ImplTraitContext::disallowed())), None => hir::FnRetTy::DefaultReturn(span), }; // Resume argument type. We let the compiler infer this to simplify the lowering. It is // fully constrained by `future::from_generator`. let input_ty = hir::Ty { hir_id: self.next_id(), kind: hir::TyKind::Infer, span }; // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`. let decl = self.arena.alloc(hir::FnDecl { inputs: arena_vec![self; input_ty], output, c_variadic: false, implicit_self: hir::ImplicitSelfKind::None, }); // Lower the argument pattern/ident. The ident is used again in the `.await` lowering. let (pat, task_context_hid) = self.pat_ident_binding_mode( span, Ident::with_dummy_span(sym::_task_context), hir::BindingAnnotation::Mutable, ); let param = hir::Param { hir_id: self.next_id(), pat, ty_span: span, span }; let params = arena_vec![self; param]; let body_id = self.lower_body(move |this| { this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind)); let old_ctx = this.task_context; this.task_context = Some(task_context_hid); let res = body(this); this.task_context = old_ctx; (params, res) }); // `static |_task_context| -> <ret_ty> { body }`: let generator_kind = hir::ExprKind::Closure( capture_clause, decl, body_id, span, Some(hir::Movability::Static), ); let generator = hir::Expr { hir_id: self.lower_node_id(closure_node_id), kind: generator_kind, span }; // `future::from_generator`: let unstable_span = self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone()); let gen_future = self.expr_lang_item_path(unstable_span, hir::LangItem::FromGenerator, ThinVec::new()); // `future::from_generator(generator)`: hir::ExprKind::Call(self.arena.alloc(gen_future), arena_vec![self; generator]) } /// Desugar `<expr>.await` into: /// ```rust /// match <expr> { /// mut pinned => loop { /// match unsafe { ::std::future::Future::poll( /// <::std::pin::Pin>::new_unchecked(&mut pinned), /// ::std::future::get_context(task_context), /// ) } { /// ::std::task::Poll::Ready(result) => break result, /// ::std::task::Poll::Pending => {} /// } /// task_context = yield (); /// } /// } /// ``` fn lower_expr_await(&mut self, await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> { match self.generator_kind { Some(hir::GeneratorKind::Async(_)) => {} Some(hir::GeneratorKind::Gen) | None => { let mut err = struct_span_err!( self.sess, await_span, E0728, "`await` is only allowed inside `async` functions and blocks" ); err.span_label(await_span, "only allowed inside `async` functions and blocks"); if let Some(item_sp) = self.current_item { err.span_label(item_sp, "this is not `async`"); } err.emit(); } } let span = self.mark_span_with_reason(DesugaringKind::Await, await_span, None); let gen_future_span = self.mark_span_with_reason( DesugaringKind::Await, await_span, self.allow_gen_future.clone(), ); let expr = self.lower_expr(expr); let pinned_ident = Ident::with_dummy_span(sym::pinned); let (pinned_pat, pinned_pat_hid) = self.pat_ident_binding_mode(span, pinned_ident, hir::BindingAnnotation::Mutable); let task_context_ident = Ident::with_dummy_span(sym::_task_context); // unsafe { // ::std::future::Future::poll( // ::std::pin::Pin::new_unchecked(&mut pinned), // ::std::future::get_context(task_context), // ) // } let poll_expr = { let pinned = self.expr_ident(span, pinned_ident, pinned_pat_hid); let ref_mut_pinned = self.expr_mut_addr_of(span, pinned); let task_context = if let Some(task_context_hid) = self.task_context { self.expr_ident_mut(span, task_context_ident, task_context_hid) } else { // Use of `await` outside of an async context, we cannot use `task_context` here. self.expr_err(span) }; let new_unchecked = self.expr_call_lang_item_fn_mut( span, hir::LangItem::PinNewUnchecked, arena_vec![self; ref_mut_pinned], ); let get_context = self.expr_call_lang_item_fn_mut( gen_future_span, hir::LangItem::GetContext, arena_vec![self; task_context], ); let call = self.expr_call_lang_item_fn( span, hir::LangItem::FuturePoll, arena_vec![self; new_unchecked, get_context], ); self.arena.alloc(self.expr_unsafe(call)) }; // `::std::task::Poll::Ready(result) => break result` let loop_node_id = self.resolver.next_node_id(); let loop_hir_id = self.lower_node_id(loop_node_id); let ready_arm = { let x_ident = Ident::with_dummy_span(sym::result); let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident); let x_expr = self.expr_ident(span, x_ident, x_pat_hid); let ready_field = self.single_pat_field(span, x_pat); let ready_pat = self.pat_lang_item_variant(span, hir::LangItem::PollReady, ready_field); let break_x = self.with_loop_scope(loop_node_id, move |this| { let expr_break = hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr)); this.arena.alloc(this.expr(await_span, expr_break, ThinVec::new())) }); self.arm(ready_pat, break_x) }; // `::std::task::Poll::Pending => {}` let pending_arm = { let pending_pat = self.pat_lang_item_variant(span, hir::LangItem::PollPending, &[]); let empty_block = self.expr_block_empty(span); self.arm(pending_pat, empty_block) }; let inner_match_stmt = { let match_expr = self.expr_match( span, poll_expr, arena_vec![self; ready_arm, pending_arm], hir::MatchSource::AwaitDesugar, ); self.stmt_expr(span, match_expr) }; // task_context = yield (); let yield_stmt = { let unit = self.expr_unit(span); let yield_expr = self.expr( span, hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr.hir_id) }), ThinVec::new(), ); let yield_expr = self.arena.alloc(yield_expr); if let Some(task_context_hid) = self.task_context { let lhs = self.expr_ident(span, task_context_ident, task_context_hid); let assign = self.expr(span, hir::ExprKind::Assign(lhs, yield_expr, span), AttrVec::new()); self.stmt_expr(span, assign) } else { // Use of `await` outside of an async context. Return `yield_expr` so that we can // proceed with type checking. self.stmt(span, hir::StmtKind::Semi(yield_expr)) } }; let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None); // loop { .. } let loop_expr = self.arena.alloc(hir::Expr { hir_id: loop_hir_id, kind: hir::ExprKind::Loop(loop_block, None, hir::LoopSource::Loop, span), span, }); // mut pinned => loop { ... } let pinned_arm = self.arm(pinned_pat, loop_expr); // match <expr> { // mut pinned => loop { .. } // } hir::ExprKind::Match(expr, arena_vec![self; pinned_arm], hir::MatchSource::AwaitDesugar) } fn lower_expr_closure( &mut self, capture_clause: CaptureBy, movability: Movability, decl: &FnDecl, body: &Expr, fn_decl_span: Span, ) -> hir::ExprKind<'hir> { let (body_id, generator_option) = self.with_new_scopes(move |this| { let prev = this.current_item; this.current_item = Some(fn_decl_span); let mut generator_kind = None; let body_id = this.lower_fn_body(decl, |this| { let e = this.lower_expr_mut(body); generator_kind = this.generator_kind; e }); let generator_option = this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability); this.current_item = prev; (body_id, generator_option) }); // Lower outside new scope to preserve `is_in_loop_condition`. let fn_decl = self.lower_fn_decl(decl, None, false, None); hir::ExprKind::Closure(capture_clause, fn_decl, body_id, fn_decl_span, generator_option) } fn generator_movability_for_fn( &mut self, decl: &FnDecl, fn_decl_span: Span, generator_kind: Option<hir::GeneratorKind>, movability: Movability, ) -> Option<hir::Movability> { match generator_kind { Some(hir::GeneratorKind::Gen) => { if decl.inputs.len() > 1 { struct_span_err!( self.sess, fn_decl_span, E0628, "too many parameters for a generator (expected 0 or 1 parameters)" ) .emit(); } Some(movability) } Some(hir::GeneratorKind::Async(_)) => { panic!("non-`async` closure body turned `async` during lowering"); } None => { if movability == Movability::Static { struct_span_err!(self.sess, fn_decl_span, E0697, "closures cannot be static") .emit(); } None } } } fn lower_expr_async_closure( &mut self, capture_clause: CaptureBy, closure_id: NodeId, decl: &FnDecl, body: &Expr, fn_decl_span: Span, ) -> hir::ExprKind<'hir> { let outer_decl = FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) }; let body_id = self.with_new_scopes(|this| { // FIXME(cramertj): allow `async` non-`move` closures with arguments. if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() { struct_span_err!( this.sess, fn_decl_span, E0708, "`async` non-`move` closures with parameters are not currently supported", ) .help( "consider using `let` statements to manually capture \ variables by reference before entering an `async move` closure", ) .emit(); } // Transform `async |x: u8| -> X { ... }` into // `|x: u8| future_from_generator(|| -> X { ... })`. let body_id = this.lower_fn_body(&outer_decl, |this| { let async_ret_ty = if let FnRetTy::Ty(ty) = &decl.output { Some(ty.clone()) } else { None }; let async_body = this.make_async_expr( capture_clause, closure_id, async_ret_ty, body.span, hir::AsyncGeneratorKind::Closure, |this| this.with_new_scopes(|this| this.lower_expr_mut(body)), ); this.expr(fn_decl_span, async_body, ThinVec::new()) }); body_id }); // We need to lower the declaration outside the new scope, because we // have to conserve the state of being inside a loop condition for the // closure argument types. let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None); hir::ExprKind::Closure(capture_clause, fn_decl, body_id, fn_decl_span, None) } /// Destructure the LHS of complex assignments. /// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`. fn lower_expr_assign( &mut self, lhs: &Expr, rhs: &Expr, eq_sign_span: Span, whole_span: Span, ) -> hir::ExprKind<'hir> { // Return early in case of an ordinary assignment. fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool { match &lhs.kind { ExprKind::Array(..) | ExprKind::Struct(..) | ExprKind::Tup(..) | ExprKind::Underscore => false, // Check for tuple struct constructor. ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(), ExprKind::Paren(e) => { match e.kind { // We special-case `(..)` for consistency with patterns. ExprKind::Range(None, None, RangeLimits::HalfOpen) => false, _ => is_ordinary(lower_ctx, e), } } _ => true, } } if is_ordinary(self, lhs) { return hir::ExprKind::Assign(self.lower_expr(lhs), self.lower_expr(rhs), eq_sign_span); } if !self.sess.features_untracked().destructuring_assignment { feature_err( &self.sess.parse_sess, sym::destructuring_assignment, eq_sign_span, "destructuring assignments are unstable", ) .span_label(lhs.span, "cannot assign to this expression") .emit(); } let mut assignments = vec![]; // The LHS becomes a pattern: `(lhs1, lhs2)`. let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments); let rhs = self.lower_expr(rhs); // Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`. let destructure_let = self.stmt_let_pat( None, whole_span, Some(rhs), pat, hir::LocalSource::AssignDesugar(eq_sign_span), ); // `a = lhs1; b = lhs2;`. let stmts = self .arena .alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter())); // Wrap everything in a block. hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None) } /// If the given expression is a path to a tuple struct, returns that path. /// It is not a complete check, but just tries to reject most paths early /// if they are not tuple structs. /// Type checking will take care of the full validation later. fn extract_tuple_struct_path<'a>( &mut self, expr: &'a Expr, ) -> Option<(&'a Option<QSelf>, &'a Path)> { if let ExprKind::Path(qself, path) = &expr.kind { // Does the path resolve to something disallowed in a tuple struct/variant pattern? if let Some(partial_res) = self.resolver.get_partial_res(expr.id) { if partial_res.unresolved_segments() == 0 && !partial_res.base_res().expected_in_tuple_struct_pat() { return None; } } return Some((qself, path)); } None } /// Convert the LHS of a destructuring assignment to a pattern. /// Each sub-assignment is recorded in `assignments`. fn destructure_assign( &mut self, lhs: &Expr, eq_sign_span: Span, assignments: &mut Vec<hir::Stmt<'hir>>, ) -> &'hir hir::Pat<'hir> { match &lhs.kind { // Underscore pattern. ExprKind::Underscore => { return self.pat_without_dbm(lhs.span, hir::PatKind::Wild); } // Slice patterns. ExprKind::Array(elements) => { let (pats, rest) = self.destructure_sequence(elements, "slice", eq_sign_span, assignments); let slice_pat = if let Some((i, span)) = rest { let (before, after) = pats.split_at(i); hir::PatKind::Slice( before, Some(self.pat_without_dbm(span, hir::PatKind::Wild)), after, ) } else { hir::PatKind::Slice(pats, None, &[]) }; return self.pat_without_dbm(lhs.span, slice_pat); } // Tuple structs. ExprKind::Call(callee, args) => { if let Some((qself, path)) = self.extract_tuple_struct_path(callee) { let (pats, rest) = self.destructure_sequence( args, "tuple struct or variant", eq_sign_span, assignments, ); let qpath = self.lower_qpath( callee.id, qself, path, ParamMode::Optional, ImplTraitContext::disallowed(), ); // Destructure like a tuple struct. let tuple_struct_pat = hir::PatKind::TupleStruct(qpath, pats, rest.map(|r| r.0)); return self.pat_without_dbm(lhs.span, tuple_struct_pat); } } // Structs. ExprKind::Struct(se) => { let field_pats = self.arena.alloc_from_iter(se.fields.iter().map(|f| { let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments); hir::PatField { hir_id: self.next_id(), ident: f.ident, pat, is_shorthand: f.is_shorthand, span: f.span, } })); let qpath = self.lower_qpath( lhs.id, &se.qself, &se.path, ParamMode::Optional, ImplTraitContext::disallowed(), ); let fields_omitted = match &se.rest { StructRest::Base(e) => { self.sess .struct_span_err( e.span, "functional record updates are not allowed in destructuring \ assignments", ) .span_suggestion( e.span, "consider removing the trailing pattern", String::new(), rustc_errors::Applicability::MachineApplicable, ) .emit(); true } StructRest::Rest(_) => true, StructRest::None => false, }; let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted); return self.pat_without_dbm(lhs.span, struct_pat); } // Tuples. ExprKind::Tup(elements) => { let (pats, rest) = self.destructure_sequence(elements, "tuple", eq_sign_span, assignments); let tuple_pat = hir::PatKind::Tuple(pats, rest.map(|r| r.0)); return self.pat_without_dbm(lhs.span, tuple_pat); } ExprKind::Paren(e) => { // We special-case `(..)` for consistency with patterns. if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind { let tuple_pat = hir::PatKind::Tuple(&[], Some(0)); return self.pat_without_dbm(lhs.span, tuple_pat); } else { return self.destructure_assign(e, eq_sign_span, assignments); } } _ => {} } // Treat all other cases as normal lvalue. let ident = Ident::new(sym::lhs, lhs.span); let (pat, binding) = self.pat_ident(lhs.span, ident); let ident = self.expr_ident(lhs.span, ident, binding); let assign = hir::ExprKind::Assign(self.lower_expr(lhs), ident, eq_sign_span); let expr = self.expr(lhs.span, assign, ThinVec::new()); assignments.push(self.stmt_expr(lhs.span, expr)); pat } /// Destructure a sequence of expressions occurring on the LHS of an assignment. /// Such a sequence occurs in a tuple (struct)/slice. /// Return a sequence of corresponding patterns, and the index and the span of `..` if it /// exists. /// Each sub-assignment is recorded in `assignments`. fn destructure_sequence( &mut self, elements: &[AstP<Expr>], ctx: &str, eq_sign_span: Span, assignments: &mut Vec<hir::Stmt<'hir>>, ) -> (&'hir [&'hir hir::Pat<'hir>], Option<(usize, Span)>) { let mut rest = None; let elements = self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| { // Check for `..` pattern. if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind { if let Some((_, prev_span)) = rest { self.ban_extra_rest_pat(e.span, prev_span, ctx); } else { rest = Some((i, e.span)); } None } else { Some(self.destructure_assign(e, eq_sign_span, assignments)) } })); (elements, rest) } /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`. fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> { let e1 = self.lower_expr_mut(e1); let e2 = self.lower_expr_mut(e2); let fn_path = hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, span); let fn_expr = self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new())); hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2]) } fn lower_expr_range( &mut self, span: Span, e1: Option<&Expr>, e2: Option<&Expr>, lims: RangeLimits, ) -> hir::ExprKind<'hir> { use rustc_ast::RangeLimits::*; let lang_item = match (e1, e2, lims) { (None, None, HalfOpen) => hir::LangItem::RangeFull, (Some(..), None, HalfOpen) => hir::LangItem::RangeFrom, (None, Some(..), HalfOpen) => hir::LangItem::RangeTo, (Some(..), Some(..), HalfOpen) => hir::LangItem::Range, (None, Some(..), Closed) => hir::LangItem::RangeToInclusive, (Some(..), Some(..), Closed) => unreachable!(), (_, None, Closed) => self.diagnostic().span_fatal(span, "inclusive range with no end"), }; let fields = self.arena.alloc_from_iter( e1.iter().map(|e| ("start", e)).chain(e2.iter().map(|e| ("end", e))).map(|(s, e)| { let expr = self.lower_expr(&e); let ident = Ident::new(Symbol::intern(s), e.span); self.expr_field(ident, expr, e.span) }), ); hir::ExprKind::Struct(self.arena.alloc(hir::QPath::LangItem(lang_item, span)), fields, None) } fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination { let target_id = match destination { Some((id, _)) => { if let Some(loop_id) = self.resolver.get_label_res(id) { Ok(self.lower_node_id(loop_id)) } else { Err(hir::LoopIdError::UnresolvedLabel) } } None => self .loop_scopes .last() .cloned() .map(|id| Ok(self.lower_node_id(id))) .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)), }; hir::Destination { label: destination.map(|(_, label)| label), target_id } } fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination { if self.is_in_loop_condition && opt_label.is_none() { hir::Destination { label: None, target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition), } } else { self.lower_loop_destination(opt_label.map(|label| (id, label))) } } fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T { let len = self.catch_scopes.len(); self.catch_scopes.push(catch_id); let result = f(self); assert_eq!( len + 1, self.catch_scopes.len(), "catch scopes should be added and removed in stack order" ); self.catch_scopes.pop().unwrap(); result } fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T { // We're no longer in the base loop's condition; we're in another loop. let was_in_loop_condition = self.is_in_loop_condition; self.is_in_loop_condition = false; let len = self.loop_scopes.len(); self.loop_scopes.push(loop_id); let result = f(self); assert_eq!( len + 1, self.loop_scopes.len(), "loop scopes should be added and removed in stack order" ); self.loop_scopes.pop().unwrap(); self.is_in_loop_condition = was_in_loop_condition; result } fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T { let was_in_loop_condition = self.is_in_loop_condition; self.is_in_loop_condition = true; let result = f(self); self.is_in_loop_condition = was_in_loop_condition; result } fn lower_expr_llvm_asm(&mut self, asm: &LlvmInlineAsm) -> hir::ExprKind<'hir> { let inner = hir::LlvmInlineAsmInner { inputs: asm.inputs.iter().map(|&(c, _)| c).collect(), outputs: asm .outputs .iter() .map(|out| hir::LlvmInlineAsmOutput { constraint: out.constraint, is_rw: out.is_rw, is_indirect: out.is_indirect, span: out.expr.span, }) .collect(), asm: asm.asm, asm_str_style: asm.asm_str_style, clobbers: asm.clobbers.clone(), volatile: asm.volatile, alignstack: asm.alignstack, dialect: asm.dialect, }; let hir_asm = hir::LlvmInlineAsm { inner, inputs_exprs: self.arena.alloc_from_iter( asm.inputs.iter().map(|&(_, ref input)| self.lower_expr_mut(input)), ), outputs_exprs: self .arena .alloc_from_iter(asm.outputs.iter().map(|out| self.lower_expr_mut(&out.expr))), }; hir::ExprKind::LlvmInlineAsm(self.arena.alloc(hir_asm)) } fn lower_expr_field(&mut self, f: &ExprField) -> hir::ExprField<'hir> { hir::ExprField { hir_id: self.next_id(), ident: f.ident, expr: self.lower_expr(&f.expr), span: f.span, is_shorthand: f.is_shorthand, } } fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> { match self.generator_kind { Some(hir::GeneratorKind::Gen) => {} Some(hir::GeneratorKind::Async(_)) => { struct_span_err!( self.sess, span, E0727, "`async` generators are not yet supported" ) .emit(); } None => self.generator_kind = Some(hir::GeneratorKind::Gen), } let expr = opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span)); hir::ExprKind::Yield(expr, hir::YieldSource::Yield) } /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into: /// ```rust /// { /// let result = match ::std::iter::IntoIterator::into_iter(<head>) { /// mut iter => { /// [opt_ident]: loop { /// let mut __next; /// match ::std::iter::Iterator::next(&mut iter) { /// ::std::option::Option::Some(val) => __next = val, /// ::std::option::Option::None => break /// }; /// let <pat> = __next; /// StmtKind::Expr(<body>); /// } /// } /// }; /// result /// } /// ``` fn lower_expr_for( &mut self, e: &Expr, pat: &Pat, head: &Expr, body: &Block, opt_label: Option<Label>, ) -> hir::Expr<'hir> { let orig_head_span = head.span; // expand <head> let mut head = self.lower_expr_mut(head); let desugared_span = self.mark_span_with_reason( DesugaringKind::ForLoop(ForLoopLoc::Head), orig_head_span, None, ); head.span = desugared_span; let iter = Ident::with_dummy_span(sym::iter); let next_ident = Ident::with_dummy_span(sym::__next); let (next_pat, next_pat_hid) = self.pat_ident_binding_mode( desugared_span, next_ident, hir::BindingAnnotation::Mutable, ); // `::std::option::Option::Some(val) => __next = val` let pat_arm = { let val_ident = Ident::with_dummy_span(sym::val); let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident); let val_expr = self.expr_ident(pat.span, val_ident, val_pat_hid); let next_expr = self.expr_ident(pat.span, next_ident, next_pat_hid); let assign = self.arena.alloc(self.expr( pat.span, hir::ExprKind::Assign(next_expr, val_expr, pat.span), ThinVec::new(), )); let some_pat = self.pat_some(pat.span, val_pat); self.arm(some_pat, assign) }; // `::std::option::Option::None => break` let break_arm = { let break_expr = self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new())); let pat = self.pat_none(e.span); self.arm(pat, break_expr) }; // `mut iter` let (iter_pat, iter_pat_nid) = self.pat_ident_binding_mode(desugared_span, iter, hir::BindingAnnotation::Mutable); // `match ::std::iter::Iterator::next(&mut iter) { ... }` let match_expr = { let iter = self.expr_ident(desugared_span, iter, iter_pat_nid); let ref_mut_iter = self.expr_mut_addr_of(desugared_span, iter); let next_expr = self.expr_call_lang_item_fn( desugared_span, hir::LangItem::IteratorNext, arena_vec![self; ref_mut_iter], ); let arms = arena_vec![self; pat_arm, break_arm]; self.expr_match(desugared_span, next_expr, arms, hir::MatchSource::ForLoopDesugar) }; let match_stmt = self.stmt_expr(desugared_span, match_expr); let next_expr = self.expr_ident(desugared_span, next_ident, next_pat_hid); // `let mut __next` let next_let = self.stmt_let_pat( None, desugared_span, None, next_pat, hir::LocalSource::ForLoopDesugar, ); // `let <pat> = __next` let pat = self.lower_pat(pat); let pat_let = self.stmt_let_pat( None, desugared_span, Some(next_expr), pat, hir::LocalSource::ForLoopDesugar, ); let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false)); let body_expr = self.expr_block(body_block, ThinVec::new()); let body_stmt = self.stmt_expr(body.span, body_expr); let loop_block = self.block_all( e.span, arena_vec![self; next_let, match_stmt, pat_let, body_stmt], None, ); // `[opt_ident]: loop { ... }` let kind = hir::ExprKind::Loop( loop_block, opt_label, hir::LoopSource::ForLoop, e.span.with_hi(orig_head_span.hi()), ); let loop_expr = self.arena.alloc(hir::Expr { hir_id: self.lower_node_id(e.id), kind, span: e.span }); // `mut iter => { ... }` let iter_arm = self.arm(iter_pat, loop_expr); let into_iter_span = self.mark_span_with_reason( DesugaringKind::ForLoop(ForLoopLoc::IntoIter), orig_head_span, None, ); // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }` let into_iter_expr = { self.expr_call_lang_item_fn( into_iter_span, hir::LangItem::IntoIterIntoIter, arena_vec![self; head], ) }; let match_expr = self.arena.alloc(self.expr_match( desugared_span, into_iter_expr, arena_vec![self; iter_arm], hir::MatchSource::ForLoopDesugar, )); let attrs: Vec<_> = e.attrs.iter().map(|a| self.lower_attr(a)).collect(); // This is effectively `{ let _result = ...; _result }`. // The construct was introduced in #21984 and is necessary to make sure that // temporaries in the `head` expression are dropped and do not leak to the // surrounding scope of the `match` since the `match` is not a terminating scope. // // Also, add the attributes to the outer returned expr node. self.expr_drop_temps_mut(desugared_span, match_expr, attrs.into()) } /// Desugar `ExprKind::Try` from: `<expr>?` into: /// ```rust /// match Try::into_result(<expr>) { /// Ok(val) => #[allow(unreachable_code)] val, /// Err(err) => #[allow(unreachable_code)] /// // If there is an enclosing `try {...}`: /// break 'catch_target Try::from_error(From::from(err)), /// // Otherwise: /// return Try::from_error(From::from(err)), /// } /// ``` fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> { let unstable_span = self.mark_span_with_reason( DesugaringKind::QuestionMark, span, self.allow_try_trait.clone(), ); let try_span = self.sess.source_map().end_point(span); let try_span = self.mark_span_with_reason( DesugaringKind::QuestionMark, try_span, self.allow_try_trait.clone(), ); // `Try::branch(<expr>)` let scrutinee = { // expand <expr> let sub_expr = self.lower_expr_mut(sub_expr); self.expr_call_lang_item_fn( unstable_span, hir::LangItem::TryTraitBranch, arena_vec![self; sub_expr], ) }; // `#[allow(unreachable_code)]` let attr = { // `allow(unreachable_code)` let allow = { let allow_ident = Ident::new(sym::allow, span); let uc_ident = Ident::new(sym::unreachable_code, span); let uc_nested = attr::mk_nested_word_item(uc_ident); attr::mk_list_item(allow_ident, vec![uc_nested]) }; attr::mk_attr_outer(allow) }; let attrs = vec![attr]; // `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,` let continue_arm = { let val_ident = Ident::with_dummy_span(sym::val); let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident); let val_expr = self.arena.alloc(self.expr_ident_with_attrs( span, val_ident, val_pat_nid, ThinVec::from(attrs.clone()), )); let continue_pat = self.pat_cf_continue(unstable_span, val_pat); self.arm(continue_pat, val_expr) }; // `ControlFlow::Break(residual) => // #[allow(unreachable_code)] // return Try::from_residual(residual),` let break_arm = { let residual_ident = Ident::with_dummy_span(sym::residual); let (residual_local, residual_local_nid) = self.pat_ident(try_span, residual_ident); let residual_expr = self.expr_ident_mut(try_span, residual_ident, residual_local_nid); let from_residual_expr = self.wrap_in_try_constructor( hir::LangItem::TryTraitFromResidual, try_span, self.arena.alloc(residual_expr), unstable_span, ); let thin_attrs = ThinVec::from(attrs); let catch_scope = self.catch_scopes.last().copied(); let ret_expr = if let Some(catch_node) = catch_scope { let target_id = Ok(self.lower_node_id(catch_node)); self.arena.alloc(self.expr( try_span, hir::ExprKind::Break( hir::Destination { label: None, target_id }, Some(from_residual_expr), ), thin_attrs, )) } else { self.arena.alloc(self.expr( try_span, hir::ExprKind::Ret(Some(from_residual_expr)), thin_attrs, )) }; let break_pat = self.pat_cf_break(try_span, residual_local); self.arm(break_pat, ret_expr) }; hir::ExprKind::Match( scrutinee, arena_vec![self; break_arm, continue_arm], hir::MatchSource::TryDesugar, ) } // ========================================================================= // Helper methods for building HIR. // ========================================================================= /// Constructs a `true` or `false` literal expression. pub(super) fn expr_bool(&mut self, span: Span, val: bool) -> &'hir hir::Expr<'hir> { let lit = Spanned { span, node: LitKind::Bool(val) }; self.arena.alloc(self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new())) } /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`. /// /// In terms of drop order, it has the same effect as wrapping `expr` in /// `{ let _t = $expr; _t }` but should provide better compile-time performance. /// /// The drop order can be important in e.g. `if expr { .. }`. pub(super) fn expr_drop_temps( &mut self, span: Span, expr: &'hir hir::Expr<'hir>, attrs: AttrVec, ) -> &'hir hir::Expr<'hir> { self.arena.alloc(self.expr_drop_temps_mut(span, expr, attrs)) } pub(super) fn expr_drop_temps_mut( &mut self, span: Span, expr: &'hir hir::Expr<'hir>, attrs: AttrVec, ) -> hir::Expr<'hir> { self.expr(span, hir::ExprKind::DropTemps(expr), attrs) } fn expr_match( &mut self, span: Span, arg: &'hir hir::Expr<'hir>, arms: &'hir [hir::Arm<'hir>], source: hir::MatchSource, ) -> hir::Expr<'hir> { self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new()) } fn expr_break(&mut self, span: Span, attrs: AttrVec) -> &'hir hir::Expr<'hir> { let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None); self.arena.alloc(self.expr(span, expr_break, attrs)) } fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> { self.expr( span, hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e), ThinVec::new(), ) } fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> { self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]), ThinVec::new())) } fn expr_call_mut( &mut self, span: Span, e: &'hir hir::Expr<'hir>, args: &'hir [hir::Expr<'hir>], ) -> hir::Expr<'hir> { self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new()) } fn expr_call( &mut self, span: Span, e: &'hir hir::Expr<'hir>, args: &'hir [hir::Expr<'hir>], ) -> &'hir hir::Expr<'hir> { self.arena.alloc(self.expr_call_mut(span, e, args)) } fn expr_call_lang_item_fn_mut( &mut self, span: Span, lang_item: hir::LangItem, args: &'hir [hir::Expr<'hir>], ) -> hir::Expr<'hir> { let path = self.arena.alloc(self.expr_lang_item_path(span, lang_item, ThinVec::new())); self.expr_call_mut(span, path, args) } fn expr_call_lang_item_fn( &mut self, span: Span, lang_item: hir::LangItem, args: &'hir [hir::Expr<'hir>], ) -> &'hir hir::Expr<'hir> { self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args)) } fn expr_lang_item_path( &mut self, span: Span, lang_item: hir::LangItem, attrs: AttrVec, ) -> hir::Expr<'hir> { self.expr(span, hir::ExprKind::Path(hir::QPath::LangItem(lang_item, span)), attrs) } pub(super) fn expr_ident( &mut self, sp: Span, ident: Ident, binding: hir::HirId, ) -> &'hir hir::Expr<'hir> { self.arena.alloc(self.expr_ident_mut(sp, ident, binding)) } pub(super) fn expr_ident_mut( &mut self, sp: Span, ident: Ident, binding: hir::HirId, ) -> hir::Expr<'hir> { self.expr_ident_with_attrs(sp, ident, binding, ThinVec::new()) } fn expr_ident_with_attrs( &mut self, span: Span, ident: Ident, binding: hir::HirId, attrs: AttrVec, ) -> hir::Expr<'hir> { let expr_path = hir::ExprKind::Path(hir::QPath::Resolved( None, self.arena.alloc(hir::Path { span, res: Res::Local(binding), segments: arena_vec![self; hir::PathSegment::from_ident(ident)], }), )); self.expr(span, expr_path, attrs) } fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> { let hir_id = self.next_id(); let span = expr.span; self.expr( span, hir::ExprKind::Block( self.arena.alloc(hir::Block { stmts: &[], expr: Some(expr), hir_id, rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated), span, targeted_by_break: false, }), None, ), ThinVec::new(), ) } fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> { let blk = self.block_all(span, &[], None); let expr = self.expr_block(blk, ThinVec::new()); self.arena.alloc(expr) } pub(super) fn expr_block( &mut self, b: &'hir hir::Block<'hir>, attrs: AttrVec, ) -> hir::Expr<'hir> { self.expr(b.span, hir::ExprKind::Block(b, None), attrs) } pub(super) fn expr( &mut self, span: Span, kind: hir::ExprKind<'hir>, attrs: AttrVec, ) -> hir::Expr<'hir> { let hir_id = self.next_id(); self.lower_attrs(hir_id, &attrs); hir::Expr { hir_id, kind, span } } fn expr_field( &mut self, ident: Ident, expr: &'hir hir::Expr<'hir>, span: Span, ) -> hir::ExprField<'hir> { hir::ExprField { hir_id: self.next_id(), ident, span, expr, is_shorthand: false } } fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> { hir::Arm { hir_id: self.next_id(), pat, guard: None, span: expr.span, body: expr } } }
39.490102
106
0.501578
01c098b96137b10dd191fd606d9bada30432e555
29,146
// SPDX-License-Identifier: MIT use core::cell::Cell; use core::cmp; #[cfg(not(feature = "no_std"))] use crate::blur; use crate::color::Color; use crate::graphicspath::GraphicsPath; use crate::graphicspath::PointType; use crate::Mode; use crate::FONT; pub trait Renderer { /// Get width fn width(&self) -> u32; /// Get height fn height(&self) -> u32; /// Access the pixel buffer fn data(&self) -> &[Color]; /// Access the pixel buffer mutably fn data_mut(&mut self) -> &mut [Color]; /// Flip the buffer fn sync(&mut self) -> bool; /// Set/get drawing mode fn mode(&self) -> &Cell<Mode>; ///Draw a pixel //faster pixel implementation (multiplexing) fn pixel(&mut self, x: i32, y: i32, color: Color) { let replace = match self.mode().get() { Mode::Blend => false, Mode::Overwrite => true, }; let w = self.width(); let h = self.height(); let data = self.data_mut(); if x >= 0 && y >= 0 && x < w as i32 && y < h as i32 { let new = color.data; let alpha = (new >> 24) & 0xFF; let old = &mut data[y as usize * w as usize + x as usize].data; if alpha >= 255 || replace { *old = new; } else if alpha > 0 { let n_alpha = 255 - alpha; let rb = ((n_alpha * (*old & 0x00FF00FF)) + (alpha * (new & 0x00FF00FF))) >> 8; let ag = (n_alpha * ((*old & 0xFF00FF00) >> 8)) + (alpha * (0x01000000 | ((new & 0x0000FF00) >> 8))); *old = (rb & 0x00FF00FF) | (ag & 0xFF00FF00); } } } /// Draw a piece of an arc. Negative radius will fill in the inside fn arc(&mut self, x0: i32, y0: i32, radius: i32, parts: u8, color: Color) { let mut x = radius.abs(); let mut y = 0; let mut err = 0; // https://github.com/rust-lang/rust-clippy/issues/5354 #[allow(clippy::comparison_chain)] while x >= y { if radius < 0 { if parts & 1 << 0 != 0 { self.rect(x0 - x, y0 + y, x as u32, 1, color); } if parts & 1 << 1 != 0 { self.rect(x0, y0 + y, x as u32 + 1, 1, color); } if parts & 1 << 2 != 0 { self.rect(x0 - y, y0 + x, y as u32, 1, color); } if parts & 1 << 3 != 0 { self.rect(x0, y0 + x, y as u32 + 1, 1, color); } if parts & 1 << 4 != 0 { self.rect(x0 - x, y0 - y, x as u32, 1, color); } if parts & 1 << 5 != 0 { self.rect(x0, y0 - y, x as u32 + 1, 1, color); } if parts & 1 << 6 != 0 { self.rect(x0 - y, y0 - x, y as u32, 1, color); } if parts & 1 << 7 != 0 { self.rect(x0, y0 - x, y as u32 + 1, 1, color); } } else if radius == 0 { self.pixel(x0, y0, color); } else { if parts & 1 << 0 != 0 { self.pixel(x0 - x, y0 + y, color); } if parts & 1 << 1 != 0 { self.pixel(x0 + x, y0 + y, color); } if parts & 1 << 2 != 0 { self.pixel(x0 - y, y0 + x, color); } if parts & 1 << 3 != 0 { self.pixel(x0 + y, y0 + x, color); } if parts & 1 << 4 != 0 { self.pixel(x0 - x, y0 - y, color); } if parts & 1 << 5 != 0 { self.pixel(x0 + x, y0 - y, color); } if parts & 1 << 6 != 0 { self.pixel(x0 - y, y0 - x, color); } if parts & 1 << 7 != 0 { self.pixel(x0 + y, y0 - x, color); } } y += 1; err += 1 + 2 * y; if 2 * (err - x) + 1 > 0 { x -= 1; err += 1 - 2 * x; } } } /// Draw a circle. Negative radius will fill in the inside fn circle(&mut self, x0: i32, y0: i32, radius: i32, color: Color) { let mut x = radius.abs(); let mut y = 0; let mut err = -radius.abs(); match radius { radius if radius > 0 => { err = 0; while x >= y { self.pixel(x0 - x, y0 + y, color); self.pixel(x0 + x, y0 + y, color); self.pixel(x0 - y, y0 + x, color); self.pixel(x0 + y, y0 + x, color); self.pixel(x0 - x, y0 - y, color); self.pixel(x0 + x, y0 - y, color); self.pixel(x0 - y, y0 - x, color); self.pixel(x0 + y, y0 - x, color); y += 1; err += 1 + 2 * y; if 2 * (err - x) + 1 > 0 { x -= 1; err += 1 - 2 * x; } } } radius if radius < 0 => { while x >= y { let lasty = y; err += y; y += 1; err += y; self.line4points(x0, y0, x, lasty, color); if err >= 0 { if x != lasty { self.line4points(x0, y0, lasty, x, color); } err -= x; x -= 1; err -= x; } } } _ => { self.pixel(x0, y0, color); } } } fn line4points(&mut self, x0: i32, y0: i32, x: i32, y: i32, color: Color) { //self.line(x0 - x, y0 + y, (x+x0), y0 + y, color); self.rect(x0 - x, y0 + y, x as u32 * 2 + 1, 1, color); if y != 0 { //self.line(x0 - x, y0 - y, (x+x0), y0-y , color); self.rect(x0 - x, y0 - y, x as u32 * 2 + 1, 1, color); } } /// Draw a line fn line(&mut self, argx1: i32, argy1: i32, argx2: i32, argy2: i32, color: Color) { let mut x = argx1; let mut y = argy1; let dx = if argx1 > argx2 { argx1 - argx2 } else { argx2 - argx1 }; let dy = if argy1 > argy2 { argy1 - argy2 } else { argy2 - argy1 }; let sx = if argx1 < argx2 { 1 } else { -1 }; let sy = if argy1 < argy2 { 1 } else { -1 }; let mut err = if dx > dy { dx } else { -dy } / 2; let mut err_tolerance; loop { self.pixel(x, y, color); if x == argx2 && y == argy2 { break; }; err_tolerance = 2 * err; if err_tolerance > -dx { err -= dy; x += sx; } if err_tolerance < dy { err += dx; y += sy; } } } fn lines(&mut self, points: &[[i32; 2]], color: Color) { if points.is_empty() { // when no points given, do nothing } else if points.len() == 1 { self.pixel(points[0][0], points[0][1], color); } else { for i in 0..points.len() - 1 { self.line( points[i][0], points[i][1], points[i + 1][0], points[i + 1][1], color, ); } } } /// Draw a path (GraphicsPath) fn draw_path_stroke(&mut self, graphicspath: GraphicsPath, color: Color) { let mut x: i32 = 0; let mut y: i32 = 0; for point in graphicspath.points { if let PointType::Connect = point.2 { self.line(x, y, point.0, point.1, color) } x = point.0; y = point.1; } } /// Draw a character, using the loaded font fn char(&mut self, x: i32, y: i32, c: char, color: Color) { let mut offset = (c as usize) * 16; for row in 0..16 { let row_data; if offset < FONT.len() { row_data = FONT[offset]; } else { row_data = 0; } for col in 0..8 { let pixel = (row_data >> (7 - col)) & 1; if pixel > 0 { self.pixel(x + col as i32, y + row as i32, color); } } offset += 1; } } /// Set entire window to a color fn set(&mut self, color: Color) { let data = self.data_mut(); let data_ptr = data.as_mut_ptr(); for i in 0..data.len() as isize { unsafe { *data_ptr.offset(i) = color } } } /// Sets the whole window to black fn clear(&mut self) { self.set(Color::rgb(0, 0, 0)); } fn rect(&mut self, x: i32, y: i32, w: u32, h: u32, color: Color) { let replace = match self.mode().get() { Mode::Blend => false, Mode::Overwrite => true, }; let self_w = self.width(); let self_h = self.height(); let start_y = cmp::max(0, cmp::min(self_h as i32 - 1, y)); let end_y = cmp::max(start_y, cmp::min(self_h as i32, y + h as i32)); let start_x = cmp::max(0, cmp::min(self_w as i32 - 1, x)); let len = cmp::max(start_x, cmp::min(self_w as i32, x + w as i32)) - start_x; let alpha = (color.data >> 24) & 0xFF; //if alpha > 0 { if alpha >= 255 || replace { let data = self.data_mut(); let data_ptr = data.as_mut_ptr(); for y in start_y..end_y { let start = (y * self_w as i32 + start_x) as isize; let end = start + len as isize; for i in start..end { unsafe { *data_ptr.offset(i) = color; } } } } else { for y in start_y..end_y { for x in start_x..start_x + len { self.pixel(x, y, color); } } } //} } #[cfg(not(feature = "no_std"))] fn box_blur(&mut self, x: i32, y: i32, w: u32, h: u32, r: i32) { let self_w = self.width(); let self_h = self.height(); let start_y = cmp::max(0, cmp::min(self_h as i32 - 1, y)); let end_y = cmp::max(start_y, cmp::min(self_h as i32, y + h as i32)); let start_x = cmp::max(0, cmp::min(self_w as i32 - 1, x)); let end_x = cmp::max(start_x, cmp::min(self_w as i32, x + w as i32)); let data = self.data_mut(); let mut blur_data: Vec<Color> = Vec::new(); for y in start_y..end_y { for x in start_x..end_x { let old = data[y as usize * self_w as usize + x as usize]; blur_data.push(old); } } let real_w = end_x - start_x; let real_h = end_y - start_y; blur::gauss_blur(&mut blur_data, real_w as u32, real_h as u32, r as f32); let mut counter: u32 = 0; for y in start_y..end_y { for x in start_x..end_x { let a = blur_data[counter as usize]; let old = &mut data[y as usize * self_w as usize + x as usize].data; *old = a.data; counter += 1; } } } #[allow(clippy::too_many_arguments)] #[cfg(not(feature = "no_std"))] fn box_shadow( &mut self, x: i32, y: i32, w: u32, h: u32, offset_x: i32, offset_y: i32, r: i32, color: Color, ) { let real_w = w + (2 * r as u32); let real_h = h + (2 * r as u32); let mut blur_data: Vec<Color> = Vec::new(); for new_x in x..x + real_w as i32 { for new_y in y..y + real_h as i32 { if new_x < x + r || new_y < y + r || new_y >= y + h as i32 + r || new_x >= x + w as i32 + r { blur_data.push(Color::rgb(255, 0, 255)); } else { blur_data.push(Color::rgb(0, 0, 0)); } } } blur::gauss_blur(&mut blur_data, real_w as u32, real_h as u32, r as f32 / 3.0); let mut counter: u32 = 0; for new_x in (x - r)..(x + real_w as i32 - r) as i32 { for new_y in (y - r)..(y + real_h as i32 - r) as i32 { let c = blur_data[counter as usize]; let alpha: u8 = if color.a() < 255 - c.r() { color.a() } else { 255 - c.r() }; let col = Color::rgba(color.r(), color.g(), color.b(), alpha); let new_x_b = new_x + offset_x; let new_y_b = new_y + offset_y; if new_x_b < x || new_x_b > x + w as i32 - 1 || new_y_b < y || new_y_b > y + h as i32 - 1 { self.pixel(new_x_b, new_y_b, col); } counter += 1; } } } /// Display an image fn image(&mut self, start_x: i32, start_y: i32, w: u32, h: u32, data: &[Color]) { match self.mode().get() { Mode::Blend => self.image_fast(start_x, start_y, w, h, data), Mode::Overwrite => self.image_opaque(start_x, start_y, w, h, data), } } // TODO: Improve speed #[inline(always)] fn image_legacy(&mut self, start_x: i32, start_y: i32, w: u32, h: u32, data: &[Color]) { let mut i = 0; for y in start_y..start_y + h as i32 { for x in start_x..start_x + w as i32 { if i < data.len() { self.pixel(x, y, data[i]) } i += 1; } } } ///Display an image overwriting a portion of window starting at given line : very quick!! fn image_over(&mut self, start: i32, image_data: &[Color]) { let start = start as usize * self.width() as usize; let window_data = self.data_mut(); let stop = cmp::min(start + image_data.len(), window_data.len()); let end = cmp::min(image_data.len(), window_data.len() - start); window_data[start..stop].copy_from_slice(&image_data[..end]); } ///Display an image using non transparent method #[inline(always)] fn image_opaque(&mut self, start_x: i32, start_y: i32, w: u32, h: u32, image_data: &[Color]) { let w = w as usize; let mut h = h as usize; let width = self.width() as usize; let height = self.height() as usize; let start_x = start_x as usize; let start_y = start_y as usize; //check boundaries if start_x >= width || start_y >= height { return; } if h + start_y > height { h = height - start_y; } let window_data = self.data_mut(); let offset = start_y * width + start_x; //copy image slices to window line by line for l in 0..h { let start = offset + l * width; let mut stop = start + w; let begin = l * w; let mut end = begin + w; //check boundaries if start_x + w > width { stop = (start_y + l + 1) * width - 1; end = begin + stop - start; } window_data[start..stop].copy_from_slice(&image_data[begin..end]); } } // Speed improved, image can be outside of window boundary #[inline(always)] fn image_fast(&mut self, start_x: i32, start_y: i32, w: u32, h: u32, image_data: &[Color]) { let w = w as usize; let h = h as usize; let width = self.width() as usize; let start_x = start_x as usize; let start_y = start_y as usize; //simply return if image is outside of window if start_x >= width || start_y >= self.height() as usize { return; } let window_data = self.data_mut(); let offset = start_y * width + start_x; //copy image slices to window line by line for l in 0..h { let start = offset + l * width; let mut stop = start + w; let begin = l * w; let end = begin + w; //check boundaries if start_x + w > width { stop = (start_y + l + 1) * width; } let mut k = 0; for i in begin..end { if i < image_data.len() { let new = image_data[i].data; let alpha = (new >> 24) & 0xFF; if alpha > 0 && (start + k) < window_data.len() && (start + k) < stop { let old = &mut window_data[start + k].data; if alpha >= 255 { *old = new; } else { let n_alpha = 255 - alpha; let rb = ((n_alpha * (*old & 0x00FF00FF)) + (alpha * (new & 0x00FF00FF))) >> 8; let ag = (n_alpha * ((*old & 0xFF00FF00) >> 8)) + (alpha * (0x01000000 | ((new & 0x0000FF00) >> 8))); *old = (rb & 0x00FF00FF) | (ag & 0xFF00FF00); } } k += 1; } } } } /// Draw a linear gradient in a rectangular region #[allow(clippy::too_many_arguments)] #[cfg(not(feature = "no_std"))] fn linear_gradient( &mut self, rect_x: i32, rect_y: i32, rect_width: u32, rect_height: u32, start_x: i32, start_y: i32, end_x: i32, end_y: i32, start_color: Color, end_color: Color, ) { if (start_x == end_x) && (start_y == end_y) { // Degenerate gradient self.rect(rect_x, rect_y, rect_width, rect_height, start_color); } else if start_x == end_x { // Vertical gradient for y in rect_y..(rect_y + rect_height as i32) { let proj = (y as f64 - start_y as f64) / (end_y as f64 - start_y as f64); let scale = if proj < 0.0 { 0.0 } else if proj > 1.0 { 1.0 } else { proj }; let color = Color::interpolate(start_color, end_color, scale); self.line(rect_x, y, rect_x + rect_width as i32 - 1, y, color); } } else if start_y == end_y { // Horizontal gradient for x in rect_x..(rect_x + rect_width as i32) { let proj = (x as f64 - start_x as f64) / (end_x as f64 - start_x as f64); let scale = if proj < 0.0 { 0.0 } else if proj > 1.0 { 1.0 } else { proj }; let color = Color::interpolate(start_color, end_color, scale); self.line(x, rect_y, x, rect_y + rect_height as i32 - 1, color); } } else { // Non axis-aligned gradient // Gradient vector let grad_x = end_x as f64 - start_x as f64; let grad_y = end_y as f64 - start_y as f64; let grad_len = grad_x * grad_x + grad_y * grad_y; for y in rect_y..(rect_y + rect_height as i32) { for x in rect_x..(rect_x + rect_width as i32) { // Pixel vector let pix_x = x as f64 - start_x as f64; let pix_y = y as f64 - start_y as f64; // Scalar projection let proj = (pix_x * grad_x + pix_y * grad_y) / grad_len; // Saturation let scale = if proj < 0.0 { 0.0 } else if proj > 1.0 { 1.0 } else { proj }; // Interpolation let color = Color::interpolate(start_color, end_color, scale); self.pixel(x, y, color); } } } } /// Draw a rect with rounded corners #[allow(clippy::too_many_arguments)] fn rounded_rect( &mut self, x: i32, y: i32, w: u32, h: u32, radius: u32, filled: bool, color: Color, ) { let w = w as i32; let h = h as i32; let r = radius as i32; if filled { //Draw inside corners self.arc(x + r, y + r, -r, 1 << 4 | 1 << 6, color); self.arc(x + w - 1 - r, y + r, -r, 1 << 5 | 1 << 7, color); self.arc(x + r, y + h - 1 - r, -r, 1 << 0 | 1 << 2, color); self.arc(x + w - 1 - r, y + h - 1 - r, -r, 1 << 1 | 1 << 3, color); // Draw inside rectangles self.rect(x + r, y, (w - 1 - r * 2) as u32, r as u32 + 1, color); self.rect( x + r, y + h - 1 - r, (w - 1 - r * 2) as u32, r as u32 + 1, color, ); self.rect(x, y + r + 1, w as u32, (h - 2 - r * 2) as u32, color); } else { //Draw outside corners self.arc(x + r, y + r, r, 1 << 4 | 1 << 6, color); self.arc(x + w - 1 - r, y + r, r, 1 << 5 | 1 << 7, color); self.arc(x + r, y + h - 1 - r, r, 1 << 0 | 1 << 2, color); self.arc(x + w - 1 - r, y + h - 1 - r, r, 1 << 1 | 1 << 3, color); // Draw outside rectangles self.rect(x + r + 1, y, (w - 2 - r * 2) as u32, 1, color); self.rect(x + r + 1, y + h - 1, (w - 2 - r * 2) as u32, 1, color); self.rect(x, y + r + 1, 1, (h - 2 - r * 2) as u32, color); self.rect(x + w - 1, y + r + 1, 1, (h - 2 - r * 2) as u32, color); } } /// Draws antialiased line #[cfg(not(feature = "no_std"))] fn wu_line(&mut self, x0: i32, y0: i32, x1: i32, y1: i32, color: Color) { //adapted from https://rosettacode.org/wiki/Xiaolin_Wu's_line_algorithm#C.23 let mut x0 = x0 as f64; let mut y0 = y0 as f64; let mut x1 = x1 as f64; let mut y1 = y1 as f64; let r = color.r(); let g = color.g(); let b = color.b(); let a = color.a() as f64; fn ipart(x: f64) -> i32 { x.trunc() as i32 } fn fpart(x: f64) -> f64 { if x < 0.0 { return 1.0 - (x - x.floor()); } x - x.floor() } fn rfpart(x: f64) -> f64 { 1.0 - fpart(x) } fn chkalpha(mut alpha: f64) -> u8 { if alpha > 255.0 { alpha = 255.0 }; if alpha < 0.0 { alpha = 0.0 }; alpha as u8 } let steep: bool = (y1 - y0).abs() > (x1 - x0).abs(); let mut temp; if steep { temp = x0; x0 = y0; y0 = temp; temp = x1; x1 = y1; y1 = temp; } if x0 > x1 { temp = x0; x0 = x1; x1 = temp; temp = y0; y0 = y1; y1 = temp; } let dx = x1 - x0; let dy = y1 - y0; let gradient = dy / dx; let mut xend: f64 = (x0 as f64).round(); let mut yend: f64 = y0 + gradient * (xend - x0); let mut xgap: f64 = rfpart(x0 + 0.5); let xpixel1 = xend as i32; let ypixel1 = (ipart(yend)) as i32; if steep { self.pixel( ypixel1, xpixel1, Color::rgba(r, g, b, chkalpha(rfpart(yend) * xgap * a)), ); self.pixel( ypixel1 + 1, xpixel1, Color::rgba(r, g, b, chkalpha(fpart(yend) * xgap * a)), ); } else { self.pixel( xpixel1, ypixel1, Color::rgba(r, g, b, chkalpha(rfpart(yend) * xgap * a)), ); self.pixel( xpixel1 + 1, ypixel1, Color::rgba(r, g, b, chkalpha(fpart(yend) * xgap * a)), ); } let mut intery: f64 = yend + gradient; xend = x1.round(); yend = y1 + gradient * (xend - x1); xgap = fpart(x1 + 0.5); let xpixel2 = xend as i32; let ypixel2 = ipart(yend) as i32; if steep { self.pixel( ypixel2, xpixel2, Color::rgba(r, g, b, chkalpha(rfpart(yend) * xgap * a)), ); self.pixel( ypixel2 + 1, xpixel2, Color::rgba(r, g, b, chkalpha(fpart(yend) * xgap * a)), ); } else { self.pixel( xpixel2, ypixel2, Color::rgba(r, g, b, chkalpha(rfpart(yend) * xgap * a)), ); self.pixel( xpixel2 + 1, ypixel2, Color::rgba(r, g, b, chkalpha(fpart(yend) * xgap * a)), ); } if steep { for x in (xpixel1 + 1)..(xpixel2) { self.pixel( ipart(intery) as i32, x, Color::rgba(r, g, b, chkalpha(a * rfpart(intery))), ); self.pixel( ipart(intery) as i32 + 1, x, Color::rgba(r, g, b, chkalpha(a * fpart(intery))), ); intery += gradient; } } else { for x in (xpixel1 + 1)..(xpixel2) { self.pixel( x, ipart(intery) as i32, Color::rgba(r, g, b, chkalpha(a * rfpart(intery))), ); self.pixel( x, ipart(intery) as i32 + 1, Color::rgba(r, g, b, chkalpha(a * fpart(intery))), ); intery += gradient; } } } ///Draws antialiased circle #[cfg(not(feature = "no_std"))] fn wu_circle(&mut self, x0: i32, y0: i32, radius: i32, color: Color) { let r = color.r(); let g = color.g(); let b = color.b(); let a = color.a(); let mut y = 0; let mut x = radius; let mut d = 0_f64; self.pixel(x0 + x, y0 + y, color); self.pixel(x0 - x, y0 - y, color); self.pixel(x0 + y, y0 - x, color); self.pixel(x0 - y, y0 + x, color); while x > y { let di = dist(radius, y); if di < d { x -= 1; } let col = Color::rgba(r, g, b, (a as f64 * (1.0 - di)) as u8); let col2 = Color::rgba(r, g, b, (a as f64 * di) as u8); self.pixel(x0 + x, y0 + y, col); self.pixel(x0 + x - 1, y0 + y, col2); //- self.pixel(x0 - x, y0 + y, col); self.pixel(x0 - x + 1, y0 + y, col2); //+ self.pixel(x0 + x, y0 - y, col); self.pixel(x0 + x - 1, y0 - y, col2); //- self.pixel(x0 - x, y0 - y, col); self.pixel(x0 - x + 1, y0 - y, col2); //+ self.pixel(x0 + y, y0 + x, col); self.pixel(x0 + y, y0 + x - 1, col2); self.pixel(x0 - y, y0 + x, col); self.pixel(x0 - y, y0 + x - 1, col2); self.pixel(x0 + y, y0 - x, col); self.pixel(x0 + y, y0 - x + 1, col2); self.pixel(x0 - y, y0 - x, col); self.pixel(x0 - y, y0 - x + 1, col2); d = di; y += 1; } fn dist(r: i32, y: i32) -> f64 { let x: f64 = ((r * r - y * y) as f64).sqrt(); x.ceil() - x } } ///Gets pixel color at x,y position fn getpixel(&self, x: i32, y: i32) -> Color { let p = (self.width() as i32 * y + x) as usize; if p >= self.data().len() { return Color::rgba(0, 0, 0, 0); } self.data()[p] } }
32.822072
98
0.4028
09e7b6b89d264820836e4178f98748ff991d0df2
197
#[cfg(test)] mod tests { //TODO: tests? } pub mod cp_info; pub mod cp; pub mod attributes; pub mod opcodes; pub mod bytecode_tools; pub mod methods; pub mod fields; pub mod class; pub mod gen;
14.071429
23
0.705584
093873c849a92622e3861d1cb146a491b6f5e1c5
52,190
use crate::infer::InferCtxtExt as _; use crate::traits::{self, PredicateObligation}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::Lrc; use rustc_hir as hir; use rustc_hir::def_id::{DefId, DefIdMap}; use rustc_hir::Node; use rustc_infer::infer::error_reporting::unexpected_hidden_region_diagnostic; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::infer::{self, InferCtxt, InferOk}; use rustc_middle::ty::fold::{BottomUpFolder, TypeFoldable, TypeFolder, TypeVisitor}; use rustc_middle::ty::free_region_map::FreeRegionRelations; use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef}; use rustc_middle::ty::{self, GenericParamDefKind, Ty, TyCtxt}; use rustc_session::config::nightly_options; use rustc_span::Span; pub type OpaqueTypeMap<'tcx> = DefIdMap<OpaqueTypeDecl<'tcx>>; /// Information about the opaque types whose values we /// are inferring in this function (these are the `impl Trait` that /// appear in the return type). #[derive(Copy, Clone, Debug)] pub struct OpaqueTypeDecl<'tcx> { /// The opaque type (`ty::Opaque`) for this declaration. pub opaque_type: Ty<'tcx>, /// The substitutions that we apply to the opaque type that this /// `impl Trait` desugars to. e.g., if: /// /// fn foo<'a, 'b, T>() -> impl Trait<'a> /// /// winds up desugared to: /// /// type Foo<'x, X> = impl Trait<'x> /// fn foo<'a, 'b, T>() -> Foo<'a, T> /// /// then `substs` would be `['a, T]`. pub substs: SubstsRef<'tcx>, /// The span of this particular definition of the opaque type. So /// for example: /// /// ``` /// type Foo = impl Baz; /// fn bar() -> Foo { /// ^^^ This is the span we are looking for! /// ``` /// /// In cases where the fn returns `(impl Trait, impl Trait)` or /// other such combinations, the result is currently /// over-approximated, but better than nothing. pub definition_span: Span, /// The type variable that represents the value of the opaque type /// that we require. In other words, after we compile this function, /// we will be created a constraint like: /// /// Foo<'a, T> = ?C /// /// where `?C` is the value of this type variable. =) It may /// naturally refer to the type and lifetime parameters in scope /// in this function, though ultimately it should only reference /// those that are arguments to `Foo` in the constraint above. (In /// other words, `?C` should not include `'b`, even though it's a /// lifetime parameter on `foo`.) pub concrete_ty: Ty<'tcx>, /// Returns `true` if the `impl Trait` bounds include region bounds. /// For example, this would be true for: /// /// fn foo<'a, 'b, 'c>() -> impl Trait<'c> + 'a + 'b /// /// but false for: /// /// fn foo<'c>() -> impl Trait<'c> /// /// unless `Trait` was declared like: /// /// trait Trait<'c>: 'c /// /// in which case it would be true. /// /// This is used during regionck to decide whether we need to /// impose any additional constraints to ensure that region /// variables in `concrete_ty` wind up being constrained to /// something from `substs` (or, at minimum, things that outlive /// the fn body). (Ultimately, writeback is responsible for this /// check.) pub has_required_region_bounds: bool, /// The origin of the opaque type. pub origin: hir::OpaqueTyOrigin, } /// Whether member constraints should be generated for all opaque types pub enum GenerateMemberConstraints { /// The default, used by typeck WhenRequired, /// The borrow checker needs member constraints in any case where we don't /// have a `'static` bound. This is because the borrow checker has more /// flexibility in the values of regions. For example, given `f<'a, 'b>` /// the borrow checker can have an inference variable outlive `'a` and `'b`, /// but not be equal to `'static`. IfNoStaticBound, } pub trait InferCtxtExt<'tcx> { fn instantiate_opaque_types<T: TypeFoldable<'tcx>>( &self, parent_def_id: DefId, body_id: hir::HirId, param_env: ty::ParamEnv<'tcx>, value: &T, value_span: Span, ) -> InferOk<'tcx, (T, OpaqueTypeMap<'tcx>)>; fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>( &self, opaque_types: &OpaqueTypeMap<'tcx>, free_region_relations: &FRR, ); fn constrain_opaque_type<FRR: FreeRegionRelations<'tcx>>( &self, def_id: DefId, opaque_defn: &OpaqueTypeDecl<'tcx>, mode: GenerateMemberConstraints, free_region_relations: &FRR, ); /*private*/ fn generate_member_constraint( &self, concrete_ty: Ty<'tcx>, opaque_type_generics: &ty::Generics, opaque_defn: &OpaqueTypeDecl<'tcx>, opaque_type_def_id: DefId, ); /*private*/ fn member_constraint_feature_gate( &self, opaque_defn: &OpaqueTypeDecl<'tcx>, opaque_type_def_id: DefId, conflict1: ty::Region<'tcx>, conflict2: ty::Region<'tcx>, ) -> bool; fn infer_opaque_definition_from_instantiation( &self, def_id: DefId, substs: SubstsRef<'tcx>, instantiated_ty: Ty<'tcx>, span: Span, ) -> Ty<'tcx>; } impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { /// Replaces all opaque types in `value` with fresh inference variables /// and creates appropriate obligations. For example, given the input: /// /// impl Iterator<Item = impl Debug> /// /// this method would create two type variables, `?0` and `?1`. It would /// return the type `?0` but also the obligations: /// /// ?0: Iterator<Item = ?1> /// ?1: Debug /// /// Moreover, it returns a `OpaqueTypeMap` that would map `?0` to /// info about the `impl Iterator<..>` type and `?1` to info about /// the `impl Debug` type. /// /// # Parameters /// /// - `parent_def_id` -- the `DefId` of the function in which the opaque type /// is defined /// - `body_id` -- the body-id with which the resulting obligations should /// be associated /// - `param_env` -- the in-scope parameter environment to be used for /// obligations /// - `value` -- the value within which we are instantiating opaque types /// - `value_span` -- the span where the value came from, used in error reporting fn instantiate_opaque_types<T: TypeFoldable<'tcx>>( &self, parent_def_id: DefId, body_id: hir::HirId, param_env: ty::ParamEnv<'tcx>, value: &T, value_span: Span, ) -> InferOk<'tcx, (T, OpaqueTypeMap<'tcx>)> { debug!( "instantiate_opaque_types(value={:?}, parent_def_id={:?}, body_id={:?}, \ param_env={:?}, value_span={:?})", value, parent_def_id, body_id, param_env, value_span, ); let mut instantiator = Instantiator { infcx: self, parent_def_id, body_id, param_env, value_span, opaque_types: Default::default(), obligations: vec![], }; let value = instantiator.instantiate_opaque_types_in_map(value); InferOk { value: (value, instantiator.opaque_types), obligations: instantiator.obligations } } /// Given the map `opaque_types` containing the opaque /// `impl Trait` types whose underlying, hidden types are being /// inferred, this method adds constraints to the regions /// appearing in those underlying hidden types to ensure that they /// at least do not refer to random scopes within the current /// function. These constraints are not (quite) sufficient to /// guarantee that the regions are actually legal values; that /// final condition is imposed after region inference is done. /// /// # The Problem /// /// Let's work through an example to explain how it works. Assume /// the current function is as follows: /// /// ```text /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>) /// ``` /// /// Here, we have two `impl Trait` types whose values are being /// inferred (the `impl Bar<'a>` and the `impl /// Bar<'b>`). Conceptually, this is sugar for a setup where we /// define underlying opaque types (`Foo1`, `Foo2`) and then, in /// the return type of `foo`, we *reference* those definitions: /// /// ```text /// type Foo1<'x> = impl Bar<'x>; /// type Foo2<'x> = impl Bar<'x>; /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. } /// // ^^^^ ^^ /// // | | /// // | substs /// // def_id /// ``` /// /// As indicating in the comments above, each of those references /// is (in the compiler) basically a substitution (`substs`) /// applied to the type of a suitable `def_id` (which identifies /// `Foo1` or `Foo2`). /// /// Now, at this point in compilation, what we have done is to /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with /// fresh inference variables C1 and C2. We wish to use the values /// of these variables to infer the underlying types of `Foo1` and /// `Foo2`. That is, this gives rise to higher-order (pattern) unification /// constraints like: /// /// ```text /// for<'a> (Foo1<'a> = C1) /// for<'b> (Foo1<'b> = C2) /// ``` /// /// For these equation to be satisfiable, the types `C1` and `C2` /// can only refer to a limited set of regions. For example, `C1` /// can only refer to `'static` and `'a`, and `C2` can only refer /// to `'static` and `'b`. The job of this function is to impose that /// constraint. /// /// Up to this point, C1 and C2 are basically just random type /// inference variables, and hence they may contain arbitrary /// regions. In fact, it is fairly likely that they do! Consider /// this possible definition of `foo`: /// /// ```text /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) { /// (&*x, &*y) /// } /// ``` /// /// Here, the values for the concrete types of the two impl /// traits will include inference variables: /// /// ```text /// &'0 i32 /// &'1 i32 /// ``` /// /// Ordinarily, the subtyping rules would ensure that these are /// sufficiently large. But since `impl Bar<'a>` isn't a specific /// type per se, we don't get such constraints by default. This /// is where this function comes into play. It adds extra /// constraints to ensure that all the regions which appear in the /// inferred type are regions that could validly appear. /// /// This is actually a bit of a tricky constraint in general. We /// want to say that each variable (e.g., `'0`) can only take on /// values that were supplied as arguments to the opaque type /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in /// scope. We don't have a constraint quite of this kind in the current /// region checker. /// /// # The Solution /// /// We generally prefer to make `<=` constraints, since they /// integrate best into the region solver. To do that, we find the /// "minimum" of all the arguments that appear in the substs: that /// is, some region which is less than all the others. In the case /// of `Foo1<'a>`, that would be `'a` (it's the only choice, after /// all). Then we apply that as a least bound to the variables /// (e.g., `'a <= '0`). /// /// In some cases, there is no minimum. Consider this example: /// /// ```text /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... } /// ``` /// /// Here we would report a more complex "in constraint", like `'r /// in ['a, 'b, 'static]` (where `'r` is some region appearing in /// the hidden type). /// /// # Constrain regions, not the hidden concrete type /// /// Note that generating constraints on each region `Rc` is *not* /// the same as generating an outlives constraint on `Tc` iself. /// For example, if we had a function like this: /// /// ```rust /// fn foo<'a, T>(x: &'a u32, y: T) -> impl Foo<'a> { /// (x, y) /// } /// /// // Equivalent to: /// type FooReturn<'a, T> = impl Foo<'a>; /// fn foo<'a, T>(..) -> FooReturn<'a, T> { .. } /// ``` /// /// then the hidden type `Tc` would be `(&'0 u32, T)` (where `'0` /// is an inference variable). If we generated a constraint that /// `Tc: 'a`, then this would incorrectly require that `T: 'a` -- /// but this is not necessary, because the opaque type we /// create will be allowed to reference `T`. So we only generate a /// constraint that `'0: 'a`. /// /// # The `free_region_relations` parameter /// /// The `free_region_relations` argument is used to find the /// "minimum" of the regions supplied to a given opaque type. /// It must be a relation that can answer whether `'a <= 'b`, /// where `'a` and `'b` are regions that appear in the "substs" /// for the opaque type references (the `<'a>` in `Foo1<'a>`). /// /// Note that we do not impose the constraints based on the /// generic regions from the `Foo1` definition (e.g., `'x`). This /// is because the constraints we are imposing here is basically /// the concern of the one generating the constraining type C1, /// which is the current function. It also means that we can /// take "implied bounds" into account in some cases: /// /// ```text /// trait SomeTrait<'a, 'b> { } /// fn foo<'a, 'b>(_: &'a &'b u32) -> impl SomeTrait<'a, 'b> { .. } /// ``` /// /// Here, the fact that `'b: 'a` is known only because of the /// implied bounds from the `&'a &'b u32` parameter, and is not /// "inherent" to the opaque type definition. /// /// # Parameters /// /// - `opaque_types` -- the map produced by `instantiate_opaque_types` /// - `free_region_relations` -- something that can be used to relate /// the free regions (`'a`) that appear in the impl trait. fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>( &self, opaque_types: &OpaqueTypeMap<'tcx>, free_region_relations: &FRR, ) { debug!("constrain_opaque_types()"); for (&def_id, opaque_defn) in opaque_types { self.constrain_opaque_type( def_id, opaque_defn, GenerateMemberConstraints::WhenRequired, free_region_relations, ); } } /// See `constrain_opaque_types` for documentation. fn constrain_opaque_type<FRR: FreeRegionRelations<'tcx>>( &self, def_id: DefId, opaque_defn: &OpaqueTypeDecl<'tcx>, mode: GenerateMemberConstraints, free_region_relations: &FRR, ) { debug!("constrain_opaque_type()"); debug!("constrain_opaque_type: def_id={:?}", def_id); debug!("constrain_opaque_type: opaque_defn={:#?}", opaque_defn); let tcx = self.tcx; let concrete_ty = self.resolve_vars_if_possible(&opaque_defn.concrete_ty); debug!("constrain_opaque_type: concrete_ty={:?}", concrete_ty); let opaque_type_generics = tcx.generics_of(def_id); let span = tcx.def_span(def_id); // If there are required region bounds, we can use them. if opaque_defn.has_required_region_bounds { let predicates_of = tcx.predicates_of(def_id); debug!("constrain_opaque_type: predicates: {:#?}", predicates_of,); let bounds = predicates_of.instantiate(tcx, opaque_defn.substs); debug!("constrain_opaque_type: bounds={:#?}", bounds); let opaque_type = tcx.mk_opaque(def_id, opaque_defn.substs); let required_region_bounds = required_region_bounds(tcx, opaque_type, bounds.predicates); debug_assert!(!required_region_bounds.is_empty()); for required_region in required_region_bounds { concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor { op: |r| self.sub_regions(infer::CallReturn(span), required_region, r), }); } if let GenerateMemberConstraints::IfNoStaticBound = mode { self.generate_member_constraint( concrete_ty, opaque_type_generics, opaque_defn, def_id, ); } return; } // There were no `required_region_bounds`, // so we have to search for a `least_region`. // Go through all the regions used as arguments to the // opaque type. These are the parameters to the opaque // type; so in our example above, `substs` would contain // `['a]` for the first impl trait and `'b` for the // second. let mut least_region = None; for param in &opaque_type_generics.params { match param.kind { GenericParamDefKind::Lifetime => {} _ => continue, } // Get the value supplied for this region from the substs. let subst_arg = opaque_defn.substs.region_at(param.index as usize); // Compute the least upper bound of it with the other regions. debug!("constrain_opaque_types: least_region={:?}", least_region); debug!("constrain_opaque_types: subst_arg={:?}", subst_arg); match least_region { None => least_region = Some(subst_arg), Some(lr) => { if free_region_relations.sub_free_regions(self.tcx, lr, subst_arg) { // keep the current least region } else if free_region_relations.sub_free_regions(self.tcx, subst_arg, lr) { // switch to `subst_arg` least_region = Some(subst_arg); } else { // There are two regions (`lr` and // `subst_arg`) which are not relatable. We // can't find a best choice. Therefore, // instead of creating a single bound like // `'r: 'a` (which is our preferred choice), // we will create a "in bound" like `'r in // ['a, 'b, 'c]`, where `'a..'c` are the // regions that appear in the impl trait. // For now, enforce a feature gate outside of async functions. self.member_constraint_feature_gate(opaque_defn, def_id, lr, subst_arg); return self.generate_member_constraint( concrete_ty, opaque_type_generics, opaque_defn, def_id, ); } } } } let least_region = least_region.unwrap_or(tcx.lifetimes.re_static); debug!("constrain_opaque_types: least_region={:?}", least_region); if let GenerateMemberConstraints::IfNoStaticBound = mode { if least_region != tcx.lifetimes.re_static { self.generate_member_constraint( concrete_ty, opaque_type_generics, opaque_defn, def_id, ); } } concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor { op: |r| self.sub_regions(infer::CallReturn(span), least_region, r), }); } /// As a fallback, we sometimes generate an "in constraint". For /// a case like `impl Foo<'a, 'b>`, where `'a` and `'b` cannot be /// related, we would generate a constraint `'r in ['a, 'b, /// 'static]` for each region `'r` that appears in the hidden type /// (i.e., it must be equal to `'a`, `'b`, or `'static`). /// /// `conflict1` and `conflict2` are the two region bounds that we /// detected which were unrelated. They are used for diagnostics. fn generate_member_constraint( &self, concrete_ty: Ty<'tcx>, opaque_type_generics: &ty::Generics, opaque_defn: &OpaqueTypeDecl<'tcx>, opaque_type_def_id: DefId, ) { // Create the set of choice regions: each region in the hidden // type can be equal to any of the region parameters of the // opaque type definition. let choice_regions: Lrc<Vec<ty::Region<'tcx>>> = Lrc::new( opaque_type_generics .params .iter() .filter(|param| match param.kind { GenericParamDefKind::Lifetime => true, GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => false, }) .map(|param| opaque_defn.substs.region_at(param.index as usize)) .chain(std::iter::once(self.tcx.lifetimes.re_static)) .collect(), ); concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor { op: |r| { self.member_constraint( opaque_type_def_id, opaque_defn.definition_span, concrete_ty, r, &choice_regions, ) }, }); } /// Member constraints are presently feature-gated except for /// async-await. We expect to lift this once we've had a bit more /// time. fn member_constraint_feature_gate( &self, opaque_defn: &OpaqueTypeDecl<'tcx>, opaque_type_def_id: DefId, conflict1: ty::Region<'tcx>, conflict2: ty::Region<'tcx>, ) -> bool { // If we have `#![feature(member_constraints)]`, no problems. if self.tcx.features().member_constraints { return false; } let span = self.tcx.def_span(opaque_type_def_id); // Without a feature-gate, we only generate member-constraints for async-await. let context_name = match opaque_defn.origin { // No feature-gate required for `async fn`. hir::OpaqueTyOrigin::AsyncFn => return false, // Otherwise, generate the label we'll use in the error message. hir::OpaqueTyOrigin::TypeAlias | hir::OpaqueTyOrigin::FnReturn | hir::OpaqueTyOrigin::Misc => "impl Trait", }; let msg = format!("ambiguous lifetime bound in `{}`", context_name); let mut err = self.tcx.sess.struct_span_err(span, &msg); let conflict1_name = conflict1.to_string(); let conflict2_name = conflict2.to_string(); let label_owned; let label = match (&*conflict1_name, &*conflict2_name) { ("'_", "'_") => "the elided lifetimes here do not outlive one another", _ => { label_owned = format!( "neither `{}` nor `{}` outlives the other", conflict1_name, conflict2_name, ); &label_owned } }; err.span_label(span, label); if nightly_options::is_nightly_build() { err.help("add #![feature(member_constraints)] to the crate attributes to enable"); } err.emit(); true } /// Given the fully resolved, instantiated type for an opaque /// type, i.e., the value of an inference variable like C1 or C2 /// (*), computes the "definition type" for an opaque type /// definition -- that is, the inferred value of `Foo1<'x>` or /// `Foo2<'x>` that we would conceptually use in its definition: /// /// type Foo1<'x> = impl Bar<'x> = AAA; <-- this type AAA /// type Foo2<'x> = impl Bar<'x> = BBB; <-- or this type BBB /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. } /// /// Note that these values are defined in terms of a distinct set of /// generic parameters (`'x` instead of `'a`) from C1 or C2. The main /// purpose of this function is to do that translation. /// /// (*) C1 and C2 were introduced in the comments on /// `constrain_opaque_types`. Read that comment for more context. /// /// # Parameters /// /// - `def_id`, the `impl Trait` type /// - `substs`, the substs used to instantiate this opaque type /// - `instantiated_ty`, the inferred type C1 -- fully resolved, lifted version of /// `opaque_defn.concrete_ty` fn infer_opaque_definition_from_instantiation( &self, def_id: DefId, substs: SubstsRef<'tcx>, instantiated_ty: Ty<'tcx>, span: Span, ) -> Ty<'tcx> { debug!( "infer_opaque_definition_from_instantiation(def_id={:?}, instantiated_ty={:?})", def_id, instantiated_ty ); // Use substs to build up a reverse map from regions to their // identity mappings. This is necessary because of `impl // Trait` lifetimes are computed by replacing existing // lifetimes with 'static and remapping only those used in the // `impl Trait` return type, resulting in the parameters // shifting. let id_substs = InternalSubsts::identity_for_item(self.tcx, def_id); let map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>> = substs.iter().enumerate().map(|(index, subst)| (*subst, id_substs[index])).collect(); // Convert the type from the function into a type valid outside // the function, by replacing invalid regions with 'static, // after producing an error for each of them. let definition_ty = instantiated_ty.fold_with(&mut ReverseMapper::new( self.tcx, self.is_tainted_by_errors(), def_id, map, instantiated_ty, span, )); debug!("infer_opaque_definition_from_instantiation: definition_ty={:?}", definition_ty); definition_ty } } // Visitor that requires that (almost) all regions in the type visited outlive // `least_region`. We cannot use `push_outlives_components` because regions in // closure signatures are not included in their outlives components. We need to // ensure all regions outlive the given bound so that we don't end up with, // say, `ReScope` appearing in a return type and causing ICEs when other // functions end up with region constraints involving regions from other // functions. // // We also cannot use `for_each_free_region` because for closures it includes // the regions parameters from the enclosing item. // // We ignore any type parameters because impl trait values are assumed to // capture all the in-scope type parameters. struct ConstrainOpaqueTypeRegionVisitor<OP> { op: OP, } impl<'tcx, OP> TypeVisitor<'tcx> for ConstrainOpaqueTypeRegionVisitor<OP> where OP: FnMut(ty::Region<'tcx>), { fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> bool { t.skip_binder().visit_with(self); false // keep visiting } fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool { match *r { // ignore bound regions, keep visiting ty::ReLateBound(_, _) => false, _ => { (self.op)(r); false } } } fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool { // We're only interested in types involving regions if !ty.flags.intersects(ty::TypeFlags::HAS_FREE_REGIONS) { return false; // keep visiting } match ty.kind { ty::Closure(_, ref substs) => { // Skip lifetime parameters of the enclosing item(s) for upvar_ty in substs.as_closure().upvar_tys() { upvar_ty.visit_with(self); } substs.as_closure().sig_as_fn_ptr_ty().visit_with(self); } ty::Generator(_, ref substs, _) => { // Skip lifetime parameters of the enclosing item(s) // Also skip the witness type, because that has no free regions. for upvar_ty in substs.as_generator().upvar_tys() { upvar_ty.visit_with(self); } substs.as_generator().return_ty().visit_with(self); substs.as_generator().yield_ty().visit_with(self); substs.as_generator().resume_ty().visit_with(self); } _ => { ty.super_visit_with(self); } } false } } struct ReverseMapper<'tcx> { tcx: TyCtxt<'tcx>, /// If errors have already been reported in this fn, we suppress /// our own errors because they are sometimes derivative. tainted_by_errors: bool, opaque_type_def_id: DefId, map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>>, map_missing_regions_to_empty: bool, /// initially `Some`, set to `None` once error has been reported hidden_ty: Option<Ty<'tcx>>, /// Span of function being checked. span: Span, } impl ReverseMapper<'tcx> { fn new( tcx: TyCtxt<'tcx>, tainted_by_errors: bool, opaque_type_def_id: DefId, map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>>, hidden_ty: Ty<'tcx>, span: Span, ) -> Self { Self { tcx, tainted_by_errors, opaque_type_def_id, map, map_missing_regions_to_empty: false, hidden_ty: Some(hidden_ty), span, } } fn fold_kind_mapping_missing_regions_to_empty( &mut self, kind: GenericArg<'tcx>, ) -> GenericArg<'tcx> { assert!(!self.map_missing_regions_to_empty); self.map_missing_regions_to_empty = true; let kind = kind.fold_with(self); self.map_missing_regions_to_empty = false; kind } fn fold_kind_normally(&mut self, kind: GenericArg<'tcx>) -> GenericArg<'tcx> { assert!(!self.map_missing_regions_to_empty); kind.fold_with(self) } } impl TypeFolder<'tcx> for ReverseMapper<'tcx> { fn tcx(&self) -> TyCtxt<'tcx> { self.tcx } fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { match r { // Ignore bound regions and `'static` regions that appear in the // type, we only need to remap regions that reference lifetimes // from the function declaraion. // This would ignore `'r` in a type like `for<'r> fn(&'r u32)`. ty::ReLateBound(..) | ty::ReStatic => return r, // If regions have been erased (by writeback), don't try to unerase // them. ty::ReErased => return r, // The regions that we expect from borrow checking. ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReEmpty(ty::UniverseIndex::ROOT) => {} ty::ReEmpty(_) | ty::RePlaceholder(_) | ty::ReVar(_) | ty::ReScope(_) => { // All of the regions in the type should either have been // erased by writeback, or mapped back to named regions by // borrow checking. bug!("unexpected region kind in opaque type: {:?}", r); } } let generics = self.tcx().generics_of(self.opaque_type_def_id); match self.map.get(&r.into()).map(|k| k.unpack()) { Some(GenericArgKind::Lifetime(r1)) => r1, Some(u) => panic!("region mapped to unexpected kind: {:?}", u), None if self.map_missing_regions_to_empty || self.tainted_by_errors => { self.tcx.lifetimes.re_root_empty } None if generics.parent.is_some() => { if let Some(hidden_ty) = self.hidden_ty.take() { unexpected_hidden_region_diagnostic( self.tcx, None, self.tcx.def_span(self.opaque_type_def_id), hidden_ty, r, ) .emit(); } self.tcx.lifetimes.re_root_empty } None => { self.tcx .sess .struct_span_err(self.span, "non-defining opaque type use in defining scope") .span_label( self.span, format!( "lifetime `{}` is part of concrete type but not used in \ parameter list of the `impl Trait` type alias", r ), ) .emit(); self.tcx().lifetimes.re_static } } } fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { match ty.kind { ty::Closure(def_id, substs) => { // I am a horrible monster and I pray for death. When // we encounter a closure here, it is always a closure // from within the function that we are currently // type-checking -- one that is now being encapsulated // in an opaque type. Ideally, we would // go through the types/lifetimes that it references // and treat them just like we would any other type, // which means we would error out if we find any // reference to a type/region that is not in the // "reverse map". // // **However,** in the case of closures, there is a // somewhat subtle (read: hacky) consideration. The // problem is that our closure types currently include // all the lifetime parameters declared on the // enclosing function, even if they are unused by the // closure itself. We can't readily filter them out, // so here we replace those values with `'empty`. This // can't really make a difference to the rest of the // compiler; those regions are ignored for the // outlives relation, and hence don't affect trait // selection or auto traits, and they are erased // during codegen. let generics = self.tcx.generics_of(def_id); let substs = self.tcx.mk_substs(substs.iter().enumerate().map(|(index, &kind)| { if index < generics.parent_count { // Accommodate missing regions in the parent kinds... self.fold_kind_mapping_missing_regions_to_empty(kind) } else { // ...but not elsewhere. self.fold_kind_normally(kind) } })); self.tcx.mk_closure(def_id, substs) } ty::Generator(def_id, substs, movability) => { let generics = self.tcx.generics_of(def_id); let substs = self.tcx.mk_substs(substs.iter().enumerate().map(|(index, &kind)| { if index < generics.parent_count { // Accommodate missing regions in the parent kinds... self.fold_kind_mapping_missing_regions_to_empty(kind) } else { // ...but not elsewhere. self.fold_kind_normally(kind) } })); self.tcx.mk_generator(def_id, substs, movability) } ty::Param(..) => { // Look it up in the substitution list. match self.map.get(&ty.into()).map(|k| k.unpack()) { // Found it in the substitution list; replace with the parameter from the // opaque type. Some(GenericArgKind::Type(t1)) => t1, Some(u) => panic!("type mapped to unexpected kind: {:?}", u), None => { self.tcx .sess .struct_span_err( self.span, &format!( "type parameter `{}` is part of concrete type but not \ used in parameter list for the `impl Trait` type alias", ty ), ) .emit(); self.tcx().types.err } } } _ => ty.super_fold_with(self), } } fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { trace!("checking const {:?}", ct); // Find a const parameter match ct.val { ty::ConstKind::Param(..) => { // Look it up in the substitution list. match self.map.get(&ct.into()).map(|k| k.unpack()) { // Found it in the substitution list, replace with the parameter from the // opaque type. Some(GenericArgKind::Const(c1)) => c1, Some(u) => panic!("const mapped to unexpected kind: {:?}", u), None => { self.tcx .sess .struct_span_err( self.span, &format!( "const parameter `{}` is part of concrete type but not \ used in parameter list for the `impl Trait` type alias", ct ), ) .emit(); self.tcx().consts.err } } } _ => ct, } } } struct Instantiator<'a, 'tcx> { infcx: &'a InferCtxt<'a, 'tcx>, parent_def_id: DefId, body_id: hir::HirId, param_env: ty::ParamEnv<'tcx>, value_span: Span, opaque_types: OpaqueTypeMap<'tcx>, obligations: Vec<PredicateObligation<'tcx>>, } impl<'a, 'tcx> Instantiator<'a, 'tcx> { fn instantiate_opaque_types_in_map<T: TypeFoldable<'tcx>>(&mut self, value: &T) -> T { debug!("instantiate_opaque_types_in_map(value={:?})", value); let tcx = self.infcx.tcx; value.fold_with(&mut BottomUpFolder { tcx, ty_op: |ty| { if ty.references_error() { return tcx.types.err; } else if let ty::Opaque(def_id, substs) = ty.kind { // Check that this is `impl Trait` type is // declared by `parent_def_id` -- i.e., one whose // value we are inferring. At present, this is // always true during the first phase of // type-check, but not always true later on during // NLL. Once we support named opaque types more fully, // this same scenario will be able to arise during all phases. // // Here is an example using type alias `impl Trait` // that indicates the distinction we are checking for: // // ```rust // mod a { // pub type Foo = impl Iterator; // pub fn make_foo() -> Foo { .. } // } // // mod b { // fn foo() -> a::Foo { a::make_foo() } // } // ``` // // Here, the return type of `foo` references a // `Opaque` indeed, but not one whose value is // presently being inferred. You can get into a // similar situation with closure return types // today: // // ```rust // fn foo() -> impl Iterator { .. } // fn bar() { // let x = || foo(); // returns the Opaque assoc with `foo` // } // ``` if let Some(opaque_hir_id) = tcx.hir().as_local_hir_id(def_id) { let parent_def_id = self.parent_def_id; let def_scope_default = || { let opaque_parent_hir_id = tcx.hir().get_parent_item(opaque_hir_id); parent_def_id == tcx.hir().local_def_id(opaque_parent_hir_id) }; let (in_definition_scope, origin) = match tcx.hir().find(opaque_hir_id) { Some(Node::Item(item)) => match item.kind { // Anonymous `impl Trait` hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(parent), origin, .. }) => (parent == self.parent_def_id, origin), // Named `type Foo = impl Bar;` hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: None, origin, .. }) => ( may_define_opaque_type(tcx, self.parent_def_id, opaque_hir_id), origin, ), _ => (def_scope_default(), hir::OpaqueTyOrigin::TypeAlias), }, Some(Node::ImplItem(item)) => match item.kind { hir::ImplItemKind::OpaqueTy(_) => ( may_define_opaque_type(tcx, self.parent_def_id, opaque_hir_id), hir::OpaqueTyOrigin::TypeAlias, ), _ => (def_scope_default(), hir::OpaqueTyOrigin::TypeAlias), }, _ => bug!( "expected (impl) item, found {}", tcx.hir().node_to_string(opaque_hir_id), ), }; if in_definition_scope { return self.fold_opaque_ty(ty, def_id, substs, origin); } debug!( "instantiate_opaque_types_in_map: \ encountered opaque outside its definition scope \ def_id={:?}", def_id, ); } } ty }, lt_op: |lt| lt, ct_op: |ct| ct, }) } fn fold_opaque_ty( &mut self, ty: Ty<'tcx>, def_id: DefId, substs: SubstsRef<'tcx>, origin: hir::OpaqueTyOrigin, ) -> Ty<'tcx> { let infcx = self.infcx; let tcx = infcx.tcx; debug!("instantiate_opaque_types: Opaque(def_id={:?}, substs={:?})", def_id, substs); // Use the same type variable if the exact same opaque type appears more // than once in the return type (e.g., if it's passed to a type alias). if let Some(opaque_defn) = self.opaque_types.get(&def_id) { debug!("instantiate_opaque_types: returning concrete ty {:?}", opaque_defn.concrete_ty); return opaque_defn.concrete_ty; } let span = tcx.def_span(def_id); debug!("fold_opaque_ty {:?} {:?}", self.value_span, span); let ty_var = infcx .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span }); let predicates_of = tcx.predicates_of(def_id); debug!("instantiate_opaque_types: predicates={:#?}", predicates_of,); let bounds = predicates_of.instantiate(tcx, substs); let param_env = tcx.param_env(def_id); let InferOk { value: bounds, obligations } = infcx.partially_normalize_associated_types_in(span, self.body_id, param_env, &bounds); self.obligations.extend(obligations); debug!("instantiate_opaque_types: bounds={:?}", bounds); let required_region_bounds = required_region_bounds(tcx, ty, bounds.predicates.clone()); debug!("instantiate_opaque_types: required_region_bounds={:?}", required_region_bounds); // Make sure that we are in fact defining the *entire* type // (e.g., `type Foo<T: Bound> = impl Bar;` needs to be // defined by a function like `fn foo<T: Bound>() -> Foo<T>`). debug!("instantiate_opaque_types: param_env={:#?}", self.param_env,); debug!("instantiate_opaque_types: generics={:#?}", tcx.generics_of(def_id),); // Ideally, we'd get the span where *this specific `ty` came // from*, but right now we just use the span from the overall // value being folded. In simple cases like `-> impl Foo`, // these are the same span, but not in cases like `-> (impl // Foo, impl Bar)`. let definition_span = self.value_span; self.opaque_types.insert( def_id, OpaqueTypeDecl { opaque_type: ty, substs, definition_span, concrete_ty: ty_var, has_required_region_bounds: !required_region_bounds.is_empty(), origin, }, ); debug!("instantiate_opaque_types: ty_var={:?}", ty_var); for predicate in &bounds.predicates { if let ty::Predicate::Projection(projection) = &predicate { if projection.skip_binder().ty.references_error() { // No point on adding these obligations since there's a type error involved. return ty_var; } } } self.obligations.reserve(bounds.predicates.len()); for predicate in bounds.predicates { // Change the predicate to refer to the type variable, // which will be the concrete type instead of the opaque type. // This also instantiates nested instances of `impl Trait`. let predicate = self.instantiate_opaque_types_in_map(&predicate); let cause = traits::ObligationCause::new(span, self.body_id, traits::SizedReturnType); // Require that the predicate holds for the concrete type. debug!("instantiate_opaque_types: predicate={:?}", predicate); self.obligations.push(traits::Obligation::new(cause, self.param_env, predicate)); } ty_var } } /// Returns `true` if `opaque_hir_id` is a sibling or a child of a sibling of `def_id`. /// /// Example: /// ```rust /// pub mod foo { /// pub mod bar { /// pub trait Bar { .. } /// /// pub type Baz = impl Bar; /// /// fn f1() -> Baz { .. } /// } /// /// fn f2() -> bar::Baz { .. } /// } /// ``` /// /// Here, `def_id` is the `DefId` of the defining use of the opaque type (e.g., `f1` or `f2`), /// and `opaque_hir_id` is the `HirId` of the definition of the opaque type `Baz`. /// For the above example, this function returns `true` for `f1` and `false` for `f2`. pub fn may_define_opaque_type(tcx: TyCtxt<'_>, def_id: DefId, opaque_hir_id: hir::HirId) -> bool { let mut hir_id = tcx.hir().as_local_hir_id(def_id).unwrap(); // Named opaque types can be defined by any siblings or children of siblings. let scope = tcx.hir().get_defining_scope(opaque_hir_id); // We walk up the node tree until we hit the root or the scope of the opaque type. while hir_id != scope && hir_id != hir::CRATE_HIR_ID { hir_id = tcx.hir().get_parent_item(hir_id); } // Syntactically, we are allowed to define the concrete type if: let res = hir_id == scope; trace!( "may_define_opaque_type(def={:?}, opaque_node={:?}) = {}", tcx.hir().find(hir_id), tcx.hir().get(opaque_hir_id), res ); res } /// Given a set of predicates that apply to an object type, returns /// the region bounds that the (erased) `Self` type must /// outlive. Precisely *because* the `Self` type is erased, the /// parameter `erased_self_ty` must be supplied to indicate what type /// has been used to represent `Self` in the predicates /// themselves. This should really be a unique type; `FreshTy(0)` is a /// popular choice. /// /// N.B., in some cases, particularly around higher-ranked bounds, /// this function returns a kind of conservative approximation. /// That is, all regions returned by this function are definitely /// required, but there may be other region bounds that are not /// returned, as well as requirements like `for<'a> T: 'a`. /// /// Requires that trait definitions have been processed so that we can /// elaborate predicates and walk supertraits. // // FIXME: callers may only have a `&[Predicate]`, not a `Vec`, so that's // what this code should accept. crate fn required_region_bounds( tcx: TyCtxt<'tcx>, erased_self_ty: Ty<'tcx>, predicates: Vec<ty::Predicate<'tcx>>, ) -> Vec<ty::Region<'tcx>> { debug!( "required_region_bounds(erased_self_ty={:?}, predicates={:?})", erased_self_ty, predicates ); assert!(!erased_self_ty.has_escaping_bound_vars()); traits::elaborate_predicates(tcx, predicates) .filter_map(|predicate| { match predicate { ty::Predicate::Projection(..) | ty::Predicate::Trait(..) | ty::Predicate::Subtype(..) | ty::Predicate::WellFormed(..) | ty::Predicate::ObjectSafe(..) | ty::Predicate::ClosureKind(..) | ty::Predicate::RegionOutlives(..) | ty::Predicate::ConstEvaluatable(..) => None, ty::Predicate::TypeOutlives(predicate) => { // Search for a bound of the form `erased_self_ty // : 'a`, but be wary of something like `for<'a> // erased_self_ty : 'a` (we interpret a // higher-ranked bound like that as 'static, // though at present the code in `fulfill.rs` // considers such bounds to be unsatisfiable, so // it's kind of a moot point since you could never // construct such an object, but this seems // correct even if that code changes). let ty::OutlivesPredicate(ref t, ref r) = predicate.skip_binder(); if t == &erased_self_ty && !r.has_escaping_bound_vars() { Some(*r) } else { None } } } }) .collect() }
40.488751
100
0.541713
efeb2144788b3058f0106a5c56004a9772c1de31
2,916
use aoc; //use regex::Regex; use pcre2::bytes::Regex; use std::collections::HashMap; use std::collections::HashSet; fn main() { let lines = aoc::lines_from_file("input.txt"); let mut r_pat: HashMap<String, String> = HashMap::new(); let mut u_pat: HashMap<String, Vec<String>> = HashMap::new(); let mut test = vec![]; for line in lines { if line.contains(":") { let s: Vec<&str> = line.split(": ").collect(); let id = s[0].to_string(); let mut val = s[1].to_string(); if val.contains("\"") { val = val.replace("\"", ""); r_pat.insert(id, val); } else { let tok: Vec<String> = val.split_whitespace().map(|s| s.to_string()).collect(); u_pat.insert(id, tok); } } else { test.push(line.clone()); } } for _ in 0..1000 { let mut transfer = HashSet::new(); transfer.clear(); for (k, v) in &r_pat { for (uk, uv) in &mut u_pat { // part 2, skip these and result manually hack tastic if uk == "0" || uk == "8" || uk == "11" { continue; } // replace any occurences of the re for i in 0..uv.len() { if uv[i] == *k { uv[i] = v.clone(); } } // Check if patter is completely resolved // contains no numbers let mut complete = true; for v in uv { if v.chars().all(char::is_numeric) { complete = false; break; } } if complete { transfer.insert(uk.clone()); } } } for t in transfer { let temp = u_pat.remove(&t).unwrap(); let pat: String = temp.join(""); r_pat.insert(t, format!("(?:{})", pat)); // non capturing } } dbg!(u_pat); // Manual regex manipulation // 0: 8 11 // 8: 42 | 42 8 // // 42+ // // 11: 42 31 | 42 11 31 // // 42 42 42 {n} 31 31 31 {m} where n == m, recursive? // // // 0: (42)+ ((42)+ (31)+) // PCRE2 recursive matching ...wat. let mut zero = "(?:42+)(42(?1)?31)".to_string(); let _42 = r_pat.get("42").unwrap().clone(); let _31 = r_pat.get("31").unwrap().clone(); dbg!(&_42, &_31); zero = zero.replace("42", &_42); zero = zero.replace("31", &_31); // let zero = r_pat.get("0").unwrap().clone(); let r = Regex::new(&format!("^{}$", zero)).unwrap(); dbg!(&zero); let count = test .iter() .filter(|t| r.is_match(t.as_bytes()).unwrap()) .count(); dbg!(count); }
26.27027
95
0.429012
ede9b6d1eb725b8eba9fe5103f59f603590a0fc6
132,193
use std::cell::RefCell; use std::ffi::{CStr, CString}; use std::fmt; use std::io::{self, SeekFrom, Write}; use std::path::Path; use std::slice; use std::str; use std::time::Duration; use curl_sys; use libc::{self, c_void, c_char, c_long, size_t, c_int, c_double, c_ulong}; use socket2::Socket; use Error; use easy::form; use easy::list; use easy::{List, Form}; use easy::windows; use panic; /// A trait for the various callbacks used by libcurl to invoke user code. /// /// This trait represents all operations that libcurl can possibly invoke a /// client for code during an HTTP transaction. Each callback has a default /// "noop" implementation, the same as in libcurl. Types implementing this trait /// may simply override the relevant functions to learn about the callbacks /// they're interested in. /// /// # Examples /// /// ``` /// use curl::easy::{Easy2, Handler, WriteError}; /// /// struct Collector(Vec<u8>); /// /// impl Handler for Collector { /// fn write(&mut self, data: &[u8]) -> Result<usize, WriteError> { /// self.0.extend_from_slice(data); /// Ok(data.len()) /// } /// } /// /// let mut easy = Easy2::new(Collector(Vec::new())); /// easy.get(true).unwrap(); /// easy.url("https://www.rust-lang.org/").unwrap(); /// easy.perform().unwrap(); /// /// assert_eq!(easy.response_code().unwrap(), 200); /// let contents = easy.get_ref(); /// println!("{}", String::from_utf8_lossy(&contents.0)); /// ``` pub trait Handler { /// Callback invoked whenever curl has downloaded data for the application. /// /// This callback function gets called by libcurl as soon as there is data /// received that needs to be saved. /// /// The callback function will be passed as much data as possible in all /// invokes, but you must not make any assumptions. It may be one byte, it /// may be thousands. If `show_header` is enabled, which makes header data /// get passed to the write callback, you can get up to /// `CURL_MAX_HTTP_HEADER` bytes of header data passed into it. This /// usually means 100K. /// /// This function may be called with zero bytes data if the transferred file /// is empty. /// /// The callback should return the number of bytes actually taken care of. /// If that amount differs from the amount passed to your callback function, /// it'll signal an error condition to the library. This will cause the /// transfer to get aborted and the libcurl function used will return /// an error with `is_write_error`. /// /// If your callback function returns `Err(WriteError::Pause)` it will cause /// this transfer to become paused. See `unpause_write` for further details. /// /// By default data is sent into the void, and this corresponds to the /// `CURLOPT_WRITEFUNCTION` and `CURLOPT_WRITEDATA` options. fn write(&mut self, data: &[u8]) -> Result<usize, WriteError> { Ok(data.len()) } /// Read callback for data uploads. /// /// This callback function gets called by libcurl as soon as it needs to /// read data in order to send it to the peer - like if you ask it to upload /// or post data to the server. /// /// Your function must then return the actual number of bytes that it stored /// in that memory area. Returning 0 will signal end-of-file to the library /// and cause it to stop the current transfer. /// /// If you stop the current transfer by returning 0 "pre-maturely" (i.e /// before the server expected it, like when you've said you will upload N /// bytes and you upload less than N bytes), you may experience that the /// server "hangs" waiting for the rest of the data that won't come. /// /// The read callback may return `Err(ReadError::Abort)` to stop the /// current operation immediately, resulting in a `is_aborted_by_callback` /// error code from the transfer. /// /// The callback can return `Err(ReadError::Pause)` to cause reading from /// this connection to pause. See `unpause_read` for further details. /// /// By default data not input, and this corresponds to the /// `CURLOPT_READFUNCTION` and `CURLOPT_READDATA` options. /// /// Note that the lifetime bound on this function is `'static`, but that /// is often too restrictive. To use stack data consider calling the /// `transfer` method and then using `read_function` to configure a /// callback that can reference stack-local data. fn read(&mut self, data: &mut [u8]) -> Result<usize, ReadError> { drop(data); Ok(0) } /// User callback for seeking in input stream. /// /// This function gets called by libcurl to seek to a certain position in /// the input stream and can be used to fast forward a file in a resumed /// upload (instead of reading all uploaded bytes with the normal read /// function/callback). It is also called to rewind a stream when data has /// already been sent to the server and needs to be sent again. This may /// happen when doing a HTTP PUT or POST with a multi-pass authentication /// method, or when an existing HTTP connection is reused too late and the /// server closes the connection. /// /// The callback function must return `SeekResult::Ok` on success, /// `SeekResult::Fail` to cause the upload operation to fail or /// `SeekResult::CantSeek` to indicate that while the seek failed, libcurl /// is free to work around the problem if possible. The latter can sometimes /// be done by instead reading from the input or similar. /// /// By default data this option is not set, and this corresponds to the /// `CURLOPT_SEEKFUNCTION` and `CURLOPT_SEEKDATA` options. fn seek(&mut self, whence: SeekFrom) -> SeekResult { drop(whence); SeekResult::CantSeek } /// Specify a debug callback /// /// `debug_function` replaces the standard debug function used when /// `verbose` is in effect. This callback receives debug information, /// as specified in the type argument. /// /// By default this option is not set and corresponds to the /// `CURLOPT_DEBUGFUNCTION` and `CURLOPT_DEBUGDATA` options. fn debug(&mut self, kind: InfoType, data: &[u8]) { debug(kind, data) } /// Callback that receives header data /// /// This function gets called by libcurl as soon as it has received header /// data. The header callback will be called once for each header and only /// complete header lines are passed on to the callback. Parsing headers is /// very easy using this. If this callback returns `false` it'll signal an /// error to the library. This will cause the transfer to get aborted and /// the libcurl function in progress will return `is_write_error`. /// /// A complete HTTP header that is passed to this function can be up to /// CURL_MAX_HTTP_HEADER (100K) bytes. /// /// It's important to note that the callback will be invoked for the headers /// of all responses received after initiating a request and not just the /// final response. This includes all responses which occur during /// authentication negotiation. If you need to operate on only the headers /// from the final response, you will need to collect headers in the /// callback yourself and use HTTP status lines, for example, to delimit /// response boundaries. /// /// When a server sends a chunked encoded transfer, it may contain a /// trailer. That trailer is identical to a HTTP header and if such a /// trailer is received it is passed to the application using this callback /// as well. There are several ways to detect it being a trailer and not an /// ordinary header: 1) it comes after the response-body. 2) it comes after /// the final header line (CR LF) 3) a Trailer: header among the regular /// response-headers mention what header(s) to expect in the trailer. /// /// For non-HTTP protocols like FTP, POP3, IMAP and SMTP this function will /// get called with the server responses to the commands that libcurl sends. /// /// By default this option is not set and corresponds to the /// `CURLOPT_HEADERFUNCTION` and `CURLOPT_HEADERDATA` options. fn header(&mut self, data: &[u8]) -> bool { drop(data); true } /// Callback to progress meter function /// /// This function gets called by libcurl instead of its internal equivalent /// with a frequent interval. While data is being transferred it will be /// called very frequently, and during slow periods like when nothing is /// being transferred it can slow down to about one call per second. /// /// The callback gets told how much data libcurl will transfer and has /// transferred, in number of bytes. The first argument is the total number /// of bytes libcurl expects to download in this transfer. The second /// argument is the number of bytes downloaded so far. The third argument is /// the total number of bytes libcurl expects to upload in this transfer. /// The fourth argument is the number of bytes uploaded so far. /// /// Unknown/unused argument values passed to the callback will be set to /// zero (like if you only download data, the upload size will remain 0). /// Many times the callback will be called one or more times first, before /// it knows the data sizes so a program must be made to handle that. /// /// Returning `false` from this callback will cause libcurl to abort the /// transfer and return `is_aborted_by_callback`. /// /// If you transfer data with the multi interface, this function will not be /// called during periods of idleness unless you call the appropriate /// libcurl function that performs transfers. /// /// `progress` must be set to `true` to make this function actually get /// called. /// /// By default this function calls an internal method and corresponds to /// `CURLOPT_PROGRESSFUNCTION` and `CURLOPT_PROGRESSDATA`. fn progress(&mut self, dltotal: f64, dlnow: f64, ultotal: f64, ulnow: f64) -> bool { drop((dltotal, dlnow, ultotal, ulnow)); true } /// Callback to SSL context /// /// This callback function gets called by libcurl just before the /// initialization of an SSL connection after having processed all /// other SSL related options to give a last chance to an /// application to modify the behaviour of the SSL /// initialization. The `ssl_ctx` parameter is actually a pointer /// to the SSL library's SSL_CTX. If an error is returned from the /// callback no attempt to establish a connection is made and the /// perform operation will return the callback's error code. /// /// This function will get called on all new connections made to a /// server, during the SSL negotiation. The SSL_CTX pointer will /// be a new one every time. /// /// To use this properly, a non-trivial amount of knowledge of /// your SSL library is necessary. For example, you can use this /// function to call library-specific callbacks to add additional /// validation code for certificates, and even to change the /// actual URI of a HTTPS request. /// /// By default this function calls an internal method and /// corresponds to `CURLOPT_SSL_CTX_FUNCTION` and /// `CURLOPT_SSL_CTX_DATA`. /// /// Note that this callback is not guaranteed to be called, not all versions /// of libcurl support calling this callback. fn ssl_ctx(&mut self, cx: *mut c_void) -> Result<(), Error> { // By default, if we're on an OpenSSL enabled libcurl and we're on // Windows, add the system's certificate store to OpenSSL's certificate // store. ssl_ctx(cx) } /// Callback to open sockets for libcurl. /// /// This callback function gets called by libcurl instead of the socket(2) /// call. The callback function should return the newly created socket /// or `None` in case no connection could be established or another /// error was detected. Any additional `setsockopt(2)` calls can of course /// be done on the socket at the user's discretion. A `None` return /// value from the callback function will signal an unrecoverable error to /// libcurl and it will return `is_couldnt_connect` from the function that /// triggered this callback. /// /// By default this function opens a standard socket and /// corresponds to `CURLOPT_OPENSOCKETFUNCTION `. fn open_socket(&mut self, family: c_int, socktype: c_int, protocol: c_int) -> Option<curl_sys::curl_socket_t> { // Note that we override this to calling a function in `socket2` to // ensure that we open all sockets with CLOEXEC. Otherwise if we rely on // libcurl to open sockets it won't use CLOEXEC. return Socket::new(family.into(), socktype.into(), Some(protocol.into())) .ok() .map(cvt); #[cfg(unix)] fn cvt(socket: Socket) -> curl_sys::curl_socket_t { use std::os::unix::prelude::*; socket.into_raw_fd() } #[cfg(windows)] fn cvt(socket: Socket) -> curl_sys::curl_socket_t { use std::os::windows::prelude::*; socket.into_raw_socket() } } } pub fn debug(kind: InfoType, data: &[u8]) { let out = io::stderr(); let prefix = match kind { InfoType::Text => "*", InfoType::HeaderIn => "<", InfoType::HeaderOut => ">", InfoType::DataIn | InfoType::SslDataIn => "{", InfoType::DataOut | InfoType::SslDataOut => "}", InfoType::__Nonexhaustive => " ", }; let mut out = out.lock(); drop(write!(out, "{} ", prefix)); match str::from_utf8(data) { Ok(s) => drop(out.write_all(s.as_bytes())), Err(_) => drop(write!(out, "({} bytes of data)\n", data.len())), } } pub fn ssl_ctx(cx: *mut c_void) -> Result<(), Error> { windows::add_certs_to_context(cx); Ok(()) } /// Raw bindings to a libcurl "easy session". /// /// This type corresponds to the `CURL` type in libcurl, and is probably what /// you want for just sending off a simple HTTP request and fetching a response. /// Each easy handle can be thought of as a large builder before calling the /// final `perform` function. /// /// There are many many configuration options for each `Easy2` handle, and they /// should all have their own documentation indicating what it affects and how /// it interacts with other options. Some implementations of libcurl can use /// this handle to interact with many different protocols, although by default /// this crate only guarantees the HTTP/HTTPS protocols working. /// /// Note that almost all methods on this structure which configure various /// properties return a `Result`. This is largely used to detect whether the /// underlying implementation of libcurl actually implements the option being /// requested. If you're linked to a version of libcurl which doesn't support /// the option, then an error will be returned. Some options also perform some /// validation when they're set, and the error is returned through this vector. /// /// Note that historically this library contained an `Easy` handle so this one's /// called `Easy2`. The major difference between the `Easy` type is that an /// `Easy2` structure uses a trait instead of closures for all of the callbacks /// that curl can invoke. The `Easy` type is actually built on top of this /// `Easy` type, and this `Easy2` type can be more flexible in some situations /// due to the generic parameter. /// /// There's not necessarily a right answer for which type is correct to use, but /// as a general rule of thumb `Easy` is typically a reasonable choice for /// synchronous I/O and `Easy2` is a good choice for asynchronous I/O. /// /// # Examples /// /// ``` /// use curl::easy::{Easy2, Handler, WriteError}; /// /// struct Collector(Vec<u8>); /// /// impl Handler for Collector { /// fn write(&mut self, data: &[u8]) -> Result<usize, WriteError> { /// self.0.extend_from_slice(data); /// Ok(data.len()) /// } /// } /// /// let mut easy = Easy2::new(Collector(Vec::new())); /// easy.get(true).unwrap(); /// easy.url("https://www.rust-lang.org/").unwrap(); /// easy.perform().unwrap(); /// /// assert_eq!(easy.response_code().unwrap(), 200); /// let contents = easy.get_ref(); /// println!("{}", String::from_utf8_lossy(&contents.0)); /// ``` pub struct Easy2<H> { inner: Box<Inner<H>>, } struct Inner<H> { handle: *mut curl_sys::CURL, header_list: Option<List>, resolve_list: Option<List>, form: Option<Form>, error_buf: RefCell<Vec<u8>>, handler: H, } unsafe impl<H: Send> Send for Inner<H> {} /// Possible proxy types that libcurl currently understands. #[allow(missing_docs)] #[derive(Debug)] pub enum ProxyType { Http = curl_sys::CURLPROXY_HTTP as isize, Http1 = curl_sys::CURLPROXY_HTTP_1_0 as isize, Socks4 = curl_sys::CURLPROXY_SOCKS4 as isize, Socks5 = curl_sys::CURLPROXY_SOCKS5 as isize, Socks4a = curl_sys::CURLPROXY_SOCKS4A as isize, Socks5Hostname = curl_sys::CURLPROXY_SOCKS5_HOSTNAME as isize, /// Hidden variant to indicate that this enum should not be matched on, it /// may grow over time. #[doc(hidden)] __Nonexhaustive, } /// Possible conditions for the `time_condition` method. #[allow(missing_docs)] #[derive(Debug)] pub enum TimeCondition { None = curl_sys::CURL_TIMECOND_NONE as isize, IfModifiedSince = curl_sys::CURL_TIMECOND_IFMODSINCE as isize, IfUnmodifiedSince = curl_sys::CURL_TIMECOND_IFUNMODSINCE as isize, LastModified = curl_sys::CURL_TIMECOND_LASTMOD as isize, /// Hidden variant to indicate that this enum should not be matched on, it /// may grow over time. #[doc(hidden)] __Nonexhaustive, } /// Possible values to pass to the `ip_resolve` method. #[allow(missing_docs)] #[derive(Debug)] pub enum IpResolve { V4 = curl_sys::CURL_IPRESOLVE_V4 as isize, V6 = curl_sys::CURL_IPRESOLVE_V6 as isize, Any = curl_sys::CURL_IPRESOLVE_WHATEVER as isize, /// Hidden variant to indicate that this enum should not be matched on, it /// may grow over time. #[doc(hidden)] __Nonexhaustive = 500, } /// Possible values to pass to the `http_version` method. #[derive(Debug)] pub enum HttpVersion { /// We don't care what http version to use, and we'd like the library to /// choose the best possible for us. Any = curl_sys::CURL_HTTP_VERSION_NONE as isize, /// Please use HTTP 1.0 in the request V10 = curl_sys::CURL_HTTP_VERSION_1_0 as isize, /// Please use HTTP 1.1 in the request V11 = curl_sys::CURL_HTTP_VERSION_1_1 as isize, /// Please use HTTP 2 in the request /// (Added in CURL 7.33.0) V2 = curl_sys::CURL_HTTP_VERSION_2_0 as isize, /// Use version 2 for HTTPS, version 1.1 for HTTP /// (Added in CURL 7.47.0) V2TLS = curl_sys::CURL_HTTP_VERSION_2TLS as isize, /// Please use HTTP 2 without HTTP/1.1 Upgrade /// (Added in CURL 7.49.0) V2PriorKnowledge = curl_sys::CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE as isize, /// Hidden variant to indicate that this enum should not be matched on, it /// may grow over time. #[doc(hidden)] __Nonexhaustive = 500, } /// Possible values to pass to the `ip_resolve` method. #[allow(missing_docs)] #[derive(Debug)] pub enum SslVersion { Default = curl_sys::CURL_SSLVERSION_DEFAULT as isize, Tlsv1 = curl_sys::CURL_SSLVERSION_TLSv1 as isize, Sslv2 = curl_sys::CURL_SSLVERSION_SSLv2 as isize, Sslv3 = curl_sys::CURL_SSLVERSION_SSLv3 as isize, // Tlsv10 = curl_sys::CURL_SSLVERSION_TLSv1_0 as isize, // Tlsv11 = curl_sys::CURL_SSLVERSION_TLSv1_1 as isize, // Tlsv12 = curl_sys::CURL_SSLVERSION_TLSv1_2 as isize, /// Hidden variant to indicate that this enum should not be matched on, it /// may grow over time. #[doc(hidden)] __Nonexhaustive = 500, } /// Possible return values from the `seek_function` callback. #[derive(Debug)] pub enum SeekResult { /// Indicates that the seek operation was a success Ok = curl_sys::CURL_SEEKFUNC_OK as isize, /// Indicates that the seek operation failed, and the entire request should /// fail as a result. Fail = curl_sys::CURL_SEEKFUNC_FAIL as isize, /// Indicates that although the seek failed libcurl should attempt to keep /// working if possible (for example "seek" through reading). CantSeek = curl_sys::CURL_SEEKFUNC_CANTSEEK as isize, /// Hidden variant to indicate that this enum should not be matched on, it /// may grow over time. #[doc(hidden)] __Nonexhaustive = 500, } /// Possible data chunks that can be witnessed as part of the `debug_function` /// callback. #[derive(Debug)] pub enum InfoType { /// The data is informational text. Text, /// The data is header (or header-like) data received from the peer. HeaderIn, /// The data is header (or header-like) data sent to the peer. HeaderOut, /// The data is protocol data received from the peer. DataIn, /// The data is protocol data sent to the peer. DataOut, /// The data is SSL/TLS (binary) data received from the peer. SslDataIn, /// The data is SSL/TLS (binary) data sent to the peer. SslDataOut, /// Hidden variant to indicate that this enum should not be matched on, it /// may grow over time. #[doc(hidden)] __Nonexhaustive, } /// Possible error codes that can be returned from the `read_function` callback. #[derive(Debug)] pub enum ReadError { /// Indicates that the connection should be aborted immediately Abort, /// Indicates that reading should be paused until `unpause` is called. Pause, /// Hidden variant to indicate that this enum should not be matched on, it /// may grow over time. #[doc(hidden)] __Nonexhaustive, } /// Possible error codes that can be returned from the `write_function` callback. #[derive(Debug)] pub enum WriteError { /// Indicates that reading should be paused until `unpause` is called. Pause, /// Hidden variant to indicate that this enum should not be matched on, it /// may grow over time. #[doc(hidden)] __Nonexhaustive, } /// Options for `.netrc` parsing. #[derive(Debug)] pub enum NetRc { /// Ignoring `.netrc` file and use information from url /// /// This option is default Ignored = curl_sys::CURL_NETRC_IGNORED as isize, /// The use of your `~/.netrc` file is optional, and information in the URL is to be /// preferred. The file will be scanned for the host and user name (to find the password only) /// or for the host only, to find the first user name and password after that machine, which /// ever information is not specified in the URL. Optional = curl_sys::CURL_NETRC_OPTIONAL as isize, /// This value tells the library that use of the file is required, to ignore the information in /// the URL, and to search the file for the host only. Required = curl_sys::CURL_NETRC_REQUIRED as isize, } /// Structure which stores possible authentication methods to get passed to /// `http_auth` and `proxy_auth`. #[derive(Clone)] pub struct Auth { bits: c_long, } /// Structure which stores possible ssl options to pass to `ssl_options`. #[derive(Clone)] pub struct SslOpt { bits: c_long, } impl<H: Handler> Easy2<H> { /// Creates a new "easy" handle which is the core of almost all operations /// in libcurl. /// /// To use a handle, applications typically configure a number of options /// followed by a call to `perform`. Options are preserved across calls to /// `perform` and need to be reset manually (or via the `reset` method) if /// this is not desired. pub fn new(handler: H) -> Easy2<H> { ::init(); unsafe { let handle = curl_sys::curl_easy_init(); assert!(!handle.is_null()); let mut ret = Easy2 { inner: Box::new(Inner { handle: handle, header_list: None, resolve_list: None, form: None, error_buf: RefCell::new(vec![0; curl_sys::CURL_ERROR_SIZE]), handler: handler, }), }; ret.default_configure(); return ret } } /// Re-initializes this handle to the default values. /// /// This puts the handle to the same state as it was in when it was just /// created. This does, however, keep live connections, the session id /// cache, the dns cache, and cookies. pub fn reset(&mut self) { unsafe { curl_sys::curl_easy_reset(self.inner.handle); } self.default_configure(); } fn default_configure(&mut self) { self.setopt_ptr(curl_sys::CURLOPT_ERRORBUFFER, self.inner.error_buf.borrow().as_ptr() as *const _) .expect("failed to set error buffer"); let _ = self.signal(false); self.ssl_configure(); let ptr = &*self.inner as *const _ as *const _; let cb: extern fn(*mut c_char, size_t, size_t, *mut c_void) -> size_t = header_cb::<H>; self.setopt_ptr(curl_sys::CURLOPT_HEADERFUNCTION, cb as *const _) .expect("failed to set header callback"); self.setopt_ptr(curl_sys::CURLOPT_HEADERDATA, ptr) .expect("failed to set header callback"); let cb: curl_sys::curl_write_callback = write_cb::<H>; self.setopt_ptr(curl_sys::CURLOPT_WRITEFUNCTION, cb as *const _) .expect("failed to set write callback"); self.setopt_ptr(curl_sys::CURLOPT_WRITEDATA, ptr) .expect("failed to set write callback"); let cb: curl_sys::curl_read_callback = read_cb::<H>; self.setopt_ptr(curl_sys::CURLOPT_READFUNCTION, cb as *const _) .expect("failed to set read callback"); self.setopt_ptr(curl_sys::CURLOPT_READDATA, ptr) .expect("failed to set read callback"); let cb: curl_sys::curl_seek_callback = seek_cb::<H>; self.setopt_ptr(curl_sys::CURLOPT_SEEKFUNCTION, cb as *const _) .expect("failed to set seek callback"); self.setopt_ptr(curl_sys::CURLOPT_SEEKDATA, ptr) .expect("failed to set seek callback"); let cb: curl_sys::curl_progress_callback = progress_cb::<H>; self.setopt_ptr(curl_sys::CURLOPT_PROGRESSFUNCTION, cb as *const _) .expect("failed to set progress callback"); self.setopt_ptr(curl_sys::CURLOPT_PROGRESSDATA, ptr) .expect("failed to set progress callback"); let cb: curl_sys::curl_debug_callback = debug_cb::<H>; self.setopt_ptr(curl_sys::CURLOPT_DEBUGFUNCTION, cb as *const _) .expect("failed to set debug callback"); self.setopt_ptr(curl_sys::CURLOPT_DEBUGDATA, ptr) .expect("failed to set debug callback"); let cb: curl_sys::curl_ssl_ctx_callback = ssl_ctx_cb::<H>; drop(self.setopt_ptr(curl_sys::CURLOPT_SSL_CTX_FUNCTION, cb as *const _)); drop(self.setopt_ptr(curl_sys::CURLOPT_SSL_CTX_DATA, ptr)); let cb: curl_sys::curl_opensocket_callback = opensocket_cb::<H>; self.setopt_ptr(curl_sys::CURLOPT_OPENSOCKETFUNCTION , cb as *const _) .expect("failed to set open socket callback"); self.setopt_ptr(curl_sys::CURLOPT_OPENSOCKETDATA, ptr) .expect("failed to set open socket callback"); } #[cfg(all(unix, not(target_os = "macos"), feature = "ssl"))] fn ssl_configure(&mut self) { let probe = ::openssl_probe::probe(); if let Some(ref path) = probe.cert_file { let _ = self.cainfo(path); } if let Some(ref path) = probe.cert_dir { let _ = self.capath(path); } } #[cfg(not(all(unix, not(target_os = "macos"), feature = "ssl")))] fn ssl_configure(&mut self) {} } impl<H> Easy2<H> { // ========================================================================= // Behavior options /// Configures this handle to have verbose output to help debug protocol /// information. /// /// By default output goes to stderr, but the `stderr` function on this type /// can configure that. You can also use the `debug_function` method to get /// all protocol data sent and received. /// /// By default, this option is `false`. pub fn verbose(&mut self, verbose: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_VERBOSE, verbose as c_long) } /// Indicates whether header information is streamed to the output body of /// this request. /// /// This option is only relevant for protocols which have header metadata /// (like http or ftp). It's not generally possible to extract headers /// from the body if using this method, that use case should be intended for /// the `header_function` method. /// /// To set HTTP headers, use the `http_header` method. /// /// By default, this option is `false` and corresponds to /// `CURLOPT_HEADER`. pub fn show_header(&mut self, show: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_HEADER, show as c_long) } /// Indicates whether a progress meter will be shown for requests done with /// this handle. /// /// This will also prevent the `progress_function` from being called. /// /// By default this option is `false` and corresponds to /// `CURLOPT_NOPROGRESS`. pub fn progress(&mut self, progress: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_NOPROGRESS, (!progress) as c_long) } /// Inform libcurl whether or not it should install signal handlers or /// attempt to use signals to perform library functions. /// /// If this option is disabled then timeouts during name resolution will not /// work unless libcurl is built against c-ares. Note that enabling this /// option, however, may not cause libcurl to work with multiple threads. /// /// By default this option is `false` and corresponds to `CURLOPT_NOSIGNAL`. /// Note that this default is **different than libcurl** as it is intended /// that this library is threadsafe by default. See the [libcurl docs] for /// some more information. /// /// [libcurl docs]: https://curl.haxx.se/libcurl/c/threadsafe.html pub fn signal(&mut self, signal: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_NOSIGNAL, (!signal) as c_long) } /// Indicates whether multiple files will be transferred based on the file /// name pattern. /// /// The last part of a filename uses fnmatch-like pattern matching. /// /// By default this option is `false` and corresponds to /// `CURLOPT_WILDCARDMATCH`. pub fn wildcard_match(&mut self, m: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_WILDCARDMATCH, m as c_long) } /// Provides the unix domain socket which this handle will work with. /// /// The string provided must be unix domain socket -encoded with the format: /// /// ```text /// /path/file.sock /// ``` pub fn unix_socket(&mut self, unix_domain_socket: &str) -> Result<(), Error> { let socket = try!(CString::new(unix_domain_socket)); self.setopt_str(curl_sys::CURLOPT_UNIX_SOCKET_PATH, &socket) } // ========================================================================= // Internal accessors /// Acquires a reference to the underlying handler for events. pub fn get_ref(&self) -> &H { &self.inner.handler } /// Acquires a reference to the underlying handler for events. pub fn get_mut(&mut self) -> &mut H { &mut self.inner.handler } // ========================================================================= // Error options // TODO: error buffer and stderr /// Indicates whether this library will fail on HTTP response codes >= 400. /// /// This method is not fail-safe especially when authentication is involved. /// /// By default this option is `false` and corresponds to /// `CURLOPT_FAILONERROR`. pub fn fail_on_error(&mut self, fail: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_FAILONERROR, fail as c_long) } // ========================================================================= // Network options /// Provides the URL which this handle will work with. /// /// The string provided must be URL-encoded with the format: /// /// ```text /// scheme://host:port/path /// ``` /// /// The syntax is not validated as part of this function and that is /// deferred until later. /// /// By default this option is not set and `perform` will not work until it /// is set. This option corresponds to `CURLOPT_URL`. pub fn url(&mut self, url: &str) -> Result<(), Error> { let url = try!(CString::new(url)); self.setopt_str(curl_sys::CURLOPT_URL, &url) } /// Configures the port number to connect to, instead of the one specified /// in the URL or the default of the protocol. pub fn port(&mut self, port: u16) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_PORT, port as c_long) } // /// Indicates whether sequences of `/../` and `/./` will be squashed or not. // /// // /// By default this option is `false` and corresponds to // /// `CURLOPT_PATH_AS_IS`. // pub fn path_as_is(&mut self, as_is: bool) -> Result<(), Error> { // } /// Provide the URL of a proxy to use. /// /// By default this option is not set and corresponds to `CURLOPT_PROXY`. pub fn proxy(&mut self, url: &str) -> Result<(), Error> { let url = try!(CString::new(url)); self.setopt_str(curl_sys::CURLOPT_PROXY, &url) } /// Provide port number the proxy is listening on. /// /// By default this option is not set (the default port for the proxy /// protocol is used) and corresponds to `CURLOPT_PROXYPORT`. pub fn proxy_port(&mut self, port: u16) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_PROXYPORT, port as c_long) } /// Indicates the type of proxy being used. /// /// By default this option is `ProxyType::Http` and corresponds to /// `CURLOPT_PROXYTYPE`. pub fn proxy_type(&mut self, kind: ProxyType) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_PROXYTYPE, kind as c_long) } /// Provide a list of hosts that should not be proxied to. /// /// This string is a comma-separated list of hosts which should not use the /// proxy specified for connections. A single `*` character is also accepted /// as a wildcard for all hosts. /// /// By default this option is not set and corresponds to /// `CURLOPT_NOPROXY`. pub fn noproxy(&mut self, skip: &str) -> Result<(), Error> { let skip = try!(CString::new(skip)); self.setopt_str(curl_sys::CURLOPT_PROXYTYPE, &skip) } /// Inform curl whether it should tunnel all operations through the proxy. /// /// This essentially means that a `CONNECT` is sent to the proxy for all /// outbound requests. /// /// By default this option is `false` and corresponds to /// `CURLOPT_HTTPPROXYTUNNEL`. pub fn http_proxy_tunnel(&mut self, tunnel: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_HTTPPROXYTUNNEL, tunnel as c_long) } /// Tell curl which interface to bind to for an outgoing network interface. /// /// The interface name, IP address, or host name can be specified here. /// /// By default this option is not set and corresponds to /// `CURLOPT_INTERFACE`. pub fn interface(&mut self, interface: &str) -> Result<(), Error> { let s = try!(CString::new(interface)); self.setopt_str(curl_sys::CURLOPT_INTERFACE, &s) } /// Indicate which port should be bound to locally for this connection. /// /// By default this option is 0 (any port) and corresponds to /// `CURLOPT_LOCALPORT`. pub fn set_local_port(&mut self, port: u16) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_LOCALPORT, port as c_long) } /// Indicates the number of attempts libcurl will perform to find a working /// port number. /// /// By default this option is 1 and corresponds to /// `CURLOPT_LOCALPORTRANGE`. pub fn local_port_range(&mut self, range: u16) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_LOCALPORTRANGE, range as c_long) } /// Sets the timeout of how long name resolves will be kept in memory. /// /// This is distinct from DNS TTL options and is entirely speculative. /// /// By default this option is 60s and corresponds to /// `CURLOPT_DNS_CACHE_TIMEOUT`. pub fn dns_cache_timeout(&mut self, dur: Duration) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_DNS_CACHE_TIMEOUT, dur.as_secs() as c_long) } /// Specify the preferred receive buffer size, in bytes. /// /// This is treated as a request, not an order, and the main point of this /// is that the write callback may get called more often with smaller /// chunks. /// /// By default this option is the maximum write size and corresopnds to /// `CURLOPT_BUFFERSIZE`. pub fn buffer_size(&mut self, size: usize) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_BUFFERSIZE, size as c_long) } // /// Enable or disable TCP Fast Open // /// // /// By default this options defaults to `false` and corresponds to // /// `CURLOPT_TCP_FASTOPEN` // pub fn fast_open(&mut self, enable: bool) -> Result<(), Error> { // } /// Configures whether the TCP_NODELAY option is set, or Nagle's algorithm /// is disabled. /// /// The purpose of Nagle's algorithm is to minimize the number of small /// packet's on the network, and disabling this may be less efficient in /// some situations. /// /// By default this option is `false` and corresponds to /// `CURLOPT_TCP_NODELAY`. pub fn tcp_nodelay(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_TCP_NODELAY, enable as c_long) } /// Configures whether TCP keepalive probes will be sent. /// /// The delay and frequency of these probes is controlled by `tcp_keepidle` /// and `tcp_keepintvl`. /// /// By default this option is `false` and corresponds to /// `CURLOPT_TCP_KEEPALIVE`. pub fn tcp_keepalive(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_TCP_KEEPALIVE, enable as c_long) } /// Configures the TCP keepalive idle time wait. /// /// This is the delay, after which the connection is idle, keepalive probes /// will be sent. Not all operating systems support this. /// /// By default this corresponds to `CURLOPT_TCP_KEEPIDLE`. pub fn tcp_keepidle(&mut self, amt: Duration) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_TCP_KEEPIDLE, amt.as_secs() as c_long) } /// Configures the delay between keepalive probes. /// /// By default this corresponds to `CURLOPT_TCP_KEEPINTVL`. pub fn tcp_keepintvl(&mut self, amt: Duration) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_TCP_KEEPINTVL, amt.as_secs() as c_long) } /// Configures the scope for local IPv6 addresses. /// /// Sets the scope_id value to use when connecting to IPv6 or link-local /// addresses. /// /// By default this value is 0 and corresponds to `CURLOPT_ADDRESS_SCOPE` pub fn address_scope(&mut self, scope: u32) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_ADDRESS_SCOPE, scope as c_long) } // ========================================================================= // Names and passwords /// Configures the username to pass as authentication for this connection. /// /// By default this value is not set and corresponds to `CURLOPT_USERNAME`. pub fn username(&mut self, user: &str) -> Result<(), Error> { let user = try!(CString::new(user)); self.setopt_str(curl_sys::CURLOPT_USERNAME, &user) } /// Configures the password to pass as authentication for this connection. /// /// By default this value is not set and corresponds to `CURLOPT_PASSWORD`. pub fn password(&mut self, pass: &str) -> Result<(), Error> { let pass = try!(CString::new(pass)); self.setopt_str(curl_sys::CURLOPT_PASSWORD, &pass) } /// Set HTTP server authentication methods to try /// /// If more than one method is set, libcurl will first query the site to see /// which authentication methods it supports and then pick the best one you /// allow it to use. For some methods, this will induce an extra network /// round-trip. Set the actual name and password with the `password` and /// `username` methods. /// /// For authentication with a proxy, see `proxy_auth`. /// /// By default this value is basic and corresponds to `CURLOPT_HTTPAUTH`. pub fn http_auth(&mut self, auth: &Auth) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_HTTPAUTH, auth.bits) } /// Configures the proxy username to pass as authentication for this /// connection. /// /// By default this value is not set and corresponds to /// `CURLOPT_PROXYUSERNAME`. pub fn proxy_username(&mut self, user: &str) -> Result<(), Error> { let user = try!(CString::new(user)); self.setopt_str(curl_sys::CURLOPT_PROXYUSERNAME, &user) } /// Configures the proxy password to pass as authentication for this /// connection. /// /// By default this value is not set and corresponds to /// `CURLOPT_PROXYPASSWORD`. pub fn proxy_password(&mut self, pass: &str) -> Result<(), Error> { let pass = try!(CString::new(pass)); self.setopt_str(curl_sys::CURLOPT_PROXYPASSWORD, &pass) } /// Set HTTP proxy authentication methods to try /// /// If more than one method is set, libcurl will first query the site to see /// which authentication methods it supports and then pick the best one you /// allow it to use. For some methods, this will induce an extra network /// round-trip. Set the actual name and password with the `proxy_password` /// and `proxy_username` methods. /// /// By default this value is basic and corresponds to `CURLOPT_PROXYAUTH`. pub fn proxy_auth(&mut self, auth: &Auth) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_PROXYAUTH, auth.bits) } /// Enable .netrc parsing /// /// By default the .netrc file is ignored and corresponds to `CURL_NETRC_IGNORED`. pub fn netrc(&mut self, netrc: NetRc) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_NETRC, netrc as c_long) } // ========================================================================= // HTTP Options /// Indicates whether the referer header is automatically updated /// /// By default this option is `false` and corresponds to /// `CURLOPT_AUTOREFERER`. pub fn autoreferer(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_AUTOREFERER, enable as c_long) } /// Enables automatic decompression of HTTP downloads. /// /// Sets the contents of the Accept-Encoding header sent in an HTTP request. /// This enables decoding of a response with Content-Encoding. /// /// Currently supported encoding are `identity`, `zlib`, and `gzip`. A /// zero-length string passed in will send all accepted encodings. /// /// By default this option is not set and corresponds to /// `CURLOPT_ACCEPT_ENCODING`. pub fn accept_encoding(&mut self, encoding: &str) -> Result<(), Error> { let encoding = try!(CString::new(encoding)); self.setopt_str(curl_sys::CURLOPT_ACCEPT_ENCODING, &encoding) } /// Request the HTTP Transfer Encoding. /// /// By default this option is `false` and corresponds to /// `CURLOPT_TRANSFER_ENCODING`. pub fn transfer_encoding(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_TRANSFER_ENCODING, enable as c_long) } /// Follow HTTP 3xx redirects. /// /// Indicates whether any `Location` headers in the response should get /// followed. /// /// By default this option is `false` and corresponds to /// `CURLOPT_FOLLOWLOCATION`. pub fn follow_location(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_FOLLOWLOCATION, enable as c_long) } /// Send credentials to hosts other than the first as well. /// /// Sends username/password credentials even when the host changes as part /// of a redirect. /// /// By default this option is `false` and corresponds to /// `CURLOPT_UNRESTRICTED_AUTH`. pub fn unrestricted_auth(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_UNRESTRICTED_AUTH, enable as c_long) } /// Set the maximum number of redirects allowed. /// /// A value of 0 will refuse any redirect. /// /// By default this option is `-1` (unlimited) and corresponds to /// `CURLOPT_MAXREDIRS`. pub fn max_redirections(&mut self, max: u32) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_MAXREDIRS, max as c_long) } // TODO: post_redirections /// Make an HTTP PUT request. /// /// By default this option is `false` and corresponds to `CURLOPT_PUT`. pub fn put(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_PUT, enable as c_long) } /// Make an HTTP POST request. /// /// This will also make the library use the /// `Content-Type: application/x-www-form-urlencoded` header. /// /// POST data can be specified through `post_fields` or by specifying a read /// function. /// /// By default this option is `false` and corresponds to `CURLOPT_POST`. pub fn post(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_POST, enable as c_long) } /// Configures the data that will be uploaded as part of a POST. /// /// Note that the data is copied into this handle and if that's not desired /// then the read callbacks can be used instead. /// /// By default this option is not set and corresponds to /// `CURLOPT_COPYPOSTFIELDS`. pub fn post_fields_copy(&mut self, data: &[u8]) -> Result<(), Error> { // Set the length before the pointer so libcurl knows how much to read try!(self.post_field_size(data.len() as u64)); self.setopt_ptr(curl_sys::CURLOPT_COPYPOSTFIELDS, data.as_ptr() as *const _) } /// Configures the size of data that's going to be uploaded as part of a /// POST operation. /// /// This is called automaticsally as part of `post_fields` and should only /// be called if data is being provided in a read callback (and even then /// it's optional). /// /// By default this option is not set and corresponds to /// `CURLOPT_POSTFIELDSIZE_LARGE`. pub fn post_field_size(&mut self, size: u64) -> Result<(), Error> { // Clear anything previous to ensure we don't read past a buffer try!(self.setopt_ptr(curl_sys::CURLOPT_POSTFIELDS, 0 as *const _)); self.setopt_off_t(curl_sys::CURLOPT_POSTFIELDSIZE_LARGE, size as curl_sys::curl_off_t) } /// Tells libcurl you want a multipart/formdata HTTP POST to be made and you /// instruct what data to pass on to the server in the `form` argument. /// /// By default this option is set to null and corresponds to /// `CURLOPT_HTTPPOST`. pub fn httppost(&mut self, form: Form) -> Result<(), Error> { try!(self.setopt_ptr(curl_sys::CURLOPT_HTTPPOST, form::raw(&form) as *const _)); self.inner.form = Some(form); Ok(()) } /// Sets the HTTP referer header /// /// By default this option is not set and corresponds to `CURLOPT_REFERER`. pub fn referer(&mut self, referer: &str) -> Result<(), Error> { let referer = try!(CString::new(referer)); self.setopt_str(curl_sys::CURLOPT_REFERER, &referer) } /// Sets the HTTP user-agent header /// /// By default this option is not set and corresponds to /// `CURLOPT_USERAGENT`. pub fn useragent(&mut self, useragent: &str) -> Result<(), Error> { let useragent = try!(CString::new(useragent)); self.setopt_str(curl_sys::CURLOPT_USERAGENT, &useragent) } /// Add some headers to this HTTP request. /// /// If you add a header that is otherwise used internally, the value here /// takes precedence. If a header is added with no content (like `Accept:`) /// the internally the header will get disabled. To add a header with no /// content, use the form `MyHeader;` (not the trailing semicolon). /// /// Headers must not be CRLF terminated. Many replaced headers have common /// shortcuts which should be prefered. /// /// By default this option is not set and corresponds to /// `CURLOPT_HTTPHEADER` /// /// # Examples /// /// ``` /// use curl::easy::{Easy, List}; /// /// let mut list = List::new(); /// list.append("Foo: bar").unwrap(); /// list.append("Bar: baz").unwrap(); /// /// let mut handle = Easy::new(); /// handle.url("https://www.rust-lang.org/").unwrap(); /// handle.http_headers(list).unwrap(); /// handle.perform().unwrap(); /// ``` pub fn http_headers(&mut self, list: List) -> Result<(), Error> { let ptr = list::raw(&list); self.inner.header_list = Some(list); self.setopt_ptr(curl_sys::CURLOPT_HTTPHEADER, ptr as *const _) } // /// Add some headers to send to the HTTP proxy. // /// // /// This function is essentially the same as `http_headers`. // /// // /// By default this option is not set and corresponds to // /// `CURLOPT_PROXYHEADER` // pub fn proxy_headers(&mut self, list: &'a List) -> Result<(), Error> { // self.setopt_ptr(curl_sys::CURLOPT_PROXYHEADER, list.raw as *const _) // } /// Set the contents of the HTTP Cookie header. /// /// Pass a string of the form `name=contents` for one cookie value or /// `name1=val1; name2=val2` for multiple values. /// /// Using this option multiple times will only make the latest string /// override the previous ones. This option will not enable the cookie /// engine, use `cookie_file` or `cookie_jar` to do that. /// /// By default this option is not set and corresponds to `CURLOPT_COOKIE`. pub fn cookie(&mut self, cookie: &str) -> Result<(), Error> { let cookie = try!(CString::new(cookie)); self.setopt_str(curl_sys::CURLOPT_COOKIE, &cookie) } /// Set the file name to read cookies from. /// /// The cookie data can be in either the old Netscape / Mozilla cookie data /// format or just regular HTTP headers (Set-Cookie style) dumped to a file. /// /// This also enables the cookie engine, making libcurl parse and send /// cookies on subsequent requests with this handle. /// /// Given an empty or non-existing file or by passing the empty string ("") /// to this option, you can enable the cookie engine without reading any /// initial cookies. /// /// If you use this option multiple times, you just add more files to read. /// Subsequent files will add more cookies. /// /// By default this option is not set and corresponds to /// `CURLOPT_COOKIEFILE`. pub fn cookie_file<P: AsRef<Path>>(&mut self, file: P) -> Result<(), Error> { self.setopt_path(curl_sys::CURLOPT_COOKIEFILE, file.as_ref()) } /// Set the file name to store cookies to. /// /// This will make libcurl write all internally known cookies to the file /// when this handle is dropped. If no cookies are known, no file will be /// created. Specify "-" as filename to instead have the cookies written to /// stdout. Using this option also enables cookies for this session, so if /// you for example follow a location it will make matching cookies get sent /// accordingly. /// /// Note that libcurl doesn't read any cookies from the cookie jar. If you /// want to read cookies from a file, use `cookie_file`. /// /// By default this option is not set and corresponds to /// `CURLOPT_COOKIEJAR`. pub fn cookie_jar<P: AsRef<Path>>(&mut self, file: P) -> Result<(), Error> { self.setopt_path(curl_sys::CURLOPT_COOKIEJAR, file.as_ref()) } /// Start a new cookie session /// /// Marks this as a new cookie "session". It will force libcurl to ignore /// all cookies it is about to load that are "session cookies" from the /// previous session. By default, libcurl always stores and loads all /// cookies, independent if they are session cookies or not. Session cookies /// are cookies without expiry date and they are meant to be alive and /// existing for this "session" only. /// /// By default this option is `false` and corresponds to /// `CURLOPT_COOKIESESSION`. pub fn cookie_session(&mut self, session: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_COOKIESESSION, session as c_long) } /// Add to or manipulate cookies held in memory. /// /// Such a cookie can be either a single line in Netscape / Mozilla format /// or just regular HTTP-style header (Set-Cookie: ...) format. This will /// also enable the cookie engine. This adds that single cookie to the /// internal cookie store. /// /// Exercise caution if you are using this option and multiple transfers may /// occur. If you use the Set-Cookie format and don't specify a domain then /// the cookie is sent for any domain (even after redirects are followed) /// and cannot be modified by a server-set cookie. If a server sets a cookie /// of the same name (or maybe you've imported one) then both will be sent /// on a future transfer to that server, likely not what you intended. /// address these issues set a domain in Set-Cookie or use the Netscape /// format. /// /// Additionally, there are commands available that perform actions if you /// pass in these exact strings: /// /// * "ALL" - erases all cookies held in memory /// * "SESS" - erases all session cookies held in memory /// * "FLUSH" - write all known cookies to the specified cookie jar /// * "RELOAD" - reread all cookies from the cookie file /// /// By default this options corresponds to `CURLOPT_COOKIELIST` pub fn cookie_list(&mut self, cookie: &str) -> Result<(), Error> { let cookie = try!(CString::new(cookie)); self.setopt_str(curl_sys::CURLOPT_COOKIELIST, &cookie) } /// Ask for a HTTP GET request. /// /// By default this option is `false` and corresponds to `CURLOPT_HTTPGET`. pub fn get(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_HTTPGET, enable as c_long) } // /// Ask for a HTTP GET request. // /// // /// By default this option is `false` and corresponds to `CURLOPT_HTTPGET`. // pub fn http_version(&mut self, vers: &str) -> Result<(), Error> { // self.setopt_long(curl_sys::CURLOPT_HTTPGET, enable as c_long) // } /// Ignore the content-length header. /// /// By default this option is `false` and corresponds to /// `CURLOPT_IGNORE_CONTENT_LENGTH`. pub fn ignore_content_length(&mut self, ignore: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_IGNORE_CONTENT_LENGTH, ignore as c_long) } /// Enable or disable HTTP content decoding. /// /// By default this option is `true` and corresponds to /// `CURLOPT_HTTP_CONTENT_DECODING`. pub fn http_content_decoding(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_HTTP_CONTENT_DECODING, enable as c_long) } /// Enable or disable HTTP transfer decoding. /// /// By default this option is `true` and corresponds to /// `CURLOPT_HTTP_TRANSFER_DECODING`. pub fn http_transfer_decoding(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_HTTP_TRANSFER_DECODING, enable as c_long) } // /// Timeout for the Expect: 100-continue response // /// // /// By default this option is 1s and corresponds to // /// `CURLOPT_EXPECT_100_TIMEOUT_MS`. // pub fn expect_100_timeout(&mut self, enable: bool) -> Result<(), Error> { // self.setopt_long(curl_sys::CURLOPT_HTTP_TRANSFER_DECODING, // enable as c_long) // } // /// Wait for pipelining/multiplexing. // /// // /// Tells libcurl to prefer to wait for a connection to confirm or deny that // /// it can do pipelining or multiplexing before continuing. // /// // /// When about to perform a new transfer that allows pipelining or // /// multiplexing, libcurl will check for existing connections to re-use and // /// pipeline on. If no such connection exists it will immediately continue // /// and create a fresh new connection to use. // /// // /// By setting this option to `true` - having `pipeline` enabled for the // /// multi handle this transfer is associated with - libcurl will instead // /// wait for the connection to reveal if it is possible to // /// pipeline/multiplex on before it continues. This enables libcurl to much // /// better keep the number of connections to a minimum when using pipelining // /// or multiplexing protocols. // /// // /// The effect thus becomes that with this option set, libcurl prefers to // /// wait and re-use an existing connection for pipelining rather than the // /// opposite: prefer to open a new connection rather than waiting. // /// // /// The waiting time is as long as it takes for the connection to get up and // /// for libcurl to get the necessary response back that informs it about its // /// protocol and support level. // pub fn http_pipewait(&mut self, enable: bool) -> Result<(), Error> { // } // ========================================================================= // Protocol Options /// Indicates the range that this request should retrieve. /// /// The string provided should be of the form `N-M` where either `N` or `M` /// can be left out. For HTTP transfers multiple ranges separated by commas /// are also accepted. /// /// By default this option is not set and corresponds to `CURLOPT_RANGE`. pub fn range(&mut self, range: &str) -> Result<(), Error> { let range = try!(CString::new(range)); self.setopt_str(curl_sys::CURLOPT_RANGE, &range) } /// Set a point to resume transfer from /// /// Specify the offset in bytes you want the transfer to start from. /// /// By default this option is 0 and corresponds to /// `CURLOPT_RESUME_FROM_LARGE`. pub fn resume_from(&mut self, from: u64) -> Result<(), Error> { self.setopt_off_t(curl_sys::CURLOPT_RESUME_FROM_LARGE, from as curl_sys::curl_off_t) } /// Set a custom request string /// /// Specifies that a custom request will be made (e.g. a custom HTTP /// method). This does not change how libcurl performs internally, just /// changes the string sent to the server. /// /// By default this option is not set and corresponds to /// `CURLOPT_CUSTOMREQUEST`. pub fn custom_request(&mut self, request: &str) -> Result<(), Error> { let request = try!(CString::new(request)); self.setopt_str(curl_sys::CURLOPT_CUSTOMREQUEST, &request) } /// Get the modification time of the remote resource /// /// If true, libcurl will attempt to get the modification time of the /// remote document in this operation. This requires that the remote server /// sends the time or replies to a time querying command. The `filetime` /// function can be used after a transfer to extract the received time (if /// any). /// /// By default this option is `false` and corresponds to `CURLOPT_FILETIME` pub fn fetch_filetime(&mut self, fetch: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_FILETIME, fetch as c_long) } /// Indicate whether to download the request without getting the body /// /// This is useful, for example, for doing a HEAD request. /// /// By default this option is `false` and corresponds to `CURLOPT_NOBODY`. pub fn nobody(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_NOBODY, enable as c_long) } /// Set the size of the input file to send off. /// /// By default this option is not set and corresponds to /// `CURLOPT_INFILESIZE_LARGE`. pub fn in_filesize(&mut self, size: u64) -> Result<(), Error> { self.setopt_off_t(curl_sys::CURLOPT_INFILESIZE_LARGE, size as curl_sys::curl_off_t) } /// Enable or disable data upload. /// /// This means that a PUT request will be made for HTTP and probably wants /// to be combined with the read callback as well as the `in_filesize` /// method. /// /// By default this option is `false` and corresponds to `CURLOPT_UPLOAD`. pub fn upload(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_UPLOAD, enable as c_long) } /// Configure the maximum file size to download. /// /// By default this option is not set and corresponds to /// `CURLOPT_MAXFILESIZE_LARGE`. pub fn max_filesize(&mut self, size: u64) -> Result<(), Error> { self.setopt_off_t(curl_sys::CURLOPT_MAXFILESIZE_LARGE, size as curl_sys::curl_off_t) } /// Selects a condition for a time request. /// /// This value indicates how the `time_value` option is interpreted. /// /// By default this option is not set and corresponds to /// `CURLOPT_TIMECONDITION`. pub fn time_condition(&mut self, cond: TimeCondition) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_TIMECONDITION, cond as c_long) } /// Sets the time value for a conditional request. /// /// The value here should be the number of seconds elapsed since January 1, /// 1970. To pass how to interpret this value, use `time_condition`. /// /// By default this option is not set and corresponds to /// `CURLOPT_TIMEVALUE`. pub fn time_value(&mut self, val: i64) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_TIMEVALUE, val as c_long) } // ========================================================================= // Connection Options /// Set maximum time the request is allowed to take. /// /// Normally, name lookups can take a considerable time and limiting /// operations to less than a few minutes risk aborting perfectly normal /// operations. /// /// If libcurl is built to use the standard system name resolver, that /// portion of the transfer will still use full-second resolution for /// timeouts with a minimum timeout allowed of one second. /// /// In unix-like systems, this might cause signals to be used unless /// `nosignal` is set. /// /// Since this puts a hard limit for how long a request is allowed to /// take, it has limited use in dynamic use cases with varying transfer /// times. You are then advised to explore `low_speed_limit`, /// `low_speed_time` or using `progress_function` to implement your own /// timeout logic. /// /// By default this option is not set and corresponds to /// `CURLOPT_TIMEOUT_MS`. pub fn timeout(&mut self, timeout: Duration) -> Result<(), Error> { // TODO: checked arithmetic and casts // TODO: use CURLOPT_TIMEOUT if the timeout is too great let ms = timeout.as_secs() * 1000 + (timeout.subsec_nanos() / 1_000_000) as u64; self.setopt_long(curl_sys::CURLOPT_TIMEOUT_MS, ms as c_long) } /// Set the low speed limit in bytes per second. /// /// This specifies the average transfer speed in bytes per second that the /// transfer should be below during `low_speed_time` for libcurl to consider /// it to be too slow and abort. /// /// By default this option is not set and corresponds to /// `CURLOPT_LOW_SPEED_LIMIT`. pub fn low_speed_limit(&mut self, limit: u32) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_LOW_SPEED_LIMIT, limit as c_long) } /// Set the low speed time period. /// /// Specifies the window of time for which if the transfer rate is below /// `low_speed_limit` the request will be aborted. /// /// By default this option is not set and corresponds to /// `CURLOPT_LOW_SPEED_TIME`. pub fn low_speed_time(&mut self, dur: Duration) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_LOW_SPEED_TIME, dur.as_secs() as c_long) } /// Rate limit data upload speed /// /// If an upload exceeds this speed (counted in bytes per second) on /// cumulative average during the transfer, the transfer will pause to keep /// the average rate less than or equal to the parameter value. /// /// By default this option is not set (unlimited speed) and corresponds to /// `CURLOPT_MAX_SEND_SPEED_LARGE`. pub fn max_send_speed(&mut self, speed: u64) -> Result<(), Error> { self.setopt_off_t(curl_sys::CURLOPT_MAX_SEND_SPEED_LARGE, speed as curl_sys::curl_off_t) } /// Rate limit data download speed /// /// If a download exceeds this speed (counted in bytes per second) on /// cumulative average during the transfer, the transfer will pause to keep /// the average rate less than or equal to the parameter value. /// /// By default this option is not set (unlimited speed) and corresponds to /// `CURLOPT_MAX_RECV_SPEED_LARGE`. pub fn max_recv_speed(&mut self, speed: u64) -> Result<(), Error> { self.setopt_off_t(curl_sys::CURLOPT_MAX_RECV_SPEED_LARGE, speed as curl_sys::curl_off_t) } /// Set the maximum connection cache size. /// /// The set amount will be the maximum number of simultaneously open /// persistent connections that libcurl may cache in the pool associated /// with this handle. The default is 5, and there isn't much point in /// changing this value unless you are perfectly aware of how this works and /// changes libcurl's behaviour. This concerns connections using any of the /// protocols that support persistent connections. /// /// When reaching the maximum limit, curl closes the oldest one in the cache /// to prevent increasing the number of open connections. /// /// By default this option is set to 5 and corresponds to /// `CURLOPT_MAXCONNECTS` pub fn max_connects(&mut self, max: u32) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_MAXCONNECTS, max as c_long) } /// Force a new connection to be used. /// /// Makes the next transfer use a new (fresh) connection by force instead of /// trying to re-use an existing one. This option should be used with /// caution and only if you understand what it does as it may seriously /// impact performance. /// /// By default this option is `false` and corresponds to /// `CURLOPT_FRESH_CONNECT`. pub fn fresh_connect(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_FRESH_CONNECT, enable as c_long) } /// Make connection get closed at once after use. /// /// Makes libcurl explicitly close the connection when done with the /// transfer. Normally, libcurl keeps all connections alive when done with /// one transfer in case a succeeding one follows that can re-use them. /// This option should be used with caution and only if you understand what /// it does as it can seriously impact performance. /// /// By default this option is `false` and corresponds to /// `CURLOPT_FORBID_REUSE`. pub fn forbid_reuse(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_FORBID_REUSE, enable as c_long) } /// Timeout for the connect phase /// /// This is the maximum time that you allow the connection phase to the /// server to take. This only limits the connection phase, it has no impact /// once it has connected. /// /// By default this value is 300 seconds and corresponds to /// `CURLOPT_CONNECTTIMEOUT_MS`. pub fn connect_timeout(&mut self, timeout: Duration) -> Result<(), Error> { let ms = timeout.as_secs() * 1000 + (timeout.subsec_nanos() / 1_000_000) as u64; self.setopt_long(curl_sys::CURLOPT_CONNECTTIMEOUT_MS, ms as c_long) } /// Specify which IP protocol version to use /// /// Allows an application to select what kind of IP addresses to use when /// resolving host names. This is only interesting when using host names /// that resolve addresses using more than one version of IP. /// /// By default this value is "any" and corresponds to `CURLOPT_IPRESOLVE`. pub fn ip_resolve(&mut self, resolve: IpResolve) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_IPRESOLVE, resolve as c_long) } /// Specify custom host name to IP address resolves. /// /// Allows specifying hostname to IP mappins to use before trying the /// system resolver. /// /// # Examples /// ``` /// use curl::easy::{Easy, List}; /// /// let mut list = List::new(); /// list.append("www.rust-lang.org:443:185.199.108.153").unwrap(); /// /// let mut handle = Easy::new(); /// handle.url("https://www.rust-lang.org/").unwrap(); /// handle.resolve(list).unwrap(); /// handle.perform().unwrap(); /// ``` pub fn resolve(&mut self, list: List) -> Result<(), Error> { let ptr = list::raw(&list); self.inner.resolve_list = Some(list); self.setopt_ptr(curl_sys::CURLOPT_RESOLVE, ptr as *const _) } /// Configure whether to stop when connected to target server /// /// When enabled it tells the library to perform all the required proxy /// authentication and connection setup, but no data transfer, and then /// return. /// /// The option can be used to simply test a connection to a server. /// /// By default this value is `false` and corresponds to /// `CURLOPT_CONNECT_ONLY`. pub fn connect_only(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_CONNECT_ONLY, enable as c_long) } // /// Set interface to speak DNS over. // /// // /// Set the name of the network interface that the DNS resolver should bind // /// to. This must be an interface name (not an address). // /// // /// By default this option is not set and corresponds to // /// `CURLOPT_DNS_INTERFACE`. // pub fn dns_interface(&mut self, interface: &str) -> Result<(), Error> { // let interface = try!(CString::new(interface)); // self.setopt_str(curl_sys::CURLOPT_DNS_INTERFACE, &interface) // } // // /// IPv4 address to bind DNS resolves to // /// // /// Set the local IPv4 address that the resolver should bind to. The // /// argument should be of type char * and contain a single numerical IPv4 // /// address as a string. // /// // /// By default this option is not set and corresponds to // /// `CURLOPT_DNS_LOCAL_IP4`. // pub fn dns_local_ip4(&mut self, ip: &str) -> Result<(), Error> { // let ip = try!(CString::new(ip)); // self.setopt_str(curl_sys::CURLOPT_DNS_LOCAL_IP4, &ip) // } // // /// IPv6 address to bind DNS resolves to // /// // /// Set the local IPv6 address that the resolver should bind to. The // /// argument should be of type char * and contain a single numerical IPv6 // /// address as a string. // /// // /// By default this option is not set and corresponds to // /// `CURLOPT_DNS_LOCAL_IP6`. // pub fn dns_local_ip6(&mut self, ip: &str) -> Result<(), Error> { // let ip = try!(CString::new(ip)); // self.setopt_str(curl_sys::CURLOPT_DNS_LOCAL_IP6, &ip) // } // // /// Set preferred DNS servers. // /// // /// Provides a list of DNS servers to be used instead of the system default. // /// The format of the dns servers option is: // /// // /// ```text // /// host[:port],[host[:port]]... // /// ``` // /// // /// By default this option is not set and corresponds to // /// `CURLOPT_DNS_SERVERS`. // pub fn dns_servers(&mut self, servers: &str) -> Result<(), Error> { // let servers = try!(CString::new(servers)); // self.setopt_str(curl_sys::CURLOPT_DNS_SERVERS, &servers) // } // ========================================================================= // SSL/Security Options /// Sets the SSL client certificate. /// /// The string should be the file name of your client certificate. The /// default format is "P12" on Secure Transport and "PEM" on other engines, /// and can be changed with `ssl_cert_type`. /// /// With NSS or Secure Transport, this can also be the nickname of the /// certificate you wish to authenticate with as it is named in the security /// database. If you want to use a file from the current directory, please /// precede it with "./" prefix, in order to avoid confusion with a /// nickname. /// /// When using a client certificate, you most likely also need to provide a /// private key with `ssl_key`. /// /// By default this option is not set and corresponds to `CURLOPT_SSLCERT`. pub fn ssl_cert<P: AsRef<Path>>(&mut self, cert: P) -> Result<(), Error> { self.setopt_path(curl_sys::CURLOPT_SSLCERT, cert.as_ref()) } /// Specify type of the client SSL certificate. /// /// The string should be the format of your certificate. Supported formats /// are "PEM" and "DER", except with Secure Transport. OpenSSL (versions /// 0.9.3 and later) and Secure Transport (on iOS 5 or later, or OS X 10.7 /// or later) also support "P12" for PKCS#12-encoded files. /// /// By default this option is "PEM" and corresponds to /// `CURLOPT_SSLCERTTYPE`. pub fn ssl_cert_type(&mut self, kind: &str) -> Result<(), Error> { let kind = try!(CString::new(kind)); self.setopt_str(curl_sys::CURLOPT_SSLCERTTYPE, &kind) } /// Specify private keyfile for TLS and SSL client cert. /// /// The string should be the file name of your private key. The default /// format is "PEM" and can be changed with `ssl_key_type`. /// /// (iOS and Mac OS X only) This option is ignored if curl was built against /// Secure Transport. Secure Transport expects the private key to be already /// present in the keychain or PKCS#12 file containing the certificate. /// /// By default this option is not set and corresponds to `CURLOPT_SSLKEY`. pub fn ssl_key<P: AsRef<Path>>(&mut self, key: P) -> Result<(), Error> { self.setopt_path(curl_sys::CURLOPT_SSLKEY, key.as_ref()) } /// Set type of the private key file. /// /// The string should be the format of your private key. Supported formats /// are "PEM", "DER" and "ENG". /// /// The format "ENG" enables you to load the private key from a crypto /// engine. In this case `ssl_key` is used as an identifier passed to /// the engine. You have to set the crypto engine with `ssl_engine`. /// "DER" format key file currently does not work because of a bug in /// OpenSSL. /// /// By default this option is "PEM" and corresponds to /// `CURLOPT_SSLKEYTYPE`. pub fn ssl_key_type(&mut self, kind: &str) -> Result<(), Error> { let kind = try!(CString::new(kind)); self.setopt_str(curl_sys::CURLOPT_SSLKEYTYPE, &kind) } /// Set passphrase to private key. /// /// This will be used as the password required to use the `ssl_key`. /// You never needed a pass phrase to load a certificate but you need one to /// load your private key. /// /// By default this option is not set and corresponds to /// `CURLOPT_KEYPASSWD`. pub fn key_password(&mut self, password: &str) -> Result<(), Error> { let password = try!(CString::new(password)); self.setopt_str(curl_sys::CURLOPT_KEYPASSWD, &password) } /// Set the SSL engine identifier. /// /// This will be used as the identifier for the crypto engine you want to /// use for your private key. /// /// By default this option is not set and corresponds to /// `CURLOPT_SSLENGINE`. pub fn ssl_engine(&mut self, engine: &str) -> Result<(), Error> { let engine = try!(CString::new(engine)); self.setopt_str(curl_sys::CURLOPT_SSLENGINE, &engine) } /// Make this handle's SSL engine the default. /// /// By default this option is not set and corresponds to /// `CURLOPT_SSLENGINE_DEFAULT`. pub fn ssl_engine_default(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_SSLENGINE_DEFAULT, enable as c_long) } // /// Enable TLS false start. // /// // /// This option determines whether libcurl should use false start during the // /// TLS handshake. False start is a mode where a TLS client will start // /// sending application data before verifying the server's Finished message, // /// thus saving a round trip when performing a full handshake. // /// // /// By default this option is not set and corresponds to // /// `CURLOPT_SSL_FALSESTARTE`. // pub fn ssl_false_start(&mut self, enable: bool) -> Result<(), Error> { // self.setopt_long(curl_sys::CURLOPT_SSLENGINE_DEFAULT, enable as c_long) // } /// Set preferred HTTP version. /// /// By default this option is not set and corresponds to /// `CURLOPT_HTTP_VERSION`. pub fn http_version(&mut self, version: HttpVersion) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_HTTP_VERSION, version as c_long) } /// Set preferred TLS/SSL version. /// /// By default this option is not set and corresponds to /// `CURLOPT_SSLVERSION`. pub fn ssl_version(&mut self, version: SslVersion) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_SSLVERSION, version as c_long) } /// Verify the certificate's name against host. /// /// This should be disabled with great caution! It basically disables the /// security features of SSL if it is disabled. /// /// By default this option is set to `true` and corresponds to /// `CURLOPT_SSL_VERIFYHOST`. pub fn ssl_verify_host(&mut self, verify: bool) -> Result<(), Error> { let val = if verify {2} else {0}; self.setopt_long(curl_sys::CURLOPT_SSL_VERIFYHOST, val) } /// Verify the peer's SSL certificate. /// /// This should be disabled with great caution! It basically disables the /// security features of SSL if it is disabled. /// /// By default this option is set to `true` and corresponds to /// `CURLOPT_SSL_VERIFYPEER`. pub fn ssl_verify_peer(&mut self, verify: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_SSL_VERIFYPEER, verify as c_long) } // /// Verify the certificate's status. // /// // /// This option determines whether libcurl verifies the status of the server // /// cert using the "Certificate Status Request" TLS extension (aka. OCSP // /// stapling). // /// // /// By default this option is set to `false` and corresponds to // /// `CURLOPT_SSL_VERIFYSTATUS`. // pub fn ssl_verify_status(&mut self, verify: bool) -> Result<(), Error> { // self.setopt_long(curl_sys::CURLOPT_SSL_VERIFYSTATUS, verify as c_long) // } /// Specify the path to Certificate Authority (CA) bundle /// /// The file referenced should hold one or more certificates to verify the /// peer with. /// /// This option is by default set to the system path where libcurl's cacert /// bundle is assumed to be stored, as established at build time. /// /// If curl is built against the NSS SSL library, the NSS PEM PKCS#11 module /// (libnsspem.so) needs to be available for this option to work properly. /// /// By default this option is the system defaults, and corresponds to /// `CURLOPT_CAINFO`. pub fn cainfo<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { self.setopt_path(curl_sys::CURLOPT_CAINFO, path.as_ref()) } /// Set the issuer SSL certificate filename /// /// Specifies a file holding a CA certificate in PEM format. If the option /// is set, an additional check against the peer certificate is performed to /// verify the issuer is indeed the one associated with the certificate /// provided by the option. This additional check is useful in multi-level /// PKI where one needs to enforce that the peer certificate is from a /// specific branch of the tree. /// /// This option makes sense only when used in combination with the /// `ssl_verify_peer` option. Otherwise, the result of the check is not /// considered as failure. /// /// By default this option is not set and corresponds to /// `CURLOPT_ISSUERCERT`. pub fn issuer_cert<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { self.setopt_path(curl_sys::CURLOPT_ISSUERCERT, path.as_ref()) } /// Specify directory holding CA certificates /// /// Names a directory holding multiple CA certificates to verify the peer /// with. If libcurl is built against OpenSSL, the certificate directory /// must be prepared using the openssl c_rehash utility. This makes sense /// only when used in combination with the `ssl_verify_peer` option. /// /// By default this option is not set and corresponds to `CURLOPT_CAPATH`. pub fn capath<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { self.setopt_path(curl_sys::CURLOPT_CAPATH, path.as_ref()) } /// Specify a Certificate Revocation List file /// /// Names a file with the concatenation of CRL (in PEM format) to use in the /// certificate validation that occurs during the SSL exchange. /// /// When curl is built to use NSS or GnuTLS, there is no way to influence /// the use of CRL passed to help in the verification process. When libcurl /// is built with OpenSSL support, X509_V_FLAG_CRL_CHECK and /// X509_V_FLAG_CRL_CHECK_ALL are both set, requiring CRL check against all /// the elements of the certificate chain if a CRL file is passed. /// /// This option makes sense only when used in combination with the /// `ssl_verify_peer` option. /// /// A specific error code (`is_ssl_crl_badfile`) is defined with the /// option. It is returned when the SSL exchange fails because the CRL file /// cannot be loaded. A failure in certificate verification due to a /// revocation information found in the CRL does not trigger this specific /// error. /// /// By default this option is not set and corresponds to `CURLOPT_CRLFILE`. pub fn crlfile<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { self.setopt_path(curl_sys::CURLOPT_CRLFILE, path.as_ref()) } /// Request SSL certificate information /// /// Enable libcurl's certificate chain info gatherer. With this enabled, /// libcurl will extract lots of information and data about the certificates /// in the certificate chain used in the SSL connection. /// /// By default this option is `false` and corresponds to /// `CURLOPT_CERTINFO`. pub fn certinfo(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_CERTINFO, enable as c_long) } // /// Set pinned public key. // /// // /// Pass a pointer to a zero terminated string as parameter. The string can // /// be the file name of your pinned public key. The file format expected is // /// "PEM" or "DER". The string can also be any number of base64 encoded // /// sha256 hashes preceded by "sha256//" and separated by ";" // /// // /// When negotiating a TLS or SSL connection, the server sends a certificate // /// indicating its identity. A public key is extracted from this certificate // /// and if it does not exactly match the public key provided to this option, // /// curl will abort the connection before sending or receiving any data. // /// // /// By default this option is not set and corresponds to // /// `CURLOPT_PINNEDPUBLICKEY`. // pub fn pinned_public_key(&mut self, enable: bool) -> Result<(), Error> { // self.setopt_long(curl_sys::CURLOPT_CERTINFO, enable as c_long) // } /// Specify a source for random data /// /// The file will be used to read from to seed the random engine for SSL and /// more. /// /// By default this option is not set and corresponds to /// `CURLOPT_RANDOM_FILE`. pub fn random_file<P: AsRef<Path>>(&mut self, p: P) -> Result<(), Error> { self.setopt_path(curl_sys::CURLOPT_RANDOM_FILE, p.as_ref()) } /// Specify EGD socket path. /// /// Indicates the path name to the Entropy Gathering Daemon socket. It will /// be used to seed the random engine for SSL. /// /// By default this option is not set and corresponds to /// `CURLOPT_EGDSOCKET`. pub fn egd_socket<P: AsRef<Path>>(&mut self, p: P) -> Result<(), Error> { self.setopt_path(curl_sys::CURLOPT_EGDSOCKET, p.as_ref()) } /// Specify ciphers to use for TLS. /// /// Holds the list of ciphers to use for the SSL connection. The list must /// be syntactically correct, it consists of one or more cipher strings /// separated by colons. Commas or spaces are also acceptable separators /// but colons are normally used, !, - and + can be used as operators. /// /// For OpenSSL and GnuTLS valid examples of cipher lists include 'RC4-SHA', /// ´SHA1+DES´, 'TLSv1' and 'DEFAULT'. The default list is normally set when /// you compile OpenSSL. /// /// You'll find more details about cipher lists on this URL: /// /// https://www.openssl.org/docs/apps/ciphers.html /// /// For NSS, valid examples of cipher lists include 'rsa_rc4_128_md5', /// ´rsa_aes_128_sha´, etc. With NSS you don't add/remove ciphers. If one /// uses this option then all known ciphers are disabled and only those /// passed in are enabled. /// /// You'll find more details about the NSS cipher lists on this URL: /// /// http://git.fedorahosted.org/cgit/mod_nss.git/plain/docs/mod_nss.html#Directives /// /// By default this option is not set and corresponds to /// `CURLOPT_SSL_CIPHER_LIST`. pub fn ssl_cipher_list(&mut self, ciphers: &str) -> Result<(), Error> { let ciphers = try!(CString::new(ciphers)); self.setopt_str(curl_sys::CURLOPT_SSL_CIPHER_LIST, &ciphers) } /// Enable or disable use of the SSL session-ID cache /// /// By default all transfers are done using the cache enabled. While nothing /// ever should get hurt by attempting to reuse SSL session-IDs, there seem /// to be or have been broken SSL implementations in the wild that may /// require you to disable this in order for you to succeed. /// /// This corresponds to the `CURLOPT_SSL_SESSIONID_CACHE` option. pub fn ssl_sessionid_cache(&mut self, enable: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_SSL_SESSIONID_CACHE, enable as c_long) } /// Set SSL behavior options /// /// Inform libcurl about SSL specific behaviors. /// /// This corresponds to the `CURLOPT_SSL_OPTIONS` option. pub fn ssl_options(&mut self, bits: &SslOpt) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_SSL_OPTIONS, bits.bits) } // /// Set SSL behavior options for proxies // /// // /// Inform libcurl about SSL specific behaviors. // /// // /// This corresponds to the `CURLOPT_PROXY_SSL_OPTIONS` option. // pub fn proxy_ssl_options(&mut self, bits: &SslOpt) -> Result<(), Error> { // self.setopt_long(curl_sys::CURLOPT_PROXY_SSL_OPTIONS, bits.bits) // } // /// Stores a private pointer-sized piece of data. // /// // /// This can be retrieved through the `private` function and otherwise // /// libcurl does not tamper with this value. This corresponds to // /// `CURLOPT_PRIVATE` and defaults to 0. // pub fn set_private(&mut self, private: usize) -> Result<(), Error> { // self.setopt_ptr(curl_sys::CURLOPT_PRIVATE, private as *const _) // } // // /// Fetches this handle's private pointer-sized piece of data. // /// // /// This corresponds to `CURLINFO_PRIVATE` and defaults to 0. // pub fn private(&mut self) -> Result<usize, Error> { // self.getopt_ptr(curl_sys::CURLINFO_PRIVATE).map(|p| p as usize) // } // ========================================================================= // getters /// Get info on unmet time conditional /// /// Returns if the condition provided in the previous request didn't match /// //// This corresponds to `CURLINFO_CONDITION_UNMET` and may return an error if the /// option is not supported pub fn time_condition_unmet(&mut self) -> Result<bool, Error> { self.getopt_long(curl_sys::CURLINFO_CONDITION_UNMET).map(|r| { if r==0 { false } else { true } }) } /// Get the last used URL /// /// In cases when you've asked libcurl to follow redirects, it may /// not be the same value you set with `url`. /// /// This methods corresponds to the `CURLINFO_EFFECTIVE_URL` option. /// /// Returns `Ok(None)` if no effective url is listed or `Err` if an error /// happens or the underlying bytes aren't valid utf-8. pub fn effective_url(&mut self) -> Result<Option<&str>, Error> { self.getopt_str(curl_sys::CURLINFO_EFFECTIVE_URL) } /// Get the last used URL, in bytes /// /// In cases when you've asked libcurl to follow redirects, it may /// not be the same value you set with `url`. /// /// This methods corresponds to the `CURLINFO_EFFECTIVE_URL` option. /// /// Returns `Ok(None)` if no effective url is listed or `Err` if an error /// happens or the underlying bytes aren't valid utf-8. pub fn effective_url_bytes(&mut self) -> Result<Option<&[u8]>, Error> { self.getopt_bytes(curl_sys::CURLINFO_EFFECTIVE_URL) } /// Get the last response code /// /// The stored value will be zero if no server response code has been /// received. Note that a proxy's CONNECT response should be read with /// `http_connectcode` and not this. /// /// Corresponds to `CURLINFO_RESPONSE_CODE` and returns an error if this /// option is not supported. pub fn response_code(&mut self) -> Result<u32, Error> { self.getopt_long(curl_sys::CURLINFO_RESPONSE_CODE).map(|c| c as u32) } /// Get the CONNECT response code /// /// Returns the last received HTTP proxy response code to a CONNECT request. /// The returned value will be zero if no such response code was available. /// /// Corresponds to `CURLINFO_HTTP_CONNECTCODE` and returns an error if this /// option is not supported. pub fn http_connectcode(&mut self) -> Result<u32, Error> { self.getopt_long(curl_sys::CURLINFO_HTTP_CONNECTCODE).map(|c| c as u32) } /// Get the remote time of the retrieved document /// /// Returns the remote time of the retrieved document (in number of seconds /// since 1 Jan 1970 in the GMT/UTC time zone). If you get `None`, it can be /// because of many reasons (it might be unknown, the server might hide it /// or the server doesn't support the command that tells document time etc) /// and the time of the document is unknown. /// /// Note that you must tell the server to collect this information before /// the transfer is made, by using the `filetime` method to /// or you will unconditionally get a `None` back. /// /// This corresponds to `CURLINFO_FILETIME` and may return an error if the /// option is not supported pub fn filetime(&mut self) -> Result<Option<i64>, Error> { self.getopt_long(curl_sys::CURLINFO_FILETIME).map(|r| { if r == -1 { None } else { Some(r as i64) } }) } /// Get the number of downloaded bytes /// /// Returns the total amount of bytes that were downloaded. /// The amount is only for the latest transfer and will be reset again for each new transfer. /// This counts actual payload data, what's also commonly called body. /// All meta and header data are excluded and will not be counted in this number. /// /// This corresponds to `CURLINFO_SIZE_DOWNLOAD` and may return an error if the /// option is not supported pub fn download_size(&mut self) -> Result<f64, Error> { self.getopt_double(curl_sys::CURLINFO_SIZE_DOWNLOAD) .map(|r| r as f64) } /// Get the content-length of the download /// /// Returns the content-length of the download. /// This is the value read from the Content-Length: field /// /// This corresponds to `CURLINFO_CONTENT_LENGTH_DOWNLOAD` and may return an error if the /// option is not supported pub fn content_length_download(&mut self) -> Result<f64, Error> { self.getopt_double(curl_sys::CURLINFO_CONTENT_LENGTH_DOWNLOAD) .map(|r| r as f64) } /// Get total time of previous transfer /// /// Returns the total time for the previous transfer, /// including name resolving, TCP connect etc. /// /// Corresponds to `CURLINFO_TOTAL_TIME` and may return an error if the /// option isn't supported. pub fn total_time(&mut self) -> Result<Duration, Error> { self.getopt_double(curl_sys::CURLINFO_TOTAL_TIME) .map(double_seconds_to_duration) } /// Get the name lookup time /// /// Returns the total time from the start /// until the name resolving was completed. /// /// Corresponds to `CURLINFO_NAMELOOKUP_TIME` and may return an error if the /// option isn't supported. pub fn namelookup_time(&mut self) -> Result<Duration, Error> { self.getopt_double(curl_sys::CURLINFO_NAMELOOKUP_TIME) .map(double_seconds_to_duration) } /// Get the time until connect /// /// Returns the total time from the start /// until the connection to the remote host (or proxy) was completed. /// /// Corresponds to `CURLINFO_CONNECT_TIME` and may return an error if the /// option isn't supported. pub fn connect_time(&mut self) -> Result<Duration, Error> { self.getopt_double(curl_sys::CURLINFO_CONNECT_TIME) .map(double_seconds_to_duration) } /// Get the time until the SSL/SSH handshake is completed /// /// Returns the total time it took from the start until the SSL/SSH /// connect/handshake to the remote host was completed. This time is most often /// very near to the `pretransfer_time` time, except for cases such as /// HTTP pipelining where the pretransfer time can be delayed due to waits in /// line for the pipeline and more. /// /// Corresponds to `CURLINFO_APPCONNECT_TIME` and may return an error if the /// option isn't supported. pub fn appconnect_time(&mut self) -> Result<Duration, Error> { self.getopt_double(curl_sys::CURLINFO_APPCONNECT_TIME) .map(double_seconds_to_duration) } /// Get the time until the file transfer start /// /// Returns the total time it took from the start until the file /// transfer is just about to begin. This includes all pre-transfer commands /// and negotiations that are specific to the particular protocol(s) involved. /// It does not involve the sending of the protocol- specific request that /// triggers a transfer. /// /// Corresponds to `CURLINFO_PRETRANSFER_TIME` and may return an error if the /// option isn't supported. pub fn pretransfer_time(&mut self) -> Result<Duration, Error> { self.getopt_double(curl_sys::CURLINFO_PRETRANSFER_TIME) .map(double_seconds_to_duration) } /// Get the time until the first byte is received /// /// Returns the total time it took from the start until the first /// byte is received by libcurl. This includes `pretransfer_time` and /// also the time the server needs to calculate the result. /// /// Corresponds to `CURLINFO_STARTTRANSFER_TIME` and may return an error if the /// option isn't supported. pub fn starttransfer_time(&mut self) -> Result<Duration, Error> { self.getopt_double(curl_sys::CURLINFO_STARTTRANSFER_TIME) .map(double_seconds_to_duration) } /// Get the time for all redirection steps /// /// Returns the total time it took for all redirection steps /// include name lookup, connect, pretransfer and transfer before final /// transaction was started. `redirect_time` contains the complete /// execution time for multiple redirections. /// /// Corresponds to `CURLINFO_REDIRECT_TIME` and may return an error if the /// option isn't supported. pub fn redirect_time(&mut self) -> Result<Duration, Error> { self.getopt_double(curl_sys::CURLINFO_REDIRECT_TIME) .map(double_seconds_to_duration) } /// Get the number of redirects /// /// Corresponds to `CURLINFO_REDIRECT_COUNT` and may return an error if the /// option isn't supported. pub fn redirect_count(&mut self) -> Result<u32, Error> { self.getopt_long(curl_sys::CURLINFO_REDIRECT_COUNT).map(|c| c as u32) } /// Get the URL a redirect would go to /// /// Returns the URL a redirect would take you to if you would enable /// `follow_location`. This can come very handy if you think using the /// built-in libcurl redirect logic isn't good enough for you but you would /// still prefer to avoid implementing all the magic of figuring out the new /// URL. /// /// Corresponds to `CURLINFO_REDIRECT_URL` and may return an error if the /// url isn't valid utf-8 or an error happens. pub fn redirect_url(&mut self) -> Result<Option<&str>, Error> { self.getopt_str(curl_sys::CURLINFO_REDIRECT_URL) } /// Get the URL a redirect would go to, in bytes /// /// Returns the URL a redirect would take you to if you would enable /// `follow_location`. This can come very handy if you think using the /// built-in libcurl redirect logic isn't good enough for you but you would /// still prefer to avoid implementing all the magic of figuring out the new /// URL. /// /// Corresponds to `CURLINFO_REDIRECT_URL` and may return an error. pub fn redirect_url_bytes(&mut self) -> Result<Option<&[u8]>, Error> { self.getopt_bytes(curl_sys::CURLINFO_REDIRECT_URL) } /// Get size of retrieved headers /// /// Corresponds to `CURLINFO_HEADER_SIZE` and may return an error if the /// option isn't supported. pub fn header_size(&mut self) -> Result<u64, Error> { self.getopt_long(curl_sys::CURLINFO_HEADER_SIZE).map(|c| c as u64) } /// Get size of sent request. /// /// Corresponds to `CURLINFO_REQUEST_SIZE` and may return an error if the /// option isn't supported. pub fn request_size(&mut self) -> Result<u64, Error> { self.getopt_long(curl_sys::CURLINFO_REQUEST_SIZE).map(|c| c as u64) } /// Get Content-Type /// /// Returns the content-type of the downloaded object. This is the value /// read from the Content-Type: field. If you get `None`, it means that the /// server didn't send a valid Content-Type header or that the protocol /// used doesn't support this. /// /// Corresponds to `CURLINFO_CONTENT_TYPE` and may return an error if the /// option isn't supported. pub fn content_type(&mut self) -> Result<Option<&str>, Error> { self.getopt_str(curl_sys::CURLINFO_CONTENT_TYPE) } /// Get Content-Type, in bytes /// /// Returns the content-type of the downloaded object. This is the value /// read from the Content-Type: field. If you get `None`, it means that the /// server didn't send a valid Content-Type header or that the protocol /// used doesn't support this. /// /// Corresponds to `CURLINFO_CONTENT_TYPE` and may return an error if the /// option isn't supported. pub fn content_type_bytes(&mut self) -> Result<Option<&[u8]>, Error> { self.getopt_bytes(curl_sys::CURLINFO_CONTENT_TYPE) } /// Get errno number from last connect failure. /// /// Note that the value is only set on failure, it is not reset upon a /// successful operation. The number is OS and system specific. /// /// Corresponds to `CURLINFO_OS_ERRNO` and may return an error if the /// option isn't supported. pub fn os_errno(&mut self) -> Result<i32, Error> { self.getopt_long(curl_sys::CURLINFO_OS_ERRNO).map(|c| c as i32) } /// Get IP address of last connection. /// /// Returns a string holding the IP address of the most recent connection /// done with this curl handle. This string may be IPv6 when that is /// enabled. /// /// Corresponds to `CURLINFO_PRIMARY_IP` and may return an error if the /// option isn't supported. pub fn primary_ip(&mut self) -> Result<Option<&str>, Error> { self.getopt_str(curl_sys::CURLINFO_PRIMARY_IP) } /// Get the latest destination port number /// /// Corresponds to `CURLINFO_PRIMARY_PORT` and may return an error if the /// option isn't supported. pub fn primary_port(&mut self) -> Result<u16, Error> { self.getopt_long(curl_sys::CURLINFO_PRIMARY_PORT).map(|c| c as u16) } /// Get local IP address of last connection /// /// Returns a string holding the IP address of the local end of most recent /// connection done with this curl handle. This string may be IPv6 when that /// is enabled. /// /// Corresponds to `CURLINFO_LOCAL_IP` and may return an error if the /// option isn't supported. pub fn local_ip(&mut self) -> Result<Option<&str>, Error> { self.getopt_str(curl_sys::CURLINFO_LOCAL_IP) } /// Get the latest local port number /// /// Corresponds to `CURLINFO_LOCAL_PORT` and may return an error if the /// option isn't supported. pub fn local_port(&mut self) -> Result<u16, Error> { self.getopt_long(curl_sys::CURLINFO_LOCAL_PORT).map(|c| c as u16) } /// Get all known cookies /// /// Returns a linked-list of all cookies cURL knows (expired ones, too). /// /// Corresponds to the `CURLINFO_COOKIELIST` option and may return an error /// if the option isn't supported. pub fn cookies(&mut self) -> Result<List, Error> { unsafe { let mut list = 0 as *mut _; let rc = curl_sys::curl_easy_getinfo(self.inner.handle, curl_sys::CURLINFO_COOKIELIST, &mut list); try!(self.cvt(rc)); Ok(list::from_raw(list)) } } /// Wait for pipelining/multiplexing /// /// Set wait to `true` to tell libcurl to prefer to wait for a connection to /// confirm or deny that it can do pipelining or multiplexing before /// continuing. /// /// When about to perform a new transfer that allows pipelining or /// multiplexing, libcurl will check for existing connections to re-use and /// pipeline on. If no such connection exists it will immediately continue /// and create a fresh new connection to use. /// /// By setting this option to `true` - and having `pipelining(true, true)` /// enabled for the multi handle this transfer is associated with - libcurl /// will instead wait for the connection to reveal if it is possible to /// pipeline/multiplex on before it continues. This enables libcurl to much /// better keep the number of connections to a minimum when using pipelining /// or multiplexing protocols. /// /// The effect thus becomes that with this option set, libcurl prefers to /// wait and re-use an existing connection for pipelining rather than the /// opposite: prefer to open a new connection rather than waiting. /// /// The waiting time is as long as it takes for the connection to get up and /// for libcurl to get the necessary response back that informs it about its /// protocol and support level. /// /// This corresponds to the `CURLOPT_PIPEWAIT` option. pub fn pipewait(&mut self, wait: bool) -> Result<(), Error> { self.setopt_long(curl_sys::CURLOPT_PIPEWAIT, wait as c_long) } // ========================================================================= // Other methods /// After options have been set, this will perform the transfer described by /// the options. /// /// This performs the request in a synchronous fashion. This can be used /// multiple times for one easy handle and libcurl will attempt to re-use /// the same connection for all transfers. /// /// This method will preserve all options configured in this handle for the /// next request, and if that is not desired then the options can be /// manually reset or the `reset` method can be called. /// /// Note that this method takes `&self`, which is quite important! This /// allows applications to close over the handle in various callbacks to /// call methods like `unpause_write` and `unpause_read` while a transfer is /// in progress. pub fn perform(&self) -> Result<(), Error> { let ret = unsafe { self.cvt(curl_sys::curl_easy_perform(self.inner.handle)) }; panic::propagate(); return ret } /// Unpause reading on a connection. /// /// Using this function, you can explicitly unpause a connection that was /// previously paused. /// /// A connection can be paused by letting the read or the write callbacks /// return `ReadError::Pause` or `WriteError::Pause`. /// /// To unpause, you may for example call this from the progress callback /// which gets called at least once per second, even if the connection is /// paused. /// /// The chance is high that you will get your write callback called before /// this function returns. pub fn unpause_read(&self) -> Result<(), Error> { unsafe { let rc = curl_sys::curl_easy_pause(self.inner.handle, curl_sys::CURLPAUSE_RECV_CONT); self.cvt(rc) } } /// Unpause writing on a connection. /// /// Using this function, you can explicitly unpause a connection that was /// previously paused. /// /// A connection can be paused by letting the read or the write callbacks /// return `ReadError::Pause` or `WriteError::Pause`. A write callback that /// returns pause signals to the library that it couldn't take care of any /// data at all, and that data will then be delivered again to the callback /// when the writing is later unpaused. /// /// To unpause, you may for example call this from the progress callback /// which gets called at least once per second, even if the connection is /// paused. pub fn unpause_write(&self) -> Result<(), Error> { unsafe { let rc = curl_sys::curl_easy_pause(self.inner.handle, curl_sys::CURLPAUSE_SEND_CONT); self.cvt(rc) } } /// URL encodes a string `s` pub fn url_encode(&mut self, s: &[u8]) -> String { if s.len() == 0 { return String::new() } unsafe { let p = curl_sys::curl_easy_escape(self.inner.handle, s.as_ptr() as *const _, s.len() as c_int); assert!(!p.is_null()); let ret = str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap(); let ret = String::from(ret); curl_sys::curl_free(p as *mut _); return ret } } /// URL decodes a string `s`, returning `None` if it fails pub fn url_decode(&mut self, s: &str) -> Vec<u8> { if s.len() == 0 { return Vec::new(); } // Work around https://curl.haxx.se/docs/adv_20130622.html, a bug where // if the last few characters are a bad escape then curl will have a // buffer overrun. let mut iter = s.chars().rev(); let orig_len = s.len(); let mut data; let mut s = s; if iter.next() == Some('%') || iter.next() == Some('%') || iter.next() == Some('%') { data = s.to_string(); data.push(0u8 as char); s = &data[..]; } unsafe { let mut len = 0; let p = curl_sys::curl_easy_unescape(self.inner.handle, s.as_ptr() as *const _, orig_len as c_int, &mut len); assert!(!p.is_null()); let slice = slice::from_raw_parts(p as *const u8, len as usize); let ret = slice.to_vec(); curl_sys::curl_free(p as *mut _); return ret } } // TODO: I don't think this is safe, you can drop this which has all the // callback data and then the next is use-after-free // // /// Attempts to clone this handle, returning a new session handle with the // /// same options set for this handle. // /// // /// Internal state info and things like persistent connections ccannot be // /// transferred. // /// // /// # Errors // /// // /// If a new handle could not be allocated or another error happens, `None` // /// is returned. // pub fn try_clone<'b>(&mut self) -> Option<Easy<'b>> { // unsafe { // let handle = curl_sys::curl_easy_duphandle(self.handle); // if handle.is_null() { // None // } else { // Some(Easy { // handle: handle, // data: blank_data(), // _marker: marker::PhantomData, // }) // } // } // } /// Receives data from a connected socket. /// /// Only useful after a successful `perform` with the `connect_only` option /// set as well. pub fn recv(&mut self, data: &mut [u8]) -> Result<usize, Error> { unsafe { let mut n = 0; let r = curl_sys::curl_easy_recv(self.inner.handle, data.as_mut_ptr() as *mut _, data.len(), &mut n); if r == curl_sys::CURLE_OK { Ok(n) } else { Err(Error::new(r)) } } } /// Sends data over the connected socket. /// /// Only useful after a successful `perform` with the `connect_only` option /// set as well. pub fn send(&mut self, data: &[u8]) -> Result<usize, Error> { unsafe { let mut n = 0; let rc = curl_sys::curl_easy_send(self.inner.handle, data.as_ptr() as *const _, data.len(), &mut n); try!(self.cvt(rc)); Ok(n) } } /// Get a pointer to the raw underlying CURL handle. pub fn raw(&self) -> *mut curl_sys::CURL { self.inner.handle } #[cfg(unix)] fn setopt_path(&mut self, opt: curl_sys::CURLoption, val: &Path) -> Result<(), Error> { use std::os::unix::prelude::*; let s = try!(CString::new(val.as_os_str().as_bytes())); self.setopt_str(opt, &s) } #[cfg(windows)] fn setopt_path(&mut self, opt: curl_sys::CURLoption, val: &Path) -> Result<(), Error> { match val.to_str() { Some(s) => self.setopt_str(opt, &try!(CString::new(s))), None => Err(Error::new(curl_sys::CURLE_CONV_FAILED)), } } fn setopt_long(&mut self, opt: curl_sys::CURLoption, val: c_long) -> Result<(), Error> { unsafe { self.cvt(curl_sys::curl_easy_setopt(self.inner.handle, opt, val)) } } fn setopt_str(&mut self, opt: curl_sys::CURLoption, val: &CStr) -> Result<(), Error> { self.setopt_ptr(opt, val.as_ptr()) } fn setopt_ptr(&self, opt: curl_sys::CURLoption, val: *const c_char) -> Result<(), Error> { unsafe { self.cvt(curl_sys::curl_easy_setopt(self.inner.handle, opt, val)) } } fn setopt_off_t(&mut self, opt: curl_sys::CURLoption, val: curl_sys::curl_off_t) -> Result<(), Error> { unsafe { let rc = curl_sys::curl_easy_setopt(self.inner.handle, opt, val); self.cvt(rc) } } fn getopt_bytes(&mut self, opt: curl_sys::CURLINFO) -> Result<Option<&[u8]>, Error> { unsafe { let p = try!(self.getopt_ptr(opt)); if p.is_null() { Ok(None) } else { Ok(Some(CStr::from_ptr(p).to_bytes())) } } } fn getopt_ptr(&mut self, opt: curl_sys::CURLINFO) -> Result<*const c_char, Error> { unsafe { let mut p = 0 as *const c_char; let rc = curl_sys::curl_easy_getinfo(self.inner.handle, opt, &mut p); try!(self.cvt(rc)); Ok(p) } } fn getopt_str(&mut self, opt: curl_sys::CURLINFO) -> Result<Option<&str>, Error> { match self.getopt_bytes(opt) { Ok(None) => Ok(None), Err(e) => Err(e), Ok(Some(bytes)) => { match str::from_utf8(bytes) { Ok(s) => Ok(Some(s)), Err(_) => Err(Error::new(curl_sys::CURLE_CONV_FAILED)), } } } } fn getopt_long(&mut self, opt: curl_sys::CURLINFO) -> Result<c_long, Error> { unsafe { let mut p = 0; let rc = curl_sys::curl_easy_getinfo(self.inner.handle, opt, &mut p); try!(self.cvt(rc)); Ok(p) } } fn getopt_double(&mut self, opt: curl_sys::CURLINFO) -> Result<c_double, Error> { unsafe { let mut p = 0 as c_double; let rc = curl_sys::curl_easy_getinfo(self.inner.handle, opt, &mut p); try!(self.cvt(rc)); Ok(p) } } /// Returns the contents of the internal error buffer, if available. /// /// When an easy handle is created it configured the `CURLOPT_ERRORBUFFER` /// parameter and instructs libcurl to store more error information into a /// buffer for better error messages and better debugging. The contents of /// that buffer are automatically coupled with all errors for methods on /// this type, but if manually invoking APIs the contents will need to be /// extracted with this method. /// /// Put another way, you probably don't need this, you're probably already /// getting nice error messages! /// /// This function will clear the internal buffer, so this is an operation /// that mutates the handle internally. pub fn take_error_buf(&self) -> Option<String> { let mut buf = self.inner.error_buf.borrow_mut(); if buf[0] == 0 { return None } let pos = buf.iter().position(|i| *i == 0).unwrap_or(buf.len()); let msg = String::from_utf8_lossy(&buf[..pos]).into_owned(); buf[0] = 0; Some(msg) } fn cvt(&self, rc: curl_sys::CURLcode) -> Result<(), Error> { if rc == curl_sys::CURLE_OK { return Ok(()) } let mut err = Error::new(rc); if let Some(msg) = self.take_error_buf() { err.set_extra(msg); } Err(Error::new(rc)) } } impl<H: fmt::Debug> fmt::Debug for Easy2<H> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Easy") .field("handle", &self.inner.handle) .field("handler", &self.inner.handle) .finish() } } impl<H> Drop for Easy2<H> { fn drop(&mut self) { unsafe { curl_sys::curl_easy_cleanup(self.inner.handle); } } } extern fn header_cb<H: Handler>(buffer: *mut c_char, size: size_t, nitems: size_t, userptr: *mut c_void) -> size_t { let keep_going = panic::catch(|| unsafe { let data = slice::from_raw_parts(buffer as *const u8, size * nitems); (*(userptr as *mut Inner<H>)).handler.header(data) }).unwrap_or(false); if keep_going { size * nitems } else { !0 } } extern fn write_cb<H: Handler>(ptr: *mut c_char, size: size_t, nmemb: size_t, data: *mut c_void) -> size_t { panic::catch(|| unsafe { let input = slice::from_raw_parts(ptr as *const u8, size * nmemb); match (*(data as *mut Inner<H>)).handler.write(input) { Ok(s) => s, Err(WriteError::Pause) | Err(WriteError::__Nonexhaustive) => curl_sys::CURL_WRITEFUNC_PAUSE, } }).unwrap_or(!0) } extern fn read_cb<H: Handler>(ptr: *mut c_char, size: size_t, nmemb: size_t, data: *mut c_void) -> size_t { panic::catch(|| unsafe { let input = slice::from_raw_parts_mut(ptr as *mut u8, size * nmemb); match (*(data as *mut Inner<H>)).handler.read(input) { Ok(s) => s, Err(ReadError::Pause) => { curl_sys::CURL_READFUNC_PAUSE } Err(ReadError::__Nonexhaustive) | Err(ReadError::Abort) => { curl_sys::CURL_READFUNC_ABORT } } }).unwrap_or(!0) } extern fn seek_cb<H: Handler>(data: *mut c_void, offset: curl_sys::curl_off_t, origin: c_int) -> c_int { panic::catch(|| unsafe { let from = if origin == libc::SEEK_SET { SeekFrom::Start(offset as u64) } else { panic!("unknown origin from libcurl: {}", origin); }; (*(data as *mut Inner<H>)).handler.seek(from) as c_int }).unwrap_or(!0) } extern fn progress_cb<H: Handler>(data: *mut c_void, dltotal: c_double, dlnow: c_double, ultotal: c_double, ulnow: c_double) -> c_int { let keep_going = panic::catch(|| unsafe { (*(data as *mut Inner<H>)).handler.progress(dltotal, dlnow, ultotal, ulnow) }).unwrap_or(false); if keep_going { 0 } else { 1 } } // TODO: expose `handle`? is that safe? extern fn debug_cb<H: Handler>(_handle: *mut curl_sys::CURL, kind: curl_sys::curl_infotype, data: *mut c_char, size: size_t, userptr: *mut c_void) -> c_int { panic::catch(|| unsafe { let data = slice::from_raw_parts(data as *const u8, size); let kind = match kind { curl_sys::CURLINFO_TEXT => InfoType::Text, curl_sys::CURLINFO_HEADER_IN => InfoType::HeaderIn, curl_sys::CURLINFO_HEADER_OUT => InfoType::HeaderOut, curl_sys::CURLINFO_DATA_IN => InfoType::DataIn, curl_sys::CURLINFO_DATA_OUT => InfoType::DataOut, curl_sys::CURLINFO_SSL_DATA_IN => InfoType::SslDataIn, curl_sys::CURLINFO_SSL_DATA_OUT => InfoType::SslDataOut, _ => return, }; (*(userptr as *mut Inner<H>)).handler.debug(kind, data) }); return 0 } extern fn ssl_ctx_cb<H: Handler>(_handle: *mut curl_sys::CURL, ssl_ctx: *mut c_void, data: *mut c_void) -> curl_sys::CURLcode { let res = panic::catch(|| unsafe { match (*(data as *mut Inner<H>)).handler.ssl_ctx(ssl_ctx) { Ok(()) => curl_sys::CURLE_OK, Err(e) => e.code(), } }); // Default to a generic SSL error in case of panic. This // shouldn't really matter since the error should be // propagated later on but better safe than sorry... res.unwrap_or(curl_sys::CURLE_SSL_CONNECT_ERROR) } // TODO: expose `purpose` and `sockaddr` inside of `address` extern fn opensocket_cb<H: Handler>(data: *mut c_void, _purpose: curl_sys::curlsocktype, address: *mut curl_sys::curl_sockaddr) -> curl_sys::curl_socket_t { let res = panic::catch(|| unsafe { (*(data as *mut Inner<H>)).handler.open_socket((*address).family, (*address).socktype, (*address).protocol) .unwrap_or(curl_sys::CURL_SOCKET_BAD) }); res.unwrap_or(curl_sys::CURL_SOCKET_BAD) } fn double_seconds_to_duration(seconds: f64) -> Duration { let whole_seconds = seconds.trunc() as u64; let nanos = seconds.fract() * 1_000_000_000f64; Duration::new(whole_seconds, nanos as u32) } #[test] fn double_seconds_to_duration_whole_second() { let dur = double_seconds_to_duration(1.0); assert_eq!(dur.as_secs(), 1); assert_eq!(dur.subsec_nanos(), 0); } #[test] fn double_seconds_to_duration_sub_second1() { let dur = double_seconds_to_duration(0.0); assert_eq!(dur.as_secs(), 0); assert_eq!(dur.subsec_nanos(), 0); } #[test] fn double_seconds_to_duration_sub_second2() { let dur = double_seconds_to_duration(0.5); assert_eq!(dur.as_secs(), 0); assert_eq!(dur.subsec_nanos(), 500_000_000); } impl Auth { /// Creates a new set of authentications with no members. /// /// An `Auth` structure is used to configure which forms of authentication /// are attempted when negotiating connections with servers. pub fn new() -> Auth { Auth { bits: 0 } } /// HTTP Basic authentication. /// /// This is the default choice, and the only method that is in wide-spread /// use and supported virtually everywhere. This sends the user name and /// password over the network in plain text, easily captured by others. pub fn basic(&mut self, on: bool) -> &mut Auth { self.flag(curl_sys::CURLAUTH_BASIC, on) } /// HTTP Digest authentication. /// /// Digest authentication is defined in RFC 2617 and is a more secure way to /// do authentication over public networks than the regular old-fashioned /// Basic method. pub fn digest(&mut self, on: bool) -> &mut Auth { self.flag(curl_sys::CURLAUTH_DIGEST, on) } /// HTTP Digest authentication with an IE flavor. /// /// Digest authentication is defined in RFC 2617 and is a more secure way to /// do authentication over public networks than the regular old-fashioned /// Basic method. The IE flavor is simply that libcurl will use a special /// "quirk" that IE is known to have used before version 7 and that some /// servers require the client to use. pub fn digest_ie(&mut self, on: bool) -> &mut Auth { self.flag(curl_sys::CURLAUTH_DIGEST_IE, on) } /// HTTP Negotiate (SPNEGO) authentication. /// /// Negotiate authentication is defined in RFC 4559 and is the most secure /// way to perform authentication over HTTP. /// /// You need to build libcurl with a suitable GSS-API library or SSPI on /// Windows for this to work. pub fn gssnegotiate(&mut self, on: bool) -> &mut Auth { self.flag(curl_sys::CURLAUTH_GSSNEGOTIATE, on) } /// HTTP NTLM authentication. /// /// A proprietary protocol invented and used by Microsoft. It uses a /// challenge-response and hash concept similar to Digest, to prevent the /// password from being eavesdropped. /// /// You need to build libcurl with either OpenSSL, GnuTLS or NSS support for /// this option to work, or build libcurl on Windows with SSPI support. pub fn ntlm(&mut self, on: bool) -> &mut Auth { self.flag(curl_sys::CURLAUTH_NTLM, on) } /// NTLM delegating to winbind helper. /// /// Authentication is performed by a separate binary application that is /// executed when needed. The name of the application is specified at /// compile time but is typically /usr/bin/ntlm_auth /// /// Note that libcurl will fork when necessary to run the winbind /// application and kill it when complete, calling waitpid() to await its /// exit when done. On POSIX operating systems, killing the process will /// cause a SIGCHLD signal to be raised (regardless of whether /// CURLOPT_NOSIGNAL is set), which must be handled intelligently by the /// application. In particular, the application must not unconditionally /// call wait() in its SIGCHLD signal handler to avoid being subject to a /// race condition. This behavior is subject to change in future versions of /// libcurl. /// /// A proprietary protocol invented and used by Microsoft. It uses a /// challenge-response and hash concept similar to Digest, to prevent the /// password from being eavesdropped. pub fn ntlm_wb(&mut self, on: bool) -> &mut Auth { self.flag(curl_sys::CURLAUTH_NTLM_WB, on) } fn flag(&mut self, bit: c_ulong, on: bool) -> &mut Auth { if on { self.bits |= bit as c_long; } else { self.bits &= !bit as c_long; } self } } impl fmt::Debug for Auth { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let bits = self.bits as c_ulong; f.debug_struct("Auth") .field("basic", &(bits & curl_sys::CURLAUTH_BASIC != 0)) .field("digest", &(bits & curl_sys::CURLAUTH_DIGEST != 0)) .field("digest_ie", &(bits & curl_sys::CURLAUTH_DIGEST_IE != 0)) .field("gssnegotiate", &(bits & curl_sys::CURLAUTH_GSSNEGOTIATE != 0)) .field("ntlm", &(bits & curl_sys::CURLAUTH_NTLM != 0)) .field("ntlm_wb", &(bits & curl_sys::CURLAUTH_NTLM_WB != 0)) .finish() } } impl SslOpt { /// Creates a new set of SSL options. pub fn new() -> SslOpt { SslOpt { bits: 0 } } /// Tells libcurl to disable certificate revocation checks for those SSL /// backends where such behavior is present. /// /// Currently this option is only supported for WinSSL (the native Windows /// SSL library), with an exception in the case of Windows' Untrusted /// Publishers blacklist which it seems can't be bypassed. This option may /// have broader support to accommodate other SSL backends in the future. /// https://curl.haxx.se/docs/ssl-compared.html pub fn no_revoke(&mut self, on: bool) -> &mut SslOpt { self.flag(curl_sys::CURLSSLOPT_NO_REVOKE, on) } /// Tells libcurl to not attempt to use any workarounds for a security flaw /// in the SSL3 and TLS1.0 protocols. /// /// If this option isn't used or this bit is set to 0, the SSL layer libcurl /// uses may use a work-around for this flaw although it might cause /// interoperability problems with some (older) SSL implementations. /// /// > WARNING: avoiding this work-around lessens the security, and by /// > setting this option to 1 you ask for exactly that. This option is only /// > supported for DarwinSSL, NSS and OpenSSL. pub fn allow_beast(&mut self, on: bool) -> &mut SslOpt { self.flag(curl_sys::CURLSSLOPT_ALLOW_BEAST, on) } fn flag(&mut self, bit: c_long, on: bool) -> &mut SslOpt { if on { self.bits |= bit as c_long; } else { self.bits &= !bit as c_long; } self } } impl fmt::Debug for SslOpt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("SslOpt") .field("no_revoke", &(self.bits & curl_sys::CURLSSLOPT_NO_REVOKE != 0)) .field("allow_beast", &(self.bits & curl_sys::CURLSSLOPT_ALLOW_BEAST != 0)) .finish() } }
40.775139
99
0.625078
bf22344adfbfa3cef5086ba292fe8e246f66da08
6,284
use bindings::{ Windows::Foundation::Numerics::*, Windows::Win32::Direct2D::* }; use windows::Result; const DEFAULT_BACKGROUND_COLOR: D2D1_COLOR_F = create_color(0x282828FF); const DEFAULT_STATUS_BAR_COLOR: D2D1_COLOR_F = create_color(0x141414FF); const DEFAULT_BRACKET_COLOR: D2D1_COLOR_F = create_color(0xFFFFFFFF); const DEFAULT_TEXT_COLOR: D2D1_COLOR_F = create_color(0xFBF1C7FF); const DEFAULT_LINE_NUMBER_COLOR: D2D1_COLOR_F = create_color(0xD5C4A1FF); const DEFAULT_CARET_COLOR: D2D1_COLOR_F = create_color(0xFE8019FF); const DEFAULT_SELECTION_COLOR: D2D1_COLOR_F = create_color(0x464646FF); const DEFAULT_VARIABLE_COLOR: D2D1_COLOR_F = create_color(0xADD8E6FF); const DEFAULT_FUNCTION_COLOR: D2D1_COLOR_F = create_color(0xFBD06DFF); const DEFAULT_METHOD_COLOR: D2D1_COLOR_F = create_color(0xD3869BFF); const DEFAULT_CLASS_COLOR: D2D1_COLOR_F = create_color(0xA0DB8EFF); const DEFAULT_ENUM_COLOR: D2D1_COLOR_F = create_color(0xA0DB8EFF); const DEFAULT_COMMENT_COLOR: D2D1_COLOR_F = create_color(0xB8BB26FF); const DEFAULT_KEYWORD_COLOR: D2D1_COLOR_F = create_color(0xFB4934FF); const DEFAULT_LITERAL_COLOR: D2D1_COLOR_F = create_color(0xFE8019FF); const DEFAULT_MACRO_PREPROCESSOR_COLOR: D2D1_COLOR_F = create_color(0xEE7AE9FF); const DEFAULT_PRIMITIVE_COLOR: D2D1_COLOR_F = create_color(0xCDF916FF); const fn create_color(color: u32) -> D2D1_COLOR_F { D2D1_COLOR_F { r: ((color >> 24) & 0xFF) as f32 / 255.0, g: ((color >> 16) & 0xFF) as f32 / 255.0, b: ((color >> 8) & 0xFF) as f32 / 255.0, a: (color & 0xFF) as f32 / 255.0 } } pub struct Theme { pub background_color: D2D1_COLOR_F, pub status_bar_brush: Option<ID2D1SolidColorBrush>, pub bracket_brush: Option<ID2D1SolidColorBrush>, pub text_brush: Option<ID2D1SolidColorBrush>, pub line_number_brush: Option<ID2D1SolidColorBrush>, pub caret_brush: Option<ID2D1SolidColorBrush>, pub selection_brush: Option<ID2D1SolidColorBrush>, pub variable_brush: Option<ID2D1SolidColorBrush>, pub function_brush: Option<ID2D1SolidColorBrush>, pub method_brush: Option<ID2D1SolidColorBrush>, pub class_brush: Option<ID2D1SolidColorBrush>, pub enum_brush: Option<ID2D1SolidColorBrush>, pub comment_brush: Option<ID2D1SolidColorBrush>, pub keyword_brush: Option<ID2D1SolidColorBrush>, pub literal_brush: Option<ID2D1SolidColorBrush>, pub macro_preprocessor_brush: Option<ID2D1SolidColorBrush>, pub primitive_brush: Option<ID2D1SolidColorBrush> } impl Default for Theme { fn default() -> Self { Self { background_color: D2D1_COLOR_F { r: 0.0, g: 0.0, b: 0.0, a: 1.0}, status_bar_brush: None, bracket_brush: None, text_brush: None, line_number_brush: None, caret_brush: None, selection_brush: None, variable_brush: None, function_brush: None, method_brush: None, class_brush: None, enum_brush: None, comment_brush: None, keyword_brush: None, literal_brush: None, macro_preprocessor_brush: None, primitive_brush: None, } } } impl Theme { pub fn new_default(render_target: &ID2D1HwndRenderTarget) -> Result<Self> { let mut theme = Self { background_color: DEFAULT_BACKGROUND_COLOR, status_bar_brush: None, bracket_brush: None, text_brush: None, line_number_brush: None, caret_brush: None, selection_brush: None, variable_brush: None, function_brush: None, method_brush: None, class_brush: None, enum_brush: None, comment_brush: None, keyword_brush: None, literal_brush: None, macro_preprocessor_brush: None, primitive_brush: None }; let brush_properties = D2D1_BRUSH_PROPERTIES { opacity: 1.0, transform: Matrix3x2::identity() }; unsafe { render_target.CreateSolidColorBrush(&DEFAULT_TEXT_COLOR, &brush_properties, &mut theme.text_brush).ok()?; render_target.CreateSolidColorBrush(&DEFAULT_STATUS_BAR_COLOR, &brush_properties, &mut theme.status_bar_brush).ok()?; render_target.CreateSolidColorBrush(&DEFAULT_BRACKET_COLOR, &brush_properties, &mut theme.bracket_brush).ok()?; render_target.CreateSolidColorBrush(&DEFAULT_LINE_NUMBER_COLOR, &brush_properties, &mut theme.line_number_brush).ok()?; render_target.CreateSolidColorBrush(&DEFAULT_CARET_COLOR, &brush_properties, &mut theme.caret_brush).ok()?; render_target.CreateSolidColorBrush(&DEFAULT_SELECTION_COLOR, &brush_properties, &mut theme.selection_brush).ok()?; render_target.CreateSolidColorBrush(&DEFAULT_VARIABLE_COLOR, &brush_properties, &mut theme.variable_brush).ok()?; render_target.CreateSolidColorBrush(&DEFAULT_FUNCTION_COLOR, &brush_properties, &mut theme.function_brush).ok()?; render_target.CreateSolidColorBrush(&DEFAULT_METHOD_COLOR, &brush_properties, &mut theme.method_brush).ok()?; render_target.CreateSolidColorBrush(&DEFAULT_CLASS_COLOR, &brush_properties, &mut theme.class_brush).ok()?; render_target.CreateSolidColorBrush(&DEFAULT_ENUM_COLOR, &brush_properties, &mut theme.enum_brush).ok()?; render_target.CreateSolidColorBrush(&DEFAULT_COMMENT_COLOR, &brush_properties, &mut theme.comment_brush).ok()?; render_target.CreateSolidColorBrush(&DEFAULT_KEYWORD_COLOR, &brush_properties, &mut theme.keyword_brush).ok()?; render_target.CreateSolidColorBrush(&DEFAULT_LITERAL_COLOR, &brush_properties, &mut theme.literal_brush).ok()?; render_target.CreateSolidColorBrush(&DEFAULT_MACRO_PREPROCESSOR_COLOR, &brush_properties, &mut theme.macro_preprocessor_brush).ok()?; render_target.CreateSolidColorBrush(&DEFAULT_PRIMITIVE_COLOR, &brush_properties, &mut theme.primitive_brush).ok()?; } Ok(theme) } }
49.480315
146
0.693507
4aa74f33ab4a7688b29510539c3c9d5db248a691
8,606
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::ST6_TCONFA { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct COMPR { bits: u8, } impl COMPR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct MASKR { bits: u8, } impl MASKR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct NEXTSTATER { bits: u8, } impl NEXTSTATER { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct PRSACTR { bits: u8, } impl PRSACTR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct SETIFR { bits: bool, } impl SETIFR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct CHAINR { bits: bool, } impl CHAINR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Proxy"] pub struct _COMPW<'a> { w: &'a mut W, } impl<'a> _COMPW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 0x0f; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _MASKW<'a> { w: &'a mut W, } impl<'a> _MASKW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 0x0f; const OFFSET: u8 = 4; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _NEXTSTATEW<'a> { w: &'a mut W, } impl<'a> _NEXTSTATEW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 0x0f; const OFFSET: u8 = 8; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PRSACTW<'a> { w: &'a mut W, } impl<'a> _PRSACTW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 0x07; const OFFSET: u8 = 12; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _SETIFW<'a> { w: &'a mut W, } impl<'a> _SETIFW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _CHAINW<'a> { w: &'a mut W, } impl<'a> _CHAINW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 18; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:3 - Sensor compare value"] #[inline] pub fn comp(&self) -> COMPR { let bits = { const MASK: u8 = 0x0f; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }; COMPR { bits } } #[doc = "Bits 4:7 - Sensor mask"] #[inline] pub fn mask(&self) -> MASKR { let bits = { const MASK: u8 = 0x0f; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) as u8 }; MASKR { bits } } #[doc = "Bits 8:11 - Next state index"] #[inline] pub fn nextstate(&self) -> NEXTSTATER { let bits = { const MASK: u8 = 0x0f; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 }; NEXTSTATER { bits } } #[doc = "Bits 12:14 - Configure transition action"] #[inline] pub fn prsact(&self) -> PRSACTR { let bits = { const MASK: u8 = 0x07; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PRSACTR { bits } } #[doc = "Bit 16 - Set interrupt flag enable"] #[inline] pub fn setif(&self) -> SETIFR { let bits = { const MASK: bool = true; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) != 0 }; SETIFR { bits } } #[doc = "Bit 18 - Enable state descriptor chaining"] #[inline] pub fn chain(&self) -> CHAINR { let bits = { const MASK: bool = true; const OFFSET: u8 = 18; ((self.bits >> OFFSET) & MASK as u32) != 0 }; CHAINR { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:3 - Sensor compare value"] #[inline] pub fn comp(&mut self) -> _COMPW { _COMPW { w: self } } #[doc = "Bits 4:7 - Sensor mask"] #[inline] pub fn mask(&mut self) -> _MASKW { _MASKW { w: self } } #[doc = "Bits 8:11 - Next state index"] #[inline] pub fn nextstate(&mut self) -> _NEXTSTATEW { _NEXTSTATEW { w: self } } #[doc = "Bits 12:14 - Configure transition action"] #[inline] pub fn prsact(&mut self) -> _PRSACTW { _PRSACTW { w: self } } #[doc = "Bit 16 - Set interrupt flag enable"] #[inline] pub fn setif(&mut self) -> _SETIFW { _SETIFW { w: self } } #[doc = "Bit 18 - Enable state descriptor chaining"] #[inline] pub fn chain(&mut self) -> _CHAINW { _CHAINW { w: self } } }
24.801153
59
0.495584
28dc30e56a30640fa61e145d82e0eed4aa886972
7,703
// Copyright (c) 2018-2022 The MobileCoin Foundation use core::{ convert::TryFrom, fmt::{Debug, Display}, hash::Hash, result::Result as StdResult, }; use displaydoc::Display; use mc_common::{NodeID, ResponderId, ResponderIdParseError}; use mc_crypto_keys::{DistinguishedEncoding, Ed25519Public, KeyError, SignatureError}; use std::{path::PathBuf, str::FromStr}; use url::Url; /// Wrapper for errors that can occur during conversion to/from `Uri` #[derive(Debug, Display, Ord, PartialOrd, Eq, PartialEq, Clone)] pub enum UriConversionError { /// Error converting key: {0} KeyConversion(KeyError), /// Error with Ed25519 signature Signature, /// Error decoding base64 Base64Decode, /// Error parsing ResponderId {0}, {1} ResponderId(String, ResponderIdParseError), /// No consensus-msg-key provided NoPubkey, } impl From<KeyError> for UriConversionError { fn from(src: KeyError) -> Self { UriConversionError::KeyConversion(src) } } impl From<SignatureError> for UriConversionError { fn from(_src: SignatureError) -> Self { // NOTE: ed25519::signature::Error does not implement Eq/Ord UriConversionError::Signature } } impl From<base64::DecodeError> for UriConversionError { fn from(_src: base64::DecodeError) -> Self { // NOTE: Base64::DecodeError does not implement Eq/Ord UriConversionError::Base64Decode } } impl From<ResponderIdParseError> for UriConversionError { fn from(src: ResponderIdParseError) -> Self { match src.clone() { ResponderIdParseError::FromUtf8Error(contents) => { UriConversionError::ResponderId(hex::encode(contents), src) } ResponderIdParseError::InvalidFormat(contents) => { UriConversionError::ResponderId(contents, src) } } } } /// A base URI trait. pub trait ConnectionUri: Clone + Display + Eq + Hash + Ord + PartialEq + PartialOrd + Send + Sync { /// Retrieve a reference to the underlying Url object. fn url(&self) -> &Url; /// Retreive the host part of the URI. fn host(&self) -> String; /// Retreive the port part of the URI. fn port(&self) -> u16; /// Retrieve the host:port string for this connection. fn addr(&self) -> String; /// Whether TLS should be used for this connection. fn use_tls(&self) -> bool; /// Retrieve the username part of the URI, or an empty string if one is not /// available. fn username(&self) -> String; /// Retrieve the password part of the URI, or an empty string if one is not /// available. fn password(&self) -> String; /// Retrieve the responder id for this connection. fn responder_id(&self) -> StdResult<ResponderId, UriConversionError> { let responder_id_string = self .get_param("responder-id") .unwrap_or_else(|| self.addr()); Ok(ResponderId::from_str(&responder_id_string)?) } /// Retrieve the `NodeID` for this connection. fn node_id(&self) -> StdResult<NodeID, UriConversionError> { Ok(NodeID { responder_id: self.responder_id()?, public_key: self.consensus_msg_key()?, }) } /// Retrieve the Public Key for Message Signing for this connection. /// /// Public keys via URIs are expected to be either hex or base64 encoded, /// with the key algorithm specified in the URI as well, for future /// compatibility with different key schemes. // FIXME: Add key ?algo=ED25519 fn consensus_msg_key(&self) -> StdResult<Ed25519Public, UriConversionError> { if let Some(pubkey) = self.get_param("consensus-msg-key") { match hex::decode(&pubkey) { Ok(pubkey_bytes) => Ok(Ed25519Public::try_from(pubkey_bytes.as_slice())?), Err(_e) => { let pubkey_bytes = base64::decode_config(&pubkey, base64::URL_SAFE)?; Ok(Ed25519Public::try_from_der(&pubkey_bytes)?) } } } else { Err(UriConversionError::NoPubkey) } } /// Get the value of a query parameter, if parameter is available. fn get_param(&self, name: &str) -> Option<String> { self.url().query_pairs().find_map(|(k, v)| { if k == name && !v.is_empty() { Some(v.to_string()) } else { None } }) } /// Get the value of a boolean query parameter. fn get_bool_param(&self, name: &str) -> bool { let p = self.get_param(name).unwrap_or_else(|| "0".into()); p == "1" || p == "true" } /// Optional TLS hostname override. fn tls_hostname_override(&self) -> Option<String> { self.get_param("tls-hostname") } /// Retrieve the CA bundle to use for this connection. If the `ca-bundle` /// query parameter is present, we will error if we fail at loading a /// certificate. When it is not present we will make a best-effort /// attempt and return Ok(None) if no certificate could be loaded. fn ca_bundle(&self) -> StdResult<Option<Vec<u8>>, String> { let ca_bundle_path = self.get_param("ca-bundle").map(PathBuf::from); // If we haven't received a ca-bundle query parameter, we're okay with host_cert // not returning anything. If the ca-bundle query parameter was present // we will propagate errors from `read_ca_bundle`. ca_bundle_path.map_or_else( || Ok(mc_util_host_cert::read_ca_bundle(None).ok()), |bundle_path| mc_util_host_cert::read_ca_bundle(Some(bundle_path)).map(Some), ) } /// Retrieve the TLS chain file path to use for this connection. fn tls_chain_path(&self) -> StdResult<String, String> { self.get_param("tls-chain") .ok_or_else(|| format!("Missing tls-chain query parameter for {}", self.url())) } /// Retrieve the TLS chain to use for this connection. fn tls_chain(&self) -> StdResult<Vec<u8>, String> { let path = self.tls_chain_path()?; std::fs::read(path.clone()) .map_err(|e| format!("Failed reading TLS chain from {}: {:?}", path, e)) } /// Retrieve the TLS key file path to use for this connection. fn tls_key_path(&self) -> StdResult<String, String> { self.get_param("tls-key") .ok_or_else(|| format!("Missing tls-key query parameter for {}", self.url())) } /// Retrieve the TLS key to use for this connection. fn tls_key(&self) -> StdResult<Vec<u8>, String> { let path = self.tls_key_path()?; std::fs::read(path.clone()) .map_err(|e| format!("Failed reading TLS key from {}: {:?}", path, e)) } } /// A trait with associated constants, representing a URI scheme and default /// ports pub trait UriScheme: Debug + Hash + Ord + PartialOrd + Eq + PartialEq + Send + Sync + Clone { /// The prefix for secure URIs const SCHEME_SECURE: &'static str; /// The prefix for insecure URIs const SCHEME_INSECURE: &'static str; /// The default port for secure URIs const DEFAULT_SECURE_PORT: u16; /// The default port for insecure URIs const DEFAULT_INSECURE_PORT: u16; /// When true, ensure the path components of a URI ends with a slash. /// This is genenerally the desired behavior for our URIs since we currently /// do not use any of them to point at a specific file. Having a /// consistent trailing slash ensures that parsing `scheme://host` and /// `scheme://host/` results in equal objects. const NORMALIZE_PATH_TRAILING_SLASH: bool = true; }
36.334906
91
0.631183
e5c473fcc2579be2c0a7de577163af60b080c2ab
3,324
extern crate dirs_sys_next; use std::path::PathBuf; use std::iter::FromIterator; use BaseDirs; use UserDirs; use ProjectDirs; pub fn base_dirs() -> Option<BaseDirs> { let home_dir = dirs_sys_next::known_folder_profile(); let data_dir = dirs_sys_next::known_folder_roaming_app_data(); let data_local_dir = dirs_sys_next::known_folder_local_app_data(); if let (Some(home_dir), Some(data_dir), Some(data_local_dir)) = (home_dir, data_dir, data_local_dir) { let cache_dir = data_local_dir.clone(); let config_dir = data_dir.clone(); let base_dirs = BaseDirs { home_dir: home_dir, cache_dir: cache_dir, config_dir: config_dir, data_dir: data_dir, data_local_dir: data_local_dir, executable_dir: None, runtime_dir: None }; Some(base_dirs) } else { None } } pub fn user_dirs() -> Option<UserDirs> { if let Some(home_dir) = dirs_sys_next::known_folder_profile() { let audio_dir = dirs_sys_next::known_folder_music(); let desktop_dir = dirs_sys_next::known_folder_desktop(); let document_dir = dirs_sys_next::known_folder_documents(); let download_dir = dirs_sys_next::known_folder_downloads(); let picture_dir = dirs_sys_next::known_folder_pictures(); let public_dir = dirs_sys_next::known_folder_public(); let template_dir = dirs_sys_next::known_folder_templates(); let video_dir = dirs_sys_next::known_folder_videos(); let user_dirs = UserDirs { home_dir: home_dir, audio_dir: audio_dir, desktop_dir: desktop_dir, document_dir: document_dir, download_dir: download_dir, font_dir: None, picture_dir: picture_dir, public_dir: public_dir, template_dir: template_dir, video_dir: video_dir }; Some(user_dirs) } else { None } } pub fn project_dirs_from_path(project_path: PathBuf) -> Option<ProjectDirs> { let app_data_local = dirs_sys_next::known_folder_local_app_data(); let app_data_roaming = dirs_sys_next::known_folder_roaming_app_data(); if let (Some(app_data_local), Some(app_data_roaming)) = (app_data_local, app_data_roaming) { let app_data_local = app_data_local.join(&project_path); let app_data_roaming = app_data_roaming.join(&project_path); let cache_dir = app_data_local.join("cache"); let data_local_dir = app_data_local.join("data"); let config_dir = app_data_roaming.join("config"); let data_dir = app_data_roaming.join("data"); let project_dirs = ProjectDirs { project_path: project_path, cache_dir: cache_dir, config_dir: config_dir, data_dir: data_dir, data_local_dir: data_local_dir, runtime_dir: None }; Some(project_dirs) } else { None } } pub fn project_dirs_from(_qualifier: &str, organization: &str, application: &str) -> Option<ProjectDirs> { ProjectDirs::from_path(PathBuf::from_iter(&[organization, application])) }
36.527473
106
0.629964
56b88da4b3bf2899b46bd0f05771cb36597d789c
38,907
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ServiceResource { #[serde(flatten)] pub tracked_resource: TrackedResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ClusterResourceProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub sku: Option<Sku>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TrackedResource { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ClusterResourceProperties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<cluster_resource_properties::ProvisioningState>, #[serde(rename = "networkProfile", default, skip_serializing_if = "Option::is_none")] pub network_profile: Option<NetworkProfile>, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<i32>, #[serde(rename = "serviceId", default, skip_serializing_if = "Option::is_none")] pub service_id: Option<String>, } pub mod cluster_resource_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Deleted, Succeeded, Failed, Moving, Moved, MoveFailed, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagedIdentityProperties { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<managed_identity_properties::Type>, #[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")] pub principal_id: Option<String>, #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, } pub mod managed_identity_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { None, SystemAssigned, UserAssigned, #[serde(rename = "SystemAssigned,UserAssigned")] SystemAssignedUserAssigned, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Sku { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tier: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub capacity: Option<i32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConfigServerSettingsValidateResult { #[serde(rename = "isValid", default, skip_serializing_if = "Option::is_none")] pub is_valid: Option<bool>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub details: Vec<ConfigServerSettingsErrorRecord>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConfigServerSettingsErrorRecord { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub uri: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub messages: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConfigServerResource { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ConfigServerProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConfigServerProperties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<config_server_properties::ProvisioningState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<Error>, #[serde(rename = "configServer", default, skip_serializing_if = "Option::is_none")] pub config_server: Option<ConfigServerSettings>, } pub mod config_server_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { NotAvailable, Deleted, Failed, Succeeded, Updating, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MonitoringSettingResource { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<MonitoringSettingProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MonitoringSettingProperties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<monitoring_setting_properties::ProvisioningState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<Error>, #[serde(rename = "traceEnabled", default, skip_serializing_if = "Option::is_none")] pub trace_enabled: Option<bool>, #[serde(rename = "appInsightsInstrumentationKey", default, skip_serializing_if = "Option::is_none")] pub app_insights_instrumentation_key: Option<String>, #[serde(rename = "appInsightsSamplingRate", default, skip_serializing_if = "Option::is_none")] pub app_insights_sampling_rate: Option<f64>, #[serde(rename = "appInsightsAgentVersions", default, skip_serializing_if = "Option::is_none")] pub app_insights_agent_versions: Option<ApplicationInsightsAgentVersions>, } pub mod monitoring_setting_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { NotAvailable, Failed, Succeeded, Updating, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ApplicationInsightsAgentVersions { #[serde(default, skip_serializing_if = "Option::is_none")] pub java: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NetworkProfile { #[serde(rename = "serviceRuntimeSubnetId", default, skip_serializing_if = "Option::is_none")] pub service_runtime_subnet_id: Option<String>, #[serde(rename = "appSubnetId", default, skip_serializing_if = "Option::is_none")] pub app_subnet_id: Option<String>, #[serde(rename = "serviceCidr", default, skip_serializing_if = "Option::is_none")] pub service_cidr: Option<String>, #[serde(rename = "serviceRuntimeNetworkResourceGroup", default, skip_serializing_if = "Option::is_none")] pub service_runtime_network_resource_group: Option<String>, #[serde(rename = "appNetworkResourceGroup", default, skip_serializing_if = "Option::is_none")] pub app_network_resource_group: Option<String>, #[serde(rename = "outboundIPs", default, skip_serializing_if = "Option::is_none")] pub outbound_i_ps: Option<network_profile::OutboundIPs>, #[serde(rename = "requiredTraffics", default, skip_serializing_if = "Vec::is_empty")] pub required_traffics: Vec<RequiredTraffic>, } pub mod network_profile { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OutboundIPs { #[serde(rename = "publicIPs", default, skip_serializing_if = "Vec::is_empty")] pub public_i_ps: Vec<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RequiredTraffic { #[serde(default, skip_serializing_if = "Option::is_none")] pub protocol: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub port: Option<i32>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub ips: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub fqdns: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub direction: Option<required_traffic::Direction>, } pub mod required_traffic { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Direction { Inbound, Outbound, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Error { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConfigServerSettings { #[serde(rename = "gitProperty", default, skip_serializing_if = "Option::is_none")] pub git_property: Option<ConfigServerGitProperty>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConfigServerGitProperty { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub repositories: Vec<GitPatternRepository>, pub uri: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub label: Option<String>, #[serde(rename = "searchPaths", default, skip_serializing_if = "Vec::is_empty")] pub search_paths: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub username: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub password: Option<String>, #[serde(rename = "hostKey", default, skip_serializing_if = "Option::is_none")] pub host_key: Option<String>, #[serde(rename = "hostKeyAlgorithm", default, skip_serializing_if = "Option::is_none")] pub host_key_algorithm: Option<String>, #[serde(rename = "privateKey", default, skip_serializing_if = "Option::is_none")] pub private_key: Option<String>, #[serde(rename = "strictHostKeyChecking", default, skip_serializing_if = "Option::is_none")] pub strict_host_key_checking: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GitPatternRepository { pub name: String, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub pattern: Vec<String>, pub uri: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub label: Option<String>, #[serde(rename = "searchPaths", default, skip_serializing_if = "Vec::is_empty")] pub search_paths: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub username: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub password: Option<String>, #[serde(rename = "hostKey", default, skip_serializing_if = "Option::is_none")] pub host_key: Option<String>, #[serde(rename = "hostKeyAlgorithm", default, skip_serializing_if = "Option::is_none")] pub host_key_algorithm: Option<String>, #[serde(rename = "privateKey", default, skip_serializing_if = "Option::is_none")] pub private_key: Option<String>, #[serde(rename = "strictHostKeyChecking", default, skip_serializing_if = "Option::is_none")] pub strict_host_key_checking: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TestKeys { #[serde(rename = "primaryKey", default, skip_serializing_if = "Option::is_none")] pub primary_key: Option<String>, #[serde(rename = "secondaryKey", default, skip_serializing_if = "Option::is_none")] pub secondary_key: Option<String>, #[serde(rename = "primaryTestEndpoint", default, skip_serializing_if = "Option::is_none")] pub primary_test_endpoint: Option<String>, #[serde(rename = "secondaryTestEndpoint", default, skip_serializing_if = "Option::is_none")] pub secondary_test_endpoint: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegenerateTestKeyRequestPayload { #[serde(rename = "keyType")] pub key_type: regenerate_test_key_request_payload::KeyType, } pub mod regenerate_test_key_request_payload { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum KeyType { Primary, Secondary, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppResource { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AppResourceProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<ManagedIdentityProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ProxyResource { #[serde(flatten)] pub resource: Resource, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppResourceProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub public: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub url: Option<String>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<app_resource_properties::ProvisioningState>, #[serde(rename = "activeDeploymentName", default, skip_serializing_if = "Option::is_none")] pub active_deployment_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub fqdn: Option<String>, #[serde(rename = "httpsOnly", default, skip_serializing_if = "Option::is_none")] pub https_only: Option<bool>, #[serde(rename = "createdTime", default, skip_serializing_if = "Option::is_none")] pub created_time: Option<String>, #[serde(rename = "temporaryDisk", default, skip_serializing_if = "Option::is_none")] pub temporary_disk: Option<TemporaryDisk>, #[serde(rename = "persistentDisk", default, skip_serializing_if = "Option::is_none")] pub persistent_disk: Option<PersistentDisk>, #[serde(rename = "enableEndToEndTLS", default, skip_serializing_if = "Option::is_none")] pub enable_end_to_end_tls: Option<bool>, } pub mod app_resource_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Succeeded, Failed, Creating, Updating, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TemporaryDisk { #[serde(rename = "sizeInGB", default, skip_serializing_if = "Option::is_none")] pub size_in_gb: Option<i32>, #[serde(rename = "mountPath", default, skip_serializing_if = "Option::is_none")] pub mount_path: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PersistentDisk { #[serde(rename = "sizeInGB", default, skip_serializing_if = "Option::is_none")] pub size_in_gb: Option<i32>, #[serde(rename = "usedInGB", default, skip_serializing_if = "Option::is_none")] pub used_in_gb: Option<i32>, #[serde(rename = "mountPath", default, skip_serializing_if = "Option::is_none")] pub mount_path: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppResourceCollection { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<AppResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceUploadDefinition { #[serde(rename = "relativePath", default, skip_serializing_if = "Option::is_none")] pub relative_path: Option<String>, #[serde(rename = "uploadUrl", default, skip_serializing_if = "Option::is_none")] pub upload_url: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BindingResource { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<BindingResourceProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BindingResourceProperties { #[serde(rename = "resourceName", default, skip_serializing_if = "Option::is_none")] pub resource_name: Option<String>, #[serde(rename = "resourceType", default, skip_serializing_if = "Option::is_none")] pub resource_type: Option<String>, #[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")] pub resource_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub key: Option<String>, #[serde(rename = "bindingParameters", default, skip_serializing_if = "Option::is_none")] pub binding_parameters: Option<serde_json::Value>, #[serde(rename = "generatedProperties", default, skip_serializing_if = "Option::is_none")] pub generated_properties: Option<String>, #[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")] pub created_at: Option<String>, #[serde(rename = "updatedAt", default, skip_serializing_if = "Option::is_none")] pub updated_at: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BindingResourceCollection { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<BindingResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CertificateResource { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CertificateProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CertificateProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub thumbprint: Option<String>, #[serde(rename = "vaultUri")] pub vault_uri: String, #[serde(rename = "keyVaultCertName")] pub key_vault_cert_name: String, #[serde(rename = "certVersion", default, skip_serializing_if = "Option::is_none")] pub cert_version: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub issuer: Option<String>, #[serde(rename = "issuedDate", default, skip_serializing_if = "Option::is_none")] pub issued_date: Option<String>, #[serde(rename = "expirationDate", default, skip_serializing_if = "Option::is_none")] pub expiration_date: Option<String>, #[serde(rename = "activateDate", default, skip_serializing_if = "Option::is_none")] pub activate_date: Option<String>, #[serde(rename = "subjectName", default, skip_serializing_if = "Option::is_none")] pub subject_name: Option<String>, #[serde(rename = "dnsNames", default, skip_serializing_if = "Vec::is_empty")] pub dns_names: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CertificateResourceCollection { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<CertificateResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NameAvailabilityParameters { #[serde(rename = "type")] pub type_: String, pub name: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NameAvailability { #[serde(rename = "nameAvailable", default, skip_serializing_if = "Option::is_none")] pub name_available: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub reason: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomDomainResource { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CustomDomainProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomDomainProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub thumbprint: Option<String>, #[serde(rename = "appName", default, skip_serializing_if = "Option::is_none")] pub app_name: Option<String>, #[serde(rename = "certName", default, skip_serializing_if = "Option::is_none")] pub cert_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomDomainResourceCollection { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<CustomDomainResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomDomainValidatePayload { pub name: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomDomainValidateResult { #[serde(rename = "isValid", default, skip_serializing_if = "Option::is_none")] pub is_valid: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DeploymentResource { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<DeploymentResourceProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub sku: Option<Sku>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DeploymentResourceProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub source: Option<UserSourceInfo>, #[serde(rename = "appName", default, skip_serializing_if = "Option::is_none")] pub app_name: Option<String>, #[serde(rename = "deploymentSettings", default, skip_serializing_if = "Option::is_none")] pub deployment_settings: Option<DeploymentSettings>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<deployment_resource_properties::ProvisioningState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<deployment_resource_properties::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub active: Option<bool>, #[serde(rename = "createdTime", default, skip_serializing_if = "Option::is_none")] pub created_time: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub instances: Vec<DeploymentInstance>, } pub mod deployment_resource_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Succeeded, Failed, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Unknown, Stopped, Running, Failed, Allocating, Upgrading, Compiling, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UserSourceInfo { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<user_source_info::Type>, #[serde(rename = "relativePath", default, skip_serializing_if = "Option::is_none")] pub relative_path: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<String>, #[serde(rename = "artifactSelector", default, skip_serializing_if = "Option::is_none")] pub artifact_selector: Option<String>, #[serde(rename = "customContainer", default, skip_serializing_if = "Option::is_none")] pub custom_container: Option<CustomContainer>, } pub mod user_source_info { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { Jar, NetCoreZip, Source, Container, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomContainer { #[serde(default, skip_serializing_if = "Option::is_none")] pub server: Option<String>, #[serde(rename = "containerImage", default, skip_serializing_if = "Option::is_none")] pub container_image: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub command: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub args: Vec<String>, #[serde(rename = "imageRegistryCredential", default, skip_serializing_if = "Option::is_none")] pub image_registry_credential: Option<ImageRegistryCredential>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ImageRegistryCredential { #[serde(default, skip_serializing_if = "Option::is_none")] pub username: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub password: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DeploymentSettings { #[serde(default, skip_serializing_if = "Option::is_none")] pub cpu: Option<i32>, #[serde(rename = "memoryInGB", default, skip_serializing_if = "Option::is_none")] pub memory_in_gb: Option<i32>, #[serde(rename = "resourceRequests", default, skip_serializing_if = "Option::is_none")] pub resource_requests: Option<ResourceRequests>, #[serde(rename = "jvmOptions", default, skip_serializing_if = "Option::is_none")] pub jvm_options: Option<String>, #[serde(rename = "netCoreMainEntryPath", default, skip_serializing_if = "Option::is_none")] pub net_core_main_entry_path: Option<String>, #[serde(rename = "environmentVariables", default, skip_serializing_if = "Option::is_none")] pub environment_variables: Option<serde_json::Value>, #[serde(rename = "runtimeVersion", default, skip_serializing_if = "Option::is_none")] pub runtime_version: Option<deployment_settings::RuntimeVersion>, } pub mod deployment_settings { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum RuntimeVersion { #[serde(rename = "Java_8")] Java8, #[serde(rename = "Java_11")] Java11, #[serde(rename = "NetCore_31")] NetCore31, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DeploymentInstance { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub reason: Option<String>, #[serde(rename = "discoveryStatus", default, skip_serializing_if = "Option::is_none")] pub discovery_status: Option<String>, #[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DeploymentResourceCollection { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<DeploymentResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceRequests { #[serde(default, skip_serializing_if = "Option::is_none")] pub cpu: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub memory: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LogFileUrlResponse { pub url: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ServiceResourceList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ServiceResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AvailableOperations { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<OperationDetail>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationDetail { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "isDataAction", default, skip_serializing_if = "Option::is_none")] pub is_data_action: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<OperationDisplay>, #[serde(default, skip_serializing_if = "Option::is_none")] pub origin: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<OperationProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationDisplay { #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationProperties { #[serde(rename = "serviceSpecification", default, skip_serializing_if = "Option::is_none")] pub service_specification: Option<ServiceSpecification>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ServiceSpecification { #[serde(rename = "logSpecifications", default, skip_serializing_if = "Vec::is_empty")] pub log_specifications: Vec<LogSpecification>, #[serde(rename = "metricSpecifications", default, skip_serializing_if = "Vec::is_empty")] pub metric_specifications: Vec<MetricSpecification>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LogSpecification { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "blobDuration", default, skip_serializing_if = "Option::is_none")] pub blob_duration: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MetricSpecification { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "displayDescription", default, skip_serializing_if = "Option::is_none")] pub display_description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub unit: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub category: Option<String>, #[serde(rename = "aggregationType", default, skip_serializing_if = "Option::is_none")] pub aggregation_type: Option<String>, #[serde(rename = "supportedAggregationTypes", default, skip_serializing_if = "Vec::is_empty")] pub supported_aggregation_types: Vec<String>, #[serde(rename = "supportedTimeGrainTypes", default, skip_serializing_if = "Vec::is_empty")] pub supported_time_grain_types: Vec<String>, #[serde(rename = "fillGapWithZero", default, skip_serializing_if = "Option::is_none")] pub fill_gap_with_zero: Option<bool>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub dimensions: Vec<MetricDimension>, #[serde(rename = "sourceMdmNamespace", default, skip_serializing_if = "Option::is_none")] pub source_mdm_namespace: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MetricDimension { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "toBeExportedForShoebox", default, skip_serializing_if = "Option::is_none")] pub to_be_exported_for_shoebox: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceSkuCollection { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ResourceSku>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceSku { #[serde(rename = "resourceType", default, skip_serializing_if = "Option::is_none")] pub resource_type: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tier: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub capacity: Option<SkuCapacity>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub locations: Vec<String>, #[serde(rename = "locationInfo", default, skip_serializing_if = "Vec::is_empty")] pub location_info: Vec<ResourceSkuLocationInfo>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub restrictions: Vec<ResourceSkuRestrictions>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SkuCapacity { pub minimum: i32, #[serde(default, skip_serializing_if = "Option::is_none")] pub maximum: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub default: Option<i32>, #[serde(rename = "scaleType", default, skip_serializing_if = "Option::is_none")] pub scale_type: Option<sku_capacity::ScaleType>, } pub mod sku_capacity { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ScaleType { None, Manual, Automatic, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceSkuLocationInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub zones: Vec<String>, #[serde(rename = "zoneDetails", default, skip_serializing_if = "Vec::is_empty")] pub zone_details: Vec<ResourceSkuZoneDetails>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceSkuRestrictions { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<resource_sku_restrictions::Type>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub values: Vec<String>, #[serde(rename = "restrictionInfo", default, skip_serializing_if = "Option::is_none")] pub restriction_info: Option<ResourceSkuRestrictionInfo>, #[serde(rename = "reasonCode", default, skip_serializing_if = "Option::is_none")] pub reason_code: Option<resource_sku_restrictions::ReasonCode>, } pub mod resource_sku_restrictions { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { Location, Zone, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ReasonCode { QuotaId, NotAvailableForSubscription, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceSkuZoneDetails { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub name: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub capabilities: Vec<ResourceSkuCapabilities>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceSkuRestrictionInfo { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub locations: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub zones: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceSkuCapabilities { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudError { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<CloudErrorBody>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudErrorBody { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub details: Vec<CloudErrorBody>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AvailableRuntimeVersions { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<SupportedRuntimeVersion>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SupportedRuntimeVersion { #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<supported_runtime_version::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub platform: Option<supported_runtime_version::Platform>, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<String>, } pub mod supported_runtime_version { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Value { #[serde(rename = "Java_8")] Java8, #[serde(rename = "Java_11")] Java11, #[serde(rename = "NetCore_31")] NetCore31, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Platform { Java, #[serde(rename = ".NET Core")] U2eNetCore, } }
44.062288
109
0.709307
de2a2c85a0c1c43482ea7447bcb10613fb9438b7
1,885
mod buffer; mod counts; mod flow_control; mod prioritize; mod recv; mod send; mod state; mod store; mod stream; mod streams; pub(crate) use self::prioritize::Prioritized; pub(crate) use self::recv::Open; pub(crate) use self::send::PollReset; pub(crate) use self::streams::{DynStreams, OpaqueStreamRef, StreamRef, Streams}; use self::buffer::Buffer; use self::counts::Counts; use self::flow_control::FlowControl; use self::prioritize::Prioritize; use self::recv::Recv; use self::send::Send; use self::state::State; use self::store::Store; use self::stream::Stream; use crate::frame::{StreamId, StreamIdOverflow}; use crate::proto::*; use bytes::Bytes; use std::time::Duration; #[derive(Debug)] pub struct Config { /// Initial window size of locally initiated streams pub local_init_window_sz: WindowSize, /// Initial maximum number of locally initiated streams. /// After receiving a Settings frame from the remote peer, /// the connection will overwrite this value with the /// MAX_CONCURRENT_STREAMS specified in the frame. pub initial_max_send_streams: usize, /// Max amount of DATA bytes to buffer per stream. pub local_max_buffer_size: usize, /// The stream ID to start the next local stream with pub local_next_stream_id: StreamId, /// If the local peer is willing to receive push promises pub local_push_enabled: bool, /// If extended connect protocol is enabled. pub extended_connect_protocol_enabled: bool, /// How long a locally reset stream should ignore frames pub local_reset_duration: Duration, /// Maximum number of locally reset streams to keep at a time pub local_reset_max: usize, /// Initial window size of remote initiated streams pub remote_init_window_sz: WindowSize, /// Maximum number of remote initiated streams pub remote_max_initiated: Option<usize>, }
27.720588
80
0.732626
89deeaa751a538d8da5e079109ad96b6c6fb3c7e
1,344
use crate::errors; use crate::models::Config; use clap::Clap; use colored::*; use log::trace; #[derive(Clap, Debug)] pub struct List {} impl List { pub fn exec(&self) -> Result<(), errors::LeftError> { let config = Config::load().unwrap_or_default(); println!("{}", "\nInstalled themes:".blue().bold()); let mut installed = 0; for repo in config.repos { trace!("Printing themes from {}", &repo.name); for theme in repo.themes { let current = match theme.current { Some(true) => "Current: ".bright_yellow().bold(), _ => "".white(), }; if theme.directory.is_some() { println!( " {}{}/{}: {}", current, repo.name.bright_magenta().bold(), theme.name.bright_green().bold(), theme .description .as_ref() .unwrap_or(&"A LeftWM theme".to_string()) ); installed += 1; } } } if installed == 0 { println!("{}", "No themes installed.".red().bold()); } Ok(()) } }
31.255814
69
0.409226
de50bb3bfed9b1abe8bba0b117837e9e5559d686
6,887
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; use std::unstable::intrinsics::{TyDesc, get_tydesc, visit_tydesc, TyVisitor, Disr, Opaque}; struct MyVisitor { types: ~[~str], } impl TyVisitor for MyVisitor { fn visit_bot(&mut self) -> bool { self.types.push(~"bot"); error!("visited bot type"); true } fn visit_nil(&mut self) -> bool { self.types.push(~"nil"); error!("visited nil type"); true } fn visit_bool(&mut self) -> bool { self.types.push(~"bool"); error!("visited bool type"); true } fn visit_int(&mut self) -> bool { self.types.push(~"int"); error!("visited int type"); true } fn visit_i8(&mut self) -> bool { self.types.push(~"i8"); error!("visited i8 type"); true } fn visit_i16(&mut self) -> bool { self.types.push(~"i16"); error!("visited i16 type"); true } fn visit_i32(&mut self) -> bool { true } fn visit_i64(&mut self) -> bool { true } fn visit_uint(&mut self) -> bool { true } fn visit_u8(&mut self) -> bool { true } fn visit_u16(&mut self) -> bool { true } fn visit_u32(&mut self) -> bool { true } fn visit_u64(&mut self) -> bool { true } fn visit_f32(&mut self) -> bool { true } fn visit_f64(&mut self) -> bool { true } fn visit_char(&mut self) -> bool { true } fn visit_estr_box(&mut self) -> bool { true } fn visit_estr_uniq(&mut self) -> bool { true } fn visit_estr_slice(&mut self) -> bool { true } fn visit_estr_fixed(&mut self, _sz: uint, _sz2: uint, _align: uint) -> bool { true } fn visit_box(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true } fn visit_uniq(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true } fn visit_uniq_managed(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true } fn visit_ptr(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true } fn visit_rptr(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true } fn visit_vec(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true } fn visit_unboxed_vec(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true } fn visit_evec_box(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true } fn visit_evec_uniq(&mut self, _mtbl: uint, inner: *TyDesc) -> bool { self.types.push(~"["); unsafe { visit_tydesc(inner, &mut *self as &mut TyVisitor); } self.types.push(~"]"); true } fn visit_evec_uniq_managed(&mut self, _mtbl: uint, inner: *TyDesc) -> bool { self.types.push(~"["); unsafe { visit_tydesc(inner, &mut *self as &mut TyVisitor) }; self.types.push(~"]"); true } fn visit_evec_slice(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true } fn visit_evec_fixed(&mut self, _n: uint, _sz: uint, _align: uint, _mtbl: uint, _inner: *TyDesc) -> bool { true } fn visit_enter_rec(&mut self, _n_fields: uint, _sz: uint, _align: uint) -> bool { true } fn visit_rec_field(&mut self, _i: uint, _name: &str, _mtbl: uint, _inner: *TyDesc) -> bool { true } fn visit_leave_rec(&mut self, _n_fields: uint, _sz: uint, _align: uint) -> bool { true } fn visit_enter_class(&mut self, _name: &str, _named_fields: bool, _n_fields: uint, _sz: uint, _align: uint) -> bool { true } fn visit_class_field(&mut self, _i: uint, _name: &str, _named: bool, _mtbl: uint, _inner: *TyDesc) -> bool { true } fn visit_leave_class(&mut self, _name: &str, _named_fields: bool, _n_fields: uint, _sz: uint, _align: uint) -> bool { true } fn visit_enter_tup(&mut self, _n_fields: uint, _sz: uint, _align: uint) -> bool { true } fn visit_tup_field(&mut self, _i: uint, _inner: *TyDesc) -> bool { true } fn visit_leave_tup(&mut self, _n_fields: uint, _sz: uint, _align: uint) -> bool { true } fn visit_enter_enum(&mut self, _n_variants: uint, _get_disr: extern unsafe fn(ptr: *Opaque) -> Disr, _sz: uint, _align: uint) -> bool { true } fn visit_enter_enum_variant(&mut self, _variant: uint, _disr_val: Disr, _n_fields: uint, _name: &str) -> bool { true } fn visit_enum_variant_field(&mut self, _i: uint, _offset: uint, _inner: *TyDesc) -> bool { true } fn visit_leave_enum_variant(&mut self, _variant: uint, _disr_val: Disr, _n_fields: uint, _name: &str) -> bool { true } fn visit_leave_enum(&mut self, _n_variants: uint, _get_disr: extern unsafe fn(ptr: *Opaque) -> Disr, _sz: uint, _align: uint) -> bool { true } fn visit_enter_fn(&mut self, _purity: uint, _proto: uint, _n_inputs: uint, _retstyle: uint) -> bool { true } fn visit_fn_input(&mut self, _i: uint, _mode: uint, _inner: *TyDesc) -> bool { true } fn visit_fn_output(&mut self, _retstyle: uint, _variadic: bool, _inner: *TyDesc) -> bool { true } fn visit_leave_fn(&mut self, _purity: uint, _proto: uint, _n_inputs: uint, _retstyle: uint) -> bool { true } fn visit_trait(&mut self, _name: &str) -> bool { true } fn visit_param(&mut self, _i: uint) -> bool { true } fn visit_self(&mut self) -> bool { true } fn visit_type(&mut self) -> bool { true } fn visit_opaque_box(&mut self) -> bool { true } fn visit_closure_ptr(&mut self, _ck: uint) -> bool { true } } fn visit_ty<T>(v: &mut MyVisitor) { unsafe { visit_tydesc(get_tydesc::<T>(), v as &mut TyVisitor) } } pub fn main() { let mut v = MyVisitor {types: ~[]}; visit_ty::<bool>(&mut v); visit_ty::<int>(&mut v); visit_ty::<i8>(&mut v); visit_ty::<i16>(&mut v); visit_ty::<~[int]>(&mut v); for s in v.types.iter() { println!("type: {}", (*s).clone()); } assert_eq!(v.types.clone(), ~[~"bool", ~"int", ~"i8", ~"i16", ~"[", ~"int", ~"]"]); }
40.751479
101
0.557863
3350116ebbe2fb1a841e5f2a5f6abe20791bce4d
1,159
use sp_runtime::RuntimeDebug; use codec::{Decode, Encode}; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; #[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, PartialOrd, Ord)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub enum CurrencyId { Native, TokenSymbol { code: [u8; 4] }, } pub trait StellarAsset { fn asset_code(&self) -> Option<[u8; 4]>; } impl StellarAsset for CurrencyId { fn asset_code(&self) -> Option<[u8; 4]> { match self { CurrencyId::TokenSymbol { code } => Some(*code), _ => None, } } } impl CurrencyId { pub fn create_from_slice(slice: &str) -> Self { if slice.len() <= 4 { let mut code: [u8; 4] = [0; 4]; code[..slice.len()].copy_from_slice(slice.as_bytes()); CurrencyId::TokenSymbol { code } } else { panic!("More than 4 bytes not supported") } } pub fn create_from_bytes(code: [u8; 4]) -> Self { CurrencyId::TokenSymbol { code } } } impl Default for CurrencyId { fn default() -> Self { CurrencyId::Native } }
23.653061
84
0.57377
e6182bbcc884e6cbe6f5bf08a44d940e483bbd4c
1,581
#[doc = "Register `T32RIS2` reader"] pub struct R(crate::R<T32RIS2_SPEC>); impl core::ops::Deref for R { type Target = crate::R<T32RIS2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::convert::From<crate::R<T32RIS2_SPEC>> for R { fn from(reader: crate::R<T32RIS2_SPEC>) -> Self { R(reader) } } #[doc = "Field `RAW_IFG` reader - Raw interrupt status"] pub struct RAW_IFG_R(crate::FieldReader<bool, bool>); impl RAW_IFG_R { pub(crate) fn new(bits: bool) -> Self { RAW_IFG_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for RAW_IFG_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bit 0 - Raw interrupt status"] #[inline(always)] pub fn raw_ifg(&self) -> RAW_IFG_R { RAW_IFG_R::new((self.bits & 0x01) != 0) } } #[doc = "Timer 2 Raw Interrupt Status Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [t32ris2](index.html) module"] pub struct T32RIS2_SPEC; impl crate::RegisterSpec for T32RIS2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [t32ris2::R](R) reader structure"] impl crate::Readable for T32RIS2_SPEC { type Reader = R; } #[doc = "`reset()` method sets T32RIS2 to value 0"] impl crate::Resettable for T32RIS2_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
30.403846
247
0.630614
0afc884d8217275f73fd9f1e7fb3040efe305b37
1,766
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://openapi-generator.tech */ #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct PipelineImpl { #[serde(rename = "_class", skip_serializing_if = "Option::is_none")] pub _class: Option<String>, #[serde(rename = "displayName", skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "estimatedDurationInMillis", skip_serializing_if = "Option::is_none")] pub estimated_duration_in_millis: Option<i32>, #[serde(rename = "fullName", skip_serializing_if = "Option::is_none")] pub full_name: Option<String>, #[serde(rename = "latestRun", skip_serializing_if = "Option::is_none")] pub latest_run: Option<String>, #[serde(rename = "name", skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "organization", skip_serializing_if = "Option::is_none")] pub organization: Option<String>, #[serde(rename = "weatherScore", skip_serializing_if = "Option::is_none")] pub weather_score: Option<i32>, #[serde(rename = "_links", skip_serializing_if = "Option::is_none")] pub _links: Option<Box<crate::models::PipelineImpllinks>>, } impl PipelineImpl { pub fn new() -> PipelineImpl { PipelineImpl { _class: None, display_name: None, estimated_duration_in_millis: None, full_name: None, latest_run: None, name: None, organization: None, weather_score: None, _links: None, } } }
33.320755
91
0.654587
ffc25e82f885e2dedd004adda7f3527636d4100d
772
// https://leetcode-cn.com/problems/number-of-substrings-with-only-1s/ // Runtime: 4 ms // Memory Usage: 2.1 MB const MOD: i64 = 1_000_000_007; pub fn num_sub(s: String) -> i32 { let mut res: i64 = 0; let mut it = s.chars().peekable(); while let Some(c) = it.next() { if c == '1' { let mut n = 1; while let Some('1') = it.peek() { it.next(); n += 1; } res += n * (n + 1) / 2; res %= MOD; } } res as i32 } // math string #[test] fn test2_1513() { assert_eq!(num_sub("0110111".to_string()), 9); assert_eq!(num_sub("101".to_string()), 2); assert_eq!(num_sub("111111".to_string()), 21); assert_eq!(num_sub("000".to_string()), 0); }
26.62069
70
0.503886
90052a2a89569483684c0a9dd429c535802bca0a
15,805
use self::ctx::Ctx; use crate::{ debug::{dump, AssertValid}, marks::Marks, mode::Mode, option::CompressOptions, util::ModuleItemExt, MAX_PAR_DEPTH, }; use rayon::prelude::*; use swc_common::{pass::Repeated, util::take::Take, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith, VisitWith}; use tracing::{span, Level}; mod arrows; mod bools; mod conds; mod ctx; mod dead_code; mod evaluate; mod if_return; mod loops; mod misc; mod numbers; mod properties; mod sequences; mod strings; mod unsafes; mod vars; pub(crate) fn pure_optimizer<'a, M>( options: &'a CompressOptions, marks: Marks, mode: &'a M, debug_infinite_loop: bool, ) -> impl 'a + VisitMut + Repeated where M: Mode, { Pure { options, marks, ctx: Default::default(), changed: Default::default(), mode, debug_infinite_loop, } } struct Pure<'a, M> { options: &'a CompressOptions, marks: Marks, ctx: Ctx, changed: bool, mode: &'a M, debug_infinite_loop: bool, } impl<M> Repeated for Pure<'_, M> { fn changed(&self) -> bool { self.changed } fn reset(&mut self) { self.ctx = Default::default(); self.changed = false; } } impl<M> Pure<'_, M> where M: Mode, { fn handle_stmt_likes<T>(&mut self, stmts: &mut Vec<T>) where T: ModuleItemExt, Vec<T>: VisitWith<self::vars::VarWithOutInitCounter> + VisitMutWith<self::vars::VarPrepender> + VisitMutWith<self::vars::VarMover>, { self.remove_dead_branch(stmts); self.remove_unreachable_stmts(stmts); self.drop_useless_blocks(stmts); self.collapse_vars_without_init(stmts); stmts.retain(|s| match s.as_stmt() { Some(Stmt::Empty(..)) => false, _ => true, }); } fn optimize_fn_stmts(&mut self, stmts: &mut Vec<Stmt>) { self.drop_unreachable_stmts(stmts); self.remove_useless_return(stmts); self.negate_if_terminate(stmts, true, false); if let Some(last) = stmts.last_mut() { self.drop_unused_stmt_at_end_of_fn(last); } } /// Visit `nodes`, maybe in parallel. fn visit_par<N>(&mut self, nodes: &mut Vec<N>) where N: for<'aa> VisitMutWith<Pure<'aa, M>> + Send + Sync, { if self.ctx.par_depth >= MAX_PAR_DEPTH * 2 || cfg!(target_arch = "wasm32") { for node in nodes { let mut v = Pure { options: self.options, marks: self.marks, ctx: self.ctx, changed: false, mode: self.mode, debug_infinite_loop: self.debug_infinite_loop, }; node.visit_mut_with(&mut v); self.changed |= v.changed; } } else { let changed = nodes .par_iter_mut() .map(|node| { let mut v = Pure { options: self.options, marks: self.marks, ctx: Ctx { par_depth: self.ctx.par_depth + 1, ..self.ctx }, changed: false, mode: self.mode, debug_infinite_loop: self.debug_infinite_loop, }; node.visit_mut_with(&mut v); v.changed }) .reduce(|| false, |a, b| a || b); self.changed |= changed; } } } impl<M> VisitMut for Pure<'_, M> where M: Mode, { noop_visit_mut_type!(); fn visit_mut_assign_expr(&mut self, e: &mut AssignExpr) { { let ctx = Ctx { is_lhs_of_assign: true, ..self.ctx }; e.left.visit_mut_children_with(&mut *self.with_ctx(ctx)); } e.right.visit_mut_with(self); } fn visit_mut_bin_expr(&mut self, e: &mut BinExpr) { e.visit_mut_children_with(self); self.compress_cmp_with_long_op(e); self.optimize_cmp_with_null_or_undefined(e); if e.op == op!(bin, "+") { self.concat_tpl(&mut e.left, &mut e.right); } } fn visit_mut_block_stmt_or_expr(&mut self, body: &mut BlockStmtOrExpr) { body.visit_mut_children_with(self); match body { BlockStmtOrExpr::BlockStmt(b) => self.optimize_fn_stmts(&mut b.stmts), BlockStmtOrExpr::Expr(_) => {} } self.optimize_arrow_body(body); } fn visit_mut_call_expr(&mut self, e: &mut CallExpr) { { let ctx = Ctx { is_callee: true, ..self.ctx }; e.callee.visit_mut_with(&mut *self.with_ctx(ctx)); } e.args.visit_mut_with(self); self.drop_arguments_of_symbol_call(e); } fn visit_mut_cond_expr(&mut self, e: &mut CondExpr) { e.visit_mut_children_with(self); self.optimize_expr_in_bool_ctx(&mut e.test); self.negate_cond_expr(e); } fn visit_mut_expr(&mut self, e: &mut Expr) { { let ctx = Ctx { in_first_expr: false, ..self.ctx }; e.visit_mut_children_with(&mut *self.with_ctx(ctx)); } self.remove_invalid(e); match e { Expr::Seq(seq) => { if seq.exprs.is_empty() { *e = Expr::Invalid(Invalid { span: DUMMY_SP }); return; } if seq.exprs.len() == 1 { self.changed = true; *e = *seq.exprs.take().into_iter().next().unwrap(); } } _ => {} } self.eval_opt_chain(e); self.eval_number_call(e); self.eval_number_method_call(e); self.swap_bin_operands(e); self.handle_property_access(e); self.optimize_bools(e); self.drop_logical_operands(e); self.lift_minus(e); self.convert_tpl_to_str(e); self.drop_useless_addition_of_str(e); self.compress_useless_deletes(e); self.remove_useless_logical_rhs(e); self.handle_negated_seq(e); self.concat_str(e); self.eval_array_method_call(e); self.eval_fn_method_call(e); self.eval_str_method_call(e); self.compress_conds_as_logical(e); self.compress_cond_with_logical_as_logical(e); self.lift_seqs_of_bin(e); self.lift_seqs_of_cond_assign(e); } fn visit_mut_expr_stmt(&mut self, s: &mut ExprStmt) { s.visit_mut_children_with(self); self.ignore_return_value(&mut s.expr); } fn visit_mut_exprs(&mut self, exprs: &mut Vec<Box<Expr>>) { self.visit_par(exprs); } fn visit_mut_for_in_stmt(&mut self, n: &mut ForInStmt) { n.right.visit_mut_with(self); n.left.visit_mut_with(self); n.body.visit_mut_with(self); match &mut *n.body { Stmt::Block(body) => { self.negate_if_terminate(&mut body.stmts, false, true); } _ => {} } } fn visit_mut_for_of_stmt(&mut self, n: &mut ForOfStmt) { n.right.visit_mut_with(self); n.left.visit_mut_with(self); n.body.visit_mut_with(self); match &mut *n.body { Stmt::Block(body) => { self.negate_if_terminate(&mut body.stmts, false, true); } _ => {} } } fn visit_mut_for_stmt(&mut self, s: &mut ForStmt) { s.visit_mut_children_with(self); self.merge_for_if_break(s); if let Some(test) = &mut s.test { self.optimize_expr_in_bool_ctx(&mut **test); } match &mut *s.body { Stmt::Block(body) => { self.negate_if_terminate(&mut body.stmts, false, true); } _ => {} } } fn visit_mut_function(&mut self, f: &mut Function) { { let ctx = Ctx { _in_try_block: false, ..self.ctx }; f.visit_mut_children_with(&mut *self.with_ctx(ctx)); } if let Some(body) = &mut f.body { self.optimize_fn_stmts(&mut body.stmts) } } fn visit_mut_if_stmt(&mut self, s: &mut IfStmt) { s.visit_mut_children_with(self); self.optimize_expr_in_bool_ctx(&mut s.test); } fn visit_mut_member_expr(&mut self, e: &mut MemberExpr) { e.obj.visit_mut_with(self); if let MemberProp::Computed(c) = &mut e.prop { c.visit_mut_with(self); // TODO: unify these two if let Some(ident) = self.optimize_property_of_member_expr(Some(&e.obj), c) { e.prop = MemberProp::Ident(ident); return; }; if let Some(ident) = self.handle_known_computed_member_expr(c) { e.prop = MemberProp::Ident(ident) }; } } fn visit_mut_super_prop_expr(&mut self, e: &mut SuperPropExpr) { if let SuperProp::Computed(c) = &mut e.prop { c.visit_mut_with(self); if let Some(ident) = self.optimize_property_of_member_expr(None, c) { e.prop = SuperProp::Ident(ident); return; }; if let Some(ident) = self.handle_known_computed_member_expr(c) { e.prop = SuperProp::Ident(ident) }; } } fn visit_mut_module_items(&mut self, items: &mut Vec<ModuleItem>) { self.visit_par(items); self.handle_stmt_likes(items); } fn visit_mut_new_expr(&mut self, e: &mut NewExpr) { { let ctx = Ctx { is_callee: true, ..self.ctx }; e.callee.visit_mut_with(&mut *self.with_ctx(ctx)); } e.args.visit_mut_with(self); } fn visit_mut_prop(&mut self, p: &mut Prop) { p.visit_mut_children_with(self); self.optimize_arrow_method_prop(p); if cfg!(feature = "debug") && cfg!(debug_assertions) { p.visit_with(&mut AssertValid); } } fn visit_mut_prop_name(&mut self, p: &mut PropName) { p.visit_mut_children_with(self); self.optimize_computed_prop_name_as_normal(p); self.optimize_prop_name(p); } fn visit_mut_prop_or_spreads(&mut self, exprs: &mut Vec<PropOrSpread>) { self.visit_par(exprs); } fn visit_mut_return_stmt(&mut self, s: &mut ReturnStmt) { s.visit_mut_children_with(self); self.drop_undefined_from_return_arg(s); } fn visit_mut_seq_expr(&mut self, e: &mut SeqExpr) { e.visit_mut_children_with(self); e.exprs.retain(|e| { if e.is_invalid() { self.changed = true; tracing::debug!("Removing invalid expr in seq"); return false; } true }); if e.exprs.len() == 0 { return; } self.merge_seq_call(e); let len = e.exprs.len(); for (idx, e) in e.exprs.iter_mut().enumerate() { let is_last = idx == len - 1; if !is_last { self.ignore_return_value(&mut **e); } } e.exprs.retain(|e| !e.is_invalid()); } fn visit_mut_stmt(&mut self, s: &mut Stmt) { let _tracing = if cfg!(feature = "debug") && self.debug_infinite_loop { let text = dump(&*s, false); if text.lines().count() < 10 { Some(span!(Level::ERROR, "visit_mut_stmt", "start" = &*text).entered()) } else { None } } else { None }; { let ctx = Ctx { is_update_arg: false, is_callee: false, in_delete: false, in_first_expr: true, ..self.ctx }; s.visit_mut_children_with(&mut *self.with_ctx(ctx)); } if cfg!(feature = "debug") && self.debug_infinite_loop { let text = dump(&*s, false); if text.lines().count() < 10 { tracing::debug!("after: visit_mut_children_with: {}", text); } } if self.options.drop_debugger { match s { Stmt::Debugger(..) => { self.changed = true; *s = Stmt::Empty(EmptyStmt { span: DUMMY_SP }); tracing::debug!("drop_debugger: Dropped a debugger statement"); return; } _ => {} } } self.loop_to_for_stmt(s); match s { Stmt::Expr(es) => { if es.expr.is_invalid() { *s = Stmt::Empty(EmptyStmt { span: DUMMY_SP }); return; } } _ => {} } if cfg!(feature = "debug") && self.debug_infinite_loop { let text = dump(&*s, false); if text.lines().count() < 10 { tracing::debug!("after: visit_mut_stmt: {}", text); } } if cfg!(feature = "debug") && cfg!(debug_assertions) { s.visit_with(&mut AssertValid); } } fn visit_mut_stmts(&mut self, items: &mut Vec<Stmt>) { self.visit_par(items); self.handle_stmt_likes(items); items.retain(|s| match s { Stmt::Empty(..) => false, _ => true, }); if cfg!(feature = "debug") && cfg!(debug_assertions) { items.visit_with(&mut AssertValid); } } /// We don't optimize [Tpl] contained in [TaggedTpl]. fn visit_mut_tagged_tpl(&mut self, n: &mut TaggedTpl) { n.tag.visit_mut_with(self); } fn visit_mut_tpl(&mut self, n: &mut Tpl) { n.visit_mut_children_with(self); debug_assert_eq!(n.exprs.len() + 1, n.quasis.len()); self.compress_tpl(n); debug_assert_eq!( n.exprs.len() + 1, n.quasis.len(), "tagged template literal compressor created an invalid template literal" ); } fn visit_mut_try_stmt(&mut self, n: &mut TryStmt) { let ctx = Ctx { _in_try_block: true, ..self.ctx }; n.block.visit_mut_with(&mut *self.with_ctx(ctx)); n.handler.visit_mut_with(self); n.finalizer.visit_mut_with(self); } fn visit_mut_unary_expr(&mut self, e: &mut UnaryExpr) { { let ctx = Ctx { in_delete: e.op == op!("delete"), ..self.ctx }; e.visit_mut_children_with(&mut *self.with_ctx(ctx)); } match e.op { op!("!") => { self.optimize_expr_in_bool_ctx(&mut e.arg); } op!(unary, "+") | op!(unary, "-") => { self.optimize_expr_in_num_ctx(&mut e.arg); } _ => {} } } fn visit_mut_update_expr(&mut self, e: &mut UpdateExpr) { let ctx = Ctx { is_update_arg: true, ..self.ctx }; e.visit_mut_children_with(&mut *self.with_ctx(ctx)); } fn visit_mut_while_stmt(&mut self, s: &mut WhileStmt) { s.visit_mut_children_with(self); self.optimize_expr_in_bool_ctx(&mut s.test); } }
25.491935
89
0.512306
e880e8d0ae75dfbf7fb7c66a7ecc1da73ae5f594
1,121
// This file is part of Substrate. // Copyright (C) 2020-2021 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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. /// The error type used by the allocators. #[derive(thiserror::Error, Debug)] pub enum Error { /// Someone tried to allocate more memory than the allowed maximum per allocation. #[error("Requested allocation size is too large")] RequestedAllocationTooLarge, /// Allocator run out of space. #[error("Allocator ran out of space")] AllocatorOutOfSpace, /// Some other error occurred. #[error("Other: {0}")] Other(&'static str) }
36.16129
83
0.73595
e6418122cd6c9c8130ca524bba1e1306004502f4
12,855
extern crate cli_test_dir; extern crate sit_core; extern crate which; extern crate remove_dir_all; use std::process; use sit_core::{Repository, record::RecordOwningContainer, path::ResolvePath}; use cli_test_dir::*; use remove_dir_all::*; include!("includes/config.rs"); /// Should list no records if there are none #[test] fn no_records() { let dir = TestDir::new("sit", "no_records"); dir.cmd() .arg("init") .expect_success(); let output = String::from_utf8(dir.cmd().args(&["records"]).expect_success().stdout).unwrap(); assert_eq!(output, ""); } /// Should list a record for item if there's one #[test] #[cfg(feature = "deprecated-items")] fn record_for_item() { let dir = TestDir::new("sit", "rec_item_record"); dir.cmd() .arg("init") .expect_success(); let id = String::from_utf8(dir.cmd().arg("item").expect_success().stdout).unwrap(); let record = String::from_utf8(dir.cmd().args(&["record", id.trim(), "--no-author", "-t", "Type"]).expect_success().stdout).unwrap(); let output = String::from_utf8(dir.cmd().args(&["records", id.trim()]).expect_success().stdout).unwrap(); assert_eq!(output, record); } /// Should list a record if there's one #[test] fn record() { let dir = TestDir::new("sit", "rec_record"); dir.cmd() .arg("init") .expect_success(); let record = String::from_utf8(dir.cmd().args(&["record", "--no-author", "-t", "Type"]).expect_success().stdout).unwrap(); let output = String::from_utf8(dir.cmd().args(&["records" ]).expect_success().stdout).unwrap(); assert_eq!(output, record); } /// Should apply filter #[test] fn filter() { let dir = TestDir::new("sit", "rec_filter"); dir.cmd() .arg("init") .expect_success(); let record = String::from_utf8(dir.cmd().args(&["record", "--no-author", "-t", "Type"]).expect_success().stdout).unwrap(); let record1 = String::from_utf8(dir.cmd().args(&["record", "--no-author", "-t", "Type"]).expect_success().stdout).unwrap(); // filter out item we just created let output = String::from_utf8(dir.cmd().args(&["records", "-f", &format!("hash != '{}'", record.trim())]).expect_success().stdout).unwrap(); assert_eq!(output, record1); } /// Should apply filter #[test] fn named_filter() { let dir = TestDir::new("sit", "rec_named_filter"); dir.cmd() .arg("init") .expect_success(); let record = String::from_utf8(dir.cmd().args(&["record", "--no-author", "-t", "Type"]).expect_success().stdout).unwrap(); let record1 = String::from_utf8(dir.cmd().args(&["record", "--no-author", "-t", "Type"]).expect_success().stdout).unwrap(); // filter out item we just created dir.create_file(".sit/.records/filters/f1", &format!("hash != '{}'", record.trim())); let output = String::from_utf8(dir.cmd().args(&["records", "-F", "f1"]).expect_success().stdout).unwrap(); assert_eq!(output, record1); } /// Should apply named user filter #[test] fn named_user_filter() { let dir = TestDir::new("sit", "rec_named_filter"); dir.cmd() .arg("init") .expect_success(); let record = String::from_utf8(dir.cmd().args(&["record", "--no-author", "-t", "Type"]).expect_success().stdout).unwrap(); let record1 = String::from_utf8(dir.cmd().args(&["record", "--no-author", "-t", "Type"]).expect_success().stdout).unwrap(); // filter out item we just created let cfg = &format!(r#"{{"records": {{"filters": {{"f1": "hash != '{}'"}}}}}}"#, record.trim()); user_config(&dir, cfg); let output = String::from_utf8(dir.cmd() .env("HOME", dir.path(".").to_str().unwrap()) .env("USERPROFILE", dir.path(".").to_str().unwrap()) .args(&["records", "-F", "f1"]).expect_success().stdout).unwrap(); assert_eq!(output, record1); } /// Should prefer repo named filter over user named filer #[test] fn repo_over_named_user_filter() { let dir = TestDir::new("sit", "rec_named_repo_over_user_filter"); dir.cmd() .arg("init") .expect_success(); let record = String::from_utf8(dir.cmd().args(&["record", "--no-author", "-t", "Type"]).expect_success().stdout).unwrap(); let record1 = String::from_utf8(dir.cmd().args(&["record", "--no-author", "-t", "Type"]).expect_success().stdout).unwrap(); // filter out item we just created let cfg = &format!(r#"{{"records": {{"filters": {{"f1": "hash != '{}'"}}}}}}"#, record1.trim()); user_config(&dir, cfg); dir.create_file(".sit/.records/filters/f1", &format!("hash != '{}'", record1.trim())); let output = String::from_utf8(dir.cmd() .env("HOME", dir.path(".").to_str().unwrap()) .env("USERPROFILE", dir.path(".").to_str().unwrap()) .args(&["records", "-F", "f1"]).expect_success().stdout).unwrap(); assert_eq!(output, record); } /// Should apply query #[test] fn query() { let dir = TestDir::new("sit", "rec_query"); dir.cmd() .arg("init") .expect_success(); let repo = Repository::open(dir.path(".sit")).unwrap(); // create a record let _record = repo.new_record(vec![("test", &b"passed"[..])].into_iter(), true).unwrap(); let output = String::from_utf8(dir.cmd().args(&["records", "-q", "files.test"]).expect_success().stdout).unwrap(); assert_eq!(output.trim(), "passed"); } /// Should apply named query #[test] fn named_query() { let dir = TestDir::new("sit", "rec_named_query"); dir.cmd() .arg("init") .expect_success(); let repo = Repository::open(dir.path(".sit")).unwrap(); // create a record let _record = repo.new_record(vec![("test", &b"passed"[..])].into_iter(), true).unwrap(); dir.create_file(".sit/.records/queries/q1", "files.test"); let output = String::from_utf8(dir.cmd().args(&["records","-Q", "q1"]).expect_success().stdout).unwrap(); assert_eq!(output.trim(), "passed"); } /// Should apply named user query #[test] fn named_user_query() { let dir = TestDir::new("sit", "rec_named_user_query"); dir.cmd() .arg("init") .expect_success(); let repo = Repository::open(dir.path(".sit")).unwrap(); // create a record let _record = repo.new_record(vec![("test", &b"passed"[..])].into_iter(), true).unwrap(); let cfg = r#"{"records": {"queries": {"q1": "files.test"}}}"#; user_config(&dir, cfg); let output = String::from_utf8(dir.cmd() .env("HOME", dir.path(".").to_str().unwrap()) .env("USERPROFILE", dir.path(".").to_str().unwrap()) .args(&["records", "-Q", "q1"]).expect_success().stdout).unwrap(); assert_eq!(output.trim(), "passed"); } /// Should prefer repo named query over user user named query #[test] fn repo_over_named_user_query() { let dir = TestDir::new("sit", "rec_repo_over_named_user_query"); dir.cmd() .arg("init") .expect_success(); let repo = Repository::open(dir.path(".sit")).unwrap(); // create a record let _record = repo.new_record(vec![("test", &b"passed"[..])].into_iter(), true).unwrap(); dir.create_file(".sit/.records/queries/q1", "files.test"); let cfg = r#"{"records": {"queries": {"q1": "null"}}}"#; user_config(&dir, cfg); let output = String::from_utf8(dir.cmd() .env("HOME", dir.path(".").to_str().unwrap()) .env("USERPROFILE", dir.path(".").to_str().unwrap()) .args(&["records", "-Q", "q1"]).expect_success().stdout).unwrap(); assert_eq!(output.trim(), "passed"); } /// Should verify PGP signature if instructed #[test] fn pgp_signature() { let dir = TestDir::new("sit", "pgp"); no_user_config(&dir); let gpg = which::which("gpg2").or_else(|_| which::which("gpg")).expect("should have gpg installed"); let mut genkey = process::Command::new(&gpg) .args(&["--batch", "--gen-key","-"]) .env("GNUPGHOME", dir.path(".").to_str().unwrap()) .stdin(::std::process::Stdio::piped()) .stdout(::std::process::Stdio::null()) .stderr(::std::process::Stdio::null()) .spawn().unwrap(); { use std::io::Write; let stdin = genkey.stdin.as_mut().expect("Failed to open stdin"); stdin.write_all(r#" Key-Type: default Subkey-Type: default Name-Real: Test Name-Comment: Test Name-Email: test@test.com Expire-Date: 0 %no-protection %commit "#.as_bytes()).expect("Failed to write to stdin"); } genkey.expect_success(); dir.cmd() .arg("init") .expect_success(); dir.cmd() .env("HOME", dir.path(".").to_str().unwrap()) // to ensure there are right configs .env("USERPROFILE", dir.path(".").to_str().unwrap()) .env("GNUPGHOME", dir.path(".").to_str().unwrap()) .args(&["record", "--sign", "--signing-key", "test@test.com", "--no-author", "-t","Sometype"]) .expect_success(); let output = String::from_utf8(dir.cmd() .env("HOME", dir.path(".").to_str().unwrap()) .env("USERPROFILE", dir.path(".").to_str().unwrap()) .env("GNUPGHOME", dir.path(".").to_str().unwrap()) .args(&["records", "-v", "-q", "verification.success"]).expect_success().stdout).unwrap(); assert_eq!(output.trim(), "true"); } /// Should indicate if PGP signature is for something else #[test] fn pgp_signature_wrong_data() { let dir = TestDir::new("sit", "pgps"); no_user_config(&dir); let gpg = which::which("gpg2").or_else(|_| which::which("gpg")).expect("should have gpg installed"); let mut genkey = process::Command::new(&gpg) .args(&["--batch", "--gen-key","-"]) .env("GNUPGHOME", dir.path(".").to_str().unwrap()) .stdin(::std::process::Stdio::piped()) .stdout(::std::process::Stdio::null()) .stderr(::std::process::Stdio::null()) .spawn().unwrap(); { use std::io::Write; let stdin = genkey.stdin.as_mut().expect("Failed to open stdin"); stdin.write_all(r#" Key-Type: default Subkey-Type: default Name-Real: Test Name-Comment: Test Name-Email: test@test.com Expire-Date: 0 %no-protection %commit "#.as_bytes()).expect("Failed to write to stdin"); } genkey.expect_success(); dir.cmd() .arg("init") .expect_success(); // Snatch the signature let oldrec = String::from_utf8(dir.cmd() .env("HOME", dir.path(".").to_str().unwrap()) // to ensure there are right configs .env("USERPROFILE", dir.path(".").to_str().unwrap()) .env("GNUPGHOME", dir.path(".").to_str().unwrap()) .args(&["record", "--sign", "--signing-key", "test@test.com", "--no-author", "-t","Sometype"]) .expect_success().stdout).unwrap(); use std::path::PathBuf; let oldrec_path: PathBuf = String::from_utf8(dir.cmd().args(&["path","--record", oldrec.trim()]).expect_success().stdout) .unwrap().trim().into(); use std::fs::File; use std::io::{Read, Write}; let mut f = File::open(oldrec_path.resolve_dir("/").unwrap().join(".signature")).unwrap(); let mut s = String::new(); f.read_to_string(&mut s).unwrap(); remove_dir_all(oldrec_path.resolve_dir("/").unwrap()).unwrap(); let mut f = File::create(dir.path(".signature")).unwrap(); f.write(s.as_bytes()).unwrap(); // dir.cmd() .env("HOME", dir.path(".").to_str().unwrap()) // to ensure there are right configs .env("USERPROFILE", dir.path(".").to_str().unwrap()) .env("GNUPGHOME", dir.path(".").to_str().unwrap()) .args(&["record", "--no-author", "-t","Sometype1", ".signature"]) .expect_success(); let output = String::from_utf8(dir.cmd() .env("HOME", dir.path(".").to_str().unwrap()) .env("USERPROFILE", dir.path(".").to_str().unwrap()) .env("GNUPGHOME", dir.path(".").to_str().unwrap()) .args(&["records", "-v", "-q", "verification.success"]).expect_success().stdout).unwrap(); assert_eq!(output.trim(), "false"); } /// Should not verify PGP key if there is no signature #[test] fn pgp_no_signature() { let dir = TestDir::new("sit", "pgpno"); no_user_config(&dir); dir.cmd() .arg("init") .expect_success(); dir.cmd() .env("HOME", dir.path(".").to_str().unwrap()) // to ensure there are right configs .env("USERPROFILE", dir.path(".").to_str().unwrap()) .args(&["record", "--no-author", "-t","Sometype"]) .expect_success(); let output = String::from_utf8(dir.cmd() .env("HOME", dir.path(".").to_str().unwrap()) .env("USERPROFILE", dir.path(".").to_str().unwrap()) .args(&["records", "-v", "-q", "verification"]).expect_success().stdout).unwrap(); assert_eq!(output.trim(), "null"); }
37.587719
145
0.585298
218070a5c03b2ad80bdce1106dcd1560bf9acf92
6,300
//! Defines the `Backend` trait. use crate::DataContext; use crate::DataId; use crate::FuncId; use crate::Linkage; use crate::ModuleNamespace; use crate::ModuleResult; use core::marker; use cranelift_codegen::isa::TargetIsa; use cranelift_codegen::Context; use cranelift_codegen::{binemit, ir}; use std::borrow::ToOwned; use std::boxed::Box; use std::string::String; /// A `Backend` implements the functionality needed to support a `Module`. /// /// Three notable implementations of this trait are: /// - `SimpleJITBackend`, defined in [cranelift-simplejit], which JITs /// the contents of a `Module` to memory which can be directly executed. /// - `ObjectBackend`, defined in [cranelift-object], which writes the /// contents of a `Module` out as a native object file. /// - `FaerieBackend`, defined in [cranelift-faerie], which writes the /// contents of a `Module` out as a native object file. /// /// [cranelift-simplejit]: https://docs.rs/cranelift-simplejit/ /// [cranelift-object]: https://docs.rs/cranelift-object/ /// [cranelift-faerie]: https://docs.rs/cranelift-faerie/ pub trait Backend where Self: marker::Sized, { /// A builder for constructing `Backend` instances. type Builder; /// The results of compiling a function. type CompiledFunction; /// The results of "compiling" a data object. type CompiledData; /// The completed output artifact for a function, if this is meaningful for /// the `Backend`. type FinalizedFunction; /// The completed output artifact for a data object, if this is meaningful for /// the `Backend`. type FinalizedData; /// This is an object returned by `Module`'s /// [`finish`](struct.Module.html#method.finish) function, /// if the `Backend` has a purpose for this. type Product; /// Create a new `Backend` instance. fn new(_: Self::Builder) -> Self; /// Return the `TargetIsa` to compile for. fn isa(&self) -> &dyn TargetIsa; /// Declare a function. fn declare_function(&mut self, id: FuncId, name: &str, linkage: Linkage); /// Declare a data object. fn declare_data( &mut self, id: DataId, name: &str, linkage: Linkage, writable: bool, align: Option<u8>, ); /// Define a function, producing the function body from the given `Context`. /// /// Functions must be declared before being defined. fn define_function( &mut self, id: FuncId, name: &str, ctx: &Context, namespace: &ModuleNamespace<Self>, code_size: u32, ) -> ModuleResult<Self::CompiledFunction>; /// Define a zero-initialized data object of the given size. /// /// Data objects must be declared before being defined. fn define_data( &mut self, id: DataId, name: &str, writable: bool, align: Option<u8>, data_ctx: &DataContext, namespace: &ModuleNamespace<Self>, ) -> ModuleResult<Self::CompiledData>; /// Write the address of `what` into the data for `data` at `offset`. `data` must refer to a /// defined data object. fn write_data_funcaddr( &mut self, data: &mut Self::CompiledData, offset: usize, what: ir::FuncRef, ); /// Write the address of `what` plus `addend` into the data for `data` at `offset`. `data` must /// refer to a defined data object. fn write_data_dataaddr( &mut self, data: &mut Self::CompiledData, offset: usize, what: ir::GlobalValue, addend: binemit::Addend, ); /// Perform all outstanding relocations on the given function. This requires all `Local` /// and `Export` entities referenced to be defined. /// /// This method is not relevant for `Backend` implementations that do not provide /// `Backend::FinalizedFunction`. fn finalize_function( &mut self, id: FuncId, func: &Self::CompiledFunction, namespace: &ModuleNamespace<Self>, ) -> Self::FinalizedFunction; /// Return the finalized artifact from the backend, if relevant. fn get_finalized_function(&self, func: &Self::CompiledFunction) -> Self::FinalizedFunction; /// Perform all outstanding relocations on the given data object. This requires all /// `Local` and `Export` entities referenced to be defined. /// /// This method is not relevant for `Backend` implementations that do not provide /// `Backend::FinalizedData`. fn finalize_data( &mut self, id: DataId, data: &Self::CompiledData, namespace: &ModuleNamespace<Self>, ) -> Self::FinalizedData; /// Return the finalized artifact from the backend, if relevant. fn get_finalized_data(&self, data: &Self::CompiledData) -> Self::FinalizedData; /// "Publish" all finalized functions and data objects to their ultimate destinations. /// /// This method is not relevant for `Backend` implementations that do not provide /// `Backend::FinalizedFunction` or `Backend::FinalizedData`. fn publish(&mut self); /// Consume this `Backend` and return a result. Some implementations may /// provide additional functionality through this result. fn finish(self, namespace: &ModuleNamespace<Self>) -> Self::Product; } /// Default names for `ir::LibCall`s. A function by this name is imported into the object as /// part of the translation of a `ir::ExternalName::LibCall` variant. pub fn default_libcall_names() -> Box<dyn Fn(ir::LibCall) -> String> { Box::new(move |libcall| match libcall { ir::LibCall::Probestack => "__cranelift_probestack".to_owned(), ir::LibCall::CeilF32 => "ceilf".to_owned(), ir::LibCall::CeilF64 => "ceil".to_owned(), ir::LibCall::FloorF32 => "floorf".to_owned(), ir::LibCall::FloorF64 => "floor".to_owned(), ir::LibCall::TruncF32 => "truncf".to_owned(), ir::LibCall::TruncF64 => "trunc".to_owned(), ir::LibCall::NearestF32 => "nearbyintf".to_owned(), ir::LibCall::NearestF64 => "nearbyint".to_owned(), ir::LibCall::Memcpy => "memcpy".to_owned(), ir::LibCall::Memset => "memset".to_owned(), ir::LibCall::Memmove => "memmove".to_owned(), }) }
35.195531
99
0.646984
fe0e45d00dd90271e108c0e9bbb032e66fc1ee25
4,327
// Copyright 2014 M. Rizky Luthfianto. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. use nalgebra::DMatrix; lazy_static! { // taken from https://github.com/seqan/seqan/blob/master/include%2Fseqan%2Fscore%2Fscore_matrix_data.h#L806 static ref ARRAY: [i32;729]=[ 2, 0, -2, 0, 0, -3, 1, -1, -1, -2, -1, -2, -1, 0, 0, 1, 0, -2, 1, 1, 0, 0, -6, -3, 0, 0, -8, 0, 3, -4, 3, 3, -4, 0, 1, -2, -3, 1, -3, -2, 2, -1, -1, 1, -1, 0, 0, -1, -2, -5, -3, 2, -1, -8, -2, -4, 12, -5, -5, -4, -3, -3, -2, -4, -5, -6, -5, -4, -3, -3, -5, -4, 0, -2, -3, -2, -8, 0, -5, -3, -8, 0, 3, -5, 4, 3, -6, 1, 1, -2, -3, 0, -4, -3, 2, -1, -1, 2, -1, 0, 0, -1, -2, -7, -4, 3, -1, -8, 0, 3, -5, 3, 4, -5, 0, 1, -2, -3, 0, -3, -2, 1, -1, -1, 2, -1, 0, 0, -1, -2, -7, -4, 3, -1, -8, -3, -4, -4, -6, -5, 9, -5, -2, 1, 2, -5, 2, 0, -3, -2, -5, -5, -4, -3, -3, -2, -1, 0, 7, -5, -2, -8, 1, 0, -3, 1, 0, -5, 5, -2, -3, -4, -2, -4, -3, 0, -1, 0, -1, -3, 1, 0, -1, -1, -7, -5, 0, -1, -8, -1, 1, -3, 1, 1, -2, -2, 6, -2, -2, 0, -2, -2, 2, -1, 0, 3, 2, -1, -1, -1, -2, -3, 0, 2, -1, -8, -1, -2, -2, -2, -2, 1, -3, -2, 5, 4, -2, 2, 2, -2, -1, -2, -2, -2, -1, 0, -1, 4, -5, -1, -2, -1, -8, -2, -3, -4, -3, -3, 2, -4, -2, 4, 4, -3, 4, 3, -3, -1, -3, -2, -3, -2, -1, -1, 3, -4, -1, -3, -1, -8, -1, 1, -5, 0, 0, -5, -2, 0, -2, -3, 5, -3, 0, 1, -1, -1, 1, 3, 0, 0, -1, -2, -3, -4, 0, -1, -8, -2, -3, -6, -4, -3, 2, -4, -2, 2, 4, -3, 6, 4, -3, -1, -3, -2, -3, -3, -2, -1, 2, -2, -1, -3, -1, -8, -1, -2, -5, -3, -2, 0, -3, -2, 2, 3, 0, 4, 6, -2, -1, -2, -1, 0, -2, -1, -1, 2, -4, -2, -2, -1, -8, 0, 2, -4, 2, 1, -3, 0, 2, -2, -3, 1, -3, -2, 2, 0, 0, 1, 0, 1, 0, 0, -2, -4, -2, 1, 0, -8, 0, -1, -3, -1, -1, -2, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, 0, 0, -1, -1, -4, -2, -1, -1, -8, 1, -1, -3, -1, -1, -5, 0, 0, -2, -3, -1, -3, -2, 0, -1, 6, 0, 0, 1, 0, -1, -1, -6, -5, 0, -1, -8, 0, 1, -5, 2, 2, -5, -1, 3, -2, -2, 1, -2, -1, 1, -1, 0, 4, 1, -1, -1, -1, -2, -5, -4, 3, -1, -8, -2, -1, -4, -1, -1, -4, -3, 2, -2, -3, 3, -3, 0, 0, -1, 0, 1, 6, 0, -1, -1, -2, 2, -4, 0, -1, -8, 1, 0, 0, 0, 0, -3, 1, -1, -1, -2, 0, -3, -2, 1, 0, 1, -1, 0, 2, 1, 0, -1, -2, -3, 0, 0, -8, 1, 0, -2, 0, 0, -3, 0, -1, 0, -1, 0, -2, -1, 0, 0, 0, -1, -1, 1, 3, 0, 0, -5, -3, -1, 0, -8, 0, -1, -3, -1, -1, -2, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, 0, 0, -1, -1, -4, -2, -1, -1, -8, 0, -2, -2, -2, -2, -1, -1, -2, 4, 3, -2, 2, 2, -2, -1, -1, -2, -2, -1, 0, -1, 4, -6, -2, -2, -1, -8, -6, -5, -8, -7, -7, 0, -7, -3, -5, -4, -3, -2, -4, -4, -4, -6, -5, 2, -2, -5, -4, -6, 17, 0, -6, -4, -8, -3, -3, 0, -4, -4, 7, -5, 0, -1, -1, -4, -1, -2, -2, -2, -5, -4, -4, -3, -3, -2, -2, 0, 10, -4, -2, -8, 0, 2, -5, 3, 3, -5, 0, 2, -2, -3, 0, -3, -2, 1, -1, 0, 3, 0, 0, -1, -1, -2, -6, -4, 3, -1, -8, 0, -1, -3, -1, -1, -2, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, 0, 0, -1, -1, -4, -2, -1, -1, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, 1, ]; static ref MAT: DMatrix<i32> = DMatrix::from_column_vector(27, 27, &*ARRAY); } #[inline] fn lookup(a: u8) -> usize { if a == b'Y' { 23 as usize } else if a == b'Z' { 24 as usize } else if a == b'X' { 25 as usize } else if a == b'*' { 26 as usize } else { (a - 65) as usize } } pub fn pam250(a: u8, b: u8) -> i32 { let a = lookup(a); let b = lookup(b); MAT[(a, b)] } #[cfg(test)] mod tests { use super::*; #[test] fn test_pam250() { let score1 = pam250(b'A', b'A'); assert_eq!(score1, 2); let score2 = pam250(b'*', b'*'); assert_eq!(score2, 1); let score3 = pam250(b'A', b'*'); assert_eq!(score3, -8); let score4 = pam250(b'*', b'*'); assert_eq!(score4, 1); let score5 = pam250(b'X', b'X'); assert_eq!(score5, -1); let score6 = pam250(b'X', b'Z'); assert_eq!(score6, -1); } }
50.313953
109
0.340421
ebc15f058d7eed1961c85b773db60d694d69907f
4,861
// @generated #[derive(Clone, PartialEq, ::prost::Message)] pub struct Transfers { #[prost(message, repeated, tag="1")] pub transfers: ::prost::alloc::vec::Vec<Transfer>, } #[derive(Clone, PartialEq, ::prost::Message)] pub struct Transfer { #[prost(bytes="vec", tag="1")] pub from: ::prost::alloc::vec::Vec<u8>, #[prost(bytes="vec", tag="2")] pub to: ::prost::alloc::vec::Vec<u8>, #[prost(uint64, tag="3")] pub token_id: u64, #[prost(bytes="vec", tag="4")] pub trx_hash: ::prost::alloc::vec::Vec<u8>, #[prost(uint64, tag="5")] pub ordinal: u64, } /// Encoded file descriptor set for the `eth.erc721.v1` package pub const FILE_DESCRIPTOR_SET: &[u8] = &[ 0x0a, 0x90, 0x05, 0x0a, 0x0c, 0x65, 0x72, 0x63, 0x37, 0x32, 0x31, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0d, 0x65, 0x74, 0x68, 0x2e, 0x65, 0x72, 0x63, 0x37, 0x32, 0x31, 0x2e, 0x76, 0x31, 0x22, 0x42, 0x0a, 0x09, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x73, 0x12, 0x35, 0x0a, 0x09, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x65, 0x74, 0x68, 0x2e, 0x65, 0x72, 0x63, 0x37, 0x32, 0x31, 0x2e, 0x76, 0x31, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x52, 0x09, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x73, 0x22, 0x7e, 0x0a, 0x08, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x12, 0x12, 0x0a, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x12, 0x0e, 0x0a, 0x02, 0x74, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x74, 0x6f, 0x12, 0x19, 0x0a, 0x08, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x07, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x49, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x74, 0x72, 0x78, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x74, 0x72, 0x78, 0x48, 0x61, 0x73, 0x68, 0x12, 0x18, 0x0a, 0x07, 0x6f, 0x72, 0x64, 0x69, 0x6e, 0x61, 0x6c, 0x18, 0x05, 0x20, 0x01, 0x28, 0x04, 0x52, 0x07, 0x6f, 0x72, 0x64, 0x69, 0x6e, 0x61, 0x6c, 0x4a, 0xa4, 0x03, 0x0a, 0x06, 0x12, 0x04, 0x00, 0x00, 0x0e, 0x01, 0x0a, 0x08, 0x0a, 0x01, 0x0c, 0x12, 0x03, 0x00, 0x00, 0x12, 0x0a, 0x08, 0x0a, 0x01, 0x02, 0x12, 0x03, 0x02, 0x00, 0x16, 0x0a, 0x0a, 0x0a, 0x02, 0x04, 0x00, 0x12, 0x04, 0x04, 0x00, 0x06, 0x01, 0x0a, 0x0a, 0x0a, 0x03, 0x04, 0x00, 0x01, 0x12, 0x03, 0x04, 0x08, 0x11, 0x0a, 0x0b, 0x0a, 0x04, 0x04, 0x00, 0x02, 0x00, 0x12, 0x03, 0x05, 0x02, 0x22, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x00, 0x02, 0x00, 0x04, 0x12, 0x03, 0x05, 0x02, 0x0a, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x00, 0x02, 0x00, 0x06, 0x12, 0x03, 0x05, 0x0b, 0x13, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x00, 0x02, 0x00, 0x01, 0x12, 0x03, 0x05, 0x14, 0x1d, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x00, 0x02, 0x00, 0x03, 0x12, 0x03, 0x05, 0x20, 0x21, 0x0a, 0x0a, 0x0a, 0x02, 0x04, 0x01, 0x12, 0x04, 0x08, 0x00, 0x0e, 0x01, 0x0a, 0x0a, 0x0a, 0x03, 0x04, 0x01, 0x01, 0x12, 0x03, 0x08, 0x08, 0x10, 0x0a, 0x0b, 0x0a, 0x04, 0x04, 0x01, 0x02, 0x00, 0x12, 0x03, 0x09, 0x02, 0x11, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x01, 0x02, 0x00, 0x05, 0x12, 0x03, 0x09, 0x02, 0x07, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x01, 0x02, 0x00, 0x01, 0x12, 0x03, 0x09, 0x08, 0x0c, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x01, 0x02, 0x00, 0x03, 0x12, 0x03, 0x09, 0x0f, 0x10, 0x0a, 0x0b, 0x0a, 0x04, 0x04, 0x01, 0x02, 0x01, 0x12, 0x03, 0x0a, 0x02, 0x0f, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x01, 0x02, 0x01, 0x05, 0x12, 0x03, 0x0a, 0x02, 0x07, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x01, 0x02, 0x01, 0x01, 0x12, 0x03, 0x0a, 0x08, 0x0a, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x01, 0x02, 0x01, 0x03, 0x12, 0x03, 0x0a, 0x0d, 0x0e, 0x0a, 0x0b, 0x0a, 0x04, 0x04, 0x01, 0x02, 0x02, 0x12, 0x03, 0x0b, 0x02, 0x16, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x01, 0x02, 0x02, 0x05, 0x12, 0x03, 0x0b, 0x02, 0x08, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x01, 0x02, 0x02, 0x01, 0x12, 0x03, 0x0b, 0x09, 0x11, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x01, 0x02, 0x02, 0x03, 0x12, 0x03, 0x0b, 0x14, 0x15, 0x0a, 0x0b, 0x0a, 0x04, 0x04, 0x01, 0x02, 0x03, 0x12, 0x03, 0x0c, 0x02, 0x15, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x01, 0x02, 0x03, 0x05, 0x12, 0x03, 0x0c, 0x02, 0x07, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x01, 0x02, 0x03, 0x01, 0x12, 0x03, 0x0c, 0x08, 0x10, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x01, 0x02, 0x03, 0x03, 0x12, 0x03, 0x0c, 0x13, 0x14, 0x0a, 0x0b, 0x0a, 0x04, 0x04, 0x01, 0x02, 0x04, 0x12, 0x03, 0x0d, 0x02, 0x15, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x01, 0x02, 0x04, 0x05, 0x12, 0x03, 0x0d, 0x02, 0x08, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x01, 0x02, 0x04, 0x01, 0x12, 0x03, 0x0d, 0x09, 0x10, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x01, 0x02, 0x04, 0x03, 0x12, 0x03, 0x0d, 0x13, 0x14, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, ]; // @@protoc_insertion_point(module)
74.784615
99
0.636495
9b96b8435e24f8071ed44e88c4fe89f6505a6093
1,541
#![feature(custom_test_frameworks)] #![no_std] #![no_main] #![test_runner(gifos::test_runner)] #![reexport_test_harness_main = "test_main"] #![deny(unsafe_op_in_unsafe_fn)] extern crate alloc; use bootloader::{entry_point, BootInfo}; use core::panic::PanicInfo; use gifos::{ println, task::{executor::Executor, keyboard, Task}, }; entry_point!(kernel_main); fn kernel_main(boot_info: &'static BootInfo) -> ! { use gifos::{ allocator, memory::{self, BootInfoFrameAllocator}, }; use x86_64::VirtAddr; println!("Hello World!"); gifos::init(); let phys_mem_offset = VirtAddr::new(boot_info.physical_memory_offset); let mut mapper = unsafe { memory::init(phys_mem_offset) }; let mut frame_allocator = unsafe { BootInfoFrameAllocator::init(&boot_info.memory_map) }; allocator::init_heap(&mut mapper, &mut frame_allocator).expect("heap initialization failed"); #[cfg(test)] test_main(); let mut executor = Executor::new(); executor.spawn(Task::new(example_task())); executor.spawn(Task::new(keyboard::print_keypresses())); executor.run(); } async fn async_number() -> u32 { 42 } async fn example_task() { let number = async_number().await; println!("async number: {}", number) } /// This function is called on panic. #[cfg(not(test))] #[panic_handler] fn panic(info: &PanicInfo) -> ! { println!("{}", info); gifos::hlt_loop(); } #[cfg(test)] #[panic_handler] fn panic(info: &PanicInfo) -> ! { gifos::test_panic_handler(info) }
23.348485
97
0.667099
69a6bbd528b8936494595b624e8f7a1409085e4b
2,492
#![allow(clippy::module_inception)] #![allow(clippy::upper_case_acronyms)] #![allow(clippy::large_enum_variant)] #![allow(clippy::wrong_self_convention)] #![allow(clippy::should_implement_trait)] #![allow(clippy::blacklisted_name)] #![allow(clippy::vec_init_then_push)] #![allow(clippy::type_complexity)] #![allow(rustdoc::bare_urls)] #![warn(missing_docs)] //! <p>Amazon Web Services X-Ray provides APIs for managing debug traces and retrieving service maps //! and other data created by processing those traces.</p> //! //! # Crate Organization //! //! The entry point for most customers will be [`Client`]. [`Client`] exposes one method for each API offered //! by the service. //! //! Some APIs require complex or nested arguments. These exist in [`model`](crate::model). //! //! Lastly, errors that can be returned by the service are contained within [`error`]. [`Error`] defines a meta //! error encompassing all possible errors that can be returned by the service. //! //! The other modules within this crate are not required for normal usage. // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use error_meta::Error; #[doc(inline)] pub use config::Config; mod aws_endpoint; /// Client and fluent builders for calling the service. pub mod client; /// Configuration for the service. pub mod config; /// Errors that can occur when calling the service. pub mod error; mod error_meta; /// Input structures for operations. pub mod input; mod json_deser; mod json_errors; mod json_ser; /// Generated accessors for nested fields pub mod lens; pub mod middleware; /// Data structures used by operation inputs/outputs. pub mod model; mod no_credentials; /// All operations that this crate can perform. pub mod operation; mod operation_deser; mod operation_ser; /// Output structures for operations. pub mod output; /// Paginators for the service pub mod paginator; /// Crate version number. pub static PKG_VERSION: &str = env!("CARGO_PKG_VERSION"); /// Re-exported types from supporting crates. pub mod types { pub use aws_smithy_http::result::SdkError; pub use aws_smithy_types::DateTime; } static API_METADATA: aws_http::user_agent::ApiMetadata = aws_http::user_agent::ApiMetadata::new("xray", PKG_VERSION); pub use aws_smithy_http::endpoint::Endpoint; pub use aws_smithy_types::retry::RetryConfig; pub use aws_types::app_name::AppName; pub use aws_types::region::Region; pub use aws_types::Credentials; #[doc(inline)] pub use client::Client;
33.226667
111
0.751605
d6cede224fe1fe325b846dc8e13e2c49898cc359
2,263
extern crate redox_users; use std::env; use std::ffi::OsString; use std::path::PathBuf; use self::redox_users::AllUsers; pub fn home_dir() -> Option<PathBuf> { let current_uid = redox_users::get_uid().ok()?; let users = AllUsers::new(false).ok()?; let user = users.get_by_id(current_uid)?; Some(PathBuf::from(user.home.clone())) } pub fn cache_dir() -> Option<PathBuf> { env::var_os("XDG_CACHE_HOME") .and_then(is_absolute_path).or_else(|| home_dir().map(|h| h.join(".cache"))) } pub fn config_dir() -> Option<PathBuf> { env::var_os("XDG_CONFIG_HOME").and_then(is_absolute_path).or_else(|| home_dir().map(|h| h.join(".config"))) } pub fn data_dir() -> Option<PathBuf> { env::var_os("XDG_DATA_HOME") .and_then(is_absolute_path).or_else(|| home_dir().map(|h| h.join(".local/share"))) } pub fn data_local_dir() -> Option<PathBuf> { data_dir().clone() } pub fn runtime_dir() -> Option<PathBuf> { env::var_os("XDG_RUNTIME_DIR").and_then(is_absolute_path) } pub fn executable_dir() -> Option<PathBuf> { env::var_os("XDG_BIN_HOME").and_then(is_absolute_path).or_else(|| { data_dir().map(|mut e| { e.pop(); e.push("bin"); e }) }) } pub fn audio_dir() -> Option<PathBuf> { home_dir().map(|h| h.join("Music")) } pub fn desktop_dir() -> Option<PathBuf> { home_dir().map(|h| h.join("Desktop")) } pub fn document_dir() -> Option<PathBuf> { home_dir().map(|h| h.join("Documents")) } pub fn download_dir() -> Option<PathBuf> { home_dir().map(|h| h.join("Downloads")) } pub fn font_dir() -> Option<PathBuf> { data_dir().map(|d| d.join("fonts")) } pub fn picture_dir() -> Option<PathBuf> { home_dir().map(|h| h.join("Pictures")) } pub fn public_dir() -> Option<PathBuf> { home_dir().map(|h| h.join("Public")) } pub fn template_dir() -> Option<PathBuf> { home_dir().map(|h| h.join("Templates")) } pub fn video_dir() -> Option<PathBuf> { home_dir().map(|h| h.join("Videos")) } // we don't need to explicitly handle empty strings in the code above, // because an empty string is not considered to be a absolute path here. fn is_absolute_path(path: OsString) -> Option<PathBuf> { let path = PathBuf::from(path); if path.is_absolute() { Some(path) } else { None } }
50.288889
159
0.648255
ff364f571828109748b211c3d02cdc5ba93718bb
53
use crate::token::tokens::Token; token!(Character);
13.25
32
0.716981
d7deebc175c9da952a9f7dd388d333747fdf6ec7
13,647
//! Tests for when multiple artifacts have the same output filename. //! See https://github.com/rust-lang/cargo/issues/6313 for more details. //! Ideally these should never happen, but I don't think we'll ever be able to //! prevent all collisions. use cargo_test_support::registry::Package; use cargo_test_support::{basic_manifest, cross_compile, project}; use std::env; #[cargo_test] fn collision_dylib() { // Path dependencies don't include metadata hash in filename for dylibs. let p = project() .file( "Cargo.toml", r#" [workspace] members = ["a", "b"] "#, ) .file( "a/Cargo.toml", r#" [package] name = "a" version = "1.0.0" [lib] crate-type = ["dylib"] "#, ) .file("a/src/lib.rs", "") .file( "b/Cargo.toml", r#" [package] name = "b" version = "1.0.0" [lib] crate-type = ["dylib"] name = "a" "#, ) .file("b/src/lib.rs", "") .build(); // `j=1` is required because on Windows you'll get an error due to // two processes writing to the file at the same time. p.cargo("build -j=1") .with_stderr_contains(&format!("\ [WARNING] output filename collision. The lib target `a` in package `b v1.0.0 ([..]/foo/b)` has the same output filename as the lib target `a` in package `a v1.0.0 ([..]/foo/a)`. Colliding filename is: [..]/foo/target/debug/deps/{}a{} The targets should have unique names. Consider changing their names to be unique or compiling them separately. This may become a hard error in the future; see <https://github.com/rust-lang/cargo/issues/6313>. ", env::consts::DLL_PREFIX, env::consts::DLL_SUFFIX)) .run(); } #[cargo_test] fn collision_example() { // Examples in a workspace can easily collide. let p = project() .file( "Cargo.toml", r#" [workspace] members = ["a", "b"] "#, ) .file("a/Cargo.toml", &basic_manifest("a", "1.0.0")) .file("a/examples/ex1.rs", "fn main() {}") .file("b/Cargo.toml", &basic_manifest("b", "1.0.0")) .file("b/examples/ex1.rs", "fn main() {}") .build(); // `j=1` is required because on Windows you'll get an error due to // two processes writing to the file at the same time. p.cargo("build --examples -j=1") .with_stderr_contains("\ [WARNING] output filename collision. The example target `ex1` in package `b v1.0.0 ([..]/foo/b)` has the same output filename as the example target `ex1` in package `a v1.0.0 ([..]/foo/a)`. Colliding filename is: [..]/foo/target/debug/examples/ex1[EXE] The targets should have unique names. Consider changing their names to be unique or compiling them separately. This may become a hard error in the future; see <https://github.com/rust-lang/cargo/issues/6313>. ") .run(); } #[cargo_test] // --out-dir and examples are currently broken on MSVC and apple. // See https://github.com/rust-lang/cargo/issues/7493 #[cfg_attr(any(target_env = "msvc", target_vendor = "apple"), ignore)] fn collision_export() { // `--out-dir` combines some things which can cause conflicts. let p = project() .file("Cargo.toml", &basic_manifest("foo", "1.0.0")) .file("examples/foo.rs", "fn main() {}") .file("src/main.rs", "fn main() {}") .build(); // -j1 to avoid issues with two processes writing to the same file at the // same time. p.cargo("build -j1 --out-dir=out -Z unstable-options --bins --examples") .masquerade_as_nightly_cargo() .with_stderr_contains("\ [WARNING] `--out-dir` filename collision. The example target `foo` in package `foo v1.0.0 ([..]/foo)` has the same output filename as the bin target `foo` in package `foo v1.0.0 ([..]/foo)`. Colliding filename is: [..]/foo/out/foo[EXE] The exported filenames should be unique. Consider changing their names to be unique or compiling them separately. This may become a hard error in the future; see <https://github.com/rust-lang/cargo/issues/6313>. ") .run(); } #[cargo_test] fn collision_doc() { let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.1.0" [dependencies] foo2 = { path = "foo2" } "#, ) .file("src/lib.rs", "") .file( "foo2/Cargo.toml", r#" [package] name = "foo2" version = "0.1.0" [lib] name = "foo" "#, ) .file("foo2/src/lib.rs", "") .build(); p.cargo("doc") .with_stderr_contains( "\ [WARNING] output filename collision. The lib target `foo` in package `foo2 v0.1.0 ([..]/foo/foo2)` has the same output \ filename as the lib target `foo` in package `foo v0.1.0 ([..]/foo)`. Colliding filename is: [..]/foo/target/doc/foo/index.html The targets should have unique names. This is a known bug where multiple crates with the same name use the same path; see <https://github.com/rust-lang/cargo/issues/6313>. ", ) .run(); } #[cargo_test] fn collision_doc_multiple_versions() { // Multiple versions of the same package. Package::new("old-dep", "1.0.0").publish(); Package::new("bar", "1.0.0").dep("old-dep", "1.0").publish(); // Note that this removes "old-dep". Just checking what happens when there // are orphans. Package::new("bar", "2.0.0").publish(); let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.1.0" [dependencies] bar = "1.0" bar2 = { package="bar", version="2.0" } "#, ) .file("src/lib.rs", "") .build(); // Should only document bar 2.0, should not document old-dep. p.cargo("doc") .with_stderr_unordered( "\ [UPDATING] [..] [DOWNLOADING] crates ... [DOWNLOADED] bar v2.0.0 [..] [DOWNLOADED] bar v1.0.0 [..] [DOWNLOADED] old-dep v1.0.0 [..] [CHECKING] old-dep v1.0.0 [CHECKING] bar v2.0.0 [CHECKING] bar v1.0.0 [DOCUMENTING] bar v2.0.0 [FINISHED] [..] [DOCUMENTING] foo v0.1.0 [..] ", ) .run(); } #[cargo_test] fn collision_doc_host_target_feature_split() { // Same dependency built twice due to different features. // // foo v0.1.0 // ├── common v1.0.0 // │ └── common-dep v1.0.0 // └── pm v0.1.0 (proc-macro) // └── common v1.0.0 // └── common-dep v1.0.0 // [build-dependencies] // └── common-dep v1.0.0 // // Here `common` and `common-dep` are built twice. `common-dep` has // different features for host versus target. Package::new("common-dep", "1.0.0") .feature("bdep-feat", &[]) .file( "src/lib.rs", r#" /// Some doc pub fn f() {} /// Another doc #[cfg(feature = "bdep-feat")] pub fn bdep_func() {} "#, ) .publish(); Package::new("common", "1.0.0") .dep("common-dep", "1.0") .file( "src/lib.rs", r#" /// Some doc pub fn f() {} "#, ) .publish(); let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.1.0" resolver = "2" [dependencies] pm = { path = "pm" } common = "1.0" [build-dependencies] common-dep = { version = "1.0", features = ["bdep-feat"] } "#, ) .file( "src/lib.rs", r#" /// Some doc pub fn f() {} "#, ) .file("build.rs", "fn main() {}") .file( "pm/Cargo.toml", r#" [package] name = "pm" version = "0.1.0" edition = "2018" [lib] proc-macro = true [dependencies] common = "1.0" "#, ) .file( "pm/src/lib.rs", r#" use proc_macro::TokenStream; /// Some doc #[proc_macro] pub fn pm(_input: TokenStream) -> TokenStream { "".parse().unwrap() } "#, ) .build(); // No warnings, no duplicates, common and common-dep only documented once. p.cargo("doc") // Cannot check full output due to https://github.com/rust-lang/cargo/issues/9076 .with_stderr_does_not_contain("[WARNING][..]") .run(); assert!(p.build_dir().join("doc/common_dep/fn.f.html").exists()); assert!(!p .build_dir() .join("doc/common_dep/fn.bdep_func.html") .exists()); assert!(p.build_dir().join("doc/common/fn.f.html").exists()); assert!(p.build_dir().join("doc/pm/macro.pm.html").exists()); assert!(p.build_dir().join("doc/foo/fn.f.html").exists()); } #[cargo_test] fn collision_doc_profile_split() { // Same dependency built twice due to different profile settings. Package::new("common", "1.0.0").publish(); let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.1.0" [dependencies] pm = { path = "pm" } common = "1.0" [profile.dev] opt-level = 2 "#, ) .file("src/lib.rs", "") .file( "pm/Cargo.toml", r#" [package] name = "pm" version = "0.1.0" [dependencies] common = "1.0" [lib] proc-macro = true "#, ) .file("pm/src/lib.rs", "") .build(); // Just to verify that common is normally built twice. p.cargo("build -v") .with_stderr( "\ [UPDATING] [..] [DOWNLOADING] crates ... [DOWNLOADED] common v1.0.0 [..] [COMPILING] common v1.0.0 [RUNNING] `rustc --crate-name common [..] [RUNNING] `rustc --crate-name common [..] [COMPILING] pm v0.1.0 [..] [RUNNING] `rustc --crate-name pm [..] [COMPILING] foo v0.1.0 [..] [RUNNING] `rustc --crate-name foo [..] [FINISHED] [..] ", ) .run(); // Should only document common once, no warnings. p.cargo("doc") .with_stderr_unordered( "\ [CHECKING] common v1.0.0 [DOCUMENTING] common v1.0.0 [DOCUMENTING] pm v0.1.0 [..] [DOCUMENTING] foo v0.1.0 [..] [FINISHED] [..] ", ) .run(); } #[cargo_test] fn collision_doc_sources() { // Different sources with the same package. Package::new("bar", "1.0.0").publish(); let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.1.0" [dependencies] bar = "1.0" bar2 = { path = "bar", package = "bar" } "#, ) .file("src/lib.rs", "") .file("bar/Cargo.toml", &basic_manifest("bar", "1.0.0")) .file("bar/src/lib.rs", "") .build(); p.cargo("doc") .with_stderr_unordered( "\ [UPDATING] [..] [DOWNLOADING] crates ... [DOWNLOADED] bar v1.0.0 [..] [WARNING] output filename collision. The lib target `bar` in package `bar v1.0.0` has the same output filename as \ the lib target `bar` in package `bar v1.0.0 ([..]/foo/bar)`. Colliding filename is: [..]/foo/target/doc/bar/index.html The targets should have unique names. This is a known bug where multiple crates with the same name use the same path; see <https://github.com/rust-lang/cargo/issues/6313>. [CHECKING] bar v1.0.0 [..] [DOCUMENTING] bar v1.0.0 [..] [DOCUMENTING] bar v1.0.0 [CHECKING] bar v1.0.0 [DOCUMENTING] foo v0.1.0 [..] [FINISHED] [..] ", ) .run(); } #[cargo_test] fn collision_doc_target() { // collision in doc with --target, doesn't fail due to orphans if cross_compile::disabled() { return; } Package::new("orphaned", "1.0.0").publish(); Package::new("bar", "1.0.0") .dep("orphaned", "1.0") .publish(); Package::new("bar", "2.0.0").publish(); let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.1.0" [dependencies] bar2 = { version = "2.0", package="bar" } bar = "1.0" "#, ) .file("src/lib.rs", "") .build(); p.cargo("doc --target") .arg(cross_compile::alternate()) .with_stderr_unordered( "\ [UPDATING] [..] [DOWNLOADING] crates ... [DOWNLOADED] orphaned v1.0.0 [..] [DOWNLOADED] bar v2.0.0 [..] [DOWNLOADED] bar v1.0.0 [..] [CHECKING] orphaned v1.0.0 [DOCUMENTING] bar v2.0.0 [CHECKING] bar v2.0.0 [CHECKING] bar v1.0.0 [DOCUMENTING] foo v0.1.0 [..] [FINISHED] [..] ", ) .run(); }
28.372141
152
0.503041
224fced730fdedc8b6e84b4b0a0913160251c957
773
use language::operations::{make_param_doc, Operation, ParamInfo}; pub struct StrStoreStringRegOp; const DOC: &str = "Copies the contents of one string register from another."; pub const OP_CODE: u32 = 2321; pub const IDENT: &str = "str_store_string_reg"; impl Operation for StrStoreStringRegOp { fn op_code(&self) -> u32 { OP_CODE } fn documentation(&self) -> &'static str { DOC } fn identifier(&self) -> &'static str { IDENT } fn param_info(&self) -> ParamInfo { ParamInfo { num_required: 2, num_optional: 0, param_docs: vec![ make_param_doc("<string_register>", ""), make_param_doc("<string_no>", ""), ], } } }
22.085714
77
0.570505
bfdf6c9f7aa93e1ff09a17d92e75f8455b0f4ade
6,824
#![deny(unused_imports, unused_variables, unused_unsafe, unreachable_patterns)] //! Wasmer-runtime is a library that makes embedding WebAssembly //! in your application easy, efficient, and safe. //! //! # How to use Wasmer-Runtime //! //! The easiest way is to use the [`instantiate`] function to create an [`Instance`]. //! Then you can use [`call`] or [`func`] and then [`call`][func.call] to call an exported function safely. //! //! [`instantiate`]: fn.instantiate.html //! [`Instance`]: struct.Instance.html //! [`call`]: struct.Instance.html#method.call //! [`func`]: struct.Instance.html#method.func //! [func.call]: struct.Function.html#method.call //! //! ## Here's an example: //! //! Given this WebAssembly: //! //! ```wat //! (module //! (type $t0 (func (param i32) (result i32))) //! (func $add_one (export "add_one") (type $t0) (param $p0 i32) (result i32) //! get_local $p0 //! i32.const 1 //! i32.add)) //! ``` //! //! compiled into wasm bytecode, we can call the exported "add_one" function: //! //! ``` //! static WASM: &'static [u8] = &[ //! // The module above compiled to bytecode goes here. //! // ... //! # 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x06, 0x01, 0x60, //! # 0x01, 0x7f, 0x01, 0x7f, 0x03, 0x02, 0x01, 0x00, 0x07, 0x0b, 0x01, 0x07, //! # 0x61, 0x64, 0x64, 0x5f, 0x6f, 0x6e, 0x65, 0x00, 0x00, 0x0a, 0x09, 0x01, //! # 0x07, 0x00, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x0b, 0x00, 0x1a, 0x04, 0x6e, //! # 0x61, 0x6d, 0x65, 0x01, 0x0a, 0x01, 0x00, 0x07, 0x61, 0x64, 0x64, 0x5f, //! # 0x6f, 0x6e, 0x65, 0x02, 0x07, 0x01, 0x00, 0x01, 0x00, 0x02, 0x70, 0x30, //! ]; //! //! use wasmer_runtime::{ //! instantiate, //! Value, //! imports, //! error, //! Func, //! }; //! //! fn main() -> error::Result<()> { //! // We're not importing anything, so make an empty import object. //! let import_object = imports! {}; //! //! let mut instance = instantiate(WASM, &import_object)?; //! //! let add_one: Func<i32, i32> = instance.func("add_one")?; //! //! let value = add_one.call(42)?; //! //! assert_eq!(value, 43); //! //! Ok(()) //! } //! ``` //! //! # Additional Notes: //! //! The `wasmer-runtime` is build to support compiler multiple backends. //! Currently, we support the [Cranelift] compiler with the [`wasmer-clif-backend`] crate. //! //! You can specify the compiler you wish to use with the [`compile_with`] function. //! //! [Cranelift]: https://github.com/CraneStation/cranelift //! [`wasmer-clif-backend`]: https://crates.io/crates/wasmer-clif-backend //! [`compile_with`]: fn.compile_with.html pub use wasmer_runtime_core::export::Export; pub use wasmer_runtime_core::global::Global; pub use wasmer_runtime_core::import::ImportObject; pub use wasmer_runtime_core::instance::{DynFunc, Instance}; pub use wasmer_runtime_core::memory::Memory; pub use wasmer_runtime_core::module::Module; pub use wasmer_runtime_core::table::Table; pub use wasmer_runtime_core::types::Value; pub use wasmer_runtime_core::vm::Ctx; pub use wasmer_runtime_core::Func; pub use wasmer_runtime_core::{compile_with, validate}; pub use wasmer_runtime_core::{func, imports}; pub mod memory { pub use wasmer_runtime_core::memory::{Atomic, Atomically, Memory, MemoryView}; } pub mod wasm { //! Various types exposed by the Wasmer Runtime. pub use wasmer_runtime_core::global::Global; pub use wasmer_runtime_core::table::Table; pub use wasmer_runtime_core::types::{ FuncSig, GlobalDescriptor, MemoryDescriptor, TableDescriptor, Type, Value, }; } pub mod error { pub use wasmer_runtime_core::cache::Error as CacheError; pub use wasmer_runtime_core::error::*; } pub mod units { //! Various unit types. pub use wasmer_runtime_core::units::{Bytes, Pages}; } pub mod cache; use wasmer_runtime_core::backend::{Compiler, CompilerConfig}; /// Compile WebAssembly binary code into a [`Module`]. /// This function is useful if it is necessary to /// compile a module before it can be instantiated /// (otherwise, the [`instantiate`] function should be used). /// /// [`Module`]: struct.Module.html /// [`instantiate`]: fn.instantiate.html /// /// # Params: /// * `wasm`: A `&[u8]` containing the /// binary code of the wasm module you want to compile. /// # Errors: /// If the operation fails, the function returns `Err(error::CompileError::...)`. pub fn compile(wasm: &[u8]) -> error::CompileResult<Module> { wasmer_runtime_core::compile_with(&wasm[..], default_compiler()) } /// The same as `compile` but takes a `CompilerConfig` for the purpose of /// changing the compiler's behavior pub fn compile_with_config( wasm: &[u8], compiler_config: CompilerConfig, ) -> error::CompileResult<Module> { wasmer_runtime_core::compile_with_config(&wasm[..], default_compiler(), compiler_config) } /// The same as `compile_with_config` but takes a `Compiler` for the purpose of /// changing the backend. pub fn compile_with_config_with( wasm: &[u8], compiler_config: CompilerConfig, compiler: &dyn Compiler, ) -> error::CompileResult<Module> { wasmer_runtime_core::compile_with_config(&wasm[..], compiler, compiler_config) } /// Compile and instantiate WebAssembly code without /// creating a [`Module`]. /// /// [`Module`]: struct.Module.html /// /// # Params: /// * `wasm`: A `&[u8]` containing the /// binary code of the wasm module you want to compile. /// * `import_object`: An object containing the values to be imported /// into the newly-created Instance, such as functions or /// Memory objects. There must be one matching property /// for each declared import of the compiled module or else a /// LinkError is thrown. /// # Errors: /// If the operation fails, the function returns a /// `error::CompileError`, `error::LinkError`, or /// `error::RuntimeError` (all combined into an `error::Error`), /// depending on the cause of the failure. pub fn instantiate(wasm: &[u8], import_object: &ImportObject) -> error::Result<Instance> { let module = compile(wasm)?; module.instantiate(import_object) } /// Get a single instance of the default compiler to use. pub fn default_compiler() -> &'static dyn Compiler { use lazy_static::lazy_static; #[cfg(feature = "llvm")] use wasmer_llvm_backend::LLVMCompiler as DefaultCompiler; #[cfg(feature = "singlepass")] use wasmer_singlepass_backend::SinglePassCompiler as DefaultCompiler; #[cfg(not(any(feature = "llvm", feature = "singlepass")))] use wasmer_clif_backend::CraneliftCompiler as DefaultCompiler; lazy_static! { static ref DEFAULT_COMPILER: DefaultCompiler = { DefaultCompiler::new() }; } &*DEFAULT_COMPILER as &dyn Compiler } /// The current version of this crate pub const VERSION: &str = env!("CARGO_PKG_VERSION");
33.950249
107
0.674091
2257441c1168a75d42a772748cbf9edc2a3a1d29
1,090
#[doc = "Reader of register S6NDTR"] pub type R = crate::R<u32, super::S6NDTR>; #[doc = "Writer for register S6NDTR"] pub type W = crate::W<u32, super::S6NDTR>; #[doc = "Register S6NDTR `reset()`'s with value 0"] impl crate::ResetValue for super::S6NDTR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `NDT`"] pub type NDT_R = crate::R<u16, u16>; #[doc = "Write proxy for field `NDT`"] pub struct NDT_W<'a> { w: &'a mut W, } impl<'a> NDT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff); self.w } } impl R { #[doc = "Bits 0:15 - Number of data items to transfer"] #[inline(always)] pub fn ndt(&self) -> NDT_R { NDT_R::new((self.bits & 0xffff) as u16) } } impl W { #[doc = "Bits 0:15 - Number of data items to transfer"] #[inline(always)] pub fn ndt(&mut self) -> NDT_W { NDT_W { w: self } } }
26.585366
74
0.56422
9bb9b21215a99513bad4fa1d801eb311ee1e1ca5
2,556
//! //! #![deny(missing_docs)] #![warn(unused_imports)] #![warn(dead_code)] use crate::types::{Address, Commit, ConsensusOutput, Hash, Signature, Status}; use serde::{de::DeserializeOwned, ser::Serialize}; use std::fmt::Debug; /// Consensus support pub trait ConsensusSupport<F: Content + Sync> { /// Support error type. type Error: Debug; /// Get a proposal content of a height. If success, return `Ok(F)` that `F` /// is an example of `Content`, else return `Err()`. fn get_content(&self, height: u64) -> Result<F, Self::Error>; /// Transmit a consensus output to other nodes. fn transmit(&self, msg: ConsensusOutput<F>) -> Result<(), Self::Error>; /// Check the validity of the transcations of a proposal. If success return `Ok(())`, /// else return `Err()`. fn check_proposal( &self, proposal_hash: &[u8], proposal: &F, signed_proposal_hash: &[u8], is_lock: bool, is_by_self: bool, ) -> Result<(), Self::Error>; /// Do commit. fn commit(&self, commit: Commit<F>) -> Result<Status, Self::Error>; /// Use the given hash and private key to sign a signature. If success, return `Ok(signature)`, /// else return `Err()`. fn sign(&self, hash: &[u8]) -> Result<Signature, Self::Error>; /// Verify a signature. If success return a `Ok(address)` that recover from the given signature /// and hash, else return `Err()`. fn verify_signature(&self, signature: &[u8], hash: &[u8]) -> Result<Address, Self::Error>; /// Hash a message. fn hash(&self, msg: &[u8]) -> Hash; } /// A trait define the proposal content, wrapper `Clone`, `Debug`, `Hash`, /// `Send`, `'static`, `Serialize` and `Deserialize`. pub trait Content: Clone + Debug + Send + 'static + Serialize + DeserializeOwned { /// Encode and decode error. type Error: Debug; /// A function to encode the content into bytes. fn encode(self) -> Result<Vec<u8>, Self::Error>; /// A function to decode bytes into Content. fn decode(bytes: &[u8]) -> Result<Self, Self::Error>; /// A function to crypt the content hash. fn hash(&self) -> Vec<u8>; } /// Vote collection and proposal collection. pub(crate) mod collection; /// Consensus survice. pub mod consensus; /// Consensus error. pub mod error; /// Types used in consensus. pub mod types; /// Some utils. pub mod util; /// Consensus wal log. pub(crate) mod wal; /// Re-pub consensus executor pub use consensus::ConsensusExecutor; /// Re-pub check proof function. pub use util::check_proof;
35.013699
99
0.641628
69492419b948fd95d556ada5e63541f3fa3ffd11
2,520
#![allow(incomplete_features)] #![cfg_attr(RUSTC_WITH_SPECIALIZATION, feature(specialization))] #![cfg_attr(RUSTC_NEEDS_PROC_MACRO_HYGIENE, feature(proc_macro_hygiene))] // Allows macro expansion of `use ::solana_sdk::*` to work within this crate extern crate self as solana_sdk; #[cfg(feature = "full")] pub use signer::signers; pub use solana_program::*; pub mod account; pub mod account_utils; pub mod builtins; pub mod client; pub mod commitment_config; pub mod compute_budget; pub mod derivation_path; pub mod deserialize_utils; pub mod entrypoint; pub mod entrypoint_deprecated; pub mod entrypoint_native; pub mod epoch_info; pub mod exit; pub mod feature; pub mod feature_set; pub mod genesis_config; pub mod hard_forks; pub mod hash; pub mod inflation; pub mod keyed_account; pub mod log; pub mod native_loader; pub mod nonce_account; pub mod nonce_keyed_account; pub mod packet; pub mod poh_config; pub mod process_instruction; pub mod program_utils; pub mod pubkey; pub mod recent_blockhashes_account; pub mod rpc_port; pub mod sanitized_transaction; pub mod secp256k1_instruction; pub mod shred_version; pub mod signature; pub mod signer; pub mod system_transaction; pub mod timing; pub mod transaction; pub mod transport; /// Convenience macro to declare a static public key and functions to interact with it /// /// Input: a single literal base58 string representation of a program's id /// /// # Example /// /// ``` /// # // wrapper is used so that the macro invocation occurs in the item position /// # // rather than in the statement position which isn't allowed. /// use std::str::FromStr; /// use solana_sdk::{declare_id, pubkey::Pubkey}; /// /// # mod item_wrapper { /// # use solana_sdk::declare_id; /// declare_id!("My11111111111111111111111111111111111111111"); /// # } /// # use item_wrapper::id; /// /// let my_id = Pubkey::from_str("My11111111111111111111111111111111111111111").unwrap(); /// assert_eq!(id(), my_id); /// ``` pub use solana_sdk_macro::declare_id; pub use solana_sdk_macro::pubkeys; #[rustversion::since(1.46.0)] pub use solana_sdk_macro::respan; // Unused `solana_sdk::program_stubs!()` macro retained for source backwards compatibility with older programs #[macro_export] #[deprecated( since = "1.4.3", note = "program_stubs macro is obsolete and can be safely removed" )] macro_rules! program_stubs { () => {}; } #[macro_use] extern crate serde_derive; pub extern crate bs58; extern crate log as logger; #[macro_use] extern crate solana_frozen_abi_macro;
26.25
110
0.755159
080dd329a731b7966d30f3070290b802b7a2459c
1,974
// Copyright (C) 2021 Leandro Lisboa Penz <lpenz@lpenz.org> // This file is subject to the terms and conditions defined in // file 'LICENSE', which is part of this source code package. #![warn(rust_2018_idioms)] #![warn(missing_docs)] //! copstr is a COPy STRing module //! //! [`copstr::Str`] wraps a fixed-size array of `u8` and provides a //! string-like interface on top. The size is specified using a const //! generic argument. //! //! The internal `u8` array corresponds to UTF-8 encoded `chars`. All //! functions guarantee that the contents are valid UTF-8 and return //! an error if they are not. Truncation only happens at UTF-8 //! boundaries. //! //! [`copstr`] is very useful when we want to add a string-like field //! to a struct that implements `Copy` but we don't want to give up //! this trait. //! //! # Example usage //! //! ```rust //! # fn main() -> Result<(), Box<dyn std::error::Error>> { //! use copstr; //! use std::convert::TryFrom; //! //! // Create an owned fixed-size string with size 6 *on the stack*: //! let mut string = copstr::Str::<6>::try_from("string")?; //! //! // Use it as a regular string: //! println!("contents: {}", string); //! //! // Replace the contents with another string that fits the size 6: //! string.replace("str")?; //! //! // Append a letter: //! string.push('i')?; //! //! // Instead of returning a potential error, we can instead use //! // truncating methods: //! string.replace_trunc("stringification"); //! assert_eq!(string.as_str(), "string"); //! //! // `copstr::Str` implements Deref<Target=str>, so all `str` // //! // methods are available: //! let split = format!("{:?}", string.split_at(3)); //! assert_eq!(split, r#"("str", "ing")"#); //! //! // We can add a `copstr` to a struct without having to give up the //! // `Copy` trait: //! #[derive(Clone, Copy)] //! pub struct Mystruct { //! // ... //! comment: copstr::Str<10>, //! } //! # Ok(()) } //! ``` mod copstr; pub use self::copstr::*;
30.84375
70
0.628166
2f8e1c96eac7a65ef0fb465500a0bf1f8858ab57
945
use solana_program::{account_info::{AccountInfo,next_account_info},entrypoint,entrypoint::ProgramResult,pubkey::Pubkey,msg}; use mokshyafeed::collection_price; use std::{ str::FromStr }; // Returns the current price of the collection as per the collection account info entrypoint!(read_price); pub fn read_price( _program_id: &Pubkey, // Ignored account_info: &[AccountInfo], // Public key of the account to read price data from _instruction_data: &[u8], )-> ProgramResult { let program_id="GK4UuXCYhFYjUbf9514GrWuCDtxd75xkqpg9bZ1K9EL7"; //always fixed let program_id = Pubkey::from_str(program_id).unwrap(); let accounts_iter = &mut account_info.iter(); // This is the account of our our account let data_account = next_account_info(accounts_iter)?; msg!("The price of the nft collection is "); let price=collection_price(&program_id, data_account)?; msg!("{}",price); Ok(()) }
35
124
0.719577
e244b34dbde7c94e4b3be3bd602d55c32f7fbf46
48,168
use crate::chain::{address, Network, OutPoint, Transaction, TxIn, TxOut}; use crate::config::Config; use crate::errors; use crate::new_index::{compute_script_hash, Query, SpendingInput, Utxo}; use crate::util::{ create_socket, electrum_merkle, extract_tx_prevouts, full_hash, get_innerscripts, get_script_asm, get_tx_fee, has_prevout, is_coinbase, script_to_address, BlockHeaderMeta, BlockId, FullHash, TransactionStatus, }; #[cfg(not(feature = "liquid"))] use bitcoin::consensus::encode; use bitcoin::hashes::hex::{FromHex, ToHex}; use bitcoin::hashes::Error as HashError; use bitcoin::{BitcoinHash, BlockHash, Script, Txid}; use hex::{self, FromHexError}; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Method, Response, Server, StatusCode}; use tokio::sync::oneshot; use hyperlocal::UnixServerExt; use std::fs; #[cfg(feature = "liquid")] use { crate::elements::{peg::PegoutValue, IssuanceValue}, elements::{ confidential::{Asset, Nonce, Value}, encode, AssetId, }, }; use serde::Serialize; use serde_json; use std::collections::{HashMap, HashSet}; use std::num::ParseIntError; use std::os::unix::fs::FileTypeExt; use std::str::FromStr; use std::sync::Arc; use std::thread; use url::form_urlencoded; const CHAIN_TXS_PER_PAGE: usize = 25; const MAX_MEMPOOL_TXS: usize = 50; const BLOCK_LIMIT: usize = 10; const ADDRESS_SEARCH_LIMIT: usize = 10; const TTL_LONG: u32 = 157_784_630; // ttl for static resources (5 years) const TTL_SHORT: u32 = 10; // ttl for volatie resources const TTL_MEMPOOL_RECENT: u32 = 5; // ttl for GET /mempool/recent const CONF_FINAL: usize = 10; // reorgs deeper than this are considered unlikely #[derive(Serialize, Deserialize)] struct BlockValue { id: String, height: u32, version: u32, timestamp: u32, tx_count: u32, size: u32, weight: u32, merkle_root: String, previousblockhash: Option<String>, #[cfg(not(feature = "liquid"))] nonce: u32, #[cfg(not(feature = "liquid"))] bits: u32, #[cfg(not(feature = "liquid"))] difficulty: u64, #[cfg(feature = "liquid")] #[serde(skip_serializing_if = "Option::is_none")] ext: Option<serde_json::Value>, } impl BlockValue { #[cfg_attr(feature = "liquid", allow(unused_variables))] fn new(blockhm: BlockHeaderMeta, network: Network) -> Self { let header = blockhm.header_entry.header(); BlockValue { id: header.bitcoin_hash().to_hex(), height: blockhm.header_entry.height() as u32, version: header.version, timestamp: header.time, tx_count: blockhm.meta.tx_count, size: blockhm.meta.size, weight: blockhm.meta.weight, merkle_root: header.merkle_root.to_hex(), previousblockhash: if header.prev_blockhash != BlockHash::default() { Some(header.prev_blockhash.to_hex()) } else { None }, #[cfg(not(feature = "liquid"))] bits: header.bits, #[cfg(not(feature = "liquid"))] nonce: header.nonce, #[cfg(not(feature = "liquid"))] difficulty: header.difficulty(bitcoin::Network::from(network)), #[cfg(feature = "liquid")] ext: Some(json!(header.ext)), } } } #[derive(Serialize, Deserialize)] struct TransactionValue { txid: Txid, version: u32, locktime: u32, vin: Vec<TxInValue>, vout: Vec<TxOutValue>, size: u32, weight: u32, fee: u64, #[serde(skip_serializing_if = "Option::is_none")] status: Option<TransactionStatus>, #[serde(skip_serializing_if = "Option::is_none")] confirmations: Option<usize>, } impl TransactionValue { fn new( tx: Transaction, blockid: Option<BlockId>, txos: &HashMap<OutPoint, TxOut>, config: &Config, best_height: usize, spends: Vec<SpendingValue>, ) -> Self { let prevouts = extract_tx_prevouts(&tx, &txos, true); let vins: Vec<TxInValue> = tx .input .iter() .enumerate() .map(|(index, txin)| { TxInValue::new(txin, prevouts.get(&(index as u32)).cloned(), config) }) .collect(); let vouts: Vec<TxOutValue> = tx .output .iter().zip(spends.iter()) .map(|(txout, spending_value) | TxOutValue::new(txout, config, Some(spending_value.spent))) .collect(); let fee = get_tx_fee(&tx, &prevouts, config.network_type); let confirmations= match blockid.clone() { Some(b) => Some(best_height - b.height + 1), None => None, }; TransactionValue { txid: tx.txid(), version: tx.version, locktime: tx.lock_time, vin: vins, vout: vouts, size: tx.get_size() as u32, weight: tx.get_weight() as u32, fee, status: Some(TransactionStatus::from(blockid)), confirmations, } } } #[derive(Serialize, Deserialize, Clone)] struct TxInValue { txid: Txid, vout: u32, prevout: Option<TxOutValue>, scriptsig: Script, scriptsig_asm: String, #[serde(skip_serializing_if = "Option::is_none")] witness: Option<Vec<String>>, is_coinbase: bool, sequence: u32, #[serde(skip_serializing_if = "Option::is_none")] inner_redeemscript_asm: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] inner_witnessscript_asm: Option<String>, #[cfg(feature = "liquid")] is_pegin: bool, #[cfg(feature = "liquid")] #[serde(skip_serializing_if = "Option::is_none")] issuance: Option<IssuanceValue>, } impl TxInValue { fn new(txin: &TxIn, prevout: Option<&TxOut>, config: &Config) -> Self { let witness = &txin.witness; #[cfg(feature = "liquid")] let witness = &witness.script_witness; let witness = if !witness.is_empty() { Some(witness.iter().map(hex::encode).collect()) } else { None }; let is_coinbase = is_coinbase(&txin); let innerscripts = prevout.map(|prevout| get_innerscripts(&txin, &prevout)); TxInValue { txid: txin.previous_output.txid, vout: txin.previous_output.vout, prevout: prevout.map(|prevout| TxOutValue::new(prevout, config, None)), scriptsig_asm: get_script_asm(&txin.script_sig), witness, inner_redeemscript_asm: innerscripts .as_ref() .and_then(|i| i.redeem_script.as_ref()) .map(get_script_asm), inner_witnessscript_asm: innerscripts .as_ref() .and_then(|i| i.witness_script.as_ref()) .map(get_script_asm), is_coinbase, sequence: txin.sequence, #[cfg(feature = "liquid")] is_pegin: txin.is_pegin, #[cfg(feature = "liquid")] issuance: if txin.has_issuance() { Some(IssuanceValue::from(txin)) } else { None }, scriptsig: txin.script_sig.clone(), } } } #[derive(Serialize, Deserialize, Clone)] struct TxOutValue { #[serde(skip_serializing_if = "Option::is_none")] spent: Option<bool>, scriptpubkey: Script, scriptpubkey_asm: String, scriptpubkey_type: String, #[serde(skip_serializing_if = "Option::is_none")] scriptpubkey_address: Option<String>, #[cfg(not(feature = "liquid"))] value: u64, #[cfg(feature = "liquid")] #[serde(skip_serializing_if = "Option::is_none")] value: Option<u64>, #[cfg(feature = "liquid")] #[serde(skip_serializing_if = "Option::is_none")] valuecommitment: Option<String>, #[cfg(feature = "liquid")] #[serde(skip_serializing_if = "Option::is_none")] asset: Option<String>, #[cfg(feature = "liquid")] #[serde(skip_serializing_if = "Option::is_none")] assetcommitment: Option<String>, #[cfg(feature = "liquid")] #[serde(skip_serializing_if = "Option::is_none")] pegout: Option<PegoutValue>, } impl TxOutValue { fn new(txout: &TxOut, config: &Config, spent: Option<bool>) -> Self { #[cfg(not(feature = "liquid"))] let value = txout.value; #[cfg(feature = "liquid")] let value = txout.value.explicit(); #[cfg(feature = "liquid")] let valuecommitment = match txout.value { Value::Confidential(..) => Some(hex::encode(encode::serialize(&txout.value))), _ => None, }; #[cfg(feature = "liquid")] let asset = match txout.asset { Asset::Explicit(value) => Some(value.to_hex()), _ => None, }; #[cfg(feature = "liquid")] let assetcommitment = match txout.asset { Asset::Confidential(..) => Some(hex::encode(encode::serialize(&txout.asset))), _ => None, }; #[cfg(not(feature = "liquid"))] let is_fee = false; #[cfg(feature = "liquid")] let is_fee = txout.is_fee(); let script = &txout.script_pubkey; let script_asm = get_script_asm(&script); let script_addr = script_to_address(&script, config.network_type); // TODO should the following something to put inside rust-elements lib? let script_type = if is_fee { "fee" } else if script.is_empty() { "empty" } else if script.is_op_return() { "op_return" } else if script.is_p2pk() { "p2pk" } else if script.is_p2pkh() { "p2pkh" } else if script.is_p2sh() { "p2sh" } else if script.is_v0_p2wpkh() { "v0_p2wpkh" } else if script.is_v0_p2wsh() { "v0_p2wsh" } else if script.is_provably_unspendable() { "provably_unspendable" } else { "unknown" }; #[cfg(feature = "liquid")] let pegout = PegoutValue::from_txout(txout, config.network_type, config.parent_network); TxOutValue { spent, scriptpubkey: script.clone(), scriptpubkey_asm: script_asm, scriptpubkey_address: script_addr, scriptpubkey_type: script_type.to_string(), value, #[cfg(feature = "liquid")] valuecommitment, #[cfg(feature = "liquid")] asset, #[cfg(feature = "liquid")] assetcommitment, #[cfg(feature = "liquid")] pegout, } } } #[derive(Serialize)] struct UtxoValue { txid: Txid, vout: u32, status: TransactionStatus, #[cfg(not(feature = "liquid"))] value: u64, #[cfg(feature = "liquid")] #[serde(skip_serializing_if = "Option::is_none")] value: Option<u64>, #[cfg(feature = "liquid")] #[serde(skip_serializing_if = "Option::is_none")] valuecommitment: Option<String>, #[cfg(feature = "liquid")] #[serde(skip_serializing_if = "Option::is_none")] asset: Option<String>, #[cfg(feature = "liquid")] #[serde(skip_serializing_if = "Option::is_none")] assetcommitment: Option<String>, #[cfg(feature = "liquid")] #[serde(skip_serializing_if = "Option::is_none")] nonce: Option<String>, #[cfg(feature = "liquid")] #[serde(skip_serializing_if = "Option::is_none")] noncecommitment: Option<String>, #[cfg(feature = "liquid")] #[serde(skip_serializing_if = "Vec::is_empty", with = "crate::util::serde_hex")] surjection_proof: Vec<u8>, #[cfg(feature = "liquid")] #[serde(skip_serializing_if = "Vec::is_empty", with = "crate::util::serde_hex")] range_proof: Vec<u8>, } impl From<Utxo> for UtxoValue { fn from(utxo: Utxo) -> Self { UtxoValue { txid: utxo.txid, vout: utxo.vout, status: TransactionStatus::from(utxo.confirmed), #[cfg(not(feature = "liquid"))] value: utxo.value, #[cfg(feature = "liquid")] value: match utxo.value { Value::Explicit(value) => Some(value), _ => None, }, #[cfg(feature = "liquid")] valuecommitment: match utxo.value { Value::Confidential(..) => Some(hex::encode(encode::serialize(&utxo.value))), _ => None, }, #[cfg(feature = "liquid")] asset: match utxo.asset { Asset::Explicit(asset) => Some(asset.to_hex()), _ => None, }, #[cfg(feature = "liquid")] assetcommitment: match utxo.asset { Asset::Confidential(..) => Some(hex::encode(encode::serialize(&utxo.asset))), _ => None, }, #[cfg(feature = "liquid")] nonce: match utxo.nonce { Nonce::Explicit(nonce) => Some(nonce.to_hex()), _ => None, }, #[cfg(feature = "liquid")] noncecommitment: match utxo.nonce { Nonce::Confidential(..) => Some(hex::encode(encode::serialize(&utxo.nonce))), _ => None, }, #[cfg(feature = "liquid")] surjection_proof: utxo.witness.surjection_proof, #[cfg(feature = "liquid")] range_proof: utxo.witness.rangeproof, } } } #[derive(Serialize)] struct SpendingValue { spent: bool, #[serde(skip_serializing_if = "Option::is_none")] txid: Option<Txid>, #[serde(skip_serializing_if = "Option::is_none")] vin: Option<u32>, #[serde(skip_serializing_if = "Option::is_none")] status: Option<TransactionStatus>, } impl From<SpendingInput> for SpendingValue { fn from(spend: SpendingInput) -> Self { SpendingValue { spent: true, txid: Some(spend.txid), vin: Some(spend.vin), status: Some(TransactionStatus::from(spend.confirmed)), } } } impl Default for SpendingValue { fn default() -> Self { SpendingValue { spent: false, txid: None, vin: None, status: None, } } } fn ttl_by_depth(height: Option<usize>, query: &Query) -> u32 { height.map_or(TTL_SHORT, |height| { if query.chain().best_height() - height >= CONF_FINAL { TTL_LONG } else { TTL_SHORT } }) } fn prepare_txs( txs: Vec<(Transaction, Option<BlockId>)>, query: &Query, config: &Config, ) -> Vec<TransactionValue> { let outpoints = txs .iter() .flat_map(|(tx, _)| { tx.input .iter() .filter(|txin| has_prevout(txin)) .map(|txin| txin.previous_output) }) .collect(); let prevouts = query.lookup_txos(&outpoints); let best_height = query.chain().best_height(); txs.into_iter() .map(|(tx, blockid)| { let spends: Vec<SpendingValue> = query .lookup_tx_spends(tx.clone()) .into_iter() .map(|spend| spend.map_or_else(SpendingValue::default, SpendingValue::from)) .collect(); TransactionValue::new(tx, blockid, &prevouts, config, best_height, spends) }) .collect() } #[tokio::main] async fn run_server(config: Arc<Config>, query: Arc<Query>, rx: oneshot::Receiver<()>) { let addr = &config.http_addr; let socket_file = &config.http_socket_file; let config = Arc::clone(&config); let query = Arc::clone(&query); let make_service_fn_inn = || { let query = Arc::clone(&query); let config = Arc::clone(&config); async move { Ok::<_, hyper::Error>(service_fn(move |req| { let query = Arc::clone(&query); let config = Arc::clone(&config); async move { let method = req.method().clone(); let uri = req.uri().clone(); let body = hyper::body::to_bytes(req.into_body()).await?; let mut resp = handle_request(method, uri, body, &query, &config) .unwrap_or_else(|err| { warn!("{:?}", err); Response::builder() .status(err.0) .header("Content-Type", "text/plain") .body(Body::from(err.1)) .unwrap() }); if let Some(ref origins) = config.cors { resp.headers_mut() .insert("Access-Control-Allow-Origin", origins.parse().unwrap()); } Ok::<_, hyper::Error>(resp) } })) } }; let server = match socket_file { None => { info!("REST server running on {}", addr); let socket = create_socket(&addr); socket.listen(511).expect("setting backlog failed"); Server::from_tcp(socket.into_tcp_listener()) .expect("Server::from_tcp failed") .serve(make_service_fn(move |_| make_service_fn_inn())) .with_graceful_shutdown(async { rx.await.ok(); }) .await } Some(path) => { if let Ok(meta) = fs::metadata(&path) { // Cleanup socket file left by previous execution if meta.file_type().is_socket() { fs::remove_file(path).ok(); } } info!("REST server running on unix socket {}", path.display()); Server::bind_unix(path) .expect("Server::bind_unix failed") .serve(make_service_fn(move |_| make_service_fn_inn())) .with_graceful_shutdown(async { rx.await.ok(); }) .await } }; if let Err(e) = server { eprintln!("server error: {}", e); } } pub fn start(config: Arc<Config>, query: Arc<Query>) -> Handle { let (tx, rx) = oneshot::channel::<()>(); Handle { tx, thread: thread::spawn(move || { run_server(config, query, rx); }), } } pub struct Handle { tx: oneshot::Sender<()>, thread: thread::JoinHandle<()>, } impl Handle { pub fn stop(self) { self.tx.send(()).expect("failed to send shutdown signal"); self.thread.join().expect("REST server failed"); } } fn handle_request( method: Method, uri: hyper::Uri, body: hyper::body::Bytes, query: &Query, config: &Config, ) -> Result<Response<Body>, HttpError> { // TODO it looks hyper does not have routing and query parsing :( let path: Vec<&str> = uri.path().split('/').skip(1).collect(); let query_params = match uri.query() { Some(value) => form_urlencoded::parse(&value.as_bytes()) .into_owned() .collect::<HashMap<String, String>>(), None => HashMap::new(), }; info!("handle {:?} {:?}", method, uri); match ( &method, path.get(0), path.get(1), path.get(2), path.get(3), path.get(4), ) { (&Method::GET, Some(&"blocks"), Some(&"tip"), Some(&"hash"), None, None) => http_message( StatusCode::OK, query.chain().best_hash().to_hex(), TTL_SHORT, ), (&Method::GET, Some(&"blocks"), Some(&"tip"), Some(&"height"), None, None) => http_message( StatusCode::OK, query.chain().best_height().to_string(), TTL_SHORT, ), (&Method::GET, Some(&"blocks"), start_height, None, None, None) => { let start_height = start_height.and_then(|height| height.parse::<usize>().ok()); blocks(&query, &config, start_height) } (&Method::GET, Some(&"block-height"), Some(height), None, None, None) => { let height = height.parse::<usize>()?; let header = query .chain() .header_by_height(height) .ok_or_else(|| HttpError::not_found("Block not found".to_string()))?; let ttl = ttl_by_depth(Some(height), query); http_message(StatusCode::OK, header.hash().to_hex(), ttl) } (&Method::GET, Some(&"block"), Some(hash), None, None, None) => { let hash = BlockHash::from_hex(hash)?; let blockhm = query .chain() .get_block_with_meta(&hash) .ok_or_else(|| HttpError::not_found("Block not found".to_string()))?; let block_value = BlockValue::new(blockhm, config.network_type); json_response(block_value, TTL_LONG) } (&Method::GET, Some(&"block"), Some(hash), Some(&"status"), None, None) => { let hash = BlockHash::from_hex(hash)?; let status = query.chain().get_block_status(&hash); let ttl = ttl_by_depth(status.height, query); json_response(status, ttl) } (&Method::GET, Some(&"block"), Some(hash), Some(&"txids"), None, None) => { let hash = BlockHash::from_hex(hash)?; let txids = query .chain() .get_block_txids(&hash) .ok_or_else(|| HttpError::not_found("Block not found".to_string()))?; json_response(txids, TTL_LONG) } (&Method::GET, Some(&"block"), Some(hash), Some(&"raw"), None, None) => { let hash = BlockHash::from_hex(hash)?; let raw = query .chain() .get_block_raw(&hash) .ok_or_else(|| HttpError::not_found("Block not found".to_string()))?; Ok(Response::builder() .status(StatusCode::OK) .header("Content-Type", "application/octet-stream") .header("Cache-Control", format!("public, max-age={:}", TTL_LONG)) .body(Body::from(raw)) .unwrap()) } (&Method::GET, Some(&"block"), Some(hash), Some(&"txid"), Some(index), None) => { let hash = BlockHash::from_hex(hash)?; let index: usize = index.parse()?; let txids = query .chain() .get_block_txids(&hash) .ok_or_else(|| HttpError::not_found("Block not found".to_string()))?; if index >= txids.len() { bail!(HttpError::not_found("tx index out of range".to_string())); } http_message(StatusCode::OK, txids[index].to_hex(), TTL_LONG) } (&Method::GET, Some(&"block"), Some(hash), Some(&"txs"), start_index, None) => { let hash = BlockHash::from_hex(hash)?; let txids = query .chain() .get_block_txids(&hash) .ok_or_else(|| HttpError::not_found("Block not found".to_string()))?; let start_index = start_index .map_or(0u32, |el| el.parse().unwrap_or(0)) .max(0u32) as usize; if start_index >= txids.len() { bail!(HttpError::not_found("start index out of range".to_string())); } else if start_index % CHAIN_TXS_PER_PAGE != 0 { bail!(HttpError::from(format!( "start index must be a multipication of {}", CHAIN_TXS_PER_PAGE ))); } // header_by_hash() only returns the BlockId for non-orphaned blocks, // or None for orphaned let confirmed_blockid = query.chain().blockid_by_hash(&hash); let txs = txids .iter() .skip(start_index) .take(CHAIN_TXS_PER_PAGE) .map(|txid| { query .lookup_txn(&txid) .map(|tx| (tx, confirmed_blockid.clone())) .ok_or_else(|| "missing tx".to_string()) }) .collect::<Result<Vec<(Transaction, Option<BlockId>)>, _>>()?; // XXX orphraned blocks alway get TTL_SHORT let ttl = ttl_by_depth(confirmed_blockid.map(|b| b.height), query); json_response(prepare_txs(txs, query, config), ttl) } (&Method::GET, Some(script_type @ &"address"), Some(script_str), None, None, None) | (&Method::GET, Some(script_type @ &"scripthash"), Some(script_str), None, None, None) => { let script_hash = to_scripthash(script_type, script_str, config.network_type)?; let stats = query.stats(&script_hash[..]); json_response( json!({ *script_type: script_str, "chain_stats": stats.0, "mempool_stats": stats.1, }), TTL_SHORT, ) } ( &Method::GET, Some(script_type @ &"addresses"), Some(addresses_str), Some(&"txs"), None, None, ) => { let addresses = addresses_str.split(","); let mut txs = vec![]; for address_str in addresses { let script_hash = to_scripthash(&"address", address_str, config.network_type)?; txs.extend( query .mempool() .history(&script_hash[..], 10000) .into_iter() .map(|tx| (tx, None)), ); txs.extend( query .chain() .history(&script_hash[..], None, 10000) .into_iter() .map(|(tx, blockid)| (tx, Some(blockid))), ); } let mut uniques = HashSet::new(); txs.retain(|(tx, _)| uniques.insert(tx.ntxid())); json_response(prepare_txs(txs, query, config), TTL_SHORT) } ( &Method::GET, Some(script_type @ &"address"), Some(script_str), Some(&"txs"), None, None, ) | ( &Method::GET, Some(script_type @ &"scripthash"), Some(script_str), Some(&"txs"), None, None, ) => { let script_hash = to_scripthash(script_type, script_str, config.network_type)?; let mut txs = vec![]; txs.extend( query .mempool() .history(&script_hash[..], MAX_MEMPOOL_TXS) .into_iter() .map(|tx| (tx, None)), ); txs.extend( query .chain() .history(&script_hash[..], None, CHAIN_TXS_PER_PAGE) .into_iter() .map(|(tx, blockid)| (tx, Some(blockid))), ); json_response(prepare_txs(txs, query, config), TTL_SHORT) } ( &Method::GET, Some(script_type @ &"address"), Some(script_str), Some(&"txs"), Some(&"chain"), last_seen_txid, ) | ( &Method::GET, Some(script_type @ &"scripthash"), Some(script_str), Some(&"txs"), Some(&"chain"), last_seen_txid, ) => { let script_hash = to_scripthash(script_type, script_str, config.network_type)?; let last_seen_txid = last_seen_txid.and_then(|txid| Txid::from_hex(txid).ok()); let txs = query .chain() .history( &script_hash[..], last_seen_txid.as_ref(), CHAIN_TXS_PER_PAGE, ) .into_iter() .map(|(tx, blockid)| (tx, Some(blockid))) .collect(); json_response(prepare_txs(txs, query, config), TTL_SHORT) } ( &Method::GET, Some(script_type @ &"address"), Some(script_str), Some(&"txs"), Some(&"mempool"), None, ) | ( &Method::GET, Some(script_type @ &"scripthash"), Some(script_str), Some(&"txs"), Some(&"mempool"), None, ) => { let script_hash = to_scripthash(script_type, script_str, config.network_type)?; let txs = query .mempool() .history(&script_hash[..], MAX_MEMPOOL_TXS) .into_iter() .map(|tx| (tx, None)) .collect(); json_response(prepare_txs(txs, query, config), TTL_SHORT) } ( &Method::GET, Some(script_type @ &"address"), Some(script_str), Some(&"utxo"), None, None, ) | ( &Method::GET, Some(script_type @ &"scripthash"), Some(script_str), Some(&"utxo"), None, None, ) => { let script_hash = to_scripthash(script_type, script_str, config.network_type)?; let utxos: Vec<UtxoValue> = query .utxo(&script_hash[..])? .into_iter() .map(UtxoValue::from) .collect(); // XXX paging? json_response(utxos, TTL_SHORT) } (&Method::GET, Some(&"address-prefix"), Some(prefix), None, None, None) => { if !config.address_search { return Err(HttpError::from("address search disabled".to_string())); } let results = query.chain().address_search(prefix, ADDRESS_SEARCH_LIMIT); json_response(results, TTL_SHORT) } (&Method::GET, Some(&"tx"), Some(hash), None, None, None) => { let hash = Txid::from_hex(hash)?; let tx = query .lookup_txn(&hash) .ok_or_else(|| HttpError::not_found("Transaction not found".to_string()))?; let blockid = query.chain().tx_confirming_block(&hash); let ttl = ttl_by_depth(blockid.as_ref().map(|b| b.height), query); let tx = prepare_txs(vec![(tx, blockid)], query, config).remove(0); json_response(tx, ttl) } (&Method::GET, Some(&"tx"), Some(hash), Some(out_type @ &"hex"), None, None) | (&Method::GET, Some(&"tx"), Some(hash), Some(out_type @ &"raw"), None, None) => { let hash = Txid::from_hex(hash)?; let rawtx = query .lookup_raw_txn(&hash) .ok_or_else(|| HttpError::not_found("Transaction not found".to_string()))?; let (content_type, body) = match *out_type { "raw" => ("application/octet-stream", Body::from(rawtx)), "hex" => ("text/plain", Body::from(hex::encode(rawtx))), _ => unreachable!(), }; let ttl = ttl_by_depth(query.get_tx_status(&hash).block_height, query); Ok(Response::builder() .status(StatusCode::OK) .header("Content-Type", content_type) .header("Cache-Control", format!("public, max-age={:}", ttl)) .body(body) .unwrap()) } (&Method::GET, Some(&"tx"), Some(hash), Some(&"status"), None, None) => { let hash = Txid::from_hex(hash)?; let status = query.get_tx_status(&hash); let ttl = ttl_by_depth(status.block_height, query); json_response(status, ttl) } (&Method::GET, Some(&"tx"), Some(hash), Some(&"merkle-proof"), None, None) => { let hash = Txid::from_hex(hash)?; let blockid = query.chain().tx_confirming_block(&hash).ok_or_else(|| { HttpError::not_found("Transaction not found or is unconfirmed".to_string()) })?; let (merkle, pos) = electrum_merkle::get_tx_merkle_proof(query.chain(), &hash, &blockid.hash)?; let merkle: Vec<String> = merkle.into_iter().map(|txid| txid.to_hex()).collect(); let ttl = ttl_by_depth(Some(blockid.height), query); json_response( json!({ "block_height": blockid.height, "merkle": merkle, "pos": pos }), ttl, ) } #[cfg(not(feature = "liquid"))] (&Method::GET, Some(&"tx"), Some(hash), Some(&"merkleblock-proof"), None, None) => { let hash = Txid::from_hex(hash)?; let merkleblock = query.chain().get_merkleblock_proof(&hash).ok_or_else(|| { HttpError::not_found("Transaction not found or is unconfirmed".to_string()) })?; let height = query .chain() .height_by_hash(&merkleblock.header.bitcoin_hash()); http_message( StatusCode::OK, hex::encode(encode::serialize(&merkleblock)), ttl_by_depth(height, query), ) } (&Method::GET, Some(&"tx"), Some(hash), Some(&"outspend"), Some(index), None) => { let hash = Txid::from_hex(hash)?; let outpoint = OutPoint { txid: hash, vout: index.parse::<u32>()?, }; let spend = query .lookup_spend(&outpoint) .map_or_else(SpendingValue::default, SpendingValue::from); let ttl = ttl_by_depth( spend .status .as_ref() .and_then(|ref status| status.block_height), query, ); json_response(spend, ttl) } (&Method::GET, Some(&"tx"), Some(hash), Some(&"outspends"), None, None) => { let hash = Txid::from_hex(hash)?; let tx = query .lookup_txn(&hash) .ok_or_else(|| HttpError::not_found("Transaction not found".to_string()))?; let spends: Vec<SpendingValue> = query .lookup_tx_spends(tx) .into_iter() .map(|spend| spend.map_or_else(SpendingValue::default, SpendingValue::from)) .collect(); // @TODO long ttl if all outputs are either spent long ago or unspendable json_response(spends, TTL_SHORT) } (&Method::GET, Some(&"broadcast"), None, None, None, None) | (&Method::POST, Some(&"tx"), None, None, None, None) => { // accept both POST and GET for backward compatibility. // GET will eventually be removed in favor of POST. let txhex = match method { Method::POST => String::from_utf8(body.to_vec())?, Method::GET => query_params .get("tx") .cloned() .ok_or_else(|| HttpError::from("Missing tx".to_string()))?, _ => return http_message(StatusCode::METHOD_NOT_ALLOWED, "Invalid method", 0), }; let txid = query .broadcast_raw(&txhex) .map_err(|err| HttpError::from(err.description().to_string()))?; http_message(StatusCode::OK, txid.to_hex(), 0) } (&Method::POST, Some(&"pushtx"), None, None, None, None) => { let body_str = String::from_utf8(body.to_vec())?; let body_json: serde_json::Value = serde_json::from_str(&body_str).unwrap(); let hex: &str = body_json["hex"].as_str().unwrap(); let txid = query .broadcast_raw(hex) .map_err(|err| HttpError::from(err.description().to_string()))?; let mut result = HashMap::new(); result.insert("txid", txid); json_response(result, TTL_SHORT) } (&Method::GET, Some(&"mempool"), None, None, None, None) => { json_response(query.mempool().backlog_stats(), TTL_SHORT) } (&Method::GET, Some(&"mempool"), Some(&"txids"), None, None, None) => { json_response(query.mempool().txids(), TTL_SHORT) } (&Method::GET, Some(&"mempool"), Some(&"recent"), None, None, None) => { let mempool = query.mempool(); let recent = mempool.recent_txs_overview(); json_response(recent, TTL_MEMPOOL_RECENT) } (&Method::GET, Some(&"fee-estimates"), None, None, None, None) => { json_response(query.estimate_fee_map(), TTL_SHORT) } #[cfg(feature = "liquid")] (&Method::GET, Some(&"asset"), Some(asset_str), None, None, None) => { let asset_id = AssetId::from_hex(asset_str)?; let asset_entry = query .lookup_asset(&asset_id)? .ok_or_else(|| HttpError::not_found("Asset id not found".to_string()))?; json_response(asset_entry, TTL_SHORT) } #[cfg(feature = "liquid")] (&Method::GET, Some(&"asset"), Some(asset_str), Some(&"txs"), None, None) => { let asset_id = AssetId::from_hex(asset_str)?; let mut txs = vec![]; txs.extend( query .mempool() .asset_history(&asset_id, MAX_MEMPOOL_TXS) .into_iter() .map(|tx| (tx, None)), ); txs.extend( query .chain() .asset_history(&asset_id, None, CHAIN_TXS_PER_PAGE) .into_iter() .map(|(tx, blockid)| (tx, Some(blockid))), ); json_response(prepare_txs(txs, query, config), TTL_SHORT) } #[cfg(feature = "liquid")] ( &Method::GET, Some(&"asset"), Some(asset_str), Some(&"txs"), Some(&"chain"), last_seen_txid, ) => { let asset_id = AssetId::from_hex(asset_str)?; let last_seen_txid = last_seen_txid.and_then(|txid| Txid::from_hex(txid).ok()); let txs = query .chain() .asset_history(&asset_id, last_seen_txid.as_ref(), CHAIN_TXS_PER_PAGE) .into_iter() .map(|(tx, blockid)| (tx, Some(blockid))) .collect(); json_response(prepare_txs(txs, query, config), TTL_SHORT) } #[cfg(feature = "liquid")] (&Method::GET, Some(&"asset"), Some(asset_str), Some(&"txs"), Some(&"mempool"), None) => { let asset_id = AssetId::from_hex(asset_str)?; let txs = query .mempool() .asset_history(&asset_id, MAX_MEMPOOL_TXS) .into_iter() .map(|tx| (tx, None)) .collect(); json_response(prepare_txs(txs, query, config), TTL_SHORT) } #[cfg(feature = "liquid")] (&Method::GET, Some(&"asset"), Some(asset_str), Some(&"supply"), param, None) => { let asset_id = AssetId::from_hex(asset_str)?; let asset_entry = query .lookup_asset(&asset_id)? .ok_or_else(|| HttpError::not_found("Asset id not found".to_string()))?; let supply = asset_entry .supply() .ok_or_else(|| HttpError::from("Asset supply is blinded".to_string()))?; let precision = asset_entry.precision(); if param == Some(&"decimal") && precision > 0 { let supply_dec = supply as f64 / 10u32.pow(precision.into()) as f64; http_message(StatusCode::OK, supply_dec.to_string(), TTL_SHORT) } else { http_message(StatusCode::OK, supply.to_string(), TTL_SHORT) } } _ => Err(HttpError::not_found(format!( "endpoint does not exist {:?}", uri.path() ))), } } fn http_message<T>(status: StatusCode, message: T, ttl: u32) -> Result<Response<Body>, HttpError> where T: Into<Body>, { Ok(Response::builder() .status(status) .header("Content-Type", "text/plain") .header("Cache-Control", format!("public, max-age={:}", ttl)) .body(message.into()) .unwrap()) } fn json_response<T: Serialize>(value: T, ttl: u32) -> Result<Response<Body>, HttpError> { let value = serde_json::to_string(&value)?; Ok(Response::builder() .header("Content-Type", "application/json") .header("Cache-Control", format!("public, max-age={:}", ttl)) .body(Body::from(value)) .unwrap()) } fn blocks( query: &Query, config: &Config, start_height: Option<usize>, ) -> Result<Response<Body>, HttpError> { let mut values = Vec::new(); let mut current_hash = match start_height { Some(height) => *query .chain() .header_by_height(height) .ok_or_else(|| HttpError::not_found("Block not found".to_string()))? .hash(), None => query.chain().best_hash(), }; let zero = [0u8; 32]; for _ in 0..BLOCK_LIMIT { let blockhm = query .chain() .get_block_with_meta(&current_hash) .ok_or_else(|| HttpError::not_found("Block not found".to_string()))?; current_hash = blockhm.header_entry.header().prev_blockhash; #[allow(unused_mut)] let mut value = BlockValue::new(blockhm, config.network_type); #[cfg(feature = "liquid")] { // exclude ExtData in block list view value.ext = None; } values.push(value); if current_hash[..] == zero[..] { break; } } json_response(values, TTL_SHORT) } fn to_scripthash( script_type: &str, script_str: &str, network: Network, ) -> Result<FullHash, HttpError> { match script_type { "address" => address_to_scripthash(script_str, network), "scripthash" => parse_scripthash(script_str), _ => bail!("Invalid script type".to_string()), } } #[allow(unused_variables)] // `network` is unused in liquid mode fn address_to_scripthash(addr: &str, network: Network) -> Result<FullHash, HttpError> { let addr = address::Address::from_str(addr)?; #[cfg(not(feature = "liquid"))] let is_expected_net = { let addr_network = Network::from(addr.network); addr_network == network || (addr_network == Network::Testnet && network == Network::Regtest) }; #[cfg(feature = "liquid")] let is_expected_net = addr.params == network.address_params(); if !is_expected_net { bail!(HttpError::from("Address on invalid network".to_string())) } Ok(compute_script_hash(&addr.script_pubkey())) } fn parse_scripthash(scripthash: &str) -> Result<FullHash, HttpError> { let bytes = hex::decode(scripthash)?; if bytes.len() != 32 { Err(HttpError::from("Invalid scripthash".to_string())) } else { Ok(full_hash(&bytes)) } } #[derive(Debug)] struct HttpError(StatusCode, String); impl HttpError { fn not_found(msg: String) -> Self { HttpError(StatusCode::NOT_FOUND, msg) } } impl From<String> for HttpError { fn from(msg: String) -> Self { HttpError(StatusCode::BAD_REQUEST, msg) } } impl From<ParseIntError> for HttpError { fn from(_e: ParseIntError) -> Self { //HttpError::from(e.description().to_string()) HttpError::from("Invalid number".to_string()) } } impl From<HashError> for HttpError { fn from(_e: HashError) -> Self { //HttpError::from(e.description().to_string()) HttpError::from("Invalid hash string".to_string()) } } impl From<FromHexError> for HttpError { fn from(_e: FromHexError) -> Self { //HttpError::from(e.description().to_string()) HttpError::from("Invalid hex string".to_string()) } } impl From<bitcoin::hashes::hex::Error> for HttpError { fn from(_e: bitcoin::hashes::hex::Error) -> Self { //HttpError::from(e.description().to_string()) HttpError::from("Invalid hex string".to_string()) } } impl From<bitcoin::util::address::Error> for HttpError { fn from(_e: bitcoin::util::address::Error) -> Self { //HttpError::from(e.description().to_string()) HttpError::from("Invalid Bitcoin address".to_string()) } } impl From<errors::Error> for HttpError { fn from(e: errors::Error) -> Self { warn!("errors::Error: {:?}", e); match e.description().to_string().as_ref() { "getblock RPC error: {\"code\":-5,\"message\":\"Block not found\"}" => { HttpError::not_found("Block not found".to_string()) } _ => HttpError::from(e.to_string()), } } } impl From<serde_json::Error> for HttpError { fn from(e: serde_json::Error) -> Self { HttpError::from(e.to_string()) } } impl From<encode::Error> for HttpError { fn from(e: encode::Error) -> Self { HttpError::from(e.to_string()) } } impl From<std::string::FromUtf8Error> for HttpError { fn from(e: std::string::FromUtf8Error) -> Self { HttpError::from(e.to_string()) } } #[cfg(feature = "liquid")] impl From<address::AddressError> for HttpError { fn from(e: address::AddressError) -> Self { HttpError::from(e.to_string()) } } #[cfg(test)] mod tests { use crate::rest::HttpError; use serde_json::Value; use std::collections::HashMap; #[test] fn test_parse_query_param() { let mut query_params = HashMap::new(); query_params.insert("limit", "10"); let limit = query_params .get("limit") .map_or(10u32, |el| el.parse().unwrap_or(10u32)) .min(30u32); assert_eq!(10, limit); query_params.insert("limit", "100"); let limit = query_params .get("limit") .map_or(10u32, |el| el.parse().unwrap_or(10u32)) .min(30u32); assert_eq!(30, limit); query_params.insert("limit", "5"); let limit = query_params .get("limit") .map_or(10u32, |el| el.parse().unwrap_or(10u32)) .min(30u32); assert_eq!(5, limit); query_params.insert("limit", "aaa"); let limit = query_params .get("limit") .map_or(10u32, |el| el.parse().unwrap_or(10u32)) .min(30u32); assert_eq!(10, limit); query_params.remove("limit"); let limit = query_params .get("limit") .map_or(10u32, |el| el.parse().unwrap_or(10u32)) .min(30u32); assert_eq!(10, limit); } #[test] fn test_parse_value_param() { let v: Value = json!({ "confirmations": 10 }); let confirmations = v .get("confirmations") .and_then(|el| el.as_u64()) .ok_or(HttpError::from( "confirmations absent or not a u64".to_string(), )) .unwrap(); assert_eq!(10, confirmations); let err = v .get("notexist") .and_then(|el| el.as_u64()) .ok_or(HttpError::from("notexist absent or not a u64".to_string())); assert!(err.is_err()); } }
33.778401
103
0.523709
5d0a0c06bd41f8729ab0b51ba9b285b0791045c4
2,817
use crate::commands::constants::*; use crate::{Error, TmuxCommand, TmuxOutput}; use std::borrow::Cow; /// # Manual /// /// tmux ^3.1: /// ```text /// tmux list-keys [-1aN] [-P prefix-string -T key-table] /// (alias: lsk) /// ``` /// /// tmux ^2.4: /// ```text /// tmux list-keys [-T key-table] /// (alias: lsk) /// ``` /// /// tmux ^2.1: /// ```text /// tmux list-keys [-t mode-table] [-T key-table] /// (alias: lsk) /// ``` /// /// tmux ^0.8: /// ```text /// tmux list-keys [-t key-table] /// (alias: lsk) /// ``` #[derive(Debug, Clone)] pub struct ListKeys<'a>(pub TmuxCommand<'a>); impl<'a> Default for ListKeys<'a> { fn default() -> Self { Self(TmuxCommand { cmd: Some(Cow::Borrowed(LIST_KEYS)), ..Default::default() }) } } impl<'a> ListKeys<'a> { pub fn new() -> Self { Default::default() } /// `[-1]` #[cfg(feature = "tmux_2_4")] pub fn first(&mut self) -> &mut Self { self.0.push_flag(_1_KEY); self } /// `[-a]` #[cfg(feature = "tmux_2_4")] pub fn command(&mut self) -> &mut Self { self.0.push_flag(A_LOWERCASE_KEY); self } /// `[-N]` #[cfg(feature = "tmux_2_4")] pub fn with_notes(&mut self) -> &mut Self { self.0.push_flag(N_UPPERCASE_KEY); self } /// `[-P prefix-string]` #[cfg(feature = "tmux_3_1")] pub fn prefix_string<S: Into<Cow<'a, str>>>(&mut self, prefix_string: S) -> &mut Self { self.0.push_option(P_UPPERCASE_KEY, prefix_string); self } /// `[-t mode-table]` #[cfg(all(feature = "tmux_2_1", not(feature = "tmux_2_4")))] pub fn mode_table<S: Into<Cow<'a, str>>>(&mut self, mode_table: S) -> &mut Self { self.0.push_option(T_LOWERCASE_KEY, mode_table); self } /// `[-t key-table]` /// `[-T key-table]` #[cfg(feature = "tmux_0_8")] pub fn key_table<S: Into<Cow<'a, str>>>(&mut self, key_table: S) -> &mut Self { #[cfg(all(feature = "tmux_0_8", not(feature = "tmux_2_1")))] self.0.push_option(T_LOWERCASE_KEY, key_table); #[cfg(feature = "tmux_2_1")] self.0.push_option(T_UPPERCASE_KEY, key_table); self } pub fn output(&self) -> Result<TmuxOutput, Error> { self.0.output() } } impl<'a> From<TmuxCommand<'a>> for ListKeys<'a> { fn from(item: TmuxCommand<'a>) -> Self { Self(TmuxCommand { bin: item.bin, cmd: Some(Cow::Borrowed(LIST_KEYS)), ..Default::default() }) } } impl<'a> From<&TmuxCommand<'a>> for ListKeys<'a> { fn from(item: &TmuxCommand<'a>) -> Self { Self(TmuxCommand { bin: item.bin.clone(), cmd: Some(Cow::Borrowed(LIST_KEYS)), ..Default::default() }) } }
24.076923
91
0.526092
877a234bd8791e5ef5494ba135b15d78f75b4e19
30,392
#![allow(clippy::rc_buffer)] use { super::{ broadcast_utils::{self, ReceiveResults}, *, }, crate::{ broadcast_stage::broadcast_utils::UnfinishedSlotInfo, cluster_nodes::ClusterNodesCache, }, solana_entry::entry::Entry, solana_ledger::shred::{ ProcessShredsStats, Shred, Shredder, MAX_DATA_SHREDS_PER_FEC_BLOCK, SHRED_TICK_REFERENCE_MASK, }, solana_sdk::{ signature::Keypair, timing::{duration_as_us, AtomicInterval}, }, std::{sync::RwLock, time::Duration}, }; #[derive(Clone)] pub struct StandardBroadcastRun { process_shreds_stats: ProcessShredsStats, transmit_shreds_stats: Arc<Mutex<SlotBroadcastStats<TransmitShredsStats>>>, insert_shreds_stats: Arc<Mutex<SlotBroadcastStats<InsertShredsStats>>>, unfinished_slot: Option<UnfinishedSlotInfo>, current_slot_and_parent: Option<(u64, u64)>, slot_broadcast_start: Option<Instant>, shred_version: u16, last_datapoint_submit: Arc<AtomicInterval>, num_batches: usize, cluster_nodes_cache: Arc<ClusterNodesCache<BroadcastStage>>, } impl StandardBroadcastRun { pub(super) fn new(shred_version: u16) -> Self { let cluster_nodes_cache = Arc::new(ClusterNodesCache::<BroadcastStage>::new( CLUSTER_NODES_CACHE_NUM_EPOCH_CAP, CLUSTER_NODES_CACHE_TTL, )); Self { process_shreds_stats: ProcessShredsStats::default(), transmit_shreds_stats: Arc::default(), insert_shreds_stats: Arc::default(), unfinished_slot: None, current_slot_and_parent: None, slot_broadcast_start: None, shred_version, last_datapoint_submit: Arc::default(), num_batches: 0, cluster_nodes_cache, } } // If the current slot has changed, generates an empty shred indicating // last shred in the previous slot, along with coding shreds for the data // shreds buffered. fn finish_prev_slot( &mut self, keypair: &Keypair, max_ticks_in_slot: u8, stats: &mut ProcessShredsStats, ) -> Vec<Shred> { let (current_slot, _) = self.current_slot_and_parent.unwrap(); match self.unfinished_slot { None => Vec::default(), Some(ref state) if state.slot == current_slot => Vec::default(), Some(ref mut state) => { let parent_offset = state.slot - state.parent; let reference_tick = max_ticks_in_slot & SHRED_TICK_REFERENCE_MASK; let fec_set_index = Shredder::fec_set_index(state.next_shred_index, state.fec_set_offset); let mut shred = Shred::new_from_data( state.slot, state.next_shred_index, parent_offset as u16, None, // data true, // is_last_in_fec_set true, // is_last_in_slot reference_tick, self.shred_version, fec_set_index.unwrap(), ); Shredder::sign_shred(keypair, &mut shred); state.data_shreds_buffer.push(shred.clone()); let mut shreds = make_coding_shreds( keypair, &mut self.unfinished_slot, true, // is_last_in_slot stats, ); shreds.insert(0, shred); self.report_and_reset_stats(true); self.unfinished_slot = None; shreds } } } fn entries_to_data_shreds( &mut self, keypair: &Keypair, entries: &[Entry], blockstore: &Blockstore, reference_tick: u8, is_slot_end: bool, process_stats: &mut ProcessShredsStats, ) -> Vec<Shred> { let (slot, parent_slot) = self.current_slot_and_parent.unwrap(); let (next_shred_index, fec_set_offset) = match &self.unfinished_slot { Some(state) => (state.next_shred_index, state.fec_set_offset), None => match blockstore.meta(slot).unwrap() { Some(slot_meta) => { let shreds_consumed = slot_meta.consumed as u32; (shreds_consumed, shreds_consumed) } None => (0, 0), }, }; let (data_shreds, next_shred_index) = Shredder::new(slot, parent_slot, reference_tick, self.shred_version) .unwrap() .entries_to_data_shreds( keypair, entries, is_slot_end, next_shred_index, fec_set_offset, process_stats, ); let mut data_shreds_buffer = match &mut self.unfinished_slot { Some(state) => { assert_eq!(state.slot, slot); std::mem::take(&mut state.data_shreds_buffer) } None => Vec::default(), }; data_shreds_buffer.extend(data_shreds.clone()); self.unfinished_slot = Some(UnfinishedSlotInfo { next_shred_index, slot, parent: parent_slot, data_shreds_buffer, fec_set_offset, }); data_shreds } #[cfg(test)] fn test_process_receive_results( &mut self, keypair: &Keypair, cluster_info: &ClusterInfo, sock: &UdpSocket, blockstore: &Arc<Blockstore>, receive_results: ReceiveResults, bank_forks: &Arc<RwLock<BankForks>>, ) -> Result<()> { let (bsend, brecv) = channel(); let (ssend, srecv) = channel(); self.process_receive_results(keypair, blockstore, &ssend, &bsend, receive_results)?; let srecv = Arc::new(Mutex::new(srecv)); let brecv = Arc::new(Mutex::new(brecv)); //data let _ = self.transmit(&srecv, cluster_info, sock, bank_forks); let _ = self.record(&brecv, blockstore); //coding let _ = self.transmit(&srecv, cluster_info, sock, bank_forks); let _ = self.record(&brecv, blockstore); Ok(()) } fn process_receive_results( &mut self, keypair: &Keypair, blockstore: &Arc<Blockstore>, socket_sender: &Sender<(Arc<Vec<Shred>>, Option<BroadcastShredBatchInfo>)>, blockstore_sender: &Sender<(Arc<Vec<Shred>>, Option<BroadcastShredBatchInfo>)>, receive_results: ReceiveResults, ) -> Result<()> { let mut receive_elapsed = receive_results.time_elapsed; let num_entries = receive_results.entries.len(); let bank = receive_results.bank.clone(); let last_tick_height = receive_results.last_tick_height; inc_new_counter_info!("broadcast_service-entries_received", num_entries); let old_broadcast_start = self.slot_broadcast_start; let old_num_batches = self.num_batches; if self.current_slot_and_parent.is_none() || bank.slot() != self.current_slot_and_parent.unwrap().0 { self.slot_broadcast_start = Some(Instant::now()); self.num_batches = 0; let slot = bank.slot(); let parent_slot = bank.parent_slot(); self.current_slot_and_parent = Some((slot, parent_slot)); receive_elapsed = Duration::new(0, 0); } let mut process_stats = ProcessShredsStats::default(); let mut to_shreds_time = Measure::start("broadcast_to_shreds"); // 1) Check if slot was interrupted let prev_slot_shreds = self.finish_prev_slot(keypair, bank.ticks_per_slot() as u8, &mut process_stats); // 2) Convert entries to shreds and coding shreds let is_last_in_slot = last_tick_height == bank.max_tick_height(); let reference_tick = bank.tick_height() % bank.ticks_per_slot(); let data_shreds = self.entries_to_data_shreds( keypair, &receive_results.entries, blockstore, reference_tick as u8, is_last_in_slot, &mut process_stats, ); // Insert the first shred so blockstore stores that the leader started this block // This must be done before the blocks are sent out over the wire. if !data_shreds.is_empty() && data_shreds[0].index() == 0 { let first = vec![data_shreds[0].clone()]; blockstore .insert_shreds(first, None, true) .expect("Failed to insert shreds in blockstore"); } to_shreds_time.stop(); let mut get_leader_schedule_time = Measure::start("broadcast_get_leader_schedule"); // Broadcast the last shred of the interrupted slot if necessary if !prev_slot_shreds.is_empty() { let slot = prev_slot_shreds[0].slot(); let batch_info = Some(BroadcastShredBatchInfo { slot, num_expected_batches: Some(old_num_batches + 1), slot_start_ts: old_broadcast_start.expect( "Old broadcast start time for previous slot must exist if the previous slot was interrupted", ), was_interrupted: true, }); let shreds = Arc::new(prev_slot_shreds); debug_assert!(shreds.iter().all(|shred| shred.slot() == slot)); socket_sender.send((shreds.clone(), batch_info.clone()))?; blockstore_sender.send((shreds, batch_info))?; } // Increment by two batches, one for the data batch, one for the coding batch. self.num_batches += 2; let num_expected_batches = { if is_last_in_slot { Some(self.num_batches) } else { None } }; let batch_info = Some(BroadcastShredBatchInfo { slot: bank.slot(), num_expected_batches, slot_start_ts: self .slot_broadcast_start .expect("Start timestamp must exist for a slot if we're broadcasting the slot"), was_interrupted: false, }); get_leader_schedule_time.stop(); let mut coding_send_time = Measure::start("broadcast_coding_send"); // Send data shreds let data_shreds = Arc::new(data_shreds); debug_assert!(data_shreds.iter().all(|shred| shred.slot() == bank.slot())); socket_sender.send((data_shreds.clone(), batch_info.clone()))?; blockstore_sender.send((data_shreds, batch_info.clone()))?; // Create and send coding shreds let coding_shreds = make_coding_shreds( keypair, &mut self.unfinished_slot, is_last_in_slot, &mut process_stats, ); let coding_shreds = Arc::new(coding_shreds); debug_assert!(coding_shreds .iter() .all(|shred| shred.slot() == bank.slot())); socket_sender.send((coding_shreds.clone(), batch_info.clone()))?; blockstore_sender.send((coding_shreds, batch_info))?; coding_send_time.stop(); process_stats.shredding_elapsed = to_shreds_time.as_us(); process_stats.get_leader_schedule_elapsed = get_leader_schedule_time.as_us(); process_stats.receive_elapsed = duration_as_us(&receive_elapsed); process_stats.coding_send_elapsed = coding_send_time.as_us(); self.process_shreds_stats.update(&process_stats); if last_tick_height == bank.max_tick_height() { self.report_and_reset_stats(false); self.unfinished_slot = None; } Ok(()) } fn insert( &mut self, blockstore: &Arc<Blockstore>, shreds: Arc<Vec<Shred>>, broadcast_shred_batch_info: Option<BroadcastShredBatchInfo>, ) { // Insert shreds into blockstore let insert_shreds_start = Instant::now(); // The first shred is inserted synchronously let data_shreds = if !shreds.is_empty() && shreds[0].index() == 0 { shreds[1..].to_vec() } else { shreds.to_vec() }; blockstore .insert_shreds(data_shreds, None, true) .expect("Failed to insert shreds in blockstore"); let insert_shreds_elapsed = insert_shreds_start.elapsed(); let new_insert_shreds_stats = InsertShredsStats { insert_shreds_elapsed: duration_as_us(&insert_shreds_elapsed), num_shreds: shreds.len(), }; self.update_insertion_metrics(&new_insert_shreds_stats, &broadcast_shred_batch_info); } fn update_insertion_metrics( &mut self, new_insertion_shreds_stats: &InsertShredsStats, broadcast_shred_batch_info: &Option<BroadcastShredBatchInfo>, ) { let mut insert_shreds_stats = self.insert_shreds_stats.lock().unwrap(); insert_shreds_stats.update(new_insertion_shreds_stats, broadcast_shred_batch_info); } fn broadcast( &mut self, sock: &UdpSocket, cluster_info: &ClusterInfo, shreds: Arc<Vec<Shred>>, broadcast_shred_batch_info: Option<BroadcastShredBatchInfo>, bank_forks: &Arc<RwLock<BankForks>>, ) -> Result<()> { trace!("Broadcasting {:?} shreds", shreds.len()); let mut transmit_stats = TransmitShredsStats::default(); // Broadcast the shreds let mut transmit_time = Measure::start("broadcast_shreds"); broadcast_shreds( sock, &shreds, &self.cluster_nodes_cache, &self.last_datapoint_submit, &mut transmit_stats, cluster_info, bank_forks, cluster_info.socket_addr_space(), )?; transmit_time.stop(); transmit_stats.transmit_elapsed = transmit_time.as_us(); transmit_stats.num_shreds = shreds.len(); // Process metrics self.update_transmit_metrics(&transmit_stats, &broadcast_shred_batch_info); Ok(()) } fn update_transmit_metrics( &mut self, new_transmit_shreds_stats: &TransmitShredsStats, broadcast_shred_batch_info: &Option<BroadcastShredBatchInfo>, ) { let mut transmit_shreds_stats = self.transmit_shreds_stats.lock().unwrap(); transmit_shreds_stats.update(new_transmit_shreds_stats, broadcast_shred_batch_info); } fn report_and_reset_stats(&mut self, was_interrupted: bool) { let stats = &self.process_shreds_stats; let unfinished_slot = self.unfinished_slot.as_ref().unwrap(); if was_interrupted { datapoint_info!( "broadcast-process-shreds-interrupted-stats", ("slot", unfinished_slot.slot as i64, i64), ("shredding_time", stats.shredding_elapsed, i64), ("receive_time", stats.receive_elapsed, i64), ( "num_data_shreds", unfinished_slot.next_shred_index as i64, i64 ), ( "get_leader_schedule_time", stats.get_leader_schedule_elapsed, i64 ), ("serialize_shreds_time", stats.serialize_elapsed, i64), ("gen_data_time", stats.gen_data_elapsed, i64), ("gen_coding_time", stats.gen_coding_elapsed, i64), ("sign_coding_time", stats.sign_coding_elapsed, i64), ("coding_send_time", stats.coding_send_elapsed, i64), ); } else { datapoint_info!( "broadcast-process-shreds-stats", ("slot", unfinished_slot.slot as i64, i64), ("shredding_time", stats.shredding_elapsed, i64), ("receive_time", stats.receive_elapsed, i64), ( "num_data_shreds", unfinished_slot.next_shred_index as i64, i64 ), ( "slot_broadcast_time", self.slot_broadcast_start.unwrap().elapsed().as_micros() as i64, i64 ), ( "get_leader_schedule_time", stats.get_leader_schedule_elapsed, i64 ), ("serialize_shreds_time", stats.serialize_elapsed, i64), ("gen_data_time", stats.gen_data_elapsed, i64), ("gen_coding_time", stats.gen_coding_elapsed, i64), ("sign_coding_time", stats.sign_coding_elapsed, i64), ("coding_send_time", stats.coding_send_elapsed, i64), ); } self.process_shreds_stats.reset(); } } // Consumes data_shreds_buffer returning corresponding coding shreds. fn make_coding_shreds( keypair: &Keypair, unfinished_slot: &mut Option<UnfinishedSlotInfo>, is_slot_end: bool, stats: &mut ProcessShredsStats, ) -> Vec<Shred> { let data_shreds = match unfinished_slot { None => Vec::default(), Some(unfinished_slot) => { let size = unfinished_slot.data_shreds_buffer.len(); // Consume a multiple of 32, unless this is the slot end. let offset = if is_slot_end { 0 } else { size % MAX_DATA_SHREDS_PER_FEC_BLOCK as usize }; unfinished_slot .data_shreds_buffer .drain(0..size - offset) .collect() } }; Shredder::data_shreds_to_coding_shreds(keypair, &data_shreds, is_slot_end, stats).unwrap() } impl BroadcastRun for StandardBroadcastRun { fn run( &mut self, keypair: &Keypair, blockstore: &Arc<Blockstore>, receiver: &Receiver<WorkingBankEntry>, socket_sender: &Sender<(Arc<Vec<Shred>>, Option<BroadcastShredBatchInfo>)>, blockstore_sender: &Sender<(Arc<Vec<Shred>>, Option<BroadcastShredBatchInfo>)>, ) -> Result<()> { let receive_results = broadcast_utils::recv_slot_entries(receiver)?; // TODO: Confirm that last chunk of coding shreds // will not be lost or delayed for too long. self.process_receive_results( keypair, blockstore, socket_sender, blockstore_sender, receive_results, ) } fn transmit( &mut self, receiver: &Arc<Mutex<TransmitReceiver>>, cluster_info: &ClusterInfo, sock: &UdpSocket, bank_forks: &Arc<RwLock<BankForks>>, ) -> Result<()> { let (shreds, batch_info) = receiver.lock().unwrap().recv()?; self.broadcast(sock, cluster_info, shreds, batch_info, bank_forks) } fn record( &mut self, receiver: &Arc<Mutex<RecordReceiver>>, blockstore: &Arc<Blockstore>, ) -> Result<()> { let (shreds, slot_start_ts) = receiver.lock().unwrap().recv()?; self.insert(blockstore, shreds, slot_start_ts); Ok(()) } } #[cfg(test)] mod test { use { super::*, solana_entry::entry::create_ticks, solana_gossip::cluster_info::{ClusterInfo, Node}, solana_ledger::{ blockstore::Blockstore, genesis_utils::create_genesis_config, get_tmp_ledger_path, shred::max_ticks_per_n_shreds, }, solana_runtime::bank::Bank, solana_sdk::{ genesis_config::GenesisConfig, signature::{Keypair, Signer}, }, solana_streamer::socket::SocketAddrSpace, std::{ops::Deref, sync::Arc, time::Duration}, }; #[allow(clippy::type_complexity)] fn setup( num_shreds_per_slot: Slot, ) -> ( Arc<Blockstore>, GenesisConfig, Arc<ClusterInfo>, Arc<Bank>, Arc<Keypair>, UdpSocket, Arc<RwLock<BankForks>>, ) { // Setup let ledger_path = get_tmp_ledger_path!(); let blockstore = Arc::new( Blockstore::open(&ledger_path).expect("Expected to be able to open database ledger"), ); let leader_keypair = Arc::new(Keypair::new()); let leader_pubkey = leader_keypair.pubkey(); let leader_info = Node::new_localhost_with_pubkey(&leader_pubkey); let cluster_info = Arc::new(ClusterInfo::new( leader_info.info, Arc::new(Keypair::new()), SocketAddrSpace::Unspecified, )); let socket = UdpSocket::bind("0.0.0.0:0").unwrap(); let mut genesis_config = create_genesis_config(10_000).genesis_config; genesis_config.ticks_per_slot = max_ticks_per_n_shreds(num_shreds_per_slot, None) + 1; let bank = Bank::new_for_tests(&genesis_config); let bank_forks = Arc::new(RwLock::new(BankForks::new(bank))); let bank0 = bank_forks.read().unwrap().root_bank(); ( blockstore, genesis_config, cluster_info, bank0, leader_keypair, socket, bank_forks, ) } #[test] fn test_interrupted_slot_last_shred() { let keypair = Arc::new(Keypair::new()); let mut run = StandardBroadcastRun::new(0); // Set up the slot to be interrupted let next_shred_index = 10; let slot = 1; let parent = 0; run.unfinished_slot = Some(UnfinishedSlotInfo { next_shred_index, slot, parent, data_shreds_buffer: Vec::default(), fec_set_offset: next_shred_index, }); run.slot_broadcast_start = Some(Instant::now()); // Set up a slot to interrupt the old slot run.current_slot_and_parent = Some((4, 2)); // Slot 2 interrupted slot 1 let shreds = run.finish_prev_slot(&keypair, 0, &mut ProcessShredsStats::default()); let shred = shreds .get(0) .expect("Expected a shred that signals an interrupt"); // Validate the shred assert_eq!(shred.parent().unwrap(), parent); assert_eq!(shred.slot(), slot); assert_eq!(shred.index(), next_shred_index); assert!(shred.is_data()); assert!(shred.verify(&keypair.pubkey())); } #[test] fn test_slot_interrupt() { // Setup let num_shreds_per_slot = 2; let (blockstore, genesis_config, cluster_info, bank0, leader_keypair, socket, bank_forks) = setup(num_shreds_per_slot); // Insert 1 less than the number of ticks needed to finish the slot let ticks0 = create_ticks(genesis_config.ticks_per_slot - 1, 0, genesis_config.hash()); let receive_results = ReceiveResults { entries: ticks0.clone(), time_elapsed: Duration::new(3, 0), bank: bank0.clone(), last_tick_height: (ticks0.len() - 1) as u64, }; // Step 1: Make an incomplete transmission for slot 0 let mut standard_broadcast_run = StandardBroadcastRun::new(0); standard_broadcast_run .test_process_receive_results( &leader_keypair, &cluster_info, &socket, &blockstore, receive_results, &bank_forks, ) .unwrap(); let unfinished_slot = standard_broadcast_run.unfinished_slot.as_ref().unwrap(); assert_eq!(unfinished_slot.next_shred_index as u64, num_shreds_per_slot); assert_eq!(unfinished_slot.slot, 0); assert_eq!(unfinished_slot.parent, 0); // Make sure the slot is not complete assert!(!blockstore.is_full(0)); // Modify the stats, should reset later standard_broadcast_run.process_shreds_stats.receive_elapsed = 10; // Broadcast stats should exist, and 2 batches should have been sent, // one for data, one for coding assert_eq!( standard_broadcast_run .transmit_shreds_stats .lock() .unwrap() .get(unfinished_slot.slot) .unwrap() .num_batches(), 2 ); assert_eq!( standard_broadcast_run .insert_shreds_stats .lock() .unwrap() .get(unfinished_slot.slot) .unwrap() .num_batches(), 2 ); // Try to fetch ticks from blockstore, nothing should break assert_eq!(blockstore.get_slot_entries(0, 0).unwrap(), ticks0); assert_eq!( blockstore.get_slot_entries(0, num_shreds_per_slot).unwrap(), vec![], ); // Step 2: Make a transmission for another bank that interrupts the transmission for // slot 0 let bank2 = Arc::new(Bank::new_from_parent(&bank0, &leader_keypair.pubkey(), 2)); let interrupted_slot = unfinished_slot.slot; // Interrupting the slot should cause the unfinished_slot and stats to reset let num_shreds = 1; assert!(num_shreds < num_shreds_per_slot); let ticks1 = create_ticks( max_ticks_per_n_shreds(num_shreds, None), 0, genesis_config.hash(), ); let receive_results = ReceiveResults { entries: ticks1.clone(), time_elapsed: Duration::new(2, 0), bank: bank2, last_tick_height: (ticks1.len() - 1) as u64, }; standard_broadcast_run .test_process_receive_results( &leader_keypair, &cluster_info, &socket, &blockstore, receive_results, &bank_forks, ) .unwrap(); let unfinished_slot = standard_broadcast_run.unfinished_slot.as_ref().unwrap(); // The shred index should have reset to 0, which makes it possible for the // index < the previous shred index for slot 0 assert_eq!(unfinished_slot.next_shred_index as u64, num_shreds); assert_eq!(unfinished_slot.slot, 2); assert_eq!(unfinished_slot.parent, 0); // Check that the stats were reset as well assert_eq!( standard_broadcast_run.process_shreds_stats.receive_elapsed, 0 ); // Broadcast stats for interrupted slot should be cleared assert!(standard_broadcast_run .transmit_shreds_stats .lock() .unwrap() .get(interrupted_slot) .is_none()); assert!(standard_broadcast_run .insert_shreds_stats .lock() .unwrap() .get(interrupted_slot) .is_none()); // Try to fetch the incomplete ticks from blockstore, should succeed assert_eq!(blockstore.get_slot_entries(0, 0).unwrap(), ticks0); assert_eq!( blockstore.get_slot_entries(0, num_shreds_per_slot).unwrap(), vec![], ); } #[test] fn test_buffer_data_shreds() { let num_shreds_per_slot = 2; let (blockstore, genesis_config, _cluster_info, bank, leader_keypair, _socket, _bank_forks) = setup(num_shreds_per_slot); let (bsend, brecv) = channel(); let (ssend, _srecv) = channel(); let mut last_tick_height = 0; let mut standard_broadcast_run = StandardBroadcastRun::new(0); let mut process_ticks = |num_ticks| { let ticks = create_ticks(num_ticks, 0, genesis_config.hash()); last_tick_height += (ticks.len() - 1) as u64; let receive_results = ReceiveResults { entries: ticks, time_elapsed: Duration::new(1, 0), bank: bank.clone(), last_tick_height, }; standard_broadcast_run .process_receive_results( &leader_keypair, &blockstore, &ssend, &bsend, receive_results, ) .unwrap(); }; for i in 0..3 { process_ticks((i + 1) * 100); } let mut shreds = Vec::<Shred>::new(); while let Ok((recv_shreds, _)) = brecv.recv_timeout(Duration::from_secs(1)) { shreds.extend(recv_shreds.deref().clone()); } assert!(shreds.len() < 32, "shreds.len(): {}", shreds.len()); assert!(shreds.iter().all(|shred| shred.is_data())); process_ticks(75); while let Ok((recv_shreds, _)) = brecv.recv_timeout(Duration::from_secs(1)) { shreds.extend(recv_shreds.deref().clone()); } assert!(shreds.len() > 64, "shreds.len(): {}", shreds.len()); let num_coding_shreds = shreds.iter().filter(|shred| shred.is_code()).count(); assert_eq!( num_coding_shreds, 32, "num coding shreds: {}", num_coding_shreds ); } #[test] fn test_slot_finish() { // Setup let num_shreds_per_slot = 2; let (blockstore, genesis_config, cluster_info, bank0, leader_keypair, socket, bank_forks) = setup(num_shreds_per_slot); // Insert complete slot of ticks needed to finish the slot let ticks = create_ticks(genesis_config.ticks_per_slot, 0, genesis_config.hash()); let receive_results = ReceiveResults { entries: ticks.clone(), time_elapsed: Duration::new(3, 0), bank: bank0, last_tick_height: ticks.len() as u64, }; let mut standard_broadcast_run = StandardBroadcastRun::new(0); standard_broadcast_run .test_process_receive_results( &leader_keypair, &cluster_info, &socket, &blockstore, receive_results, &bank_forks, ) .unwrap(); assert!(standard_broadcast_run.unfinished_slot.is_none()) } }
37.290798
101
0.57706
e9b6ba0117cf4a1a2155aa34750781a0e45162b0
1,680
pub use self::context::Context; pub use self::module::{Module, ModuleBuilder}; pub use self::function::{Function, FunctionLabel, FunctionBuilder}; pub use self::builder::{Builder, PositionedBuilder}; pub use self::block::{BasicBlock, Label}; pub use self::value::Value; pub use self::phi::Phi; pub use self::alloca::Alloca; pub use self::constant::Constant; pub use self::global::Global; pub use self::ty::{Type, FunctionType, IntegerType, PointerType, ArrayType}; pub use self::target::{Target, TargetMachine, DataLayout}; pub use self::pass_manager::{FunctionPassManager, InitializedFunctionPassManager}; pub use llvm_sys::{LLVMIntPredicate, LLVMRealPredicate}; pub mod init; pub mod context; pub mod module; pub mod function; pub mod block; pub mod builder; pub mod value; pub mod phi; pub mod alloca; pub mod constant; pub mod ty; pub mod target; pub mod pass_manager; pub mod global; // // TODO: Error Checking // This is currently a safety hole. // // TODO: Reduce the number of lifetimes. // It isn't completely clear that this is possible, but this is a first attempt. // // TODO: Docs // // TODO: See what safety guarentees LLVM actually needs. // The official LLVM docs aren't very clear on, e.g., when different contexts/modules/function/builders // can be mixed, or what things can outlive other things. // // TODO: Consider wrapping the C++ API in another way. // The official wrapper is useful, since it requires no effort and is maintained by LLVM. However, // it has a number of annoying issues. For example, given the similarity between LLVM's Twine and Rust's // &str, there should be no reason to use CStr. // // TODO: Missing functionality //
32.307692
106
0.741071
3384b02d57e970f201c34155a16539dfb101140d
1,141
use std::{thread,time}; extern crate rand; use std::sync::{Arc,Mutex}; #[macro_use] extern crate lazy_static; lazy_static! { static ref NEURAL_NET_WEIGHTS: Vec<Arc<Mutex<Vec<f64>>>> = { let mut nn = Vec::with_capacity(10000); for _ in 0..10000 { let mut mm = Vec::with_capacity(100); for _ in 0..100 { mm.push(rand::random::<f64>()); } let mm = Arc::new(Mutex::new(mm)); nn.push(mm); } nn }; } fn train() { let t = time::Duration::from_millis(100); loop { for _ in 0..100 { let update_position = rand::random::<u64>() % 1000000; let update_column = update_position / 10000; let update_row = update_position % 100; let update_value = rand::random::<f64>(); let mut update_column = NEURAL_NET_WEIGHTS[update_column as usize].lock().unwrap(); update_column[update_row as usize] = update_value; } thread::sleep(t); } } fn main() { let t = time::Duration::from_millis(1000); for _ in 0..500 { thread::spawn(train); } loop { thread::sleep(t); } }
24.276596
92
0.567046
eb161d1b09d9325a8e4cfb9ff722921074d9835b
3,670
use super::super::bus::rcc; use super::super::generic::platform::stm32f3x; use super::super::generic::traits::primitive_extensions; use super::super::registerblocks::dma::DMA; pub mod dma { use super::primitive_extensions::BitOps; use super::rcc; use super::stm32f3x::adresses; use super::DMA; pub struct DmaDevice { device: DMA, // offset_adder: u32, } impl DmaDevice { pub unsafe fn new(channel: u32) -> DmaDevice { rcc::rcc::activate_dma1_bus_clock(); DmaDevice { device: DMA::new(adresses::dma::DMA1, channel), // offset_adder: 0x14 * (channel - 1) } } pub fn enable(self) -> DmaDevice { self.enable_dma_channel(); self } pub fn mem_size(self, width: u32) -> DmaDevice { self.set_mem_register_width(width); self } pub fn periph_size(self, width: u32) -> DmaDevice { self.set_peripherial_register_width(width); self } pub fn disable(self) -> DmaDevice { self.disable_dma_channel(); self } pub fn peripherial_is_source(self) -> DmaDevice { self.read_from_peripherial(); self } pub fn memory_is_source(self) -> DmaDevice { self.read_from_memory(); self } pub fn mem_target_addr(self, mem_adress: u32) -> DmaDevice { self.set_memory_adress(mem_adress); self } pub fn peripherial_target_addr(self, peripherial_adress: u32) -> DmaDevice { self.set_peripherial_adress(peripherial_adress); self } pub fn transfer_amount(self, amount: u16) -> DmaDevice { self.set_number_of_bytes_to_process(amount); self } fn set_mem_register_width(&self, width: u32) { let bit_pattern = match width { 8 => 0b00, 16 => 0b01, 32 => 0b10, _ => 0b00, }; self.device.dynamic.ccrx.set_bit(bit_pattern << 10); } fn set_peripherial_register_width(&self, width: u32) { let bit_pattern = match width { 8 => 0b00, 16 => 0b01, 32 => 0b10, _ => 0b00, }; self.device.dynamic.ccrx.set_bit(bit_pattern << 8); } fn enable_dma_channel(&self) { self.device.dynamic.ccrx.set_bit(0b1); } fn disable_dma_channel(&self) { self.device.dynamic.ccrx.clear_bit(0b1); } fn read_from_peripherial(&self) { self.device.dynamic.ccrx.clear_bit(0b1 << 4); } fn read_from_memory(&self) { self.device.dynamic.ccrx.set_bit(0b1 << 4); // when reading from memory, increment ptr also! (MINC) self.device.dynamic.ccrx.set_bit(0b1 << 7); } // addr to read from fn set_memory_adress(&self, mem_adress: u32) { self.device.dynamic.cmarx.replace_whole_register(mem_adress); } // destination fn set_peripherial_adress(&self, periph_adress: u32) { self.device .dynamic .cparx .replace_whole_register(periph_adress); } fn set_number_of_bytes_to_process(&self, num_of_bytes: u16) { self.device .dynamic .cndtrx .write_whole_register(num_of_bytes as u32); } } }
28.015267
84
0.529155
64a21135232a34f2902f58d762b2df4bbe74e748
10,829
#![crate_name = "uu_unexpand"] /* * This file is part of the uutils coreutils package. * * (c) Virgile Andreani <virgile.andreani@anbuco.fr> * (c) kwantam <kwantam@gmail.com> * 20150428 updated to work with both UTF-8 and non-UTF-8 encodings * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate unicode_width; #[macro_use] extern crate uucore; use std::fs::File; use std::io::{stdin, stdout, BufRead, BufReader, BufWriter, Read, Stdout, Write}; use std::str::from_utf8; use unicode_width::UnicodeWidthChar; static NAME: &str = "unexpand"; static VERSION: &str = env!("CARGO_PKG_VERSION"); const DEFAULT_TABSTOP: usize = 8; fn tabstops_parse(s: String) -> Vec<usize> { let words = s.split(',').collect::<Vec<&str>>(); let nums = words .into_iter() .map(|sn| { sn.parse() .unwrap_or_else(|_| crash!(1, "{}\n", "tab size contains invalid character(s)")) }) .collect::<Vec<usize>>(); if nums.iter().any(|&n| n == 0) { crash!(1, "{}\n", "tab size cannot be 0"); } if let (false, _) = nums .iter() .fold((true, 0), |(acc, last), &n| (acc && last <= n, n)) { crash!(1, "{}\n", "tab sizes must be ascending"); } nums } struct Options { files: Vec<String>, tabstops: Vec<usize>, aflag: bool, uflag: bool, } impl Options { fn new(matches: getopts::Matches) -> Options { let tabstops = match matches.opt_str("t") { None => vec![DEFAULT_TABSTOP], Some(s) => tabstops_parse(s), }; let aflag = (matches.opt_present("all") || matches.opt_present("tabs")) && !matches.opt_present("first-only"); let uflag = !matches.opt_present("U"); let files = if matches.free.is_empty() { vec!["-".to_owned()] } else { matches.free }; Options { files, tabstops, aflag, uflag, } } } pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag( "a", "all", "convert all blanks, instead of just initial blanks", ); opts.optflag( "", "first-only", "convert only leading sequences of blanks (overrides -a)", ); opts.optopt( "t", "tabs", "have tabs N characters apart instead of 8 (enables -a)", "N", ); opts.optopt( "t", "tabs", "use comma separated LIST of tab positions (enables -a)", "LIST", ); opts.optflag( "U", "no-utf8", "interpret input file as 8-bit ASCII rather than UTF-8", ); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => crash!(1, "{}", f), }; if matches.opt_present("help") { println!("{} {}\n", NAME, VERSION); println!("Usage: {} [OPTION]... [FILE]...\n", NAME); println!( "{}", opts.usage( "Convert blanks in each FILE to tabs, writing to standard output.\n\ With no FILE, or when FILE is -, read standard input." ) ); return 0; } if matches.opt_present("V") { println!("{} {}", NAME, VERSION); return 0; } unexpand(Options::new(matches)); 0 } fn open(path: String) -> BufReader<Box<dyn Read + 'static>> { let file_buf; if path == "-" { BufReader::new(Box::new(stdin()) as Box<dyn Read>) } else { file_buf = match File::open(&path[..]) { Ok(a) => a, Err(e) => crash!(1, "{}: {}", &path[..], e), }; BufReader::new(Box::new(file_buf) as Box<dyn Read>) } } fn next_tabstop(tabstops: &[usize], col: usize) -> Option<usize> { if tabstops.len() == 1 { Some(tabstops[0] - col % tabstops[0]) } else { // find next larger tab match tabstops.iter().find(|&&t| t > col) { Some(t) => Some(t - col), None => None, // if there isn't one in the list, tab becomes a single space } } } fn write_tabs( output: &mut BufWriter<Stdout>, tabstops: &[usize], mut scol: usize, col: usize, prevtab: bool, init: bool, amode: bool, ) { // This conditional establishes the following: // We never turn a single space before a non-blank into // a tab, unless it's at the start of the line. let ai = init || amode; if (ai && !prevtab && col > scol + 1) || (col > scol && (init || ai && prevtab)) { while let Some(nts) = next_tabstop(tabstops, scol) { if col < scol + nts { break; } safe_unwrap!(output.write_all(b"\t")); scol += nts; } } while col > scol { safe_unwrap!(output.write_all(b" ")); scol += 1; } } #[derive(PartialEq, Eq, Debug)] enum CharType { Backspace, Space, Tab, Other, } fn next_char_info(uflag: bool, buf: &[u8], byte: usize) -> (CharType, usize, usize) { let (ctype, cwidth, nbytes) = if uflag { let nbytes = char::from(buf[byte]).len_utf8(); if byte + nbytes > buf.len() { // make sure we don't overrun the buffer because of invalid UTF-8 (CharType::Other, 1, 1) } else if let Ok(t) = from_utf8(&buf[byte..byte + nbytes]) { // Now that we think it's UTF-8, figure out what kind of char it is match t.chars().next() { Some(' ') => (CharType::Space, 0, 1), Some('\t') => (CharType::Tab, 0, 1), Some('\x08') => (CharType::Backspace, 0, 1), Some(c) => ( CharType::Other, UnicodeWidthChar::width(c).unwrap_or(0), nbytes, ), None => { // invalid char snuck past the utf8_validation_iterator somehow??? (CharType::Other, 1, 1) } } } else { // otherwise, it's not valid (CharType::Other, 1, 1) // implicit assumption: non-UTF8 char has display width 1 } } else { ( match buf[byte] { // always take exactly 1 byte in strict ASCII mode 0x20 => CharType::Space, 0x09 => CharType::Tab, 0x08 => CharType::Backspace, _ => CharType::Other, }, 1, 1, ) }; (ctype, cwidth, nbytes) } fn unexpand(options: Options) { let mut output = BufWriter::new(stdout()); let ts = &options.tabstops[..]; let mut buf = Vec::new(); let lastcol = if ts.len() > 1 { *ts.last().unwrap() } else { 0 }; for file in options.files.into_iter() { let mut fh = open(file); while match fh.read_until(b'\n', &mut buf) { Ok(s) => s > 0, Err(_) => !buf.is_empty(), } { let mut byte = 0; // offset into the buffer let mut col = 0; // the current column let mut scol = 0; // the start col for the current span, i.e., the already-printed width let mut init = true; // are we at the start of the line? let mut pctype = CharType::Other; while byte < buf.len() { // when we have a finite number of columns, never convert past the last column if lastcol > 0 && col >= lastcol { write_tabs( &mut output, ts, scol, col, pctype == CharType::Tab, init, true, ); safe_unwrap!(output.write_all(&buf[byte..])); scol = col; break; } // figure out how big the next char is, if it's UTF-8 let (ctype, cwidth, nbytes) = next_char_info(options.uflag, &buf, byte); // now figure out how many columns this char takes up, and maybe print it let tabs_buffered = init || options.aflag; match ctype { CharType::Space | CharType::Tab => { // compute next col, but only write space or tab chars if not buffering col += if ctype == CharType::Space { 1 } else { next_tabstop(ts, col).unwrap_or(1) }; if !tabs_buffered { safe_unwrap!(output.write_all(&buf[byte..byte + nbytes])); scol = col; // now printed up to this column } } CharType::Other | CharType::Backspace => { // always write_tabs( &mut output, ts, scol, col, pctype == CharType::Tab, init, options.aflag, ); init = false; // no longer at the start of a line col = if ctype == CharType::Other { // use computed width col + cwidth } else if col > 0 { // Backspace case, but only if col > 0 col - 1 } else { 0 }; safe_unwrap!(output.write_all(&buf[byte..byte + nbytes])); scol = col; // we've now printed up to this column } } byte += nbytes; // move on to next char pctype = ctype; // save the previous type } // write out anything remaining write_tabs( &mut output, ts, scol, col, pctype == CharType::Tab, init, true, ); safe_unwrap!(output.flush()); buf.truncate(0); // clear out the buffer } } crash_if_err!(1, output.flush()) }
30.333333
100
0.462185
6af5649119431ee2ea3679404dd2f1ba96c71bbf
83,917
// Assorted public API tests. use std::sync::Arc; use std::sync::Mutex; use std::sync::atomic::{AtomicUsize, Ordering}; use std::mem; use std::fmt; use std::env; use std::error::Error; use std::io::{self, Write, Read}; use rustls; use rustls::{ClientConfig, ClientSession, ResolvesClientCert}; use rustls::{ServerConfig, ServerSession, ResolvesServerCert}; use rustls::Session; use rustls::{Stream, StreamOwned}; use rustls::{ProtocolVersion, SignatureScheme, CipherSuite}; use rustls::TLSError; use rustls::sign; use rustls::{ALL_CIPHERSUITES, SupportedCipherSuite}; use rustls::KeyLog; use rustls::ClientHello; #[cfg(feature = "quic")] use rustls::quic::{self, QuicExt, ClientQuicExt, ServerQuicExt}; #[cfg(feature = "dangerous_configuration")] use rustls::ClientCertVerified; use webpki; #[allow(dead_code)] mod common; use crate::common::*; fn alpn_test(server_protos: Vec<Vec<u8>>, client_protos: Vec<Vec<u8>>, agreed: Option<&[u8]>) { let mut client_config = make_client_config(KeyType::RSA); let mut server_config = make_server_config(KeyType::RSA); client_config.alpn_protocols = client_protos; server_config.alpn_protocols = server_protos; let server_config = Arc::new(server_config); for client_config in AllClientVersions::new(client_config) { let (mut client, mut server) = make_pair_for_arc_configs(&Arc::new(client_config), &server_config); assert_eq!(client.get_alpn_protocol(), None); assert_eq!(server.get_alpn_protocol(), None); do_handshake(&mut client, &mut server); assert_eq!(client.get_alpn_protocol(), agreed); assert_eq!(server.get_alpn_protocol(), agreed); } } #[test] fn alpn() { // no support alpn_test(vec![], vec![], None); // server support alpn_test(vec![b"server-proto".to_vec()], vec![], None); // client support alpn_test(vec![], vec![b"client-proto".to_vec()], None); // no overlap alpn_test(vec![b"server-proto".to_vec()], vec![b"client-proto".to_vec()], None); // server chooses preference alpn_test(vec![b"server-proto".to_vec(), b"client-proto".to_vec()], vec![b"client-proto".to_vec(), b"server-proto".to_vec()], Some(b"server-proto")); // case sensitive alpn_test(vec![b"PROTO".to_vec()], vec![b"proto".to_vec()], None); } fn version_test(client_versions: Vec<ProtocolVersion>, server_versions: Vec<ProtocolVersion>, result: Option<ProtocolVersion>) { let mut client_config = make_client_config(KeyType::RSA); let mut server_config = make_server_config(KeyType::RSA); println!("version {:?} {:?} -> {:?}", client_versions, server_versions, result); if !client_versions.is_empty() { client_config.versions = client_versions; } if !server_versions.is_empty() { server_config.versions = server_versions; } let (mut client, mut server) = make_pair_for_configs(client_config, server_config); assert_eq!(client.get_protocol_version(), None); assert_eq!(server.get_protocol_version(), None); if result.is_none() { let err = do_handshake_until_error(&mut client, &mut server); assert_eq!(err.is_err(), true); } else { do_handshake(&mut client, &mut server); assert_eq!(client.get_protocol_version(), result); assert_eq!(server.get_protocol_version(), result); } } #[test] fn versions() { // default -> 1.3 version_test(vec![], vec![], Some(ProtocolVersion::TLSv1_3)); // client default, server 1.2 -> 1.2 version_test(vec![], vec![ProtocolVersion::TLSv1_2], Some(ProtocolVersion::TLSv1_2)); // client 1.2, server default -> 1.2 version_test(vec![ProtocolVersion::TLSv1_2], vec![], Some(ProtocolVersion::TLSv1_2)); // client 1.2, server 1.3 -> fail version_test(vec![ProtocolVersion::TLSv1_2], vec![ProtocolVersion::TLSv1_3], None); // client 1.3, server 1.2 -> fail version_test(vec![ProtocolVersion::TLSv1_3], vec![ProtocolVersion::TLSv1_2], None); // client 1.3, server 1.2+1.3 -> 1.3 version_test(vec![ProtocolVersion::TLSv1_3], vec![ProtocolVersion::TLSv1_2, ProtocolVersion::TLSv1_3], Some(ProtocolVersion::TLSv1_3)); // client 1.2+1.3, server 1.2 -> 1.2 version_test(vec![ProtocolVersion::TLSv1_3, ProtocolVersion::TLSv1_2], vec![ProtocolVersion::TLSv1_2], Some(ProtocolVersion::TLSv1_2)); } fn check_read(reader: &mut dyn io::Read, bytes: &[u8]) { let mut buf = Vec::new(); assert_eq!(bytes.len(), reader.read_to_end(&mut buf).unwrap()); assert_eq!(bytes.to_vec(), buf); } #[test] fn buffered_client_data_sent() { let server_config = Arc::new(make_server_config(KeyType::RSA)); for client_config in AllClientVersions::new(make_client_config(KeyType::RSA)) { let (mut client, mut server) = make_pair_for_arc_configs(&Arc::new(client_config), &server_config); assert_eq!(5, client.write(b"hello").unwrap()); do_handshake(&mut client, &mut server); transfer(&mut client, &mut server); server.process_new_packets().unwrap(); check_read(&mut server, b"hello"); } } #[test] fn buffered_server_data_sent() { let server_config = Arc::new(make_server_config(KeyType::RSA)); for client_config in AllClientVersions::new(make_client_config(KeyType::RSA)) { let (mut client, mut server) = make_pair_for_arc_configs(&Arc::new(client_config), &server_config); assert_eq!(5, server.write(b"hello").unwrap()); do_handshake(&mut client, &mut server); transfer(&mut server, &mut client); client.process_new_packets().unwrap(); check_read(&mut client, b"hello"); } } #[test] fn buffered_both_data_sent() { let server_config = Arc::new(make_server_config(KeyType::RSA)); for client_config in AllClientVersions::new(make_client_config(KeyType::RSA)) { let (mut client, mut server) = make_pair_for_arc_configs(&Arc::new(client_config), &server_config); assert_eq!(12, server.write(b"from-server!").unwrap()); assert_eq!(12, client.write(b"from-client!").unwrap()); do_handshake(&mut client, &mut server); transfer(&mut server, &mut client); client.process_new_packets().unwrap(); transfer(&mut client, &mut server); server.process_new_packets().unwrap(); check_read(&mut client, b"from-server!"); check_read(&mut server, b"from-client!"); } } #[test] fn client_can_get_server_cert() { for kt in ALL_KEY_TYPES.iter() { for client_config in AllClientVersions::new(make_client_config(*kt)) { let (mut client, mut server) = make_pair_for_configs(client_config, make_server_config(*kt)); do_handshake(&mut client, &mut server); let certs = client.get_peer_certificates(); assert_eq!(certs, Some(kt.get_chain())); } } } #[test] fn server_can_get_client_cert() { for kt in ALL_KEY_TYPES.iter() { let mut client_config = make_client_config(*kt); client_config.set_single_client_cert(kt.get_chain(), kt.get_key()) .unwrap(); let server_config = Arc::new(make_server_config_with_mandatory_client_auth(*kt)); for client_config in AllClientVersions::new(client_config) { let (mut client, mut server) = make_pair_for_arc_configs(&Arc::new(client_config), &server_config); do_handshake(&mut client, &mut server); let certs = server.get_peer_certificates(); assert_eq!(certs, Some(kt.get_chain())); } } } fn check_read_and_close(reader: &mut dyn io::Read, expect: &[u8]) { let mut buf = Vec::new(); buf.resize(expect.len(), 0u8); assert_eq!(expect.len(), reader.read(&mut buf).unwrap()); assert_eq!(expect.to_vec(), buf); let err = reader.read(&mut buf); assert!(err.is_err()); assert_eq!(err.err().unwrap().kind(), io::ErrorKind::ConnectionAborted); } #[test] fn server_close_notify() { let kt = KeyType::RSA; let mut client_config = make_client_config(kt); client_config.set_single_client_cert(kt.get_chain(), kt.get_key()) .unwrap(); let server_config = Arc::new(make_server_config_with_mandatory_client_auth(kt)); for client_config in AllClientVersions::new(client_config) { let (mut client, mut server) = make_pair_for_arc_configs(&Arc::new(client_config), &server_config); do_handshake(&mut client, &mut server); // check that alerts don't overtake appdata assert_eq!(12, server.write(b"from-server!").unwrap()); assert_eq!(12, client.write(b"from-client!").unwrap()); server.send_close_notify(); transfer(&mut server, &mut client); client.process_new_packets().unwrap(); check_read_and_close(&mut client, b"from-server!"); transfer(&mut client, &mut server); server.process_new_packets().unwrap(); check_read(&mut server, b"from-client!"); } } #[test] fn client_close_notify() { let kt = KeyType::RSA; let mut client_config = make_client_config(kt); client_config.set_single_client_cert(kt.get_chain(), kt.get_key()) .unwrap(); let server_config = Arc::new(make_server_config_with_mandatory_client_auth(kt)); for client_config in AllClientVersions::new(client_config) { let (mut client, mut server) = make_pair_for_arc_configs(&Arc::new(client_config), &server_config); do_handshake(&mut client, &mut server); // check that alerts don't overtake appdata assert_eq!(12, server.write(b"from-server!").unwrap()); assert_eq!(12, client.write(b"from-client!").unwrap()); client.send_close_notify(); transfer(&mut client, &mut server); server.process_new_packets().unwrap(); check_read_and_close(&mut server, b"from-client!"); transfer(&mut server, &mut client); client.process_new_packets().unwrap(); check_read(&mut client, b"from-server!"); } } #[derive(Default)] struct ServerCheckCertResolve { expected_sni: Option<String>, expected_sigalgs: Option<Vec<SignatureScheme>>, expected_alpn: Option<Vec<Vec<u8>>>, } impl ResolvesServerCert for ServerCheckCertResolve { fn resolve(&self, client_hello: ClientHello) -> Option<sign::CertifiedKey> { if client_hello.sigschemes().len() == 0 { panic!("no signature schemes shared by client"); } if let Some(expected_sni) = &self.expected_sni { let sni: &str = client_hello.server_name().expect("sni unexpectedly absent").into(); assert_eq!(expected_sni, sni); } if let Some(expected_sigalgs) = &self.expected_sigalgs { if expected_sigalgs != &client_hello.sigschemes() { panic!("unexpected signature schemes (wanted {:?} got {:?})", self.expected_sigalgs, client_hello.sigschemes()); } } if let Some(expected_alpn) = &self.expected_alpn { let alpn = client_hello.alpn().expect("alpn unexpectedly absent"); assert_eq!(alpn.len(), expected_alpn.len()); for (got, wanted) in alpn.iter().zip(expected_alpn.iter()) { assert_eq!(got, &wanted.as_slice()); } } None } } #[test] fn server_cert_resolve_with_sni() { for kt in ALL_KEY_TYPES.iter() { let client_config = make_client_config(*kt); let mut server_config = make_server_config(*kt); server_config.cert_resolver = Arc::new(ServerCheckCertResolve { expected_sni: Some("the-value-from-sni".into()), ..Default::default() }); let mut client = ClientSession::new(&Arc::new(client_config), dns_name("the-value-from-sni")); let mut server = ServerSession::new(&Arc::new(server_config)); let err = do_handshake_until_error(&mut client, &mut server); assert_eq!(err.is_err(), true); } } #[test] fn server_cert_resolve_with_alpn() { for kt in ALL_KEY_TYPES.iter() { let mut client_config = make_client_config(*kt); client_config.alpn_protocols = vec!["foo".into(), "bar".into()]; let mut server_config = make_server_config(*kt); server_config.cert_resolver = Arc::new(ServerCheckCertResolve { expected_alpn: Some(vec![ b"foo".to_vec(), b"bar".to_vec() ]), ..Default::default() }); let mut client = ClientSession::new(&Arc::new(client_config), dns_name("sni-value")); let mut server = ServerSession::new(&Arc::new(server_config)); let err = do_handshake_until_error(&mut client, &mut server); assert_eq!(err.is_err(), true); } } fn check_sigalgs_reduced_by_ciphersuite(kt: KeyType, suite: CipherSuite, expected_sigalgs: Vec<SignatureScheme>) { let mut client_config = make_client_config(kt); client_config.ciphersuites = vec![ find_suite(suite) ]; let mut server_config = make_server_config(kt); server_config.cert_resolver = Arc::new(ServerCheckCertResolve { expected_sigalgs: Some(expected_sigalgs), ..Default::default() }); let mut client = ClientSession::new(&Arc::new(client_config), dns_name("localhost")); let mut server = ServerSession::new(&Arc::new(server_config)); let err = do_handshake_until_error(&mut client, &mut server); assert_eq!(err.is_err(), true); } #[test] fn server_cert_resolve_reduces_sigalgs_for_rsa_ciphersuite() { check_sigalgs_reduced_by_ciphersuite( KeyType::RSA, CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, vec![ SignatureScheme::RSA_PSS_SHA512, SignatureScheme::RSA_PSS_SHA384, SignatureScheme::RSA_PSS_SHA256, SignatureScheme::RSA_PKCS1_SHA512, SignatureScheme::RSA_PKCS1_SHA384, SignatureScheme::RSA_PKCS1_SHA256, ] ); } #[test] fn server_cert_resolve_reduces_sigalgs_for_ecdsa_ciphersuite() { check_sigalgs_reduced_by_ciphersuite( KeyType::ECDSA, CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, vec![ SignatureScheme::ECDSA_NISTP384_SHA384, SignatureScheme::ECDSA_NISTP256_SHA256, ] ); } struct ServerCheckNoSNI {} impl ResolvesServerCert for ServerCheckNoSNI { fn resolve(&self, client_hello: ClientHello) -> Option<sign::CertifiedKey> { assert!(client_hello.server_name().is_none()); None } } #[test] fn client_with_sni_disabled_does_not_send_sni() { for kt in ALL_KEY_TYPES.iter() { let mut client_config = make_client_config(*kt); client_config.enable_sni = false; let mut server_config = make_server_config(*kt); server_config.cert_resolver = Arc::new(ServerCheckNoSNI {}); let server_config = Arc::new(server_config); for client_config in AllClientVersions::new(client_config) { let mut client = ClientSession::new(&Arc::new(client_config), dns_name("value-not-sent")); let mut server = ServerSession::new(&server_config); let err = do_handshake_until_error(&mut client, &mut server); assert_eq!(err.is_err(), true); } } } #[test] fn client_checks_server_certificate_with_given_name() { for kt in ALL_KEY_TYPES.iter() { let client_config = make_client_config(*kt); let server_config = Arc::new(make_server_config(*kt)); for client_config in AllClientVersions::new(client_config) { let mut client = ClientSession::new(&Arc::new(client_config), dns_name("not-the-right-hostname.com")); let mut server = ServerSession::new(&server_config); let err = do_handshake_until_error(&mut client, &mut server); assert_eq!(err, Err(TLSErrorFromPeer::Client( TLSError::WebPKIError(webpki::Error::CertNotValidForName)) ) ); } } } struct ClientCheckCertResolve { query_count: AtomicUsize, expect_queries: usize } impl ClientCheckCertResolve { fn new(expect_queries: usize) -> ClientCheckCertResolve { ClientCheckCertResolve { query_count: AtomicUsize::new(0), expect_queries: expect_queries } } } impl Drop for ClientCheckCertResolve { fn drop(&mut self) { let count = self.query_count.load(Ordering::SeqCst); assert_eq!(count, self.expect_queries); } } impl ResolvesClientCert for ClientCheckCertResolve { fn resolve(&self, acceptable_issuers: &[&[u8]], sigschemes: &[SignatureScheme]) -> Option<sign::CertifiedKey> { self.query_count.fetch_add(1, Ordering::SeqCst); if acceptable_issuers.len() == 0 { panic!("no issuers offered by server"); } if sigschemes.len() == 0 { panic!("no signature schemes shared by server"); } None } fn has_certs(&self) -> bool { true } } #[test] fn client_cert_resolve() { for kt in ALL_KEY_TYPES.iter() { let mut client_config = make_client_config(*kt); client_config.client_auth_cert_resolver = Arc::new(ClientCheckCertResolve::new(2)); let server_config = Arc::new(make_server_config_with_mandatory_client_auth(*kt)); for client_config in AllClientVersions::new(client_config) { let (mut client, mut server) = make_pair_for_arc_configs(&Arc::new(client_config), &server_config); assert_eq!( do_handshake_until_error(&mut client, &mut server), Err(TLSErrorFromPeer::Server(TLSError::NoCertificatesPresented))); } } } #[test] fn client_auth_works() { for kt in ALL_KEY_TYPES.iter() { let client_config = make_client_config_with_auth(*kt); let server_config = Arc::new(make_server_config_with_mandatory_client_auth(*kt)); for client_config in AllClientVersions::new(client_config) { let (mut client, mut server) = make_pair_for_arc_configs(&Arc::new(client_config), &server_config); do_handshake(&mut client, &mut server); } } } #[cfg(feature = "dangerous_configuration")] mod test_clientverifier { use super::*; use crate::common::MockClientVerifier; use rustls::internal::msgs::enums::AlertDescription; use rustls::internal::msgs::enums::ContentType; // Client is authorized! fn ver_ok() -> Result<ClientCertVerified, TLSError> { Ok(rustls::ClientCertVerified::assertion()) } // Use when we shouldn't even attempt verification fn ver_unreachable() -> Result<ClientCertVerified, TLSError> { unreachable!() } // Verifier that returns an error that we can expect fn ver_err() -> Result<ClientCertVerified, TLSError> { Err(TLSError::General("test err".to_string())) } #[test] // Happy path, we resolve to a root, it is verified OK, should be able to connect fn client_verifier_works() { for kt in ALL_KEY_TYPES.iter() { let client_verifier = MockClientVerifier { verified: ver_ok, subjects: Some(get_client_root_store(*kt).get_subjects()), mandatory: Some(true), offered_schemes: None, }; let mut server_config = ServerConfig::new(Arc::new(client_verifier)); server_config.set_single_cert(kt.get_chain(), kt.get_key()).unwrap(); let server_config = Arc::new(server_config); let client_config = make_client_config_with_auth(*kt); for client_config in AllClientVersions::new(client_config) { let (mut client, mut server) = make_pair_for_arc_configs(&Arc::new(client_config.clone()), &server_config); let err = do_handshake_until_error(&mut client, &mut server); assert_eq!(err, Ok(())); } } } // Server offers no verification schemes #[test] fn client_verifier_no_schemes() { for kt in ALL_KEY_TYPES.iter() { let client_verifier = MockClientVerifier { verified: ver_ok, subjects: Some(get_client_root_store(*kt).get_subjects()), mandatory: Some(true), offered_schemes: Some(vec![]), }; let mut server_config = ServerConfig::new(Arc::new(client_verifier)); server_config.set_single_cert(kt.get_chain(), kt.get_key()).unwrap(); let server_config = Arc::new(server_config); let client_config = make_client_config_with_auth(*kt); for client_config in AllClientVersions::new(client_config) { let (mut client, mut server) = make_pair_for_arc_configs(&Arc::new(client_config.clone()), &server_config); let err = do_handshake_until_error(&mut client, &mut server); assert_eq!(err, Err(TLSErrorFromPeer::Client(TLSError::CorruptMessagePayload(ContentType::Handshake)))); } } } // Common case, we do not find a root store to resolve to #[test] fn client_verifier_no_root() { for kt in ALL_KEY_TYPES.iter() { let client_verifier = MockClientVerifier { verified: ver_ok, subjects: None, mandatory: Some(true), offered_schemes: None, }; let mut server_config = ServerConfig::new(Arc::new(client_verifier)); server_config.set_single_cert(kt.get_chain(), kt.get_key()).unwrap(); let server_config = Arc::new(server_config); let client_config = make_client_config_with_auth(*kt); for client_config in AllClientVersions::new(client_config) { let mut server = ServerSession::new(&server_config); let mut client = ClientSession::new(&Arc::new(client_config), dns_name("notlocalhost")); let errs = do_handshake_until_both_error(&mut client, &mut server); assert_eq!(errs, Err(vec![ TLSErrorFromPeer::Server(TLSError::General("client rejected by client_auth_root_subjects".into())), TLSErrorFromPeer::Client(TLSError::AlertReceived(AlertDescription::AccessDenied)) ])); } } } // If we cannot resolve a root, we cannot decide if auth is mandatory #[test] fn client_verifier_no_auth_no_root() { for kt in ALL_KEY_TYPES.iter() { let client_verifier = MockClientVerifier { verified: ver_unreachable, subjects: None, mandatory: Some(true), offered_schemes: None, }; let mut server_config = ServerConfig::new(Arc::new(client_verifier)); server_config.set_single_cert(kt.get_chain(), kt.get_key()).unwrap(); let server_config = Arc::new(server_config); let client_config = make_client_config(*kt); for client_config in AllClientVersions::new(client_config) { let mut server = ServerSession::new(&server_config); let mut client = ClientSession::new(&Arc::new(client_config), dns_name("notlocalhost")); let errs = do_handshake_until_both_error(&mut client, &mut server); assert_eq!(errs, Err(vec![ TLSErrorFromPeer::Server(TLSError::General("client rejected by client_auth_root_subjects".into())), TLSErrorFromPeer::Client(TLSError::AlertReceived(AlertDescription::AccessDenied)) ])); } } } // If we do have a root, we must do auth #[test] fn client_verifier_no_auth_yes_root() { for kt in ALL_KEY_TYPES.iter() { let client_verifier = MockClientVerifier { verified: ver_unreachable, subjects: Some(get_client_root_store(*kt).get_subjects()), mandatory: Some(true), offered_schemes: None, }; let mut server_config = ServerConfig::new(Arc::new(client_verifier)); server_config.set_single_cert(kt.get_chain(), kt.get_key()).unwrap(); let server_config = Arc::new(server_config); let client_config = make_client_config(*kt); for client_config in AllClientVersions::new(client_config) { println!("Failing: {:?}", client_config.versions); let mut server = ServerSession::new(&server_config); let mut client = ClientSession::new(&Arc::new(client_config), dns_name("localhost")); let errs = do_handshake_until_both_error(&mut client, &mut server); assert_eq!(errs, Err(vec![ TLSErrorFromPeer::Server(TLSError::NoCertificatesPresented), TLSErrorFromPeer::Client(TLSError::AlertReceived(AlertDescription::CertificateRequired)) ])); } } } #[test] // Triple checks we propagate the TLSError through fn client_verifier_fails_properly() { for kt in ALL_KEY_TYPES.iter() { let client_verifier = MockClientVerifier { verified: ver_err, subjects: Some(get_client_root_store(*kt).get_subjects()), mandatory: Some(true), offered_schemes: None, }; let mut server_config = ServerConfig::new(Arc::new(client_verifier)); server_config.set_single_cert(kt.get_chain(), kt.get_key()).unwrap(); let server_config = Arc::new(server_config); let client_config = make_client_config_with_auth(*kt); for client_config in AllClientVersions::new(client_config) { let mut server = ServerSession::new(&server_config); let mut client = ClientSession::new(&Arc::new(client_config), dns_name("localhost")); let err = do_handshake_until_error(&mut client, &mut server); assert_eq!(err, Err(TLSErrorFromPeer::Server( TLSError::General("test err".into())))); } } } #[test] // If a verifier returns a None on Mandatory-ness, then we error out fn client_verifier_must_determine_client_auth_requirement_to_continue() { for kt in ALL_KEY_TYPES.iter() { let client_verifier = MockClientVerifier { verified: ver_ok, subjects: Some(get_client_root_store(*kt).get_subjects()), mandatory: None, offered_schemes: None, }; let mut server_config = ServerConfig::new(Arc::new(client_verifier)); server_config.set_single_cert(kt.get_chain(), kt.get_key()).unwrap(); let server_config = Arc::new(server_config); let client_config = make_client_config_with_auth(*kt); for client_config in AllClientVersions::new(client_config) { let mut server = ServerSession::new(&server_config); let mut client = ClientSession::new(&Arc::new(client_config), dns_name("localhost")); let errs = do_handshake_until_both_error(&mut client, &mut server); assert_eq!(errs, Err(vec![ TLSErrorFromPeer::Server(TLSError::General("client rejected by client_auth_mandatory".into())), TLSErrorFromPeer::Client(TLSError::AlertReceived(AlertDescription::AccessDenied)) ])); } } } } // mod test_clientverifier #[test] fn client_error_is_sticky() { let (mut client, _) = make_pair(KeyType::RSA); client.read_tls(&mut b"\x16\x03\x03\x00\x08\x0f\x00\x00\x04junk".as_ref()).unwrap(); let mut err = client.process_new_packets(); assert_eq!(err.is_err(), true); err = client.process_new_packets(); assert_eq!(err.is_err(), true); } #[test] fn server_error_is_sticky() { let (_, mut server) = make_pair(KeyType::RSA); server.read_tls(&mut b"\x16\x03\x03\x00\x08\x0f\x00\x00\x04junk".as_ref()).unwrap(); let mut err = server.process_new_packets(); assert_eq!(err.is_err(), true); err = server.process_new_packets(); assert_eq!(err.is_err(), true); } #[test] fn server_is_send_and_sync() { let (_, server) = make_pair(KeyType::RSA); &server as &dyn Send; &server as &dyn Sync; } #[test] fn client_is_send_and_sync() { let (client, _) = make_pair(KeyType::RSA); &client as &dyn Send; &client as &dyn Sync; } #[test] fn server_respects_buffer_limit_pre_handshake() { let (mut client, mut server) = make_pair(KeyType::RSA); server.set_buffer_limit(32); assert_eq!(server.write(b"01234567890123456789").unwrap(), 20); assert_eq!(server.write(b"01234567890123456789").unwrap(), 12); do_handshake(&mut client, &mut server); transfer(&mut server, &mut client); client.process_new_packets().unwrap(); check_read(&mut client, b"01234567890123456789012345678901"); } #[test] fn server_respects_buffer_limit_post_handshake() { let (mut client, mut server) = make_pair(KeyType::RSA); // this test will vary in behaviour depending on the default suites do_handshake(&mut client, &mut server); server.set_buffer_limit(48); assert_eq!(server.write(b"01234567890123456789").unwrap(), 20); assert_eq!(server.write(b"01234567890123456789").unwrap(), 6); transfer(&mut server, &mut client); client.process_new_packets().unwrap(); check_read(&mut client, b"01234567890123456789012345"); } #[test] fn client_respects_buffer_limit_pre_handshake() { let (mut client, mut server) = make_pair(KeyType::RSA); client.set_buffer_limit(32); assert_eq!(client.write(b"01234567890123456789").unwrap(), 20); assert_eq!(client.write(b"01234567890123456789").unwrap(), 12); do_handshake(&mut client, &mut server); transfer(&mut client, &mut server); server.process_new_packets().unwrap(); check_read(&mut server, b"01234567890123456789012345678901"); } #[test] fn client_respects_buffer_limit_post_handshake() { let (mut client, mut server) = make_pair(KeyType::RSA); do_handshake(&mut client, &mut server); client.set_buffer_limit(48); assert_eq!(client.write(b"01234567890123456789").unwrap(), 20); assert_eq!(client.write(b"01234567890123456789").unwrap(), 6); transfer(&mut client, &mut server); server.process_new_packets().unwrap(); check_read(&mut server, b"01234567890123456789012345"); } struct OtherSession<'a> { sess: &'a mut dyn Session, pub reads: usize, pub writes: usize, pub writevs: Vec<Vec<usize>>, fail_ok: bool, pub short_writes: bool, pub last_error: Option<rustls::TLSError>, } impl<'a> OtherSession<'a> { fn new(sess: &'a mut dyn Session) -> OtherSession<'a> { OtherSession { sess, reads: 0, writes: 0, writevs: vec![], fail_ok: false, short_writes: false, last_error: None, } } fn new_fails(sess: &'a mut dyn Session) -> OtherSession<'a> { let mut os = OtherSession::new(sess); os.fail_ok = true; os } } impl<'a> io::Read for OtherSession<'a> { fn read(&mut self, mut b: &mut [u8]) -> io::Result<usize> { self.reads += 1; self.sess.write_tls(b.by_ref()) } } impl<'a> io::Write for OtherSession<'a> { fn write(&mut self, mut b: &[u8]) -> io::Result<usize> { self.writes += 1; let l = self.sess.read_tls(b.by_ref())?; let rc = self.sess.process_new_packets(); if !self.fail_ok { rc.unwrap(); } else if rc.is_err() { self.last_error = rc.err(); } Ok(l) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl<'a> rustls::WriteV for OtherSession<'a> { fn writev(&mut self, b: &[&[u8]]) -> io::Result<usize> { let mut total = 0; let mut lengths = vec![]; for bytes in b { let write_len = if self.short_writes { if bytes.len() > 5 { bytes.len() / 2 } else { bytes.len() } } else { bytes.len() }; let l = self.sess.read_tls(&mut io::Cursor::new(&bytes[..write_len]))?; lengths.push(l); total += l; if bytes.len() != l { break; } } let rc = self.sess.process_new_packets(); if !self.fail_ok { rc.unwrap(); } else if rc.is_err() { self.last_error = rc.err(); } self.writevs.push(lengths); Ok(total) } } #[test] fn client_complete_io_for_handshake() { let (mut client, mut server) = make_pair(KeyType::RSA); assert_eq!(true, client.is_handshaking()); let (rdlen, wrlen) = client.complete_io(&mut OtherSession::new(&mut server)).unwrap(); assert!(rdlen > 0 && wrlen > 0); assert_eq!(false, client.is_handshaking()); } #[test] fn client_complete_io_for_handshake_eof() { let (mut client, _) = make_pair(KeyType::RSA); let mut input = io::Cursor::new(Vec::new()); assert_eq!(true, client.is_handshaking()); let err = client.complete_io(&mut input).unwrap_err(); assert_eq!(io::ErrorKind::UnexpectedEof, err.kind()); } #[test] fn client_complete_io_for_write() { for kt in ALL_KEY_TYPES.iter() { let (mut client, mut server) = make_pair(*kt); do_handshake(&mut client, &mut server); client.write(b"01234567890123456789").unwrap(); client.write(b"01234567890123456789").unwrap(); { let mut pipe = OtherSession::new(&mut server); let (rdlen, wrlen) = client.complete_io(&mut pipe).unwrap(); assert!(rdlen == 0 && wrlen > 0); assert_eq!(pipe.writes, 2); } check_read(&mut server, b"0123456789012345678901234567890123456789"); } } #[test] fn client_complete_io_for_read() { for kt in ALL_KEY_TYPES.iter() { let (mut client, mut server) = make_pair(*kt); do_handshake(&mut client, &mut server); server.write(b"01234567890123456789").unwrap(); { let mut pipe = OtherSession::new(&mut server); let (rdlen, wrlen) = client.complete_io(&mut pipe).unwrap(); assert!(rdlen > 0 && wrlen == 0); assert_eq!(pipe.reads, 1); } check_read(&mut client, b"01234567890123456789"); } } #[test] fn server_complete_io_for_handshake() { for kt in ALL_KEY_TYPES.iter() { let (mut client, mut server) = make_pair(*kt); assert_eq!(true, server.is_handshaking()); let (rdlen, wrlen) = server.complete_io(&mut OtherSession::new(&mut client)).unwrap(); assert!(rdlen > 0 && wrlen > 0); assert_eq!(false, server.is_handshaking()); } } #[test] fn server_complete_io_for_handshake_eof() { let (_, mut server) = make_pair(KeyType::RSA); let mut input = io::Cursor::new(Vec::new()); assert_eq!(true, server.is_handshaking()); let err = server.complete_io(&mut input).unwrap_err(); assert_eq!(io::ErrorKind::UnexpectedEof, err.kind()); } #[test] fn server_complete_io_for_write() { for kt in ALL_KEY_TYPES.iter() { let (mut client, mut server) = make_pair(*kt); do_handshake(&mut client, &mut server); server.write(b"01234567890123456789").unwrap(); server.write(b"01234567890123456789").unwrap(); { let mut pipe = OtherSession::new(&mut client); let (rdlen, wrlen) = server.complete_io(&mut pipe).unwrap(); assert!(rdlen == 0 && wrlen > 0); assert_eq!(pipe.writes, 2); } check_read(&mut client, b"0123456789012345678901234567890123456789"); } } #[test] fn server_complete_io_for_read() { for kt in ALL_KEY_TYPES.iter() { let (mut client, mut server) = make_pair(*kt); do_handshake(&mut client, &mut server); client.write(b"01234567890123456789").unwrap(); { let mut pipe = OtherSession::new(&mut client); let (rdlen, wrlen) = server.complete_io(&mut pipe).unwrap(); assert!(rdlen > 0 && wrlen == 0); assert_eq!(pipe.reads, 1); } check_read(&mut server, b"01234567890123456789"); } } #[test] fn client_stream_write() { for kt in ALL_KEY_TYPES.iter() { let (mut client, mut server) = make_pair(*kt); { let mut pipe = OtherSession::new(&mut server); let mut stream = Stream::new(&mut client, &mut pipe); assert_eq!(stream.write(b"hello").unwrap(), 5); } check_read(&mut server, b"hello"); } } #[test] fn client_streamowned_write() { for kt in ALL_KEY_TYPES.iter() { let (client, mut server) = make_pair(*kt); { let pipe = OtherSession::new(&mut server); let mut stream = StreamOwned::new(client, pipe); assert_eq!(stream.write(b"hello").unwrap(), 5); } check_read(&mut server, b"hello"); } } #[test] fn client_stream_read() { for kt in ALL_KEY_TYPES.iter() { let (mut client, mut server) = make_pair(*kt); server.write(b"world").unwrap(); { let mut pipe = OtherSession::new(&mut server); let mut stream = Stream::new(&mut client, &mut pipe); check_read(&mut stream, b"world"); } } } #[test] fn client_streamowned_read() { for kt in ALL_KEY_TYPES.iter() { let (client, mut server) = make_pair(*kt); server.write(b"world").unwrap(); { let pipe = OtherSession::new(&mut server); let mut stream = StreamOwned::new(client, pipe); check_read(&mut stream, b"world"); } } } #[test] fn server_stream_write() { for kt in ALL_KEY_TYPES.iter() { let (mut client, mut server) = make_pair(*kt); { let mut pipe = OtherSession::new(&mut client); let mut stream = Stream::new(&mut server, &mut pipe); assert_eq!(stream.write(b"hello").unwrap(), 5); } check_read(&mut client, b"hello"); } } #[test] fn server_streamowned_write() { for kt in ALL_KEY_TYPES.iter() { let (mut client, server) = make_pair(*kt); { let pipe = OtherSession::new(&mut client); let mut stream = StreamOwned::new(server, pipe); assert_eq!(stream.write(b"hello").unwrap(), 5); } check_read(&mut client, b"hello"); } } #[test] fn server_stream_read() { for kt in ALL_KEY_TYPES.iter() { let (mut client, mut server) = make_pair(*kt); client.write(b"world").unwrap(); { let mut pipe = OtherSession::new(&mut client); let mut stream = Stream::new(&mut server, &mut pipe); check_read(&mut stream, b"world"); } } } #[test] fn server_streamowned_read() { for kt in ALL_KEY_TYPES.iter() { let (mut client, server) = make_pair(*kt); client.write(b"world").unwrap(); { let pipe = OtherSession::new(&mut client); let mut stream = StreamOwned::new(server, pipe); check_read(&mut stream, b"world"); } } } struct FailsWrites { errkind: io::ErrorKind, after: usize, } impl io::Read for FailsWrites { fn read(&mut self, _b: &mut [u8]) -> io::Result<usize> { Ok(0) } } impl io::Write for FailsWrites { fn write(&mut self, b: &[u8]) -> io::Result<usize> { if self.after > 0 { self.after -= 1; Ok(b.len()) } else { Err(io::Error::new(self.errkind, "oops")) } } fn flush(&mut self) -> io::Result<()> { Ok(()) } } #[test] fn stream_write_reports_underlying_io_error_before_plaintext_processed() { let (mut client, mut server) = make_pair(KeyType::RSA); do_handshake(&mut client, &mut server); let mut pipe = FailsWrites { errkind: io::ErrorKind::WouldBlock, after: 0, }; client.write(b"hello").unwrap(); let mut client_stream = Stream::new(&mut client, &mut pipe); let rc = client_stream.write(b"world"); assert!(rc.is_err()); let err = rc.err().unwrap(); assert_eq!(err.kind(), io::ErrorKind::WouldBlock); assert_eq!(err.description(), "oops"); } #[test] fn stream_write_swallows_underlying_io_error_after_plaintext_processed() { let (mut client, mut server) = make_pair(KeyType::RSA); do_handshake(&mut client, &mut server); let mut pipe = FailsWrites { errkind: io::ErrorKind::WouldBlock, after: 1, }; client.write(b"hello").unwrap(); let mut client_stream = Stream::new(&mut client, &mut pipe); let rc = client_stream.write(b"world"); assert_eq!(format!("{:?}", rc), "Ok(5)"); } fn make_disjoint_suite_configs() -> (ClientConfig, ServerConfig) { let kt = KeyType::RSA; let mut server_config = make_server_config(kt); server_config.ciphersuites = vec![find_suite(CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256)]; let mut client_config = make_client_config(kt); client_config.ciphersuites = vec![find_suite(CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384)]; (client_config, server_config) } #[test] fn client_stream_handshake_error() { let (client_config, server_config) = make_disjoint_suite_configs(); let (mut client, mut server) = make_pair_for_configs(client_config, server_config); { let mut pipe = OtherSession::new_fails(&mut server); let mut client_stream = Stream::new(&mut client, &mut pipe); let rc = client_stream.write(b"hello"); assert!(rc.is_err()); assert_eq!(format!("{:?}", rc), "Err(Custom { kind: InvalidData, error: AlertReceived(HandshakeFailure) })"); let rc = client_stream.write(b"hello"); assert!(rc.is_err()); assert_eq!(format!("{:?}", rc), "Err(Custom { kind: InvalidData, error: AlertReceived(HandshakeFailure) })"); } } #[test] fn client_streamowned_handshake_error() { let (client_config, server_config) = make_disjoint_suite_configs(); let (client, mut server) = make_pair_for_configs(client_config, server_config); let pipe = OtherSession::new_fails(&mut server); let mut client_stream = StreamOwned::new(client, pipe); let rc = client_stream.write(b"hello"); assert!(rc.is_err()); assert_eq!(format!("{:?}", rc), "Err(Custom { kind: InvalidData, error: AlertReceived(HandshakeFailure) })"); let rc = client_stream.write(b"hello"); assert!(rc.is_err()); assert_eq!(format!("{:?}", rc), "Err(Custom { kind: InvalidData, error: AlertReceived(HandshakeFailure) })"); } #[test] fn server_stream_handshake_error() { let (client_config, server_config) = make_disjoint_suite_configs(); let (mut client, mut server) = make_pair_for_configs(client_config, server_config); client.write(b"world").unwrap(); { let mut pipe = OtherSession::new_fails(&mut client); let mut server_stream = Stream::new(&mut server, &mut pipe); let mut bytes = [0u8; 5]; let rc = server_stream.read(&mut bytes); assert!(rc.is_err()); assert_eq!(format!("{:?}", rc), "Err(Custom { kind: InvalidData, error: PeerIncompatibleError(\"no ciphersuites in common\") })"); } } #[test] fn server_streamowned_handshake_error() { let (client_config, server_config) = make_disjoint_suite_configs(); let (mut client, server) = make_pair_for_configs(client_config, server_config); client.write(b"world").unwrap(); let pipe = OtherSession::new_fails(&mut client); let mut server_stream = StreamOwned::new(server, pipe); let mut bytes = [0u8; 5]; let rc = server_stream.read(&mut bytes); assert!(rc.is_err()); assert_eq!(format!("{:?}", rc), "Err(Custom { kind: InvalidData, error: PeerIncompatibleError(\"no ciphersuites in common\") })"); } #[test] fn server_config_is_clone() { let _ = make_server_config(KeyType::RSA).clone(); } #[test] fn client_config_is_clone() { let _ = make_client_config(KeyType::RSA).clone(); } #[test] fn client_session_is_debug() { let (client, _) = make_pair(KeyType::RSA); println!("{:?}", client); } #[test] fn server_session_is_debug() { let (_, server) = make_pair(KeyType::RSA); println!("{:?}", server); } #[test] fn server_complete_io_for_handshake_ending_with_alert() { let (client_config, server_config) = make_disjoint_suite_configs(); let (mut client, mut server) = make_pair_for_configs(client_config, server_config); assert_eq!(true, server.is_handshaking()); let mut pipe = OtherSession::new_fails(&mut client); let rc = server.complete_io(&mut pipe); assert!(rc.is_err(), "server io failed due to handshake failure"); assert!(!server.wants_write(), "but server did send its alert"); assert_eq!(format!("{:?}", pipe.last_error), "Some(AlertReceived(HandshakeFailure))", "which was received by client"); } #[test] fn server_exposes_offered_sni() { let kt = KeyType::RSA; let mut client = ClientSession::new(&Arc::new(make_client_config(kt)), dns_name("second.testserver.com")); let mut server = ServerSession::new(&Arc::new(make_server_config(kt))); assert_eq!(None, server.get_sni_hostname()); do_handshake(&mut client, &mut server); assert_eq!(Some("second.testserver.com"), server.get_sni_hostname()); } #[test] fn sni_resolver_works() { let kt = KeyType::RSA; let mut resolver = rustls::ResolvesServerCertUsingSNI::new(); let signing_key = sign::RSASigningKey::new(&kt.get_key()) .unwrap(); let signing_key: Arc<Box<dyn sign::SigningKey>> = Arc::new(Box::new(signing_key)); resolver.add("localhost", sign::CertifiedKey::new(kt.get_chain(), signing_key.clone())) .unwrap(); let mut server_config = make_server_config(kt); server_config.cert_resolver = Arc::new(resolver); let server_config = Arc::new(server_config); let mut server1 = ServerSession::new(&server_config); let mut client1 = ClientSession::new(&Arc::new(make_client_config(kt)), dns_name("localhost")); let err = do_handshake_until_error(&mut client1, &mut server1); assert_eq!(err, Ok(())); let mut server2 = ServerSession::new(&server_config); let mut client2 = ClientSession::new(&Arc::new(make_client_config(kt)), dns_name("notlocalhost")); let err = do_handshake_until_error(&mut client2, &mut server2); assert_eq!(err, Err(TLSErrorFromPeer::Server( TLSError::General("no server certificate chain resolved".into())))); } #[test] fn sni_resolver_rejects_wrong_names() { let kt = KeyType::RSA; let mut resolver = rustls::ResolvesServerCertUsingSNI::new(); let signing_key = sign::RSASigningKey::new(&kt.get_key()) .unwrap(); let signing_key: Arc<Box<dyn sign::SigningKey>> = Arc::new(Box::new(signing_key)); assert_eq!(Ok(()), resolver.add("localhost", sign::CertifiedKey::new(kt.get_chain(), signing_key.clone()))); assert_eq!(Err(TLSError::General("The server certificate is not valid for the given name".into())), resolver.add("not-localhost", sign::CertifiedKey::new(kt.get_chain(), signing_key.clone()))); assert_eq!(Err(TLSError::General("Bad DNS name".into())), resolver.add("not ascii 🦀", sign::CertifiedKey::new(kt.get_chain(), signing_key.clone()))); } #[test] fn sni_resolver_rejects_bad_certs() { let kt = KeyType::RSA; let mut resolver = rustls::ResolvesServerCertUsingSNI::new(); let signing_key = sign::RSASigningKey::new(&kt.get_key()) .unwrap(); let signing_key: Arc<Box<dyn sign::SigningKey>> = Arc::new(Box::new(signing_key)); assert_eq!(Err(TLSError::General("No end-entity certificate in certificate chain".into())), resolver.add("localhost", sign::CertifiedKey::new(vec![], signing_key.clone()))); let bad_chain = vec![ rustls::Certificate(vec![ 0xa0 ]) ]; assert_eq!(Err(TLSError::General("End-entity certificate in certificate chain is syntactically invalid".into())), resolver.add("localhost", sign::CertifiedKey::new(bad_chain, signing_key.clone()))); } fn do_exporter_test(client_config: ClientConfig, server_config: ServerConfig) { let mut client_secret = [0u8; 64]; let mut server_secret = [0u8; 64]; let (mut client, mut server) = make_pair_for_configs(client_config, server_config); assert_eq!(Err(TLSError::HandshakeNotComplete), client.export_keying_material(&mut client_secret, b"label", Some(b"context"))); assert_eq!(Err(TLSError::HandshakeNotComplete), server.export_keying_material(&mut server_secret, b"label", Some(b"context"))); do_handshake(&mut client, &mut server); assert_eq!(Ok(()), client.export_keying_material(&mut client_secret, b"label", Some(b"context"))); assert_eq!(Ok(()), server.export_keying_material(&mut server_secret, b"label", Some(b"context"))); assert_eq!(client_secret.to_vec(), server_secret.to_vec()); assert_eq!(Ok(()), client.export_keying_material(&mut client_secret, b"label", None)); assert_ne!(client_secret.to_vec(), server_secret.to_vec()); assert_eq!(Ok(()), server.export_keying_material(&mut server_secret, b"label", None)); assert_eq!(client_secret.to_vec(), server_secret.to_vec()); } #[test] fn test_tls12_exporter() { for kt in ALL_KEY_TYPES.iter() { let mut client_config = make_client_config(*kt); let server_config = make_server_config(*kt); client_config.versions = vec![ ProtocolVersion::TLSv1_2 ]; do_exporter_test(client_config, server_config); } } #[test] fn test_tls13_exporter() { for kt in ALL_KEY_TYPES.iter() { let mut client_config = make_client_config(*kt); let server_config = make_server_config(*kt); client_config.versions = vec![ ProtocolVersion::TLSv1_3 ]; do_exporter_test(client_config, server_config); } } fn do_suite_test(client_config: ClientConfig, server_config: ServerConfig, expect_suite: &'static SupportedCipherSuite, expect_version: ProtocolVersion) { println!("do_suite_test {:?} {:?}", expect_version, expect_suite.suite); let (mut client, mut server) = make_pair_for_configs(client_config, server_config); assert_eq!(None, client.get_negotiated_ciphersuite()); assert_eq!(None, server.get_negotiated_ciphersuite()); assert_eq!(None, client.get_protocol_version()); assert_eq!(None, server.get_protocol_version()); assert_eq!(true, client.is_handshaking()); assert_eq!(true, server.is_handshaking()); transfer(&mut client, &mut server); server.process_new_packets().unwrap(); assert_eq!(true, client.is_handshaking()); assert_eq!(true, server.is_handshaking()); assert_eq!(None, client.get_protocol_version()); assert_eq!(Some(expect_version), server.get_protocol_version()); assert_eq!(None, client.get_negotiated_ciphersuite()); assert_eq!(Some(expect_suite), server.get_negotiated_ciphersuite()); transfer(&mut server, &mut client); client.process_new_packets().unwrap(); assert_eq!(Some(expect_suite), client.get_negotiated_ciphersuite()); assert_eq!(Some(expect_suite), server.get_negotiated_ciphersuite()); transfer(&mut client, &mut server); server.process_new_packets().unwrap(); transfer(&mut server, &mut client); client.process_new_packets().unwrap(); assert_eq!(false, client.is_handshaking()); assert_eq!(false, server.is_handshaking()); assert_eq!(Some(expect_version), client.get_protocol_version()); assert_eq!(Some(expect_version), server.get_protocol_version()); assert_eq!(Some(expect_suite), client.get_negotiated_ciphersuite()); assert_eq!(Some(expect_suite), server.get_negotiated_ciphersuite()); } fn find_suite(suite: CipherSuite) -> &'static SupportedCipherSuite { for scs in ALL_CIPHERSUITES.iter() { if scs.suite == suite { return scs; } } panic!("find_suite given unsuppported suite"); } static TEST_CIPHERSUITES: [(ProtocolVersion, KeyType, CipherSuite); 9] = [ (ProtocolVersion::TLSv1_3, KeyType::RSA, CipherSuite::TLS13_CHACHA20_POLY1305_SHA256), (ProtocolVersion::TLSv1_3, KeyType::RSA, CipherSuite::TLS13_AES_256_GCM_SHA384), (ProtocolVersion::TLSv1_3, KeyType::RSA, CipherSuite::TLS13_AES_128_GCM_SHA256), (ProtocolVersion::TLSv1_2, KeyType::ECDSA, CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256), (ProtocolVersion::TLSv1_2, KeyType::RSA, CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256), (ProtocolVersion::TLSv1_2, KeyType::ECDSA, CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384), (ProtocolVersion::TLSv1_2, KeyType::ECDSA, CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256), (ProtocolVersion::TLSv1_2, KeyType::RSA, CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384), (ProtocolVersion::TLSv1_2, KeyType::RSA, CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256) ]; #[test] fn negotiated_ciphersuite_default() { for kt in ALL_KEY_TYPES.iter() { do_suite_test(make_client_config(*kt), make_server_config(*kt), find_suite(CipherSuite::TLS13_CHACHA20_POLY1305_SHA256), ProtocolVersion::TLSv1_3); } } #[test] fn all_suites_covered() { assert_eq!(ALL_CIPHERSUITES.len(), TEST_CIPHERSUITES.len()); } #[test] fn negotiated_ciphersuite_client() { for item in TEST_CIPHERSUITES.iter() { let (version, kt, suite) = *item; let scs = find_suite(suite); let mut client_config = make_client_config(kt); client_config.ciphersuites = vec![scs]; client_config.versions = vec![version]; do_suite_test(client_config, make_server_config(kt), scs, version); } } #[test] fn negotiated_ciphersuite_server() { for item in TEST_CIPHERSUITES.iter() { let (version, kt, suite) = *item; let scs = find_suite(suite); let mut server_config = make_server_config(kt); server_config.ciphersuites = vec![scs]; server_config.versions = vec![version]; do_suite_test(make_client_config(kt), server_config, scs, version); } } #[derive(Debug, PartialEq)] struct KeyLogItem { label: String, client_random: Vec<u8>, secret: Vec<u8>, } struct KeyLogToVec { label: &'static str, items: Mutex<Vec<KeyLogItem>>, } impl KeyLogToVec { fn new(who: &'static str) -> Self { KeyLogToVec { label: who, items: Mutex::new(vec![]), } } fn take(&self) -> Vec<KeyLogItem> { mem::replace(&mut self.items.lock() .unwrap(), vec![]) } } impl KeyLog for KeyLogToVec { fn log(&self, label: &str, client: &[u8], secret: &[u8]) { let value = KeyLogItem { label: label.into(), client_random: client.into(), secret: secret.into() }; println!("key log {:?}: {:?}", self.label, value); self.items.lock() .unwrap() .push(value); } } #[test] fn key_log_for_tls12() { let client_key_log = Arc::new(KeyLogToVec::new("client")); let server_key_log = Arc::new(KeyLogToVec::new("server")); let kt = KeyType::RSA; let mut client_config = make_client_config(kt); client_config.versions = vec![ ProtocolVersion::TLSv1_2 ]; client_config.key_log = client_key_log.clone(); let client_config = Arc::new(client_config); let mut server_config = make_server_config(kt); server_config.key_log = server_key_log.clone(); let server_config = Arc::new(server_config); // full handshake let (mut client, mut server) = make_pair_for_arc_configs(&client_config, &server_config); do_handshake(&mut client, &mut server); let client_full_log = client_key_log.take(); let server_full_log = server_key_log.take(); assert_eq!(client_full_log, server_full_log); assert_eq!(1, client_full_log.len()); assert_eq!("CLIENT_RANDOM", client_full_log[0].label); // resumed let (mut client, mut server) = make_pair_for_arc_configs(&client_config, &server_config); do_handshake(&mut client, &mut server); let client_resume_log = client_key_log.take(); let server_resume_log = server_key_log.take(); assert_eq!(client_resume_log, server_resume_log); assert_eq!(1, client_resume_log.len()); assert_eq!("CLIENT_RANDOM", client_resume_log[0].label); assert_eq!(client_full_log[0].secret, client_resume_log[0].secret); } #[test] fn key_log_for_tls13() { let client_key_log = Arc::new(KeyLogToVec::new("client")); let server_key_log = Arc::new(KeyLogToVec::new("server")); let kt = KeyType::RSA; let mut client_config = make_client_config(kt); client_config.versions = vec![ ProtocolVersion::TLSv1_3 ]; client_config.key_log = client_key_log.clone(); let client_config = Arc::new(client_config); let mut server_config = make_server_config(kt); server_config.key_log = server_key_log.clone(); let server_config = Arc::new(server_config); // full handshake let (mut client, mut server) = make_pair_for_arc_configs(&client_config, &server_config); do_handshake(&mut client, &mut server); let client_full_log = client_key_log.take(); let server_full_log = server_key_log.take(); assert_eq!(5, client_full_log.len()); assert_eq!("CLIENT_HANDSHAKE_TRAFFIC_SECRET", client_full_log[0].label); assert_eq!("SERVER_HANDSHAKE_TRAFFIC_SECRET", client_full_log[1].label); assert_eq!("SERVER_TRAFFIC_SECRET_0", client_full_log[2].label); assert_eq!("EXPORTER_SECRET", client_full_log[3].label); assert_eq!("CLIENT_TRAFFIC_SECRET_0", client_full_log[4].label); assert_eq!(client_full_log[0], server_full_log[1]); assert_eq!(client_full_log[1], server_full_log[0]); assert_eq!(client_full_log[2], server_full_log[2]); assert_eq!(client_full_log[3], server_full_log[3]); assert_eq!(client_full_log[4], server_full_log[4]); // resumed let (mut client, mut server) = make_pair_for_arc_configs(&client_config, &server_config); do_handshake(&mut client, &mut server); let client_resume_log = client_key_log.take(); let server_resume_log = server_key_log.take(); assert_eq!(5, client_resume_log.len()); assert_eq!("CLIENT_HANDSHAKE_TRAFFIC_SECRET", client_resume_log[0].label); assert_eq!("SERVER_HANDSHAKE_TRAFFIC_SECRET", client_resume_log[1].label); assert_eq!("SERVER_TRAFFIC_SECRET_0", client_resume_log[2].label); assert_eq!("EXPORTER_SECRET", client_resume_log[3].label); assert_eq!("CLIENT_TRAFFIC_SECRET_0", client_resume_log[4].label); assert_eq!(client_resume_log[0], server_resume_log[1]); assert_eq!(client_resume_log[1], server_resume_log[0]); assert_eq!(client_resume_log[2], server_resume_log[2]); assert_eq!(client_resume_log[3], server_resume_log[3]); assert_eq!(client_resume_log[4], server_resume_log[4]); } #[test] fn vectored_write_for_server_appdata() { let (mut client, mut server) = make_pair(KeyType::RSA); do_handshake(&mut client, &mut server); server.write(b"01234567890123456789").unwrap(); server.write(b"01234567890123456789").unwrap(); { let mut pipe = OtherSession::new(&mut client); let wrlen = server.writev_tls(&mut pipe).unwrap(); assert_eq!(84, wrlen); assert_eq!(pipe.writevs, vec![vec![42, 42]]); } check_read(&mut client, b"0123456789012345678901234567890123456789"); } #[test] fn vectored_write_for_client_appdata() { let (mut client, mut server) = make_pair(KeyType::RSA); do_handshake(&mut client, &mut server); client.write(b"01234567890123456789").unwrap(); client.write(b"01234567890123456789").unwrap(); { let mut pipe = OtherSession::new(&mut server); let wrlen = client.writev_tls(&mut pipe).unwrap(); assert_eq!(84, wrlen); assert_eq!(pipe.writevs, vec![vec![42, 42]]); } check_read(&mut server, b"0123456789012345678901234567890123456789"); } #[test] fn vectored_write_for_server_handshake() { let (mut client, mut server) = make_pair(KeyType::RSA); server.write(b"01234567890123456789").unwrap(); server.write(b"0123456789").unwrap(); transfer(&mut client, &mut server); server.process_new_packets().unwrap(); { let mut pipe = OtherSession::new(&mut client); let wrlen = server.writev_tls(&mut pipe).unwrap(); // don't assert exact sizes here, to avoid a brittle test assert!(wrlen > 4000); // its pretty big (contains cert chain) assert_eq!(pipe.writevs.len(), 1); // only one writev assert!(pipe.writevs[0].len() > 3); // at least a server hello/cert/serverkx } client.process_new_packets().unwrap(); transfer(&mut client, &mut server); server.process_new_packets().unwrap(); { let mut pipe = OtherSession::new(&mut client); let wrlen = server.writev_tls(&mut pipe).unwrap(); assert_eq!(wrlen, 177); assert_eq!(pipe.writevs, vec![vec![103, 42, 32]]); } assert_eq!(server.is_handshaking(), false); assert_eq!(client.is_handshaking(), false); check_read(&mut client, b"012345678901234567890123456789"); } #[test] fn vectored_write_for_client_handshake() { let (mut client, mut server) = make_pair(KeyType::RSA); client.write(b"01234567890123456789").unwrap(); client.write(b"0123456789").unwrap(); { let mut pipe = OtherSession::new(&mut server); let wrlen = client.writev_tls(&mut pipe).unwrap(); // don't assert exact sizes here, to avoid a brittle test assert!(wrlen > 200); // just the client hello assert_eq!(pipe.writevs.len(), 1); // only one writev assert!(pipe.writevs[0].len() == 1); // only a client hello } transfer(&mut server, &mut client); client.process_new_packets().unwrap(); { let mut pipe = OtherSession::new(&mut server); let wrlen = client.writev_tls(&mut pipe).unwrap(); assert_eq!(wrlen, 138); // CCS, finished, then two application datas assert_eq!(pipe.writevs, vec![vec![6, 58, 42, 32]]); } assert_eq!(server.is_handshaking(), false); assert_eq!(client.is_handshaking(), false); check_read(&mut server, b"012345678901234567890123456789"); } #[test] fn vectored_write_with_slow_client() { let (mut client, mut server) = make_pair(KeyType::RSA); client.set_buffer_limit(32); do_handshake(&mut client, &mut server); server.write(b"01234567890123456789").unwrap(); { let mut pipe = OtherSession::new(&mut client); pipe.short_writes = true; let wrlen = server.writev_tls(&mut pipe).unwrap() + server.writev_tls(&mut pipe).unwrap() + server.writev_tls(&mut pipe).unwrap() + server.writev_tls(&mut pipe).unwrap() + server.writev_tls(&mut pipe).unwrap() + server.writev_tls(&mut pipe).unwrap(); assert_eq!(42, wrlen); assert_eq!(pipe.writevs, vec![vec![21], vec![10], vec![5], vec![3], vec![3]]); } check_read(&mut client, b"01234567890123456789"); } struct ServerStorage { storage: Arc<dyn rustls::StoresServerSessions>, put_count: AtomicUsize, get_count: AtomicUsize, take_count: AtomicUsize, } impl ServerStorage { fn new() -> ServerStorage { ServerStorage { storage: rustls::ServerSessionMemoryCache::new(1024), put_count: AtomicUsize::new(0), get_count: AtomicUsize::new(0), take_count: AtomicUsize::new(0), } } fn puts(&self) -> usize { self.put_count.load(Ordering::SeqCst) } fn gets(&self) -> usize { self.get_count.load(Ordering::SeqCst) } fn takes(&self) -> usize { self.take_count.load(Ordering::SeqCst) } } impl fmt::Debug for ServerStorage { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "(put: {:?}, get: {:?}, take: {:?})", self.put_count, self.get_count, self.take_count) } } impl rustls::StoresServerSessions for ServerStorage { fn put(&self, key: Vec<u8>, value: Vec<u8>) -> bool { self.put_count.fetch_add(1, Ordering::SeqCst); self.storage.put(key, value) } fn get(&self, key: &[u8]) -> Option<Vec<u8>> { self.get_count.fetch_add(1, Ordering::SeqCst); self.storage.get(key) } fn take(&self, key: &[u8]) -> Option<Vec<u8>> { self.take_count.fetch_add(1, Ordering::SeqCst); self.storage.take(key) } } #[test] fn tls13_stateful_resumption() { let kt = KeyType::RSA; let mut client_config = make_client_config(kt); client_config.versions = vec![ ProtocolVersion::TLSv1_3 ]; let client_config = Arc::new(client_config); let mut server_config = make_server_config(kt); let storage = Arc::new(ServerStorage::new()); server_config.session_storage = storage.clone(); let server_config = Arc::new(server_config); // full handshake let (mut client, mut server) = make_pair_for_arc_configs(&client_config, &server_config); let (full_c2s, full_s2c) = do_handshake(&mut client, &mut server); assert_eq!(storage.puts(), 1); assert_eq!(storage.gets(), 0); assert_eq!(storage.takes(), 0); // resumed let (mut client, mut server) = make_pair_for_arc_configs(&client_config, &server_config); let (resume_c2s, resume_s2c) = do_handshake(&mut client, &mut server); assert!(resume_c2s > full_c2s); assert!(resume_s2c < full_s2c); assert_eq!(storage.puts(), 2); assert_eq!(storage.gets(), 0); assert_eq!(storage.takes(), 1); // resumed again let (mut client, mut server) = make_pair_for_arc_configs(&client_config, &server_config); let (resume2_c2s, resume2_s2c) = do_handshake(&mut client, &mut server); assert_eq!(resume_s2c, resume2_s2c); assert_eq!(resume_c2s, resume2_c2s); assert_eq!(storage.puts(), 3); assert_eq!(storage.gets(), 0); assert_eq!(storage.takes(), 2); } #[test] fn tls13_stateless_resumption() { let kt = KeyType::RSA; let mut client_config = make_client_config(kt); client_config.versions = vec![ ProtocolVersion::TLSv1_3 ]; let client_config = Arc::new(client_config); let mut server_config = make_server_config(kt); server_config.ticketer = rustls::Ticketer::new(); let storage = Arc::new(ServerStorage::new()); server_config.session_storage = storage.clone(); let server_config = Arc::new(server_config); // full handshake let (mut client, mut server) = make_pair_for_arc_configs(&client_config, &server_config); let (full_c2s, full_s2c) = do_handshake(&mut client, &mut server); assert_eq!(storage.puts(), 0); assert_eq!(storage.gets(), 0); assert_eq!(storage.takes(), 0); // resumed let (mut client, mut server) = make_pair_for_arc_configs(&client_config, &server_config); let (resume_c2s, resume_s2c) = do_handshake(&mut client, &mut server); assert!(resume_c2s > full_c2s); assert!(resume_s2c < full_s2c); assert_eq!(storage.puts(), 0); assert_eq!(storage.gets(), 0); assert_eq!(storage.takes(), 0); // resumed again let (mut client, mut server) = make_pair_for_arc_configs(&client_config, &server_config); let (resume2_c2s, resume2_s2c) = do_handshake(&mut client, &mut server); assert_eq!(resume_s2c, resume2_s2c); assert_eq!(resume_c2s, resume2_c2s); assert_eq!(storage.puts(), 0); assert_eq!(storage.gets(), 0); assert_eq!(storage.takes(), 0); } #[cfg(feature = "quic")] mod test_quic { use super::*; // Returns the sender's next secrets to use, or the receiver's error. fn step(send: &mut dyn Session, recv: &mut dyn Session) -> Result<Option<quic::Keys>, TLSError> { let mut buf = Vec::new(); let secrets = loop { let prev = buf.len(); if let Some(x) = send.write_hs(&mut buf) { break Some(x); } if prev == buf.len() { break None; } }; if let Err(e) = recv.read_hs(&buf) { return Err(e); } else { assert_eq!(recv.get_alert(), None); } Ok(secrets) } #[test] fn test_quic_handshake() { fn equal_dir_keys(x: &quic::DirectionalKeys, y: &quic::DirectionalKeys) -> bool { // Check that these two sets of keys are equal. The quic module's unit tests validate // that the IV and the keys are consistent, so we can just check the IV here. x.packet.iv.nonce_for(42).as_ref() == y.packet.iv.nonce_for(42).as_ref() } fn compatible_keys(x: &quic::Keys, y: &quic::Keys) -> bool { equal_dir_keys(&x.local, &y.remote) && equal_dir_keys(&x.remote, &y.local) } let kt = KeyType::RSA; let mut client_config = make_client_config(kt); client_config.versions = vec![ProtocolVersion::TLSv1_3]; client_config.enable_early_data = true; let client_config = Arc::new(client_config); let mut server_config = make_server_config(kt); server_config.versions = vec![ProtocolVersion::TLSv1_3]; server_config.max_early_data_size = 0xffffffff; server_config.alpn_protocols = vec!["foo".into()]; let server_config = Arc::new(server_config); let client_params = &b"client params"[..]; let server_params = &b"server params"[..]; // full handshake let mut client = ClientSession::new_quic(&client_config, dns_name("localhost"), client_params.into()); let mut server = ServerSession::new_quic(&server_config, server_params.into()); let client_initial = step(&mut client, &mut server).unwrap(); assert!(client_initial.is_none()); assert!(client.get_0rtt_keys().is_none()); assert_eq!(server.get_quic_transport_parameters(), Some(client_params)); let server_hs = step(&mut server, &mut client).unwrap().unwrap(); assert!(server.get_0rtt_keys().is_none()); let client_hs = step(&mut client, &mut server).unwrap().unwrap(); assert!(compatible_keys(&server_hs, &client_hs)); assert!(client.is_handshaking()); let server_1rtt = step(&mut server, &mut client).unwrap().unwrap(); assert!(!client.is_handshaking()); assert_eq!(client.get_quic_transport_parameters(), Some(server_params)); assert!(server.is_handshaking()); let client_1rtt = step(&mut client, &mut server).unwrap().unwrap(); assert!(!server.is_handshaking()); assert!(compatible_keys(&server_1rtt, &client_1rtt)); assert!(!compatible_keys(&server_hs, &server_1rtt)); assert!(step(&mut client, &mut server).unwrap().is_none()); assert!(step(&mut server, &mut client).unwrap().is_none()); // 0-RTT handshake let mut client = ClientSession::new_quic(&client_config, dns_name("localhost"), client_params.into()); assert!(client.get_negotiated_ciphersuite().is_some()); let mut server = ServerSession::new_quic(&server_config, server_params.into()); step(&mut client, &mut server).unwrap(); assert_eq!(client.get_quic_transport_parameters(), Some(server_params)); { let client_early = client.get_0rtt_keys().unwrap(); let server_early = server.get_0rtt_keys().unwrap(); assert!(equal_dir_keys(&client_early, &server_early)); } step(&mut server, &mut client).unwrap().unwrap(); step(&mut client, &mut server).unwrap().unwrap(); step(&mut server, &mut client).unwrap().unwrap(); assert!(client.is_early_data_accepted()); // 0-RTT rejection { let mut client_config = (*client_config).clone(); client_config.alpn_protocols = vec!["foo".into()]; let mut client = ClientSession::new_quic( &Arc::new(client_config), dns_name("localhost"), client_params.into(), ); let mut server = ServerSession::new_quic(&server_config, server_params.into()); step(&mut client, &mut server).unwrap(); assert_eq!(client.get_quic_transport_parameters(), Some(server_params)); assert!(client.get_0rtt_keys().is_some()); assert!(server.get_0rtt_keys().is_none()); step(&mut server, &mut client).unwrap().unwrap(); step(&mut client, &mut server).unwrap().unwrap(); step(&mut server, &mut client).unwrap().unwrap(); assert!(!client.is_early_data_accepted()); } // failed handshake let mut client = ClientSession::new_quic( &client_config, dns_name("example.com"), client_params.into(), ); let mut server = ServerSession::new_quic(&server_config, server_params.into()); step(&mut client, &mut server).unwrap(); step(&mut server, &mut client).unwrap().unwrap(); assert!(step(&mut server, &mut client).is_err()); assert_eq!( client.get_alert(), Some(rustls::internal::msgs::enums::AlertDescription::BadCertificate) ); } #[test] fn test_quic_rejects_missing_alpn() { let client_params = &b"client params"[..]; let server_params = &b"server params"[..]; for &kt in ALL_KEY_TYPES.iter() { let mut client_config = make_client_config(kt); client_config.versions = vec![ProtocolVersion::TLSv1_3]; client_config.alpn_protocols = vec!["bar".into()]; let client_config = Arc::new(client_config); let mut server_config = make_server_config(kt); server_config.versions = vec![ProtocolVersion::TLSv1_3]; server_config.alpn_protocols = vec!["foo".into()]; let server_config = Arc::new(server_config); let mut client = ClientSession::new_quic(&client_config, dns_name("localhost"), client_params.into()); let mut server = ServerSession::new_quic(&server_config, server_params.into()); assert_eq!(step(&mut client, &mut server).err().unwrap(), TLSError::NoApplicationProtocol); assert_eq!(server.get_alert(), Some(rustls::internal::msgs::enums::AlertDescription::NoApplicationProtocol)); } } } // mod test_quic #[test] fn test_client_does_not_offer_sha1() { use rustls::internal::msgs::{message::Message, message::MessagePayload, handshake::HandshakePayload, enums::HandshakeType, codec::Codec}; for kt in ALL_KEY_TYPES.iter() { for client_config in AllClientVersions::new(make_client_config(*kt)) { let (mut client, _) = make_pair_for_configs(client_config, make_server_config(*kt)); assert!(client.wants_write()); let mut buf = [0u8; 262144]; let sz = client.write_tls(&mut buf.as_mut()) .unwrap(); let mut msg = Message::read_bytes(&buf[..sz]) .unwrap(); assert!(msg.decode_payload()); assert!(msg.is_handshake_type(HandshakeType::ClientHello)); let client_hello = match msg.payload { MessagePayload::Handshake(hs) => match hs.payload { HandshakePayload::ClientHello(ch) => ch, _ => unreachable!() } _ => unreachable!() }; let sigalgs = client_hello.get_sigalgs_extension() .unwrap(); assert_eq!(sigalgs.contains(&SignatureScheme::RSA_PKCS1_SHA1), false, "sha1 unexpectedly offered"); } } } #[test] fn test_client_mtu_reduction() { fn collect_write_lengths(client: &mut ClientSession) -> Vec<usize> { let mut r = Vec::new(); let mut buf = [0u8; 128]; loop { let sz = client.write_tls(&mut buf.as_mut()) .unwrap(); r.push(sz); assert!(sz <= 64); if sz < 64 { break; } } r } for kt in ALL_KEY_TYPES.iter() { let mut client_config = make_client_config(*kt); client_config.set_mtu(&Some(64)); let mut client = ClientSession::new(&Arc::new(client_config), dns_name("localhost")); let writes = collect_write_lengths(&mut client); assert!(writes.iter().all(|x| *x <= 64)); assert!(writes.len() > 1); } } #[test] fn exercise_key_log_file_for_client() { let server_config = Arc::new(make_server_config(KeyType::RSA)); let mut client_config = make_client_config(KeyType::RSA); env::set_var("SSLKEYLOGFILE", "./sslkeylogfile.txt"); client_config.key_log = Arc::new(rustls::KeyLogFile::new()); for client_config in AllClientVersions::new(client_config) { let (mut client, mut server) = make_pair_for_arc_configs(&Arc::new(client_config), &server_config); assert_eq!(5, client.write(b"hello").unwrap()); do_handshake(&mut client, &mut server); transfer(&mut client, &mut server); server.process_new_packets().unwrap(); } } #[test] fn exercise_key_log_file_for_server() { let mut server_config = make_server_config(KeyType::RSA); env::set_var("SSLKEYLOGFILE", "./sslkeylogfile.txt"); server_config.key_log = Arc::new(rustls::KeyLogFile::new()); let server_config = Arc::new(server_config); for client_config in AllClientVersions::new(make_client_config(KeyType::RSA)) { let (mut client, mut server) = make_pair_for_arc_configs(&Arc::new(client_config), &server_config); assert_eq!(5, client.write(b"hello").unwrap()); do_handshake(&mut client, &mut server); transfer(&mut client, &mut server); server.process_new_packets().unwrap(); } } fn assert_lt(left: usize, right: usize) { if left >= right { panic!("expected {} < {}", left, right); } } #[test] fn session_types_are_not_huge() { // Arbitrary sizes assert_lt(mem::size_of::<ServerSession>(), 1600); assert_lt(mem::size_of::<ClientSession>(), 1600); } use rustls::internal::msgs::{message::Message, message::MessagePayload, handshake::HandshakePayload, handshake::ClientExtension}; #[test] fn test_server_rejects_duplicate_sni_names() { fn duplicate_sni_payload(msg: &mut Message) { if let MessagePayload::Handshake(hs) = &mut msg.payload { if let HandshakePayload::ClientHello(ch) = &mut hs.payload { for mut ext in ch.extensions.iter_mut() { if let ClientExtension::ServerName(snr) = &mut ext { snr.push(snr[0].clone()); } } } } } let (mut client, mut server) = make_pair(KeyType::RSA); transfer_altered(&mut client, duplicate_sni_payload, &mut server); assert_eq!(server.process_new_packets(), Err(TLSError::PeerMisbehavedError("ClientHello SNI contains duplicate name types".into()))); } #[test] fn test_server_rejects_empty_sni_extension() { fn empty_sni_payload(msg: &mut Message) { if let MessagePayload::Handshake(hs) = &mut msg.payload { if let HandshakePayload::ClientHello(ch) = &mut hs.payload { for mut ext in ch.extensions.iter_mut() { if let ClientExtension::ServerName(snr) = &mut ext { snr.clear(); } } } } } let (mut client, mut server) = make_pair(KeyType::RSA); transfer_altered(&mut client, empty_sni_payload, &mut server); assert_eq!(server.process_new_packets(), Err(TLSError::PeerMisbehavedError("ClientHello SNI did not contain a hostname".into()))); } #[test] fn test_server_rejects_clients_without_any_kx_group_overlap() { fn different_kx_group(msg: &mut Message) { if let MessagePayload::Handshake(hs) = &mut msg.payload { if let HandshakePayload::ClientHello(ch) = &mut hs.payload { for mut ext in ch.extensions.iter_mut() { if let ClientExtension::NamedGroups(ngs) = &mut ext { ngs.clear(); } if let ClientExtension::KeyShare(ks) = &mut ext { ks.clear(); } } } } } let (mut client, mut server) = make_pair(KeyType::RSA); transfer_altered(&mut client, different_kx_group, &mut server); assert_eq!(server.process_new_packets(), Err(TLSError::PeerIncompatibleError("no kx group overlap with client".into()))); }
35.709362
130
0.618778
d5e32eefc5be4b9235257ec2647135acd4a032c9
4,081
use byteorder::{BigEndian, ReadBytesExt}; use colors::{BitDepth, ColorType}; use crc::crc32; use error::PngError; use std::io::Cursor; #[derive(Debug, Clone, Copy)] /// Headers from the IHDR chunk of the image pub struct IhdrData { /// The width of the image in pixels pub width: u32, /// The height of the image in pixels pub height: u32, /// The color type of the image pub color_type: ColorType, /// The bit depth of the image pub bit_depth: BitDepth, /// The compression method used for this image (0 for DEFLATE) pub compression: u8, /// The filter mode used for this image (currently only 0 is valid) pub filter: u8, /// The interlacing mode of the image (0 = None, 1 = Adam7) pub interlaced: u8, } #[derive(Debug, PartialEq, Clone)] /// Options to use for performing operations on headers (such as stripping) pub enum Headers { /// None None, /// Some, with a list of 4-character chunk codes Some(Vec<String>), /// Headers that won't affect rendering (all but cHRM, gAMA, iCCP, sBIT, sRGB, bKGD, hIST, pHYs, sPLT) Safe, /// All non-critical headers All, } #[inline] pub fn file_header_is_valid(bytes: &[u8]) -> bool { let expected_header: [u8; 8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; *bytes == expected_header } pub fn parse_next_header(byte_data: &[u8], byte_offset: &mut usize, fix_errors: bool) -> Result<Option<(String, Vec<u8>)>, PngError> { let mut rdr = Cursor::new(byte_data.iter() .skip(*byte_offset) .take(4) .cloned() .collect::<Vec<u8>>()); let length: u32 = match rdr.read_u32::<BigEndian>() { Ok(x) => x, Err(_) => return Err(PngError::new("Invalid data found; unable to read PNG file")), }; *byte_offset += 4; let mut header_bytes: Vec<u8> = byte_data.iter().skip(*byte_offset).take(4).cloned().collect(); let header = match String::from_utf8(header_bytes.clone()) { Ok(x) => x, Err(_) => return Err(PngError::new("Invalid data found; unable to read PNG file")), }; if header == "IEND" { // End of data return Ok(None); } *byte_offset += 4; let data: Vec<u8> = byte_data.iter() .skip(*byte_offset) .take(length as usize) .cloned() .collect(); *byte_offset += length as usize; let mut rdr = Cursor::new(byte_data.iter() .skip(*byte_offset) .take(4) .cloned() .collect::<Vec<u8>>()); let crc: u32 = match rdr.read_u32::<BigEndian>() { Ok(x) => x, Err(_) => return Err(PngError::new("Invalid data found; unable to read PNG file")), }; *byte_offset += 4; header_bytes.extend_from_slice(&data); if !fix_errors && crc32::checksum_ieee(header_bytes.as_ref()) != crc { return Err(PngError::new(&format!("CRC Mismatch in {} header; May be recoverable by using --fix", header))); } Ok(Some((header, data))) } pub fn parse_ihdr_header(byte_data: &[u8]) -> Result<IhdrData, PngError> { let mut rdr = Cursor::new(&byte_data[0..8]); Ok(IhdrData { color_type: match byte_data[9] { 0 => ColorType::Grayscale, 2 => ColorType::RGB, 3 => ColorType::Indexed, 4 => ColorType::GrayscaleAlpha, 6 => ColorType::RGBA, _ => return Err(PngError::new("Unexpected color type in header")), }, bit_depth: match byte_data[8] { 1 => BitDepth::One, 2 => BitDepth::Two, 4 => BitDepth::Four, 8 => BitDepth::Eight, 16 => BitDepth::Sixteen, _ => return Err(PngError::new("Unexpected bit depth in header")), }, width: rdr.read_u32::<BigEndian>().unwrap(), height: rdr.read_u32::<BigEndian>().unwrap(), compression: byte_data[10], filter: byte_data[11], interlaced: byte_data[12], }) }
33.178862
106
0.574369
090035dfc592c02d4c33b5416b85228e3c34cef3
25,950
//! Driver for the LSM303DLHC 3D accelerometer and 3D magnetometer sensor. //! //! May be used with NineDof and Temperature //! //! I2C Interface //! //! <https://www.st.com/en/mems-and-sensors/lsm303dlhc.html> //! //! The syscall interface is described in [lsm303dlhc.md](https://github.com/tock/tock/tree/master/doc/syscalls/70006_lsm303dlhc.md) //! //! Usage //! ----- //! //! ```rust //! let mux_i2c = components::i2c::I2CMuxComponent::new(&stm32f3xx::i2c::I2C1) //! .finalize(components::i2c_mux_component_helper!()); //! //! let lsm303dlhc = components::lsm303dlhc::Lsm303dlhcI2CComponent::new() //! .finalize(components::lsm303dlhc_i2c_component_helper!(mux_i2c)); //! //! lsm303dlhc.configure( //! lsm303dlhc::Lsm303dlhcAccelDataRate::DataRate25Hz, //! false, //! lsm303dlhc::Lsm303dlhcScale::Scale2G, //! false, //! true, //! lsm303dlhc::Lsm303dlhcMagnetoDataRate::DataRate3_0Hz, //! lsm303dlhc::Lsm303dlhcRange::Range4_7G, //!); //! ``` //! //! NideDof Example //! //! ```rust //! let grant_cap = create_capability!(capabilities::MemoryAllocationCapability); //! let grant_ninedof = board_kernel.create_grant(&grant_cap); //! //! // use as primary NineDof Sensor //! let ninedof = static_init!( //! capsules::ninedof::NineDof<'static>, //! capsules::ninedof::NineDof::new(lsm303dlhc, grant_ninedof) //! ); //! //! hil::sensors::NineDof::set_client(lsm303dlhc, ninedof); //! //! // use as secondary NineDof Sensor //! let lsm303dlhc_secondary = static_init!( //! capsules::ninedof::NineDofNode<'static, &'static dyn hil::sensors::NineDof>, //! capsules::ninedof::NineDofNode::new(lsm303dlhc) //! ); //! ninedof.add_secondary_driver(lsm303dlhc_secondary); //! hil::sensors::NineDof::set_client(lsm303dlhc, ninedof); //! ``` //! //! Temperature Example //! //! ```rust //! let grant_cap = create_capability!(capabilities::MemoryAllocationCapability); //! let grant_temp = board_kernel.create_grant(&grant_cap); //! //! lsm303dlhc.configure( //! lsm303dlhc::Lsm303dlhcAccelDataRate::DataRate25Hz, //! false, //! lsm303dlhc::Lsm303dlhcScale::Scale2G, //! false, //! true, //! lsm303dlhc::Lsm303dlhcMagnetoDataRate::DataRate3_0Hz, //! lsm303dlhc::Lsm303dlhcRange::Range4_7G, //!); //! let temp = static_init!( //! capsules::temperature::TemperatureSensor<'static>, //! capsules::temperature::TemperatureSensor::new(lsm303dlhc, grant_temperature)); //! kernel::hil::sensors::TemperatureDriver::set_client(lsm303dlhc, temp); //! ``` //! //! Author: Alexandru Radovici <msg4alex@gmail.com> //! #![allow(non_camel_case_types)] use core::cell::Cell; use enum_primitive::cast::FromPrimitive; use enum_primitive::enum_from_primitive; use kernel::common::cells::{OptionalCell, TakeCell}; use kernel::common::registers::register_bitfields; use kernel::hil::i2c::{self, Error}; use kernel::hil::sensors; use kernel::{AppId, Callback, Driver, ReturnCode}; register_bitfields![u8, CTRL_REG1 [ /// Output data rate ODR OFFSET(4) NUMBITS(4) [], /// Low Power enable LPEN OFFSET(3) NUMBITS(1) [], /// Z enable ZEN OFFSET(2) NUMBITS(1) [], /// Y enable YEN OFFSET(1) NUMBITS(1) [], /// X enable XEN OFFSET(0) NUMBITS(1) [] ], CTRL_REG4 [ /// Block Data update BDU OFFSET(7) NUMBITS(2) [], /// Big Little Endian BLE OFFSET(6) NUMBITS(1) [], /// Full Scale selection FS OFFSET(4) NUMBITS(2) [], /// High Resolution HR OFFSET(3) NUMBITS(1) [], /// SPI Serial Interface SIM OFFSET(0) NUMBITS(1) [] ] ]; use crate::driver; /// Syscall driver number. pub const DRIVER_NUM: usize = driver::NUM::Lsm303dlch as usize; // Buffer to use for I2C messages pub static mut BUFFER: [u8; 8] = [0; 8]; /// Register values const REGISTER_AUTO_INCREMENT: u8 = 0x80; enum_from_primitive! { enum AccelerometerRegisters { CTRL_REG1 = 0x20, CTRL_REG4 = 0x23, OUT_X_L_A = 0x28, OUT_X_H_A = 0x29, OUT_Y_L_A = 0x2A, OUT_Y_H_A = 0x2B, OUT_Z_L_A = 0x2C, OUT_Z_H_A = 0x2D, } } enum_from_primitive! { enum MagnetometerRegisters { CRA_REG_M = 0x00, CRB_REG_M = 0x01, OUT_X_H_M = 0x03, OUT_X_L_M = 0x04, OUT_Z_H_M = 0x05, OUT_Z_L_M = 0x06, OUT_Y_H_M = 0x07, OUT_Y_L_M = 0x08, TEMP_OUT_H_M = 0x31, TEMP_OUT_L_M = 0x32, } } // Experimental const TEMP_OFFSET: i8 = 17; // Manual page Table 20, page 25 enum_from_primitive! { #[derive(Clone, Copy, PartialEq)] pub enum Lsm303dlhcAccelDataRate { Off = 0, DataRate1Hz = 1, DataRate10Hz = 2, DataRate25Hz = 3, DataRate50Hz = 4, DataRate100Hz = 5, DataRate200Hz = 6, DataRate400Hz = 7, LowPower1620Hz = 8, Normal1344LowPower5376Hz = 9, } } // Manual table 72, page 25 enum_from_primitive! { #[derive(Clone, Copy, PartialEq)] pub enum Lsm303dlhcMagnetoDataRate { DataRate0_75Hz = 0, DataRate1_5Hz = 1, DataRate3_0Hz = 2, DataRate7_5Hz = 3, DataRate15_0Hz = 4, DataRate30_0Hz = 5, DataRate75_0Hz = 6, DataRate220_0Hz = 7, } } enum_from_primitive! { #[derive(Clone, Copy, PartialEq)] pub enum Lsm303dlhcScale { Scale2G = 0, Scale4G = 1, Scale8G = 2, Scale16G = 3 } } // Manual table 27, page 27 const SCALE_FACTOR: [u8; 4] = [2, 4, 8, 16]; // Manual table 75, page 38 enum_from_primitive! { #[derive(Clone, Copy, PartialEq)] pub enum Lsm303dlhcRange { Range1G = 0, Range1_3G = 1, Range1_9G = 2, Range2_5G = 3, Range4_0G = 4, Range4_7G = 5, Range5_6G = 7, Range8_1 = 8, } } // Manual table 75, page 38 const RANGE_FACTOR_X_Y: [i16; 8] = [ 1000, // placeholder 1100, 855, 670, 450, 400, 330, 230, ]; // Manual table 75, page 38 const RANGE_FACTOR_Z: [i16; 8] = [ 1000, // placeholder 980, 760, 600, 400, 355, 295, 205, ]; #[derive(Clone, Copy, PartialEq)] enum State { Idle, IsPresent, SetPowerMode, SetScaleAndResolution, ReadAccelerationXYZ, SetTemperatureDataRate, SetRange, ReadTemperature, ReadMagnetometerXYZ, } pub struct Lsm303dlhcI2C<'a> { config_in_progress: Cell<bool>, i2c_accelerometer: &'a dyn i2c::I2CDevice, i2c_magnetometer: &'a dyn i2c::I2CDevice, callback: OptionalCell<Callback>, state: Cell<State>, accel_scale: Cell<Lsm303dlhcScale>, mag_range: Cell<Lsm303dlhcRange>, accel_high_resolution: Cell<bool>, mag_data_rate: Cell<Lsm303dlhcMagnetoDataRate>, accel_data_rate: Cell<Lsm303dlhcAccelDataRate>, low_power: Cell<bool>, temperature: Cell<bool>, buffer: TakeCell<'static, [u8]>, nine_dof_client: OptionalCell<&'a dyn sensors::NineDofClient>, temperature_client: OptionalCell<&'a dyn sensors::TemperatureClient>, } impl<'a> Lsm303dlhcI2C<'a> { pub fn new( i2c_accelerometer: &'a dyn i2c::I2CDevice, i2c_magnetometer: &'a dyn i2c::I2CDevice, buffer: &'static mut [u8], ) -> Lsm303dlhcI2C<'a> { // setup and return struct Lsm303dlhcI2C { config_in_progress: Cell::new(false), i2c_accelerometer: i2c_accelerometer, i2c_magnetometer: i2c_magnetometer, callback: OptionalCell::empty(), state: Cell::new(State::Idle), accel_scale: Cell::new(Lsm303dlhcScale::Scale2G), mag_range: Cell::new(Lsm303dlhcRange::Range1G), accel_high_resolution: Cell::new(false), mag_data_rate: Cell::new(Lsm303dlhcMagnetoDataRate::DataRate0_75Hz), accel_data_rate: Cell::new(Lsm303dlhcAccelDataRate::DataRate1Hz), low_power: Cell::new(false), temperature: Cell::new(false), buffer: TakeCell::new(buffer), nine_dof_client: OptionalCell::empty(), temperature_client: OptionalCell::empty(), } } pub fn configure( &self, accel_data_rate: Lsm303dlhcAccelDataRate, low_power: bool, accel_scale: Lsm303dlhcScale, accel_high_resolution: bool, temperature: bool, mag_data_rate: Lsm303dlhcMagnetoDataRate, mag_range: Lsm303dlhcRange, ) { if self.state.get() == State::Idle { self.config_in_progress.set(true); self.accel_scale.set(accel_scale); self.accel_high_resolution.set(accel_high_resolution); self.temperature.set(temperature); self.mag_data_rate.set(mag_data_rate); self.mag_range.set(mag_range); self.accel_data_rate.set(accel_data_rate); self.low_power.set(low_power); self.set_power_mode(accel_data_rate, low_power); } } fn is_present(&self) { self.state.set(State::IsPresent); self.buffer.take().map(|buf| { // turn on i2c to send commands buf[0] = 0x0F; self.i2c_magnetometer.write_read(buf, 1, 1); }); } fn set_power_mode(&self, data_rate: Lsm303dlhcAccelDataRate, low_power: bool) { if self.state.get() == State::Idle { self.state.set(State::SetPowerMode); self.buffer.take().map(|buf| { buf[0] = AccelerometerRegisters::CTRL_REG1 as u8; buf[1] = (CTRL_REG1::ODR.val(data_rate as u8) + CTRL_REG1::LPEN.val(low_power as u8) + CTRL_REG1::ZEN::SET + CTRL_REG1::YEN::SET + CTRL_REG1::XEN::SET) .value; self.i2c_accelerometer.write(buf, 2); }); } } fn set_scale_and_resolution(&self, scale: Lsm303dlhcScale, high_resolution: bool) { if self.state.get() == State::Idle { self.state.set(State::SetScaleAndResolution); // TODO move these in completed self.accel_scale.set(scale); self.accel_high_resolution.set(high_resolution); self.buffer.take().map(|buf| { buf[0] = AccelerometerRegisters::CTRL_REG4 as u8; buf[1] = (CTRL_REG4::FS.val(scale as u8) + CTRL_REG4::HR.val(high_resolution as u8)) .value; self.i2c_accelerometer.write(buf, 2); }); } } fn read_acceleration_xyz(&self) { if self.state.get() == State::Idle { self.state.set(State::ReadAccelerationXYZ); self.buffer.take().map(|buf| { buf[0] = AccelerometerRegisters::OUT_X_L_A as u8 | REGISTER_AUTO_INCREMENT; self.i2c_accelerometer.write_read(buf, 1, 6); }); } } fn set_temperature_and_magneto_data_rate( &self, temperature: bool, data_rate: Lsm303dlhcMagnetoDataRate, ) { if self.state.get() == State::Idle { self.state.set(State::SetTemperatureDataRate); self.buffer.take().map(|buf| { buf[0] = MagnetometerRegisters::CRA_REG_M as u8; buf[1] = ((data_rate as u8) << 2) | if temperature { 1 << 7 } else { 0 }; self.i2c_magnetometer.write(buf, 2); }); } } fn set_range(&self, range: Lsm303dlhcRange) { if self.state.get() == State::Idle { self.state.set(State::SetRange); // TODO move these in completed self.mag_range.set(range); self.buffer.take().map(|buf| { buf[0] = MagnetometerRegisters::CRB_REG_M as u8; buf[1] = (range as u8) << 5; buf[2] = 0; self.i2c_magnetometer.write(buf, 3); }); } } fn read_temperature(&self) { if self.state.get() == State::Idle { self.state.set(State::ReadTemperature); self.buffer.take().map(|buf| { buf[0] = MagnetometerRegisters::TEMP_OUT_H_M as u8; self.i2c_magnetometer.write_read(buf, 1, 2); }); } } fn read_magnetometer_xyz(&self) { if self.state.get() == State::Idle { self.state.set(State::ReadMagnetometerXYZ); self.buffer.take().map(|buf| { buf[0] = MagnetometerRegisters::OUT_X_H_M as u8; self.i2c_magnetometer.write_read(buf, 1, 6); }); } } } impl i2c::I2CClient for Lsm303dlhcI2C<'_> { fn command_complete(&self, buffer: &'static mut [u8], error: Error) { match self.state.get() { State::IsPresent => { let present = if error == Error::CommandComplete && buffer[0] == 60 { true } else { false }; self.callback.map(|callback| { callback.schedule(if present { 1 } else { 0 }, 0, 0); }); self.buffer.replace(buffer); self.state.set(State::Idle); } State::SetPowerMode => { let set_power = error == Error::CommandComplete; self.callback.map(|callback| { callback.schedule(if set_power { 1 } else { 0 }, 0, 0); }); self.buffer.replace(buffer); self.state.set(State::Idle); if self.config_in_progress.get() { self.set_scale_and_resolution( self.accel_scale.get(), self.accel_high_resolution.get(), ); } } State::SetScaleAndResolution => { let set_scale_and_resolution = error == Error::CommandComplete; self.callback.map(|callback| { callback.schedule(if set_scale_and_resolution { 1 } else { 0 }, 0, 0); }); self.buffer.replace(buffer); self.state.set(State::Idle); if self.config_in_progress.get() { self.set_temperature_and_magneto_data_rate( self.temperature.get(), self.mag_data_rate.get(), ); } } State::ReadAccelerationXYZ => { let mut x: usize = 0; let mut y: usize = 0; let mut z: usize = 0; let values = if error == Error::CommandComplete { self.nine_dof_client.map(|client| { // compute using only integers let scale_factor = self.accel_scale.get() as usize; x = (((buffer[0] as i16 | ((buffer[1] as i16) << 8)) as i32) * (SCALE_FACTOR[scale_factor] as i32) * 1000 / 32768) as usize; y = (((buffer[2] as i16 | ((buffer[3] as i16) << 8)) as i32) * (SCALE_FACTOR[scale_factor] as i32) * 1000 / 32768) as usize; z = (((buffer[4] as i16 | ((buffer[5] as i16) << 8)) as i32) * (SCALE_FACTOR[scale_factor] as i32) * 1000 / 32768) as usize; client.callback(x, y, z); }); x = (buffer[0] as i16 | ((buffer[1] as i16) << 8)) as usize; y = (buffer[2] as i16 | ((buffer[3] as i16) << 8)) as usize; z = (buffer[4] as i16 | ((buffer[5] as i16) << 8)) as usize; true } else { self.nine_dof_client.map(|client| { client.callback(0, 0, 0); }); false }; if values { self.callback.map(|callback| { callback.schedule(x, y, z); }); } else { self.callback.map(|callback| { callback.schedule(0, 0, 0); }); } self.buffer.replace(buffer); self.state.set(State::Idle); } State::SetTemperatureDataRate => { let set_temperature_and_magneto_data_rate = error == Error::CommandComplete; self.callback.map(|callback| { callback.schedule( if set_temperature_and_magneto_data_rate { 1 } else { 0 }, 0, 0, ); }); self.buffer.replace(buffer); self.state.set(State::Idle); if self.config_in_progress.get() { self.set_range(self.mag_range.get()); } } State::SetRange => { let set_range = error == Error::CommandComplete; self.callback.map(|callback| { callback.schedule(if set_range { 1 } else { 0 }, 0, 0); }); if self.config_in_progress.get() { self.config_in_progress.set(false); } self.buffer.replace(buffer); self.state.set(State::Idle); } State::ReadTemperature => { let mut temp: usize = 0; let values = if error == Error::CommandComplete { temp = ((buffer[1] as i16 | ((buffer[0] as i16) << 8)) >> 4) as usize; self.temperature_client.map(|client| { client.callback((temp as i16 / 8 + TEMP_OFFSET as i16) as usize); }); true } else { self.temperature_client.map(|client| { client.callback(0); }); false }; if values { self.callback.map(|callback| { callback.schedule(temp, 0, 0); }); } else { self.callback.map(|callback| { callback.schedule(0, 0, 0); }); } self.buffer.replace(buffer); self.state.set(State::Idle); } State::ReadMagnetometerXYZ => { let mut x: usize = 0; let mut y: usize = 0; let mut z: usize = 0; let values = if error == Error::CommandComplete { self.nine_dof_client.map(|client| { // compute using only integers let range = self.mag_range.get() as usize; x = (((buffer[1] as i16 | ((buffer[0] as i16) << 8)) as i32) * 100 / RANGE_FACTOR_X_Y[range] as i32) as usize; z = (((buffer[3] as i16 | ((buffer[2] as i16) << 8)) as i32) * 100 / RANGE_FACTOR_X_Y[range] as i32) as usize; y = (((buffer[5] as i16 | ((buffer[4] as i16) << 8)) as i32) * 100 / RANGE_FACTOR_Z[range] as i32) as usize; client.callback(x, y, z); }); x = ((buffer[1] as u16 | ((buffer[0] as u16) << 8)) as i16) as usize; z = ((buffer[3] as u16 | ((buffer[2] as u16) << 8)) as i16) as usize; y = ((buffer[5] as u16 | ((buffer[4] as u16) << 8)) as i16) as usize; true } else { self.nine_dof_client.map(|client| { client.callback(0, 0, 0); }); false }; if values { self.callback.map(|callback| { callback.schedule(x, y, z); }); } else { self.callback.map(|callback| { callback.schedule(0, 0, 0); }); } self.buffer.replace(buffer); self.state.set(State::Idle); } _ => { self.buffer.replace(buffer); } } } } impl Driver for Lsm303dlhcI2C<'_> { fn command(&self, command_num: usize, data1: usize, data2: usize, _: AppId) -> ReturnCode { match command_num { 0 => ReturnCode::SUCCESS, // Check is sensor is correctly connected 1 => { if self.state.get() == State::Idle { self.is_present(); ReturnCode::SUCCESS } else { ReturnCode::EBUSY } } // Set Accelerometer Power Mode 2 => { if self.state.get() == State::Idle { if let Some(data_rate) = Lsm303dlhcAccelDataRate::from_usize(data1) { self.set_power_mode(data_rate, if data2 != 0 { true } else { false }); ReturnCode::SUCCESS } else { ReturnCode::EINVAL } } else { ReturnCode::EBUSY } } // Set Accelerometer Scale And Resolution 3 => { if self.state.get() == State::Idle { if let Some(scale) = Lsm303dlhcScale::from_usize(data1) { self.set_scale_and_resolution(scale, if data2 != 0 { true } else { false }); ReturnCode::SUCCESS } else { ReturnCode::EINVAL } } else { ReturnCode::EBUSY } } // Set Magnetometer Temperature Enable and Data Rate 4 => { if self.state.get() == State::Idle { if let Some(data_rate) = Lsm303dlhcMagnetoDataRate::from_usize(data1) { self.set_temperature_and_magneto_data_rate( if data2 != 0 { true } else { false }, data_rate, ); ReturnCode::SUCCESS } else { ReturnCode::EINVAL } } else { ReturnCode::EBUSY } } // Set Magnetometer Range 5 => { if self.state.get() == State::Idle { if let Some(range) = Lsm303dlhcRange::from_usize(data1) { self.set_range(range); ReturnCode::SUCCESS } else { ReturnCode::EINVAL } } else { ReturnCode::EBUSY } } // Read Acceleration XYZ 6 => { if self.state.get() == State::Idle { self.read_acceleration_xyz(); ReturnCode::SUCCESS } else { ReturnCode::EBUSY } } // Read Temperature 7 => { if self.state.get() == State::Idle { self.read_temperature(); ReturnCode::SUCCESS } else { ReturnCode::EBUSY } } // Read Mangetometer XYZ 8 => { if self.state.get() == State::Idle { self.read_magnetometer_xyz(); ReturnCode::SUCCESS } else { ReturnCode::EBUSY } } // default _ => ReturnCode::ENOSUPPORT, } } fn subscribe( &self, subscribe_num: usize, callback: Option<Callback>, _app_id: AppId, ) -> ReturnCode { match subscribe_num { 0 /* set the one shot callback */ => { self.callback.insert (callback); ReturnCode::SUCCESS }, // default _ => ReturnCode::ENOSUPPORT, } } } impl<'a> sensors::NineDof<'a> for Lsm303dlhcI2C<'a> { fn set_client(&self, nine_dof_client: &'a dyn sensors::NineDofClient) { self.nine_dof_client.replace(nine_dof_client); } fn read_accelerometer(&self) -> ReturnCode { if self.state.get() == State::Idle { self.read_acceleration_xyz(); ReturnCode::SUCCESS } else { ReturnCode::EBUSY } } fn read_magnetometer(&self) -> ReturnCode { if self.state.get() == State::Idle { self.read_magnetometer_xyz(); ReturnCode::SUCCESS } else { ReturnCode::EBUSY } } } impl<'a> sensors::TemperatureDriver<'a> for Lsm303dlhcI2C<'a> { fn set_client(&self, temperature_client: &'a dyn sensors::TemperatureClient) { self.temperature_client.replace(temperature_client); } fn read_temperature(&self) -> ReturnCode { if self.state.get() == State::Idle { self.read_temperature(); ReturnCode::SUCCESS } else { ReturnCode::EBUSY } } }
33.965969
132
0.498882
abb77af52801bcf93a47c536216e82662cba8bde
793
use derive_more::From; use hedera::TransactionReceipt; use pyo3::prelude::*; #[pyclass(name = TransactionReceipt)] #[derive(From)] pub struct PyTransactionReceipt { pub(crate) inner: TransactionReceipt, } #[pymethods] impl PyTransactionReceipt { #[getter] pub fn status(&self) -> PyResult<u8> { Ok(self.inner.status as u8) } #[getter] pub fn account_id(&self) -> PyResult<Option<String>> { Ok(self.inner.account_id.as_ref().map(|id| id.to_string())) } #[getter] pub fn contract_id(&self) -> PyResult<Option<String>> { Ok(self.inner.contract_id.as_ref().map(|id| id.to_string())) } #[getter] pub fn file_id(&self) -> PyResult<Option<String>> { Ok(self.inner.file_id.as_ref().map(|id| id.to_string())) } }
24.030303
68
0.6343
22e9c77801f2ab328f0c871a265437fc538e658d
7,153
/// Test that \p pattern fails to parse with default flags. pub fn test_parse_fails(pattern: &str) { let res = regress::Regex::new(pattern); assert!(res.is_err(), "Pattern should not have parsed: {}", pattern); } /// Format a Match by inserting commas between all capture groups. fn format_match(r: &regress::Match, input: &str) -> String { let mut result = input[r.range()].to_string(); for cg in r.captures.iter() { result.push(','); if let Some(cg) = cg { result.push_str(&input[cg.clone()]) } } result } pub trait StringTestHelpers { /// "Fluent" style helper for testing that a String is equal to a str. fn test_eq(&self, s: &str); } impl StringTestHelpers for String { fn test_eq(&self, rhs: &str) { assert_eq!(self.as_str(), rhs) } } pub trait VecTestHelpers { /// "Fluent" style helper for testing that a Vec<&str> is equal to a /// Vec<&str>. fn test_eq(&self, rhs: Vec<&str>); } impl VecTestHelpers for Vec<&str> { fn test_eq(&self, rhs: Vec<&str>) { assert_eq!(*self, rhs) } } /// A compiled regex which remembers a TestConfig. #[derive(Debug, Clone)] pub struct TestCompiledRegex { re: regress::Regex, tc: TestConfig, } impl TestCompiledRegex { /// Search for self in \p input, returning a list of all matches. pub fn matches<'a, 'b>(&'a self, input: &'b str, start: usize) -> Vec<regress::Match> { use regress::backends as rbe; match (self.tc.use_ascii(input), self.tc.backend) { (true, Backend::PikeVM) => { rbe::find::<rbe::PikeVMExecutor>(&self.re, input, start).collect() } (false, Backend::PikeVM) => { rbe::find::<rbe::PikeVMExecutor>(&self.re, input, start).collect() } (true, Backend::Backtracking) => { rbe::find_ascii::<rbe::BacktrackExecutor>(&self.re, input, start).collect() } (false, Backend::Backtracking) => { rbe::find::<rbe::BacktrackExecutor>(&self.re, input, start).collect() } } } /// Search for self in \p input, returning the first Match, or None if /// none. pub fn find(&self, input: &str) -> Option<regress::Match> { self.matches(input, 0).into_iter().next() } /// Match against a string, returning the first formatted match. pub fn match1f(&self, input: &str) -> String { match self.find(input) { Some(m) => format_match(&m, input), None => panic!("Failed to match {}", input), } } /// Match against a string, returning the match as a Vec containing None /// for unmatched groups, or the matched strings. pub fn match1_vec<'a, 'b>(&'a self, input: &'b str) -> Vec<Option<&'b str>> { let mut result = Vec::new(); let m: regress::Match = self.find(input).expect("Failed to match"); result.push(Some(&input[m.range()])); for cr in m.captures { result.push(cr.map(|r| &input[r])); } result } /// Test that matching against \p input fails. pub fn test_fails(&self, input: &str) { assert!(self.find(input).is_none(), "Should not have matched") } /// Test that matching against \p input succeeds. pub fn test_succeeds(&self, input: &str) { assert!(self.find(input).is_some(), "Should have matched") } /// Return a list of all non-overlapping total match ranges from a given /// start. pub fn match_all_from<'a, 'b>(&'a self, input: &'b str, start: usize) -> Vec<regress::Range> { self.matches(input, start) .into_iter() .map(move |m| m.range()) .collect() } /// Return a list of all non-overlapping matches. pub fn match_all<'a, 'b>(&'a self, input: &'b str) -> Vec<&'b str> { self.matches(input, 0) .into_iter() .map(move |m| &input[m.range()]) .collect() } /// Collect all matches into a String, separated by commas. pub fn run_global_match(&self, input: &str) -> String { self.matches(input, 0) .into_iter() .map(move |m| format_match(&m, input)) .collect::<Vec<String>>() .join(",") } } /// Our backend types. #[derive(Debug, Copy, Clone)] enum Backend { PikeVM, Backtracking, } /// Description of how to test a regex. #[derive(Debug, Copy, Clone)] pub struct TestConfig { // Whether to prefer ASCII forms if the input is ASCII. ascii: bool, // Whether to optimize. optimize: bool, // Which backed to use. backend: Backend, } impl TestConfig { /// Whether to use ASCII for this input. pub fn use_ascii(&self, s: &str) -> bool { self.ascii && s.is_ascii() } /// Compile a pattern to a regex, with default flags. pub fn compile(&self, pattern: &str) -> TestCompiledRegex { self.compilef(pattern, "") } /// Compile a pattern to a regex, with given flags. pub fn compilef(&self, pattern: &str, flags_str: &str) -> TestCompiledRegex { let mut flags = regress::Flags::from(flags_str); flags.no_opt = !self.optimize; let re = regress::Regex::with_flags(pattern, flags); assert!( re.is_ok(), "Failed to parse! flags: {} pattern: {}, error: {}", flags_str, pattern, re.unwrap_err() ); TestCompiledRegex { re: re.unwrap(), tc: *self, } } /// Test that \p pattern and \p flags successfully parses, and matches /// \p input. pub fn test_match_succeeds(&self, pattern: &str, flags_str: &str, input: &str) { let cr = self.compilef(pattern, flags_str); cr.test_succeeds(input) } /// Test that \p pattern and \p flags successfully parses, and does not /// match \p input. pub fn test_match_fails(&self, pattern: &str, flags_str: &str, input: &str) { let cr = self.compilef(pattern, flags_str); cr.test_fails(input) } } /// Invoke \p F with each test config, in turn. pub fn test_with_configs<F>(func: F) where F: Fn(TestConfig), { // Note we wish to be able to determine the TestConfig from the line number. // Also note that optimizations are not supported for PikeVM backend, as it // doesn't implement Loop1CharBody. func(TestConfig { ascii: true, optimize: false, backend: Backend::PikeVM, }); func(TestConfig { ascii: false, optimize: false, backend: Backend::PikeVM, }); func(TestConfig { ascii: true, optimize: false, backend: Backend::Backtracking, }); func(TestConfig { ascii: false, optimize: false, backend: Backend::Backtracking, }); func(TestConfig { ascii: true, optimize: true, backend: Backend::Backtracking, }); func(TestConfig { ascii: false, optimize: true, backend: Backend::Backtracking, }); }
29.92887
98
0.575003
5d61de3e09cfd24589da00963ebfbf6f489dc0cc
8,387
use crate::common::Direction; use crate::framework::error::GameResult; use crate::npc::NPC; use crate::rng::RNG; use crate::shared_game_state::SharedGameState; use crate::stage::{Stage, BackgroundType}; impl NPC { pub(crate) fn tick_n001_experience(&mut self, state: &mut SharedGameState, stage: &mut Stage) -> GameResult { if stage.data.background_type == BackgroundType::Scrolling || stage.data.background_type == BackgroundType::OutsideWind { if self.action_num == 0 { self.action_num = 1; self.vel_x = self.rng.range(-0x80..0x80) as i32; self.vel_y = self.rng.range(-0x7f..0x100) as i32; } self.vel_x -= 0x8; if self.x < 80 * 0x200 { self.cond.set_alive(false); return Ok(()); } if self.vel_x < -0x600 { self.vel_x = -0x600; } if self.flags.hit_left_wall() { self.vel_x = 0x100; } if self.flags.hit_top_wall() { self.vel_y = 0x40; } if self.flags.hit_bottom_wall() { self.vel_y = -0x40; } } else { if self.action_num == 0 { self.action_num = 1; self.anim_num = self.rng.range(0..4) as u16; self.vel_x = self.rng.range(-0x200..0x200) as i32; self.vel_y = self.rng.range(-0x400..0) as i32; self.direction = if self.rng.range(0..1) != 0 { Direction::Left } else { Direction::Right }; } self.vel_y += if self.flags.in_water() { 0x15 } else { 0x2a }; if self.flags.hit_left_wall() && self.vel_x < 0 { self.vel_x = -self.vel_x; } if self.flags.hit_right_wall() && self.vel_x > 0 { self.vel_x = -self.vel_x; } if self.flags.hit_top_wall() && self.vel_y < 0 { self.vel_y = -self.vel_y; } if self.flags.hit_bottom_wall() { state.sound_manager.play_sfx(45); self.vel_y = -0x280; self.vel_x = 2 * self.vel_x / 3; } if self.flags.hit_left_wall() || self.flags.hit_right_wall() || self.flags.hit_bottom_wall() { state.sound_manager.play_sfx(45); self.action_counter2 += 1; if self.action_counter2 > 2 { self.vel_y -= 0x200; } } else { self.action_counter2 = 0; } self.vel_x = self.vel_x.clamp(-0x5ff, 0x5ff); self.vel_y = self.vel_y.clamp(-0x5ff, 0x5ff); } self.x += self.vel_x; self.y += self.vel_y; self.anim_counter += 1; if self.direction == Direction::Left { if self.anim_counter > 2 { self.anim_counter = 0; self.anim_num += 1; if self.anim_num > 5 { self.anim_num = 0; } } } else if self.anim_counter > 2 { self.anim_counter = 0; if self.anim_num > 0 { self.anim_num -= 1; } else { self.anim_num = 5; } } self.anim_rect = state.constants.npc.n001_experience[self.anim_num as usize]; if self.action_num != 0 { if self.exp >= 20 { self.anim_rect.top += 32; self.anim_rect.bottom += 32; } else if self.exp >= 5 { self.anim_rect.top += 16; self.anim_rect.bottom += 16; } self.action_num = 1; } self.action_counter += 1; if self.action_counter > 500 && self.anim_num == 5 && self.anim_counter == 2 { self.cond.set_alive(false); return Ok(()); } if self.action_counter > 400 && (self.action_counter & 0x02) != 0 { self.anim_rect.left = 0; self.anim_rect.top = 0; self.anim_rect.right = 0; self.anim_rect.bottom = 0; } Ok(()) } pub(crate) fn tick_n086_missile_pickup(&mut self, state: &mut SharedGameState, stage: &mut Stage) -> GameResult { if self.direction == Direction::Left { self.anim_counter += 1; if self.anim_counter > 2 { self.anim_counter = 0; self.anim_num += 1; if self.anim_num > 1 { self.anim_num = 0; } } self.action_counter2 += 1; } if stage.data.background_type == BackgroundType::Scrolling || stage.data.background_type == BackgroundType::OutsideWind { if self.action_num == 0 { self.action_num = 1; self.vel_x = self.rng.range(0x7f..0x100) as i32; self.vel_y = self.rng.range(-0x20..0x20) as i32; } self.vel_x -= 0x08; if self.x < 80 * 0x200 { self.cond.set_alive(false) } if self.flags.hit_left_wall() { self.vel_x = 0x100; } if self.flags.hit_top_wall() { self.vel_y = 0x40; } if self.flags.hit_bottom_wall() { self.vel_y = -0x40; } self.x += self.vel_x; self.y += self.vel_y; } match self.exp { 1 => { self.anim_rect = state.constants.npc.n086_missile_pickup[self.anim_num as usize]; } 3 => { self.anim_rect = state.constants.npc.n086_missile_pickup[2 + self.anim_num as usize]; } _ => (), } if self.action_counter2 > 550 { self.cond.set_alive(false); } if self.action_counter2 > 500 && self.action_counter2 & 0x02 != 0 { self.anim_rect.right = self.anim_rect.left; self.anim_rect.bottom = self.anim_rect.top; } if self.action_counter2 > 547 { self.anim_rect = state.constants.npc.n086_missile_pickup[4]; } Ok(()) } pub(crate) fn tick_n087_heart_pickup(&mut self, state: &mut SharedGameState, stage: &mut Stage) -> GameResult { if self.direction == Direction::Left { self.anim_counter += 1; if self.anim_counter > 2 { self.anim_counter = 0; self.anim_num += 1; if self.anim_num > 1 { self.anim_num = 0; } } self.action_counter2 += 1; } if stage.data.background_type == BackgroundType::Scrolling || stage.data.background_type == BackgroundType::OutsideWind { if self.action_num == 0 { self.action_num = 1; self.vel_x = self.rng.range(0x7f..0x100) as i32; self.vel_y = self.rng.range(-0x20..0x20) as i32; } self.vel_x -= 0x08; if self.x < 80 * 0x200 { self.cond.set_alive(false) } if self.flags.hit_left_wall() { self.vel_x = 0x100; } if self.flags.hit_top_wall() { self.vel_y = 0x40; } if self.flags.hit_bottom_wall() { self.vel_y = -0x40; } self.x += self.vel_x; self.y += self.vel_y; } match self.exp { 2 => { self.anim_rect = state.constants.npc.n087_heart_pickup[self.anim_num as usize]; } 6 => { self.anim_rect = state.constants.npc.n087_heart_pickup[2 + self.anim_num as usize]; } _ => (), } if self.action_counter2 > 550 { self.cond.set_alive(false); } if self.action_counter2 > 500 && self.action_counter2 & 0x02 != 0 { self.anim_rect.right = self.anim_rect.left; self.anim_rect.bottom = self.anim_rect.top; } if self.action_counter2 > 547 { self.anim_rect = state.constants.npc.n087_heart_pickup[4]; } Ok(()) } }
30.277978
129
0.481459
4a58b8ed06adde35ee69d95804c583f1e953a382
3,695
// Copyright 2018-2021 Parity Technologies (UK) Ltd. // // 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 core::ops::{ Index, IndexMut, }; /// Stores the number of set bits for each 256-bits block in a compact `u8`. #[derive(Debug, Default, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub struct CountFree { /// Set bits per 256-bit chunk. counts: [u8; 32], /// Since with `u8` can only count up to 255 but there might be the need /// to count up to 256 bits for 256-bit chunks we need to store one extra /// bit per counter to determine filled chunks. full: FullMask, } impl Index<u8> for CountFree { type Output = u8; fn index(&self, index: u8) -> &Self::Output { &self.counts[index as usize] } } impl IndexMut<u8> for CountFree { fn index_mut(&mut self, index: u8) -> &mut Self::Output { &mut self.counts[index as usize] } } #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub struct FullMask(u32); impl FullMask { /// Returns `true` if the 256-bit chunk at the given index is full. pub fn is_full(self, index: u8) -> bool { assert!(index < 32); (self.0 >> (31 - index as u32)) & 0x01 == 1 } /// Sets the flag for the 256-bit chunk at the given index to `full`. pub fn set_full(&mut self, index: u8) { self.0 |= 1_u32 << (31 - index as u32); } /// Resets the flag for the 256-bit chunk at the given index to not `full`. pub fn reset_full(&mut self, index: u8) { self.0 &= !(1_u32 << (31 - index as u32)); } } impl CountFree { /// Returns the position of the first free `u8` in the free counts. /// /// Returns `None` if all counts are `0xFF`. pub fn position_first_zero(&self) -> Option<u8> { let i = (!self.full.0).leading_zeros(); if i == 32 { return None } Some(i as u8) } /// Increases the number of set bits for the given index. /// /// # Panics /// /// - If the given index is out of bounds. /// - If the increment would cause an overflow. pub fn inc(&mut self, index: usize) { assert!(index < 32, "index is out of bounds"); if self.counts[index] == !0 { self.full.set_full(index as u8); } else { self.counts[index] += 1; } } /// Decreases the number of set bits for the given index. /// /// Returns the new number of set bits. /// /// # Panics /// /// - If the given index is out of bounds. /// - If the decrement would cause an overflow. pub fn dec(&mut self, index: u8) -> u8 { assert!(index < 32, "index is out of bounds"); if self.full.is_full(index) { self.full.reset_full(index); } else { let new_value = self.counts[index as usize] .checked_sub(1) .expect("set bits decrement overflowed"); self.counts[index as usize] = new_value; } self.counts[index as usize] } }
31.853448
83
0.60406
eb815788fd634b992057929acd1941c0796abe39
356
mod with_compact; mod without_compact; use super::*; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::Atom; fn option(process: &Process, digits: u8) -> Term { process .tuple_from_slice(&[tag(), process.integer(digits).unwrap()]) .unwrap() } fn tag() -> Term { Atom::str_to_term("decimals") }
19.777778
69
0.662921
e9521940512d3e5ca5ff5eddf5a339e40b279687
2,379
use bytes::Bytes; use mini_redis::client; use tokio::sync::mpsc; use tokio::sync::oneshot; /// Multiple different commands are multiplexed over a single channel. #[derive(Debug)] enum Command { Get { key: String, resp: Responder<Option<Bytes>>, }, Set { key: String, val: Vec<u8>, resp: Responder<()>, }, } /// Provided by the requester and used by the manager task to send /// the command response back to the requester. type Responder<T> = oneshot::Sender<mini_redis::Result<T>>; #[tokio::main] async fn main() { // create a new channel with a capacity of most 32 let (tx, mut rx) = mpsc::channel(32); let tx2 = tx.clone(); // `move` the ownership of `rx` into the task let manager = tokio::spawn(async move { // establish a connection to the server let mut client = client::connect("127.0.0.1:6379").await.unwrap(); // start recerving messages while let Some(cmd) = rx.recv().await { match cmd { Command::Get { key, resp } => { let res = client.get(&key).await; // Ignore errors let _ = resp.send(res); } Command::Set { key, val, resp } => { let res = client.set(&key, val.into()).await; // Ignore errors let _ = resp.send(res); } } } }); let t1 = tokio::spawn(async move { let (resp_tx, resp_rx) = oneshot::channel(); let cmd = Command::Get { key: "hello".to_string(), resp: resp_tx, }; // Send the GET request tx.send(cmd).await.unwrap(); // Await the response let res = resp_rx.await; println!("GOT = {:?}", res); }); let t2 = tokio::spawn(async move { let (resp_tx, resp_rx) = oneshot::channel(); let cmd = Command::Set { key: "foo".to_string(), val: b"bar".to_vec(), resp: resp_tx, }; // Send the SET request tx2.send(cmd).await.unwrap(); // Await the response let res = resp_rx.await; println!("GOT = {:?}", res) }); t1.await.unwrap(); t2.await.unwrap(); manager.await.unwrap(); } // async operations are lazy...
26.730337
74
0.513241
22b9eb8e754453ea44d56f3669c8fbf1371e8c71
10,186
// 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. //! The compiler code necessary for `#[derive(Decodable)]`. See encodable.rs for more. use deriving; use deriving::generic::*; use deriving::generic::ty::*; use syntax::ast; use syntax::ast::{Expr, MetaItem, Mutability}; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; use syntax::parse::token::InternedString; use syntax::parse::token; use syntax::ptr::P; use syntax_pos::Span; pub fn expand_deriving_rustc_decodable(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Annotatable, push: &mut FnMut(Annotatable)) { expand_deriving_decodable_imp(cx, span, mitem, item, push, "rustc_serialize") } pub fn expand_deriving_decodable(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Annotatable, push: &mut FnMut(Annotatable)) { expand_deriving_decodable_imp(cx, span, mitem, item, push, "serialize") } fn expand_deriving_decodable_imp(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Annotatable, push: &mut FnMut(Annotatable), krate: &'static str) { if cx.crate_root != Some("std") { // FIXME(#21880): lift this requirement. cx.span_err(span, "this trait cannot be derived with #![no_std] \ or #![no_core]"); return; } let typaram = &*deriving::hygienic_type_parameter(item, "__D"); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: Path::new_(vec![krate, "Decodable"], None, vec![], true), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), is_unsafe: false, supports_unions: false, methods: vec![MethodDef { name: "decode", generics: LifetimeBounds { lifetimes: Vec::new(), bounds: vec![(typaram, vec![Path::new_(vec![krate, "Decoder"], None, vec![], true)])], }, explicit_self: None, args: vec![Ptr(Box::new(Literal(Path::new_local(typaram))), Borrowed(None, Mutability::Mutable))], ret_ty: Literal(Path::new_(pathvec_std!(cx, core::result::Result), None, vec!(Box::new(Self_), Box::new(Literal(Path::new_( vec![typaram, "Error"], None, vec![], false )))), true)), attributes: Vec::new(), is_unsafe: false, unify_fieldless_variants: false, combine_substructure: combine_substructure(Box::new(|a, b, c| { decodable_substructure(a, b, c, krate) })), }], associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) } fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure, krate: &str) -> P<Expr> { let decoder = substr.nonself_args[0].clone(); let recurse = vec![cx.ident_of(krate), cx.ident_of("Decodable"), cx.ident_of("decode")]; let exprdecode = cx.expr_path(cx.path_global(trait_span, recurse)); // throw an underscore in front to suppress unused variable warnings let blkarg = cx.ident_of("_d"); let blkdecoder = cx.expr_ident(trait_span, blkarg); return match *substr.fields { StaticStruct(_, ref summary) => { let nfields = match *summary { Unnamed(ref fields, _) => fields.len(), Named(ref fields) => fields.len(), }; let read_struct_field = cx.ident_of("read_struct_field"); let path = cx.path_ident(trait_span, substr.type_ident); let result = decode_static_fields(cx, trait_span, path, summary, |cx, span, name, field| { cx.expr_try(span, cx.expr_method_call(span, blkdecoder.clone(), read_struct_field, vec![cx.expr_str(span, name), cx.expr_usize(span, field), exprdecode.clone()])) }); let result = cx.expr_ok(trait_span, result); cx.expr_method_call(trait_span, decoder, cx.ident_of("read_struct"), vec![cx.expr_str(trait_span, substr.type_ident.name.as_str()), cx.expr_usize(trait_span, nfields), cx.lambda_expr_1(trait_span, result, blkarg)]) } StaticEnum(_, ref fields) => { let variant = cx.ident_of("i"); let mut arms = Vec::new(); let mut variants = Vec::new(); let rvariant_arg = cx.ident_of("read_enum_variant_arg"); for (i, &(ident, v_span, ref parts)) in fields.iter().enumerate() { variants.push(cx.expr_str(v_span, ident.name.as_str())); let path = cx.path(trait_span, vec![substr.type_ident, ident]); let decoded = decode_static_fields(cx, v_span, path, parts, |cx, span, _, field| { let idx = cx.expr_usize(span, field); cx.expr_try(span, cx.expr_method_call(span, blkdecoder.clone(), rvariant_arg, vec![idx, exprdecode.clone()])) }); arms.push(cx.arm(v_span, vec![cx.pat_lit(v_span, cx.expr_usize(v_span, i))], decoded)); } arms.push(cx.arm_unreachable(trait_span)); let result = cx.expr_ok(trait_span, cx.expr_match(trait_span, cx.expr_ident(trait_span, variant), arms)); let lambda = cx.lambda_expr(trait_span, vec![blkarg, variant], result); let variant_vec = cx.expr_vec(trait_span, variants); let variant_vec = cx.expr_addr_of(trait_span, variant_vec); let result = cx.expr_method_call(trait_span, blkdecoder, cx.ident_of("read_enum_variant"), vec![variant_vec, lambda]); cx.expr_method_call(trait_span, decoder, cx.ident_of("read_enum"), vec![cx.expr_str(trait_span, substr.type_ident.name.as_str()), cx.lambda_expr_1(trait_span, result, blkarg)]) } _ => cx.bug("expected StaticEnum or StaticStruct in derive(Decodable)"), }; } /// Create a decoder for a single enum variant/struct: /// - `outer_pat_path` is the path to this enum variant/struct /// - `getarg` should retrieve the `usize`-th field with name `@str`. fn decode_static_fields<F>(cx: &mut ExtCtxt, trait_span: Span, outer_pat_path: ast::Path, fields: &StaticFields, mut getarg: F) -> P<Expr> where F: FnMut(&mut ExtCtxt, Span, InternedString, usize) -> P<Expr> { match *fields { Unnamed(ref fields, is_tuple) => { let path_expr = cx.expr_path(outer_pat_path); if !is_tuple { path_expr } else { let fields = fields.iter() .enumerate() .map(|(i, &span)| { getarg(cx, span, token::intern_and_get_ident(&format!("_field{}", i)), i) }) .collect(); cx.expr_call(trait_span, path_expr, fields) } } Named(ref fields) => { // use the field's span to get nicer error messages. let fields = fields.iter() .enumerate() .map(|(i, &(ident, span))| { let arg = getarg(cx, span, ident.name.as_str(), i); cx.field_imm(span, ident, arg) }) .collect(); cx.expr_struct(trait_span, outer_pat_path, fields) } } }
44.675439
99
0.456803
f72759a8394ab10ac18efee9330380161a33b88e
1,368
use rocket::http; use rocket::request; use rocket::Outcome; use rocket::State; use nats::Client; use r2d2::PooledConnection; use r2d2_nats::NatsConnectionManager; use std::ops::Deref; use std::ops::DerefMut; use std::env; type Pool = r2d2::Pool<NatsConnectionManager>; pub fn init_pool() -> Pool { let manager = NatsConnectionManager::new(nats_url()) .expect("connection manager"); return r2d2::Pool::builder() .max_size(15) .build(manager) .unwrap(); } fn nats_url() -> String { env::var("NATS_ADDRESS") .expect("NATS_ADDRESS environment variable must be set") } pub struct NatsConnection(pub PooledConnection<NatsConnectionManager>); impl<'a, 'r> request::FromRequest<'a, 'r> for NatsConnection { type Error = (); fn from_request(request: &'a request::Request<'r>) -> request::Outcome<NatsConnection, ()> { let pool = request.guard::<State<Pool>>()?; match pool.get() { Ok(conn) => Outcome::Success(NatsConnection(conn)), Err(_) => Outcome::Failure((http::Status::ServiceUnavailable, ())), } } } impl Deref for NatsConnection { type Target = Client; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for NatsConnection { fn deref_mut(&mut self) -> &mut nats::Client { &mut self.0 } }
23.586207
96
0.626462
38956aede49132c44bd5bfafd6e59b29c7d01961
1,252
//! Borp: A re-implementation of Borg in Rust //! //! There are several purposes here. One is to have a project of reasonable complexity to work on //! in Rust. Another is to understand how Borg works better. Ultimately, this may become a useful //! alternative implementation itself. //! //! But, to start with, we're going to just try decoding the borg backups themselves. extern crate serde_json; extern crate borp; // Things that will need to be implemented: // - [X] Lock // - [ ] Config file // - [ ] Repository // - [ ] LoggedIO // - [ ] Index files // - [ ] Manifest use borp::lock::Lock; use std::fs::File; use std::io::Read; use std::path::Path; fn main() { let mut lock = Lock::new(Path::new(".").to_path_buf(), "lock".to_string()); lock.lock_shared().unwrap(); println!("lock: {:?}", lock); { use std::process::Command; Command::new("cat").arg("lock.roster").status().unwrap(); Command::new("echo").status().unwrap(); } let mut data: Vec<u8> = vec![]; File::open("config").unwrap().read_to_end(&mut data).unwrap(); println!("parse: {:?}", borp::config::entries(&data)); // let conf: toml::Value = toml::from_slice(&data).unwrap(); // println!("config: {:?}", conf); }
30.536585
99
0.621406
c18df83786e1a42fe09fa4e5bba9c8f376428203
1,500
use rand::Rng; use futures::AsyncWriteExt; use smol::{fs::File, io::BufWriter}; use std::error::Error; use crate::io::{ClientId, Transaction, TransactionId}; const LINES: usize = 10000000; pub async fn generate_random(file_out: &str) -> Result<(), Box<dyn Error>> { let mut wri = BufWriter::new(File::create(file_out).await?); wri.write(Transaction::header().as_bytes()).await?; wri.write(b"\n").await?; let mut rng = rand::thread_rng(); for _ in 0..LINES { let transaction = match rng.gen_range(0..5) { 0 => Transaction::Deposit { client: ClientId(rng.gen()), tx: TransactionId(rng.gen()), amount: rng.gen(), }, 1 => Transaction::Withdrawal { client: ClientId(rng.gen()), tx: TransactionId(rng.gen()), amount: rng.gen(), }, 2 => Transaction::Dispute { client: ClientId(rng.gen()), tx: TransactionId(rng.gen()), }, 3 => Transaction::Resolve { client: ClientId(rng.gen()), tx: TransactionId(rng.gen()), }, 4 => Transaction::ChargeBack { client: ClientId(rng.gen()), tx: TransactionId(rng.gen()), }, _ => unreachable!(), }; wri.write(transaction.to_csv().as_bytes()).await?; wri.write(b"\n").await?; } Ok(()) }
30
76
0.502
62f80e1c18ebfa890660eaa2bf5b82952666f335
20,079
//! SocketCAN support. //! //! The Linux kernel supports using CAN-devices through a network-like API //! (see https://www.kernel.org/doc/Documentation/networking/can.txt). This //! crate allows easy access to this functionality without having to wrestle //! libc calls. //! //! # An introduction to CAN //! //! The CAN bus was originally designed to allow microcontrollers inside a //! vehicle to communicate over a single shared bus. Messages called //! *frames* are multicast to all devices on the bus. //! //! Every frame consists of an ID and a payload of up to 8 bytes. If two //! devices attempt to send a frame at the same time, the device with the //! higher ID will notice the conflict, stop sending and reattempt to sent its //! frame in the next time slot. This means that the lower the ID, the higher //! the priority. Since most devices have a limited buffer for outgoing frames, //! a single device with a high priority (== low ID) can block communication //! on that bus by sending messages too fast. //! //! The Linux socketcan subsystem makes the CAN bus available as a regular //! networking device. Opening an network interface allows receiving all CAN //! messages received on it. A device CAN be opened multiple times, every //! client will receive all CAN frames simultaneously. //! //! Similarly, CAN frames can be sent to the bus by multiple client //! simultaneously as well. //! //! # Hardware and more information //! //! More information on CAN [can be found on Wikipedia](). When not running on //! an embedded platform with already integrated CAN components, //! [Thomas Fischl's USBtin](http://www.fischl.de/usbtin/) (see //! [section 2.4](http://www.fischl.de/usbtin/#socketcan)) is one of many ways //! to get started. //! //! # RawFd //! //! Raw access to the underlying file descriptor and construction through //! is available through the `AsRawFd`, `IntoRawFd` and `FromRawFd` //! implementations. // clippy: do not warn about things like "SocketCAN" inside the docs #![cfg_attr(feature = "cargo-clippy", allow(doc_markdown))] extern crate byte_conv; extern crate hex; extern crate itertools; extern crate libc; extern crate netlink_rs; extern crate nix; extern crate try_from; mod err; pub use err::{CanError, CanErrorDecodingFailure}; pub mod dump; mod nl; mod util; #[cfg(test)] mod tests; use libc::{c_int, c_short, c_void, c_uint, c_ulong, socket, SOCK_RAW, close, bind, sockaddr, read, write, SOL_SOCKET, SO_RCVTIMEO, timespec, timeval, EINPROGRESS, SO_SNDTIMEO, time_t, suseconds_t, fcntl, F_GETFL, F_SETFL, O_NONBLOCK}; use itertools::Itertools; use nix::net::if_::if_nametoindex; pub use nl::CanInterface; use std::{error, fmt, io, time}; use std::mem::{size_of, uninitialized}; use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use util::{set_socket_option, set_socket_option_mult}; /// Check an error return value for timeouts. /// /// Due to the fact that timeouts are reported as errors, calling `read_frame` /// on a socket with a timeout that does not receive a frame in time will /// result in an error being returned. This trait adds a `should_retry` method /// to `Error` and `Result` to check for this condition. pub trait ShouldRetry { /// Check for timeout /// /// If `true`, the error is probably due to a timeout. fn should_retry(&self) -> bool; } impl ShouldRetry for io::Error { fn should_retry(&self) -> bool { match self.kind() { // EAGAIN, EINPROGRESS and EWOULDBLOCK are the three possible codes // returned when a timeout occurs. the stdlib already maps EAGAIN // and EWOULDBLOCK os WouldBlock io::ErrorKind::WouldBlock => true, // however, EINPROGRESS is also valid io::ErrorKind::Other => { if let Some(i) = self.raw_os_error() { i == EINPROGRESS } else { false } } _ => false, } } } impl<E: fmt::Debug> ShouldRetry for io::Result<E> { fn should_retry(&self) -> bool { if let Err(ref e) = *self { e.should_retry() } else { false } } } // constants stolen from C headers const AF_CAN: c_int = 29; const PF_CAN: c_int = 29; const CAN_RAW: c_int = 1; const SOL_CAN_BASE: c_int = 100; const SOL_CAN_RAW: c_int = SOL_CAN_BASE + CAN_RAW; const CAN_RAW_FILTER: c_int = 1; const CAN_RAW_ERR_FILTER: c_int = 2; const CAN_RAW_LOOPBACK: c_int = 3; const CAN_RAW_RECV_OWN_MSGS: c_int = 4; // unused: // const CAN_RAW_FD_FRAMES: c_int = 5; const CAN_RAW_JOIN_FILTERS: c_int = 6; // get timestamp in a struct timeval (us accuracy) // const SIOCGSTAMP: c_int = 0x8906; // get timestamp in a struct timespec (ns accuracy) const SIOCGSTAMPNS: c_int = 0x8907; /// if set, indicate 29 bit extended format pub const EFF_FLAG: u32 = 0x80000000; /// remote transmission request flag pub const RTR_FLAG: u32 = 0x40000000; /// error flag pub const ERR_FLAG: u32 = 0x20000000; /// valid bits in standard frame id pub const SFF_MASK: u32 = 0x000007ff; /// valid bits in extended frame id pub const EFF_MASK: u32 = 0x1fffffff; /// valid bits in error frame pub const ERR_MASK: u32 = 0x1fffffff; /// an error mask that will cause SocketCAN to report all errors pub const ERR_MASK_ALL: u32 = ERR_MASK; /// an error mask that will cause SocketCAN to silently drop all errors pub const ERR_MASK_NONE: u32 = 0; fn c_timeval_new(t: time::Duration) -> timeval { timeval { tv_sec: t.as_secs() as time_t, tv_usec: (t.subsec_nanos() / 1000) as suseconds_t, } } #[derive(Debug)] #[repr(C)] struct CanAddr { _af_can: c_short, if_index: c_int, // address familiy, rx_id: u32, tx_id: u32, } #[derive(Debug)] /// Errors opening socket pub enum CanSocketOpenError { /// Device could not be found LookupError(nix::Error), /// System error while trying to look up device name IOError(io::Error), } impl fmt::Display for CanSocketOpenError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { CanSocketOpenError::LookupError(ref e) => write!(f, "CAN Device not found: {}", e), CanSocketOpenError::IOError(ref e) => write!(f, "IO: {}", e), } } } impl error::Error for CanSocketOpenError { fn description(&self) -> &str { match *self { CanSocketOpenError::LookupError(_) => "can device not found", CanSocketOpenError::IOError(ref e) => e.description(), } } fn cause(&self) -> Option<&error::Error> { match *self { CanSocketOpenError::LookupError(ref e) => Some(e), CanSocketOpenError::IOError(ref e) => Some(e), } } } #[derive(Debug, Copy, Clone)] /// Error that occurs when creating CAN packets pub enum ConstructionError { /// CAN ID was outside the range of valid IDs IDTooLarge, /// More than 8 Bytes of payload data were passed in TooMuchData, } impl fmt::Display for ConstructionError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ConstructionError::IDTooLarge => write!(f, "CAN ID too large"), ConstructionError::TooMuchData => { write!(f, "Payload is larger than CAN maximum of 8 bytes") } } } } impl error::Error for ConstructionError { fn description(&self) -> &str { match *self { ConstructionError::IDTooLarge => "can id too large", ConstructionError::TooMuchData => "too much data", } } } impl From<nix::Error> for CanSocketOpenError { fn from(e: nix::Error) -> CanSocketOpenError { CanSocketOpenError::LookupError(e) } } impl From<io::Error> for CanSocketOpenError { fn from(e: io::Error) -> CanSocketOpenError { CanSocketOpenError::IOError(e) } } /// A socket for a CAN device. /// /// Will be closed upon deallocation. To close manually, use std::drop::Drop. /// Internally this is just a wrapped file-descriptor. #[derive(Debug)] pub struct CanSocket { fd: c_int, } impl CanSocket { /// Open a named CAN device. /// /// Usually the more common case, opens a socket can device by name, such /// as "vcan0" or "socan0". pub fn open(ifname: &str) -> Result<CanSocket, CanSocketOpenError> { let if_index = if_nametoindex(ifname)?; CanSocket::open_if(if_index) } /// Open CAN device by interface number. /// /// Opens a CAN device by kernel interface number. pub fn open_if(if_index: c_uint) -> Result<CanSocket, CanSocketOpenError> { let addr = CanAddr { _af_can: AF_CAN as c_short, if_index: if_index as c_int, rx_id: 0, // ? tx_id: 0, // ? }; // open socket let sock_fd; unsafe { sock_fd = socket(PF_CAN, SOCK_RAW, CAN_RAW); } if sock_fd == -1 { return Err(CanSocketOpenError::from(io::Error::last_os_error())); } // bind it let bind_rv; unsafe { let sockaddr_ptr = &addr as *const CanAddr; bind_rv = bind(sock_fd, sockaddr_ptr as *const sockaddr, size_of::<CanAddr>() as u32); } // FIXME: on fail, close socket (do not leak socketfds) if bind_rv == -1 { let e = io::Error::last_os_error(); unsafe { close(sock_fd); } return Err(CanSocketOpenError::from(e)); } Ok(CanSocket { fd: sock_fd }) } fn close(&mut self) -> io::Result<()> { unsafe { let rv = close(self.fd); if rv != -1 { return Err(io::Error::last_os_error()); } } Ok(()) } /// Change socket to non-blocking mode pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { // retrieve current flags let oldfl = unsafe { fcntl(self.fd, F_GETFL) }; if oldfl == -1 { return Err(io::Error::last_os_error()); } let newfl = if nonblocking { oldfl | O_NONBLOCK } else { oldfl & !O_NONBLOCK }; let rv = unsafe { fcntl(self.fd, F_SETFL, newfl) }; if rv != 0 { return Err(io::Error::last_os_error()); } Ok(()) } /// Sets the read timeout on the socket /// /// For convenience, the result value can be checked using /// `ShouldRetry::should_retry` when a timeout is set. pub fn set_read_timeout(&self, duration: time::Duration) -> io::Result<()> { set_socket_option(self.fd, SOL_SOCKET, SO_RCVTIMEO, &c_timeval_new(duration)) } /// Sets the write timeout on the socket pub fn set_write_timeout(&self, duration: time::Duration) -> io::Result<()> { set_socket_option(self.fd, SOL_SOCKET, SO_SNDTIMEO, &c_timeval_new(duration)) } /// Blocking read a single can frame. pub fn read_frame(&self) -> io::Result<CanFrame> { let mut frame = CanFrame { _id: 0, _data_len: 0, _pad: 0, _res0: 0, _res1: 0, _data: [0; 8], }; let read_rv = unsafe { let frame_ptr = &mut frame as *mut CanFrame; read(self.fd, frame_ptr as *mut c_void, size_of::<CanFrame>()) }; if read_rv as usize != size_of::<CanFrame>() { return Err(io::Error::last_os_error()); } Ok(frame) } /// Blocking read a single can frame with timestamp /// /// Note that reading a frame and retrieving the timestamp requires two /// consecutive syscalls. To avoid race conditions, exclusive access /// to the socket is enforce through requiring a `mut &self`. pub fn read_frame_with_timestamp(&mut self) -> io::Result<(CanFrame, time::SystemTime)> { let frame = self.read_frame()?; let mut ts: timespec; let rval = unsafe { // we initialize tv calling ioctl, passing this responsibility on ts = uninitialized(); libc::ioctl(self.fd, SIOCGSTAMPNS as c_ulong, &mut ts as *mut timespec) }; if rval == -1 { return Err(io::Error::last_os_error()); } Ok((frame, util::system_time_from_timespec(ts))) } /// Write a single can frame. /// /// Note that this function can fail with an `EAGAIN` error or similar. /// Use `write_frame_insist` if you need to be sure that the message got /// sent or failed. pub fn write_frame(&self, frame: &CanFrame) -> io::Result<()> { // not a mutable reference needed (see std::net::UdpSocket) for // a comparison // debug!("Sending: {:?}", frame); let write_rv = unsafe { let frame_ptr = frame as *const CanFrame; write(self.fd, frame_ptr as *const c_void, size_of::<CanFrame>()) }; if write_rv as usize != size_of::<CanFrame>() { return Err(io::Error::last_os_error()); } Ok(()) } /// Blocking write a single can frame, retrying until it gets sent /// successfully. pub fn write_frame_insist(&self, frame: &CanFrame) -> io::Result<()> { loop { match self.write_frame(frame) { Ok(v) => return Ok(v), Err(e) => { if !e.should_retry() { return Err(e); } } } } } /// Sets filters on the socket. /// /// CAN packages received by SocketCAN are matched against these filters, /// only matching packets are returned by the interface. /// /// See `CanFilter` for details on how filtering works. By default, all /// single filter matching all incoming frames is installed. pub fn set_filters(&self, filters: &[CanFilter]) -> io::Result<()> { set_socket_option_mult(self.fd, SOL_CAN_RAW, CAN_RAW_FILTER, filters) } /// Sets the error mask on the socket. /// /// By default (`ERR_MASK_NONE`) no error conditions are reported as /// special error frames by the socket. Enabling error conditions by /// setting `ERR_MASK_ALL` or another non-empty error mask causes the /// socket to receive notification about the specified conditions. #[inline] pub fn set_error_mask(&self, mask: u32) -> io::Result<()> { set_socket_option(self.fd, SOL_CAN_RAW, CAN_RAW_ERR_FILTER, &mask) } /// Enable or disable loopback. /// /// By default, loopback is enabled, causing other applications that open /// the same CAN bus to see frames emitted by different applications on /// the same system. #[inline] pub fn set_loopback(&self, enabled: bool) -> io::Result<()> { let loopback: c_int = if enabled { 1 } else { 0 }; set_socket_option(self.fd, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback) } /// Enable or disable receiving of own frames. /// /// When loopback is enabled, this settings controls if CAN frames sent /// are received back immediately by sender. Default is off. pub fn set_recv_own_msgs(&self, enabled: bool) -> io::Result<()> { let recv_own_msgs: c_int = if enabled { 1 } else { 0 }; set_socket_option(self.fd, SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS, &recv_own_msgs) } /// Enable or disable join filters. /// /// By default a frame is accepted if it matches any of the filters set /// with `set_filters`. If join filters is enabled, a frame has to match /// _all_ filters to be accepted. pub fn set_join_filters(&self, enabled: bool) -> io::Result<()> { let join_filters: c_int = if enabled { 1 } else { 0 }; set_socket_option(self.fd, SOL_CAN_RAW, CAN_RAW_JOIN_FILTERS, &join_filters) } } impl AsRawFd for CanSocket { fn as_raw_fd(&self) -> RawFd { self.fd } } impl FromRawFd for CanSocket { unsafe fn from_raw_fd(fd: RawFd) -> CanSocket { CanSocket { fd: fd } } } impl IntoRawFd for CanSocket { fn into_raw_fd(self) -> RawFd { self.fd } } impl Drop for CanSocket { fn drop(&mut self) { self.close().ok(); // ignore result } } /// CanFrame /// /// Uses the same memory layout as the underlying kernel struct for performance /// reasons. #[derive(Debug, Copy, Clone)] #[repr(C)] pub struct CanFrame { /// 32 bit CAN_ID + EFF/RTR/ERR flags _id: u32, /// data length. Bytes beyond are not valid _data_len: u8, /// padding _pad: u8, /// reserved _res0: u8, /// reserved _res1: u8, /// buffer for data _data: [u8; 8], } impl CanFrame { pub fn new(id: u32, data: &[u8], rtr: bool, err: bool) -> Result<CanFrame, ConstructionError> { let mut _id = id; if data.len() > 8 { return Err(ConstructionError::TooMuchData); } if id > EFF_MASK { return Err(ConstructionError::IDTooLarge); } // set EFF_FLAG on large message if id > SFF_MASK { _id |= EFF_FLAG; } if rtr { _id |= RTR_FLAG; } if err { _id |= ERR_FLAG; } let mut full_data = [0; 8]; // not cool =/ for (n, c) in data.iter().enumerate() { full_data[n] = *c; } Ok(CanFrame { _id: _id, _data_len: data.len() as u8, _pad: 0, _res0: 0, _res1: 0, _data: full_data, }) } /// Return the actual CAN ID (without EFF/RTR/ERR flags) #[inline] pub fn id(&self) -> u32 { if self.is_extended() { self._id & EFF_MASK } else { self._id & SFF_MASK } } /// Return the error message #[inline] pub fn err(&self) -> u32 { self._id & ERR_MASK } /// Check if frame uses 29 bit extended frame format #[inline] pub fn is_extended(&self) -> bool { self._id & EFF_FLAG != 0 } /// Check if frame is an error message #[inline] pub fn is_error(&self) -> bool { self._id & ERR_FLAG != 0 } /// Check if frame is a remote transmission request #[inline] pub fn is_rtr(&self) -> bool { self._id & RTR_FLAG != 0 } /// A slice into the actual data. Slice will always be <= 8 bytes in length #[inline] pub fn data(&self) -> &[u8] { &self._data[..(self._data_len as usize)] } /// Read error from message and transform it into a `CanError`. /// /// SocketCAN errors are indicated using the error bit and coded inside /// id and data payload. Call `error()` converts these into usable /// `CanError` instances. /// /// If the frame is malformed, this may fail with a /// `CanErrorDecodingFailure`. #[inline] pub fn error(&self) -> Result<CanError, CanErrorDecodingFailure> { CanError::from_frame(self) } } impl fmt::UpperHex for CanFrame { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{:X}#", self.id())?; let mut parts = self.data().iter().map(|v| format!("{:02X}", v)); let sep = if f.alternate() { " " } else { "" }; write!(f, "{}", parts.join(sep)) } } /// CanFilter /// /// Contains an internal id and mask. Packets are considered to be matched by /// a filter if `received_id & mask == filter_id & mask` holds true. #[derive(Debug, Copy, Clone)] #[repr(C)] pub struct CanFilter { _id: u32, _mask: u32, } impl CanFilter { /// Construct a new CAN filter. pub fn new(id: u32, mask: u32) -> Result<CanFilter, ConstructionError> { Ok(CanFilter { _id: id, _mask: mask, }) } }
29.571429
99
0.598884
ac42348ba8214d79f37ccafbe98bca1e8b46942f
474
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. pub mod accessor; pub mod archivist; mod component_lifecycle; pub mod configs; pub mod constants; pub mod container; pub mod diagnostics; pub mod error; pub mod events; pub mod formatter; pub mod inspect; pub mod lifecycle; pub mod logs; pub(crate) mod moniker_rewriter; pub mod pipeline; pub mod repository;
22.571429
73
0.776371
117322c5315ef72d434d86d8ba4041ba5d25112f
4,540
/*! * Admin command handlers */ use chrono::{DateTime, Utc}; use itertools::Itertools; use diesel::prelude::{ExpressionMethods, QueryDsl, RunQueryDsl, OptionalExtension}; use serenity::{ client::Context, model::prelude::Message, utils::MessageBuilder, }; use uuid::Uuid; use crate::error::Error; use crate::extensions::MessageExt; use crate::models::*; use crate::PgPooledConn; use super::*; #[tracing::instrument(skip(_ctx, msg, conn))] pub async fn reset(_ctx: &Context, msg: &Message, conn: &PgPooledConn) -> StringResult { let game = msg.game(conn)?; let (game, part) = match game { Some((game, part)) => (game, part), None => return Ok(None), }; match msg.content.split(' ').collect::<Vec<_>>().as_slice() { [_, "do"] => { let reset_id = Uuid::new_v4(); let win_ids = par_dsl::participation .filter(par_dsl::is_win.eq(true)) .filter(par_dsl::game_id.eq(&game.id)) .select(par_dsl::win_id) .load::<Option<Uuid>>(conn)? .into_iter() .filter_map(|id| id) .collect::<Vec<_>>(); diesel::update( dsl::win .filter(dsl::reset.eq(false)) .filter(dsl::id.eq(diesel::dsl::any(win_ids)))) .set((dsl::reset.eq(true), dsl::reset_at.eq(diesel::dsl::now), dsl::reset_id.eq(reset_id))) .execute(conn)?; // Mark the current participation as skipped (if any) if let Some(part) = part { part.skip(conn)?; } Ok(Some(format!("Scores reset avec ID {}", reset_id))) } [_, "list"] => { use diesel::sql_types::Timestamptz; let resets = dsl::win .select((dsl::reset_id, diesel::dsl::sql::<Timestamptz>("max(reset_at) as rst"))) .inner_join(par_dsl::participation) .filter(par_dsl::game_id.eq(&game.id)) .filter(dsl::reset.eq(true)) .filter(diesel::dsl::sql("true group by reset_id")) .order_by(diesel::dsl::sql::<Timestamptz>("rst")) .load::<(Option<Uuid>, DateTime<Utc>)>(conn)? .into_iter() .enumerate() .filter_map(|(i, (id, at))| match id { Some(id) => Some(format!("{}. {} à {}", i + 1, id, at)), _ => None, }) .join("\n"); Ok(Some(format!("Resets:\n{}", resets))) } [_, "cancel", id] => { let reset_id: Uuid = id.parse().map_err(|_| Error::InvalidResetId)?; diesel::update(dsl::win.filter(dsl::reset.eq(true)).filter(dsl::reset_id.eq(reset_id))) .set((dsl::reset.eq(false), dsl::reset_at.eq::<Option<DateTime<Utc>>>(None), dsl::reset_id.eq::<Option<Uuid>>(None))) .execute(conn) .optional()? .ok_or(Error::InvalidResetId)?; Ok(Some(format!("Reset {} annulé", reset_id))) } [..] => Err(Error::UnknownArguments), } } #[tracing::instrument(skip(_ctx, msg, conn))] pub async fn force_skip(_ctx: &Context, msg: &Message, conn: &PgPooledConn) -> StringResult { let game = msg.game(&conn)?; let part = match game { Some((_, Some(part))) => part, Some(_) => return Err(Error::NoParticipant), None => return Ok(None), }; part.skip(&conn)?; Ok(Some(MessageBuilder::new() .push("A vos photos, ") .mention(&part.player()) .push(" n'a plus la main, on y a coupé court !") .build())) } #[tracing::instrument(skip(_ctx, msg, conn))] pub async fn start(_ctx: &Context, msg: &Message, conn: &PgPooledConn) -> StringResult { let game = msg.game(conn)?; if game.is_some() { return Ok(Some(format!("Il y a déjà une partie en cours dans ce chan"))) } let guild = match msg.guild_id { Some(guild) => guild, None => return Ok(None), }; let game = NewGame { guild_id: &guild.to_string(), channel_id: &msg.channel_id.to_string(), creator_id: &msg.author.id.to_string(), }; let game: Game = diesel::insert_into(game_dsl::game).values(game).get_result(conn)?; println!("Created new game: {:?}", game); Ok(Some(format!("Partie démarrée !"))) }
34.656489
99
0.519383
8752386d6bfe0580ee244ec11a7a2cac3e23c235
2,583
mod use_context; mod use_effect; mod use_reducer; mod use_ref; mod use_state; pub use use_context::*; pub use use_effect::*; pub use use_reducer::*; pub use use_ref::*; pub use use_state::*; use crate::{HookUpdater, CURRENT_HOOK}; use std::cell::RefCell; use std::ops::DerefMut; use std::rc::Rc; /// Low level building block of creating hooks. /// /// It is used to created the pre-defined primitive hooks. /// Generally, it isn't needed to create hooks and should be avoided as most custom hooks can be /// created by combining other hooks as described in [Yew Docs]. /// /// The `initializer` callback is called once to create the initial state of the hook. /// `runner` callback handles the logic of the hook. It is called when the hook function is called. /// `destructor`, as the name implies, is called to cleanup the leftovers of the hook. /// /// See the pre-defined hooks for examples of how to use this function. /// /// [Yew Docs]: https://yew.rs/next/concepts/function-components/custom-hooks pub fn use_hook<InternalHook: 'static, Output, Tear: FnOnce(&mut InternalHook) + 'static>( initializer: impl FnOnce() -> InternalHook, runner: impl FnOnce(&mut InternalHook, HookUpdater) -> Output, destructor: Tear, ) -> Output { // Extract current hook let updater = CURRENT_HOOK.with(|hook_state| { // Determine which hook position we're at and increment for the next hook let hook_pos = hook_state.counter; hook_state.counter += 1; // Initialize hook if this is the first call if hook_pos >= hook_state.hooks.len() { let initial_state = Rc::new(RefCell::new(initializer())); hook_state.hooks.push(initial_state.clone()); hook_state.destroy_listeners.push(Box::new(move || { destructor(initial_state.borrow_mut().deref_mut()); })); } let hook = hook_state .hooks .get(hook_pos) .expect("Not the same number of hooks. Hooks must not be called conditionally") .clone(); HookUpdater { hook, process_message: hook_state.process_message.clone(), } }); // Execute the actual hook closure we were given. Let it mutate the hook state and let // it create a callback that takes the mutable hook state. let mut hook = updater.hook.borrow_mut(); let hook: &mut InternalHook = hook .downcast_mut() .expect("Incompatible hook type. Hooks must always be called in the same order"); runner(hook, updater.clone()) }
35.875
99
0.662795
d73caa416d3ccce351a70fe8a65393c7b4ca6421
7,735
use futures::{Async, Future}; use tower_load as load; use tower_service::Service; use tower_test::mock; use super::*; macro_rules! assert_fut_ready { ($fut:expr, $val:expr) => {{ assert_fut_ready!($fut, $val, "must be ready"); }}; ($fut:expr, $val:expr, $msg:expr) => {{ assert_eq!( $fut.poll().expect("must not fail"), Async::Ready($val), $msg ); }}; } macro_rules! assert_ready { ($svc:expr) => {{ assert_ready!($svc, "must be ready"); }}; ($svc:expr, $msg:expr) => {{ assert!($svc.poll_ready().expect("must not fail").is_ready(), $msg); }}; } macro_rules! assert_fut_not_ready { ($fut:expr) => {{ assert_fut_not_ready!($fut, "must not be ready"); }}; ($fut:expr, $msg:expr) => {{ assert!(!$fut.poll().expect("must not fail").is_ready(), $msg); }}; } macro_rules! assert_not_ready { ($svc:expr) => {{ assert_not_ready!($svc, "must not be ready"); }}; ($svc:expr, $msg:expr) => {{ assert!(!$svc.poll_ready().expect("must not fail").is_ready(), $msg); }}; } #[test] fn basic() { // start the pool let (mock, mut handle) = mock::pair::<(), load::Constant<mock::Mock<(), &'static str>, usize>>(); let mut pool = Builder::new().build(mock, ()); with_task(|| { assert_not_ready!(pool); }); // give the pool a backing service let (svc1_m, mut svc1) = mock::pair(); handle .next_request() .unwrap() .1 .send_response(load::Constant::new(svc1_m, 0)); with_task(|| { assert_ready!(pool); }); // send a request to the one backing service let mut fut = pool.call(()); with_task(|| { assert_fut_not_ready!(fut); }); svc1.next_request().unwrap().1.send_response("foobar"); with_task(|| { assert_fut_ready!(fut, "foobar"); }); } #[test] fn high_load() { // start the pool let (mock, mut handle) = mock::pair::<(), load::Constant<mock::Mock<(), &'static str>, usize>>(); let mut pool = Builder::new() .urgency(1.0) // so _any_ NotReady will add a service .underutilized_below(0.0) // so no Ready will remove a service .max_services(Some(2)) .build(mock, ()); with_task(|| { assert_not_ready!(pool); }); // give the pool a backing service let (svc1_m, mut svc1) = mock::pair(); svc1.allow(1); handle .next_request() .unwrap() .1 .send_response(load::Constant::new(svc1_m, 0)); with_task(|| { assert_ready!(pool); }); // make the one backing service not ready let mut fut1 = pool.call(()); // if we poll_ready again, pool should notice that load is increasing // since urgency == 1.0, it should immediately enter high load with_task(|| { assert_not_ready!(pool); }); // it should ask the maker for another service, so we give it one let (svc2_m, mut svc2) = mock::pair(); svc2.allow(1); handle .next_request() .unwrap() .1 .send_response(load::Constant::new(svc2_m, 0)); // the pool should now be ready again for one more request with_task(|| { assert_ready!(pool); }); let mut fut2 = pool.call(()); with_task(|| { assert_not_ready!(pool); }); // the pool should _not_ try to add another service // sicen we have max_services(2) with_task(|| { assert!(!handle.poll_request().unwrap().is_ready()); }); // let see that each service got one request svc1.next_request().unwrap().1.send_response("foo"); svc2.next_request().unwrap().1.send_response("bar"); with_task(|| { assert_fut_ready!(fut1, "foo"); }); with_task(|| { assert_fut_ready!(fut2, "bar"); }); } #[test] fn low_load() { // start the pool let (mock, mut handle) = mock::pair::<(), load::Constant<mock::Mock<(), &'static str>, usize>>(); let mut pool = Builder::new() .urgency(1.0) // so any event will change the service count .build(mock, ()); with_task(|| { assert_not_ready!(pool); }); // give the pool a backing service let (svc1_m, mut svc1) = mock::pair(); svc1.allow(1); handle .next_request() .unwrap() .1 .send_response(load::Constant::new(svc1_m, 0)); with_task(|| { assert_ready!(pool); }); // cycling a request should now work let mut fut = pool.call(()); svc1.next_request().unwrap().1.send_response("foo"); with_task(|| { assert_fut_ready!(fut, "foo"); }); // and pool should now not be ready (since svc1 isn't ready) // it should immediately try to add another service // which we give it with_task(|| { assert_not_ready!(pool); }); let (svc2_m, mut svc2) = mock::pair(); svc2.allow(1); handle .next_request() .unwrap() .1 .send_response(load::Constant::new(svc2_m, 0)); // pool is now ready // which (because of urgency == 1.0) should immediately cause it to drop a service // it'll drop svc1, so it'll still be ready with_task(|| { assert_ready!(pool); }); // and even with another ready, it won't drop svc2 since its now the only service with_task(|| { assert_ready!(pool); }); // cycling a request should now work on svc2 let mut fut = pool.call(()); svc2.next_request().unwrap().1.send_response("foo"); with_task(|| { assert_fut_ready!(fut, "foo"); }); // and again (still svc2) svc2.allow(1); with_task(|| { assert_ready!(pool); }); let mut fut = pool.call(()); svc2.next_request().unwrap().1.send_response("foo"); with_task(|| { assert_fut_ready!(fut, "foo"); }); } #[test] fn failing_service() { // start the pool let (mock, mut handle) = mock::pair::<(), load::Constant<mock::Mock<(), &'static str>, usize>>(); let mut pool = Builder::new() .urgency(1.0) // so _any_ NotReady will add a service .underutilized_below(0.0) // so no Ready will remove a service .build(mock, ()); with_task(|| { assert_not_ready!(pool); }); // give the pool a backing service let (svc1_m, mut svc1) = mock::pair(); svc1.allow(1); handle .next_request() .unwrap() .1 .send_response(load::Constant::new(svc1_m, 0)); with_task(|| { assert_ready!(pool); }); // one request-response cycle let mut fut = pool.call(()); svc1.next_request().unwrap().1.send_response("foo"); with_task(|| { assert_fut_ready!(fut, "foo"); }); // now make svc1 fail, so it has to be removed svc1.send_error("ouch"); // polling now should recognize the failed service, // try to create a new one, and then realize the maker isn't ready with_task(|| { assert_not_ready!(pool); }); // then we release another service let (svc2_m, mut svc2) = mock::pair(); svc2.allow(1); handle .next_request() .unwrap() .1 .send_response(load::Constant::new(svc2_m, 0)); // the pool should now be ready again with_task(|| { assert_ready!(pool); }); // and a cycle should work (and go through svc2) let mut fut = pool.call(()); svc2.next_request().unwrap().1.send_response("bar"); with_task(|| { assert_fut_ready!(fut, "bar"); }); } fn with_task<F: FnOnce() -> U, U>(f: F) -> U { use futures::future::lazy; lazy(|| Ok::<_, ()>(f())).wait().unwrap() }
27.045455
86
0.55863
5beb1d8b8c476feb3d4478afa731239c0c807643
260
// Regression test for HashMap only impl'ing Send/Sync if its contents do use std::collections::HashMap; use std::rc::Rc; fn foo<T: Send>() {} fn main() { foo::<HashMap<Rc<()>, Rc<()>>>(); //~^ ERROR `Rc<()>` cannot be sent between threads safely }
21.666667
73
0.619231
712b73e7f3c03062a3ff8bab1e5d68df9fe4aaa3
2,547
#[doc = "Register `RD_MAC_SPI_SYS_3` reader"] pub struct R(crate::R<RD_MAC_SPI_SYS_3_SPEC>); impl core::ops::Deref for R { type Target = crate::R<RD_MAC_SPI_SYS_3_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<RD_MAC_SPI_SYS_3_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<RD_MAC_SPI_SYS_3_SPEC>) -> Self { R(reader) } } #[doc = "Field `SPI_PAD_CONF_2` reader - Stores the second part of SPI_PAD_CONF."] pub struct SPI_PAD_CONF_2_R(crate::FieldReader<u32, u32>); impl SPI_PAD_CONF_2_R { #[inline(always)] pub(crate) fn new(bits: u32) -> Self { SPI_PAD_CONF_2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for SPI_PAD_CONF_2_R { type Target = crate::FieldReader<u32, u32>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `SYS_DATA_PART0_0` reader - Stores the zeroth part of the zeroth part of system data."] pub struct SYS_DATA_PART0_0_R(crate::FieldReader<u16, u16>); impl SYS_DATA_PART0_0_R { #[inline(always)] pub(crate) fn new(bits: u16) -> Self { SYS_DATA_PART0_0_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for SYS_DATA_PART0_0_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bits 0:17 - Stores the second part of SPI_PAD_CONF."] #[inline(always)] pub fn spi_pad_conf_2(&self) -> SPI_PAD_CONF_2_R { SPI_PAD_CONF_2_R::new((self.bits & 0x0003_ffff) as u32) } #[doc = "Bits 18:31 - Stores the zeroth part of the zeroth part of system data."] #[inline(always)] pub fn sys_data_part0_0(&self) -> SYS_DATA_PART0_0_R { SYS_DATA_PART0_0_R::new(((self.bits >> 18) & 0x3fff) as u16) } } #[doc = "Register 3 of BLOCK1.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rd_mac_spi_sys_3](index.html) module"] pub struct RD_MAC_SPI_SYS_3_SPEC; impl crate::RegisterSpec for RD_MAC_SPI_SYS_3_SPEC { type Ux = u32; } #[doc = "`read()` method returns [rd_mac_spi_sys_3::R](R) reader structure"] impl crate::Readable for RD_MAC_SPI_SYS_3_SPEC { type Reader = R; } #[doc = "`reset()` method sets RD_MAC_SPI_SYS_3 to value 0"] impl crate::Resettable for RD_MAC_SPI_SYS_3_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
34.418919
240
0.660777