hexsha
stringlengths
40
40
size
int64
4
1.05M
content
stringlengths
4
1.05M
avg_line_length
float64
1.33
100
max_line_length
int64
1
1k
alphanum_fraction
float64
0.25
1
919dfc73381e40775930b2a94251ef959280fd0a
257
pub fn capitalize<S: ToString>(string: &S) -> String { let string = string.to_string(); let mut chars = string.chars(); match chars.next() { None => String::new(), Some(c) => c.to_uppercase().to_string() + chars.as_str() } }
28.555556
64
0.575875
9b7846c4f7788e3bd0f3f924f50c18beec5e4051
803
// if1.rs pub fn bigger(a: i32, b: i32) -> i32 { if a > b { a } else { b } } // Don't mind this for now :) #[cfg(test)] mod tests { use super::*; #[test] fn ten_is_bigger_than_eight() { assert_eq!(10, bigger(10, 8)); } #[test] fn fortytwo_is_bigger_than_thirtytwo() { assert_eq!(42, bigger(32, 42)); } } // It's possible to do this in one line if you would like! // Some similar examples from other languages: // - In C(++) this would be: `a > b ? a : b` // - In Python this would be: `a if a > b else b` // Remember in Rust that: // - the `if` condition does not need to be surrounded by parentheses // - `if`/`else` conditionals are expressions // - Each condition is followed by a `{}` block.
13.163934
69
0.556663
f520e3ca8fe02dc0efdb046973ec9e1905d4c1e9
10,112
use std::fmt::{self, Debug, Formatter}; use std::hash::{Hash, Hasher}; use std::net::SocketAddr; use std::time::{Duration, Instant}; use crate::id::NodeId; // TODO: Should remove as_* functions and replace them with from_requested, from_responded, etc to hide the logic // of the nodes initial status. // TODO: Should address the subsecond lookup paper where questionable nodes should not automatically be replaced with // good nodes, instead, questionable nodes should be pinged twice and then become available to be replaced. This reduces // GOOD node churn since after 15 minutes, a long lasting node could potentially be replaced by a short lived good node. // This strategy is actually what is vaguely specified in the standard? // TODO: Should we be storing a SocketAddr instead of a SocketAddrV4? /// Maximum wait period before a node becomes questionable. const MAX_LAST_SEEN_MINS: u64 = 15; /// Maximum number of requests before a Questionable node becomes Bad. const MAX_REFRESH_REQUESTS: usize = 2; /// Status of the node. /// Ordering of the enumerations is important, variants higher /// up are considered to be less than those further down. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Ord, PartialOrd)] pub enum NodeStatus { Bad, Questionable, Good, } /// Node participating in the dht. #[derive(Clone)] pub struct Node { handle: NodeHandle, last_request: Option<Instant>, last_response: Option<Instant>, last_local_request: Option<Instant>, refresh_requests: usize, } impl Node { /// Create a new node that has recently responded to us but never requested from us. pub fn as_good(id: NodeId, addr: SocketAddr) -> Node { Node { handle: NodeHandle { id, addr }, last_response: Some(Instant::now()), last_request: None, last_local_request: None, refresh_requests: 0, } } /// Create a questionable node that has responded to us before but never requested from us. pub fn as_questionable(id: NodeId, addr: SocketAddr) -> Node { let last_response_offset = Duration::from_secs(MAX_LAST_SEEN_MINS * 60); let last_response = Instant::now().checked_sub(last_response_offset).unwrap(); Node { handle: NodeHandle { id, addr }, last_response: Some(last_response), last_request: None, last_local_request: None, refresh_requests: 0, } } /// Create a new node that has never responded to us or requested from us. pub fn as_bad(id: NodeId, addr: SocketAddr) -> Node { Node { handle: NodeHandle { id, addr }, last_response: None, last_request: None, last_local_request: None, refresh_requests: 0, } } pub fn update(&mut self, other: Node) { assert_eq!(self.handle, other.handle); let self_status = self.status(); let other_status = other.status(); match (self_status, other_status) { (NodeStatus::Good, NodeStatus::Good) => { *self = Self { handle: self.handle, last_response: other.last_response, last_request: self.last_request, last_local_request: self.last_local_request, refresh_requests: 0, }; } (NodeStatus::Good, NodeStatus::Questionable) => {} (NodeStatus::Good, NodeStatus::Bad) => {} (NodeStatus::Questionable, NodeStatus::Good) => { *self = other; } (NodeStatus::Questionable, NodeStatus::Questionable) => {} (NodeStatus::Questionable, NodeStatus::Bad) => {} (NodeStatus::Bad, NodeStatus::Good) => { *self = other; } (NodeStatus::Bad, NodeStatus::Questionable) => { *self = other; } (NodeStatus::Bad, NodeStatus::Bad) => {} } } /// Record that we sent the node a request. pub fn local_request(&mut self) { self.last_local_request = Some(Instant::now()); if self.status() != NodeStatus::Good { self.refresh_requests = self.refresh_requests.saturating_add(1); } } /// Record that the node sent us a request. pub fn remote_request(&mut self) { self.last_request = Some(Instant::now()); } /// Return true if we have sent this node a request recently. pub fn recently_requested_from(&self) -> bool { if let Some(time) = self.last_local_request { // TODO: I made the 30 seconds up, seems reasonable. time > Instant::now() - Duration::from_secs(30) } else { false } } pub fn id(&self) -> NodeId { self.handle.id } pub fn addr(&self) -> SocketAddr { self.handle.addr } /// Current status of the node. /// /// The specification says: /// /// https://www.bittorrent.org/beps/bep_0005.html /// /// A good node is a node has responded to one of our queries within the last 15 minutes. A node is also good /// if it has ever responded to one of our queries and has sent us a query within the last 15 minutes. /// After 15 minutes of inactivity, a node becomes questionable. Nodes become bad when they fail to respond to /// multiple queries in a row. pub fn status(&self) -> NodeStatus { let curr_time = Instant::now(); // Check if node has ever responded to us let since_response = match self.last_response { Some(response_time) => curr_time - response_time, None => return NodeStatus::Bad, }; // Check if node has recently responded to us if since_response < Duration::from_secs(MAX_LAST_SEEN_MINS * 60) { return NodeStatus::Good; } // Check if we have request from node multiple times already without response if self.refresh_requests >= MAX_REFRESH_REQUESTS { return NodeStatus::Bad; } // Check if the node has recently requested from us if let Some(request_time) = self.last_request { let since_request = curr_time - request_time; if since_request < Duration::from_secs(MAX_LAST_SEEN_MINS * 60) { return NodeStatus::Good; } } NodeStatus::Questionable } /// Is node good or questionable? pub fn is_pingable(&self) -> bool { // Function is moderately expensive let status = self.status(); status == NodeStatus::Good || status == NodeStatus::Questionable } pub(crate) fn handle(&self) -> &NodeHandle { &self.handle } } impl Eq for Node {} impl PartialEq<Node> for Node { fn eq(&self, other: &Node) -> bool { self.handle == other.handle } } impl Hash for Node { fn hash<H>(&self, state: &mut H) where H: Hasher, { self.handle.hash(state); } } impl Debug for Node { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { f.debug_struct("Node") .field("id", &self.handle.id) .field("addr", &self.handle.addr) .field("last_request", &self.last_request) .field("last_response", &self.last_response) .field("refresh_requests", &self.refresh_requests) .finish() } } /// Node id + its socket address. #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct NodeHandle { pub id: NodeId, pub addr: SocketAddr, } impl NodeHandle { pub fn new(id: NodeId, addr: SocketAddr) -> Self { Self { id, addr } } } impl Debug for NodeHandle { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{:?}@{:?}", self.id, self.addr) } } #[cfg(test)] mod tests { use std::time::{Duration, Instant}; use crate::routing::node::{Node, NodeStatus}; use crate::test; #[test] fn positive_as_bad() { let node = Node::as_bad(test::dummy_node_id(), test::dummy_socket_addr_v4()); assert_eq!(node.status(), NodeStatus::Bad); } #[test] fn positive_as_questionable() { let node = Node::as_questionable(test::dummy_node_id(), test::dummy_socket_addr_v4()); assert_eq!(node.status(), NodeStatus::Questionable); } #[test] fn positive_as_good() { let node = Node::as_good(test::dummy_node_id(), test::dummy_socket_addr_v4()); assert_eq!(node.status(), NodeStatus::Good); } #[test] fn positive_request_renewal() { let mut node = Node::as_questionable(test::dummy_node_id(), test::dummy_socket_addr_v4()); node.remote_request(); assert_eq!(node.status(), NodeStatus::Good); } #[test] fn positive_node_idle() { let mut node = Node::as_good(test::dummy_node_id(), test::dummy_socket_addr_v4()); let time_offset = Duration::from_secs(super::MAX_LAST_SEEN_MINS * 60); let idle_time = Instant::now() - time_offset; node.last_response = Some(idle_time); assert_eq!(node.status(), NodeStatus::Questionable); } #[test] fn positive_node_idle_reqeusts() { let mut node = Node::as_questionable(test::dummy_node_id(), test::dummy_socket_addr_v4()); for _ in 0..super::MAX_REFRESH_REQUESTS { node.local_request(); } assert_eq!(node.status(), NodeStatus::Bad); } #[test] fn positive_good_status_ordering() { assert!(NodeStatus::Good > NodeStatus::Questionable); assert!(NodeStatus::Good > NodeStatus::Bad); } #[test] fn positive_questionable_status_ordering() { assert!(NodeStatus::Questionable > NodeStatus::Bad); assert!(NodeStatus::Questionable < NodeStatus::Good); } #[test] fn positive_bad_status_ordering() { assert!(NodeStatus::Bad < NodeStatus::Good); assert!(NodeStatus::Bad < NodeStatus::Questionable); } }
31.113846
120
0.607991
508d2602d71232b549607acc6821775b04cf0278
4,323
use crate::util::{Counted, HashMap}; use nalgebra::{Isometry3, Matrix4, Orthographic3, Point3, Vector2, Vector3, Point2}; use std::cmp::Ordering; use std::ops::{Deref, DerefMut}; use uuid::Uuid; const ZFAR: f32 = 20000.0; #[rustfmt::skip] const OPENGL_TO_WGPU_MATRIX: Matrix4<f32> = Matrix4::new( 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, ); #[derive(Debug, Copy, Clone, PartialEq)] pub struct OrthographicProjection { pub rect: Vector2<f32>, pub zoom: f32, pub znear: f32, pub zfar: f32, } impl OrthographicProjection { #[inline] pub fn new(rect: Vector2<f32>) -> Self { OrthographicProjection { rect, znear: 0.001, zfar: 20000.0, zoom: 1.0, } } #[inline] pub fn zoomed(&self) -> Vector2<f32> { self.rect / self.zoom } #[inline] pub fn to_homogeneous(&self) -> Matrix4<f32> { let half = self.zoomed() / 2.0; let proj = Orthographic3::new( -half.x as f32, half.x as f32, -half.y as f32, half.y as f32, self.znear, ZFAR, ) .to_homogeneous(); // see https://metashapes.com/blog/opengl-metal-projection-matrix-problem/ OPENGL_TO_WGPU_MATRIX * proj } #[inline] pub fn px_range_factor(&self, base: Vector2<f32>) -> Vector2<f32> { let zoomed = self.zoomed(); Vector2::new(base.x / zoomed.x, base.y / zoomed.y) } #[inline] pub fn scaled(&self, base: Vector2<f32>) -> Self { let mut a = self.to_owned(); let aspect = base.x / base.y; let min_aspect = a.rect.x / a.rect.y; match min_aspect .partial_cmp(&aspect) .expect("not NaN for delta_aspect") { Ordering::Less => { a.rect.x = a.rect.x / min_aspect * aspect; } Ordering::Equal => {} Ordering::Greater => { let inverse_min_aspect = 1.0 / min_aspect; let inverse_aspect = 1.0 / aspect; a.rect.y = a.rect.y / inverse_min_aspect * inverse_aspect; } } a } } #[derive(Debug, Copy, Clone, PartialEq)] pub struct RawCamera { pub eye: Point2<f32>, pub projection: OrthographicProjection, } impl RawCamera { #[inline] pub fn new(rect: Vector2<f32>, eye: Point2<f32>) -> Self { let projection = OrthographicProjection::new(rect); RawCamera::from_parts(eye, projection) } #[inline] pub fn from_parts(eye: Point2<f32>, projection: OrthographicProjection) -> Self { Self { eye, projection } } #[inline] pub fn view(&self) -> Isometry3<f32> { Isometry3::look_at_rh(&Point3::new(self.eye.x, self.eye.y, ZFAR / 2.0), &Point3::new(self.eye.x, self.eye.y, - 1.0), &Vector3::y()) } #[inline] pub fn relative_to_origin(&self, point: Vector2<f32>) -> Vector2<f32> { let scaled = self.projection.zoomed(); Vector2::new( scaled.x * point.x + self.eye.x, scaled.y * point.y + self.eye.y, ) } } #[derive(Default)] pub struct Cameras { underlying: HashMap<Uuid, Counted<RawCamera>>, } impl Cameras { pub fn insert_camera(&mut self, id: Uuid, camera: RawCamera) { log::debug!("insert camera: {:?}", id); self.underlying.insert(id, Counted::one(camera)); } pub fn update_camera(&mut self, id: &Uuid, camera: RawCamera) { log::debug!("update camera: {:?}", id); *self .underlying .get_mut(id) .expect("camera to update") .deref_mut() = camera; } pub fn inc_camera(&mut self, id: &Uuid) { self.underlying.get_mut(id).map(Counted::inc); } pub fn dec_camera(&mut self, id: &Uuid) { let count = self .underlying .get_mut(id) .map(Counted::dec) .unwrap_or_default(); if count == 0 { log::debug!("remove camera: {:?}", id); self.underlying.remove(id); } } pub fn get(&self, camera_id: &Uuid) -> Option<RawCamera> { self.underlying.get(camera_id).map(Deref::deref).copied() } }
26.521472
139
0.544067
33b36f7b5482b6bc6fce2755a3e6bd3f7eebf8f4
102,581
// Copyright 2018 Flavien Raynaud. // Copyright Materialize, Inc. and contributors. All rights reserved. // // 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. // // This file is derived from the avro-rs project, available at // https://github.com/flavray/avro-rs. It was incorporated // directly into Materialize on March 3, 2020. // // The original source code is subject to the terms of the MIT license, a copy // of which can be found in the LICENSE file at the root of this repository. //! Logic for parsing and interacting with schemas in Avro format. use std::borrow::Cow; use std::cell::RefCell; use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; use std::fmt; use std::rc::Rc; use std::str::FromStr; use digest::Digest; use itertools::Itertools; use regex::Regex; use serde::{ ser::{SerializeMap, SerializeSeq}, Serialize, Serializer, }; use serde_json::{self, Map, Value}; use tracing::{debug, warn}; use types::{DecimalValue, Value as AvroValue}; use crate::error::Error as AvroError; use crate::reader::SchemaResolver; use crate::types; use crate::types::AvroMap; use crate::util::MapHelper; pub fn resolve_schemas( writer_schema: &Schema, reader_schema: &Schema, ) -> Result<Schema, AvroError> { let r_indices = reader_schema.indices.clone(); let (reader_to_writer_names, writer_to_reader_names): (HashMap<_, _>, HashMap<_, _>) = writer_schema .indices .iter() .flat_map(|(name, widx)| { r_indices .get(name) .map(|ridx| ((*ridx, *widx), (*widx, *ridx))) }) .unzip(); let reader_fullnames = reader_schema .indices .iter() .map(|(f, i)| (*i, f)) .collect::<HashMap<_, _>>(); let mut resolver = SchemaResolver { named: Default::default(), indices: Default::default(), writer_to_reader_names, reader_to_writer_names, reader_to_resolved_names: Default::default(), reader_fullnames, reader_schema, }; let writer_node = writer_schema.top_node_or_named(); let reader_node = reader_schema.top_node_or_named(); let inner = resolver.resolve(writer_node, reader_node)?; let sch = Schema { named: resolver.named.into_iter().map(Option::unwrap).collect(), indices: resolver.indices, top: inner, }; Ok(sch) } /// Describes errors happened while parsing Avro schemas. #[derive(Clone, Debug, Eq, PartialEq)] pub struct ParseSchemaError(String); impl ParseSchemaError { pub fn new<S>(msg: S) -> ParseSchemaError where S: Into<String>, { ParseSchemaError(msg.into()) } } impl fmt::Display for ParseSchemaError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } impl std::error::Error for ParseSchemaError {} /// Represents an Avro schema fingerprint /// More information about Avro schema fingerprints can be found in the /// [Avro Schema Fingerprint documentation](https://avro.apache.org/docs/current/spec.html#schema_fingerprints) #[derive(Debug)] pub struct SchemaFingerprint { pub bytes: Vec<u8>, } impl fmt::Display for SchemaFingerprint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}", self.bytes .iter() .map(|byte| format!("{:02x}", byte)) .collect::<Vec<String>>() .join("") ) } } #[derive(Clone, Debug, PartialEq)] pub enum SchemaPieceOrNamed { Piece(SchemaPiece), Named(usize), } impl SchemaPieceOrNamed { pub fn get_human_name(&self, root: &Schema) -> String { match self { Self::Piece(piece) => format!("{:?}", piece), Self::Named(idx) => format!("{}", root.lookup(*idx).name), } } #[inline(always)] pub fn get_piece_and_name<'a>( &'a self, root: &'a Schema, ) -> (&'a SchemaPiece, Option<&'a FullName>) { self.as_ref().get_piece_and_name(root) } #[inline(always)] pub fn as_ref(&self) -> SchemaPieceRefOrNamed { match self { SchemaPieceOrNamed::Piece(piece) => SchemaPieceRefOrNamed::Piece(piece), SchemaPieceOrNamed::Named(index) => SchemaPieceRefOrNamed::Named(*index), } } } impl From<SchemaPiece> for SchemaPieceOrNamed { #[inline(always)] fn from(piece: SchemaPiece) -> Self { Self::Piece(piece) } } #[derive(Clone, Debug, PartialEq)] pub enum SchemaPiece { /// A `null` Avro schema. Null, /// A `boolean` Avro schema. Boolean, /// An `int` Avro schema. Int, /// A `long` Avro schema. Long, /// A `float` Avro schema. Float, /// A `double` Avro schema. Double, /// An `Int` Avro schema with a semantic type being days since the unix epoch. Date, /// An `Int64` Avro schema with a semantic type being milliseconds since the unix epoch. /// /// <https://avro.apache.org/docs/current/spec.html#Timestamp+%28millisecond+precision%29> TimestampMilli, /// An `Int64` Avro schema with a semantic type being microseconds since the unix epoch. /// /// <https://avro.apache.org/docs/current/spec.html#Timestamp+%28microsecond+precision%29> TimestampMicro, /// A `bytes` or `fixed` Avro schema with a logical type of `decimal` and /// the specified precision and scale. /// /// If the underlying type is `fixed`, /// the `fixed_size` field specifies the size. Decimal { precision: usize, scale: usize, fixed_size: Option<usize>, }, /// A `bytes` Avro schema. /// `Bytes` represents a sequence of 8-bit unsigned bytes. Bytes, /// A `string` Avro schema. /// `String` represents a unicode character sequence. String, /// A `string` Avro schema that is tagged as representing JSON data Json, /// A `string` Avro schema with a logical type of `uuid`. Uuid, /// A `array` Avro schema. Avro arrays are required to have the same type for each element. /// This variant holds the `Schema` for the array element type. Array(Box<SchemaPieceOrNamed>), /// A `map` Avro schema. /// `Map` holds a pointer to the `Schema` of its values, which must all be the same schema. /// `Map` keys are assumed to be `string`. Map(Box<SchemaPieceOrNamed>), /// A `union` Avro schema. Union(UnionSchema), /// A value written as `int` and read as `long`, /// for the timestamp-millis logicalType. ResolveIntTsMilli, /// A value written as `int` and read as `long`, /// for the timestamp-micros logicalType. ResolveIntTsMicro, /// A value written as an `int` with `date` logical type, /// and read as any timestamp type ResolveDateTimestamp, /// A value written as `int` and read as `long` ResolveIntLong, /// A value written as `int` and read as `float` ResolveIntFloat, /// A value written as `int` and read as `double` ResolveIntDouble, /// A value written as `long` and read as `float` ResolveLongFloat, /// A value written as `long` and read as `double` ResolveLongDouble, /// A value written as `float` and read as `double` ResolveFloatDouble, /// A concrete (i.e., non-`union`) type in the writer, /// resolved against one specific variant of a `union` in the writer. ResolveConcreteUnion { /// The index of the variant in the reader index: usize, /// The concrete type inner: Box<SchemaPieceOrNamed>, n_reader_variants: usize, reader_null_variant: Option<usize>, }, /// A union in the writer, resolved against a union in the reader. /// The two schemas may have different variants and the variants may be in a different order. ResolveUnionUnion { /// A mapping of the fields in the writer to those in the reader. /// If the `i`th element is `Err(e)`, the `i`th field in the writer /// did not match any field in the reader (or even if it matched by name, resolution failed). /// If the `i`th element is `Ok((j, piece))`, then the `i`th field of the writer /// matched the `j`th field of the reader, and `piece` is their resolved node. permutation: Vec<Result<(usize, SchemaPieceOrNamed), AvroError>>, n_reader_variants: usize, reader_null_variant: Option<usize>, }, /// The inverse of `ResolveConcreteUnion` ResolveUnionConcrete { index: usize, inner: Box<SchemaPieceOrNamed>, }, /// A `record` Avro schema. /// /// The `lookup` table maps field names to their position in the `Vec` /// of `fields`. Record { doc: Documentation, fields: Vec<RecordField>, lookup: HashMap<String, usize>, }, /// An `enum` Avro schema. Enum { doc: Documentation, symbols: Vec<String>, /// The index of the default value. /// /// This is only used in schema resolution: it is the value that /// will be read by a reader when a writer writes a value that the reader /// does not expect. default_idx: Option<usize>, }, /// A `fixed` Avro schema. Fixed { size: usize }, /// A record in the writer, resolved against a record in the reader. /// The two schemas may have different fields and the fields may be in a different order. ResolveRecord { /// Fields that do not exist in the writer schema, but had a default /// value specified in the reader schema, which we use. defaults: Vec<ResolvedDefaultValueField>, /// Fields in the order of their appearance in the writer schema. /// `Present` if they could be resolved against a field in the reader schema; /// `Absent` otherwise. fields: Vec<ResolvedRecordField>, /// The size of `defaults`, plus the number of `Present` values in `fields`. n_reader_fields: usize, }, /// An enum in the writer, resolved against an enum in the reader. /// The two schemas may have different values and the values may be in a different order. ResolveEnum { doc: Documentation, /// Symbols in order of the writer schema along with their index in the reader schema, /// or `Err(symbol_name)` if they don't exist in the reader schema. symbols: Vec<Result<(usize, String), String>>, /// The value to decode if the writer writes some value not expected by the reader. default: Option<(usize, String)>, }, } impl SchemaPiece { /// Returns whether the schema node is "underlyingly" an Int (but possibly a logicalType typedef) pub fn is_underlying_int(&self) -> bool { matches!(self, SchemaPiece::Int | SchemaPiece::Date) } /// Returns whether the schema node is "underlyingly" an Int64 (but possibly a logicalType typedef) pub fn is_underlying_long(&self) -> bool { matches!( self, SchemaPiece::Long | SchemaPiece::TimestampMilli | SchemaPiece::TimestampMicro ) } } /// Represents any valid Avro schema /// More information about Avro schemas can be found in the /// [Avro Specification](https://avro.apache.org/docs/current/spec.html#schemas) #[derive(Clone, PartialEq)] pub struct Schema { pub(crate) named: Vec<NamedSchemaPiece>, pub(crate) indices: HashMap<FullName, usize>, pub top: SchemaPieceOrNamed, } impl ToString for Schema { fn to_string(&self) -> String { let json = serde_json::to_value(self).unwrap(); json.to_string() } } impl std::fmt::Debug for Schema { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if f.alternate() { f.write_str( &serde_json::to_string_pretty(self) .unwrap_or_else(|e| format!("failed to serialize: {}", e)), ) } else { f.write_str( &serde_json::to_string(self) .unwrap_or_else(|e| format!("failed to serialize: {}", e)), ) } } } impl Schema { pub fn top_node(&self) -> SchemaNode { let (inner, name) = self.top.get_piece_and_name(self); SchemaNode { root: self, inner, name, } } pub fn top_node_or_named(&self) -> SchemaNodeOrNamed { SchemaNodeOrNamed { root: self, inner: self.top.as_ref(), } } pub fn lookup(&self, idx: usize) -> &NamedSchemaPiece { &self.named[idx] } pub fn try_lookup_name(&self, name: &FullName) -> Option<&NamedSchemaPiece> { self.indices.get(name).map(|&idx| &self.named[idx]) } } /// This type is used to simplify enum variant comparison between `Schema` and `types::Value`. /// /// **NOTE** This type was introduced due to a limitation of `mem::discriminant` requiring a _value_ /// be constructed in order to get the discriminant, which makes it difficult to implement a /// function that maps from `Discriminant<Schema> -> Discriminant<Value>`. Conversion into this /// intermediate type should be especially fast, as the number of enum variants is small, which /// _should_ compile into a jump-table for the conversion. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum SchemaKind { // Fixed-length types Null, Boolean, Int, Long, Float, Double, // Variable-length types Bytes, String, Array, Map, Union, Record, Enum, Fixed, // This can arise in resolved schemas, particularly when a union resolves to a non-union. // We would need to do a lookup to find the actual type. Unknown, } impl SchemaKind { pub fn name(self) -> &'static str { match self { SchemaKind::Null => "null", SchemaKind::Boolean => "boolean", SchemaKind::Int => "int", SchemaKind::Long => "long", SchemaKind::Float => "float", SchemaKind::Double => "double", SchemaKind::Bytes => "bytes", SchemaKind::String => "string", SchemaKind::Array => "array", SchemaKind::Map => "map", SchemaKind::Union => "union", SchemaKind::Record => "record", SchemaKind::Enum => "enum", SchemaKind::Fixed => "fixed", SchemaKind::Unknown => "unknown", } } } impl<'a> From<&'a SchemaPiece> for SchemaKind { #[inline(always)] fn from(piece: &'a SchemaPiece) -> SchemaKind { match piece { SchemaPiece::Null => SchemaKind::Null, SchemaPiece::Boolean => SchemaKind::Boolean, SchemaPiece::Int => SchemaKind::Int, SchemaPiece::Long => SchemaKind::Long, SchemaPiece::Float => SchemaKind::Float, SchemaPiece::Double => SchemaKind::Double, SchemaPiece::Date => SchemaKind::Int, SchemaPiece::TimestampMilli | SchemaPiece::TimestampMicro | SchemaPiece::ResolveIntTsMilli | SchemaPiece::ResolveDateTimestamp | SchemaPiece::ResolveIntTsMicro => SchemaKind::Long, SchemaPiece::Decimal { fixed_size: None, .. } => SchemaKind::Bytes, SchemaPiece::Decimal { fixed_size: Some(_), .. } => SchemaKind::Fixed, SchemaPiece::Bytes => SchemaKind::Bytes, SchemaPiece::String => SchemaKind::String, SchemaPiece::Array(_) => SchemaKind::Array, SchemaPiece::Map(_) => SchemaKind::Map, SchemaPiece::Union(_) => SchemaKind::Union, SchemaPiece::ResolveUnionUnion { .. } => SchemaKind::Union, SchemaPiece::ResolveIntLong => SchemaKind::Long, SchemaPiece::ResolveIntFloat => SchemaKind::Float, SchemaPiece::ResolveIntDouble => SchemaKind::Double, SchemaPiece::ResolveLongFloat => SchemaKind::Float, SchemaPiece::ResolveLongDouble => SchemaKind::Double, SchemaPiece::ResolveFloatDouble => SchemaKind::Double, SchemaPiece::ResolveConcreteUnion { .. } => SchemaKind::Union, SchemaPiece::ResolveUnionConcrete { inner: _, .. } => SchemaKind::Unknown, SchemaPiece::Record { .. } => SchemaKind::Record, SchemaPiece::Enum { .. } => SchemaKind::Enum, SchemaPiece::Fixed { .. } => SchemaKind::Fixed, SchemaPiece::ResolveRecord { .. } => SchemaKind::Record, SchemaPiece::ResolveEnum { .. } => SchemaKind::Enum, SchemaPiece::Json => SchemaKind::String, SchemaPiece::Uuid => SchemaKind::String, } } } impl<'a> From<SchemaNode<'a>> for SchemaKind { #[inline(always)] fn from(schema: SchemaNode<'a>) -> SchemaKind { SchemaKind::from(schema.inner) } } impl<'a> From<&'a Schema> for SchemaKind { #[inline(always)] fn from(schema: &'a Schema) -> SchemaKind { Self::from(schema.top_node()) } } /// Represents names for `record`, `enum` and `fixed` Avro schemas. /// /// Each of these `Schema`s have a `fullname` composed of two parts: /// * a name /// * a namespace /// /// `aliases` can also be defined, to facilitate schema evolution. /// /// More information about schema names can be found in the /// [Avro specification](https://avro.apache.org/docs/current/spec.html#names) #[derive(Clone, Debug, PartialEq)] pub struct Name { pub name: String, pub namespace: Option<String>, pub aliases: Option<Vec<String>>, } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct FullName { name: String, namespace: String, } impl FullName { pub fn from_parts(name: &str, namespace: Option<&str>, default_namespace: &str) -> FullName { if let Some(ns) = namespace { FullName { name: name.to_owned(), namespace: ns.to_owned(), } } else { let mut split = name.rsplitn(2, '.'); let name = split.next().unwrap(); let namespace = split.next().unwrap_or(default_namespace); FullName { name: name.into(), namespace: namespace.into(), } } } pub fn base_name(&self) -> &str { &self.name } } impl fmt::Display for FullName { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}.{}", self.namespace, self.name) } } /// Represents documentation for complex Avro schemas. pub type Documentation = Option<String>; impl Name { /// Create a new `Name`. /// No `namespace` nor `aliases` will be defined. pub fn new(name: &str) -> Name { Name { name: name.to_owned(), namespace: None, aliases: None, } } /// Parse a `serde_json::Value` into a `Name`. fn parse(complex: &Map<String, Value>) -> Result<Self, AvroError> { let name = complex .name() .ok_or_else(|| ParseSchemaError::new("No `name` field"))?; if name.is_empty() { return Err(ParseSchemaError::new(format!( "Name cannot be the empty string: {:?}", complex )) .into()); } let (namespace, name) = if let Some(index) = name.rfind('.') { let computed_namespace = name[..index].to_owned(); let computed_name = name[index + 1..].to_owned(); if let Some(provided_namespace) = complex.string("namespace") { if provided_namespace != computed_namespace { warn!( "Found dots in name {}, updating to namespace {} and name {}", name, computed_namespace, computed_name ); } } (Some(computed_namespace), computed_name) } else { (complex.string("namespace"), name) }; if !Regex::new(r"(^[A-Za-z_][A-Za-z0-9_]*)$") .unwrap() .is_match(&name) { return Err(ParseSchemaError::new(format!( "Invalid name. Must start with [A-Za-z_] and subsequently only contain [A-Za-z0-9_]. Found: {}", name )) .into()); } let aliases: Option<Vec<String>> = complex .get("aliases") .and_then(|aliases| aliases.as_array()) .and_then(|aliases| { aliases .iter() .map(|alias| alias.as_str()) .map(|alias| alias.map(|a| a.to_string())) .collect::<Option<_>>() }); Ok(Name { name, namespace, aliases, }) } /// Return the `fullname` of this `Name` /// /// More information about fullnames can be found in the /// [Avro specification](https://avro.apache.org/docs/current/spec.html#names) pub fn fullname(&self, default_namespace: &str) -> FullName { FullName::from_parts(&self.name, self.namespace.as_deref(), default_namespace) } } #[derive(Clone, Debug, PartialEq)] pub struct ResolvedDefaultValueField { pub name: String, pub doc: Documentation, pub default: types::Value, pub order: RecordFieldOrder, pub position: usize, } #[derive(Clone, Debug, PartialEq)] pub enum ResolvedRecordField { Absent(Schema), Present(RecordField), } /// Represents a `field` in a `record` Avro schema. #[derive(Clone, Debug, PartialEq)] pub struct RecordField { /// Name of the field. pub name: String, /// Documentation of the field. pub doc: Documentation, /// Default value of the field. /// This value will be used when reading Avro datum if schema resolution /// is enabled. pub default: Option<Value>, /// Schema of the field. pub schema: SchemaPieceOrNamed, /// Order of the field. /// /// **NOTE** This currently has no effect. pub order: RecordFieldOrder, /// Position of the field in the list of `field` of its parent `Schema` pub position: usize, } /// Represents any valid order for a `field` in a `record` Avro schema. #[derive(Copy, Clone, Debug, PartialEq)] pub enum RecordFieldOrder { Ascending, Descending, Ignore, } impl RecordField {} #[derive(Debug, Clone)] pub struct UnionSchema { schemas: Vec<SchemaPieceOrNamed>, // Used to ensure uniqueness of anonymous schema inputs, and provide constant time finding of the // schema index given a value. anon_variant_index: HashMap<SchemaKind, usize>, // Same as above, for named input references named_variant_index: HashMap<usize, usize>, } impl UnionSchema { pub(crate) fn new(schemas: Vec<SchemaPieceOrNamed>) -> Result<Self, AvroError> { let mut avindex = HashMap::new(); let mut nvindex = HashMap::new(); for (i, schema) in schemas.iter().enumerate() { match schema { SchemaPieceOrNamed::Piece(sp) => { if let SchemaPiece::Union(_) = sp { return Err(ParseSchemaError::new( "Unions may not directly contain a union", ) .into()); } let kind = SchemaKind::from(sp); if avindex.insert(kind, i).is_some() { return Err( ParseSchemaError::new("Unions cannot contain duplicate types").into(), ); } } SchemaPieceOrNamed::Named(idx) => { if nvindex.insert(*idx, i).is_some() { return Err( ParseSchemaError::new("Unions cannot contain duplicate types").into(), ); } } } } Ok(UnionSchema { schemas, anon_variant_index: avindex, named_variant_index: nvindex, }) } /// Returns a slice to all variants of this schema. pub fn variants(&self) -> &[SchemaPieceOrNamed] { &self.schemas } /// Returns true if the first variant of this `UnionSchema` is `Null`. pub fn is_nullable(&self) -> bool { !self.schemas.is_empty() && self.schemas[0] == SchemaPieceOrNamed::Piece(SchemaPiece::Null) } pub fn match_piece(&self, sp: &SchemaPiece) -> Option<(usize, &SchemaPieceOrNamed)> { self.anon_variant_index .get(&SchemaKind::from(sp)) .map(|idx| (*idx, &self.schemas[*idx])) } pub fn match_ref( &self, other: SchemaPieceRefOrNamed, names_map: &HashMap<usize, usize>, ) -> Option<(usize, &SchemaPieceOrNamed)> { match other { SchemaPieceRefOrNamed::Piece(sp) => self.match_piece(sp), SchemaPieceRefOrNamed::Named(idx) => names_map .get(&idx) .and_then(|idx| self.named_variant_index.get(idx)) .map(|idx| (*idx, &self.schemas[*idx])), } } #[inline(always)] pub fn match_( &self, other: &SchemaPieceOrNamed, names_map: &HashMap<usize, usize>, ) -> Option<(usize, &SchemaPieceOrNamed)> { self.match_ref(other.as_ref(), names_map) } } // No need to compare variant_index, it is derivative of schemas. impl PartialEq for UnionSchema { fn eq(&self, other: &UnionSchema) -> bool { self.schemas.eq(&other.schemas) } } #[derive(Default)] struct SchemaParser { named: Vec<Option<NamedSchemaPiece>>, indices: HashMap<FullName, usize>, } impl SchemaParser { fn parse(mut self, value: &Value) -> Result<Schema, AvroError> { let top = self.parse_inner("", value)?; let SchemaParser { named, indices } = self; Ok(Schema { named: named.into_iter().map(|o| o.unwrap()).collect(), indices, top, }) } fn parse_inner( &mut self, default_namespace: &str, value: &Value, ) -> Result<SchemaPieceOrNamed, AvroError> { match *value { Value::String(ref t) => { let name = FullName::from_parts(t.as_str(), None, default_namespace); if let Some(idx) = self.indices.get(&name) { Ok(SchemaPieceOrNamed::Named(*idx)) } else { Ok(SchemaPieceOrNamed::Piece(Schema::parse_primitive( t.as_str(), )?)) } } Value::Object(ref data) => self.parse_complex(default_namespace, data), Value::Array(ref data) => Ok(SchemaPieceOrNamed::Piece( self.parse_union(default_namespace, data)?, )), _ => Err(ParseSchemaError::new("Must be a JSON string, object or array").into()), } } fn alloc_name(&mut self, fullname: FullName) -> Result<usize, AvroError> { let idx = match self.indices.entry(fullname) { Entry::Vacant(ve) => *ve.insert(self.named.len()), Entry::Occupied(oe) => { return Err(ParseSchemaError::new(format!( "Sub-schema with name {} encountered multiple times", oe.key() )) .into()) } }; self.named.push(None); Ok(idx) } fn insert(&mut self, index: usize, schema: NamedSchemaPiece) { assert!(self.named[index].is_none()); self.named[index] = Some(schema); } fn parse_named_type( &mut self, type_name: &str, default_namespace: &str, complex: &Map<String, Value>, ) -> Result<usize, AvroError> { let name = Name::parse(complex)?; match name.name.as_str() { "null" | "boolean" | "int" | "long" | "float" | "double" | "bytes" | "string" => { return Err(ParseSchemaError::new(format!( "{} may not be used as a custom type name", name.name )) .into()) } _ => {} }; let fullname = name.fullname(default_namespace); let default_namespace = fullname.namespace.clone(); let idx = self.alloc_name(fullname.clone())?; let piece = match type_name { "record" => self.parse_record(&default_namespace, complex), "enum" => self.parse_enum(complex), "fixed" => self.parse_fixed(&default_namespace, complex), _ => unreachable!("Unknown named type kind: {}", type_name), }?; self.insert( idx, NamedSchemaPiece { name: fullname, piece, }, ); Ok(idx) } /// Parse a `serde_json::Value` representing a complex Avro type into a /// `Schema`. /// /// Avro supports "recursive" definition of types. /// e.g: {"type": {"type": "string"}} fn parse_complex( &mut self, default_namespace: &str, complex: &Map<String, Value>, ) -> Result<SchemaPieceOrNamed, AvroError> { match complex.get("type") { Some(&Value::String(ref t)) => Ok(match t.as_str() { "record" | "enum" | "fixed" => SchemaPieceOrNamed::Named(self.parse_named_type( t, default_namespace, complex, )?), "array" => SchemaPieceOrNamed::Piece(self.parse_array(default_namespace, complex)?), "map" => SchemaPieceOrNamed::Piece(self.parse_map(default_namespace, complex)?), "bytes" => SchemaPieceOrNamed::Piece(Self::parse_bytes(complex)?), "int" => SchemaPieceOrNamed::Piece(Self::parse_int(complex)?), "long" => SchemaPieceOrNamed::Piece(Self::parse_long(complex)?), "string" => SchemaPieceOrNamed::Piece(Self::from_string(complex)), other => { let name = FullName { name: other.into(), namespace: default_namespace.into(), }; if let Some(idx) = self.indices.get(&name) { SchemaPieceOrNamed::Named(*idx) } else { SchemaPieceOrNamed::Piece(Schema::parse_primitive(t.as_str())?) } } }), Some(&Value::Object(ref data)) => match data.get("type") { Some(ref value) => self.parse_inner(default_namespace, value), None => Err( ParseSchemaError::new(format!("Unknown complex type: {:?}", complex)).into(), ), }, _ => Err(ParseSchemaError::new("No `type` in complex type").into()), } } /// Parse a `serde_json::Value` representing a Avro record type into a /// `Schema`. fn parse_record( &mut self, default_namespace: &str, complex: &Map<String, Value>, ) -> Result<SchemaPiece, AvroError> { let mut lookup = HashMap::new(); let fields: Vec<RecordField> = complex .get("fields") .and_then(|fields| fields.as_array()) .ok_or_else(|| ParseSchemaError::new("No `fields` in record").into()) .and_then(|fields| { fields .iter() .filter_map(|field| field.as_object()) .enumerate() .map(|(position, field)| { self.parse_record_field(default_namespace, field, position) }) .collect::<Result<_, _>>() })?; for field in &fields { lookup.insert(field.name.clone(), field.position); } Ok(SchemaPiece::Record { doc: complex.doc(), fields, lookup, }) } /// Parse a `serde_json::Value` into a `RecordField`. fn parse_record_field( &mut self, default_namespace: &str, field: &Map<String, Value>, position: usize, ) -> Result<RecordField, AvroError> { let name = field .name() .ok_or_else(|| ParseSchemaError::new("No `name` in record field"))?; let schema = field .get("type") .ok_or_else(|| ParseSchemaError::new("No `type` in record field").into()) .and_then(|type_| self.parse_inner(default_namespace, type_))?; let default = field.get("default").cloned(); let order = field .get("order") .and_then(|order| order.as_str()) .and_then(|order| match order { "ascending" => Some(RecordFieldOrder::Ascending), "descending" => Some(RecordFieldOrder::Descending), "ignore" => Some(RecordFieldOrder::Ignore), _ => None, }) .unwrap_or(RecordFieldOrder::Ascending); Ok(RecordField { name, doc: field.doc(), default, schema, order, position, }) } /// Parse a `serde_json::Value` representing a Avro enum type into a /// `Schema`. fn parse_enum(&mut self, complex: &Map<String, Value>) -> Result<SchemaPiece, AvroError> { let symbols: Vec<String> = complex .get("symbols") .and_then(|v| v.as_array()) .ok_or_else(|| ParseSchemaError::new("No `symbols` field in enum")) .and_then(|symbols| { symbols .iter() .map(|symbol| symbol.as_str().map(|s| s.to_string())) .collect::<Option<_>>() .ok_or_else(|| ParseSchemaError::new("Unable to parse `symbols` in enum")) })?; let mut unique_symbols: HashSet<&String> = HashSet::new(); for symbol in symbols.iter() { if unique_symbols.contains(symbol) { return Err(ParseSchemaError::new(format!( "Enum symbols must be unique, found multiple: {}", symbol )) .into()); } else { unique_symbols.insert(symbol); } } let default_idx = if let Some(default) = complex.get("default") { let default_str = default.as_str().ok_or_else(|| { ParseSchemaError::new(format!( "Enum default should be a string, got: {:?}", default )) })?; let default_idx = symbols .iter() .position(|x| x == default_str) .ok_or_else(|| { ParseSchemaError::new(format!( "Enum default not found in list of symbols: {}", default_str )) })?; Some(default_idx) } else { None }; Ok(SchemaPiece::Enum { doc: complex.doc(), symbols, default_idx, }) } /// Parse a `serde_json::Value` representing a Avro array type into a /// `Schema`. fn parse_array( &mut self, default_namespace: &str, complex: &Map<String, Value>, ) -> Result<SchemaPiece, AvroError> { complex .get("items") .ok_or_else(|| ParseSchemaError::new("No `items` in array").into()) .and_then(|items| self.parse_inner(default_namespace, items)) .map(|schema| SchemaPiece::Array(Box::new(schema))) } /// Parse a `serde_json::Value` representing a Avro map type into a /// `Schema`. fn parse_map( &mut self, default_namespace: &str, complex: &Map<String, Value>, ) -> Result<SchemaPiece, AvroError> { complex .get("values") .ok_or_else(|| ParseSchemaError::new("No `values` in map").into()) .and_then(|items| self.parse_inner(default_namespace, items)) .map(|schema| SchemaPiece::Map(Box::new(schema))) } /// Parse a `serde_json::Value` representing a Avro union type into a /// `Schema`. fn parse_union( &mut self, default_namespace: &str, items: &[Value], ) -> Result<SchemaPiece, AvroError> { items .iter() .map(|value| self.parse_inner(default_namespace, value)) .collect::<Result<Vec<_>, _>>() .and_then(|schemas| Ok(SchemaPiece::Union(UnionSchema::new(schemas)?))) } /// Parse a `serde_json::Value` representing a logical decimal type into a /// `Schema`. fn parse_decimal(complex: &Map<String, Value>) -> Result<(usize, usize), AvroError> { let precision = complex .get("precision") .and_then(|v| v.as_i64()) .ok_or_else(|| ParseSchemaError::new("No `precision` in decimal"))?; let scale = complex.get("scale").and_then(|v| v.as_i64()).unwrap_or(0); if scale < 0 { return Err(ParseSchemaError::new("Decimal scale must be greater than zero").into()); } if precision < 0 { return Err( ParseSchemaError::new("Decimal precision must be greater than zero").into(), ); } if scale > precision { return Err(ParseSchemaError::new("Decimal scale is greater than precision").into()); } Ok((precision as usize, scale as usize)) } /// Parse a `serde_json::Value` representing an Avro bytes type into a /// `Schema`. fn parse_bytes(complex: &Map<String, Value>) -> Result<SchemaPiece, AvroError> { let logical_type = complex.get("logicalType").and_then(|v| v.as_str()); if let Some("decimal") = logical_type { match Self::parse_decimal(complex) { Ok((precision, scale)) => { return Ok(SchemaPiece::Decimal { precision, scale, fixed_size: None, }) } Err(e) => warn!( "parsing decimal as regular bytes due to parse error: {:?}, {:?}", complex, e ), } } Ok(SchemaPiece::Bytes) } /// Parse a [`serde_json::Value`] representing an Avro Int type /// /// If the complex type has a `connect.name` tag (as [emitted by /// Debezium][1]) that matches a `Date` tag, we specify that the correct /// schema to use is `Date`. /// /// [1]: https://debezium.io/docs/connectors/mysql/#temporal-values fn parse_int(complex: &Map<String, Value>) -> Result<SchemaPiece, AvroError> { const AVRO_DATE: &str = "date"; const DEBEZIUM_DATE: &str = "io.debezium.time.Date"; const KAFKA_DATE: &str = "org.apache.kafka.connect.data.Date"; if let Some(name) = complex.get("connect.name") { if name == DEBEZIUM_DATE || name == KAFKA_DATE { if name == KAFKA_DATE { warn!("using deprecated debezium date format"); } return Ok(SchemaPiece::Date); } } // Put this after the custom semantic types so that the debezium // warning is emitted, since the logicalType tag shows up in the // deprecated debezium format :-/ if let Some(name) = complex.get("logicalType") { if name == AVRO_DATE { return Ok(SchemaPiece::Date); } } if !complex.is_empty() { debug!("parsing complex type as regular int: {:?}", complex); } Ok(SchemaPiece::Int) } /// Parse a [`serde_json::Value`] representing an Avro Int64/Long type /// /// The debezium/kafka types are document at [the debezium site][1], and the /// avro ones are documented at [Avro][2]. /// /// [1]: https://debezium.io/docs/connectors/mysql/#temporal-values /// [2]: https://avro.apache.org/docs/1.9.0/spec.html fn parse_long(complex: &Map<String, Value>) -> Result<SchemaPiece, AvroError> { const AVRO_MILLI_TS: &str = "timestamp-millis"; const AVRO_MICRO_TS: &str = "timestamp-micros"; const CONNECT_MILLI_TS: &[&str] = &[ "io.debezium.time.Timestamp", "org.apache.kafka.connect.data.Timestamp", ]; const CONNECT_MICRO_TS: &str = "io.debezium.time.MicroTimestamp"; if let Some(serde_json::Value::String(name)) = complex.get("connect.name") { if CONNECT_MILLI_TS.contains(&&**name) { return Ok(SchemaPiece::TimestampMilli); } if name == CONNECT_MICRO_TS { return Ok(SchemaPiece::TimestampMicro); } } if let Some(name) = complex.get("logicalType") { if name == AVRO_MILLI_TS { return Ok(SchemaPiece::TimestampMilli); } if name == AVRO_MICRO_TS { return Ok(SchemaPiece::TimestampMicro); } } if !complex.is_empty() { debug!("parsing complex type as regular long: {:?}", complex); } Ok(SchemaPiece::Long) } fn from_string(complex: &Map<String, Value>) -> SchemaPiece { const CONNECT_JSON: &str = "io.debezium.data.Json"; if let Some(serde_json::Value::String(name)) = complex.get("connect.name") { if CONNECT_JSON == name.as_str() { return SchemaPiece::Json; } } if let Some(name) = complex.get("logicalType") { if name == "uuid" { return SchemaPiece::Uuid; } } debug!("parsing complex type as regular string: {:?}", complex); SchemaPiece::String } /// Parse a `serde_json::Value` representing a Avro fixed type into a /// `Schema`. fn parse_fixed( &mut self, _default_namespace: &str, complex: &Map<String, Value>, ) -> Result<SchemaPiece, AvroError> { let _name = Name::parse(complex)?; let size = complex .get("size") .and_then(|v| v.as_i64()) .ok_or_else(|| ParseSchemaError::new("No `size` in fixed"))?; if size <= 0 { return Err(ParseSchemaError::new(format!( "Fixed values require a positive size attribute, found: {}", size )) .into()); } let logical_type = complex.get("logicalType").and_then(|v| v.as_str()); if let Some("decimal") = logical_type { match Self::parse_decimal(complex) { Ok((precision, scale)) => { let max = ((2_usize.pow((8 * size - 1) as u32) - 1) as f64).log10() as usize; if precision > max { warn!("Decimal precision {} requires more than {} bytes of space, parsing as fixed", precision, size); } else { return Ok(SchemaPiece::Decimal { precision, scale, fixed_size: Some(size as usize), }); } } Err(e) => warn!( "parsing decimal as fixed due to parse error: {:?}, {:?}", complex, e ), } } Ok(SchemaPiece::Fixed { size: size as usize, }) } } impl Schema { /// Create a `Schema` from a `serde_json::Value` representing a JSON Avro /// schema. pub fn parse(value: &Value) -> Result<Self, AvroError> { let p = SchemaParser { named: vec![], indices: Default::default(), }; p.parse(value) } /// Converts `self` into its [Parsing Canonical Form]. /// /// [Parsing Canonical Form]: /// https://avro.apache.org/docs/1.8.2/spec.html#Parsing+Canonical+Form+for+Schemas pub fn canonical_form(&self) -> String { let json = serde_json::to_value(self).unwrap(); parsing_canonical_form(&json) } /// Generate [fingerprint] of Schema's [Parsing Canonical Form]. /// /// [Parsing Canonical Form]: /// https://avro.apache.org/docs/1.8.2/spec.html#Parsing+Canonical+Form+for+Schemas /// [fingerprint]: /// https://avro.apache.org/docs/current/spec.html#schema_fingerprints pub fn fingerprint<D: Digest>(&self) -> SchemaFingerprint { let mut d = D::new(); d.update(self.canonical_form()); SchemaFingerprint { bytes: d.finalize().to_vec(), } } /// Parse a `serde_json::Value` representing a primitive Avro type into a /// `Schema`. fn parse_primitive(primitive: &str) -> Result<SchemaPiece, AvroError> { match primitive { "null" => Ok(SchemaPiece::Null), "boolean" => Ok(SchemaPiece::Boolean), "int" => Ok(SchemaPiece::Int), "long" => Ok(SchemaPiece::Long), "double" => Ok(SchemaPiece::Double), "float" => Ok(SchemaPiece::Float), "bytes" => Ok(SchemaPiece::Bytes), "string" => Ok(SchemaPiece::String), other => Err(ParseSchemaError::new(format!("Unknown type: {}", other)).into()), } } } impl FromStr for Schema { type Err = AvroError; /// Create a `Schema` from a string representing a JSON Avro schema. fn from_str(input: &str) -> Result<Self, AvroError> { let value = serde_json::from_str(input) .map_err(|e| ParseSchemaError::new(format!("Error parsing JSON: {}", e)))?; Self::parse(&value) } } #[derive(Clone, Debug, PartialEq)] pub struct NamedSchemaPiece { pub name: FullName, pub piece: SchemaPiece, } #[derive(Copy, Clone, Debug)] pub struct SchemaNode<'a> { pub root: &'a Schema, pub inner: &'a SchemaPiece, pub name: Option<&'a FullName>, } #[derive(Copy, Clone)] pub enum SchemaPieceRefOrNamed<'a> { Piece(&'a SchemaPiece), Named(usize), } impl<'a> SchemaPieceRefOrNamed<'a> { #[inline(always)] pub fn get_piece_and_name(self, root: &'a Schema) -> (&'a SchemaPiece, Option<&'a FullName>) { match self { SchemaPieceRefOrNamed::Piece(sp) => (sp, None), SchemaPieceRefOrNamed::Named(index) => { let named_piece = root.lookup(index); (&named_piece.piece, Some(&named_piece.name)) } } } } #[derive(Copy, Clone)] pub struct SchemaNodeOrNamed<'a> { pub root: &'a Schema, pub inner: SchemaPieceRefOrNamed<'a>, } impl<'a> SchemaNodeOrNamed<'a> { #[inline(always)] pub fn lookup(self) -> SchemaNode<'a> { let (inner, name) = self.inner.get_piece_and_name(self.root); SchemaNode { root: self.root, inner, name, } } #[inline(always)] pub fn step(self, next: &'a SchemaPieceOrNamed) -> Self { self.step_ref(next.as_ref()) } #[inline(always)] pub fn step_ref(self, next: SchemaPieceRefOrNamed<'a>) -> Self { Self { root: self.root, inner: match next { SchemaPieceRefOrNamed::Piece(piece) => SchemaPieceRefOrNamed::Piece(piece), SchemaPieceRefOrNamed::Named(index) => SchemaPieceRefOrNamed::Named(index), }, } } pub fn to_schema(self) -> Schema { let mut cloner = SchemaSubtreeDeepCloner { old_root: self.root, old_to_new_names: Default::default(), named: Default::default(), }; let piece = cloner.clone_piece_or_named(self.inner); let named: Vec<NamedSchemaPiece> = cloner.named.into_iter().map(Option::unwrap).collect(); let indices: HashMap<FullName, usize> = named .iter() .enumerate() .map(|(i, nsp)| (nsp.name.clone(), i)) .collect(); Schema { named, indices, top: piece, } } } struct SchemaSubtreeDeepCloner<'a> { old_root: &'a Schema, old_to_new_names: HashMap<usize, usize>, named: Vec<Option<NamedSchemaPiece>>, } impl<'a> SchemaSubtreeDeepCloner<'a> { fn clone_piece(&mut self, piece: &SchemaPiece) -> SchemaPiece { match piece { SchemaPiece::Null => SchemaPiece::Null, SchemaPiece::Boolean => SchemaPiece::Boolean, SchemaPiece::Int => SchemaPiece::Int, SchemaPiece::Long => SchemaPiece::Long, SchemaPiece::Float => SchemaPiece::Float, SchemaPiece::Double => SchemaPiece::Double, SchemaPiece::Date => SchemaPiece::Date, SchemaPiece::TimestampMilli => SchemaPiece::TimestampMilli, SchemaPiece::TimestampMicro => SchemaPiece::TimestampMicro, SchemaPiece::Json => SchemaPiece::Json, SchemaPiece::Decimal { scale, precision, fixed_size, } => SchemaPiece::Decimal { scale: *scale, precision: *precision, fixed_size: *fixed_size, }, SchemaPiece::Bytes => SchemaPiece::Bytes, SchemaPiece::String => SchemaPiece::String, SchemaPiece::Uuid => SchemaPiece::Uuid, SchemaPiece::Array(inner) => { SchemaPiece::Array(Box::new(self.clone_piece_or_named(inner.as_ref().as_ref()))) } SchemaPiece::Map(inner) => { SchemaPiece::Map(Box::new(self.clone_piece_or_named(inner.as_ref().as_ref()))) } SchemaPiece::Union(us) => SchemaPiece::Union(UnionSchema { schemas: us .schemas .iter() .map(|s| self.clone_piece_or_named(s.as_ref())) .collect(), anon_variant_index: us.anon_variant_index.clone(), named_variant_index: us.named_variant_index.clone(), }), SchemaPiece::ResolveIntLong => SchemaPiece::ResolveIntLong, SchemaPiece::ResolveIntFloat => SchemaPiece::ResolveIntFloat, SchemaPiece::ResolveIntDouble => SchemaPiece::ResolveIntDouble, SchemaPiece::ResolveLongFloat => SchemaPiece::ResolveLongFloat, SchemaPiece::ResolveLongDouble => SchemaPiece::ResolveLongDouble, SchemaPiece::ResolveFloatDouble => SchemaPiece::ResolveFloatDouble, SchemaPiece::ResolveIntTsMilli => SchemaPiece::ResolveIntTsMilli, SchemaPiece::ResolveIntTsMicro => SchemaPiece::ResolveIntTsMicro, SchemaPiece::ResolveDateTimestamp => SchemaPiece::ResolveDateTimestamp, SchemaPiece::ResolveConcreteUnion { index, inner, n_reader_variants, reader_null_variant, } => SchemaPiece::ResolveConcreteUnion { index: *index, inner: Box::new(self.clone_piece_or_named(inner.as_ref().as_ref())), n_reader_variants: *n_reader_variants, reader_null_variant: *reader_null_variant, }, SchemaPiece::ResolveUnionUnion { permutation, n_reader_variants, reader_null_variant, } => SchemaPiece::ResolveUnionUnion { permutation: permutation .clone() .into_iter() .map(|o| o.map(|(idx, piece)| (idx, self.clone_piece_or_named(piece.as_ref())))) .collect(), n_reader_variants: *n_reader_variants, reader_null_variant: *reader_null_variant, }, SchemaPiece::ResolveUnionConcrete { index, inner } => { SchemaPiece::ResolveUnionConcrete { index: *index, inner: Box::new(self.clone_piece_or_named(inner.as_ref().as_ref())), } } SchemaPiece::Record { doc, fields, lookup, } => SchemaPiece::Record { doc: doc.clone(), fields: fields .iter() .map(|rf| RecordField { name: rf.name.clone(), doc: rf.doc.clone(), default: rf.default.clone(), schema: self.clone_piece_or_named(rf.schema.as_ref()), order: rf.order, position: rf.position, }) .collect(), lookup: lookup.clone(), }, SchemaPiece::Enum { doc, symbols, default_idx, } => SchemaPiece::Enum { doc: doc.clone(), symbols: symbols.clone(), default_idx: *default_idx, }, SchemaPiece::Fixed { size } => SchemaPiece::Fixed { size: *size }, SchemaPiece::ResolveRecord { defaults, fields, n_reader_fields, } => SchemaPiece::ResolveRecord { defaults: defaults.clone(), fields: fields .iter() .map(|rf| match rf { ResolvedRecordField::Present(rf) => { ResolvedRecordField::Present(RecordField { name: rf.name.clone(), doc: rf.doc.clone(), default: rf.default.clone(), schema: self.clone_piece_or_named(rf.schema.as_ref()), order: rf.order, position: rf.position, }) } ResolvedRecordField::Absent(writer_schema) => { ResolvedRecordField::Absent(writer_schema.clone()) } }) .collect(), n_reader_fields: *n_reader_fields, }, SchemaPiece::ResolveEnum { doc, symbols, default, } => SchemaPiece::ResolveEnum { doc: doc.clone(), symbols: symbols.clone(), default: default.clone(), }, } } fn clone_piece_or_named(&mut self, piece: SchemaPieceRefOrNamed) -> SchemaPieceOrNamed { match piece { SchemaPieceRefOrNamed::Piece(piece) => self.clone_piece(piece).into(), SchemaPieceRefOrNamed::Named(index) => { let new_index = match self.old_to_new_names.entry(index) { Entry::Vacant(ve) => { let new_index = self.named.len(); self.named.push(None); ve.insert(new_index); let old_named_piece = self.old_root.lookup(index); let new_named_piece = NamedSchemaPiece { name: old_named_piece.name.clone(), piece: self.clone_piece(&old_named_piece.piece), }; self.named[new_index] = Some(new_named_piece); new_index } Entry::Occupied(oe) => *oe.get(), }; SchemaPieceOrNamed::Named(new_index) } } } } impl<'a> SchemaNode<'a> { #[inline(always)] pub fn step(self, next: &'a SchemaPieceOrNamed) -> Self { let (inner, name) = next.get_piece_and_name(self.root); Self { root: self.root, inner, name, } } pub fn json_to_value(self, json: &serde_json::Value) -> Result<AvroValue, ParseSchemaError> { use serde_json::Value::*; let val = match (json, self.inner) { // A default value always matches the first variant of a union (json, SchemaPiece::Union(us)) => match us.schemas.first() { Some(variant) => AvroValue::Union { index: 0, inner: Box::new(self.step(variant).json_to_value(json)?), n_variants: us.schemas.len(), null_variant: us .schemas .iter() .position(|s| s == &SchemaPieceOrNamed::Piece(SchemaPiece::Null)), }, None => return Err(ParseSchemaError("Union schema has no variants".to_owned())), }, (Null, SchemaPiece::Null) => AvroValue::Null, (Bool(b), SchemaPiece::Boolean) => AvroValue::Boolean(*b), (Number(n), piece) => match piece { SchemaPiece::Int => { let i = n .as_i64() .and_then(|i| i32::try_from(i).ok()) .ok_or_else(|| { ParseSchemaError(format!("{} is not a 32-bit integer", n)) })?; AvroValue::Int(i) } SchemaPiece::Long => { let i = n.as_i64().ok_or_else(|| { ParseSchemaError(format!("{} is not a 64-bit integer", n)) })?; AvroValue::Long(i) } SchemaPiece::Float => { let f = n .as_f64() .ok_or_else(|| ParseSchemaError(format!("{} is not a 32-bit float", n)))?; AvroValue::Float(f as f32) } SchemaPiece::Double => { let f = n .as_f64() .ok_or_else(|| ParseSchemaError(format!("{} is not a 64-bit float", n)))?; AvroValue::Double(f) } _ => { return Err(ParseSchemaError(format!( "Unexpected number in default: {}", n ))) } }, (String(s), piece) if s.eq_ignore_ascii_case("nan") && (piece == &SchemaPiece::Float || piece == &SchemaPiece::Double) => { match piece { SchemaPiece::Float => AvroValue::Float(f32::NAN), SchemaPiece::Double => AvroValue::Double(f64::NAN), _ => unreachable!(), } } (String(s), piece) if s.eq_ignore_ascii_case("infinity") && (piece == &SchemaPiece::Float || piece == &SchemaPiece::Double) => { match piece { SchemaPiece::Float => AvroValue::Float(f32::INFINITY), SchemaPiece::Double => AvroValue::Double(f64::INFINITY), _ => unreachable!(), } } (String(s), piece) if s.eq_ignore_ascii_case("-infinity") && (piece == &SchemaPiece::Float || piece == &SchemaPiece::Double) => { match piece { SchemaPiece::Float => AvroValue::Float(f32::NEG_INFINITY), SchemaPiece::Double => AvroValue::Double(f64::NEG_INFINITY), _ => unreachable!(), } } (String(s), SchemaPiece::Bytes) => AvroValue::Bytes(s.clone().into_bytes()), ( String(s), SchemaPiece::Decimal { precision, scale, .. }, ) => AvroValue::Decimal(DecimalValue { precision: *precision, scale: *scale, unscaled: s.clone().into_bytes(), }), (String(s), SchemaPiece::String) => AvroValue::String(s.clone()), (Object(map), SchemaPiece::Record { fields, .. }) => { let field_values = fields .iter() .map(|rf| { let jval = map.get(&rf.name).ok_or_else(|| { ParseSchemaError(format!( "Field not found in default value: {}", rf.name )) })?; let value = self.step(&rf.schema).json_to_value(jval)?; Ok((rf.name.clone(), value)) }) .collect::<Result<Vec<(std::string::String, AvroValue)>, ParseSchemaError>>()?; AvroValue::Record(field_values) } (String(s), SchemaPiece::Enum { symbols, .. }) => { match symbols.iter().find_position(|sym| s == *sym) { Some((index, sym)) => AvroValue::Enum(index, sym.clone()), None => return Err(ParseSchemaError(format!("Enum variant not found: {}", s))), } } (Array(vals), SchemaPiece::Array(inner)) => { let node = self.step(&**inner); let vals = vals .iter() .map(|val| node.json_to_value(val)) .collect::<Result<Vec<_>, ParseSchemaError>>()?; AvroValue::Array(vals) } (Object(map), SchemaPiece::Map(inner)) => { let node = self.step(&**inner); let map = map .iter() .map(|(k, v)| node.json_to_value(v).map(|v| (k.clone(), v))) .collect::<Result<HashMap<_, _>, ParseSchemaError>>()?; AvroValue::Map(AvroMap(map)) } (String(s), SchemaPiece::Fixed { size }) if s.len() == *size => { AvroValue::Fixed(*size, s.clone().into_bytes()) } _ => { return Err(ParseSchemaError(format!( "Json default value {} does not match schema", json ))) } }; Ok(val) } } #[derive(Clone)] struct SchemaSerContext<'a> { node: SchemaNodeOrNamed<'a>, // This does not logically need Rc<RefCell<_>> semantics -- // it is only ever mutated in one stack frame at a time. // But AFAICT serde doesn't expose a way to // provide some mutable context to every node in the tree... seen_named: Rc<RefCell<HashMap<usize, String>>>, } #[derive(Clone)] struct RecordFieldSerContext<'a> { outer: &'a SchemaSerContext<'a>, inner: &'a RecordField, } impl<'a> SchemaSerContext<'a> { fn step(&'a self, next: SchemaPieceRefOrNamed<'a>) -> Self { Self { node: self.node.step_ref(next), seen_named: self.seen_named.clone(), } } } impl<'a> Serialize for SchemaSerContext<'a> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self.node.inner { SchemaPieceRefOrNamed::Piece(piece) => match piece { SchemaPiece::Null => serializer.serialize_str("null"), SchemaPiece::Boolean => serializer.serialize_str("boolean"), SchemaPiece::Int => serializer.serialize_str("int"), SchemaPiece::Long => serializer.serialize_str("long"), SchemaPiece::Float => serializer.serialize_str("float"), SchemaPiece::Double => serializer.serialize_str("double"), SchemaPiece::Date => { let mut map = serializer.serialize_map(Some(2))?; map.serialize_entry("type", "int")?; map.serialize_entry("logicalType", "date")?; map.end() } SchemaPiece::TimestampMilli | SchemaPiece::TimestampMicro => { let mut map = serializer.serialize_map(Some(2))?; map.serialize_entry("type", "long")?; if piece == &SchemaPiece::TimestampMilli { map.serialize_entry("logicalType", "timestamp-millis")?; } else { map.serialize_entry("logicalType", "timestamp-micros")?; } map.end() } SchemaPiece::Decimal { precision, scale, fixed_size: None, } => { let mut map = serializer.serialize_map(Some(4))?; map.serialize_entry("type", "bytes")?; map.serialize_entry("precision", precision)?; map.serialize_entry("scale", scale)?; map.serialize_entry("logicalType", "decimal")?; map.end() } SchemaPiece::Bytes => serializer.serialize_str("bytes"), SchemaPiece::String => serializer.serialize_str("string"), SchemaPiece::Array(inner) => { let mut map = serializer.serialize_map(Some(2))?; map.serialize_entry("type", "array")?; map.serialize_entry("items", &self.step(inner.as_ref().as_ref()))?; map.end() } SchemaPiece::Map(inner) => { let mut map = serializer.serialize_map(Some(2))?; map.serialize_entry("type", "map")?; map.serialize_entry("values", &self.step(inner.as_ref().as_ref()))?; map.end() } SchemaPiece::Union(inner) => { let variants = inner.variants(); let mut seq = serializer.serialize_seq(Some(variants.len()))?; for v in variants { seq.serialize_element(&self.step(v.as_ref()))?; } seq.end() } SchemaPiece::Json => { let mut map = serializer.serialize_map(Some(2))?; map.serialize_entry("type", "string")?; map.serialize_entry("connect.name", "io.debezium.data.Json")?; map.end() } SchemaPiece::Uuid => { let mut map = serializer.serialize_map(Some(4))?; map.serialize_entry("type", "string")?; map.serialize_entry("logicalType", "uuid")?; map.end() } SchemaPiece::Record { .. } | SchemaPiece::Decimal { fixed_size: Some(_), .. } | SchemaPiece::Enum { .. } | SchemaPiece::Fixed { .. } => { unreachable!("Unexpected named schema piece in anonymous schema position") } SchemaPiece::ResolveIntLong | SchemaPiece::ResolveDateTimestamp | SchemaPiece::ResolveIntFloat | SchemaPiece::ResolveIntDouble | SchemaPiece::ResolveLongFloat | SchemaPiece::ResolveLongDouble | SchemaPiece::ResolveFloatDouble | SchemaPiece::ResolveConcreteUnion { .. } | SchemaPiece::ResolveUnionUnion { .. } | SchemaPiece::ResolveUnionConcrete { .. } | SchemaPiece::ResolveRecord { .. } | SchemaPiece::ResolveIntTsMicro | SchemaPiece::ResolveIntTsMilli | SchemaPiece::ResolveEnum { .. } => { panic!("Attempted to serialize resolved schema") } }, SchemaPieceRefOrNamed::Named(index) => { let mut map = self.seen_named.borrow_mut(); let named_piece = match map.get(&index) { Some(name) => { return serializer.serialize_str(name.as_str()); } None => self.node.root.lookup(index), }; let name = named_piece.name.to_string(); map.insert(index, name.clone()); std::mem::drop(map); match &named_piece.piece { SchemaPiece::Record { doc, fields, .. } => { let mut map = serializer.serialize_map(None)?; map.serialize_entry("type", "record")?; map.serialize_entry("name", &name)?; if let Some(ref docstr) = doc { map.serialize_entry("doc", docstr)?; } // TODO (brennan) - serialize aliases map.serialize_entry( "fields", &fields .iter() .map(|f| RecordFieldSerContext { outer: self, inner: f, }) .collect::<Vec<_>>(), )?; map.end() } SchemaPiece::Enum { symbols, default_idx, .. } => { let mut map = serializer.serialize_map(None)?; map.serialize_entry("type", "enum")?; map.serialize_entry("name", &name)?; map.serialize_entry("symbols", symbols)?; if let Some(default_idx) = *default_idx { assert!(default_idx < symbols.len()); map.serialize_entry("default", &symbols[default_idx])?; } map.end() } SchemaPiece::Fixed { size } => { let mut map = serializer.serialize_map(None)?; map.serialize_entry("type", "fixed")?; map.serialize_entry("name", &name)?; map.serialize_entry("size", size)?; map.end() } SchemaPiece::Decimal { scale, precision, fixed_size: Some(size), } => { let mut map = serializer.serialize_map(Some(6))?; map.serialize_entry("type", "fixed")?; map.serialize_entry("logicalType", "decimal")?; map.serialize_entry("name", &name)?; map.serialize_entry("size", size)?; map.serialize_entry("precision", precision)?; map.serialize_entry("scale", scale)?; map.end() } SchemaPiece::Null | SchemaPiece::Boolean | SchemaPiece::Int | SchemaPiece::Long | SchemaPiece::Float | SchemaPiece::Double | SchemaPiece::Date | SchemaPiece::TimestampMilli | SchemaPiece::TimestampMicro | SchemaPiece::Decimal { fixed_size: None, .. } | SchemaPiece::Bytes | SchemaPiece::String | SchemaPiece::Array(_) | SchemaPiece::Map(_) | SchemaPiece::Union(_) | SchemaPiece::Uuid | SchemaPiece::Json => { unreachable!("Unexpected anonymous schema piece in named schema position") } SchemaPiece::ResolveIntLong | SchemaPiece::ResolveDateTimestamp | SchemaPiece::ResolveIntFloat | SchemaPiece::ResolveIntDouble | SchemaPiece::ResolveLongFloat | SchemaPiece::ResolveLongDouble | SchemaPiece::ResolveFloatDouble | SchemaPiece::ResolveConcreteUnion { .. } | SchemaPiece::ResolveUnionUnion { .. } | SchemaPiece::ResolveUnionConcrete { .. } | SchemaPiece::ResolveRecord { .. } | SchemaPiece::ResolveIntTsMilli | SchemaPiece::ResolveIntTsMicro | SchemaPiece::ResolveEnum { .. } => { panic!("Attempted to serialize resolved schema") } } } } } } impl Serialize for Schema { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let ctx = SchemaSerContext { node: SchemaNodeOrNamed { root: self, inner: self.top.as_ref(), }, seen_named: Rc::new(RefCell::new(Default::default())), }; ctx.serialize(serializer) } } impl<'a> Serialize for RecordFieldSerContext<'a> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut map = serializer.serialize_map(None)?; map.serialize_entry("name", &self.inner.name)?; map.serialize_entry("type", &self.outer.step(self.inner.schema.as_ref()))?; if let Some(default) = &self.inner.default { map.serialize_entry("default", default)?; } map.end() } } /// Parses a **valid** avro schema into the Parsing Canonical Form. /// <https://avro.apache.org/docs/1.8.2/spec.html#Parsing+Canonical+Form+for+Schemas> fn parsing_canonical_form(schema: &serde_json::Value) -> String { match schema { serde_json::Value::Object(map) => pcf_map(map), serde_json::Value::String(s) => pcf_string(s), serde_json::Value::Array(v) => pcf_array(v), serde_json::Value::Number(n) => n.to_string(), _ => unreachable!("{:?} cannot yet be printed in canonical form", schema), } } fn pcf_map(schema: &Map<String, serde_json::Value>) -> String { // Look for the namespace variant up front. let ns = schema.get("namespace").and_then(|v| v.as_str()); let mut fields = Vec::new(); for (k, v) in schema { // Reduce primitive types to their simple form. ([PRIMITIVE] rule) if schema.len() == 1 && k == "type" { // Invariant: function is only callable from a valid schema, so this is acceptable. if let serde_json::Value::String(s) = v { return pcf_string(s); } } // Strip out unused fields ([STRIP] rule) if field_ordering_position(k).is_none() { continue; } // Fully qualify the name, if it isn't already ([FULLNAMES] rule). if k == "name" { // Invariant: Only valid schemas. Must be a string. let name = v.as_str().unwrap(); let n = match ns { Some(namespace) if !name.contains('.') => { Cow::Owned(format!("{}.{}", namespace, name)) } _ => Cow::Borrowed(name), }; fields.push((k, format!("{}:{}", pcf_string(k), pcf_string(&*n)))); continue; } // Strip off quotes surrounding "size" type, if they exist ([INTEGERS] rule). if k == "size" { let i = match v.as_str() { Some(s) => s.parse::<i64>().expect("Only valid schemas are accepted!"), None => v.as_i64().unwrap(), }; fields.push((k, format!("{}:{}", pcf_string(k), i))); continue; } // For anything else, recursively process the result. fields.push(( k, format!("{}:{}", pcf_string(k), parsing_canonical_form(v)), )); } // Sort the fields by their canonical ordering ([ORDER] rule). fields.sort_unstable_by_key(|(k, _)| field_ordering_position(k).unwrap()); let inter = fields .into_iter() .map(|(_, v)| v) .collect::<Vec<_>>() .join(","); format!("{{{}}}", inter) } fn pcf_array(arr: &[serde_json::Value]) -> String { let inter = arr .iter() .map(parsing_canonical_form) .collect::<Vec<String>>() .join(","); format!("[{}]", inter) } fn pcf_string(s: &str) -> String { format!("\"{}\"", s) } // Used to define the ordering and inclusion of fields. fn field_ordering_position(field: &str) -> Option<usize> { let v = match field { "name" => 1, "type" => 2, "fields" => 3, "symbols" => 4, "items" => 5, "values" => 6, "size" => 7, _ => return None, }; Some(v) } #[cfg(test)] mod tests { use types::Record; use types::ToAvro; use super::*; fn check_schema(schema: &str, expected: SchemaPiece) { let schema = Schema::from_str(schema).unwrap(); assert_eq!(&expected, schema.top_node().inner); // Test serialization round trip let schema = serde_json::to_string(&schema).unwrap(); let schema = Schema::from_str(&schema).unwrap(); assert_eq!(&expected, schema.top_node().inner); } #[test] fn test_primitive_schema() { check_schema("\"null\"", SchemaPiece::Null); check_schema("\"int\"", SchemaPiece::Int); check_schema("\"double\"", SchemaPiece::Double); } #[test] fn test_array_schema() { check_schema( r#"{"type": "array", "items": "string"}"#, SchemaPiece::Array(Box::new(SchemaPieceOrNamed::Piece(SchemaPiece::String))), ); } #[test] fn test_map_schema() { check_schema( r#"{"type": "map", "values": "double"}"#, SchemaPiece::Map(Box::new(SchemaPieceOrNamed::Piece(SchemaPiece::Double))), ); } #[test] fn test_union_schema() { check_schema( r#"["null", "int"]"#, SchemaPiece::Union( UnionSchema::new(vec![ SchemaPieceOrNamed::Piece(SchemaPiece::Null), SchemaPieceOrNamed::Piece(SchemaPiece::Int), ]) .unwrap(), ), ); } #[test] fn test_multi_union_schema() { let schema = Schema::from_str(r#"["null", "int", "float", "string", "bytes"]"#); assert!(schema.is_ok()); let schema = schema.unwrap(); let node = schema.top_node(); assert_eq!(SchemaKind::from(&schema), SchemaKind::Union); let union_schema = match node.inner { SchemaPiece::Union(u) => u, _ => unreachable!(), }; assert_eq!(union_schema.variants().len(), 5); let mut variants = union_schema.variants().iter(); assert_eq!( SchemaKind::from(node.step(variants.next().unwrap())), SchemaKind::Null ); assert_eq!( SchemaKind::from(node.step(variants.next().unwrap())), SchemaKind::Int ); assert_eq!( SchemaKind::from(node.step(variants.next().unwrap())), SchemaKind::Float ); assert_eq!( SchemaKind::from(node.step(variants.next().unwrap())), SchemaKind::String ); assert_eq!( SchemaKind::from(node.step(variants.next().unwrap())), SchemaKind::Bytes ); assert_eq!(variants.next(), None); } #[test] fn test_record_schema() { let schema = r#" { "type": "record", "name": "test", "fields": [ {"name": "a", "type": "long", "default": 42}, {"name": "b", "type": "string"} ] } "#; let mut lookup = HashMap::new(); lookup.insert("a".to_owned(), 0); lookup.insert("b".to_owned(), 1); let expected = SchemaPiece::Record { doc: None, fields: vec![ RecordField { name: "a".to_string(), doc: None, default: Some(Value::Number(42i64.into())), schema: SchemaPiece::Long.into(), order: RecordFieldOrder::Ascending, position: 0, }, RecordField { name: "b".to_string(), doc: None, default: None, schema: SchemaPiece::String.into(), order: RecordFieldOrder::Ascending, position: 1, }, ], lookup, }; check_schema(schema, expected); } #[test] fn test_enum_schema() { let schema = r#"{"type": "enum", "name": "Suit", "symbols": ["diamonds", "spades", "jokers", "clubs", "hearts"], "default": "jokers"}"#; let expected = SchemaPiece::Enum { doc: None, symbols: vec![ "diamonds".to_owned(), "spades".to_owned(), "jokers".to_owned(), "clubs".to_owned(), "hearts".to_owned(), ], default_idx: Some(2), }; check_schema(schema, expected); let bad_schema = Schema::from_str( r#"{"type": "enum", "name": "Suit", "symbols": ["diamonds", "spades", "jokers", "clubs", "hearts"], "default": "blah"}"#, ); assert!(bad_schema.is_err()); } #[test] fn test_fixed_schema() { let schema = r#"{"type": "fixed", "name": "test", "size": 16}"#; let expected = SchemaPiece::Fixed { size: 16usize }; check_schema(schema, expected); } #[test] fn test_date_schema() { let kinds = &[ r#"{ "type": "int", "name": "datish", "logicalType": "date" }"#, r#"{ "type": "int", "name": "datish", "connect.name": "io.debezium.time.Date" }"#, r#"{ "type": "int", "name": "datish", "connect.name": "org.apache.kafka.connect.data.Date" }"#, ]; for kind in kinds { check_schema(*kind, SchemaPiece::Date); let schema = Schema::from_str(*kind).unwrap(); assert_eq!( serde_json::to_string(&schema).unwrap(), r#"{"type":"int","logicalType":"date"}"# ); } } #[test] fn new_field_in_middle() { let reader = r#"{ "type": "record", "name": "MyRecord", "fields": [{"name": "f1", "type": "int"}, {"name": "f2", "type": "int"}] }"#; let writer = r#"{ "type": "record", "name": "MyRecord", "fields": [{"name": "f1", "type": "int"}, {"name": "f_interposed", "type": "int"}, {"name": "f2", "type": "int"}] }"#; let reader = Schema::from_str(reader).unwrap(); let writer = Schema::from_str(writer).unwrap(); let mut record = Record::new(writer.top_node()).unwrap(); record.put("f1", 1); record.put("f2", 2); record.put("f_interposed", 42); let value = record.avro(); let mut buf = vec![]; crate::encode::encode(&value, &writer, &mut buf); let resolved = resolve_schemas(&writer, &reader).unwrap(); let reader = &mut &buf[..]; let reader_value = crate::decode::decode(resolved.top_node(), reader).unwrap(); let expected = crate::types::Value::Record(vec![ ("f1".to_string(), crate::types::Value::Int(1)), ("f2".to_string(), crate::types::Value::Int(2)), ]); assert_eq!(reader_value, expected); assert!(reader.is_empty()); // all bytes should have been consumed } #[test] fn new_field_at_end() { let reader = r#"{ "type": "record", "name": "MyRecord", "fields": [{"name": "f1", "type": "int"}] }"#; let writer = r#"{ "type": "record", "name": "MyRecord", "fields": [{"name": "f1", "type": "int"}, {"name": "f2", "type": "int"}] }"#; let reader = Schema::from_str(reader).unwrap(); let writer = Schema::from_str(writer).unwrap(); let mut record = Record::new(writer.top_node()).unwrap(); record.put("f1", 1); record.put("f2", 2); let value = record.avro(); let mut buf = vec![]; crate::encode::encode(&value, &writer, &mut buf); let resolved = resolve_schemas(&writer, &reader).unwrap(); let reader = &mut &buf[..]; let reader_value = crate::decode::decode(resolved.top_node(), reader).unwrap(); let expected = crate::types::Value::Record(vec![("f1".to_string(), crate::types::Value::Int(1))]); assert_eq!(reader_value, expected); assert!(reader.is_empty()); // all bytes should have been consumed } #[test] fn default_non_nums() { let reader = r#"{ "type": "record", "name": "MyRecord", "fields": [ {"name": "f1", "type": "double", "default": "NaN"}, {"name": "f2", "type": "double", "default": "Infinity"}, {"name": "f3", "type": "double", "default": "-Infinity"} ] } "#; let writer = r#"{"type": "record", "name": "MyRecord", "fields": []}"#; let writer_schema = Schema::from_str(writer).unwrap(); let reader_schema = Schema::from_str(reader).unwrap(); let resolved = resolve_schemas(&writer_schema, &reader_schema).unwrap(); let record = Record::new(writer_schema.top_node()).unwrap(); let value = record.avro(); let mut buf = vec![]; crate::encode::encode(&value, &writer_schema, &mut buf); let reader = &mut &buf[..]; let reader_value = crate::decode::decode(resolved.top_node(), reader).unwrap(); let expected = crate::types::Value::Record(vec![ ("f1".to_string(), crate::types::Value::Double(f64::NAN)), ("f2".to_string(), crate::types::Value::Double(f64::INFINITY)), ( "f3".to_string(), crate::types::Value::Double(f64::NEG_INFINITY), ), ]); #[derive(Debug)] struct NanEq(crate::types::Value); impl std::cmp::PartialEq for NanEq { fn eq(&self, other: &Self) -> bool { match (self, other) { ( NanEq(crate::types::Value::Double(x)), NanEq(crate::types::Value::Double(y)), ) if x.is_nan() && y.is_nan() => true, ( NanEq(crate::types::Value::Float(x)), NanEq(crate::types::Value::Float(y)), ) if x.is_nan() && y.is_nan() => true, ( NanEq(crate::types::Value::Record(xs)), NanEq(crate::types::Value::Record(ys)), ) => { let xs = xs .iter() .cloned() .map(|(k, v)| (k, NanEq(v))) .collect::<Vec<_>>(); let ys = ys .iter() .cloned() .map(|(k, v)| (k, NanEq(v))) .collect::<Vec<_>>(); xs == ys } (NanEq(x), NanEq(y)) => x == y, } } } assert_eq!(NanEq(reader_value), NanEq(expected)); assert!(reader.is_empty()); } #[test] fn test_decimal_schemas() { let schema = r#"{ "type": "fixed", "name": "dec", "size": 8, "logicalType": "decimal", "precision": 12, "scale": 5 }"#; let expected = SchemaPiece::Decimal { precision: 12, scale: 5, fixed_size: Some(8), }; check_schema(schema, expected); let schema = r#"{ "type": "bytes", "logicalType": "decimal", "precision": 12, "scale": 5 }"#; let expected = SchemaPiece::Decimal { precision: 12, scale: 5, fixed_size: None, }; check_schema(schema, expected); let res = Schema::from_str( r#"["bytes", { "type": "bytes", "logicalType": "decimal", "precision": 12, "scale": 5 }]"#, ); assert_eq!( res.unwrap_err().to_string(), "Schema parse error: Unions cannot contain duplicate types" ); let writer_schema = Schema::from_str( r#"["null", { "type": "bytes" }]"#, ) .unwrap(); let reader_schema = Schema::from_str( r#"["null", { "type": "bytes", "logicalType": "decimal", "precision": 12, "scale": 5 }]"#, ) .unwrap(); let resolved = resolve_schemas(&writer_schema, &reader_schema).unwrap(); let expected = SchemaPiece::ResolveUnionUnion { permutation: vec![ Ok((0, SchemaPieceOrNamed::Piece(SchemaPiece::Null))), Ok(( 1, SchemaPieceOrNamed::Piece(SchemaPiece::Decimal { precision: 12, scale: 5, fixed_size: None, }), )), ], n_reader_variants: 2, reader_null_variant: Some(0), }; assert_eq!(resolved.top_node().inner, &expected); } #[test] fn test_no_documentation() { let schema = Schema::from_str(r#"{"type": "enum", "name": "Coin", "symbols": ["heads", "tails"]}"#) .unwrap(); let doc = match schema.top_node().inner { SchemaPiece::Enum { doc, .. } => doc.clone(), _ => panic!(), }; assert!(doc.is_none()); } #[test] fn test_documentation() { let schema = Schema::from_str( r#"{"type": "enum", "name": "Coin", "doc": "Some documentation", "symbols": ["heads", "tails"]}"# ).unwrap(); let doc = match schema.top_node().inner { SchemaPiece::Enum { doc, .. } => doc.clone(), _ => None, }; assert_eq!("Some documentation".to_owned(), doc.unwrap()); } #[test] fn test_namespaces_and_names() { // When name and namespace specified, full name should contain both. let schema = Schema::from_str( r#"{"type": "fixed", "namespace": "namespace", "name": "name", "size": 1}"#, ) .unwrap(); assert_eq!(schema.named.len(), 1); assert_eq!( schema.named[0].name, FullName { name: "name".into(), namespace: "namespace".into() } ); // When name contains dots, parse the dot-separated name as the namespace. let schema = Schema::from_str(r#"{"type": "enum", "name": "name.has.dots", "symbols": ["A", "B"]}"#) .unwrap(); assert_eq!(schema.named.len(), 1); assert_eq!( schema.named[0].name, FullName { name: "dots".into(), namespace: "name.has".into() } ); // Same as above, ignore any provided namespace. let schema = Schema::from_str( r#"{"type": "enum", "namespace": "namespace", "name": "name.has.dots", "symbols": ["A", "B"]}"#, ) .unwrap(); assert_eq!(schema.named.len(), 1); assert_eq!( schema.named[0].name, FullName { name: "dots".into(), namespace: "name.has".into() } ); // Use default namespace when namespace is not provided. // Materialize uses "" as the default namespace. let schema = Schema::from_str( r#"{"type": "record", "name": "TestDoc", "doc": "Doc string", "fields": [{"name": "name", "type": "string"}]}"#, ) .unwrap(); assert_eq!(schema.named.len(), 1); assert_eq!( schema.named[0].name, FullName { name: "TestDoc".into(), namespace: "".into() } ); // Empty namespace strings should be allowed. let schema = Schema::from_str( r#"{"type": "record", "namespace": "", "name": "TestDoc", "doc": "Doc string", "fields": [{"name": "name", "type": "string"}]}"#, ) .unwrap(); assert_eq!(schema.named.len(), 1); assert_eq!( schema.named[0].name, FullName { name: "TestDoc".into(), namespace: "".into() } ); // Equality of names is defined on the FullName and is case-sensitive. let first = Schema::from_str( r#"{"type": "fixed", "namespace": "namespace", "name": "name", "size": 1}"#, ) .unwrap(); let second = Schema::from_str( r#"{"type": "fixed", "name": "namespace.name", "size": 1}"#, ) .unwrap(); assert_eq!(first.named[0].name, second.named[0].name); let first = Schema::from_str( r#"{"type": "fixed", "namespace": "namespace", "name": "name", "size": 1}"#, ) .unwrap(); let second = Schema::from_str( r#"{"type": "fixed", "name": "namespace.Name", "size": 1}"#, ) .unwrap(); assert_ne!(first.named[0].name, second.named[0].name); let first = Schema::from_str( r#"{"type": "fixed", "namespace": "Namespace", "name": "name", "size": 1}"#, ) .unwrap(); let second = Schema::from_str( r#"{"type": "fixed", "namespace": "namespace", "name": "name", "size": 1}"#, ) .unwrap(); assert_ne!(first.named[0].name, second.named[0].name); // The name portion of a fullname, record field names, and enum symbols must: // start with [A-Za-z_] and subsequently contain only [A-Za-z0-9_] assert!(Schema::from_str( r#"{"type": "record", "name": "99 problems but a name aint one", "fields": [{"name": "name", "type": "string"}]}"# ) .is_err()); assert!(Schema::from_str( r#"{"type": "record", "name": "!!!", "fields": [{"name": "name", "type": "string"}]}"# ) .is_err()); assert!(Schema::from_str( r#"{"type": "record", "name": "_valid_until_©", "fields": [{"name": "name", "type": "string"}]}"# ) .is_err()); // Use previously defined names and namespaces as type. let schema = Schema::from_str(r#"{"type": "record", "name": "org.apache.avro.tests.Hello", "fields": [ {"name": "f1", "type": {"type": "enum", "name": "MyEnum", "symbols": ["Foo", "Bar", "Baz"]}}, {"name": "f2", "type": "org.apache.avro.tests.MyEnum"}, {"name": "f3", "type": "MyEnum"}, {"name": "f4", "type": {"type": "enum", "name": "other.namespace.OtherEnum", "symbols": ["one", "two", "three"]}}, {"name": "f5", "type": "other.namespace.OtherEnum"}, {"name": "f6", "type": {"type": "enum", "name": "ThirdEnum", "namespace": "some.other", "symbols": ["Alice", "Bob"]}}, {"name": "f7", "type": "some.other.ThirdEnum"} ]}"#).unwrap(); assert_eq!(schema.named.len(), 4); if let SchemaPiece::Record { fields, .. } = schema.named[0].clone().piece { assert_eq!(fields[0].schema, SchemaPieceOrNamed::Named(1)); // f1 assert_eq!(fields[1].schema, SchemaPieceOrNamed::Named(1)); // f2 assert_eq!(fields[2].schema, SchemaPieceOrNamed::Named(1)); // f3 assert_eq!(fields[3].schema, SchemaPieceOrNamed::Named(2)); // f4 assert_eq!(fields[4].schema, SchemaPieceOrNamed::Named(2)); // f5 assert_eq!(fields[5].schema, SchemaPieceOrNamed::Named(3)); // f6 assert_eq!(fields[6].schema, SchemaPieceOrNamed::Named(3)); // f7 } else { panic!("Expected SchemaPiece::Record, found something else"); } let schema = Schema::from_str( r#"{"type": "record", "name": "x.Y", "fields": [ {"name": "e", "type": {"type": "record", "name": "Z", "fields": [ {"name": "f", "type": "x.Y"}, {"name": "g", "type": "x.Z"} ]} } ]}"#, ) .unwrap(); assert_eq!(schema.named.len(), 2); if let SchemaPiece::Record { fields, .. } = schema.named[0].clone().piece { assert_eq!(fields[0].schema, SchemaPieceOrNamed::Named(1)); // e } else { panic!("Expected SchemaPiece::Record, found something else"); } if let SchemaPiece::Record { fields, .. } = schema.named[1].clone().piece { assert_eq!(fields[0].schema, SchemaPieceOrNamed::Named(0)); // f assert_eq!(fields[1].schema, SchemaPieceOrNamed::Named(1)); // g } else { panic!("Expected SchemaPiece::Record, found something else"); } let schema = Schema::from_str( r#"{"type": "record", "name": "R", "fields": [ {"name": "s", "type": {"type": "record", "namespace": "x", "name": "Y", "fields": [ {"name": "e", "type": {"type": "enum", "namespace": "", "name": "Z", "symbols": ["Foo", "Bar"]} } ]}}, {"name": "t", "type": "Z"} ]}"#, ) .unwrap(); assert_eq!(schema.named.len(), 3); if let SchemaPiece::Record { fields, .. } = schema.named[0].clone().piece { assert_eq!(fields[0].schema, SchemaPieceOrNamed::Named(1)); // s assert_eq!(fields[1].schema, SchemaPieceOrNamed::Named(2)); // t - refers to "".Z } else { panic!("Expected SchemaPiece::Record, found something else"); } } // Tests to ensure Schema is Send + Sync. These tests don't need to _do_ anything, if they can // compile, they pass. #[test] fn test_schema_is_send() { fn send<S: Send>(_s: S) {} let schema = Schema { named: vec![], indices: Default::default(), top: SchemaPiece::Null.into(), }; send(schema); } #[test] fn test_schema_is_sync() { fn sync<S: Sync>(_s: S) {} let schema = Schema { named: vec![], indices: Default::default(), top: SchemaPiece::Null.into(), }; sync(&schema); sync(schema); } #[test] fn test_schema_fingerprint() { use md5::Md5; use sha2::Sha256; let raw_schema = r#" { "type": "record", "name": "test", "fields": [ {"name": "a", "type": "long", "default": 42}, {"name": "b", "type": "string"} ] } "#; let schema = Schema::from_str(raw_schema).unwrap(); assert_eq!( "5ecb2d1f0eaa647d409e6adbd5d70cd274d85802aa9167f5fe3b73ba70b32c76", format!("{}", schema.fingerprint::<Sha256>()) ); assert_eq!( "a2c99a3f40ea2eea32593d63b483e962", format!("{}", schema.fingerprint::<Md5>()) ); } }
36.158266
144
0.505864
c18f17c5385350c37897df9fc13350a63a1711f9
30,254
use std::collections::BTreeMap; use std::fmt::Debug; use std::net::SocketAddr; use std::str::FromStr; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, }; use futures::{ self, future::{self, Either}, sync::{mpsc, oneshot}, Async, AsyncSink, Future, IntoFuture, Sink, Stream, }; use tokio::net::TcpStream; use tokio::runtime::TaskExecutor; use tokio_codec; use crate::consumer::ConsumerOptions; use crate::error::{ConnectionError, SharedError}; use crate::message::{ proto::{self, command_subscribe::SubType}, Codec, Message, }; use crate::producer::{self, ProducerOptions}; pub enum Register { Request { key: RequestKey, resolver: oneshot::Sender<Message>, }, Consumer { consumer_id: u64, resolver: mpsc::UnboundedSender<Message>, }, } #[derive(Debug, Clone, PartialEq, Ord, PartialOrd, Eq)] pub enum RequestKey { RequestId(u64), ProducerSend { producer_id: u64, sequence_id: u64 }, } #[derive(Clone)] pub struct Authentication { pub name: String, pub data: Vec<u8>, } pub struct Receiver<S: Stream<Item = Message, Error = ConnectionError>> { inbound: S, outbound: mpsc::UnboundedSender<Message>, error: SharedError, pending_requests: BTreeMap<RequestKey, oneshot::Sender<Message>>, consumers: BTreeMap<u64, mpsc::UnboundedSender<Message>>, received_messages: BTreeMap<RequestKey, Message>, registrations: mpsc::UnboundedReceiver<Register>, shutdown: oneshot::Receiver<()>, } impl<S: Stream<Item = Message, Error = ConnectionError>> Receiver<S> { pub fn new( inbound: S, outbound: mpsc::UnboundedSender<Message>, error: SharedError, registrations: mpsc::UnboundedReceiver<Register>, shutdown: oneshot::Receiver<()>, ) -> Receiver<S> { Receiver { inbound, outbound, error, pending_requests: BTreeMap::new(), received_messages: BTreeMap::new(), consumers: BTreeMap::new(), registrations, shutdown, } } } impl<S: Stream<Item = Message, Error = ConnectionError>> Future for Receiver<S> { type Item = (); type Error = (); fn poll(&mut self) -> Result<Async<()>, ()> { match self.shutdown.poll() { Ok(Async::Ready(())) | Err(futures::Canceled) => return Err(()), Ok(Async::NotReady) => {} } //Are we worried about starvation here? loop { match self.registrations.poll() { Ok(Async::Ready(Some(Register::Request { key, resolver }))) => { match self.received_messages.remove(&key) { Some(msg) => { let _ = resolver.send(msg); } None => { self.pending_requests.insert(key, resolver); } } } Ok(Async::Ready(Some(Register::Consumer { consumer_id, resolver, }))) => { self.consumers.insert(consumer_id, resolver); } Ok(Async::Ready(None)) | Err(_) => { self.error.set(ConnectionError::Disconnected); return Err(()); } Ok(Async::NotReady) => break, } } loop { match self.inbound.poll() { Ok(Async::Ready(Some(msg))) => { if msg.command.ping.is_some() { let _ = self.outbound.unbounded_send(messages::pong()); } else if msg.command.message.is_some() { if let Some(consumer) = self .consumers .get_mut(&msg.command.message.as_ref().unwrap().consumer_id) { let _ = consumer.unbounded_send(msg); } } else { if let Some(request_key) = msg.request_key() { if let Some(resolver) = self.pending_requests.remove(&request_key) { // We don't care if the receiver has dropped their future let _ = resolver.send(msg); } else { self.received_messages.insert(request_key, msg); } } else { println!( "Received message with no request_id; dropping. Message: {:?}", msg.command ); } } } Ok(Async::Ready(None)) => { self.error.set(ConnectionError::Disconnected); return Err(()); } Ok(Async::NotReady) => return Ok(Async::NotReady), Err(e) => { self.error.set(e); return Err(()); } } } } } pub struct Sender<S: Sink<SinkItem = Message, SinkError = ConnectionError>> { sink: S, outbound: mpsc::UnboundedReceiver<Message>, buffered: Option<Message>, error: SharedError, shutdown: oneshot::Receiver<()>, } impl<S: Sink<SinkItem = Message, SinkError = ConnectionError>> Sender<S> { pub fn new( sink: S, outbound: mpsc::UnboundedReceiver<Message>, error: SharedError, shutdown: oneshot::Receiver<()>, ) -> Sender<S> { Sender { sink, outbound, buffered: None, error, shutdown, } } fn try_start_send(&mut self, item: Message) -> futures::Poll<(), ConnectionError> { if let AsyncSink::NotReady(item) = self.sink.start_send(item)? { self.buffered = Some(item); return Ok(Async::NotReady); } Ok(Async::Ready(())) } } impl<S: Sink<SinkItem = Message, SinkError = ConnectionError>> Future for Sender<S> { type Item = (); type Error = (); fn poll(&mut self) -> Result<Async<()>, ()> { match self.shutdown.poll() { Ok(Async::Ready(())) | Err(futures::Canceled) => return Err(()), Ok(Async::NotReady) => {} } if let Some(item) = self.buffered.take() { try_ready!(self.try_start_send(item).map_err(|e| self.error.set(e))) } loop { match self.outbound.poll()? { Async::Ready(Some(item)) => { try_ready!(self.try_start_send(item).map_err(|e| self.error.set(e))) } Async::Ready(None) => { try_ready!(self.sink.close().map_err(|e| self.error.set(e))); return Ok(Async::Ready(())); } Async::NotReady => { try_ready!(self.sink.poll_complete().map_err(|e| self.error.set(e))); return Ok(Async::NotReady); } } } } } #[derive(Clone)] pub struct SerialId(Arc<AtomicUsize>); impl SerialId { pub fn new() -> SerialId { SerialId(Arc::new(AtomicUsize::new(0))) } pub fn get(&self) -> u64 { self.0.fetch_add(1, Ordering::Relaxed) as u64 } } /// An owned type that can send messages like a connection #[derive(Clone)] pub struct ConnectionSender { tx: mpsc::UnboundedSender<Message>, registrations: mpsc::UnboundedSender<Register>, request_id: SerialId, error: SharedError, } impl ConnectionSender { pub fn new( tx: mpsc::UnboundedSender<Message>, registrations: mpsc::UnboundedSender<Register>, request_id: SerialId, error: SharedError, ) -> ConnectionSender { ConnectionSender { tx, registrations, request_id, error, } } pub fn send( &self, producer_id: u64, producer_name: String, sequence_id: u64, num_messages: Option<i32>, message: producer::Message, ) -> impl Future<Item = proto::CommandSendReceipt, Error = ConnectionError> { let key = RequestKey::ProducerSend { producer_id, sequence_id, }; let msg = messages::send( producer_id, producer_name, sequence_id, num_messages, message, ); self.send_message(msg, key, |resp| resp.command.send_receipt) } pub fn send_ping(&self) -> Result<(), ConnectionError> { self.tx .unbounded_send(messages::ping()) .map_err(|_| ConnectionError::Disconnected) } pub fn lookup_topic<S: Into<String>>( &self, topic: S, authoritative: bool, ) -> impl Future<Item = proto::CommandLookupTopicResponse, Error = ConnectionError> { let request_id = self.request_id.get(); let msg = messages::lookup_topic(topic.into(), authoritative, request_id); self.send_message(msg, RequestKey::RequestId(request_id), |resp| { resp.command.lookup_topic_response }) } pub fn lookup_partitioned_topic<S: Into<String>>( &self, topic: S, ) -> impl Future<Item = proto::CommandPartitionedTopicMetadataResponse, Error = ConnectionError> { let request_id = self.request_id.get(); let msg = messages::lookup_partitioned_topic(topic.into(), request_id); self.send_message(msg, RequestKey::RequestId(request_id), |resp| { resp.command.partition_metadata_response }) } pub fn create_producer( &self, topic: String, producer_id: u64, producer_name: Option<String>, options: ProducerOptions, ) -> impl Future<Item = proto::CommandProducerSuccess, Error = ConnectionError> { let request_id = self.request_id.get(); let msg = messages::create_producer(topic, producer_name, producer_id, request_id, options); self.send_message(msg, RequestKey::RequestId(request_id), |resp| { resp.command.producer_success }) } pub fn get_topics_of_namespace( &self, namespace: String, mode: proto::get_topics::Mode, ) -> impl Future<Item = proto::CommandGetTopicsOfNamespaceResponse, Error = ConnectionError> { let request_id = self.request_id.get(); let msg = messages::get_topics_of_namespace(request_id, namespace, mode); self.send_message(msg, RequestKey::RequestId(request_id), |resp| { resp.command.get_topics_of_namespace_response }) } pub fn close_producer( &self, producer_id: u64, ) -> impl Future<Item = proto::CommandSuccess, Error = ConnectionError> { let request_id = self.request_id.get(); let msg = messages::close_producer(producer_id, request_id); self.send_message(msg, RequestKey::RequestId(request_id), |resp| { resp.command.success }) } pub fn subscribe( &self, resolver: mpsc::UnboundedSender<Message>, topic: String, subscription: String, sub_type: SubType, consumer_id: u64, consumer_name: Option<String>, options: ConsumerOptions, ) -> impl Future<Item = proto::CommandSuccess, Error = ConnectionError> { let request_id = self.request_id.get(); let msg = messages::subscribe( topic, subscription, sub_type, consumer_id, request_id, consumer_name, options, ); match self.registrations.unbounded_send(Register::Consumer { consumer_id, resolver, }) { Ok(_) => {} Err(_) => { self.error.set(ConnectionError::Disconnected); return Either::A(future::failed(ConnectionError::Disconnected)); } } Either::B( self.send_message(msg, RequestKey::RequestId(request_id), |resp| { resp.command.success }), ) } pub fn send_flow(&self, consumer_id: u64, message_permits: u32) -> Result<(), ConnectionError> { self.tx .unbounded_send(messages::flow(consumer_id, message_permits)) .map_err(|_| ConnectionError::Disconnected) } pub fn send_ack( &self, consumer_id: u64, message_ids: Vec<proto::MessageIdData>, cumulative: bool, ) -> Result<(), ConnectionError> { self.tx .unbounded_send(messages::ack(consumer_id, message_ids, cumulative)) .map_err(|_| ConnectionError::Disconnected) } pub fn send_redeliver_unacknowleged_messages( &self, consumer_id: u64, message_ids: Vec<proto::MessageIdData>, ) -> Result<(), ConnectionError> { self.tx .unbounded_send(messages::redeliver_unacknowleged_messages( consumer_id, message_ids, )) .map_err(|_| ConnectionError::Disconnected) } pub fn close_consumer( &self, consumer_id: u64, ) -> impl Future<Item = proto::CommandSuccess, Error = ConnectionError> { let request_id = self.request_id.get(); let msg = messages::close_consumer(consumer_id, request_id); self.send_message(msg, RequestKey::RequestId(request_id), |resp| { resp.command.success }) } fn send_message<R: Debug, F>( &self, msg: Message, key: RequestKey, extract: F, ) -> impl Future<Item = R, Error = ConnectionError> where F: FnOnce(Message) -> Option<R>, { let (resolver, response) = oneshot::channel(); trace!("sending message(key = {:?}): {:?}", key, msg); let k = key.clone(); let response = response .map_err(|oneshot::Canceled| ConnectionError::Disconnected) .and_then(move |message: Message| { trace!("received message(key = {:?}): {:?}", k, message); extract_message(message, extract) }); match ( self.registrations .unbounded_send(Register::Request { key, resolver }), self.tx.unbounded_send(msg), ) { (Ok(_), Ok(_)) => Either::A(response), _ => Either::B(future::err(ConnectionError::Disconnected)), } } } pub struct Connection { addr: String, sender: ConnectionSender, sender_shutdown: Option<oneshot::Sender<()>>, receiver_shutdown: Option<oneshot::Sender<()>>, executor: TaskExecutor, } impl Connection { pub fn new( addr: String, auth_data: Option<Authentication>, proxy_to_broker_url: Option<String>, executor: TaskExecutor, ) -> impl Future<Item = Connection, Error = ConnectionError> { SocketAddr::from_str(&addr) .into_future() .map_err(|e| ConnectionError::SocketAddr(e.to_string())) .and_then(|addr| { TcpStream::connect(&addr) .map_err(|e| e.into()) .map(|stream| tokio_codec::Framed::new(stream, Codec)) .and_then(|stream| { stream .send({ let msg = messages::connect(auth_data, proxy_to_broker_url); trace!("connection message: {:?}", msg); msg }) .and_then(|stream| stream.into_future().map_err(|(err, _)| err)) .and_then(move |(msg, stream)| match msg { Some(Message { command: proto::BaseCommand { error: Some(error), .. }, .. }) => Err(ConnectionError::PulsarError(format!("{:?}", error))), Some(msg) => { let cmd = msg.command.clone(); trace!("received connection response: {:?}", msg); msg.command .connected .ok_or_else(|| { ConnectionError::PulsarError(format!( "Unexpected message from pulsar: {:?}", cmd )) }) .map(|_msg| stream) } None => Err(ConnectionError::Disconnected), }) }) }) .map(move |pulsar| { let (sink, stream) = pulsar.split(); let (tx, rx) = mpsc::unbounded(); let (registrations_tx, registrations_rx) = mpsc::unbounded(); let error = SharedError::new(); let (receiver_shutdown_tx, receiver_shutdown_rx) = oneshot::channel(); let (sender_shutdown_tx, sender_shutdown_rx) = oneshot::channel(); executor.spawn(Receiver::new( stream, tx.clone(), error.clone(), registrations_rx, receiver_shutdown_rx, )); executor.spawn(Sender::new(sink, rx, error.clone(), sender_shutdown_rx)); let sender = ConnectionSender::new(tx, registrations_tx, SerialId::new(), error); Connection { addr, sender, sender_shutdown: Some(sender_shutdown_tx), receiver_shutdown: Some(receiver_shutdown_tx), executor, } }) } pub fn error(&self) -> Option<ConnectionError> { self.sender.error.remove() } pub fn is_valid(&self) -> bool { self.sender.error.is_set() } pub fn addr(&self) -> &str { &self.addr } /// Chain to send a message, e.g. conn.sender().send_ping() pub fn sender(&self) -> &ConnectionSender { &self.sender } pub fn executor(&self) -> TaskExecutor { self.executor.clone() } } impl Drop for Connection { fn drop(&mut self) { if let Some(shutdown) = self.sender_shutdown.take() { let _ = shutdown.send(()); } if let Some(shutdown) = self.receiver_shutdown.take() { let _ = shutdown.send(()); } } } fn extract_message<T: Debug, F>(message: Message, extract: F) -> Result<T, ConnectionError> where F: FnOnce(Message) -> Option<T>, { if message.command.error.is_some() { Err(ConnectionError::PulsarError(format!( "{:?}", message.command.error.unwrap() ))) } else if message.command.send_error.is_some() { Err(ConnectionError::PulsarError(format!( "{:?}", message.command.error.unwrap() ))) } else { let cmd = message.command.clone(); if let Some(extracted) = extract(message) { trace!("extracted message: {:?}", extracted); Ok(extracted) } else { Err(ConnectionError::UnexpectedResponse(format!("{:?}", cmd))) } } } pub(crate) mod messages { use chrono::Utc; use crate::connection::Authentication; use crate::consumer::ConsumerOptions; use crate::message::{ proto::{self, base_command::Type as CommandType, command_subscribe::SubType}, Message, Payload, }; use crate::producer::{self, ProducerOptions}; pub fn connect(auth: Option<Authentication>, proxy_to_broker_url: Option<String>) -> Message { let (auth_method_name, auth_data) = match auth { Some(auth) => (Some(auth.name), Some(auth.data)), None => (None, None), }; Message { command: proto::BaseCommand { type_: CommandType::Connect as i32, connect: Some(proto::CommandConnect { auth_method_name, auth_data, proxy_to_broker_url, client_version: String::from("2.0.1-incubating"), protocol_version: Some(12), ..Default::default() }), ..Default::default() }, payload: None, } } pub fn ping() -> Message { Message { command: proto::BaseCommand { type_: CommandType::Ping as i32, ping: Some(proto::CommandPing {}), ..Default::default() }, payload: None, } } pub fn pong() -> Message { Message { command: proto::BaseCommand { type_: CommandType::Pong as i32, pong: Some(proto::CommandPong {}), ..Default::default() }, payload: None, } } pub fn create_producer( topic: String, producer_name: Option<String>, producer_id: u64, request_id: u64, options: ProducerOptions, ) -> Message { Message { command: proto::BaseCommand { type_: CommandType::Producer as i32, producer: Some(proto::CommandProducer { topic, producer_id, request_id, producer_name, encrypted: options.encrypted, metadata: options .metadata .iter() .map(|(k, v)| proto::KeyValue { key: k.clone(), value: v.clone(), }) .collect(), schema: options.schema, ..Default::default() }), ..Default::default() }, payload: None, } } pub fn get_topics_of_namespace( request_id: u64, namespace: String, mode: proto::get_topics::Mode, ) -> Message { Message { command: proto::BaseCommand { type_: CommandType::GetTopicsOfNamespace as i32, get_topics_of_namespace: Some(proto::CommandGetTopicsOfNamespace { request_id, namespace, mode: Some(mode as i32), }), ..Default::default() }, payload: None, } } pub fn send( producer_id: u64, producer_name: String, sequence_id: u64, num_messages: Option<i32>, message: producer::Message, ) -> Message { let properties = message .properties .into_iter() .map(|(key, value)| proto::KeyValue { key, value }) .collect(); Message { command: proto::BaseCommand { type_: CommandType::Send as i32, send: Some(proto::CommandSend { producer_id, sequence_id, num_messages, }), ..Default::default() }, payload: Some(Payload { metadata: proto::MessageMetadata { producer_name, sequence_id, properties, publish_time: Utc::now().timestamp_millis() as u64, replicated_from: None, partition_key: message.partition_key, replicate_to: message.replicate_to, compression: message.compression, uncompressed_size: message.uncompressed_size, num_messages_in_batch: message.num_messages_in_batch, event_time: message.event_time, encryption_keys: message.encryption_keys, encryption_algo: message.encryption_algo, encryption_param: message.encryption_param, schema_version: message.schema_version, }, data: message.payload, }), } } pub fn lookup_topic(topic: String, authoritative: bool, request_id: u64) -> Message { Message { command: proto::BaseCommand { type_: CommandType::Lookup as i32, lookup_topic: Some(proto::CommandLookupTopic { topic, request_id, authoritative: Some(authoritative), ..Default::default() }), ..Default::default() }, payload: None, } } pub fn lookup_partitioned_topic(topic: String, request_id: u64) -> Message { Message { command: proto::BaseCommand { type_: CommandType::PartitionedMetadata as i32, partition_metadata: Some(proto::CommandPartitionedTopicMetadata { topic, request_id, ..Default::default() }), ..Default::default() }, payload: None, } } pub fn close_producer(producer_id: u64, request_id: u64) -> Message { Message { command: proto::BaseCommand { type_: CommandType::CloseProducer as i32, close_producer: Some(proto::CommandCloseProducer { producer_id, request_id, }), ..Default::default() }, payload: None, } } pub fn subscribe( topic: String, subscription: String, sub_type: SubType, consumer_id: u64, request_id: u64, consumer_name: Option<String>, options: ConsumerOptions, ) -> Message { Message { command: proto::BaseCommand { type_: CommandType::Subscribe as i32, subscribe: Some(proto::CommandSubscribe { topic, subscription, sub_type: sub_type as i32, consumer_id, request_id, consumer_name, priority_level: options.priority_level, durable: options.durable, metadata: options .metadata .iter() .map(|(k, v)| proto::KeyValue { key: k.clone(), value: v.clone(), }) .collect(), read_compacted: options.read_compacted, initial_position: options.initial_position, schema: options.schema, start_message_id: options.start_message_id, ..Default::default() }), ..Default::default() }, payload: None, } } pub fn flow(consumer_id: u64, message_permits: u32) -> Message { Message { command: proto::BaseCommand { type_: CommandType::Flow as i32, flow: Some(proto::CommandFlow { consumer_id, message_permits, }), ..Default::default() }, payload: None, } } pub fn ack( consumer_id: u64, message_id: Vec<proto::MessageIdData>, cumulative: bool, ) -> Message { Message { command: proto::BaseCommand { type_: CommandType::Ack as i32, ack: Some(proto::CommandAck { consumer_id, ack_type: if cumulative { proto::command_ack::AckType::Cumulative as i32 } else { proto::command_ack::AckType::Individual as i32 }, message_id, validation_error: None, properties: Vec::new(), }), ..Default::default() }, payload: None, } } pub fn redeliver_unacknowleged_messages( consumer_id: u64, message_ids: Vec<proto::MessageIdData>, ) -> Message { Message { command: proto::BaseCommand { type_: CommandType::RedeliverUnacknowledgedMessages as i32, redeliver_unacknowledged_messages: Some( proto::CommandRedeliverUnacknowledgedMessages { consumer_id, message_ids, }, ), ..Default::default() }, payload: None, } } pub fn close_consumer(consumer_id: u64, request_id: u64) -> Message { Message { command: proto::BaseCommand { type_: CommandType::CloseConsumer as i32, close_consumer: Some(proto::CommandCloseConsumer { consumer_id, request_id, }), ..Default::default() }, payload: None, } } }
32.992366
100
0.491935
11570f7a031d4dcdb161f21c429b1b8f3c16938b
20,590
// Copyright 2019 The Exonum Team // // 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 exonum::helpers::Height; use exonum::{ messages::{AnyTx, Verified}, runtime::{ErrorMatch, SnapshotExt}, }; use exonum_btc_anchoring::{ blockchain::{errors::Error, BtcAnchoringInterface, SignInput}, btc::{self, BuilderError}, config::Config, test_helpers::{ create_fake_funding_transaction, get_anchoring_schema, AnchoringTestKit, ANCHORING_INSTANCE_ID, }, }; use exonum_crypto::KeyPair; use exonum_explorer::CommittedTransaction; use exonum_supervisor::ConfigPropose; fn assert_tx_error(tx: &CommittedTransaction, e: ErrorMatch) { assert_eq!( *tx.status().unwrap_err(), e.for_service(ANCHORING_INSTANCE_ID) ); } fn unspent_funding_transaction(anchoring_testkit: &AnchoringTestKit) -> Option<btc::Transaction> { get_anchoring_schema(&anchoring_testkit.inner.snapshot()).unspent_funding_transaction() } fn change_tx_signature(tx: Verified<AnyTx>, keypair: &KeyPair) -> Verified<AnyTx> { Verified::from_value( tx.into_payload(), keypair.public_key(), keypair.secret_key(), ) } fn test_anchoring_config_change<F>(mut config_change_predicate: F) -> AnchoringTestKit where F: FnMut(&mut AnchoringTestKit, &mut Config), { let mut anchoring_testkit = AnchoringTestKit::default(); let anchoring_interval = anchoring_testkit .actual_anchoring_config() .anchoring_interval; assert!(anchoring_testkit.last_anchoring_tx().is_none()); // Establish anchoring transactions chain. anchoring_testkit.inner.create_block_with_transactions( anchoring_testkit .create_signature_txs() .into_iter() .flatten(), ); // Skip the next anchoring height. anchoring_testkit .inner .create_blocks_until(Height(anchoring_interval * 2)); let last_anchoring_tx = anchoring_testkit.last_anchoring_tx().unwrap(); // Modify anchoring configuration. let mut new_cfg = anchoring_testkit.actual_anchoring_config(); let old_cfg = new_cfg.clone(); config_change_predicate(&mut anchoring_testkit, &mut new_cfg); // Commit configuration with without last anchoring node. anchoring_testkit.inner.create_block_with_transaction( anchoring_testkit.create_config_change_tx( ConfigPropose::new(0, anchoring_testkit.inner.height().next()) .service_config(ANCHORING_INSTANCE_ID, new_cfg.clone()), ), ); // Extract a previous anchoring transaction from the proposal. let (anchoring_tx_proposal, previous_anchoring_tx) = anchoring_testkit .anchoring_transaction_proposal() .map(|(tx, inputs)| (tx, inputs[0].clone())) .unwrap(); // Verify anchoring transaction proposal. { assert_eq!(last_anchoring_tx, previous_anchoring_tx); let snapshot = anchoring_testkit.inner.snapshot(); let schema = get_anchoring_schema(&snapshot); assert_eq!(schema.following_config().unwrap(), new_cfg); assert_eq!(schema.actual_config(), old_cfg); let (out_script, payload) = anchoring_tx_proposal.anchoring_metadata().unwrap(); // Height for the transition anchoring transaction should be same as in the latest // anchoring transaction. assert_eq!(payload.block_height, Height(0)); assert_eq!(&new_cfg.anchoring_out_script(), out_script); } // Finalize transition transaction anchoring_testkit.inner.create_block_with_transactions( anchoring_testkit .create_signature_txs() .into_iter() .flatten(), ); // Verify that the following configuration becomes an actual. let snapshot = anchoring_testkit.inner.snapshot(); let schema = get_anchoring_schema(&snapshot); assert!(schema.following_config().is_none()); assert_eq!(schema.actual_config(), new_cfg); assert_eq!( anchoring_tx_proposal.id(), anchoring_testkit.last_anchoring_tx().unwrap().id() ); // Verify that we have an anchoring transaction proposal. let anchoring_tx_proposal = anchoring_testkit .anchoring_transaction_proposal() .unwrap() .0; // Verify anchoring transaction metadata let tx_meta = anchoring_tx_proposal.anchoring_metadata().unwrap(); assert_eq!(tx_meta.1.block_height, Height(anchoring_interval)); assert_eq!( anchoring_testkit .actual_anchoring_config() .anchoring_out_script(), *tx_meta.0 ); anchoring_testkit } #[test] fn simple() { let mut anchoring_testkit = AnchoringTestKit::default(); let anchoring_interval = anchoring_testkit .actual_anchoring_config() .anchoring_interval; assert!(anchoring_testkit.last_anchoring_tx().is_none()); let signatures = anchoring_testkit .create_signature_txs() .into_iter() .flatten(); anchoring_testkit .inner .create_block_with_transactions(signatures) .transactions .iter() .try_for_each(|tx| tx.status()) .expect("Each transaction should be successful."); let tx0 = anchoring_testkit.last_anchoring_tx().unwrap(); let tx0_meta = tx0.anchoring_metadata().unwrap(); assert!(tx0_meta.1.block_height == Height(0)); anchoring_testkit .inner .create_blocks_until(Height(anchoring_interval)); // Ensure that the anchoring proposal has expected height. assert_eq!( anchoring_testkit .anchoring_transaction_proposal() .unwrap() .0 .anchoring_payload() .unwrap() .block_height, Height(anchoring_interval) ); let signatures = anchoring_testkit .create_signature_txs() .into_iter() .take(3) .flatten(); anchoring_testkit .inner .create_block_with_transactions(signatures); let tx1 = anchoring_testkit.last_anchoring_tx().unwrap(); let tx1_meta = tx1.anchoring_metadata().unwrap(); assert!(tx0.id() == tx1.prev_tx_id()); // script_pubkey should be the same assert!(tx0_meta.0 == tx1_meta.0); assert!(tx1_meta.1.block_height == Height(anchoring_interval)); } #[test] fn additional_funding() { let mut anchoring_testkit = AnchoringTestKit::default(); let anchoring_interval = anchoring_testkit .actual_anchoring_config() .anchoring_interval; assert!(anchoring_testkit.last_anchoring_tx().is_none()); // Establish anchoring transactions chain with the initial funding transaction. anchoring_testkit.inner.create_block_with_transactions( anchoring_testkit .create_signature_txs() .into_iter() .flatten(), ); // Add another funding transaction. let (txs, new_funding_tx) = anchoring_testkit.create_funding_confirmation_txs(150_000); anchoring_testkit.inner.create_block_with_transactions(txs); // Reach the next anchoring height. anchoring_testkit .inner .create_blocks_until(Height(anchoring_interval)); // Ensure that the anchoring proposal has input with the our funding transaction. assert_eq!( anchoring_testkit .anchoring_transaction_proposal() .unwrap() .1[1], new_funding_tx ); anchoring_testkit.inner.create_block_with_transactions( anchoring_testkit .create_signature_txs() .into_iter() .take(3) .flatten(), ); let tx1 = anchoring_testkit.last_anchoring_tx().unwrap(); let tx1_meta = tx1.anchoring_metadata().unwrap(); assert!(tx1_meta.1.block_height == Height(anchoring_interval)); assert_eq!(tx1.0.input[1].previous_output.txid, new_funding_tx.0.txid()); } #[test] fn err_spent_funding() { let anchoring_interval = 5; let mut anchoring_testkit = AnchoringTestKit::new(4, anchoring_interval); // Add an initial funding transaction to enable anchoring. let (txs, spent_funding_transaction) = anchoring_testkit.create_funding_confirmation_txs(20_000); anchoring_testkit .inner .create_block_with_transactions(txs.into_iter().skip(1)); assert!(anchoring_testkit.last_anchoring_tx().is_none()); // Establish anchoring transactions chain with the initial funding transaction. anchoring_testkit.inner.create_block_with_transactions( anchoring_testkit .create_signature_txs() .into_iter() .flatten(), ); // Try to add spent funding transaction. let block = anchoring_testkit.inner.create_block_with_transactions( anchoring_testkit .create_funding_confirmation_txs_with(spent_funding_transaction) .into_iter() .take(1), ); assert_tx_error( &block[0], ErrorMatch::from_fail(&Error::AlreadyUsedFundingTx), ); // Reach the next anchoring height. anchoring_testkit .inner .create_blocks_until(Height(anchoring_interval)); // Ensure that the anchoring proposal has no input with the spent funding transaction. assert_eq!( anchoring_testkit .anchoring_transaction_proposal() .unwrap() .1 .len(), 1 ); } #[test] fn insufficient_funds() { let mut anchoring_testkit = AnchoringTestKit::new(4, 5); { let snapshot = anchoring_testkit.inner.snapshot(); let schema = get_anchoring_schema(&snapshot); let proposal = schema .actual_proposed_anchoring_transaction(snapshot.for_core()) .unwrap(); assert_eq!(proposal, Err(BuilderError::NoInputs)); } // Replenish the anchoring wallet by the given amount of satoshis. anchoring_testkit .inner .create_block_with_transactions(anchoring_testkit.create_funding_confirmation_txs(20).0); // Check that we have not enough satoshis to create proposal. { let snapshot = anchoring_testkit.inner.snapshot(); let schema = get_anchoring_schema(&snapshot); let proposal = schema .actual_proposed_anchoring_transaction(snapshot.for_core()) .unwrap(); assert_eq!( proposal, Err(BuilderError::InsufficientFunds { balance: 20, total_fee: 1530 }) ); } } #[test] fn no_anchoring_proposal() { let mut anchoring_testkit = AnchoringTestKit::default(); let anchoring_interval = anchoring_testkit .actual_anchoring_config() .anchoring_interval; assert!(anchoring_testkit.last_anchoring_tx().is_none()); let mut signatures = anchoring_testkit.create_signature_txs(); let leftover_signatures = signatures.pop().unwrap(); anchoring_testkit .inner .create_block_with_transactions(signatures.into_iter().flatten()); // Anchor a next height. anchoring_testkit .inner .create_blocks_until(Height(anchoring_interval)); let signatures = anchoring_testkit .create_signature_txs() .into_iter() .flatten(); anchoring_testkit .inner .create_block_with_transactions(signatures); // Very slow node. let block = anchoring_testkit .inner .create_block_with_transactions(leftover_signatures); assert_tx_error( &block[0], ErrorMatch::from_fail(&Error::UnexpectedProposalTxId), ); } #[test] fn unexpected_anchoring_proposal() { let mut anchoring_testkit = AnchoringTestKit::default(); let anchoring_interval = anchoring_testkit .actual_anchoring_config() .anchoring_interval; assert!(anchoring_testkit.last_anchoring_tx().is_none()); let mut signatures = anchoring_testkit.create_signature_txs(); let leftover_signatures = signatures.pop().unwrap(); anchoring_testkit .inner .create_block_with_transactions(signatures.into_iter().flatten()); anchoring_testkit .inner .create_blocks_until(Height(anchoring_interval)); // Anchor a next height. let signatures = anchoring_testkit .create_signature_txs() .into_iter() .flatten(); anchoring_testkit .inner .create_block_with_transactions(signatures); // Wait until the next anchoring height becomes an actual. anchoring_testkit .inner .create_blocks_until(Height(anchoring_interval * 2)); // Very slow node let block = anchoring_testkit .inner .create_block_with_transactions(leftover_signatures); assert_tx_error( &block[0], ErrorMatch::from_fail(&Error::UnexpectedProposalTxId), ); } #[test] fn add_anchoring_node() { test_anchoring_config_change(|anchoring_testkit, cfg| { cfg.anchoring_keys.push(anchoring_testkit.add_node()); }); } #[test] fn remove_anchoring_node() { test_anchoring_config_change(|_, cfg| { cfg.anchoring_keys.pop(); }); } #[test] fn change_anchoring_node_without_funds() { test_anchoring_config_change(|anchoring_testkit, cfg| { cfg.anchoring_keys[0].bitcoin_key = anchoring_testkit.gen_bitcoin_key(); }); } #[test] fn add_anchoring_node_insufficient_funds() { let mut anchoring_testkit = AnchoringTestKit::new(4, 5); let anchoring_interval = anchoring_testkit .actual_anchoring_config() .anchoring_interval; // Add an initial funding transaction to enable anchoring. anchoring_testkit .inner .create_block_with_transactions(anchoring_testkit.create_funding_confirmation_txs(2000).0); assert!(anchoring_testkit.last_anchoring_tx().is_none()); // Establish anchoring transactions chain. anchoring_testkit.inner.create_block_with_transactions( anchoring_testkit .create_signature_txs() .into_iter() .flatten(), ); // Skip the next anchoring height. anchoring_testkit .inner .create_blocks_until(Height(anchoring_interval * 2)); // Add an anchoring node. let mut new_cfg = anchoring_testkit.actual_anchoring_config(); new_cfg.anchoring_keys.push(anchoring_testkit.add_node()); // Commit configuration with without last anchoring node. anchoring_testkit.inner.create_block_with_transaction( anchoring_testkit.create_config_change_tx( ConfigPropose::new(0, anchoring_testkit.inner.height().next()) .service_config(ANCHORING_INSTANCE_ID, new_cfg), ), ); anchoring_testkit.inner.create_block(); // Ensure that the anchoring transaction proposal is unsuitable. { let snapshot = anchoring_testkit.inner.snapshot(); let schema = get_anchoring_schema(&snapshot); let proposal = schema .actual_proposed_anchoring_transaction(snapshot.for_core()) .unwrap(); assert_eq!( proposal, Err(BuilderError::InsufficientFunds { total_fee: 1530, balance: 470 }) ); } // Add funds. let (txs, funding_tx) = anchoring_testkit.create_funding_confirmation_txs(2000); anchoring_testkit.inner.create_block_with_transactions(txs); // Ensure that we have a suitable transition anchoring transaction proposal. assert_eq!( anchoring_testkit .anchoring_transaction_proposal() .unwrap() .1[1], funding_tx ); } #[test] fn funding_tx_err_unsuitable() { let mut anchoring_testkit = AnchoringTestKit::default(); // Create weird funding transaction. let mut config = anchoring_testkit.actual_anchoring_config(); config.anchoring_keys.swap(3, 1); let funding_tx = create_fake_funding_transaction(&config.anchoring_address(), 10_000); // Check that it did not pass. let block = anchoring_testkit.inner.create_block_with_transactions( anchoring_testkit.create_funding_confirmation_txs_with(funding_tx), ); assert_tx_error( &block[0], ErrorMatch::from_fail(&Error::UnsuitableFundingTx), ); } #[test] fn funding_tx_override() { // Actually, we can override the funding transaction by another one. let anchoring_interval = 5; let mut anchoring_testkit = AnchoringTestKit::new(4, anchoring_interval); // Add an initial funding transaction to enable anchoring. let (txs, first_funding_transaction) = anchoring_testkit.create_funding_confirmation_txs(2000); anchoring_testkit.inner.create_block_with_transactions(txs); assert_eq!( unspent_funding_transaction(&anchoring_testkit).unwrap(), first_funding_transaction ); // Override the funding transaction by the second one. let (txs, second_funding_transaction) = anchoring_testkit.create_funding_confirmation_txs(2400); anchoring_testkit.inner.create_block_with_transactions(txs); assert_eq!( unspent_funding_transaction(&anchoring_testkit).unwrap(), second_funding_transaction ); } #[test] fn sign_input_err_unauthorized() { let mut testkit = AnchoringTestKit::default(); // Create sign_input transaction from the anchoring node. let tx = testkit .create_signature_tx_for_node(&testkit.inner.us()) .unwrap()[0] .clone(); // Re-sign this transaction by the other keypair. let malformed_tx = change_tx_signature(tx, &KeyPair::random()); // Commit this transaction and check status. let block = testkit.inner.create_block_with_transaction(malformed_tx); assert_tx_error( &block[0], ErrorMatch::from_fail(&Error::UnauthorizedAnchoringKey), ); } #[test] fn add_funds_err_unauthorized() { let mut testkit = AnchoringTestKit::default(); // Create add_funds transaction from the anchoring node. let tx = testkit.create_funding_confirmation_txs(100).0[0].clone(); // Re-sign this transaction by the other keypair. let malformed_tx = change_tx_signature(tx, &KeyPair::random()); // Commit this transaction and check status. let block = testkit.inner.create_block_with_transaction(malformed_tx); assert_tx_error( &block[0], ErrorMatch::from_fail(&Error::UnauthorizedAnchoringKey), ); } #[test] fn sing_input_err_no_such_input() { let mut testkit = AnchoringTestKit::default(); let us = testkit.inner.us(); // Create sign_input transaction for the anchoring node. let tx = testkit.create_signature_tx_for_node(&us).unwrap()[0] .payload() .parse::<SignInput>() .unwrap(); // Change input ID. let malformed_tx = us .service_keypair() .sign_input(ANCHORING_INSTANCE_ID, SignInput { input: 10, ..tx }); // Commit this transaction and check status. let block = testkit.inner.create_block_with_transaction(malformed_tx); assert_tx_error(&block[0], ErrorMatch::from_fail(&Error::NoSuchInput)); } #[test] fn sign_input_err_input_verification_failed() { let mut testkit = AnchoringTestKit::default(); let (first_node, second_node) = { let validators = testkit.inner.network().validators(); (validators[0].clone(), validators[1].clone()) }; // Create sign_input transaction for the first anchoring node. let tx = testkit.create_signature_tx_for_node(&first_node).unwrap()[0].clone(); // Re-sign this transaction by the second anchoring node. let malformed_tx = change_tx_signature(tx, &second_node.service_keypair()); // Commit this transaction and check status. let block = testkit.inner.create_block_with_transaction(malformed_tx); assert_tx_error( &block[0], ErrorMatch::from_fail(&Error::InputVerificationFailed) .with_description_containing("secp: signature failed verification"), ); } // TODO Implement tests for anchoring recovery [ECR-3581]
32.891374
100
0.682516
eb24a2b3782abbc11bc491bed755fe9b76797410
300,084
#[cfg(feature = "no_std")] use core::f64::consts::PI; #[cfg(not(feature = "no_std"))] use std::f64::consts::PI; pub const X0: [[f64; 1007]; 3] = [ [ 0.99986069925, 0.02506324281, 0.00835274807, 0.00010466796, 0.00003490608, 0.00003110838, 0.00002561408, 0.00002142365, 0.00001709161, 0.00001707934, 0.00001442753, 0.00001113027, 0.00000934484, 0.00000899854, 0.0000056682, 0.00000661858, 0.00000739644, 0.00000681381, 0.00000611293, 0.00000451129, 0.00000451985, 0.00000449743, 0.00000406291, 0.00000541115, 0.00000546682, 0.0000051378, 0.00000263916, 0.0000021722, 0.00000292146, 0.00000227915, 0.00000226835, 0.00000255833, 0.00000256157, 0.00000178679, 0.00000178303, 0.00000178303, 0.00000155471, 0.00000155246, 0.0000020764, 0.00000199988, 0.0000012897, 0.00000128155, 0.00000152241, 0.00000078109, 0.00000073503, 0.00000093001, 0.00000065526, 0.0000006324, 0.00000062961, 0.0000008587, 0.00000083233, 0.0000006285, 0.00000079971, 0.00000060043, 0.00000075613, 0.00000053731, 0.00000057574, 0.00000057574, 0.00000072385, 0.00000051135, 0.00000050604, 0.00000049613, 0.00000048009, 0.00000059233, 0.00000048264, 0.00000047368, 0.00000039225, 0.00000051307, 0.00000050639, 0.00000039555, 0.00000042757, 0.00000048941, 0.00000048302, 0.00000037971, 0.00000043643, 0.0000003183, 0.00000033959, 0.00000030184, 0.00000032562, 0.00000038887, 0.00000028515, 0.00000028873, 0.00000036633, 0.00000024984, 0.00000026364, 0.00000030326, 0.00000028166, 0.00000028001, 0.00000021157, 0.00000023113, 0.00000021642, 0.00000019448, 0.00000026055, 0.00000018232, 0.00000023248, 0.00000022785, 0.00000017091, 0.00000019399, 0.00000021067, 0.0000002131, 0.00000014189, 0.00000013864, 0.00000018884, 0.00000017875, 0.00000018602, 0.00000013605, 0.00000015064, 0.00000012969, 0.00000014403, 0.00000013311, 0.00000013645, 0.00000011583, 0.00000011405, 0.00000015057, 0.0000001433, 0.00000012375, 0.00000012366, 0.00000010016, 0.00000012435, 0.00000009513, 0.00000010997, 0.00000011583, 0.00000009034, 0.00000011842, 0.00000008869, 0.00000008614, 0.00000010312, 0.00000008411, 0.00000007911, 0.00000010379, 0.00000010374, 0.0000001048, 0.00000007404, 0.00000007357, 0.0000000982, 0.00000007018, 0.00000009668, 0.00000007545, 0.00000007202, 0.00000007144, 0.00000008883, 0.00000006626, 0.00000007015, 0.00000006159, 0.00000007413, 0.00000006355, 0.00000007286, 0.00000006314, 0.00000006257, 0.00000006484, 0.00000005803, 0.00000006391, 0.0000000753, 0.00000006921, 0.00000007626, 0.00000007531, 0.00000006902, 0.00000005434, 0.00000006223, 0.00000007296, 0.00000005833, 0.00000007171, 0.00000006251, 0.00000006251, 0.00000005683, 0.00000006383, 0.00000006194, 0.00000005036, 0.00000006774, 0.00000006224, 0.00000004621, 0.00000006293, 0.00000006297, 0.00000005186, 0.00000006196, 0.0000000616, 0.00000005414, 0.00000005413, 0.00000004863, 0.00000005711, 0.0000000515, 0.00000004269, 0.00000004017, 0.00000004069, 0.00000003993, 0.00000004016, 0.0000000529, 0.00000004831, 0.00000003487, 0.0000000412, 0.0000000441, 0.00000004023, 0.0000000398, 0.00000003173, 0.00000003293, 0.00000002935, 0.00000002979, 0.0000000398, 0.00000003892, 0.00000003042, 0.00000003608, 0.00000003721, 0.00000003581, 0.0000000288, 0.00000002806, 0.00000003626, 0.00000002794, 0.00000002729, 0.00000003625, 0.00000003206, 0.00000003556, 0.00000002856, 0.00000002611, 0.00000002535, 0.0000000352, 0.00000003434, 0.00000002572, 0.00000002647, 0.00000003026, 0.00000002378, 0.00000002979, 0.00000003082, 0.00000002716, 0.00000002215, 0.00000003032, 0.00000002421, 0.00000002275, 0.00000002466, 0.00000002529, 0.00000002015, 0.00000002218, 0.00000002005, 0.0000000201, 0.00000002641, 0.00000002438, 0.00000001893, 0.00000001893, 0.00000002156, 0.00000002071, 0.00000002395, 0.00000001954, 0.00000002006, 0.00000001776, 0.00000001964, 0.00000002332, 0.00000001863, 0.00000001928, 0.00000002436, 0.00000002163, 0.0000000225, 0.00000002052, 0.00000001886, 0.0000000217, 0.00000002058, 0.00000001774, 0.00000001841, 0.00000001578, 0.00000001577, 0.00000001541, 0.00000002012, 0.00000001543, 0.00000001543, 0.00000001513, 0.00000001489, 0.00000001639, 0.00000001443, 0.00000001337, 0.00000001797, 0.00000001488, 0.00000001453, 0.00000001349, 0.00000001477, 0.00000001688, 0.00000001491, 0.00000001471, 0.00000001263, 0.00000001685, 0.00000001375, 0.00000001641, 0.000000012, 0.00000001272, 0.00000001214, 0.00000001406, 0.00000001524, 0.00000001149, 0.00000001547, 0.0000000146, 0.00000001323, 0.00000001252, 0.00000001459, 0.00000001235, 0.00000001028, 0.0000000133, 0.00000001312, 0.00000001246, 0.00000000992, 0.00000000988, 0.00000001365, 0.0000000102, 0.00000001191, 0.00000001191, 0.00000000978, 0.00000000971, 0.00000000962, 0.00000001025, 0.0000000099, 0.00000000964, 0.00000000944, 0.00000000944, 0.00000001092, 0.00000001132, 0.00000000859, 0.00000001213, 0.00000000942, 0.00000000942, 0.00000001045, 0.00000000851, 0.0000000085, 0.00000000895, 0.0000000102, 0.00000000845, 0.00000000863, 0.00000000853, 0.00000000811, 0.00000000966, 0.00000000917, 0.00000001083, 0.00000000779, 0.00000000964, 0.00000000995, 0.00000000962, 0.00000000779, 0.0000000098, 0.0000000093, 0.00000000829, 0.00000000733, 0.00000000743, 0.00000000818, 0.00000000905, 0.00000000905, 0.00000000798, 0.00000000817, 0.00000000884, 0.00000000755, 0.00000000651, 0.00000000616, 0.00000000651, 0.00000000723, 0.00000000784, 0.00000000784, 0.00000000785, 0.00000000611, 0.00000000576, 0.0000000057, 0.00000000576, 0.0000000077, 0.00000000773, 0.00000000581, 0.00000000719, 0.00000000578, 0.00000000536, 0.00000000633, 0.00000000581, 0.00000000532, 0.00000000657, 0.00000000599, 0.0000000054, 0.0000000054, 0.00000000628, 0.00000000532, 0.00000000513, 0.00000000649, 0.00000000582, 0.00000000517, 0.00000000609, 0.00000000615, 0.00000000622, 0.00000000536, 0.00000000516, 0.00000000613, 0.00000000583, 0.00000000636, 0.00000000665, 0.00000000583, 0.00000000479, 0.00000000571, 0.00000000565, 0.00000000462, 0.00000000551, 0.00000000504, 0.00000000535, 0.0000000046, 0.00000000449, 0.00000000453, 0.00000000527, 0.00000000502, 0.00000000603, 0.00000000532, 0.0000000053, 0.00000000431, 0.00000000465, 0.00000000559, 0.00000000485, 0.00000000584, 0.0000000055, 0.00000000481, 0.00000000569, 0.00000000551, 0.00000000389, 0.00000000389, 0.00000000388, 0.00000000388, 0.00000000515, 0.00000000394, 0.00000000491, 0.0000000044, 0.00000000382, 0.00000000503, 0.00000000439, 0.00000000381, 0.00000000371, 0.00000000516, 0.00000000417, 0.00000000483, 0.00000000381, 0.00000000378, 0.00000000393, 0.00000000376, 0.00000000365, 0.00000000371, 0.00000000355, 0.00000000499, 0.00000000379, 0.00000000471, 0.00000000417, 0.00000000485, 0.00000000358, 0.00000000358, 0.00000000365, 0.00000000351, 0.00000000351, 0.00000000429, 0.00000000388, 0.00000000464, 0.00000000396, 0.00000000421, 0.00000000366, 0.0000000036, 0.00000000336, 0.00000000336, 0.00000000326, 0.00000000395, 0.0000000045, 0.00000000363, 0.00000000399, 0.00000000316, 0.0000000043, 0.00000000363, 0.00000000317, 0.00000000395, 0.00000000324, 0.00000000299, 0.00000000304, 0.00000000298, 0.00000000414, 0.00000000339, 0.00000000351, 0.00000000362, 0.00000000304, 0.00000000395, 0.0000000032, 0.00000000384, 0.00000000279, 0.00000000365, 0.00000000377, 0.00000000275, 0.00000000316, 0.00000000339, 0.00000000386, 0.00000000273, 0.00000000314, 0.00000000281, 0.00000000287, 0.00000000265, 0.00000000325, 0.00000000362, 0.00000000269, 0.00000000344, 0.00000000255, 0.00000000334, 0.00000000316, 0.00000000283, 0.00000000305, 0.0000000027, 0.00000000243, 0.00000000243, 0.00000000296, 0.00000000301, 0.00000000329, 0.00000000267, 0.00000000285, 0.00000000286, 0.00000000311, 0.00000000319, 0.00000000241, 0.00000000229, 0.00000000235, 0.00000000253, 0.00000000277, 0.00000000234, 0.00000000216, 0.00000000241, 0.00000000214, 0.00000000213, 0.0000000024, 0.00000000212, 0.00000000259, 0.00000000259, 0.00000000222, 0.00000000201, 0.00000000274, 0.00000000243, 0.00000000234, 0.00000000203, 0.00000000246, 0.00000000216, 0.0000000021, 0.00000000199, 0.0000000027, 0.00000000207, 0.00000000212, 0.00000000269, 0.00000000221, 0.00000000225, 0.00000000197, 0.00000000192, 0.00000000241, 0.00000000261, 0.00000000255, 0.00000000256, 0.00000000182, 0.0000000025, 0.00000000196, 0.00000000187, 0.00000000229, 0.00000000175, 0.00000000187, 0.00000000175, 0.00000000241, 0.00000000236, 0.00000000217, 0.00000000173, 0.00000000191, 0.00000000231, 0.00000000169, 0.00000000235, 0.00000000188, 0.00000000217, 0.0000000023, 0.00000000208, 0.00000000165, 0.00000000177, 0.00000000208, 0.00000000167, 0.00000000198, 0.00000000169, 0.00000000214, 0.00000000172, 0.00000000172, 0.00000000223, 0.00000000159, 0.00000000219, 0.00000000207, 0.00000000176, 0.0000000017, 0.0000000017, 0.00000000205, 0.00000000167, 0.0000000021, 0.00000000163, 0.00000000159, 0.00000000148, 0.00000000165, 0.00000000196, 0.00000000146, 0.00000000148, 0.00000000146, 0.00000000143, 0.00000000142, 0.0000000014, 0.00000000153, 0.00000000162, 0.00000000162, 0.00000000143, 0.00000000188, 0.00000000155, 0.00000000174, 0.00000000179, 0.00000000135, 0.00000000164, 0.00000000134, 0.00000000174, 0.00000000146, 0.00000000137, 0.00000000167, 0.00000000152, 0.00000000124, 0.00000000135, 0.00000000172, 0.00000000123, 0.00000000122, 0.0000000017, 0.00000000155, 0.0000000012, 0.00000000141, 0.0000000012, 0.00000000123, 0.00000000144, 0.00000000165, 0.00000000119, 0.00000000117, 0.00000000163, 0.00000000163, 0.00000000119, 0.00000000145, 0.00000000145, 0.00000000159, 0.00000000114, 0.00000000147, 0.00000000156, 0.00000000131, 0.00000000118, 0.00000000118, 0.00000000137, 0.00000000137, 0.00000000109, 0.00000000111, 0.00000000111, 0.00000000123, 0.00000000107, 0.00000000133, 0.00000000123, 0.00000000123, 0.00000000113, 0.00000000131, 0.0000000011, 0.0000000011, 0.00000000103, 0.00000000103, 0.00000000113, 0.00000000103, 0.00000000115, 0.00000000107, 0.00000000107, 0.00000000106, 0.00000000143, 0.00000000143, 0.00000000115, 0.00000000112, 0.00000000099, 0.00000000126, 0.00000000115, 0.000000001, 0.00000000107, 0.0000000012, 0.00000000138, 0.00000000138, 0.00000000105, 0.00000000135, 0.00000000104, 0.00000000098, 0.00000000111, 0.000000001, 0.00000000095, 0.0000000013, 0.0000000012, 0.00000000114, 0.00000000114, 0.00000000119, 0.00000000117, 0.00000000107, 0.00000000095, 0.0000000011, 0.0000000011, 0.00000000097, 0.00000000095, 0.00000000091, 0.00000000112, 0.00000000126, 0.000000001, 0.00000000127, 0.00000000119, 0.00000000089, 0.00000000126, 0.00000000093, 0.0000000012, 0.00000000118, 0.00000000099, 0.00000000095, 0.00000000089, 0.00000000124, 0.00000000089, 0.00000000096, 0.00000000096, 0.00000000103, 0.00000000099, 0.00000000099, 0.0000000009, 0.00000000086, 0.00000000086, 0.00000000098, 0.00000000098, 0.00000000086, 0.00000000118, 0.00000000117, 0.00000000083, 0.00000000092, 0.00000000085, 0.00000000101, 0.00000000088, 0.00000000113, 0.00000000083, 0.00000000082, 0.00000000087, 0.00000000107, 0.00000000084, 0.00000000084, 0.00000000107, 0.00000000082, 0.00000000105, 0.00000000105, 0.00000000114, 0.00000000082, 0.00000000112, 0.00000000102, 0.00000000102, 0.00000000092, 0.00000000083, 0.00000000112, 0.0000000008, 0.0000000008, 0.00000000088, 0.00000000081, 0.00000000092, 0.0000000011, 0.00000000087, 0.00000000085, 0.00000000078, 0.0000000008, 0.0000000008, 0.00000000079, 0.00000000088, 0.00000000081, 0.00000000093, 0.00000000088, 0.00000000096, 0.00000000106, 0.00000000097, 0.00000000081, 0.00000000077, 0.00000000076, 0.00000000098, 0.00000000083, 0.00000000079, 0.00000000096, 0.00000000096, 0.00000000075, 0.00000000074, 0.00000000074, 0.00000000073, 0.00000000073, 0.00000000085, 0.00000000072, 0.00000000072, 0.000000001, 0.00000000085, 0.00000000075, 0.00000000076, 0.00000000072, 0.00000000097, 0.00000000087, 0.0000000008, 0.0000000007, 0.0000000007, 0.0000000007, 0.00000000078, 0.0000000007, 0.00000000077, 0.00000000069, 0.00000000082, 0.00000000067, 0.00000000067, 0.00000000067, 0.00000000077, 0.0000000008, 0.0000000007, 0.0000000007, 0.00000000074, 0.00000000076, 0.00000000091, 0.00000000091, 0.00000000067, 0.00000000067, 0.00000000067, 0.00000000083, 0.0000000008, 0.00000000068, 0.00000000069, 0.00000000089, 0.00000000079, 0.00000000073, 0.00000000073, 0.00000000065, 0.00000000064, 0.00000000066, 0.00000000066, 0.00000000065, 0.00000000076, 0.00000000084, 0.00000000063, 0.00000000064, 0.00000000072, 0.00000000066, 0.00000000072, 0.00000000061, 0.00000000064, 0.00000000068, 0.00000000062, 0.00000000073, 0.0000000006, 0.00000000078, 0.0000000006, 0.00000000059, 0.00000000075, 0.00000000058, 0.0000000006, 0.00000000069, 0.00000000059, 0.00000000062, 0.00000000081, 0.00000000059, 0.00000000059, 0.00000000063, 0.00000000057, 0.00000000057, 0.0000000006, 0.00000000072, 0.00000000059, 0.00000000068, 0.00000000056, 0.00000000056, 0.00000000056, 0.00000000057, 0.00000000057, 0.00000000069, 0.00000000059, 0.00000000065, 0.00000000059, 0.00000000073, 0.00000000076, 0.00000000067, 0.00000000073, 0.00000000074, 0.0000000007, 0.0000000006, 0.00000000059, 0.00000000074, 0.00000000058, 0.00000000053, 0.00000000059, 0.00000000063, 0.00000000056, 0.00000000063, 0.0000000007, 0.00000000072, 0.00000000052, 0.00000000052, 0.00000000052, 0.00000000054, 0.00000000066, 0.00000000066, 0.00000000051, 0.00000000058, 0.00000000061, 0.00000000054, 0.00000000056, 0.00000000067, 0.00000000056, 0.00000000062, 0.00000000062, 0.0000000005, 0.0000000005, 0.0000000005, 0.0000000005, 0.00000000049, 0.00000000049, 0.00000000065, 0.00000000069, 0.00000000068, 0.00000000049, 0.0000000005, 0.00000000049, 0.00000000059, 0.0000000005, 0.00000000059, 0.00000000058, 0.00000000051, 0.00000000048, 0.00000000065, 0.00000000056, 0.00000000057, 0.00000000048, 0.00000000047, 0.0000000006, 0.00000000049, 0.0000000005, 0.00000000046, 0.00000000048, 0.00000000055, 0.00000000054, 0.0000000006, 0.00000000064, 0.00000000059, 0.00000000049, 0.00000000058, 0.00000000058, 0.00000000046, 0.00000000045, 0.00000000055, 0.00000000055, 0.00000000061, 0.00000000054, 0.00000000054, 0.00000000044, 0.00000000052, 0.00000000044, 0.00000000045, 0.00000000046, 0.00000000048, 0.00000000051, 0.00000000045, 0.00000000046, 0.00000000047, 0.00000000051, 0.00000000046, 0.00000000052, 0.00000000052, 0.00000000044, 0.00000000049, 0.00000000053, 0.00000000045, 0.00000000043, 0.00000000043, 0.00000000049, 0.00000000044, 0.00000000042, 0.00000000045, 0.00000000051, 0.00000000041, 0.00000000057, 0.00000000047, 0.00000000056, 0.0000000005, 0.00000000047, 0.00000000041, 0.00000000056, 0.00000000048, 0.00000000054, 0.00000000052, 0.00000000043, 0.00000000041, 0.00000000042, 0.00000000044, 0.00000000044, 0.00000000039, 0.0000000004, 0.00000000044, 0.0000000005, 0.00000000054, 0.00000000054, 0.00000000045, 0.00000000047, 0.00000000043, 0.00000000047, 0.00000000047, 0.0000000004, 0.00000000043, 0.00000000042, 0.00000000051, 0.00000000042, 0.00000000042, 0.00000000052, 0.0000000004, 0.0000000004, 0.0000000004, 0.00000000038, 0.00000000037, 0.00000000037, 0.00000000042, 0.00000000042, 0.00000000042, 0.0000000004, 0.00000000043, 0.00000000041, 0.00000000038, 0.0000000005, 0.0000000005, ], [ 1.75347045757, 4.93819429098, 1.71033525539, 1.66721984219, 4.44373803231, 0.66875189331, 0.5858860749, 1.09204474884, 0.49540863237, 6.15314019418, 3.47210398336, 3.69621650479, 6.07385378286, 3.17607463681, 2.15241946891, 1.31175222119, 4.36662524112, 2.2181539794, 5.38470180335, 6.09315891204, 1.27931036318, 5.36941929064, 0.54369369385, 0.78670634299, 1.46109463961, 4.4369503779, 5.3955175263, 4.51265697015, 2.51372357301, 1.23940916733, 3.27356345008, 2.26545070197, 1.45478864804, 2.96645630109, 0.40472561766, 6.24380795499, 1.62414733243, 1.41969109555, 5.85326148962, 4.0721683011, 5.21698329136, 4.80258701251, 0.86901699174, 1.84890519772, 2.69517697923, 3.93777887053, 3.6556833316, 2.24124127597, 4.40729385308, 3.02430778985, 6.19780778434, 2.03823135444, 2.49335782552, 3.39955163445, 4.15948190002, 1.5626889204, 3.96971590315, 2.6788176695, 4.85114866885, 1.31237333336, 5.34520074613, 2.64370047145, 4.00571885519, 3.78322753249, 4.77126143981, 6.10696378485, 3.25281924495, 5.78448747277, 2.05215225623, 4.93022654622, 3.64063452002, 0.45355151773, 0.60366334071, 3.04093006964, 3.14688065147, 2.00885127406, 1.72230567102, 3.96882361878, 2.84647033523, 5.36022568355, 6.10933021457, 1.01228967614, 2.90798803424, 2.17919076736, 0.54621601823, 1.99372292658, 0.48127325062, 2.82603231075, 5.07256589577, 0.8599693017, 4.63524157818, 4.40136974621, 0.30340363466, 3.4136209513, 6.19009992884, 1.1682184896, 0.58584172932, 4.43188457477, 3.80033599994, 4.65919931667, 1.30988546287, 4.59350621319, 2.42694418444, 0.15660631596, 0.50024326019, 5.19720916665, 3.1214803835, 6.06491705231, 1.4372592278, 3.60732173221, 5.14981984839, 5.46063496654, 4.40016025355, 5.21434071429, 6.02775140319, 3.10941922715, 3.53911446993, 2.24542867964, 1.06626484546, 1.19056065248, 2.19198404583, 4.05250824543, 5.42875830514, 4.16957446176, 5.04690919891, 1.60161199451, 2.59789642414, 2.44368872285, 3.15428722892, 4.81870974023, 2.40569215505, 2.95288921695, 5.4141904987, 3.83057351958, 3.69556241034, 1.23420241153, 1.92238869394, 1.23604547808, 5.883915377, 0.76464656573, 3.89630774866, 0.70123567856, 4.136223607, 0.94592300466, 5.03498725246, 5.03541099132, 3.58219614228, 6.22485628824, 4.23208117686, 3.20813291319, 6.09476150956, 3.9760152675, 0.20298795021, 0.69969701816, 4.29336813013, 3.51464444079, 2.75534627331, 5.94625981048, 2.24396249102, 5.9898204027, 2.32930728499, 6.14759594277, 2.19374266424, 4.45479090841, 3.49552871951, 0.64667497225, 3.56522608256, 3.83694551305, 1.99358309023, 0.35231413534, 1.34668136864, 2.32035231613, 4.40170593853, 0.71187314766, 2.58705857336, 4.78250009298, 2.9996195788, 3.65415218952, 3.76722359858, 4.32712250291, 4.10583483822, 2.38358764863, 3.785809031, 2.42056660765, 2.86272128776, 5.24041079205, 3.34482936009, 2.83916520281, 3.51068129706, 3.29656037233, 3.80589939396, 6.22474978871, 3.31931976159, 5.19128151293, 4.01637480858, 3.67590980046, 6.20067573402, 1.19681754169, 5.52571426134, 3.19425693799, 5.60952778146, 5.22104546686, 1.0399523122, 1.61225556126, 4.2155161422, 1.42632163253, 5.69269191706, 4.17319557124, 3.00192313835, 2.15397091751, 4.28947576556, 3.33625143564, 2.43261867894, 1.58310702384, 5.3798637151, 3.64656923781, 4.79831420582, 3.81972272861, 5.2407807498, 3.62833713669, 0.36159339669, 1.77514222265, 3.06935389211, 5.26643739208, 4.76553829426, 3.15326621321, 5.95465292259, 5.59166943387, 5.94709131586, 2.48432239832, 0.69324011482, 4.16423892775, 4.11254992503, 4.28275048815, 6.1291020556, 0.980574649, 5.66795892365, 2.0090223629, 4.3217914441, 0.13148357341, 0.37275781655, 0.31048315304, 0.14855204887, 0.2510315344, 4.40649103371, 5.26030609599, 4.59250450967, 4.4077082348, 1.41797907369, 2.39728922664, 5.23006608728, 3.61213584641, 5.49596575387, 4.69821533065, 2.08482289391, 0.34653293659, 5.64311385009, 0.8077955919, 1.80359816798, 0.36995312887, 0.68755069426, 5.96098287839, 0.65061890512, 2.95205535091, 4.44076102657, 2.26329309493, 3.06401553951, 6.18654785499, 5.67450527487, 5.460786546, 5.75097749599, 4.14004774348, 3.20087734666, 6.22974184712, 5.75779240419, 0.9172897135, 5.70877589839, 1.08927160683, 6.27664360507, 1.47556274227, 0.89738913067, 1.22660393299, 5.67596795657, 4.27066787572, 3.01961706159, 4.02915828753, 4.97235137781, 1.38571450422, 1.41166880118, 5.29807880334, 2.84096519816, 2.51029997292, 1.00065727327, 1.10091584033, 4.66430542078, 4.13817744468, 0.97969587833, 6.11146862666, 2.82319817767, 3.43008039922, 3.21845317343, 4.73852758176, 1.91000724147, 2.63568544853, 2.21768401152, 0.39039931315, 1.7919273993, 5.86379546667, 0.78473810598, 3.92065202481, 1.0062852297, 1.48109589441, 4.04235990086, 5.2279073711, 1.42062620155, 0.46195584294, 5.19678367921, 1.45204280805, 2.40089211752, 0.71539416375, 5.75499771232, 4.43158774725, 2.75614337272, 6.13459778682, 4.14597367445, 2.47007329129, 1.32514794865, 3.58339682996, 0.77431665261, 0.25423339373, 3.92658368218, 0.45683397157, 4.62590378445, 2.22316684933, 5.09643797682, 2.6094985693, 3.79905998257, 1.6436832849, 3.81538816339, 2.83314540925, 2.62501051906, 0.52083502825, 0.84319899817, 3.82941056281, 3.93683821152, 5.7047445182, 2.41491885723, 3.06743374106, 0.87758060898, 2.20169255256, 3.43654258027, 1.53152362816, 1.2279826083, 4.54665961586, 3.06908128494, 5.60311452827, 0.21363273558, 1.34025743471, 0.90840576142, 4.26997200274, 6.06660590951, 1.17258360285, 2.92798889289, 4.58762178742, 3.25871870022, 2.11793230261, 3.24412649701, 3.40440707563, 0.31668062965, 4.41105068397, 3.70291605445, 4.90568628758, 4.53092429894, 4.06133972007, 3.94494306228, 4.71270964329, 5.53858241889, 3.70224967645, 2.92986975188, 1.79095811234, 6.15311267171, 6.06042539245, 2.74682435671, 2.82325235087, 1.33548820034, 2.58673571504, 3.92092198777, 1.96630641591, 4.03874430699, 5.14547341413, 6.12277243019, 3.18401450277, 5.0983364913, 3.57566005736, 6.24827137997, 0.97407216668, 0.85487069842, 1.83659178149, 0.4349120389, 5.31145947559, 5.8329898198, 1.7156088001, 6.13610027053, 0.07138791653, 3.95560592819, 1.86946119801, 2.95240683895, 1.64539130884, 3.43047350256, 3.21806007009, 1.13963224225, 5.5089013304, 1.67075264819, 6.10437801091, 5.96788884074, 0.97316688838, 3.07660544855, 4.65767245093, 4.8256286915, 2.02484381212, 4.59067170554, 5.6142440724, 3.74461559548, 4.41750912984, 4.36951119319, 4.51952349691, 1.56678612595, 4.45581102621, 2.11020607854, 5.76233679446, 5.24317955258, 2.72562606986, 0.8162159788, 4.7829471194, 3.3307359169, 1.35444198321, 3.49115357527, 3.15737999738, 3.62050447597, 2.21887831196, 2.96356670458, 0.79790217165, 0.49080052992, 0.69464877419, 2.35908361907, 4.8273944432, 0.62612486089, 0.81896878015, 1.4133066775, 5.23522689515, 4.93781139708, 0.53943839302, 0.23150267191, 4.29615345291, 0.80548840004, 4.03075171777, 2.39021484637, 4.29069778349, 1.52889301942, 5.39427984473, 3.70774573147, 3.86306301151, 0.15985948407, 3.82763680613, 4.17890604161, 4.29176984719, 5.93395494462, 0.42214982034, 4.93815385347, 0.0772197183, 2.49901226571, 4.01872268681, 0.96409855547, 1.25425361388, 0.82514906124, 5.73507538514, 2.59688143484, 6.10829032638, 2.29032835664, 1.09519308783, 1.47223989608, 4.86653427016, 3.30150277561, 5.11010310272, 2.49278036693, 1.18157001338, 0.20537228942, 3.51559724211, 4.94623609008, 3.1330312426, 5.54205330844, 4.23095234926, 4.26252488384, 0.0521586717, 2.54680473739, 4.10172883526, 0.07899510796, 1.10648037942, 1.15683223901, 3.4201150532, 2.50494570372, 0.28647364691, 3.21063889136, 4.71059907821, 2.9943933077, 1.01522459538, 3.36978882786, 0.51356087882, 1.58719268637, 5.1257458531, 5.01445941939, 5.44670796756, 2.09481715597, 3.79438383373, 2.57405501441, 2.36637350989, 3.2172597467, 3.43127382595, 1.42789121927, 5.11101601554, 3.8538726179, 4.14346519403, 5.23697266935, 0.00533428175, 5.8365437948, 4.93054195434, 5.8249897147, 0.93528415346, 0.40019527935, 3.06628694399, 1.7547160672, 1.5266896007, 3.40184768346, 4.01628844723, 3.36122016267, 2.04581063866, 5.09422826, 5.60213035381, 0.53150571182, 2.30148639986, 4.41917983264, 4.24183231344, 2.21911266897, 4.75761261391, 0.16732487654, 5.41173900219, 5.47425531847, 4.58223305763, 0.28794939753, 2.0248530345, 5.02460023035, 1.08399000143, 6.27756282518, 2.60472823534, 5.11378923747, 3.4739610148, 5.5966291544, 4.97442863783, 2.40692408305, 0.72059454942, 2.37182548424, 4.7306797582, 4.59043597135, 3.97387947664, 3.26732644351, 3.73983013574, 4.34216809137, 1.25880044898, 5.38973312367, 4.9999084706, 3.90246086071, 5.40805183208, 3.49598218672, 4.05199209274, 6.0103953944, 0.63813817825, 5.87166506948, 5.5438552664, 0.88175440791, 1.4679623187, 4.85018558111, 0.75075299347, 0.87966880312, 3.57999903444, 0.39484750798, 2.67465416652, 0.23882077577, 0.85202349514, 5.37141800193, 1.22241558577, 1.79747194391, 3.70215026876, 4.78754155685, 2.32218951292, 3.68702080121, 6.15650399253, 5.71964679538, 5.30407615411, 0.07815962516, 5.60920106543, 5.44099179137, 4.27755511799, 1.55848605346, 2.60101256262, 1.27059509188, 4.19104806587, 5.79651030598, 3.38729000615, 4.942614472, 5.21069118841, 5.69263982892, 1.45223428169, 4.05745332726, 1.1914090758, 5.52535299558, 5.84076902832, 6.20892018031, 2.13726910032, 0.74320909184, 1.19695838858, 0.73795876397, 3.11536370558, 4.35849093916, 4.28708216617, 3.90603326867, 2.74250030398, 4.18513637906, 1.84089435963, 4.06094470975, 2.57788751226, 1.7066799759, 5.40927777429, 1.23925579836, 2.54415078163, 4.10438279102, 2.76724250809, 4.37410999057, 2.27442358208, 2.37617280556, 2.16622176546, 3.03066152119, 5.64258939044, 1.00594418221, 1.95402250286, 3.61193663544, 1.76186229885, 4.8866712738, 3.890438054, 2.75809551865, 2.20489389956, 4.57936207476, 2.668760799, 1.7202750438, 2.7588262647, 3.27680652019, 1.51224865614, 0.91984229557, 3.78326005147, 5.73842498855, 1.79019915134, 1.19294266238, 4.66544469064, 3.52903073097, 4.02566335272, 4.96595619835, 4.55918305844, 2.08935051421, 1.0335172481, 0.57056498904, 2.15061044327, 5.57514638218, 3.97355954616, 4.55824596261, 1.74741902247, 2.12273849218, 0.27869701115, 3.75372093481, 2.89481263784, 5.21922596573, 1.90078630587, 1.90914871846, 5.6330799185, 2.79120257993, 3.85733099272, 4.22068998833, 5.98375623165, 2.99457476326, 4.31165167302, 3.10862438843, 3.03286435761, 5.41503454763, 5.99165259734, 1.33458093593, 0.25750692887, 5.67599033319, 2.08797711521, 1.43212365415, 3.61958161583, 5.99715593195, 2.30094279014, 0.48008010598, 1.07338684504, 2.64494034094, 0.74221743876, 4.37747381017, 6.06683620849, 0.58169736416, 0.38965345976, 0.5983114156, 0.93909542206, 3.41472072058, 3.23381285207, 1.34148300572, 3.7384435938, 4.10902635534, 3.1413364551, 4.01226998426, 2.29415888429, 0.23020335948, 3.76744436736, 2.05049922518, 0.90577628609, 0.19375496576, 0.10696172464, 2.21757059467, 2.41107951633, 4.23745405632, 0.88149755532, 0.94957627406, 3.87374571694, 2.77478785571, 4.07080782247, 3.82951941927, 2.7088859404, 2.89783593458, 3.75069763806, 1.35671084183, 1.35246903804, 5.48905138227, 3.59069348639, 4.80792276932, 3.00407783628, 3.72088724498, 4.36458397294, 0.37007007331, 2.32197271603, 6.14240130116, 1.45118645187, 3.36946826019, 3.27906531246, 4.53816488559, 0.87069012239, 1.41865192078, 5.85619230131, 3.2490126448, 5.19394745813, 2.16665694222, 0.14089796919, 3.62140277149, 1.39348893935, 2.20964866296, 5.48885750823, 2.20640709608, 4.50777033878, 1.98497858569, 4.66355498696, 6.24025577336, 0.66729085356, 5.98124271908, 4.02724017625, 2.6212933964, 3.65241534932, 0.04178130909, 0.32356695638, 5.37794526764, 2.90983978106, 1.96590105616, 1.98227687206, 0.25938390676, 4.92418361725, 3.63417247018, 5.17587638062, 4.63132769081, 2.01720588184, 2.85493203288, 4.94849285823, 2.27501820444, 3.43499900992, 6.02127545231, 5.48703292615, 0.17045217443, 1.83540783927, 4.81312573338, 4.99636632687, 5.36758481138, 4.6017469201, 2.04678665255, 2.55353968467, 5.64799287134, 2.47526506655, 4.1732685061, 0.23293815799, 0.13241010748, 1.44106493302, 2.94569161083, 0.77941152413, 3.64312239532, 2.14076318935, 1.999807432, 1.67507258686, 2.11438932219, 4.53414425046, 3.66592557921, 4.23436375372, 2.69579215047, 3.95274142218, 5.01328627787, 6.17321822941, 5.21213167261, 4.27995662426, 0.09093186873, 0.54185576116, 2.78134607936, 1.59783352501, 5.48721212671, 0.75473231286, 2.90814349886, 0.67966569221, 6.18332621846, 3.22950754418, 4.56094059497, 4.47214922427, 2.55184049976, 4.42124944201, 0.47683719349, 0.20507190989, 5.82409350668, 0.42390666617, 2.87556762555, 1.27058846781, 2.68580345393, 3.96273011871, 2.13380171799, 4.87646676285, 0.02714811761, 2.20528431296, 4.16486482248, 3.82312915284, 2.71579349818, 4.67855976016, 1.96997381249, 2.52728721608, 3.09052199581, 3.55801157684, 1.90302432953, 0.79584524101, 0.39208551086, 3.3850318073, 0.51774809611, 2.34882980338, 2.11713130342, 6.00949211634, 4.74855693255, 1.56579326622, 0.37222072501, 2.60537764043, 5.912073328, 3.15618940951, 2.11594966811, 1.05069506955, 3.66132366701, 4.02457482788, 0.59069175384, 3.26289105386, 1.0551604213, 5.6776348074, 4.87358219235, 1.7749513803, 3.61747287023, 4.36702417592, 1.22543152233, 0.84172627776, 4.29307138428, 5.44071514919, 4.73181482869, 2.77114790322, 2.31997560907, 1.94933767144, 2.18007483018, 4.46845874247, 1.53914825533, 1.32272515661, 1.95397557344, 4.69455799921, 5.07674655291, 5.07674655291, 0.63077087865, 3.59016732594, 6.19031950148, 2.44170258748, 3.95175048363, 0.2698739409, 2.11910349639, 3.21674377716, 4.28455887932, 1.59500717257, 3.00541030027, 4.80655958998, 3.2087004671, 4.19440679704, 0.99121344005, 5.23363777755, 1.10988199958, 1.97427905695, 3.72444308522, 5.17708029533, 2.75949485809, 2.83397317642, 4.7776401571, 4.33153690679, 1.72047044215, 4.40652103235, 5.1803876551, 5.16566622453, 1.2407534903, 5.40778008235, 6.066999513, 1.62616739636, 3.56883579861, 0.42724314502, 5.1042759464, 2.79730041476, 3.85123315789, 3.20288072834, 5.42298629738, 1.12093494405, 2.78871592108, 2.27794751316, 6.20709507263, 0.20647678216, 4.21002666289, 4.72419290173, 0.82323755553, 2.88192111957, 4.04752097938, 6.21526623133, 0.43326734132, 5.37917268925, 5.19212576524, 3.1037291002, 6.22187415, 3.11607958976, 1.76871622593, 1.97645700808, 3.04557845219, 1.28858480303, 4.79112566977, 4.52703512787, 0.43156198612, 2.81178684757, 4.46091937774, 0.65497165024, 4.15809563419, 0.89798744348, 4.27548568888, 2.85120735939, 2.50261741205, 0.83831240155, 4.41165168727, 4.69793524808, 3.56154893542, 1.54738888492, 1.44765859641, 5.20087497624, 0.38205897719, 5.88641926833, 5.28307931868, 5.69294803866, 4.69164296803, 1.95689060462, 5.54499872381, 1.12158335918, 1.36615498859, 1.95434456607, 4.50829221159, 2.60727518415, 5.81439105801, 3.96208965107, 2.46325624829, 1.94770311943, 4.70083045322, 3.53311914292, 1.5094815182, 0.29378456988, 0.07156369559, 2.24525725009, 0.27418012894, 0.09116813653, 0.79913949254, 2.85822305358, 3.79031051907, 3.6434787266, 0.65521409425, 3.95515629208, 2.90982798521, 1.62788860301, 2.84763289309, ], [ 6283.3196674749, 0.2438174835, 12566.3955174663, 18849.4713674577, 6282.83203250789, 83997.09113559539, 529.9347825781, 1577.0997249643, 6279.7965491259, 6286.84278582391, 2353.1099712553, 5223.4501023187, 12036.7045523717, 10213.5293636945, 1059.6257476727, 5753.6287023803, 398.3928208917, 4705.9761250271, 6813.0106325695, 5885.1706640667, 6257.0213476751, 6309.61798727471, 6681.46867088311, 775.7664288075, 14143.7390599141, 7860.6632099227, 5507.7970561509, 11507.0135872771, 5507.3094211839, 7058.8422787989, 4693.75913722409, 12168.2465140581, 710.1768660418, 796.5418242999, 6283.25235717211, 6283.3869777777, 25132.5472174491, 5487.0216606585, 11790.8729061423, 17790.08943726851, 7079.61767429131, 3739.0052475915, 213.5429129215, 8827.6340873583, 1589.3167127673, 9437.5191174035, 11770.0975106499, 6262.5442719825, 6304.0950629673, 167284.005405149, 3340.8562441833, 7.3573644843, 6070.0205720369, 4137.1542509997, 6496.6187629129, 1194.6908277081, 6284.2999885431, 6282.3393464067, 10976.83498721549, 6290.4332144757, 6276.2061204741, 6127.8992680407, 6438.7400669091, 3154.4432674121, 801.5771136403, 3128.6325825793, 8429.4850839501, 12353.0964220283, 11856.462468908, 5481.4987363511, 17260.3984721739, 9225.7830907665, 2544.07060239989, 426.8420083595, 5856.23384163189, 2145.92159899169, 7085.1405985987, 10977.32262218251, 4164.0681721295, 13367.7288136231, 12569.91863581531, 3930.4535137031, 18073.9487561337, 26.0545023163, 9438.0067523705, 4535.3032544079, 12562.8723991173, 5088.8726572503, 11371.9485072417, 5223.93773728571, 12559.2819704655, 12565.9078824993, 71430.45180064559, 1747.7725955835, 18319.7804023631, 5753.14106741329, 4933.4522578161, 10447.14402212089, 7477.7666776995, 8031.3360805419, 2942.7072407751, 8636.18582124671, 156137.71980228278, 1592.8398311163, 17297.9385098427, 13096.0864825609, 16496.6052136859, 7633.1870771337, 20426.8149099055, 12139.7973265903, 13368.2164485901, 5331.6012612243, 529.44714761109, 7084.6529636317, 7342.7015976641, 6279.72923882311, 6286.9100961267, 397.9051859247, 15110.7099373497, 7235.0380737255, 10989.0519750185, 5729.7502646325, 9623.9320941747, 15721.0826023619, 6148.2545874395, 6418.38474751031, 6836.8890703173, 14712.5609339415, 2119.00767786191, 1349.62359217529, 5486.53402569149, 5999.4603486097, 6040.5910635009, 5088.3850222833, 6567.1789863401, 6526.04827144891, 21228.1482060623, 12540.0971976665, 6245.2919948391, 6321.3473401107, 5642.93474619389, 5327.7199258663, 7860.17557495569, 12964.5445208745, 23543.4743221653, 1990.9888345245, 537.0483295789, 951.4745887671, 4690.7236538421, 16730.70750707931, 955.3559241251, 24073.1652872599, 10973.7995038335, 522.8212355773, 22004.1584523533, 18422.8731765817, 155.17658195069, 7238.9194090835, 18451.3223640495, 16730.21987211229, 640.1411037975, 3929.96587873609, 6277.7967431675, 6288.8425917823, 1551.2890401315, 5216.33655531789, 5230.5636493195, 14314.4119305333, 102.84895673509, 11014.8626598513, 553.32558535889, 5650.5359281617, 26088.1469590577, 77714.015285604, 84672.2320270212, 239424.6340718364, 6180.2268932563, 6386.4124416935, 90280.1669855868, 6916.1034067881, 1577.5873599313, 7875.91568110771, 6254.8704800071, 3634.37720703489, 6311.7688549427, 4690.23601887509, 25158.3579022819, 5760.7422493811, 10447.6316570879, 6709.91785835091, 6805.89708556871, 4731.7868098599, 5856.7214765989, 1066.7392946735, 9917.45305702629, 12592.6938372661, 12566.4628277691, 13341.9181287903, 75.0254160508, 18053.1733606413, 6208.5380689076, 5966.9277978183, 6358.1012660422, 10575.6505004253, 5863.8350235997, 6599.7115371315, 8030.8484455749, 3.76693583251, 6020.2357441021, 11506.52595231009, 8428.9974489831, 12721.8159169005, 6702.8043113501, 31415.6230674405, 250570.9196747026, 6546.4035908477, 5884.68302909969, 2352.6223362883, 13916.2629271251, 2389.1378379327, 12566.32820716351, 14945.0723560709, 12029.5910053709, 13362.6935242827, 29088.5675985015, 11015.3502948183, 6077.1341190377, 16200.52890701769, 12043.8180993725, 6262.96434807611, 6489.5052159121, 6303.6749868737, 4700.87268422489, 4590.6663630055, 149.8070146181, 6279.4383321169, 6287.2010028329, 18139.5383188994, 11926.4982311523, 1162.7185218913, 13518.1139237169, 3154.9309023791, 13521.9952590749, 4686.6455902233, 10022.0810975829, 242.97242145751, 5746.5151553795, 95143.3767384616, 6037.4880212455, 12669.4882916849, 6529.1513137043, 7238.4317741165, 19651.2922985815, 23013.7833570707, 6820.1241795703, 65147.37595065419, 4292.5746504339, 7632.6994421667, 13119.9649203087, 4292.0870154669, 6293.95633282471, 6272.6830021251, 20.5315780089, 110.45013870291, 17655.0243572331, 1052.51220067191, 2544.5582373669, 33018.7772947211, 76.50988875911, 633.0275567967, 6016.7126257531, 12779.6946129043, 18875.2820522905, 9411.7084325707, 18636.1722720197, 12573.5090644671, 25934.3681485729, 2378.9206560881, 6.86972951729, 11499.9000402763, 6549.9267091967, 10973.3118688665, 11790.3852711753, 18209.5740811437, 10177.5014970171, 11926.01059618529, 246.0754637129, 8661.9965060795, 6993.2527160332, 38.3768531213, 24357.0246061251, 6112.6467968557, 2146.4092339587, 12491.613918899, 5429.63565075589, 6453.9925380941, 8274.0646845159, 11371.4608722747, 4732.2744448269, 6290.36590417291, 6276.2734307769, 6247.2918007975, 6319.34753415231, 12565.4151963981, 12545.6201219739, 4694.2467721911, 3893.93801205869, 6259.44122972711, 6307.1981052227, 17797.2029842693, 17782.9758902677, 1692.40948698591, 82576.73740351178, 6298.57213865991, 6268.0671962899, 15508.8589407579, 6173.1133462555, 6393.5259886943, 3904.1551939033, 220.6564599223, 17256.8753538249, 949.4194264533, 16201.0165419847, 4803.9654584435, 206.42936592071, 149854.6439522914, 36948.9869909407, 2648.6986429565, 796.0541893329, 11403.9208130585, 12567.37583853451, 10213.0417287275, 22805.4917485101, 2787.2868413409, 5120.35732810009, 10575.1628654583, 7834.3648901229, 5572.8989839496, 6284.8041401832, 6281.8351947666, 12410.9751180321, 12416.8323203317, 22483.60475700909, 4060.97539791089, 17259.91083720689, 1596.43025976811, 1748.2602305505, 161000.92955515758, 4907.05823266209, 7234.5504387585, 846.3266522347, 853.4401992355, 12323.6669134923, 12587.1709129587, 13915.77529215809, 6069.53293706989, 6133.2688353733, 11933.6117781531, 15720.5949673949, 8662.48414104651, 18852.9944858067, 52176.0501006319, 5334.1440585051, 18842.3578204569, 5849.1202946311, 6151.7777057885, 6286.6060248927, 6280.0333100571, 17298.4261448097, 11514.1271342779, 12456.1891962469, 11764.5745863425, 6414.8616291613, 3340.36860921629, 10420.23010099111, 10983.94853421629, 5326.5428765373, 7232.49527644471, 433.9555553603, 10969.72144021469, 5863.3473886327, 26735.7014447297, 40879.1966871603, 12592.2062022991, 5547.4431539431, 6062.9070250361, 4171.1817191303, 3104.6862419403, 6503.7323099137, 15670.83794192309, 173567.0812551404, 3495.78900865049, 4274.27449334889, 9387.76209193169, 24602.8562523545, 12490.1294461907, 322711.54834139, 5120.8449630671, 18845.9482491087, 7019.19618100671, 8827.14645239129, 1582.2031657665, 29296.8592070621, 72850.8055327292, 213.0552779545, 14.47091148511, 97238.871361971, 14313.9242955663, 6245.1866318371, 6321.4527031127, 6297.5467614765, 6269.0925734733, 12320.56387123691, 4156.95462512869, 1479.11039154791, 5650.0482931947, 9917.9406919933, 17157.3056979553, 233141.55822184499, 14143.2514249471, 5643.4223811609, 135.30889751891, 13760.8425276909, 9779.3524936089, 14919.2616712381, 17267.5120191747, 7872.39256275871, 13517.62628874989, 6923.2169537889, 13625.7774476555, 10874.2298479639, 161710.8626037159, 3185.43584474911, 11712.71150074729, 22779.6810636773, 12528.26248182851, 6295.0490203109, 6271.5903146389, 6836.40143535029, 11617.21990849651, 205.9417309537, 3894.4256470257, 956.53297345411, 23581.5019948011, 5231.0512842865, 7445.7943718827, 17253.2849251731, 21393.7857873411, 6279.3875142118, 6287.251820738, 1059.1381127057, 5642.4420600927, 1385.3177574676, 22484.0923919761, 16858.7263504167, 20995.6367839329, 19650.8046636145, 7335.5880506633, 11769.6098756829, 5905.94605955911, 37.7838551523, 641.12142486571, 5750.1055840313, 1350.1112271423, 44809.4063833799, 3.6883357796, 12345.9828750275, 21953.91379191449, 29826.5501721567, 4176.2851599325, 10818.3791043993, 10177.01386205009, 10970.2090751817, 6660.6932753907, 29864.5778447925, 20597.4877805247, 316.6356871401, 6924.1972748571, 2636.9692901205, 26709.8907598969, 14945.5599910379, 16858.23871544969, 18073.46112116669, 19379.1623325523, 12360.2099690291, 30665.9111409493, 6816.53375091851, 6147.69434246491, 1376.0176173293, 6418.9449924849, 6055.8435346859, 28287.2343023447, 16522.4158985187, 283.6155013817, 6255.9181113781, 6310.7212235717, 6129.5408569901, 6510.7958002639, 377.6174253993, 24705.9490265731, 5469.7693835151, 6437.0984779597, 11720.3126827151, 169379.5000286584, 632.5399218297, 1265.81129610991, 4487.57358878689, 4377.3672675675, 419.2408263917, 11713.1991357143, 10454.25756912169, 103.3365917021, 2222.1004520805, 30356.2411372513, 6309.1303523077, 262.84010588929, 6283.56348495841, 6283.0758499914, 10440.03047512009, 5746.0275204125, 23581.0143598341, 7096.8699514347, 5573.3866189166, 16460.08971204149, 8672.21368792411, 5437.23683272371, 9381.2034902007, 11216.5281078075, 284.1031363487, 12562.80508881451, 7129.4025022261, 70755.31090921978, 77713.52765063698, 5635.8211991931, 14712.07329897449, 17272.1278250099, 15907.0079441661, 48739.6160795995, 6206.5659612323, 224.5886131854, 18848.98373249069, 5934.39524702691, 16460.5773470085, 22003.6708173863, 2942.21960580809, 11614.6771112157, 9778.8648586419, 3744.5835282543, 8390.3541750173, 1.7282901918, 17996.2749857057, 6275.71848550709, 394.86970254271, 34596.1208371689, 6438.2524319421, 17256.38771885789, 401.91593924071, 10984.4361691833, 6632.2440879229, 11087.5289434019, 743.23387801611, 4796.85191144269, 3097.64000524229, 5714.4977934475, 5539.8419719753, 12132.6837795895, 24492.6499311351, 6233.5626420031, 6333.0766929467, 266.85085920531, 13199.1792567795, 10344.05124790229, 12569.9859461181, 12012.8261146239, 6294.36536773881, 6272.273967211, 13119.47728534169, 17686.9966630499, 13521.50762410789, 802.0647486073, 5017.2645538815, 419.72846135871, 20199.3387771165, 33326.33491569069, 19800.7021387413, 6852.1415415023, 17370.6047933933, 5618.5636223449, 17654.5367222661, 2008.8013566425, 5436.7491977567, 775.2787938405, 12552.1684234647, 5010.1510068807, 28.6930049513, 11610.1063614957, 20452.6255947383, 27511.2240560537, 12431.3304374309, 28767.1682419675, 16840.9138282987, 19805.0711090663, 12701.4605975017, 11.2895177474, 17473.6975676119, 16627.6147328607, 6948.0757126049, 3531.2844328163, 167959.1462965748, 23013.29572210369, 3583.5848481573, 333857.8339442562, 6058.48723680599, 12809.12412144031, 162420.7956522742, 12528.3678448305, 25933.8805136059, 95.7354097343, 52669.8257758191, 19247.6203708659, 11610.7957758577, 661.4767442645, 9929.6700448293, 12250.0036478097, 6205.6458970469, 6360.99343790291, 228278.3484689702, 19402.55313533309, 38526.3305333885, 4307.8271216189, 21228.63584102931, 6263.64990657511, 6302.9894283747, 6315.8522182663, 6250.7871166835, 11925.5179100841, 6226.4212925393, 6340.2180424105, 24734.3982140409, 12463.30274324771, 18875.76968725751, 6260.5444660241, 6306.09486892571, 2111.8941308611, 18415.7596295809, 6289.94822637491, 6276.69110857489, 6241.7688764901, 6324.8704584597, 3496.2766436175, 10344.5388828693, 24336.2492106327, 83974.0791732134, 84020.1030979774, 12772.58106590351, 2069.2506523901, 18773.2052961821, 3641.4907540357, 11499.41240530929, 11190.6217176205, 18823.1730476579, 12570.3276707294, 16062.4283436003, 5216.8241902849, 9814.36028280769, 6210.0225416159, 6356.6167933339, 12721.32828193349, 18699.9081703231, 12560.8725931589, 5815.3546771205, 10239.3400485273, 263.3277408563, 155.6642169177, 27511.7116910207, 31441.4337522733, 6155.3008241375, 6411.3385108123, 951.9622237341, 28236.98964190589, 21.0192129759, 11300.8280388399, 6312.74917601091, 6253.8901589389, 78263.95324220609, 23938.1002072245, 12829.4794408391, 16737.8210540801, 3.2793008655, 6133.7564703403, 1293.24040609909, 17893.1822114871, 23539.9512038163, 311565.2627385237, 736.1203310153, 14158.9915310991, 16061.94070863329, 6432.8828646095, 2699.49100183409, 15671.3255768901, 178430.2910080152, 6751.28465782931, 7349.81514466491, 24066.0517402591, 18202.4605341429, 6252.40554183991, 6314.2337931099, 58864.30010066279, 9380.71585523369, 10557.35034334029, 6439.7203879773, 6126.91894697251, 23123.9896782901, 13951.9570924174, 89570.23393702849, 8858.0711268371, 12342.0507217644, 5017.7521888485, 18429.9867235825, 17054.2129237367, 12985.88016134151, 20597.0001455577, 5483.4985423095, 21424.2228268199, 522.3336006103, 6187.3404402571, 6379.2988946927, 24382.8352909579, 8983.0544867925, 6131.4223863897, 6435.2169485601, 8258.81221333091, 3957.8826236923, 3738.51761262449, 5767.8557963819, 6798.7835385679, 18216.6876281445, 29864.0902098255, 12189.0219095505, 24080.2788342607, 15141.14697682849, 1573.57660661529, 1550.8014051645, 101426.452588453, 78423.9483341623, 1580.6228433133, 27043.2590656993, 6812.5229976025, 6081.06627230081, 6485.573062649, 36109.6260221481, 16944.0066025173, 5.2791068239, 16737.33341911309, 12537.9463299985, 20198.85114214949, 56600.0354720387, 6040.10342853389, 3956.2641985359, 40796.5827401577, 22743.16556203289, 42456.5402296081, 19801.1897737083, 5622.08674069391, 5888.6937824157, 6677.9455525341, 41194.7317435659, 6261.9840270079, 6304.6553079419, 5870.9485706005, 6695.6907643493, 12850.2548363315, 6253.4982293261, 6313.14110562371, 5316.3487900393, 12282.5361986011, 24422.6141688908, 63659.1215683211, 16723.5939600785, 17995.78735073869, 18106.4813069251, 17363.4912463925, 6124.37614969171, 6442.2631852581, 4705.4884900601, 23550.5878691661, 12036.21691740469, 5237.67719632029, 16207.64245401849, 6774.98295993371, 7083.14079264031, 6394.50630976251, 6172.1330251873, 9924.5666040271, 22380.9996177575, 6390.9831914135, 6175.6561435363, 16193.41536001689, 32217.4439985643, 6653.0194834153, 5913.6198515345, 6265.50714535691, 6301.1321895929, 5959.3266158505, 16723.10632511149, 23646.5670963839, 4897.4243911387, 6944.5525942559, 10660.44311755889, 35371.6434484929, 6370.62787201471, 6196.0114629351, 22345.0165586247, 15265.64270181689, 6315.2919732917, 6251.34736165811, 323.74923414091, 10873.74221299689, 109.9625037359, 11823.4054569337, 28774.2817889683, 18099.7594409665, 17576.7903418305, 245707.7099218278, 10557.8379783073, 71430.9394356126, 28760.05469496669, 3854.7898494737, 23440.3815479467, 13088.9729355601, 12564.91104475801, 7548.8871461013, 6286.3551508569, 18625.1265717558, 35050.2440919589, 553.8132203259, 167993.9384537073, 41991.0297503823, 15663.79170522509, 7250.29054491051, 6277.2537518451, 6289.3855831047, 18003.38853270651, 793.0187059509, 10027.65937824569, 647.25465079831, 4597.77991000629, 6279.30891415889, 3166.66025521511, 6226.5164053051, 6340.12292964471, 12303.3115940935, 5864.3952685743, 6702.2440663755, 23536.3607751645, 5760.25461441409, 12139.30969162329, 67589.3312645407, 11079.92776143409, 23227.0824525087, 4804.4530934105, 30349.1275902505, 92747.9329843061, 12299.7884757445, 12171.7696324071, 15.49628866851, 3684.1342325067, 6717.0314053517, 26087.65932409069, 12164.7233957091, 5219.5179490556, 3178.38960805111, 5227.38225558179, 19004.4041319249, 4583.55281600469, 3627.2636600341, 6411.2712005095, 6155.3681344403, 5849.6079295981, 5791.16874004909, 5791.6563750161, 5113.2437810993, 30775.7257811265, 14169.5497447469, 10454.74520408871, 23141.8022004081, 28313.0449871775, 5244.2930566845, 5657.6494751625, 6908.9898597873, 2574.99527684569, 536.5606946119, 6684.9917892321, 5881.6475457177, 16310.73522823709, 16311.2228632041, 46386.7499258277, 60530.2451682583, 96678.14268052569, 12323.17927852529, 21954.4014268815, 4164.5558070965, 33794.7875410121, 43739.0461634493, 3981.73385156551, 27707.29867681129, 7669.21494381111, 3646.59419483791, 82534.6474380951, 800.06494264891, 11609.61872652869, 26.5421372833, 30640.1004561165, 8982.5668518255, 96563.24283557819, 17583.9038888313, 23539.46356884929, 170.4290531357, 735.6326960483, 6680.98103591609, 44033.8837720559, 80181.29364935629, 24279.3508356971, 5490.5447790075, 6490.0204047715, 6076.6189301783, 18208.1061251085, 4480.46004178609, 16097.9237677661, 16097.43613279909, 491.9071099423, 6006.5738956105, 6560.0654393393, 5333.65642353809, 244287.8438247112, 2301.34199842589, 33794.2999060451, 4384.48081456829, 35579.9350570535, 18326.8939493639, 533.45790092711, 16703.3059509825, 5209.2230083171, 38650.4173236825, 12555.3498172024, 5992.3468016089, 6574.2925333409, 69942.1974183125, 12146.9108735911, 39301.8531447125, 46360.9392409949, 8402.0835278533, 44137.1951668575, 22029.9691371861, 31441.92138724031, 9225.29545579949, 71519.54096076029, 7762.1862415393, 3735.48212924251, 40398.4337367495, 4707.9862312257, 28664.0754677489, 11919.3846841515, 316428.47249139857, 27278.7126339243, 83659.5206898825, 12662.3747446841, 16627.12709789369, 12571.9184417737, 7322.34627826531, 664.99986261351, 5641.9544251257, 6425.4982945111, 6141.1410404387, 22594.2987131955, 20894.53186172529, 5540.3296069423, 17782.48825530069, 6006.2846737335, 6560.3546612163, 142861.1474187747, 24499.7634781359, 7026.3097280075, 955.8435590921, 24485.5363841343, 9388.2497268987, 6359.5857387505, 8635.69818627969, 27831.79440179969, 6334.60000533731, 6232.03932961249, 11905.1625906853, 7076.0945559423, 5444.3503797245, 7122.2889552253, 44933.4931736739, 5715.6010297445, 6851.0383052053, 36147.6536947839, 6238.1784478383, 6328.4608871115, 3214.8925631597, 23141.3145654411, 19804.5834740993, 20.11150191529, 84334.66158130829, 60284.16619777939, ], ]; pub const X1: [[f64; 600]; 3] = [ [ 0.00154550744, 0.00051503383, 0.00001290763, 0.00000702576, 0.00000430422, 0.00000212689, 0.00000212524, 0.00000062308, 0.00000059808, 0.00000059474, 0.00000048914, 0.00000042814, 0.00000046457, 0.00000036653, 0.00000035649, 0.00000035362, 0.00000032151, 0.00000028763, 0.00000028447, 0.00000027537, 0.00000024819, 0.00000020615, 0.00000019621, 0.00000018378, 0.00000016494, 0.00000016756, 0.00000014558, 0.00000014404, 0.00000014052, 0.00000012261, 0.00000012758, 0.00000010086, 0.00000009469, 0.00000010425, 0.00000010425, 0.0000000957, 0.00000009044, 0.00000008544, 0.00000008214, 0.00000006157, 0.00000006271, 0.00000005524, 0.00000007314, 0.00000005157, 0.00000006749, 0.00000004853, 0.00000005304, 0.00000004985, 0.00000004709, 0.00000004601, 0.00000004201, 0.00000005607, 0.00000004257, 0.00000004394, 0.0000000387, 0.00000005154, 0.00000005036, 0.00000005076, 0.00000003593, 0.00000003384, 0.00000003371, 0.00000003536, 0.00000004292, 0.00000003407, 0.00000003152, 0.00000002883, 0.00000002751, 0.00000003323, 0.00000002999, 0.00000002496, 0.00000003358, 0.00000002297, 0.00000002047, 0.00000002778, 0.00000002025, 0.00000002663, 0.00000002009, 0.00000002148, 0.00000001853, 0.00000002478, 0.00000002023, 0.00000001735, 0.00000002417, 0.00000001809, 0.00000001893, 0.00000001708, 0.00000001898, 0.0000000182, 0.00000001541, 0.00000001555, 0.00000001779, 0.00000001448, 0.0000000145, 0.0000000145, 0.00000001822, 0.00000001372, 0.00000001375, 0.000000014, 0.00000001247, 0.00000001231, 0.00000001141, 0.00000001138, 0.00000001047, 0.00000001058, 0.00000001025, 0.00000000973, 0.00000001114, 0.00000000963, 0.00000000941, 0.00000001068, 0.00000000929, 0.00000000899, 0.00000000889, 0.00000000889, 0.00000001018, 0.0000000106, 0.00000001017, 0.00000000797, 0.00000000795, 0.00000000795, 0.000000008, 0.00000000719, 0.00000000698, 0.00000000686, 0.00000000673, 0.00000000902, 0.00000000678, 0.00000000671, 0.00000000744, 0.00000000706, 0.00000000661, 0.00000000633, 0.00000000621, 0.00000000638, 0.00000000625, 0.00000000637, 0.00000000628, 0.00000000653, 0.00000000578, 0.00000000563, 0.0000000061, 0.00000000666, 0.0000000072, 0.0000000062, 0.00000000553, 0.00000000553, 0.00000000523, 0.00000000524, 0.00000000569, 0.00000000514, 0.00000000563, 0.00000000495, 0.00000000481, 0.00000000481, 0.00000000466, 0.0000000044, 0.00000000437, 0.00000000452, 0.00000000499, 0.0000000044, 0.00000000587, 0.00000000388, 0.00000000398, 0.00000000423, 0.0000000053, 0.00000000379, 0.00000000379, 0.00000000377, 0.00000000419, 0.00000000383, 0.00000000383, 0.00000000375, 0.00000000457, 0.00000000457, 0.00000000481, 0.00000000344, 0.00000000453, 0.00000000364, 0.00000000364, 0.00000000327, 0.00000000358, 0.00000000342, 0.00000000342, 0.00000000318, 0.0000000032, 0.00000000354, 0.00000000318, 0.00000000318, 0.00000000304, 0.00000000343, 0.00000000343, 0.00000000359, 0.00000000398, 0.00000000306, 0.000000003, 0.00000000307, 0.00000000297, 0.00000000365, 0.00000000336, 0.00000000295, 0.00000000288, 0.00000000287, 0.00000000378, 0.00000000289, 0.00000000347, 0.00000000321, 0.00000000289, 0.0000000026, 0.00000000268, 0.00000000242, 0.00000000245, 0.00000000234, 0.00000000267, 0.00000000282, 0.00000000279, 0.0000000029, 0.00000000298, 0.0000000027, 0.00000000294, 0.00000000214, 0.00000000207, 0.00000000216, 0.00000000195, 0.00000000199, 0.0000000025, 0.00000000194, 0.00000000203, 0.00000000203, 0.00000000258, 0.00000000189, 0.00000000186, 0.00000000184, 0.0000000018, 0.00000000185, 0.00000000205, 0.00000000187, 0.00000000187, 0.00000000187, 0.00000000235, 0.00000000173, 0.00000000184, 0.0000000023, 0.00000000166, 0.00000000189, 0.00000000166, 0.00000000186, 0.00000000184, 0.00000000184, 0.00000000156, 0.00000000182, 0.00000000175, 0.00000000154, 0.00000000154, 0.00000000164, 0.00000000146, 0.00000000184, 0.00000000191, 0.00000000144, 0.00000000146, 0.00000000142, 0.00000000185, 0.00000000133, 0.00000000131, 0.00000000146, 0.00000000128, 0.00000000128, 0.00000000123, 0.00000000121, 0.00000000123, 0.00000000123, 0.00000000117, 0.0000000012, 0.00000000113, 0.00000000137, 0.00000000113, 0.00000000123, 0.00000000132, 0.00000000113, 0.00000000113, 0.00000000116, 0.0000000012, 0.00000000109, 0.00000000103, 0.00000000103, 0.00000000104, 0.00000000105, 0.00000000109, 0.00000000102, 0.00000000101, 0.00000000114, 0.00000000111, 0.00000000107, 0.00000000099, 0.00000000102, 0.00000000102, 0.0000000012, 0.00000000095, 0.00000000121, 0.000000001, 0.0000000009, 0.000000001, 0.00000000089, 0.00000000087, 0.00000000086, 0.00000000095, 0.00000000084, 0.00000000106, 0.00000000095, 0.00000000082, 0.00000000081, 0.00000000084, 0.00000000084, 0.0000000008, 0.00000000085, 0.00000000084, 0.0000000008, 0.00000000092, 0.00000000077, 0.0000000008, 0.00000000104, 0.00000000093, 0.00000000085, 0.00000000086, 0.00000000075, 0.0000000009, 0.0000000009, 0.00000000082, 0.00000000101, 0.00000000094, 0.00000000083, 0.00000000073, 0.00000000101, 0.00000000074, 0.00000000092, 0.00000000075, 0.00000000085, 0.00000000069, 0.00000000084, 0.00000000069, 0.00000000075, 0.00000000067, 0.00000000076, 0.00000000068, 0.00000000067, 0.00000000073, 0.00000000065, 0.00000000069, 0.00000000087, 0.00000000076, 0.00000000064, 0.00000000078, 0.00000000066, 0.00000000063, 0.00000000063, 0.00000000061, 0.00000000073, 0.00000000057, 0.00000000059, 0.00000000058, 0.0000000006, 0.00000000057, 0.00000000056, 0.00000000056, 0.00000000056, 0.00000000054, 0.00000000055, 0.00000000061, 0.00000000065, 0.00000000072, 0.00000000072, 0.00000000071, 0.00000000061, 0.00000000061, 0.00000000052, 0.00000000054, 0.00000000052, 0.00000000066, 0.0000000005, 0.00000000051, 0.00000000049, 0.00000000053, 0.00000000053, 0.00000000049, 0.00000000049, 0.00000000049, 0.00000000049, 0.0000000005, 0.0000000005, 0.00000000051, 0.00000000058, 0.00000000047, 0.00000000049, 0.00000000049, 0.00000000046, 0.00000000052, 0.00000000047, 0.00000000046, 0.00000000063, 0.00000000048, 0.00000000046, 0.0000000005, 0.00000000054, 0.00000000045, 0.00000000049, 0.00000000049, 0.00000000045, 0.00000000046, 0.00000000048, 0.00000000049, 0.00000000049, 0.00000000044, 0.00000000044, 0.00000000051, 0.00000000042, 0.00000000042, 0.00000000043, 0.00000000043, 0.00000000041, 0.00000000053, 0.00000000042, 0.00000000041, 0.00000000045, 0.0000000004, 0.0000000004, 0.0000000004, 0.00000000045, 0.00000000045, 0.00000000042, 0.0000000004, 0.00000000039, 0.00000000044, 0.00000000038, 0.00000000038, 0.00000000041, 0.00000000038, 0.00000000038, 0.00000000039, 0.00000000046, 0.00000000041, 0.00000000038, 0.00000000038, 0.00000000037, 0.00000000037, 0.00000000037, 0.00000000036, 0.00000000045, 0.00000000049, 0.00000000038, 0.00000000041, 0.00000000036, 0.00000000048, 0.00000000041, 0.00000000038, 0.00000000036, 0.00000000036, 0.00000000036, 0.00000000048, 0.00000000037, 0.00000000047, 0.00000000034, 0.00000000034, 0.00000000034, 0.00000000036, 0.00000000034, 0.00000000037, 0.00000000034, 0.00000000033, 0.00000000035, 0.00000000044, 0.00000000033, 0.00000000033, 0.00000000033, 0.00000000033, 0.00000000034, 0.00000000034, 0.00000000032, 0.00000000036, 0.00000000032, 0.00000000033, 0.00000000033, 0.00000000031, 0.00000000041, 0.00000000037, 0.00000000034, 0.00000000032, 0.00000000032, 0.00000000037, 0.00000000036, 0.00000000035, 0.00000000035, 0.00000000035, 0.0000000003, 0.00000000032, 0.00000000032, 0.00000000029, 0.00000000029, 0.00000000029, 0.0000000003, 0.00000000029, 0.00000000032, 0.00000000028, 0.0000000003, 0.00000000029, 0.0000000003, 0.00000000034, 0.00000000034, 0.00000000038, 0.00000000038, 0.00000000029, 0.00000000033, 0.00000000028, 0.00000000032, 0.0000000003, 0.00000000027, 0.0000000003, 0.00000000028, 0.00000000027, 0.00000000027, 0.00000000027, 0.00000000027, 0.00000000027, 0.00000000027, 0.00000000026, 0.00000000034, 0.00000000027, 0.00000000027, 0.00000000028, 0.00000000026, 0.00000000026, 0.00000000026, 0.00000000029, 0.00000000029, 0.00000000026, 0.00000000028, 0.00000000032, 0.00000000026, 0.00000000025, 0.00000000029, 0.00000000027, 0.00000000024, 0.00000000024, 0.00000000028, 0.00000000024, 0.00000000025, 0.00000000025, 0.00000000029, 0.00000000024, 0.00000000028, 0.00000000024, 0.00000000024, 0.00000000024, 0.00000000025, 0.00000000025, 0.00000000024, 0.00000000028, 0.00000000024, 0.00000000023, 0.0000000003, 0.00000000024, 0.00000000023, 0.00000000022, 0.00000000023, 0.00000000025, 0.00000000023, 0.00000000023, 0.00000000024, 0.00000000024, 0.00000000021, 0.00000000029, 0.00000000021, 0.00000000021, 0.00000000022, 0.00000000022, 0.00000000022, 0.00000000026, 0.0000000002, 0.0000000002, 0.00000000027, 0.0000000002, 0.0000000002, 0.0000000002, 0.00000000025, 0.0000000002, 0.0000000002, 0.00000000022, 0.00000000024, 0.00000000019, 0.0000000002, 0.0000000002, 0.00000000022, 0.00000000022, 0.00000000022, 0.00000000018, 0.00000000018, 0.00000000019, 0.00000000019, 0.00000000019, 0.00000000019, 0.0000000002, 0.0000000002, ], [ 0.64605836878, 6.00263199393, 5.95941652859, 1.75347943445, 2.45216492471, 1.73380190045, 4.91484799365, 0.3619329771, 3.81187956678, 2.83659652893, 5.21332670904, 0.43864033644, 0.01089905463, 2.19635713914, 1.44752011203, 4.47215447256, 5.19677261546, 5.91618988907, 1.14976229491, 5.49920443604, 2.92230738957, 3.71821460067, 2.88650825392, 1.46521342874, 6.21543454587, 3.81938434057, 5.97530104893, 0.68122522191, 1.45747121073, 4.15789187748, 0.34831751321, 3.29242550455, 4.6392045785, 2.38242547117, 4.26610810148, 1.89427100067, 2.00972967096, 0.05731253621, 1.25401494002, 3.35676469316, 4.75475820102, 5.3694101419, 0.49102526454, 5.14965163127, 4.32513020462, 0.62462823219, 5.64244320178, 4.62777616911, 3.96386608147, 6.02376124126, 1.28125193997, 2.55800509408, 4.12450123624, 0.04709285339, 2.68681123019, 6.15930214427, 4.09009014859, 2.30606090748, 2.40570544354, 5.40354177904, 0.28961103245, 3.73353119602, 4.93786086114, 2.4059927333, 1.73356525688, 4.92077247219, 5.24449444697, 1.91880015934, 2.25355241223, 3.52078273708, 4.25271343539, 4.53559364224, 3.53660263792, 1.46152428305, 1.44003078455, 5.71398175957, 5.73390835065, 1.89688144273, 2.84762029989, 0.03933370984, 2.39095052485, 2.91944410412, 5.16772880951, 0.78457177103, 4.22746619412, 0.29122424525, 2.3400737078, 1.8772897448, 1.10077450497, 3.67004127739, 1.80817581905, 0.18764842398, 0.99962470222, 5.64890887043, 1.70526332053, 0.89281758077, 0.76961577554, 4.85224030747, 1.86305212941, 4.10244270612, 3.49241515175, 2.80935582144, 6.02902034733, 3.76081315695, 5.32138364615, 0.24159402695, 5.94057908115, 2.13180404708, 5.78706319005, 0.3739370227, 3.11135132378, 1.07875107899, 0.29953586851, 0.06581239696, 4.23379398746, 1.05626464973, 5.59172649862, 5.364162766, 1.67821896162, 4.97031461103, 4.75445763497, 3.86746073982, 0.23124353834, 5.36448356218, 5.5618480784, 2.26778049127, 0.13408295783, 1.28940504615, 4.258207053, 4.09030374624, 3.99296008106, 0.86914955896, 3.31200729066, 0.47109166303, 1.88693051693, 6.16733887432, 1.85369027207, 4.28657823528, 5.33616352365, 4.82044552939, 0.48716946879, 3.30009380787, 0.47572131456, 5.87390167695, 4.28779208332, 2.36074148933, 0.75768878632, 5.54806074141, 0.12658241682, 2.30528734098, 2.21509710432, 3.58067034949, 2.50655660751, 4.14197696514, 4.51385713822, 0.4571681154, 3.18132586326, 5.55409870988, 1.08746970886, 2.15051971988, 4.7191709418, 2.041186026, 5.77147994683, 1.16599451585, 3.0067279932, 2.02388854283, 4.62464502982, 5.90352173005, 5.62219874401, 6.24432820927, 0.40420536338, 5.62315844522, 4.19200440747, 2.45652916518, 1.89483272077, 0.28668049892, 0.7257723698, 4.39782645564, 2.25070711701, 2.71208539186, 4.87210297876, 0.54833716779, 6.10019640486, 0.13364568371, 2.70295484544, 1.02467818407, 5.32503015719, 1.32350341546, 2.00970548291, 3.71302827314, 2.93550529951, 4.09955266779, 0.12298117861, 2.58873546625, 1.77608786075, 3.29263568042, 0.51221148619, 2.74542548477, 2.72364909606, 4.05850212848, 2.18795828306, 3.33776996109, 0.39946174567, 3.04361347297, 0.7283850104, 2.23787969105, 5.30650717041, 1.04284839158, 3.62847841862, 4.34386674771, 2.31719119888, 4.0739343796, 5.83055956746, 4.50260656021, 3.13773429847, 2.03216763842, 0.93822937797, 2.16529088691, 2.52895912407, 0.93543623291, 1.60966002008, 5.60316710178, 2.87143133187, 3.93236191602, 4.61596023287, 2.36749003244, 2.25356528795, 4.3949682847, 5.6302500757, 1.63377883836, 0.12949416246, 4.20955149479, 5.76808682495, 4.68506649147, 4.93663483706, 5.91135912176, 2.05685668523, 4.59167688742, 5.91611965384, 1.38702654435, 4.65365446464, 2.23774195109, 1.3259758191, 2.84387211432, 1.19482070134, 4.46969004938, 3.01631602481, 3.38049875173, 2.34433370292, 3.4727151585, 3.2677154823, 5.67725689556, 0.97127667708, 4.52273465985, 4.05729660897, 0.20513580951, 2.29402324776, 3.76178854682, 1.99164382254, 1.34565609994, 3.72101619927, 0.01824676794, 4.75893185547, 5.03857686201, 3.41348197806, 0.18086618365, 5.45134858107, 0.98195264587, 0.10275700246, 0.26259126301, 4.4771171305, 1.0391312214, 2.33706395068, 3.68199834086, 5.07439785395, 4.42839393502, 6.08414353296, 4.12294240934, 2.0969640014, 2.23828708218, 2.28034205827, 0.5059770528, 0.11832394316, 0.24702432231, 5.58102765204, 3.75605193168, 2.65465737803, 2.59681923716, 4.42190708814, 2.21750546661, 3.66232090402, 2.47220154064, 2.67705199399, 5.67042027327, 0.97811329938, 2.49695982999, 2.69903868611, 0.05336928445, 2.04355401267, 3.68840859712, 4.37665365923, 5.33255005639, 4.3339033213, 5.93949751968, 1.34358559692, 1.545308678, 5.14280637669, 2.50046187937, 0.0160091831, 3.84772162011, 1.14755262027, 5.50098095238, 0.34711727404, 5.79487336888, 3.04423309467, 4.19702378753, 0.87932993874, 5.70308186355, 1.36958890049, 5.42045444776, 0.29330855376, 0.17489631763, 0.81273058913, 4.00156639703, 0.6255895953, 6.02294397735, 0.197679481, 6.08995730057, 5.45896547971, 5.31992956371, 6.09826272325, 2.86248284119, 5.96635290969, 2.35039346805, 0.0019870303, 6.09242867296, 0.89145782253, 4.35477901935, 0.61262618132, 1.62832949134, 4.61214364579, 4.83480996889, 4.26265140929, 3.2460963889, 6.0704772451, 0.20786131115, 3.29499829591, 5.09754892709, 0.73384165663, 3.69394501139, 4.31639568529, 3.41816290372, 0.99537559299, 5.29204726636, 3.726990386, 4.50408758477, 2.80099560279, 0.69432195316, 3.24953926506, 3.51548937348, 4.46074610322, 5.33393809517, 0.9124024473, 2.17966368743, 2.96145051332, 4.53949491324, 0.15191781763, 5.87045161229, 0.77556931591, 5.87296425674, 0.23083621209, 1.27148175728, 5.37705181537, 0.26640147565, 1.21229891621, 2.44818566509, 2.35337977576, 5.93502263343, 0.76420455409, 4.18738074622, 1.36303997543, 5.28549359722, 4.92672897893, 6.04327871377, 0.60525485888, 2.59123701567, 5.65157500725, 0.07520350695, 3.40680645218, 2.46543782438, 0.97665096734, 4.98006572526, 1.66846784739, 3.45134537804, 4.17729143118, 2.09298679166, 5.73796654718, 1.54245276158, 1.71424177408, 5.48854983581, 4.49443808542, 0.03975141461, 5.05887207146, 4.51484833854, 3.00236481482, 5.42122497288, 3.44074843825, 1.96431249949, 0.60097746518, 4.98977220505, 3.01088620106, 3.63764737159, 1.08500510566, 1.47304377234, 4.33726197214, 1.51170891404, 1.85670214007, 4.78695133916, 1.02071442021, 0.40756986853, 3.62600931231, 2.13148338898, 3.00393862246, 0.45945430396, 0.14772670564, 4.68905632727, 1.54746367368, 4.3224744279, 0.00254937606, 5.06793905702, 2.87431244066, 2.71291798518, 3.93561558747, 4.9531312813, 0.25558032671, 0.10976793876, 3.31895424299, 5.02561530595, 2.4723614991, 1.11170997081, 6.16488744565, 4.91170884792, 2.07642652738, 5.02138933475, 1.41330554556, 0.04410300421, 5.78167784671, 6.16266694488, 5.48085477947, 4.6405951428, 0.43106257187, 2.33852383906, 6.17960213131, 4.6960137864, 0.39760453863, 6.28050310342, 0.32621587842, 5.17748996647, 1.64189885412, 5.26052334707, 1.38801022558, 2.0992747976, 5.01642644412, 1.97967235505, 2.80234472663, 1.90506635542, 2.30422309015, 3.20661909223, 2.79016934175, 2.02741588975, 4.13127522861, 4.59578048276, 3.87810188817, 0.56182222293, 4.95130100456, 4.38300866562, 0.10343586811, 4.48170445266, 1.70919210465, 4.08300924175, 0.30962555206, 4.09101330171, 1.21597687953, 0.61019544663, 2.47223060088, 6.25412877228, 3.41910013684, 3.45170661535, 2.20855027459, 2.69261850768, 0.83074174405, 2.96012497927, 0.38688555099, 6.26164802166, 2.489140841, 2.489140841, 0.09098498823, 4.30269873097, 2.26254947152, 3.16446260317, 1.87847577782, 2.57345584103, 6.17121903514, 3.16071544619, 5.862790153, 0.78574341965, 5.12222686816, 2.95935499043, 0.07805875622, 1.31621330654, 4.45185289388, 4.32330584281, 1.39195112722, 0.53286078729, 2.32405719366, 5.54771281521, 6.17188911074, 4.56663555607, 3.42500443489, 5.99215939135, 0.6563741813, 0.24480889857, 3.76734683925, 6.02674277322, 2.32047706036, 1.77181133426, 3.80331914659, 6.01470923824, 6.27941236443, 0.36912120822, 0.18788001431, 0.17746825116, 3.39870851542, 2.42845493949, 0.33223863826, 2.5466538221, 5.74078884001, 5.90495655038, 4.22338082584, 0.55027097677, 2.62016281496, 3.25064295131, 4.40689701323, 3.8636229191, 2.78491065355, 2.44405132476, 0.5070929141, 2.66240986547, 1.98880441412, 5.13039706771, 5.85302121512, 3.95115098429, 0.8095583307, 1.92863541994, 4.50601984314, 3.73455640738, 0.62345777089, 3.85563309519, 3.21746306158, 1.36063534536, 3.99741791962, 5.13650786055, 0.81555419576, 3.5856941208, 3.06283945185, 4.24597953395, 1.10438688036, 5.78251945962, 3.31448732534, 5.13427576878, 4.08575884387, 1.38262024424, 5.26591980546, 4.52225402167, 3.41053115091, 0.8072026736, 4.78724181293, 0.67000770864, 2.0763093298, 1.72148703277, 3.685764303, 3.53209868087, 0.81961551511, 2.60684350676, 0.44774356245, 1.20852424503, 5.85945140949, 4.99560905506, 1.65292451759, 4.44471803531, 2.1834821363, 4.46505143635, 2.03036294822, 4.61817062443, 4.28397604583, 2.36455752682, 0.18461366541, 4.29574443999, 3.8495702723, 2.85391796921, ], [ 0.2438174835, 12566.3955174663, 18849.4713674577, 6283.3196674749, 6282.83203250789, 6279.7965491259, 6286.84278582391, 4705.9761250271, 6257.0213476751, 6309.61798727471, 775.7664288075, 1059.6257476727, 7860.6632099227, 5753.6287023803, 5885.1706640667, 6813.0106325695, 6681.46867088311, 25132.5472174491, 6127.8992680407, 6438.7400669091, 5487.0216606585, 7079.61767429131, 5507.7970561509, 11790.8729061423, 11507.0135872771, 7058.8422787989, 6290.4332144757, 6276.2061204741, 796.5418242999, 4693.75913722409, 7.3573644843, 3739.0052475915, 6070.0205720369, 6284.2999885431, 6282.3393464067, 4137.1542509997, 6496.6187629129, 1194.6908277081, 1589.3167127673, 8827.6340873583, 8429.4850839501, 4933.4522578161, 4535.3032544079, 11770.0975106499, 5088.8726572503, 6040.5910635009, 3154.4432674121, 12569.91863581531, 5331.6012612243, 6526.04827144891, 7633.1870771337, 5729.7502646325, 3930.4535137031, 12559.2819704655, 7235.0380737255, 8031.3360805419, 6836.8890703173, 7477.7666776995, 12565.9078824993, 10977.32262218251, 11371.9485072417, 4164.0681721295, 1592.8398311163, 3128.6325825793, 5223.93773728571, 1747.7725955835, 7342.7015976641, 801.5771136403, 8636.18582124671, 2145.92159899169, 155.17658195069, 17260.3984721739, 1990.9888345245, 5481.4987363511, 951.4745887671, 26.0545023163, 4690.7236538421, 537.0483295789, 553.32558535889, 1349.62359217529, 522.8212355773, 529.44714761109, 7085.1405985987, 397.9051859247, 9438.0067523705, 10989.0519750185, 5216.33655531789, 5230.5636493195, 426.8420083595, 13096.0864825609, 12562.8723991173, 5753.14106741329, 6262.96434807611, 6303.6749868737, 10973.7995038335, 7875.91568110771, 7084.6529636317, 12721.8159169005, 2119.00767786191, 18319.7804023631, 1066.7392946735, 2942.7072407751, 5642.93474619389, 242.97242145751, 10447.14402212089, 640.1411037975, 15721.0826023619, 2389.1378379327, 20426.8149099055, 529.9347825781, 10575.6505004253, 16496.6052136859, 6277.7967431675, 6288.8425917823, 12540.0971976665, 5760.7422493811, 6805.89708556871, 14314.4119305333, 6286.6060248927, 6280.0333100571, 12029.5910053709, 9623.9320941747, 6148.2545874395, 5856.7214765989, 12964.5445208745, 13368.2164485901, 6418.38474751031, 6709.91785835091, 12043.8180993725, 16730.70750707931, 14712.5609339415, 4292.5746504339, 13119.9649203087, 4690.23601887509, 13518.1139237169, 5746.5151553795, 4686.6455902233, 3929.96587873609, 5088.3850222833, 10447.6316570879, 6820.1241795703, 3634.37720703489, 13916.2629271251, 31415.6230674405, 6259.44122972711, 6307.1981052227, 14143.7390599141, 12139.7973265903, 12036.7045523717, 4700.87268422489, 11014.8626598513, 13362.6935242827, 6279.4383321169, 6287.2010028329, 10177.5014970171, 1577.5873599313, 11499.9000402763, 12573.5090644671, 12410.9751180321, 24073.1652872599, 6.86972951729, 7860.17557495569, 8274.0646845159, 4694.2467721911, 12592.6938372661, 6180.2268932563, 6386.4124416935, 7872.39256275871, 5327.7199258663, 6247.2918007975, 6319.34753415231, 2352.6223362883, 6077.1341190377, 6489.5052159121, 4292.0870154669, 18451.3223640495, 2787.2868413409, 6245.2919948391, 6321.3473401107, 12323.6669134923, 9917.45305702629, 6262.5442719825, 6304.0950629673, 11926.4982311523, 77714.015285604, 7238.9194090835, 6254.8704800071, 6311.7688549427, 12779.6946129043, 6298.57213865991, 6268.0671962899, 1052.51220067191, 1551.2890401315, 5863.8350235997, 90280.1669855868, 3893.93801205869, 5429.63565075589, 10022.0810975829, 17782.9758902677, 6702.8043113501, 18073.9487561337, 1577.0997249643, 2353.1099712553, 213.5429129215, 5223.4501023187, 17797.2029842693, 220.6564599223, 955.3559241251, 14945.0723560709, 2544.5582373669, 7632.6994421667, 1596.43025976811, 206.42936592071, 13341.9181287903, 4731.7868098599, 5642.4420600927, 17790.08943726851, 12168.2465140581, 2146.4092339587, 8030.8484455749, 213.0552779545, 3185.43584474911, 5884.68302909969, 1748.2602305505, 6924.1972748571, 641.12142486571, 6503.7323099137, 6062.9070250361, 796.0541893329, 11506.52595231009, 18209.5740811437, 12566.4628277691, 853.4401992355, 3495.78900865049, 5849.1202946311, 10213.5293636945, 6290.36590417291, 6276.2734307769, 9779.3524936089, 19651.2922985815, 12566.32820716351, 12567.37583853451, 110.45013870291, 3.76693583251, 433.9555553603, 5863.3473886327, 10983.94853421629, 6037.4880212455, 2648.6986429565, 10969.72144021469, 6529.1513137043, 6453.9925380941, 6112.6467968557, 12353.0964220283, 149.8070146181, 11015.3502948183, 3894.4256470257, 18636.1722720197, 13760.8425276909, 4156.95462512869, 7234.5504387585, 18139.5383188994, 5507.3094211839, 18875.2820522905, 6069.53293706989, 16200.52890701769, 20.5315780089, 17256.8753538249, 6393.5259886943, 6173.1133462555, 18852.9944858067, 9381.2034902007, 65147.37595065419, 16201.0165419847, 6836.40143535029, 12565.4151963981, 17655.0243572331, 10575.1628654583, 10213.0417287275, 17253.2849251731, 10420.23010099111, 633.0275567967, 6295.0490203109, 6271.5903146389, 23013.7833570707, 11790.3852711753, 3340.36860921629, 10970.2090751817, 4803.9654584435, 4171.1817191303, 1582.2031657665, 23543.4743221653, 10973.3118688665, 6549.9267091967, 6016.7126257531, 11514.1271342779, 17267.5120191747, 13625.7774476555, 10976.83498721549, 76.50988875911, 8661.9965060795, 1350.1112271423, 9917.9406919933, 12809.12412144031, 12345.9828750275, 775.2787938405, 11216.5281078075, 12012.8261146239, 5643.4223811609, 11614.6771112157, 6255.9181113781, 6310.7212235717, 6923.2169537889, 5635.8211991931, 10440.03047512009, 3583.5848481573, 10818.3791043993, 6993.2527160332, 13521.9952590749, 5650.0482931947, 4732.2744448269, 22805.4917485101, 12360.2099690291, 5120.35732810009, 6370.62787201471, 6196.0114629351, 18842.3578204569, 3097.64000524229, 10177.01386205009, 18415.7596295809, 949.4194264533, 3104.6862419403, 13517.62628874989, 16858.7263504167, 1059.1381127057, 398.3928208917, 11713.1991357143, 2378.9206560881, 11712.71150074729, 30356.2411372513, 3154.9309023791, 18429.9867235825, 11925.5179100841, 10454.25756912169, 15670.83794192309, 6438.2524319421, 17298.4261448097, 3904.1551939033, 5231.0512842865, 3496.2766436175, 8672.21368792411, 14143.2514249471, 24357.0246061251, 15720.5949673949, 16460.5773470085, 9387.76209193169, 17259.91083720689, 9778.8648586419, 155.6642169177, 34570.3101523361, 149854.6439522914, 12456.1891962469, 17996.2749857057, 11764.5745863425, 4705.4884900601, 13915.77529215809, 28237.4772768729, 7335.5880506633, 6055.8435346859, 6510.7958002639, 12545.6201219739, 6312.74917601091, 6253.8901589389, 5326.5428765373, 2699.49100183409, 8983.0544867925, 14919.2616712381, 5572.8989839496, 16522.4158985187, 35579.9350570535, 6208.5380689076, 6358.1012660422, 21393.7857873411, 5547.4431539431, 7019.19618100671, 12416.8323203317, 12592.2062022991, 26084.2656236997, 23006.6698100699, 15141.14697682849, 24279.3508356971, 6816.53375091851, 5750.1055840313, 19379.1623325523, 16737.33341911309, 24066.0517402591, 104351.8563837803, 8662.48414104651, 26735.7014447297, 12132.6837795895, 24602.8562523545, 7834.3648901229, 161000.92955515758, 29303.9727540629, 10984.4361691833, 45584.9289947039, 5244.2930566845, 23581.0143598341, 19650.8046636145, 29289.7456600613, 6390.9831914135, 6175.6561435363, 17789.60180230149, 24705.9490265731, 15663.79170522509, 16460.08971204149, 553.8132203259, 17370.6047933933, 13119.47728534169, 4164.5558070965, 23020.8969040715, 54247.1693182669, 32243.2546833971, 24336.2492106327, 11769.6098756829, 16723.10632511149, 16723.5939600785, 8827.14645239129, 8402.0835278533, 16062.4283436003, 5856.23384163189, 6297.5467614765, 6269.0925734733, 15508.8589407579, 6394.50630976251, 6172.1330251873, 29826.5501721567, 17297.9385098427, 6309.1303523077, 29089.0552334685, 11933.6117781531, 26482.4146271079, 20452.6255947383, 18073.46112116669, 11499.41240530929, 3340.8562441833, 18216.6876281445, 18202.4605341429, 5216.8241902849, 4060.97539791089, 951.9622237341, 18848.98373249069, 26709.8907598969, 28230.4310401749, 24491.18197509989, 9924.5666040271, 8982.5668518255, 22484.0923919761, 6040.10342853389, 6418.9449924849, 6147.69434246491, 9380.71585523369, 7238.4317741165, 17272.1278250099, 58953.3892607775, 29026.7290469913, 12721.32828193349, 7322.34627826531, 3981.73385156551, 19804.5834740993, 173567.0812551404, 205.9417309537, 23013.29572210369, 49515.1386909235, 38500.5198485557, 17686.9966630499, 5641.9544251257, 21228.63584102931, 34520.5531268643, 8635.69818627969, 5746.0275204125, 21202.3375212295, 7349.81514466491, 16496.11757871889, 33019.2649296881, 21150.56954840009, 29296.8592070621, 27511.2240560537, 11933.12414318609, 11918.89704918449, 29062.7569136687, 12490.1294461907, 6334.60000533731, 6232.03932961249, 419.2408263917, 419.72846135871, 16858.23871544969, 16208.13008898551, 27278.7126339243, 5017.2645538815, 24080.2788342607, 23539.9512038163, 18606.25512851669, 30665.9111409493, 6660.6932753907, 5905.94605955911, 31571.0434668747, 16061.94070863329, 23539.46356884929, 3738.51761262449, 2942.21960580809, 15110.7099373497, 55023.1795645579, 233141.55822184499, 12587.1709129587, 34911.6558935745, 1692.40948698591, 2544.07060239989, 24382.8352909579, 6205.6458970469, 6360.99343790291, 31172.8944634665, 36949.4746259077, 18053.1733606413, 32367.3414736911, 4487.57358878689, 10239.3400485273, 4796.85191144269, 6226.4212925393, 6340.2180424105, 5974.0413448191, 6592.5979901307, 19402.55313533309, 46386.7499258277, 9225.7830907665, 9910.33951002549, 15265.64270181689, 52176.0501006319, 62883.5989569971, 11617.21990849651, 5120.8449630671, 6680.98103591609, 522.3336006103, 6263.64990657511, 6302.9894283747, 23581.5019948011, 29424.8780503995, 16737.8210540801, 22743.16556203289, 22743.6531969999, 25158.8455372489, 21424.2228268199, 21424.7104617869, 14712.07329897449, 5760.25461441409, 31969.1924702829, 17893.1822114871, 8584.9054833843, 23550.5878691661, 6717.0314053517, 7445.7943718827, 5849.6079295981, 14155.4684127501, 6294.36536773881, 6272.273967211, 18208.1061251085, 18208.5937600755, 22779.6810636773, 28628.5800435831, 40879.6843221273, 30221.1760572159, 4379.8828549737, 8186.7564799761, 28760.05469496669, 18422.8731765817, 12036.21691740469, 28313.0449871775, 34513.5068901663, 34115.3578867581, 21548.7185518083, 17654.5367222661, 55798.7021758819, 20597.4877805247, 18875.76968725751, 1588.82907780029, 9411.7084325707, 536.5606946119, 6187.3404402571, 6379.2988946927, 18326.8939493639, 6233.5626420031, 6333.0766929467, 5972.4788686065, 6594.1604663433, 6948.0757126049, 5618.5636223449, 83974.0791732134, 84020.1030979774, 50316.9596220473, 9070.3626913323, ], ]; pub const X2: [[f64; 248]; 3] = [ [ 0.00052911498, 0.00006074441, 0.00002406871, 0.00000096033, 0.00000029888, 0.00000014021, 0.00000013375, 0.00000008148, 0.00000008195, 0.00000008001, 0.00000007754, 0.00000007223, 0.00000004616, 0.0000000306, 0.00000003717, 0.00000002991, 0.00000003235, 0.00000002393, 0.00000002034, 0.00000002028, 0.00000002064, 0.00000001914, 0.0000000177, 0.00000001761, 0.00000001558, 0.00000001551, 0.00000001436, 0.00000001469, 0.00000001319, 0.0000000118, 0.00000001337, 0.00000001039, 0.00000001313, 0.00000001041, 0.00000001202, 0.00000000904, 0.0000000087, 0.00000001149, 0.00000001069, 0.00000000772, 0.00000000846, 0.00000000742, 0.00000000966, 0.00000000664, 0.00000000662, 0.00000000659, 0.00000000853, 0.00000000823, 0.00000000783, 0.00000000785, 0.00000000694, 0.00000000566, 0.00000000684, 0.00000000499, 0.00000000596, 0.00000000486, 0.00000000483, 0.00000000441, 0.00000000412, 0.00000000561, 0.0000000039, 0.00000000405, 0.00000000501, 0.00000000392, 0.00000000369, 0.00000000483, 0.00000000489, 0.00000000481, 0.00000000448, 0.00000000321, 0.0000000032, 0.00000000361, 0.00000000361, 0.00000000412, 0.00000000304, 0.00000000356, 0.00000000283, 0.00000000362, 0.00000000248, 0.00000000252, 0.00000000257, 0.00000000327, 0.0000000023, 0.00000000289, 0.00000000297, 0.00000000209, 0.00000000207, 0.00000000188, 0.00000000189, 0.00000000194, 0.00000000176, 0.00000000164, 0.00000000205, 0.00000000205, 0.00000000139, 0.00000000155, 0.00000000152, 0.00000000129, 0.00000000127, 0.00000000132, 0.00000000122, 0.00000000163, 0.00000000114, 0.00000000118, 0.00000000148, 0.00000000123, 0.00000000103, 0.00000000138, 0.00000000107, 0.00000000104, 0.00000000096, 0.00000000099, 0.00000000096, 0.00000000084, 0.00000000111, 0.00000000087, 0.00000000078, 0.00000000076, 0.00000000105, 0.00000000073, 0.00000000102, 0.0000000007, 0.00000000071, 0.00000000092, 0.0000000007, 0.00000000091, 0.00000000083, 0.00000000088, 0.00000000074, 0.00000000085, 0.00000000061, 0.0000000006, 0.00000000058, 0.00000000078, 0.00000000059, 0.00000000057, 0.00000000056, 0.00000000065, 0.00000000051, 0.0000000005, 0.0000000005, 0.00000000049, 0.00000000066, 0.00000000049, 0.00000000048, 0.00000000053, 0.00000000058, 0.00000000052, 0.00000000061, 0.00000000044, 0.00000000044, 0.00000000042, 0.00000000059, 0.00000000051, 0.00000000051, 0.00000000046, 0.00000000041, 0.00000000056, 0.00000000051, 0.00000000049, 0.00000000036, 0.00000000044, 0.00000000035, 0.00000000044, 0.00000000046, 0.00000000034, 0.00000000034, 0.00000000035, 0.00000000035, 0.00000000032, 0.00000000034, 0.00000000045, 0.00000000035, 0.00000000031, 0.0000000003, 0.00000000039, 0.00000000041, 0.00000000031, 0.00000000028, 0.00000000028, 0.00000000027, 0.00000000027, 0.00000000025, 0.00000000026, 0.00000000025, 0.0000000003, 0.00000000032, 0.00000000023, 0.00000000026, 0.00000000024, 0.00000000023, 0.00000000021, 0.00000000021, 0.00000000028, 0.00000000022, 0.00000000021, 0.0000000002, 0.0000000002, 0.00000000026, 0.00000000023, 0.00000000026, 0.00000000018, 0.0000000002, 0.00000000019, 0.00000000018, 0.00000000018, 0.00000000022, 0.00000000019, 0.0000000002, 0.00000000024, 0.00000000023, 0.00000000017, 0.00000000016, 0.00000000016, 0.00000000021, 0.0000000002, 0.00000000021, 0.0000000002, 0.00000000014, 0.00000000014, 0.00000000015, 0.00000000019, 0.00000000019, 0.00000000013, 0.00000000017, 0.00000000013, 0.00000000016, 0.00000000012, 0.00000000012, 0.00000000012, 0.00000000015, 0.00000000012, 0.00000000015, 0.00000000011, 0.00000000013, 0.00000000011, 0.00000000011, 0.0000000001, 0.00000000014, 0.0000000001, 0.0000000001, 0.0000000001, 0.0000000001, 0.0000000001, 0.0000000001, 0.00000000009, 0.0000000001, 0.00000000011, ], [ 3.32403354915, 2.05485843872, 4.23086027149, 4.14485769516, 0.73436192593, 3.21121684298, 3.31400005464, 2.19949162987, 4.38954108022, 5.91956929382, 0.72231700953, 5.38114271434, 6.1670322737, 4.83964573312, 2.45040909403, 4.05993241608, 4.10584554352, 3.40776365917, 4.34141229883, 2.28023581144, 1.58527926677, 4.42314112548, 5.05862783743, 3.3790285294, 2.13660228192, 2.12932375831, 2.85243683562, 4.51404554645, 3.46234944603, 2.9917059583, 1.03982518814, 5.82323058792, 2.16977183919, 0.76562479642, 5.5990917975, 2.42848578586, 3.83740101245, 4.59530313333, 5.80442130983, 4.23369730112, 2.93878609085, 0.30768536261, 3.62307276164, 2.78855764568, 4.76048207091, 1.23774551244, 5.22418483353, 5.77365627974, 5.87375907691, 5.03738396313, 1.93706172082, 6.00002295544, 2.68347359202, 2.99674498554, 1.38539217884, 6.11316978391, 6.25283705744, 0.27873568624, 5.58840963851, 0.75091675093, 6.20968064366, 1.55299195368, 3.39229516665, 5.39455294636, 4.36331143713, 1.36538995021, 2.13588971106, 4.74275484789, 0.85608336591, 2.9691187918, 2.00218171333, 0.5951950142, 0.08584353459, 5.91338851626, 0.96839213314, 1.28855678128, 2.2399217834, 3.8863384342, 4.75322854174, 1.16164987849, 1.79452152688, 3.02081233401, 0.23367695814, 5.24697142787, 1.59965866765, 0.2734167472, 4.92862210539, 5.64673454004, 0.60545229996, 0.4104695931, 4.08570919572, 2.79150408226, 3.21370431881, 2.25101785528, 4.61869477858, 5.81412821499, 0.10500467147, 5.5219353509, 0.96654930095, 0.16052766322, 4.78358483655, 0.93280092706, 5.70431693679, 2.37854817453, 5.63695738547, 3.7578591005, 3.36994741884, 3.83865460083, 4.33977826153, 5.27997888785, 1.97792917854, 2.27831564394, 1.53382620869, 5.20596620689, 3.96322491245, 6.02515097465, 4.18422621711, 5.70862044549, 3.5384540518, 0.89693480363, 0.66758153957, 5.22505818809, 0.56166089035, 1.96485842296, 2.53450052921, 3.10960565577, 3.98989749432, 5.01539409795, 1.96538390591, 5.97852929798, 4.2311438166, 5.52155170015, 1.47891111226, 2.41141378465, 4.67526538731, 2.06129454632, 3.80170948025, 3.38872777921, 4.81168622601, 4.1736967608, 4.41669813786, 2.27712508812, 5.495855845, 1.99905022377, 3.76233131596, 4.12374270394, 1.2308314416, 1.27828874996, 3.42876383277, 0.31046230867, 0.38954461131, 4.09986255075, 1.01599200374, 5.38279738858, 1.26573618407, 0.52171400874, 4.09327874029, 3.27189314076, 2.37524851068, 3.2115956795, 6.20393463674, 3.69396549327, 3.61386877088, 1.66014811397, 3.78615165617, 3.81444510796, 5.98049768477, 3.58408872678, 6.09075949155, 0.62535692558, 3.61147349841, 1.48783646485, 0.3859007697, 5.38472872675, 4.39715700541, 1.14782571257, 5.61324415849, 0.76672410297, 4.07975589699, 2.36060849192, 4.04275590321, 2.11023646997, 1.72579553961, 2.55064187749, 2.68812943588, 5.98905764002, 4.08880306095, 6.09814489767, 0.90493478768, 1.88327707702, 2.2672722651, 3.868951978, 2.37138453193, 1.07450535792, 4.83463880427, 5.98744320172, 0.31265663265, 5.44332565028, 2.02675372626, 0.80832702606, 5.31358634432, 2.28255799994, 4.61413285151, 3.66100662326, 4.7779464912, 1.89582517195, 3.74943338657, 3.25511318252, 2.60030261119, 1.57388276311, 4.78368329384, 3.95703430839, 5.1706919569, 1.2009964456, 3.7736655876, 0.39427566601, 3.7944569612, 4.04662298246, 0.14269366851, 4.66600220934, 4.21847977142, 2.8142048444, 4.46915157584, 4.71429939378, 1.38925168648, 4.69427401677, 3.33196861521, 2.70989366066, 0.72221452149, 5.53894834507, 2.04879024946, 4.37879205675, 0.57625721169, 1.78471307843, 1.09547571668, 5.02230424673, 2.24605985689, 6.26009139838, 1.93802583909, 0.13064402023, 6.05309072952, 1.18002886182, 2.50762435685, 2.55643759758, 5.33273079625, 1.49151911226, 4.24000912367, 0.39610887139, ], [ 6283.3196674749, 0.2438174835, 12566.3955174663, 18849.4713674577, 6282.83203250789, 6279.7965491259, 6286.84278582391, 6309.61798727471, 6257.0213476751, 6127.8992680407, 6438.7400669091, 83997.09113559539, 710.1768660418, 4705.9761250271, 5507.7970561509, 25132.5472174491, 7058.8422787989, 775.7664288075, 6290.4332144757, 6276.2061204741, 7860.6632099227, 5487.0216606585, 1059.6257476727, 5753.6287023803, 7079.61767429131, 6040.5910635009, 5885.1706640667, 6526.04827144891, 6681.46867088311, 6813.0106325695, 5729.7502646325, 6282.3393464067, 529.9347825781, 6284.2999885431, 6836.8890703173, 5331.6012612243, 4933.4522578161, 167284.005405149, 1577.0997249643, 7235.0380737255, 11790.8729061423, 4137.1542509997, 11856.462468908, 7633.1870771337, 1194.6908277081, 11507.0135872771, 4535.3032544079, 155.17658195069, 5088.8726572503, 2353.1099712553, 801.5771136403, 796.5418242999, 3128.6325825793, 12569.91863581531, 8031.3360805419, 1589.3167127673, 8429.4850839501, 6496.6187629129, 4693.75913722409, 7477.7666776995, 6070.0205720369, 3739.0052475915, 1592.8398311163, 26.0545023163, 553.32558535889, 12036.7045523717, 5223.4501023187, 10213.5293636945, 156137.71980228278, 951.4745887671, 1990.9888345245, 12565.9078824993, 12721.8159169005, 398.3928208917, 4690.7236538421, 5481.4987363511, 242.97242145751, 9438.0067523705, 8827.6340873583, 3154.4432674121, 11371.9485072417, 14143.7390599141, 1747.7725955835, 7085.1405985987, 1349.62359217529, 11770.0975106499, 4164.0681721295, 7875.91568110771, 2389.1378379327, 10977.32262218251, 7342.7015976641, 5223.93773728571, 10973.7995038335, 13368.2164485901, 10575.6505004253, 12410.9751180321, 3930.4535137031, 397.9051859247, 12592.6938372661, 8636.18582124671, 13119.9649203087, 5507.3094211839, 17260.3984721739, 4292.5746504339, 17790.08943726851, 12562.8723991173, 13518.1139237169, 12168.2465140581, 10989.0519750185, 2145.92159899169, 6283.25235717211, 13096.0864825609, 6283.3869777777, 16730.70750707931, 12540.0971976665, 10177.5014970171, 12323.6669134923, 6709.91785835091, 5642.4420600927, 5856.7214765989, 250570.9196747026, 5753.14106741329, 14314.4119305333, 13916.2629271251, 7084.6529636317, 6924.1972748571, 31415.6230674405, 71430.45180064559, 529.44714761109, 95143.3767384616, 8274.0646845159, 16496.6052136859, 5642.93474619389, 213.5429129215, 640.1411037975, 4690.23601887509, 13341.9181287903, 4731.7868098599, 3893.93801205869, 12573.5090644671, 3634.37720703489, 18319.7804023631, 2787.2868413409, 13362.6935242827, 12964.5445208745, 14919.2616712381, 1577.5873599313, 15721.0826023619, 4292.0870154669, 24073.1652872599, 10447.14402212089, 20426.8149099055, 84672.2320270212, 6370.62787201471, 6196.0114629351, 2119.00767786191, 3185.43584474911, 10976.83498721549, 9437.5191174035, 239424.6340718364, 3495.78900865049, 18139.5383188994, 3929.96587873609, 8661.9965060795, 3894.4256470257, 6262.5442719825, 6304.0950629673, 18875.2820522905, 10420.23010099111, 23013.7833570707, 7.3573644843, 3340.8562441833, 10213.0417287275, 14712.5609339415, 12809.12412144031, 9779.3524936089, 82576.73740351178, 22779.6810636773, 2942.7072407751, 5429.63565075589, 11014.8626598513, 9623.9320941747, 18209.5740811437, 9381.2034902007, 3583.5848481573, 10447.6316570879, 796.0541893329, 9917.45305702629, 12012.8261146239, 14143.2514249471, 26709.8907598969, 7632.6994421667, 17256.8753538249, 12353.0964220283, 77714.015285604, 6993.2527160332, 6836.40143535029, 1748.2602305505, 9225.7830907665, 149854.6439522914, 2544.07060239989, 11614.6771112157, 426.8420083595, 30640.1004561165, 155.6642169177, 11926.4982311523, 17298.4261448097, 18073.46112116669, 19651.2922985815, 5856.23384163189, 72850.8055327292, 8983.0544867925, 16460.5773470085, 17259.91083720689, 16858.7263504167, 23543.4743221653, 13367.7288136231, 2146.4092339587, 22484.0923919761, 16200.52890701769, 20199.3387771165, 8672.21368792411, 18073.9487561337, 16201.0165419847, 7860.17557495569, 18451.3223640495, 5572.8989839496, 17996.2749857057, 19403.0407703001, 14945.0723560709, 12559.2819704655, 10818.3791043993, 12567.37583853451, 28767.1682419675, 90280.1669855868, 22805.4917485101, 35372.1310834599, 11506.52595231009, 21228.63584102931, 12779.6946129043, 23141.8022004081, 1350.1112271423, 10575.1628654583, 22345.5041935917, 9778.8648586419, 29826.5501721567, 23581.5019948011, 25158.8455372489, ], ]; pub const X3: [[f64; 46]; 3] = [ [ 0.0000023279, 0.00000076843, 0.00000035331, 0.00000005282, 0.00000001631, 0.00000001483, 0.00000001479, 0.00000000652, 0.00000000656, 0.00000000317, 0.00000000318, 0.00000000227, 0.00000000201, 0.00000000201, 0.00000000036, 0.00000000034, 0.00000000033, 0.00000000032, 0.00000000032, 0.00000000026, 0.00000000023, 0.00000000025, 0.00000000027, 0.0000000002, 0.00000000019, 0.00000000019, 0.00000000018, 0.00000000017, 0.00000000013, 0.00000000011, 0.0000000001, 0.0000000001, 0.00000000009, 0.00000000011, 0.00000000009, 0.00000000008, 0.00000000008, 0.00000000008, 0.00000000007, 0.00000000007, 0.00000000005, 0.00000000005, 0.00000000006, 0.00000000006, 0.00000000005, 0.00000000005, ], [ 3.40634928966, 2.52439403387, 3.34616699853, 2.40489818589, 5.43859760597, 2.22678849266, 4.40151760084, 4.70876083993, 1.58695055624, 3.00237328519, 3.63024148359, 2.27961613476, 0.81376672334, 5.8064290051, 1.33765000112, 1.93992455025, 4.22745351005, 5.38348719867, 4.41212819179, 0.50334838608, 2.01776542272, 1.5840599004, 5.17969059866, 3.76292921295, 3.01515389134, 6.05056350877, 2.29290644779, 0.49235818139, 4.49557806784, 5.29141894629, 4.46246654504, 3.03842434664, 1.50545167256, 6.25880735981, 5.39258795934, 1.26531983919, 2.25393064493, 3.03070423945, 2.58386169059, 1.92157668691, 4.86563371701, 6.21240311845, 3.95562930301, 5.83931193332, 3.46747665337, 3.58293336989, ], [ 0.2438174835, 12566.3955174663, 6283.3196674749, 18849.4713674577, 6282.83203250789, 6438.7400669091, 6127.8992680407, 6279.7965491259, 6286.84278582391, 6526.04827144891, 6040.5910635009, 25132.5472174491, 6836.8890703173, 5729.7502646325, 12569.91863581531, 4705.9761250271, 12410.9751180321, 6257.0213476751, 6309.61798727471, 775.7664288075, 1059.6257476727, 7860.6632099227, 12565.9078824993, 5753.6287023803, 5885.1706640667, 6813.0106325695, 12721.8159169005, 6681.46867088311, 5487.0216606585, 7079.61767429131, 5507.7970561509, 11790.8729061423, 11507.0135872771, 12592.6938372661, 7058.8422787989, 6290.4332144757, 6276.2061204741, 796.5418242999, 4693.75913722409, 7.3573644843, 3739.0052475915, 6070.0205720369, 6284.2999885431, 6282.3393464067, 4137.1542509997, 6496.6187629129, ], ]; pub const X4: [[f64; 20]; 3] = [ [ 0.00000114918, 0.00000006817, 0.00000003158, 0.00000000211, 0.0000000021, 0.00000000253, 0.00000000073, 0.00000000042, 0.00000000023, 0.00000000022, 0.00000000012, 0.00000000009, 0.00000000009, 0.00000000008, 0.00000000005, 0.00000000005, 0.00000000005, 0.00000000005, 0.00000000004, 0.00000000003, ], [ 0.06053023506, 4.47624663983, 0.47910545815, 3.72351646714, 2.88489921647, 0.64665875683, 3.92376796583, 4.60322795936, 6.04513529243, 6.04140763882, 0.51640078868, 4.2100805556, 5.19392488383, 6.16587249238, 5.9791399691, 3.78878463461, 2.68915538708, 5.56850457487, 3.40118346072, 5.17221494066, ], [ 6283.3196674749, 0.2438174835, 12566.3955174663, 6438.7400669091, 6127.8992680407, 18849.4713674577, 6282.83203250789, 710.1768660418, 6279.7965491259, 6286.84278582391, 25132.5472174491, 83997.09113559539, 11856.462468908, 167284.005405149, 6257.0213476751, 6309.61798727471, 12410.9751180321, 156137.71980228278, 12565.9078824993, 529.9347825781, ], ]; pub const X5: [[f64; 7]; 3] = [ [ 0.00000000877, 0.00000000305, 0.00000000101, 0.00000000025, 0.00000000025, 0.0000000001, 0.00000000003, ], [ 0.16136296068, 5.62973274927, 4.88076699149, 5.30593958386, 1.27879113841, 5.11399286577, 2.56205735968, ], [ 6283.3196674749, 0.2438174835, 12566.3955174663, 6438.7400669091, 6127.8992680407, 18849.4713674577, 6282.83203250789, ], ]; pub const Y0: [[f64; 1007]; 3] = [ [ 0.99986069925, 0.02506324281, 0.00835274807, 0.00010466796, 0.00003490608, 0.00003110838, 0.00002561408, 0.00002142365, 0.00001709161, 0.00001707934, 0.00001442753, 0.00001113027, 0.00000934484, 0.00000899854, 0.0000056682, 0.00000661858, 0.00000739644, 0.00000681381, 0.00000611293, 0.00000451129, 0.00000451985, 0.00000449743, 0.00000406291, 0.00000541115, 0.00000546682, 0.0000051378, 0.00000263916, 0.0000021722, 0.00000292146, 0.00000227915, 0.00000226835, 0.00000255833, 0.00000256157, 0.00000178679, 0.00000178303, 0.00000178303, 0.00000155471, 0.00000155246, 0.0000020764, 0.00000199988, 0.0000012897, 0.00000128155, 0.00000152241, 0.00000078109, 0.00000073503, 0.00000093001, 0.00000065526, 0.0000006324, 0.00000062961, 0.0000008587, 0.00000083233, 0.0000006285, 0.00000079971, 0.00000060043, 0.00000075613, 0.00000053731, 0.00000057574, 0.00000057574, 0.00000072385, 0.00000051135, 0.00000050604, 0.00000049613, 0.00000048009, 0.00000059233, 0.00000048264, 0.00000047368, 0.00000039225, 0.00000051307, 0.00000050639, 0.00000039555, 0.00000042757, 0.00000048941, 0.00000048302, 0.00000037971, 0.00000043643, 0.0000003183, 0.00000033959, 0.00000030184, 0.00000032562, 0.00000038887, 0.00000028515, 0.00000028873, 0.00000036633, 0.00000024984, 0.00000026364, 0.00000030326, 0.00000028166, 0.00000028001, 0.00000021157, 0.00000023113, 0.00000021642, 0.00000019448, 0.00000026055, 0.00000018232, 0.00000023248, 0.00000022785, 0.00000017091, 0.00000019399, 0.00000021067, 0.0000002131, 0.00000014189, 0.00000013864, 0.00000018884, 0.00000017875, 0.00000018602, 0.00000013605, 0.00000015064, 0.00000012969, 0.00000014403, 0.00000013311, 0.00000013645, 0.00000011583, 0.00000011405, 0.00000015057, 0.0000001433, 0.00000012375, 0.00000012366, 0.00000010016, 0.00000012435, 0.00000009513, 0.00000010997, 0.00000011583, 0.00000009034, 0.00000011842, 0.00000008869, 0.00000008614, 0.00000010312, 0.00000008411, 0.00000007911, 0.00000010379, 0.00000010374, 0.0000001048, 0.00000007404, 0.00000007357, 0.0000000982, 0.00000007018, 0.00000009668, 0.00000007545, 0.00000007202, 0.00000007144, 0.00000008883, 0.00000006626, 0.00000007015, 0.00000006159, 0.00000007413, 0.00000006355, 0.00000007286, 0.00000006314, 0.00000006257, 0.00000006484, 0.00000005803, 0.00000006391, 0.0000000753, 0.00000006921, 0.00000007626, 0.00000007531, 0.00000006902, 0.00000005434, 0.00000006223, 0.00000007296, 0.00000005833, 0.00000007171, 0.00000006251, 0.00000006251, 0.00000005683, 0.00000006383, 0.00000006194, 0.00000005036, 0.00000006774, 0.00000006224, 0.00000004621, 0.00000006293, 0.00000006297, 0.00000005186, 0.00000006196, 0.0000000616, 0.00000005414, 0.00000005413, 0.00000004863, 0.00000005711, 0.0000000515, 0.00000004269, 0.00000004017, 0.00000004069, 0.00000003993, 0.00000004016, 0.0000000529, 0.00000004831, 0.00000003487, 0.0000000412, 0.0000000441, 0.00000004023, 0.0000000398, 0.00000003173, 0.00000003293, 0.00000002935, 0.00000002979, 0.0000000398, 0.00000003892, 0.00000003042, 0.00000003608, 0.00000003721, 0.00000003581, 0.0000000288, 0.00000002806, 0.00000003626, 0.00000002794, 0.00000002729, 0.00000003625, 0.00000003206, 0.00000003556, 0.00000002856, 0.00000002611, 0.00000002535, 0.0000000352, 0.00000003434, 0.00000002572, 0.00000002647, 0.00000003026, 0.00000002378, 0.00000002979, 0.00000003082, 0.00000002716, 0.00000002215, 0.00000003032, 0.00000002421, 0.00000002275, 0.00000002466, 0.00000002529, 0.00000002015, 0.00000002218, 0.00000002005, 0.0000000201, 0.00000002641, 0.00000002438, 0.00000001893, 0.00000001893, 0.00000002156, 0.00000002071, 0.00000002395, 0.00000001954, 0.00000002006, 0.00000001776, 0.00000001964, 0.00000002332, 0.00000001863, 0.00000001928, 0.00000002436, 0.00000002163, 0.0000000225, 0.00000002052, 0.00000001886, 0.0000000217, 0.00000002058, 0.00000001774, 0.00000001841, 0.00000001578, 0.00000001577, 0.00000001541, 0.00000002012, 0.00000001543, 0.00000001543, 0.00000001513, 0.00000001489, 0.00000001639, 0.00000001443, 0.00000001337, 0.00000001797, 0.00000001488, 0.00000001453, 0.00000001349, 0.00000001477, 0.00000001688, 0.00000001491, 0.00000001471, 0.00000001263, 0.00000001685, 0.00000001375, 0.00000001641, 0.000000012, 0.00000001272, 0.00000001214, 0.00000001406, 0.00000001524, 0.00000001149, 0.00000001547, 0.0000000146, 0.00000001323, 0.00000001252, 0.00000001459, 0.00000001235, 0.00000001028, 0.0000000133, 0.00000001312, 0.00000001246, 0.00000000992, 0.00000000988, 0.00000001365, 0.0000000102, 0.00000001191, 0.00000001191, 0.00000000978, 0.00000000971, 0.00000000962, 0.00000001025, 0.0000000099, 0.00000000964, 0.00000000944, 0.00000000944, 0.00000001092, 0.00000001132, 0.00000000859, 0.00000001213, 0.00000000942, 0.00000000942, 0.00000001045, 0.00000000851, 0.0000000085, 0.00000000895, 0.0000000102, 0.00000000845, 0.00000000863, 0.00000000853, 0.00000000811, 0.00000000966, 0.00000000917, 0.00000001083, 0.00000000779, 0.00000000964, 0.00000000995, 0.00000000962, 0.00000000779, 0.0000000098, 0.0000000093, 0.00000000829, 0.00000000733, 0.00000000743, 0.00000000818, 0.00000000905, 0.00000000905, 0.00000000798, 0.00000000817, 0.00000000884, 0.00000000755, 0.00000000651, 0.00000000616, 0.00000000651, 0.00000000723, 0.00000000784, 0.00000000784, 0.00000000785, 0.00000000611, 0.00000000576, 0.0000000057, 0.00000000576, 0.0000000077, 0.00000000773, 0.00000000581, 0.00000000719, 0.00000000578, 0.00000000536, 0.00000000633, 0.00000000581, 0.00000000532, 0.00000000657, 0.00000000599, 0.0000000054, 0.0000000054, 0.00000000628, 0.00000000532, 0.00000000513, 0.00000000649, 0.00000000582, 0.00000000517, 0.00000000609, 0.00000000615, 0.00000000622, 0.00000000536, 0.00000000516, 0.00000000613, 0.00000000583, 0.00000000636, 0.00000000665, 0.00000000583, 0.00000000479, 0.00000000571, 0.00000000565, 0.00000000462, 0.00000000551, 0.00000000504, 0.00000000535, 0.0000000046, 0.00000000449, 0.00000000453, 0.00000000527, 0.00000000502, 0.00000000603, 0.00000000532, 0.0000000053, 0.00000000431, 0.00000000465, 0.00000000559, 0.00000000485, 0.00000000584, 0.0000000055, 0.00000000481, 0.00000000569, 0.00000000551, 0.00000000389, 0.00000000389, 0.00000000388, 0.00000000388, 0.00000000515, 0.00000000394, 0.00000000491, 0.0000000044, 0.00000000382, 0.00000000503, 0.00000000439, 0.00000000381, 0.00000000371, 0.00000000516, 0.00000000417, 0.00000000483, 0.00000000381, 0.00000000378, 0.00000000393, 0.00000000376, 0.00000000365, 0.00000000371, 0.00000000355, 0.00000000499, 0.00000000379, 0.00000000471, 0.00000000417, 0.00000000485, 0.00000000358, 0.00000000358, 0.00000000365, 0.00000000351, 0.00000000351, 0.00000000429, 0.00000000388, 0.00000000464, 0.00000000396, 0.00000000421, 0.00000000366, 0.0000000036, 0.00000000336, 0.00000000336, 0.00000000326, 0.00000000395, 0.0000000045, 0.00000000363, 0.00000000399, 0.00000000316, 0.0000000043, 0.00000000363, 0.00000000317, 0.00000000395, 0.00000000324, 0.00000000299, 0.00000000304, 0.00000000298, 0.00000000414, 0.00000000339, 0.00000000351, 0.00000000362, 0.00000000304, 0.00000000395, 0.0000000032, 0.00000000384, 0.00000000279, 0.00000000365, 0.00000000377, 0.00000000275, 0.00000000316, 0.00000000339, 0.00000000386, 0.00000000273, 0.00000000314, 0.00000000281, 0.00000000287, 0.00000000265, 0.00000000325, 0.00000000362, 0.00000000269, 0.00000000344, 0.00000000255, 0.00000000334, 0.00000000316, 0.00000000283, 0.00000000305, 0.0000000027, 0.00000000243, 0.00000000243, 0.00000000296, 0.00000000301, 0.00000000329, 0.00000000267, 0.00000000285, 0.00000000286, 0.00000000311, 0.00000000319, 0.00000000241, 0.00000000229, 0.00000000235, 0.00000000253, 0.00000000277, 0.00000000234, 0.00000000216, 0.00000000241, 0.00000000214, 0.00000000213, 0.0000000024, 0.00000000212, 0.00000000259, 0.00000000259, 0.00000000222, 0.00000000201, 0.00000000274, 0.00000000243, 0.00000000234, 0.00000000203, 0.00000000246, 0.00000000216, 0.0000000021, 0.00000000199, 0.0000000027, 0.00000000207, 0.00000000212, 0.00000000269, 0.00000000221, 0.00000000225, 0.00000000197, 0.00000000192, 0.00000000241, 0.00000000261, 0.00000000255, 0.00000000256, 0.00000000182, 0.0000000025, 0.00000000196, 0.00000000187, 0.00000000229, 0.00000000175, 0.00000000187, 0.00000000175, 0.00000000241, 0.00000000236, 0.00000000217, 0.00000000173, 0.00000000191, 0.00000000231, 0.00000000169, 0.00000000235, 0.00000000188, 0.00000000217, 0.0000000023, 0.00000000208, 0.00000000165, 0.00000000177, 0.00000000208, 0.00000000167, 0.00000000198, 0.00000000169, 0.00000000214, 0.00000000172, 0.00000000172, 0.00000000223, 0.00000000159, 0.00000000219, 0.00000000207, 0.00000000176, 0.0000000017, 0.0000000017, 0.00000000205, 0.00000000167, 0.0000000021, 0.00000000163, 0.00000000159, 0.00000000148, 0.00000000165, 0.00000000196, 0.00000000146, 0.00000000148, 0.00000000146, 0.00000000143, 0.00000000142, 0.0000000014, 0.00000000153, 0.00000000162, 0.00000000162, 0.00000000143, 0.00000000188, 0.00000000155, 0.00000000174, 0.00000000179, 0.00000000135, 0.00000000164, 0.00000000134, 0.00000000174, 0.00000000146, 0.00000000137, 0.00000000167, 0.00000000152, 0.00000000124, 0.00000000135, 0.00000000172, 0.00000000123, 0.00000000122, 0.0000000017, 0.00000000155, 0.0000000012, 0.00000000141, 0.0000000012, 0.00000000123, 0.00000000144, 0.00000000165, 0.00000000119, 0.00000000117, 0.00000000163, 0.00000000163, 0.00000000119, 0.00000000145, 0.00000000145, 0.00000000159, 0.00000000114, 0.00000000147, 0.00000000156, 0.00000000131, 0.00000000118, 0.00000000118, 0.00000000137, 0.00000000137, 0.00000000109, 0.00000000111, 0.00000000111, 0.00000000123, 0.00000000107, 0.00000000133, 0.00000000123, 0.00000000123, 0.00000000113, 0.00000000131, 0.0000000011, 0.0000000011, 0.00000000103, 0.00000000103, 0.00000000113, 0.00000000103, 0.00000000115, 0.00000000107, 0.00000000107, 0.00000000106, 0.00000000143, 0.00000000143, 0.00000000115, 0.00000000112, 0.00000000099, 0.00000000126, 0.00000000115, 0.000000001, 0.00000000107, 0.0000000012, 0.00000000138, 0.00000000138, 0.00000000105, 0.00000000135, 0.00000000104, 0.00000000098, 0.00000000111, 0.000000001, 0.00000000095, 0.0000000013, 0.0000000012, 0.00000000114, 0.00000000114, 0.00000000119, 0.00000000117, 0.00000000107, 0.00000000095, 0.0000000011, 0.0000000011, 0.00000000097, 0.00000000095, 0.00000000091, 0.00000000112, 0.00000000126, 0.000000001, 0.00000000127, 0.00000000119, 0.00000000089, 0.00000000126, 0.00000000093, 0.0000000012, 0.00000000118, 0.00000000099, 0.00000000095, 0.00000000089, 0.00000000124, 0.00000000089, 0.00000000096, 0.00000000096, 0.00000000103, 0.00000000099, 0.00000000099, 0.0000000009, 0.00000000086, 0.00000000086, 0.00000000098, 0.00000000098, 0.00000000086, 0.00000000118, 0.00000000117, 0.00000000083, 0.00000000092, 0.00000000085, 0.00000000101, 0.00000000088, 0.00000000113, 0.00000000083, 0.00000000082, 0.00000000087, 0.00000000107, 0.00000000084, 0.00000000084, 0.00000000107, 0.00000000082, 0.00000000105, 0.00000000105, 0.00000000114, 0.00000000082, 0.00000000112, 0.00000000102, 0.00000000102, 0.00000000092, 0.00000000083, 0.00000000112, 0.0000000008, 0.0000000008, 0.00000000088, 0.00000000081, 0.00000000092, 0.0000000011, 0.00000000087, 0.00000000085, 0.00000000078, 0.0000000008, 0.0000000008, 0.00000000079, 0.00000000088, 0.00000000081, 0.00000000093, 0.00000000088, 0.00000000096, 0.00000000106, 0.00000000097, 0.00000000081, 0.00000000077, 0.00000000076, 0.00000000098, 0.00000000083, 0.00000000079, 0.00000000096, 0.00000000096, 0.00000000075, 0.00000000074, 0.00000000074, 0.00000000073, 0.00000000073, 0.00000000085, 0.00000000072, 0.00000000072, 0.000000001, 0.00000000085, 0.00000000075, 0.00000000076, 0.00000000072, 0.00000000097, 0.00000000087, 0.0000000008, 0.0000000007, 0.0000000007, 0.0000000007, 0.00000000078, 0.0000000007, 0.00000000077, 0.00000000069, 0.00000000082, 0.00000000067, 0.00000000067, 0.00000000067, 0.00000000077, 0.0000000008, 0.0000000007, 0.0000000007, 0.00000000074, 0.00000000076, 0.00000000091, 0.00000000091, 0.00000000067, 0.00000000067, 0.00000000067, 0.00000000083, 0.0000000008, 0.00000000068, 0.00000000069, 0.00000000089, 0.00000000079, 0.00000000073, 0.00000000073, 0.00000000065, 0.00000000064, 0.00000000066, 0.00000000066, 0.00000000065, 0.00000000076, 0.00000000084, 0.00000000063, 0.00000000064, 0.00000000072, 0.00000000066, 0.00000000072, 0.00000000061, 0.00000000064, 0.00000000068, 0.00000000062, 0.00000000073, 0.0000000006, 0.00000000078, 0.0000000006, 0.00000000059, 0.00000000075, 0.00000000058, 0.0000000006, 0.00000000069, 0.00000000059, 0.00000000062, 0.00000000081, 0.00000000059, 0.00000000059, 0.00000000063, 0.00000000057, 0.00000000057, 0.0000000006, 0.00000000072, 0.00000000059, 0.00000000068, 0.00000000056, 0.00000000056, 0.00000000056, 0.00000000057, 0.00000000057, 0.00000000069, 0.00000000059, 0.00000000065, 0.00000000059, 0.00000000073, 0.00000000076, 0.00000000067, 0.00000000073, 0.00000000074, 0.0000000007, 0.0000000006, 0.00000000059, 0.00000000074, 0.00000000058, 0.00000000053, 0.00000000059, 0.00000000063, 0.00000000056, 0.00000000063, 0.0000000007, 0.00000000072, 0.00000000052, 0.00000000052, 0.00000000052, 0.00000000054, 0.00000000066, 0.00000000066, 0.00000000051, 0.00000000058, 0.00000000061, 0.00000000054, 0.00000000056, 0.00000000067, 0.00000000056, 0.00000000062, 0.00000000062, 0.0000000005, 0.0000000005, 0.0000000005, 0.0000000005, 0.00000000049, 0.00000000049, 0.00000000065, 0.00000000069, 0.00000000068, 0.00000000049, 0.0000000005, 0.00000000049, 0.00000000059, 0.0000000005, 0.00000000059, 0.00000000058, 0.00000000051, 0.00000000048, 0.00000000065, 0.00000000056, 0.00000000057, 0.00000000048, 0.00000000047, 0.0000000006, 0.00000000049, 0.0000000005, 0.00000000046, 0.00000000048, 0.00000000055, 0.00000000054, 0.0000000006, 0.00000000064, 0.00000000059, 0.00000000049, 0.00000000058, 0.00000000058, 0.00000000046, 0.00000000045, 0.00000000055, 0.00000000055, 0.00000000061, 0.00000000054, 0.00000000054, 0.00000000044, 0.00000000052, 0.00000000044, 0.00000000045, 0.00000000046, 0.00000000048, 0.00000000051, 0.00000000045, 0.00000000046, 0.00000000047, 0.00000000051, 0.00000000046, 0.00000000052, 0.00000000052, 0.00000000044, 0.00000000049, 0.00000000053, 0.00000000045, 0.00000000043, 0.00000000043, 0.00000000049, 0.00000000044, 0.00000000042, 0.00000000045, 0.00000000051, 0.00000000041, 0.00000000057, 0.00000000047, 0.00000000056, 0.0000000005, 0.00000000047, 0.00000000041, 0.00000000056, 0.00000000048, 0.00000000054, 0.00000000052, 0.00000000043, 0.00000000041, 0.00000000042, 0.00000000044, 0.00000000044, 0.00000000039, 0.0000000004, 0.00000000044, 0.0000000005, 0.00000000054, 0.00000000054, 0.00000000045, 0.00000000047, 0.00000000043, 0.00000000047, 0.00000000047, 0.0000000004, 0.00000000043, 0.00000000042, 0.00000000051, 0.00000000042, 0.00000000042, 0.00000000052, 0.0000000004, 0.0000000004, 0.0000000004, 0.00000000038, 0.00000000037, 0.00000000037, 0.00000000042, 0.00000000042, 0.00000000042, 0.0000000004, 0.00000000043, 0.00000000041, 0.00000000038, 0.0000000005, 0.0000000005, ], [ 0.18267413078, 3.36739796418, 0.13953892859, 0.0964235154, 6.0145343591, 5.38114087369, 5.29827505528, 2.66284107563, 5.20779761275, 4.58234386738, 1.90130765657, 5.26701283158, 4.50305745607, 1.60527831001, 0.58162314212, 6.02414120157, 2.79582891432, 0.6473576526, 3.81390547656, 4.52236258525, 5.99169934357, 3.79862296384, 5.25608267423, 5.49909532338, 6.17348361999, 2.86615405111, 3.8247211995, 2.94186064336, 4.0845198998, 5.95179814771, 4.84435977688, 0.69465437518, 6.16717762843, 1.39565997429, 5.11711459804, 4.6730116282, 0.05335100564, 6.13208007594, 4.28246516283, 2.5013719743, 3.64618696457, 3.23179068571, 5.58140597212, 0.27810887092, 1.12438065243, 5.50857519732, 2.08488700481, 0.67044494917, 2.83649752628, 1.45351146305, 4.62701145755, 0.46743502764, 0.92256149872, 1.82875530765, 2.58868557323, 6.27507790078, 2.39891957636, 1.1080213427, 0.13875968847, 6.02476231374, 3.77440441934, 1.07290414466, 2.4349225284, 5.35402385929, 0.05887245943, 4.53616745806, 1.68202291816, 4.21369114598, 0.48135592944, 3.35943021943, 2.06983819322, 5.16594049812, 2.17445966751, 1.47013374285, 4.71767697827, 3.57964760085, 0.15150934422, 2.39802729198, 4.41726666203, 0.64783670316, 4.53853388778, 5.72467865653, 1.33719170745, 3.74998709416, 5.25860499861, 0.42292659979, 5.193662231, 1.25523598395, 3.50176956898, 5.57235828208, 3.06444525139, 5.97216607301, 1.87419996146, 4.98441727809, 4.61930360205, 2.73901481639, 5.29823070971, 6.00268090156, 2.22953967314, 3.08840298987, 6.02227444325, 3.0227098864, 0.85614785764, 4.86899529635, 2.07103958699, 3.62641283985, 1.5506840567, 4.49412072551, 6.14964820819, 2.03652540541, 3.57902352159, 3.88983863974, 5.97095658034, 0.5019517339, 4.4569550764, 1.53862290035, 1.96831814313, 3.81622500644, 5.77865382585, 5.90294963286, 0.62118771904, 2.48171191864, 3.85796197835, 2.59877813496, 3.47611287212, 0.03081566771, 1.02710009735, 0.87289239606, 1.58349090213, 0.10632075985, 3.97648848184, 1.38209289015, 3.8433941719, 5.40136984638, 2.12476608355, 5.94659139192, 3.49318502073, 5.94843445846, 4.31311905021, 5.47703554612, 5.46710407546, 5.41362465894, 5.70701993379, 5.65831198505, 3.46419092567, 3.46461466453, 2.01139981548, 1.51246730786, 2.66128485006, 1.63733658639, 1.38237252918, 2.40521894071, 4.91537693059, 5.41208599854, 2.72257180334, 1.943848114, 4.32614260011, 4.37546348368, 0.67316616422, 1.27743142232, 0.75851095819, 1.43520696239, 0.62294633745, 2.88399458161, 1.92473239272, 2.21747129905, 5.13602240936, 2.26614918626, 3.56437941703, 1.92311046214, 2.91747769543, 0.74955598933, 2.83090961174, 5.42426212805, 4.15785490016, 3.21170376619, 1.428823252, 2.08335586272, 2.19642727179, 2.75632617612, 2.53503851142, 0.81279132183, 2.21501270421, 3.99136293444, 1.29192496097, 0.52802181166, 4.91562568689, 1.26836887601, 1.93988497026, 1.72576404553, 2.23510306717, 1.51236080833, 1.7485234348, 3.62048518613, 5.58717113537, 2.10511347366, 4.62987940723, 5.90920652207, 3.95491793455, 1.6234606112, 4.03873145467, 3.65024914006, 5.75234129258, 0.04145923446, 2.64471981541, 6.13871061291, 0.98030293667, 2.60239924444, 1.43112681156, 3.7247672443, 5.86027209236, 1.76545510884, 0.86182235214, 0.01231069705, 3.80906738831, 2.07577291101, 0.08592522543, 5.39051905541, 3.669984423, 2.05754080989, 5.07398237707, 3.34593854945, 1.49855756532, 3.69564106529, 0.05314931388, 1.58246988642, 4.38385659579, 0.87928045349, 4.37629498907, 0.91352607152, 5.40562909521, 2.59344260095, 5.68334625182, 5.85354681494, 4.55830572881, 5.69296362938, 4.09716259686, 0.43822603611, 2.7509951173, 4.8438725538, 5.08514679694, 5.02287213343, 4.86094102925, 1.8218278612, 2.83569470692, 3.6895097692, 3.02170818288, 2.83691190801, 6.13036805408, 0.82649289984, 3.65926976048, 5.1829321732, 3.92516942708, 3.12741900385, 0.51402656711, 1.91732926338, 4.07231752329, 2.3785919187, 0.23280184119, 1.94074945567, 5.39993967465, 4.39018655159, 2.22141523192, 1.38125902411, 2.86996469977, 0.69249676813, 1.49321921272, 1.4741588746, 4.10370894807, 3.88999021921, 4.18018116919, 2.56925141669, 4.77167367345, 4.65894552032, 4.18699607739, 5.62967869388, 4.1379795716, 2.66006793362, 1.56425462469, 6.18795172265, 5.60977811105, 2.79740025979, 0.96357897619, 2.69987154893, 1.4488207348, 5.59995461433, 3.40155505101, 2.95651083102, 6.12405778157, 3.72728247655, 1.27016887136, 0.93950364612, 5.71304625366, 5.81330482072, 6.23510174757, 2.56738111789, 5.69208485871, 1.39907964627, 1.25240185088, 1.85928407242, 1.64765684663, 3.16773125497, 0.33921091467, 1.06488912173, 0.64688768472, 5.10278829353, 3.3627237261, 4.29299913988, 5.49712708636, 2.34985569802, 5.71867421008, 6.19348487479, 5.61315622766, 3.6571110443, 6.13301518193, 5.17434482333, 3.62598735241, 6.16443178844, 0.83009579073, 5.42778314413, 4.18420138552, 2.86079142045, 1.18534704592, 1.42220880644, 2.57517734766, 0.8992769645, 2.89594427545, 2.01260050316, 2.34511297941, 4.96662237412, 2.35578735539, 2.02763029837, 6.19670011124, 0.65237052253, 0.38404899643, 4.18029489609, 2.22826365578, 3.21447961169, 2.2445918366, 1.26234908246, 1.05421419226, 5.23322400864, 2.41399532496, 5.40020688961, 5.50763453832, 4.1339481914, 0.84412253043, 1.49663741427, 2.44837693578, 3.77248887935, 1.86574625348, 6.24391260854, 5.94037158869, 2.97586328906, 4.63987761174, 0.89072554788, 1.78442906238, 6.05264641509, 2.47920208822, 2.69917567595, 4.49580958272, 5.88497258324, 1.3571925661, 3.01682546062, 4.82951502701, 0.54713597581, 1.67333017022, 1.83361074884, 5.02906961003, 2.84025435717, 2.13211972766, 3.33488996078, 2.96012797214, 5.63213604686, 2.37414673548, 0.00032066291, 0.82619343851, 2.13145334966, 1.35907342509, 3.36175443914, 1.44072369133, 1.34803641207, 4.3176206835, 4.39404867767, 6.04787718072, 1.01593938825, 5.49171831457, 3.53710274271, 2.4679479802, 0.43308443375, 4.55197610339, 4.75481082956, 0.38594751092, 5.14645638415, 4.67747505318, 5.68646114706, 5.5672596788, 0.26579545469, 5.14730101928, 3.7406631488, 1.12060083942, 0.1448124733, 4.56530394374, 4.78377689692, 5.52640225498, 0.29866487122, 1.38161051216, 3.21618763564, 1.85967717576, 1.6472637433, 5.85202122263, 3.93810500361, 0.09995632139, 1.39198903052, 4.39709251394, 2.54396321518, 1.50580912176, 3.08687612414, 3.25483236471, 3.59564013891, 3.01987537874, 4.04344774561, 2.17381926869, 2.84671280305, 2.79871486639, 2.94872717012, 6.27917510634, 6.02660735301, 0.53940975175, 4.19154046767, 3.67238322579, 1.15482974306, 5.52860495919, 0.07055813902, 1.7599395901, 6.0668309636, 1.92035724848, 1.58658367058, 5.19130080276, 0.64808198517, 4.53436303138, 5.51029115203, 5.2031895103, 5.40703775457, 0.78828729228, 3.2565981164, 5.33851384127, 5.53135776054, 6.12569565789, 3.66443056835, 0.22542241669, 5.25182737341, 1.80229899871, 2.72535712612, 5.51787738042, 2.45995539098, 3.96101117316, 2.7199014567, 3.09968934621, 3.82348351794, 5.27854205827, 2.29226668471, 4.87224846445, 2.25684047934, 5.74970236841, 5.86256617398, 4.36315861783, 1.99294614713, 3.36735752668, 4.78960869869, 0.92821593891, 5.5895190136, 5.67648753585, 5.96664259426, 5.53753804163, 4.16427905835, 1.02608510804, 4.53749399958, 0.71953202985, 5.80758206821, 6.18462887647, 0.15414528977, 4.8722991024, 3.53930677592, 0.92198404013, 2.75236634018, 4.91776126981, 1.94480091531, 3.37543976329, 1.56223491581, 3.97125698165, 2.66015602247, 5.83332121064, 1.6229549985, 0.9760084106, 2.53093250846, 4.79138408835, 5.8188693598, 5.8692212194, 1.84931872641, 0.93414937692, 4.9988626273, 1.63984256457, 3.13980275142, 4.5651896345, 5.72761357577, 4.94058515466, 2.08435720561, 3.15798901317, 3.5549495263, 0.302070439, 3.87591164077, 0.52402082918, 2.22358750694, 4.14485134121, 3.93716983669, 1.64646341991, 1.86047749915, 2.99868754607, 0.39862703515, 5.42466894469, 2.57266886723, 3.66617634256, 1.57613060854, 4.26574746801, 3.35974562754, 4.2541933879, 5.64767313384, 5.11258425974, 1.4954906172, 0.1839197404, 6.23907858108, 4.97264401025, 5.58708477402, 4.93201648946, 0.47501431186, 3.52343193321, 0.88974137342, 2.10230203862, 0.73069007306, 5.98997615944, 2.67103598665, 0.64831634218, 0.04522363352, 1.73812120333, 3.8409426754, 0.76186633809, 6.15302938442, 5.00033837792, 0.4540567077, 3.45380390356, 2.65478632822, 4.70676649838, 4.17552456214, 0.40140025709, 5.04475734159, 4.0258328276, 3.40363231104, 0.83612775625, 5.4329835298, 0.80102915744, 0.01829077781, 6.16123229814, 2.40308314985, 4.8381227703, 2.16903380895, 2.77137176457, 5.97118942936, 3.81893679688, 3.42911214381, 2.33166453392, 0.6956628517, 1.92518585993, 2.48119576594, 4.4395990676, 5.35052715864, 1.15927608909, 3.97305893961, 2.4525507347, 6.18035129909, 0.13779660073, 5.46314197385, 5.59205778351, 5.15079536124, 1.96564383477, 1.10385783973, 4.95120975616, 5.56441247552, 0.65902902155, 5.93480456615, 3.3682682707, 5.27294659555, 3.21674523006, 3.89298583971, 2.11622447442, 4.58570766573, 1.007257815, 0.59168717373, 4.79054860554, 4.03840473864, 3.87019546457, 2.7067587912, 6.27087503385, 1.03021623583, 5.98298407227, 2.62025173907, 4.22571397919, 4.95808633295, 0.23022549161, 0.49830220802, 4.12184350213, 6.16462326207, 5.62824965405, 5.90379805618, 3.95455666878, 4.26997270152, 1.49653119992, 3.70806542711, 2.31400541864, 5.90934736896, 5.45034774436, 1.54456737879, 2.78769461236, 2.71628583938, 2.33523694188, 1.17170397718, 2.61434005227, 3.41169068642, 5.63174103655, 1.00709118546, 0.13588364911, 3.83848144749, 5.95164477875, 0.97335445483, 2.53358646423, 1.1964461813, 2.80331366377, 0.70362725529, 0.80537647876, 0.59542543867, 1.4598651944, 4.07179306364, 5.71833316259, 0.38322617607, 2.04114030865, 0.19106597205, 3.31587494701, 2.3196417272, 1.18729919186, 0.63409757277, 3.00856574797, 1.0979644722, 0.149478717, 1.1880299379, 1.7060101934, 6.22463763653, 5.63223127595, 5.35405637827, 1.02603600816, 0.21940282455, 5.90533164276, 3.09464836385, 1.95823440417, 2.45486702592, 0.25356721797, 2.98838673165, 0.51855418741, 2.60431357489, 5.28295396943, 0.57981411648, 4.00435005538, 5.54435587296, 2.98744963581, 0.17662269567, 0.55194216539, 1.84949333794, 2.18292460802, 1.32401631104, 3.64842963894, 3.47158263266, 0.33835239167, 4.0622835917, 1.22040625314, 2.28653466592, 2.64989366154, 4.41295990485, 1.42377843647, 2.74085534623, 4.67942071523, 1.46206803081, 0.70264556724, 4.42085627054, 6.04696991631, 4.96989590925, 4.1051940064, 0.51718078841, 3.00291998094, 2.04878528903, 1.28476695157, 0.73014646335, 5.19246908636, 5.78577582542, 1.07414401415, 5.45460641914, 2.80667748337, 4.49603988169, 5.29408634455, 1.96044978655, 2.1691077424, 2.50989174885, 1.84392439378, 1.66301652528, 6.05387198611, 2.167647267, 2.53823002855, 4.7121327819, 2.44147365747, 0.72336255749, 4.94259233986, 2.19664804056, 0.47970289838, 2.47657261289, 4.90614394615, 1.67775805144, 3.78836692146, 0.84028318953, 2.66665772953, 2.45229388212, 5.66196525445, 2.30294939014, 1.20399152892, 2.50001149568, 5.40031574607, 4.27968226719, 1.32703960779, 2.17990131127, 6.06909982221, 2.92326536483, 3.91825505548, 2.01989715959, 0.09553378894, 4.57487416308, 5.29168357177, 2.79378764615, 5.08245905369, 3.89276904283, 1.43001232077, 3.02198277867, 1.79867193339, 1.70826898567, 2.9673685588, 5.58307910278, 2.98944824758, 1.14380332092, 1.678216318, 0.48155847774, 3.73745326901, 1.71169429599, 5.19219909829, 6.10587791973, 3.78044498975, 0.77646852784, 0.63561076928, 2.93697401198, 0.4141822589, 3.09275866016, 4.66945944657, 5.37967983395, 4.41044639229, 2.45644384945, 1.05049706961, 2.08161902252, 4.75417028947, 5.03595593677, 3.80714894085, 1.33904345426, 0.39510472937, 0.41148054527, 4.97177288715, 0.21179463686, 2.06337614338, 3.60508005382, 3.06053136401, 0.44640955505, 4.42572835968, 3.37769653143, 3.84581453123, 5.00579533671, 1.30888647192, 3.91623659935, 4.88284115481, 0.26461151247, 3.24232940659, 0.28397734649, 3.79678848458, 3.0309505933, 0.47599032576, 4.12433601146, 4.07719654455, 0.90446873976, 2.6024721793, 4.94532713838, 4.84479908786, 3.01186125982, 4.51648793763, 5.49180050451, 2.07232606852, 0.56996686256, 3.57060375879, 3.24586891365, 0.54359299539, 2.96334792367, 5.236721906, 5.80516008052, 1.12499582368, 2.38194509538, 3.44248995108, 1.46082924902, 0.49974269222, 2.70916029747, 4.80332084911, 2.11265208796, 1.21054975257, 0.02703719822, 3.91641579991, 5.46712129325, 1.33734717206, 2.25046201901, 4.61252989167, 1.65871121739, 2.99014426818, 2.90135289748, 4.12263682656, 2.85045311521, 5.18922617388, 4.91746089028, 4.25329717989, 5.13629564655, 4.44636395235, 5.9829774482, 1.11500712714, 2.39193379192, 0.5630053912, 3.30567043605, 1.5979444444, 0.63448798616, 5.73566114928, 5.39392547964, 1.14499717138, 3.10776343336, 0.3991774857, 0.95649088929, 1.51972566902, 1.98721525004, 0.33222800273, 2.36664156781, 1.96288183765, 1.81423548051, 2.0885444229, 0.77803347659, 0.54633497662, 4.43869578954, 3.17776060575, 6.2781822466, 5.08460970539, 1.03458131364, 1.19968434762, 1.58539308271, 3.6867459949, 5.76308404993, 5.23211999381, 2.45377850108, 2.16148808063, 4.83368738065, 2.62595674809, 0.96524582701, 3.30278586555, 0.20415505351, 2.04667654344, 5.93782050272, 5.93782050272, 2.41252260456, 2.72227505748, 0.72832616881, 3.16101850189, 1.20035157643, 3.89077193587, 0.37854134464, 0.60927850338, 2.89766241568, 3.10994458213, 2.8935214834, 0.38317924664, 3.12376167242, 0.36435757253, 3.50595022612, 2.20156720545, 5.16096365273, 4.61952317468, 4.01249891427, 2.38095415684, 4.98226292129, 0.5483071696, 1.64594745036, 2.71376255252, 3.16580349936, 1.43461397348, 3.23576326319, 1.63790414031, 2.62361047024, 2.56200976684, 3.66284145075, 5.82227097996, 3.54507538375, 2.15364675842, 3.60628396854, 4.33029118489, 4.40476950322, 0.06525117672, 5.90233323358, 3.29126676894, 5.97731735914, 3.6095913283, 3.59486989773, 5.95314247069, 3.83698375555, 1.35461053261, 3.19696372316, 1.99803947181, 1.99803947181, 3.53347961961, 1.22650408797, 2.28043683109, 4.77367705513, 3.85218997059, 2.69173127084, 4.35951224787, 3.84874383995, 4.63629874583, 4.91886576255, 2.63923033609, 3.15339657493, 2.39403388232, 1.31112479278, 2.47672465258, 4.64446990453, 5.14565632171, 3.80837636245, 3.62132943845, 4.674525427, 4.65107782321, 1.54528326296, 0.19791989913, 3.54725333487, 1.47478212539, 2.85938112982, 3.22032934298, 2.95623880108, 5.1439509665, 1.24099052077, 6.03171570454, 5.36736063063, 2.5872993074, 5.61037642387, 2.70468936208, 1.28041103259, 0.93182108526, 2.40910872834, 2.84085536047, 3.12713892129, 1.99075260862, 3.11818521171, 6.1600475768, 3.63007864944, 5.09444795757, 1.17403028794, 3.71228299188, 0.98055905828, 3.12084664124, 0.38609427782, 0.83260974343, 5.83397233956, 6.07854396898, 0.38354823927, 2.93749588479, 1.03647885736, 4.24359473122, 5.53288597787, 4.03405257508, 0.37690679264, 3.13003412642, 1.96232281613, 6.22187049858, 5.00617355027, 4.78395267597, 0.67446092329, 4.98656910933, 4.80355711691, 5.51152847292, 1.28742672679, 2.21951419227, 5.21427505339, 2.22601042104, 5.52595261887, 4.48062431201, 0.05709227621, 4.41842921988, ], [ 6283.3196674749, 0.2438174835, 12566.3955174663, 18849.4713674577, 6282.83203250789, 83997.09113559539, 529.9347825781, 1577.0997249643, 6279.7965491259, 6286.84278582391, 2353.1099712553, 5223.4501023187, 12036.7045523717, 10213.5293636945, 1059.6257476727, 5753.6287023803, 398.3928208917, 4705.9761250271, 6813.0106325695, 5885.1706640667, 6257.0213476751, 6309.61798727471, 6681.46867088311, 775.7664288075, 14143.7390599141, 7860.6632099227, 5507.7970561509, 11507.0135872771, 5507.3094211839, 7058.8422787989, 4693.75913722409, 12168.2465140581, 710.1768660418, 796.5418242999, 6283.25235717211, 6283.3869777777, 25132.5472174491, 5487.0216606585, 11790.8729061423, 17790.08943726851, 7079.61767429131, 3739.0052475915, 213.5429129215, 8827.6340873583, 1589.3167127673, 9437.5191174035, 11770.0975106499, 6262.5442719825, 6304.0950629673, 167284.005405149, 3340.8562441833, 7.3573644843, 6070.0205720369, 4137.1542509997, 6496.6187629129, 1194.6908277081, 6284.2999885431, 6282.3393464067, 10976.83498721549, 6290.4332144757, 6276.2061204741, 6127.8992680407, 6438.7400669091, 3154.4432674121, 801.5771136403, 3128.6325825793, 8429.4850839501, 12353.0964220283, 11856.462468908, 5481.4987363511, 17260.3984721739, 9225.7830907665, 2544.07060239989, 426.8420083595, 5856.23384163189, 2145.92159899169, 7085.1405985987, 10977.32262218251, 4164.0681721295, 13367.7288136231, 12569.91863581531, 3930.4535137031, 18073.9487561337, 26.0545023163, 9438.0067523705, 4535.3032544079, 12562.8723991173, 5088.8726572503, 11371.9485072417, 5223.93773728571, 12559.2819704655, 12565.9078824993, 71430.45180064559, 1747.7725955835, 18319.7804023631, 5753.14106741329, 4933.4522578161, 10447.14402212089, 7477.7666776995, 8031.3360805419, 2942.7072407751, 8636.18582124671, 156137.71980228278, 1592.8398311163, 17297.9385098427, 13096.0864825609, 16496.6052136859, 7633.1870771337, 20426.8149099055, 12139.7973265903, 13368.2164485901, 5331.6012612243, 529.44714761109, 7084.6529636317, 7342.7015976641, 6279.72923882311, 6286.9100961267, 397.9051859247, 15110.7099373497, 7235.0380737255, 10989.0519750185, 5729.7502646325, 9623.9320941747, 15721.0826023619, 6148.2545874395, 6418.38474751031, 6836.8890703173, 14712.5609339415, 2119.00767786191, 1349.62359217529, 5486.53402569149, 5999.4603486097, 6040.5910635009, 5088.3850222833, 6567.1789863401, 6526.04827144891, 21228.1482060623, 12540.0971976665, 6245.2919948391, 6321.3473401107, 5642.93474619389, 5327.7199258663, 7860.17557495569, 12964.5445208745, 23543.4743221653, 1990.9888345245, 537.0483295789, 951.4745887671, 4690.7236538421, 16730.70750707931, 955.3559241251, 24073.1652872599, 10973.7995038335, 522.8212355773, 22004.1584523533, 18422.8731765817, 155.17658195069, 7238.9194090835, 18451.3223640495, 16730.21987211229, 640.1411037975, 3929.96587873609, 6277.7967431675, 6288.8425917823, 1551.2890401315, 5216.33655531789, 5230.5636493195, 14314.4119305333, 102.84895673509, 11014.8626598513, 553.32558535889, 5650.5359281617, 26088.1469590577, 77714.015285604, 84672.2320270212, 239424.6340718364, 6180.2268932563, 6386.4124416935, 90280.1669855868, 6916.1034067881, 1577.5873599313, 7875.91568110771, 6254.8704800071, 3634.37720703489, 6311.7688549427, 4690.23601887509, 25158.3579022819, 5760.7422493811, 10447.6316570879, 6709.91785835091, 6805.89708556871, 4731.7868098599, 5856.7214765989, 1066.7392946735, 9917.45305702629, 12592.6938372661, 12566.4628277691, 13341.9181287903, 75.0254160508, 18053.1733606413, 6208.5380689076, 5966.9277978183, 6358.1012660422, 10575.6505004253, 5863.8350235997, 6599.7115371315, 8030.8484455749, 3.76693583251, 6020.2357441021, 11506.52595231009, 8428.9974489831, 12721.8159169005, 6702.8043113501, 31415.6230674405, 250570.9196747026, 6546.4035908477, 5884.68302909969, 2352.6223362883, 13916.2629271251, 2389.1378379327, 12566.32820716351, 14945.0723560709, 12029.5910053709, 13362.6935242827, 29088.5675985015, 11015.3502948183, 6077.1341190377, 16200.52890701769, 12043.8180993725, 6262.96434807611, 6489.5052159121, 6303.6749868737, 4700.87268422489, 4590.6663630055, 149.8070146181, 6279.4383321169, 6287.2010028329, 18139.5383188994, 11926.4982311523, 1162.7185218913, 13518.1139237169, 3154.9309023791, 13521.9952590749, 4686.6455902233, 10022.0810975829, 242.97242145751, 5746.5151553795, 95143.3767384616, 6037.4880212455, 12669.4882916849, 6529.1513137043, 7238.4317741165, 19651.2922985815, 23013.7833570707, 6820.1241795703, 65147.37595065419, 4292.5746504339, 7632.6994421667, 13119.9649203087, 4292.0870154669, 6293.95633282471, 6272.6830021251, 20.5315780089, 110.45013870291, 17655.0243572331, 1052.51220067191, 2544.5582373669, 33018.7772947211, 76.50988875911, 633.0275567967, 6016.7126257531, 12779.6946129043, 18875.2820522905, 9411.7084325707, 18636.1722720197, 12573.5090644671, 25934.3681485729, 2378.9206560881, 6.86972951729, 11499.9000402763, 6549.9267091967, 10973.3118688665, 11790.3852711753, 18209.5740811437, 10177.5014970171, 11926.01059618529, 246.0754637129, 8661.9965060795, 6993.2527160332, 38.3768531213, 24357.0246061251, 6112.6467968557, 2146.4092339587, 12491.613918899, 5429.63565075589, 6453.9925380941, 8274.0646845159, 11371.4608722747, 4732.2744448269, 6290.36590417291, 6276.2734307769, 6247.2918007975, 6319.34753415231, 12565.4151963981, 12545.6201219739, 4694.2467721911, 3893.93801205869, 6259.44122972711, 6307.1981052227, 17797.2029842693, 17782.9758902677, 1692.40948698591, 82576.73740351178, 6298.57213865991, 6268.0671962899, 15508.8589407579, 6173.1133462555, 6393.5259886943, 3904.1551939033, 220.6564599223, 17256.8753538249, 949.4194264533, 16201.0165419847, 4803.9654584435, 206.42936592071, 149854.6439522914, 36948.9869909407, 2648.6986429565, 796.0541893329, 11403.9208130585, 12567.37583853451, 10213.0417287275, 22805.4917485101, 2787.2868413409, 5120.35732810009, 10575.1628654583, 7834.3648901229, 5572.8989839496, 6284.8041401832, 6281.8351947666, 12410.9751180321, 12416.8323203317, 22483.60475700909, 4060.97539791089, 17259.91083720689, 1596.43025976811, 1748.2602305505, 161000.92955515758, 4907.05823266209, 7234.5504387585, 846.3266522347, 853.4401992355, 12323.6669134923, 12587.1709129587, 13915.77529215809, 6069.53293706989, 6133.2688353733, 11933.6117781531, 15720.5949673949, 8662.48414104651, 18852.9944858067, 52176.0501006319, 5334.1440585051, 18842.3578204569, 5849.1202946311, 6151.7777057885, 6286.6060248927, 6280.0333100571, 17298.4261448097, 11514.1271342779, 12456.1891962469, 11764.5745863425, 6414.8616291613, 3340.36860921629, 10420.23010099111, 10983.94853421629, 5326.5428765373, 7232.49527644471, 433.9555553603, 10969.72144021469, 5863.3473886327, 26735.7014447297, 40879.1966871603, 12592.2062022991, 5547.4431539431, 6062.9070250361, 4171.1817191303, 3104.6862419403, 6503.7323099137, 15670.83794192309, 173567.0812551404, 3495.78900865049, 4274.27449334889, 9387.76209193169, 24602.8562523545, 12490.1294461907, 322711.54834139, 5120.8449630671, 18845.9482491087, 7019.19618100671, 8827.14645239129, 1582.2031657665, 29296.8592070621, 72850.8055327292, 213.0552779545, 14.47091148511, 97238.871361971, 14313.9242955663, 6245.1866318371, 6321.4527031127, 6297.5467614765, 6269.0925734733, 12320.56387123691, 4156.95462512869, 1479.11039154791, 5650.0482931947, 9917.9406919933, 17157.3056979553, 233141.55822184499, 14143.2514249471, 5643.4223811609, 135.30889751891, 13760.8425276909, 9779.3524936089, 14919.2616712381, 17267.5120191747, 7872.39256275871, 13517.62628874989, 6923.2169537889, 13625.7774476555, 10874.2298479639, 161710.8626037159, 3185.43584474911, 11712.71150074729, 22779.6810636773, 12528.26248182851, 6295.0490203109, 6271.5903146389, 6836.40143535029, 11617.21990849651, 205.9417309537, 3894.4256470257, 956.53297345411, 23581.5019948011, 5231.0512842865, 7445.7943718827, 17253.2849251731, 21393.7857873411, 6279.3875142118, 6287.251820738, 1059.1381127057, 5642.4420600927, 1385.3177574676, 22484.0923919761, 16858.7263504167, 20995.6367839329, 19650.8046636145, 7335.5880506633, 11769.6098756829, 5905.94605955911, 37.7838551523, 641.12142486571, 5750.1055840313, 1350.1112271423, 44809.4063833799, 3.6883357796, 12345.9828750275, 21953.91379191449, 29826.5501721567, 4176.2851599325, 10818.3791043993, 10177.01386205009, 10970.2090751817, 6660.6932753907, 29864.5778447925, 20597.4877805247, 316.6356871401, 6924.1972748571, 2636.9692901205, 26709.8907598969, 14945.5599910379, 16858.23871544969, 18073.46112116669, 19379.1623325523, 12360.2099690291, 30665.9111409493, 6816.53375091851, 6147.69434246491, 1376.0176173293, 6418.9449924849, 6055.8435346859, 28287.2343023447, 16522.4158985187, 283.6155013817, 6255.9181113781, 6310.7212235717, 6129.5408569901, 6510.7958002639, 377.6174253993, 24705.9490265731, 5469.7693835151, 6437.0984779597, 11720.3126827151, 169379.5000286584, 632.5399218297, 1265.81129610991, 4487.57358878689, 4377.3672675675, 419.2408263917, 11713.1991357143, 10454.25756912169, 103.3365917021, 2222.1004520805, 30356.2411372513, 6309.1303523077, 262.84010588929, 6283.56348495841, 6283.0758499914, 10440.03047512009, 5746.0275204125, 23581.0143598341, 7096.8699514347, 5573.3866189166, 16460.08971204149, 8672.21368792411, 5437.23683272371, 9381.2034902007, 11216.5281078075, 284.1031363487, 12562.80508881451, 7129.4025022261, 70755.31090921978, 77713.52765063698, 5635.8211991931, 14712.07329897449, 17272.1278250099, 15907.0079441661, 48739.6160795995, 6206.5659612323, 224.5886131854, 18848.98373249069, 5934.39524702691, 16460.5773470085, 22003.6708173863, 2942.21960580809, 11614.6771112157, 9778.8648586419, 3744.5835282543, 8390.3541750173, 1.7282901918, 17996.2749857057, 6275.71848550709, 394.86970254271, 34596.1208371689, 6438.2524319421, 17256.38771885789, 401.91593924071, 10984.4361691833, 6632.2440879229, 11087.5289434019, 743.23387801611, 4796.85191144269, 3097.64000524229, 5714.4977934475, 5539.8419719753, 12132.6837795895, 24492.6499311351, 6233.5626420031, 6333.0766929467, 266.85085920531, 13199.1792567795, 10344.05124790229, 12569.9859461181, 12012.8261146239, 6294.36536773881, 6272.273967211, 13119.47728534169, 17686.9966630499, 13521.50762410789, 802.0647486073, 5017.2645538815, 419.72846135871, 20199.3387771165, 33326.33491569069, 19800.7021387413, 6852.1415415023, 17370.6047933933, 5618.5636223449, 17654.5367222661, 2008.8013566425, 5436.7491977567, 775.2787938405, 12552.1684234647, 5010.1510068807, 28.6930049513, 11610.1063614957, 20452.6255947383, 27511.2240560537, 12431.3304374309, 28767.1682419675, 16840.9138282987, 19805.0711090663, 12701.4605975017, 11.2895177474, 17473.6975676119, 16627.6147328607, 6948.0757126049, 3531.2844328163, 167959.1462965748, 23013.29572210369, 3583.5848481573, 333857.8339442562, 6058.48723680599, 12809.12412144031, 162420.7956522742, 12528.3678448305, 25933.8805136059, 95.7354097343, 52669.8257758191, 19247.6203708659, 11610.7957758577, 661.4767442645, 9929.6700448293, 12250.0036478097, 6205.6458970469, 6360.99343790291, 228278.3484689702, 19402.55313533309, 38526.3305333885, 4307.8271216189, 21228.63584102931, 6263.64990657511, 6302.9894283747, 6315.8522182663, 6250.7871166835, 11925.5179100841, 6226.4212925393, 6340.2180424105, 24734.3982140409, 12463.30274324771, 18875.76968725751, 6260.5444660241, 6306.09486892571, 2111.8941308611, 18415.7596295809, 6289.94822637491, 6276.69110857489, 6241.7688764901, 6324.8704584597, 3496.2766436175, 10344.5388828693, 24336.2492106327, 83974.0791732134, 84020.1030979774, 12772.58106590351, 2069.2506523901, 18773.2052961821, 3641.4907540357, 11499.41240530929, 11190.6217176205, 18823.1730476579, 12570.3276707294, 16062.4283436003, 5216.8241902849, 9814.36028280769, 6210.0225416159, 6356.6167933339, 12721.32828193349, 18699.9081703231, 12560.8725931589, 5815.3546771205, 10239.3400485273, 263.3277408563, 155.6642169177, 27511.7116910207, 31441.4337522733, 6155.3008241375, 6411.3385108123, 951.9622237341, 28236.98964190589, 21.0192129759, 11300.8280388399, 6312.74917601091, 6253.8901589389, 78263.95324220609, 23938.1002072245, 12829.4794408391, 16737.8210540801, 3.2793008655, 6133.7564703403, 1293.24040609909, 17893.1822114871, 23539.9512038163, 311565.2627385237, 736.1203310153, 14158.9915310991, 16061.94070863329, 6432.8828646095, 2699.49100183409, 15671.3255768901, 178430.2910080152, 6751.28465782931, 7349.81514466491, 24066.0517402591, 18202.4605341429, 6252.40554183991, 6314.2337931099, 58864.30010066279, 9380.71585523369, 10557.35034334029, 6439.7203879773, 6126.91894697251, 23123.9896782901, 13951.9570924174, 89570.23393702849, 8858.0711268371, 12342.0507217644, 5017.7521888485, 18429.9867235825, 17054.2129237367, 12985.88016134151, 20597.0001455577, 5483.4985423095, 21424.2228268199, 522.3336006103, 6187.3404402571, 6379.2988946927, 24382.8352909579, 8983.0544867925, 6131.4223863897, 6435.2169485601, 8258.81221333091, 3957.8826236923, 3738.51761262449, 5767.8557963819, 6798.7835385679, 18216.6876281445, 29864.0902098255, 12189.0219095505, 24080.2788342607, 15141.14697682849, 1573.57660661529, 1550.8014051645, 101426.452588453, 78423.9483341623, 1580.6228433133, 27043.2590656993, 6812.5229976025, 6081.06627230081, 6485.573062649, 36109.6260221481, 16944.0066025173, 5.2791068239, 16737.33341911309, 12537.9463299985, 20198.85114214949, 56600.0354720387, 6040.10342853389, 3956.2641985359, 40796.5827401577, 22743.16556203289, 42456.5402296081, 19801.1897737083, 5622.08674069391, 5888.6937824157, 6677.9455525341, 41194.7317435659, 6261.9840270079, 6304.6553079419, 5870.9485706005, 6695.6907643493, 12850.2548363315, 6253.4982293261, 6313.14110562371, 5316.3487900393, 12282.5361986011, 24422.6141688908, 63659.1215683211, 16723.5939600785, 17995.78735073869, 18106.4813069251, 17363.4912463925, 6124.37614969171, 6442.2631852581, 4705.4884900601, 23550.5878691661, 12036.21691740469, 5237.67719632029, 16207.64245401849, 6774.98295993371, 7083.14079264031, 6394.50630976251, 6172.1330251873, 9924.5666040271, 22380.9996177575, 6390.9831914135, 6175.6561435363, 16193.41536001689, 32217.4439985643, 6653.0194834153, 5913.6198515345, 6265.50714535691, 6301.1321895929, 5959.3266158505, 16723.10632511149, 23646.5670963839, 4897.4243911387, 6944.5525942559, 10660.44311755889, 35371.6434484929, 6370.62787201471, 6196.0114629351, 22345.0165586247, 15265.64270181689, 6315.2919732917, 6251.34736165811, 323.74923414091, 10873.74221299689, 109.9625037359, 11823.4054569337, 28774.2817889683, 18099.7594409665, 17576.7903418305, 245707.7099218278, 10557.8379783073, 71430.9394356126, 28760.05469496669, 3854.7898494737, 23440.3815479467, 13088.9729355601, 12564.91104475801, 7548.8871461013, 6286.3551508569, 18625.1265717558, 35050.2440919589, 553.8132203259, 167993.9384537073, 41991.0297503823, 15663.79170522509, 7250.29054491051, 6277.2537518451, 6289.3855831047, 18003.38853270651, 793.0187059509, 10027.65937824569, 647.25465079831, 4597.77991000629, 6279.30891415889, 3166.66025521511, 6226.5164053051, 6340.12292964471, 12303.3115940935, 5864.3952685743, 6702.2440663755, 23536.3607751645, 5760.25461441409, 12139.30969162329, 67589.3312645407, 11079.92776143409, 23227.0824525087, 4804.4530934105, 30349.1275902505, 92747.9329843061, 12299.7884757445, 12171.7696324071, 15.49628866851, 3684.1342325067, 6717.0314053517, 26087.65932409069, 12164.7233957091, 5219.5179490556, 3178.38960805111, 5227.38225558179, 19004.4041319249, 4583.55281600469, 3627.2636600341, 6411.2712005095, 6155.3681344403, 5849.6079295981, 5791.16874004909, 5791.6563750161, 5113.2437810993, 30775.7257811265, 14169.5497447469, 10454.74520408871, 23141.8022004081, 28313.0449871775, 5244.2930566845, 5657.6494751625, 6908.9898597873, 2574.99527684569, 536.5606946119, 6684.9917892321, 5881.6475457177, 16310.73522823709, 16311.2228632041, 46386.7499258277, 60530.2451682583, 96678.14268052569, 12323.17927852529, 21954.4014268815, 4164.5558070965, 33794.7875410121, 43739.0461634493, 3981.73385156551, 27707.29867681129, 7669.21494381111, 3646.59419483791, 82534.6474380951, 800.06494264891, 11609.61872652869, 26.5421372833, 30640.1004561165, 8982.5668518255, 96563.24283557819, 17583.9038888313, 23539.46356884929, 170.4290531357, 735.6326960483, 6680.98103591609, 44033.8837720559, 80181.29364935629, 24279.3508356971, 5490.5447790075, 6490.0204047715, 6076.6189301783, 18208.1061251085, 4480.46004178609, 16097.9237677661, 16097.43613279909, 491.9071099423, 6006.5738956105, 6560.0654393393, 5333.65642353809, 244287.8438247112, 2301.34199842589, 33794.2999060451, 4384.48081456829, 35579.9350570535, 18326.8939493639, 533.45790092711, 16703.3059509825, 5209.2230083171, 38650.4173236825, 12555.3498172024, 5992.3468016089, 6574.2925333409, 69942.1974183125, 12146.9108735911, 39301.8531447125, 46360.9392409949, 8402.0835278533, 44137.1951668575, 22029.9691371861, 31441.92138724031, 9225.29545579949, 71519.54096076029, 7762.1862415393, 3735.48212924251, 40398.4337367495, 4707.9862312257, 28664.0754677489, 11919.3846841515, 316428.47249139857, 27278.7126339243, 83659.5206898825, 12662.3747446841, 16627.12709789369, 12571.9184417737, 7322.34627826531, 664.99986261351, 5641.9544251257, 6425.4982945111, 6141.1410404387, 22594.2987131955, 20894.53186172529, 5540.3296069423, 17782.48825530069, 6006.2846737335, 6560.3546612163, 142861.1474187747, 24499.7634781359, 7026.3097280075, 955.8435590921, 24485.5363841343, 9388.2497268987, 6359.5857387505, 8635.69818627969, 27831.79440179969, 6334.60000533731, 6232.03932961249, 11905.1625906853, 7076.0945559423, 5444.3503797245, 7122.2889552253, 44933.4931736739, 5715.6010297445, 6851.0383052053, 36147.6536947839, 6238.1784478383, 6328.4608871115, 3214.8925631597, 23141.3145654411, 19804.5834740993, 20.11150191529, 84334.66158130829, 60284.16619777939, ], ]; pub const Y1: [[f64; 600]; 3] = [ [ 0.00154550744, 0.00051503383, 0.00001290763, 0.00000702576, 0.00000430422, 0.00000212689, 0.00000212524, 0.00000062308, 0.00000059808, 0.00000059474, 0.00000048914, 0.00000042814, 0.00000046457, 0.00000036653, 0.00000035649, 0.00000035362, 0.00000032151, 0.00000028763, 0.00000028447, 0.00000027537, 0.00000024819, 0.00000020615, 0.00000019621, 0.00000018378, 0.00000016494, 0.00000016756, 0.00000014558, 0.00000014404, 0.00000014052, 0.00000012261, 0.00000012758, 0.00000010086, 0.00000009469, 0.00000010425, 0.00000010425, 0.0000000957, 0.00000009044, 0.00000008544, 0.00000008214, 0.00000006157, 0.00000006271, 0.00000005524, 0.00000007314, 0.00000005157, 0.00000006749, 0.00000004853, 0.00000005304, 0.00000004985, 0.00000004709, 0.00000004601, 0.00000004201, 0.00000005607, 0.00000004257, 0.00000004394, 0.0000000387, 0.00000005154, 0.00000005036, 0.00000005076, 0.00000003593, 0.00000003384, 0.00000003371, 0.00000003536, 0.00000004292, 0.00000003407, 0.00000003152, 0.00000002883, 0.00000002751, 0.00000003323, 0.00000002999, 0.00000002496, 0.00000003358, 0.00000002297, 0.00000002047, 0.00000002778, 0.00000002025, 0.00000002663, 0.00000002009, 0.00000002148, 0.00000001853, 0.00000002478, 0.00000002023, 0.00000001735, 0.00000002417, 0.00000001809, 0.00000001893, 0.00000001708, 0.00000001898, 0.0000000182, 0.00000001541, 0.00000001555, 0.00000001779, 0.00000001448, 0.0000000145, 0.0000000145, 0.00000001822, 0.00000001372, 0.00000001375, 0.000000014, 0.00000001247, 0.00000001231, 0.00000001141, 0.00000001138, 0.00000001047, 0.00000001058, 0.00000001025, 0.00000000973, 0.00000001114, 0.00000000963, 0.00000000941, 0.00000001068, 0.00000000929, 0.00000000899, 0.00000000889, 0.00000000889, 0.00000001018, 0.0000000106, 0.00000001017, 0.00000000797, 0.00000000795, 0.00000000795, 0.000000008, 0.00000000719, 0.00000000698, 0.00000000686, 0.00000000673, 0.00000000902, 0.00000000678, 0.00000000671, 0.00000000744, 0.00000000706, 0.00000000661, 0.00000000633, 0.00000000621, 0.00000000638, 0.00000000625, 0.00000000637, 0.00000000628, 0.00000000653, 0.00000000578, 0.00000000563, 0.0000000061, 0.00000000666, 0.0000000072, 0.0000000062, 0.00000000553, 0.00000000553, 0.00000000523, 0.00000000524, 0.00000000569, 0.00000000514, 0.00000000563, 0.00000000495, 0.00000000481, 0.00000000481, 0.00000000466, 0.0000000044, 0.00000000437, 0.00000000452, 0.00000000499, 0.0000000044, 0.00000000587, 0.00000000388, 0.00000000398, 0.00000000423, 0.0000000053, 0.00000000379, 0.00000000379, 0.00000000377, 0.00000000419, 0.00000000383, 0.00000000383, 0.00000000375, 0.00000000457, 0.00000000457, 0.00000000481, 0.00000000344, 0.00000000453, 0.00000000364, 0.00000000364, 0.00000000327, 0.00000000358, 0.00000000342, 0.00000000342, 0.00000000318, 0.0000000032, 0.00000000354, 0.00000000318, 0.00000000318, 0.00000000304, 0.00000000343, 0.00000000343, 0.00000000359, 0.00000000398, 0.00000000306, 0.000000003, 0.00000000307, 0.00000000297, 0.00000000365, 0.00000000336, 0.00000000295, 0.00000000288, 0.00000000287, 0.00000000378, 0.00000000289, 0.00000000347, 0.00000000321, 0.00000000289, 0.0000000026, 0.00000000268, 0.00000000242, 0.00000000245, 0.00000000234, 0.00000000267, 0.00000000282, 0.00000000279, 0.0000000029, 0.00000000298, 0.0000000027, 0.00000000294, 0.00000000214, 0.00000000207, 0.00000000216, 0.00000000195, 0.00000000199, 0.0000000025, 0.00000000194, 0.00000000203, 0.00000000203, 0.00000000258, 0.00000000189, 0.00000000186, 0.00000000184, 0.0000000018, 0.00000000185, 0.00000000205, 0.00000000187, 0.00000000187, 0.00000000187, 0.00000000235, 0.00000000173, 0.00000000184, 0.0000000023, 0.00000000166, 0.00000000189, 0.00000000166, 0.00000000186, 0.00000000184, 0.00000000184, 0.00000000156, 0.00000000182, 0.00000000175, 0.00000000154, 0.00000000154, 0.00000000164, 0.00000000146, 0.00000000184, 0.00000000191, 0.00000000144, 0.00000000146, 0.00000000142, 0.00000000185, 0.00000000133, 0.00000000131, 0.00000000146, 0.00000000128, 0.00000000128, 0.00000000123, 0.00000000121, 0.00000000123, 0.00000000123, 0.00000000117, 0.0000000012, 0.00000000113, 0.00000000137, 0.00000000113, 0.00000000123, 0.00000000132, 0.00000000113, 0.00000000113, 0.00000000116, 0.0000000012, 0.00000000109, 0.00000000103, 0.00000000103, 0.00000000104, 0.00000000105, 0.00000000109, 0.00000000102, 0.00000000101, 0.00000000114, 0.00000000111, 0.00000000107, 0.00000000099, 0.00000000102, 0.00000000102, 0.0000000012, 0.00000000095, 0.00000000121, 0.000000001, 0.0000000009, 0.000000001, 0.00000000089, 0.00000000087, 0.00000000086, 0.00000000095, 0.00000000084, 0.00000000106, 0.00000000095, 0.00000000082, 0.00000000081, 0.00000000084, 0.00000000084, 0.0000000008, 0.00000000085, 0.00000000084, 0.0000000008, 0.00000000092, 0.00000000077, 0.0000000008, 0.00000000104, 0.00000000093, 0.00000000085, 0.00000000086, 0.00000000075, 0.0000000009, 0.0000000009, 0.00000000082, 0.00000000101, 0.00000000094, 0.00000000083, 0.00000000073, 0.00000000101, 0.00000000074, 0.00000000092, 0.00000000075, 0.00000000085, 0.00000000069, 0.00000000084, 0.00000000069, 0.00000000075, 0.00000000067, 0.00000000076, 0.00000000068, 0.00000000067, 0.00000000073, 0.00000000065, 0.00000000069, 0.00000000087, 0.00000000076, 0.00000000064, 0.00000000078, 0.00000000066, 0.00000000063, 0.00000000063, 0.00000000061, 0.00000000073, 0.00000000057, 0.00000000059, 0.00000000058, 0.0000000006, 0.00000000057, 0.00000000056, 0.00000000056, 0.00000000056, 0.00000000054, 0.00000000055, 0.00000000061, 0.00000000065, 0.00000000072, 0.00000000072, 0.00000000071, 0.00000000061, 0.00000000061, 0.00000000052, 0.00000000054, 0.00000000052, 0.00000000066, 0.0000000005, 0.00000000051, 0.00000000049, 0.00000000053, 0.00000000053, 0.00000000049, 0.00000000049, 0.00000000049, 0.00000000049, 0.0000000005, 0.0000000005, 0.00000000051, 0.00000000058, 0.00000000047, 0.00000000049, 0.00000000049, 0.00000000046, 0.00000000052, 0.00000000047, 0.00000000046, 0.00000000063, 0.00000000048, 0.00000000046, 0.0000000005, 0.00000000054, 0.00000000045, 0.00000000049, 0.00000000049, 0.00000000045, 0.00000000046, 0.00000000048, 0.00000000049, 0.00000000049, 0.00000000044, 0.00000000044, 0.00000000051, 0.00000000042, 0.00000000042, 0.00000000043, 0.00000000043, 0.00000000041, 0.00000000053, 0.00000000042, 0.00000000041, 0.00000000045, 0.0000000004, 0.0000000004, 0.0000000004, 0.00000000045, 0.00000000045, 0.00000000042, 0.0000000004, 0.00000000039, 0.00000000044, 0.00000000038, 0.00000000038, 0.00000000041, 0.00000000038, 0.00000000038, 0.00000000039, 0.00000000046, 0.00000000041, 0.00000000038, 0.00000000038, 0.00000000037, 0.00000000037, 0.00000000037, 0.00000000036, 0.00000000045, 0.00000000049, 0.00000000038, 0.00000000041, 0.00000000036, 0.00000000048, 0.00000000041, 0.00000000038, 0.00000000036, 0.00000000036, 0.00000000036, 0.00000000048, 0.00000000037, 0.00000000047, 0.00000000034, 0.00000000034, 0.00000000034, 0.00000000036, 0.00000000034, 0.00000000037, 0.00000000034, 0.00000000033, 0.00000000035, 0.00000000044, 0.00000000033, 0.00000000033, 0.00000000033, 0.00000000033, 0.00000000034, 0.00000000034, 0.00000000032, 0.00000000036, 0.00000000032, 0.00000000033, 0.00000000033, 0.00000000031, 0.00000000041, 0.00000000037, 0.00000000034, 0.00000000032, 0.00000000032, 0.00000000037, 0.00000000036, 0.00000000035, 0.00000000035, 0.00000000035, 0.0000000003, 0.00000000032, 0.00000000032, 0.00000000029, 0.00000000029, 0.00000000029, 0.0000000003, 0.00000000029, 0.00000000032, 0.00000000028, 0.0000000003, 0.00000000029, 0.0000000003, 0.00000000034, 0.00000000034, 0.00000000038, 0.00000000038, 0.00000000029, 0.00000000033, 0.00000000028, 0.00000000032, 0.0000000003, 0.00000000027, 0.0000000003, 0.00000000028, 0.00000000027, 0.00000000027, 0.00000000027, 0.00000000027, 0.00000000027, 0.00000000027, 0.00000000026, 0.00000000034, 0.00000000027, 0.00000000027, 0.00000000028, 0.00000000026, 0.00000000026, 0.00000000026, 0.00000000029, 0.00000000029, 0.00000000026, 0.00000000028, 0.00000000032, 0.00000000026, 0.00000000025, 0.00000000029, 0.00000000027, 0.00000000024, 0.00000000024, 0.00000000028, 0.00000000024, 0.00000000025, 0.00000000025, 0.00000000029, 0.00000000024, 0.00000000028, 0.00000000024, 0.00000000024, 0.00000000024, 0.00000000025, 0.00000000025, 0.00000000024, 0.00000000028, 0.00000000024, 0.00000000023, 0.0000000003, 0.00000000024, 0.00000000023, 0.00000000022, 0.00000000023, 0.00000000025, 0.00000000023, 0.00000000023, 0.00000000024, 0.00000000024, 0.00000000021, 0.00000000029, 0.00000000021, 0.00000000021, 0.00000000022, 0.00000000022, 0.00000000022, 0.00000000026, 0.0000000002, 0.0000000002, 0.00000000027, 0.0000000002, 0.0000000002, 0.0000000002, 0.00000000025, 0.0000000002, 0.0000000002, 0.00000000022, 0.00000000024, 0.00000000019, 0.0000000002, 0.0000000002, 0.00000000022, 0.00000000022, 0.00000000022, 0.00000000018, 0.00000000018, 0.00000000019, 0.00000000019, 0.00000000019, 0.00000000019, 0.0000000002, 0.0000000002, ], [ 5.35844734917, 4.43183566713, 4.3886202018, 0.18268310766, 4.0229612515, 0.16300557365, 3.34405166686, 5.07432195748, 2.24108323998, 1.26580020213, 3.64253038225, 5.15102931682, 4.72328803502, 0.62556081234, 6.15990909241, 2.90135814576, 3.62597628866, 4.34539356227, 5.8621512753, 3.92840810925, 1.35151106278, 2.14741827387, 1.31571192713, 6.17760240913, 4.64463821908, 2.24858801378, 4.40450472214, 5.39361420229, 6.16986019111, 5.72868820428, 5.06070649359, 1.72162917776, 3.06840825171, 0.81162914438, 2.69531177468, 0.32347467387, 0.43893334417, 4.76970151659, 5.9664039204, 1.78596836636, 3.18396187423, 3.79861381511, 5.20341424492, 3.57885530448, 2.75433387783, 5.33701721257, 0.93005422139, 3.05697984231, 2.39306975468, 4.45296491447, 5.99364092036, 0.98720876729, 2.55370490945, 4.75948183378, 1.1160149034, 4.58850581748, 2.51929382179, 0.73526458069, 3.97650177033, 3.83274545225, 5.00200001284, 5.30432752281, 3.36706453434, 0.8351964065, 0.16276893009, 0.2083834918, 3.67369812017, 3.48959648614, 0.68275608544, 5.09157906387, 5.82350976219, 2.96479731544, 1.96580631113, 6.17391326343, 3.01082711135, 1.00159277919, 4.16311202386, 0.32608511593, 4.41841662668, 1.61013003664, 0.82015419806, 4.49024043092, 3.59693248271, 2.35536809783, 2.65666986732, 5.00361322564, 3.91087003459, 3.4480860716, 5.81316348536, 2.09924495059, 0.23737949225, 1.75844475078, 5.7120136826, 4.07811254364, 0.13446699374, 5.60520656116, 2.34041210234, 3.28144398068, 0.29225580262, 2.53164637932, 1.92161882496, 1.23855949465, 1.31663136695, 2.19001683016, 0.60899466577, 4.95398300734, 4.36978275435, 0.56100772029, 4.21626686326, 5.08632600308, 1.54055499699, 5.79114005938, 5.01192484889, 4.77820137734, 2.66299766067, 5.76865363011, 4.02093017183, 3.7933664392, 0.10742263482, 3.39951828424, 3.18366130818, 2.29666441302, 4.94363251872, 3.79368723538, 3.9910517516, 0.69698416448, 4.84647193821, 6.00179402654, 2.68741072621, 2.51950741945, 2.42216375426, 5.58153853935, 1.74121096386, 2.04188798982, 0.31613419014, 4.59654254753, 3.42448659886, 5.85737456207, 0.62377454326, 3.2496492026, 5.19955844918, 4.87089013467, 5.18811029494, 4.30310535016, 2.71699575652, 0.78994516254, 5.4700777667, 3.97726441461, 4.8389713972, 3.87608366777, 3.78589343112, 2.00987402269, 0.93576028071, 2.57118063835, 2.94306081142, 5.16955709579, 1.61052953646, 3.98330238308, 5.79985868924, 0.57972339309, 0.00678196141, 3.61198235279, 4.20068362004, 5.87838349624, 1.4359316664, 0.45309221604, 3.05384870302, 4.33272540326, 4.05140241721, 4.67353188247, 5.11659434377, 0.91076946484, 2.62120808067, 0.88573283839, 3.46562904756, 4.9990694793, 5.43816135018, 2.82703012884, 0.67991079022, 1.14128906507, 0.15971399837, 5.26072614817, 4.52940007806, 4.8460346641, 1.13215851865, 5.73706716445, 3.75423383039, 6.03589239585, 0.43890915611, 2.14223194635, 1.36470897271, 2.52875634099, 4.83537015899, 1.01793913946, 0.20529153395, 4.86343200722, 2.08300781298, 1.17462915798, 1.15285276926, 2.48770580169, 0.61716195626, 4.90856628789, 5.11185072605, 1.47281714617, 2.29918133719, 0.66708336426, 3.73571084362, 2.61364471837, 5.19927474541, 2.77307042091, 3.88798752568, 2.5031380528, 4.25976324066, 2.93181023342, 4.70853062526, 0.46137131163, 5.65061835836, 0.59449456012, 0.95816279728, 2.50623255971, 3.18045634687, 4.03237077499, 4.44222765867, 2.36156558922, 3.04516390608, 0.79669370564, 0.68276896116, 2.8241719579, 0.91786109532, 3.20457516516, 4.84188314285, 2.638755168, 4.19729049815, 6.25586281827, 0.22424585668, 4.34056279496, 0.48606035843, 3.02088056063, 4.34532332705, 6.09941552473, 3.08285813784, 0.66694562429, 6.03836479949, 1.27307578752, 5.90720968173, 6.04048637618, 4.58711235161, 1.80970242494, 0.77353737613, 5.0435114853, 1.69691915551, 4.10646056877, 5.68366565747, 2.95193833305, 2.48650028218, 4.91752478989, 0.72322692096, 2.19099222002, 0.42084749575, 2.91645242674, 5.29181252606, 4.73063574833, 0.04654287508, 0.32618788162, 4.98427830485, 1.75166251045, 0.73895960068, 5.69434162626, 4.81514598285, 4.97498024339, 2.90632080371, 5.75152020178, 3.90786027747, 2.11120201406, 0.36200887356, 2.85759760823, 4.51334720616, 5.69373873614, 3.6677603282, 0.66749075538, 0.70954573147, 5.21836603318, 4.83071292354, 4.9594133027, 4.01023132524, 5.32684825848, 4.22545370482, 1.02602291037, 5.99270341494, 3.78830179341, 2.09152457722, 0.90140521385, 4.24784832079, 4.09962394648, 5.69050227976, 0.92616350319, 1.12824235931, 4.76575826483, 3.61435033946, 2.11761227033, 5.94744998603, 3.76175372959, 2.7631069945, 4.36870119289, 6.0559745773, 3.1161050048, 3.5720100499, 0.92966555257, 4.72839816349, 2.27692529332, 5.85994160066, 3.93018462558, 5.05950625443, 1.08248438849, 4.61502942146, 2.62622746074, 5.59171891913, 4.13228553675, 6.08197788088, 0.70806546737, 5.00569753414, 1.74569264442, 5.52511956951, 5.57236272383, 5.33797857569, 4.45214765055, 4.91006846138, 1.37756832018, 0.74657649932, 3.74913323692, 4.52746639645, 4.43327916798, 1.25396392931, 0.77959714125, 1.57278335709, 4.52163234616, 5.60384680292, 5.92557534615, 2.18342250812, 0.05753316454, 3.04134731899, 3.2640136421, 2.6918550825, 4.81689271569, 1.35808826471, 1.77865763794, 1.72420196911, 3.52675260029, 5.44623063701, 2.12314868459, 2.74559935849, 4.98895923052, 5.70776457338, 0.57965828598, 2.1561940592, 6.07488391156, 4.37179192959, 2.26511827996, 1.67874293827, 1.94469304669, 2.88994977642, 3.76314176838, 5.62479142768, 0.60886736064, 4.53224684011, 6.11029124003, 4.86430679802, 4.2996552855, 5.48795829629, 4.30216792995, 4.94322519248, 5.98387073766, 3.80625548858, 1.83719780245, 2.78309524301, 0.8773893383, 0.78258344897, 1.22263365304, 2.33500088089, 2.61658441943, 6.07542895582, 3.71469727042, 3.35593265214, 4.47248238697, 5.31764383927, 1.02044068888, 0.93918602686, 4.78759248733, 1.83601012538, 4.03623415117, 5.68903994773, 3.40926939847, 0.09767152059, 1.88054905125, 5.74808775798, 0.52219046486, 4.16717022039, 6.25484174196, 3.28503810088, 3.91775350902, 2.92364175862, 4.75214039499, 3.48807574467, 2.94405201174, 1.43156848803, 0.70883599249, 1.86995211145, 3.53510882628, 2.17177379198, 3.41897587826, 1.44008987426, 2.0668510448, 2.65580143245, 6.18543275273, 5.90805829894, 3.08250524084, 0.28590581328, 3.21615501236, 2.591510747, 5.11995884892, 2.05521298551, 3.70227971577, 4.57473494926, 5.17184328434, 1.71852303243, 6.25985265406, 6.25985265406, 5.89327075469, 4.71493835645, 3.49714273023, 4.44510876745, 1.14212165839, 2.36481926067, 3.38233495451, 4.96796930709, 4.82215691915, 1.74815791619, 0.31322632556, 4.0431578259, 5.8240989512, 4.59409111885, 3.34091252113, 3.64722285417, 0.30900035436, 2.98410187235, 4.7564919846, 4.21088151991, 4.59187061808, 3.91005845267, 6.21139146959, 5.14345155225, 3.90932016585, 4.60880580452, 3.12521745961, 1.96840086543, 1.56811412304, 1.89701220521, 3.60669363968, 3.21269518092, 3.68972702028, 6.10039920596, 3.67007112439, 0.30403746373, 0.40887602826, 1.23154839984, 0.33427002863, 3.87501941695, 1.63582276543, 1.21937301495, 3.59821221655, 2.56047890182, 6.16657680956, 5.44889821497, 2.13261854972, 3.38050467777, 2.81221233882, 1.67423219491, 2.91090812586, 0.13839577785, 5.65380556855, 1.88042187886, 2.52021697492, 5.92836585991, 2.18099177342, 0.90143427409, 1.54173979189, 1.84830381005, 5.02250294215, 3.77934660139, 4.26341483447, 5.54313072444, 1.38932865248, 5.09927453137, 4.69085169487, 4.0599371678, 0.91834451421, 1.66178131503, 2.73190240418, 0.69175314473, 4.73525892997, 0.30767945102, 1.00265951424, 1.45883005475, 4.73151177298, 4.29199382621, 5.49813240003, 3.55143054136, 4.53015131722, 1.64885508302, 2.88700963334, 6.02264922068, 2.75250951602, 6.10434010761, 5.24524976767, 0.75326086687, 3.97691648841, 4.60109278395, 6.13743188286, 4.99580076168, 4.42136306455, 5.36876316169, 4.95719787895, 2.19655051246, 4.45594644643, 0.74968073356, 3.34260766105, 5.37411547339, 1.30232025786, 4.70861603764, 5.0815101886, 4.90026899469, 4.88985723155, 4.96950484222, 3.99925126629, 5.04462761864, 4.1174501489, 1.02839985963, 4.33416022359, 2.65258449905, 5.26265995716, 1.04936648816, 4.8214392781, 5.97769334002, 2.29282659231, 1.21411432675, 0.87325499796, 5.21948189448, 1.09161353868, 3.55960074091, 3.55960074091, 4.28222488832, 5.52194731109, 5.52194731109, 3.49943174674, 6.07681616993, 2.16376008059, 5.33584675127, 2.28483676839, 1.64666673478, 6.07302432574, 2.42662159283, 3.56571153376, 5.52794317615, 2.01489779401, 1.49204312505, 5.81677586075, 5.81677586075, 4.21172313283, 1.74369099855, 3.56347944199, 2.51496251708, 6.09500922463, 3.69512347867, 2.95145769488, 1.83973482412, 2.37799900039, 0.07485283254, 5.38239668902, 0.505513003, 3.29228335956, 5.25656062979, 1.96130235408, 5.53200449549, 1.03604717996, 2.01853988925, 5.92091322542, 1.1470624291, 3.42481272827, 0.08212819079, 2.87392170851, 0.61268580951, 2.89425510955, 0.45956662142, 3.04737429764, 2.71317971903, 0.79376120003, 4.89700264579, 2.72494811319, 5.4203665991, 1.28312164242, ], [ 0.2438174835, 12566.3955174663, 18849.4713674577, 6283.3196674749, 6282.83203250789, 6279.7965491259, 6286.84278582391, 4705.9761250271, 6257.0213476751, 6309.61798727471, 775.7664288075, 1059.6257476727, 7860.6632099227, 5753.6287023803, 5885.1706640667, 6813.0106325695, 6681.46867088311, 25132.5472174491, 6127.8992680407, 6438.7400669091, 5487.0216606585, 7079.61767429131, 5507.7970561509, 11790.8729061423, 11507.0135872771, 7058.8422787989, 6290.4332144757, 6276.2061204741, 796.5418242999, 4693.75913722409, 7.3573644843, 3739.0052475915, 6070.0205720369, 6284.2999885431, 6282.3393464067, 4137.1542509997, 6496.6187629129, 1194.6908277081, 1589.3167127673, 8827.6340873583, 8429.4850839501, 4933.4522578161, 4535.3032544079, 11770.0975106499, 5088.8726572503, 6040.5910635009, 3154.4432674121, 12569.91863581531, 5331.6012612243, 6526.04827144891, 7633.1870771337, 5729.7502646325, 3930.4535137031, 12559.2819704655, 7235.0380737255, 8031.3360805419, 6836.8890703173, 7477.7666776995, 12565.9078824993, 10977.32262218251, 11371.9485072417, 4164.0681721295, 1592.8398311163, 3128.6325825793, 5223.93773728571, 1747.7725955835, 7342.7015976641, 801.5771136403, 8636.18582124671, 2145.92159899169, 155.17658195069, 17260.3984721739, 1990.9888345245, 5481.4987363511, 951.4745887671, 26.0545023163, 4690.7236538421, 537.0483295789, 553.32558535889, 1349.62359217529, 522.8212355773, 529.44714761109, 7085.1405985987, 397.9051859247, 9438.0067523705, 10989.0519750185, 5216.33655531789, 5230.5636493195, 426.8420083595, 13096.0864825609, 12562.8723991173, 5753.14106741329, 6262.96434807611, 6303.6749868737, 10973.7995038335, 7875.91568110771, 7084.6529636317, 12721.8159169005, 2119.00767786191, 18319.7804023631, 1066.7392946735, 2942.7072407751, 5642.93474619389, 242.97242145751, 10447.14402212089, 640.1411037975, 15721.0826023619, 2389.1378379327, 20426.8149099055, 529.9347825781, 10575.6505004253, 16496.6052136859, 6277.7967431675, 6288.8425917823, 12540.0971976665, 5760.7422493811, 6805.89708556871, 14314.4119305333, 6286.6060248927, 6280.0333100571, 12029.5910053709, 9623.9320941747, 6148.2545874395, 5856.7214765989, 12964.5445208745, 13368.2164485901, 6418.38474751031, 6709.91785835091, 12043.8180993725, 16730.70750707931, 14712.5609339415, 4292.5746504339, 13119.9649203087, 4690.23601887509, 13518.1139237169, 5746.5151553795, 4686.6455902233, 3929.96587873609, 5088.3850222833, 10447.6316570879, 6820.1241795703, 3634.37720703489, 13916.2629271251, 31415.6230674405, 6259.44122972711, 6307.1981052227, 14143.7390599141, 12139.7973265903, 12036.7045523717, 4700.87268422489, 11014.8626598513, 13362.6935242827, 6279.4383321169, 6287.2010028329, 10177.5014970171, 1577.5873599313, 11499.9000402763, 12573.5090644671, 12410.9751180321, 24073.1652872599, 6.86972951729, 7860.17557495569, 8274.0646845159, 4694.2467721911, 12592.6938372661, 6180.2268932563, 6386.4124416935, 7872.39256275871, 5327.7199258663, 6247.2918007975, 6319.34753415231, 2352.6223362883, 6077.1341190377, 6489.5052159121, 4292.0870154669, 18451.3223640495, 2787.2868413409, 6245.2919948391, 6321.3473401107, 12323.6669134923, 9917.45305702629, 6262.5442719825, 6304.0950629673, 11926.4982311523, 77714.015285604, 7238.9194090835, 6254.8704800071, 6311.7688549427, 12779.6946129043, 6298.57213865991, 6268.0671962899, 1052.51220067191, 1551.2890401315, 5863.8350235997, 90280.1669855868, 3893.93801205869, 5429.63565075589, 10022.0810975829, 17782.9758902677, 6702.8043113501, 18073.9487561337, 1577.0997249643, 2353.1099712553, 213.5429129215, 5223.4501023187, 17797.2029842693, 220.6564599223, 955.3559241251, 14945.0723560709, 2544.5582373669, 7632.6994421667, 1596.43025976811, 206.42936592071, 13341.9181287903, 4731.7868098599, 5642.4420600927, 17790.08943726851, 12168.2465140581, 2146.4092339587, 8030.8484455749, 213.0552779545, 3185.43584474911, 5884.68302909969, 1748.2602305505, 6924.1972748571, 641.12142486571, 6503.7323099137, 6062.9070250361, 796.0541893329, 11506.52595231009, 18209.5740811437, 12566.4628277691, 853.4401992355, 3495.78900865049, 5849.1202946311, 10213.5293636945, 6290.36590417291, 6276.2734307769, 9779.3524936089, 19651.2922985815, 12566.32820716351, 12567.37583853451, 110.45013870291, 3.76693583251, 433.9555553603, 5863.3473886327, 10983.94853421629, 6037.4880212455, 2648.6986429565, 10969.72144021469, 6529.1513137043, 6453.9925380941, 6112.6467968557, 12353.0964220283, 149.8070146181, 11015.3502948183, 3894.4256470257, 18636.1722720197, 13760.8425276909, 4156.95462512869, 7234.5504387585, 18139.5383188994, 5507.3094211839, 18875.2820522905, 6069.53293706989, 16200.52890701769, 20.5315780089, 17256.8753538249, 6393.5259886943, 6173.1133462555, 18852.9944858067, 9381.2034902007, 65147.37595065419, 16201.0165419847, 6836.40143535029, 12565.4151963981, 17655.0243572331, 10575.1628654583, 10213.0417287275, 17253.2849251731, 10420.23010099111, 633.0275567967, 6295.0490203109, 6271.5903146389, 23013.7833570707, 11790.3852711753, 3340.36860921629, 10970.2090751817, 4803.9654584435, 4171.1817191303, 1582.2031657665, 23543.4743221653, 10973.3118688665, 6549.9267091967, 6016.7126257531, 11514.1271342779, 17267.5120191747, 13625.7774476555, 10976.83498721549, 76.50988875911, 8661.9965060795, 1350.1112271423, 9917.9406919933, 12809.12412144031, 12345.9828750275, 775.2787938405, 11216.5281078075, 12012.8261146239, 5643.4223811609, 11614.6771112157, 6255.9181113781, 6310.7212235717, 6923.2169537889, 5635.8211991931, 10440.03047512009, 3583.5848481573, 10818.3791043993, 6993.2527160332, 13521.9952590749, 5650.0482931947, 4732.2744448269, 22805.4917485101, 12360.2099690291, 5120.35732810009, 6370.62787201471, 6196.0114629351, 18842.3578204569, 3097.64000524229, 10177.01386205009, 18415.7596295809, 949.4194264533, 3104.6862419403, 13517.62628874989, 16858.7263504167, 1059.1381127057, 398.3928208917, 11713.1991357143, 2378.9206560881, 11712.71150074729, 30356.2411372513, 3154.9309023791, 18429.9867235825, 11925.5179100841, 10454.25756912169, 15670.83794192309, 6438.2524319421, 17298.4261448097, 3904.1551939033, 5231.0512842865, 3496.2766436175, 8672.21368792411, 14143.2514249471, 24357.0246061251, 15720.5949673949, 16460.5773470085, 9387.76209193169, 17259.91083720689, 9778.8648586419, 155.6642169177, 34570.3101523361, 149854.6439522914, 12456.1891962469, 17996.2749857057, 11764.5745863425, 4705.4884900601, 13915.77529215809, 28237.4772768729, 7335.5880506633, 6055.8435346859, 6510.7958002639, 12545.6201219739, 6312.74917601091, 6253.8901589389, 5326.5428765373, 2699.49100183409, 8983.0544867925, 14919.2616712381, 5572.8989839496, 16522.4158985187, 35579.9350570535, 6208.5380689076, 6358.1012660422, 21393.7857873411, 5547.4431539431, 7019.19618100671, 12416.8323203317, 12592.2062022991, 26084.2656236997, 23006.6698100699, 15141.14697682849, 24279.3508356971, 6816.53375091851, 5750.1055840313, 19379.1623325523, 16737.33341911309, 24066.0517402591, 104351.8563837803, 8662.48414104651, 26735.7014447297, 12132.6837795895, 24602.8562523545, 7834.3648901229, 161000.92955515758, 29303.9727540629, 10984.4361691833, 45584.9289947039, 5244.2930566845, 23581.0143598341, 19650.8046636145, 29289.7456600613, 6390.9831914135, 6175.6561435363, 17789.60180230149, 24705.9490265731, 15663.79170522509, 16460.08971204149, 553.8132203259, 17370.6047933933, 13119.47728534169, 4164.5558070965, 23020.8969040715, 54247.1693182669, 32243.2546833971, 24336.2492106327, 11769.6098756829, 16723.10632511149, 16723.5939600785, 8827.14645239129, 8402.0835278533, 16062.4283436003, 5856.23384163189, 6297.5467614765, 6269.0925734733, 15508.8589407579, 6394.50630976251, 6172.1330251873, 29826.5501721567, 17297.9385098427, 6309.1303523077, 29089.0552334685, 11933.6117781531, 26482.4146271079, 20452.6255947383, 18073.46112116669, 11499.41240530929, 3340.8562441833, 18216.6876281445, 18202.4605341429, 5216.8241902849, 4060.97539791089, 951.9622237341, 18848.98373249069, 26709.8907598969, 28230.4310401749, 24491.18197509989, 9924.5666040271, 8982.5668518255, 22484.0923919761, 6040.10342853389, 6418.9449924849, 6147.69434246491, 9380.71585523369, 7238.4317741165, 17272.1278250099, 58953.3892607775, 29026.7290469913, 12721.32828193349, 7322.34627826531, 3981.73385156551, 19804.5834740993, 173567.0812551404, 205.9417309537, 23013.29572210369, 49515.1386909235, 38500.5198485557, 17686.9966630499, 5641.9544251257, 21228.63584102931, 34520.5531268643, 8635.69818627969, 5746.0275204125, 21202.3375212295, 7349.81514466491, 16496.11757871889, 33019.2649296881, 21150.56954840009, 29296.8592070621, 27511.2240560537, 11933.12414318609, 11918.89704918449, 29062.7569136687, 12490.1294461907, 6334.60000533731, 6232.03932961249, 419.2408263917, 419.72846135871, 16858.23871544969, 16208.13008898551, 27278.7126339243, 5017.2645538815, 24080.2788342607, 23539.9512038163, 18606.25512851669, 30665.9111409493, 6660.6932753907, 5905.94605955911, 31571.0434668747, 16061.94070863329, 23539.46356884929, 3738.51761262449, 2942.21960580809, 15110.7099373497, 55023.1795645579, 233141.55822184499, 12587.1709129587, 34911.6558935745, 1692.40948698591, 2544.07060239989, 24382.8352909579, 6205.6458970469, 6360.99343790291, 31172.8944634665, 36949.4746259077, 18053.1733606413, 32367.3414736911, 4487.57358878689, 10239.3400485273, 4796.85191144269, 6226.4212925393, 6340.2180424105, 5974.0413448191, 6592.5979901307, 19402.55313533309, 46386.7499258277, 9225.7830907665, 9910.33951002549, 15265.64270181689, 52176.0501006319, 62883.5989569971, 11617.21990849651, 5120.8449630671, 6680.98103591609, 522.3336006103, 6263.64990657511, 6302.9894283747, 23581.5019948011, 29424.8780503995, 16737.8210540801, 22743.16556203289, 22743.6531969999, 25158.8455372489, 21424.2228268199, 21424.7104617869, 14712.07329897449, 5760.25461441409, 31969.1924702829, 17893.1822114871, 8584.9054833843, 23550.5878691661, 6717.0314053517, 7445.7943718827, 5849.6079295981, 14155.4684127501, 6294.36536773881, 6272.273967211, 18208.1061251085, 18208.5937600755, 22779.6810636773, 28628.5800435831, 40879.6843221273, 30221.1760572159, 4379.8828549737, 8186.7564799761, 28760.05469496669, 18422.8731765817, 12036.21691740469, 28313.0449871775, 34513.5068901663, 34115.3578867581, 21548.7185518083, 17654.5367222661, 55798.7021758819, 20597.4877805247, 18875.76968725751, 1588.82907780029, 9411.7084325707, 536.5606946119, 6187.3404402571, 6379.2988946927, 18326.8939493639, 6233.5626420031, 6333.0766929467, 5972.4788686065, 6594.1604663433, 6948.0757126049, 5618.5636223449, 83974.0791732134, 84020.1030979774, 50316.9596220473, 9070.3626913323, ], ]; pub const Y2: [[f64; 248]; 3] = [ [ 0.00052911498, 0.00006074441, 0.00002406871, 0.00000096033, 0.00000029888, 0.00000014021, 0.00000013375, 0.00000008148, 0.00000008195, 0.00000008001, 0.00000007754, 0.00000007223, 0.00000004616, 0.0000000306, 0.00000003717, 0.00000002991, 0.00000003235, 0.00000002393, 0.00000002034, 0.00000002028, 0.00000002064, 0.00000001914, 0.0000000177, 0.00000001761, 0.00000001558, 0.00000001551, 0.00000001436, 0.00000001469, 0.00000001319, 0.0000000118, 0.00000001337, 0.00000001039, 0.00000001313, 0.00000001041, 0.00000001202, 0.00000000904, 0.0000000087, 0.00000001149, 0.00000001069, 0.00000000772, 0.00000000846, 0.00000000742, 0.00000000966, 0.00000000664, 0.00000000662, 0.00000000659, 0.00000000853, 0.00000000823, 0.00000000783, 0.00000000785, 0.00000000694, 0.00000000566, 0.00000000684, 0.00000000499, 0.00000000596, 0.00000000486, 0.00000000483, 0.00000000441, 0.00000000412, 0.00000000561, 0.0000000039, 0.00000000405, 0.00000000501, 0.00000000392, 0.00000000369, 0.00000000483, 0.00000000489, 0.00000000481, 0.00000000448, 0.00000000321, 0.0000000032, 0.00000000361, 0.00000000361, 0.00000000412, 0.00000000304, 0.00000000356, 0.00000000283, 0.00000000362, 0.00000000248, 0.00000000252, 0.00000000257, 0.00000000327, 0.0000000023, 0.00000000289, 0.00000000297, 0.00000000209, 0.00000000207, 0.00000000188, 0.00000000189, 0.00000000194, 0.00000000176, 0.00000000164, 0.00000000205, 0.00000000205, 0.00000000139, 0.00000000155, 0.00000000152, 0.00000000129, 0.00000000127, 0.00000000132, 0.00000000122, 0.00000000163, 0.00000000114, 0.00000000118, 0.00000000148, 0.00000000123, 0.00000000103, 0.00000000138, 0.00000000107, 0.00000000104, 0.00000000096, 0.00000000099, 0.00000000096, 0.00000000084, 0.00000000111, 0.00000000087, 0.00000000078, 0.00000000076, 0.00000000105, 0.00000000073, 0.00000000102, 0.0000000007, 0.00000000071, 0.00000000092, 0.0000000007, 0.00000000091, 0.00000000083, 0.00000000088, 0.00000000074, 0.00000000085, 0.00000000061, 0.0000000006, 0.00000000058, 0.00000000078, 0.00000000059, 0.00000000057, 0.00000000056, 0.00000000065, 0.00000000051, 0.0000000005, 0.0000000005, 0.00000000049, 0.00000000066, 0.00000000049, 0.00000000048, 0.00000000053, 0.00000000058, 0.00000000052, 0.00000000061, 0.00000000044, 0.00000000044, 0.00000000042, 0.00000000059, 0.00000000051, 0.00000000051, 0.00000000046, 0.00000000041, 0.00000000056, 0.00000000051, 0.00000000049, 0.00000000036, 0.00000000044, 0.00000000035, 0.00000000044, 0.00000000046, 0.00000000034, 0.00000000034, 0.00000000035, 0.00000000035, 0.00000000032, 0.00000000034, 0.00000000045, 0.00000000035, 0.00000000031, 0.0000000003, 0.00000000039, 0.00000000041, 0.00000000031, 0.00000000028, 0.00000000028, 0.00000000027, 0.00000000027, 0.00000000025, 0.00000000026, 0.00000000025, 0.0000000003, 0.00000000032, 0.00000000023, 0.00000000026, 0.00000000024, 0.00000000023, 0.00000000021, 0.00000000021, 0.00000000028, 0.00000000022, 0.00000000021, 0.0000000002, 0.0000000002, 0.00000000026, 0.00000000023, 0.00000000026, 0.00000000018, 0.0000000002, 0.00000000019, 0.00000000018, 0.00000000018, 0.00000000022, 0.00000000019, 0.0000000002, 0.00000000024, 0.00000000023, 0.00000000017, 0.00000000016, 0.00000000016, 0.00000000021, 0.0000000002, 0.00000000021, 0.0000000002, 0.00000000014, 0.00000000014, 0.00000000015, 0.00000000019, 0.00000000019, 0.00000000013, 0.00000000017, 0.00000000013, 0.00000000016, 0.00000000012, 0.00000000012, 0.00000000012, 0.00000000015, 0.00000000012, 0.00000000015, 0.00000000011, 0.00000000013, 0.00000000011, 0.00000000011, 0.0000000001, 0.00000000014, 0.0000000001, 0.0000000001, 0.0000000001, 0.0000000001, 0.0000000001, 0.0000000001, 0.00000000009, 0.0000000001, 0.00000000011, ], [ 1.75323722235, 0.48406211192, 2.6600639447, 2.57406136836, 2.30515825272, 1.64042051619, 1.74320372785, 0.62869530307, 2.81874475342, 4.34877296703, 5.43470598991, 3.81034638754, 4.59623594691, 3.26884940633, 0.87961276723, 2.48913608928, 2.53504921673, 1.83696733237, 2.77061597204, 0.70943948464, 0.01448293997, 2.85234479868, 3.48783151064, 1.8082322026, 0.56580595512, 0.55852743151, 1.28164050883, 2.94324921966, 1.89155311923, 1.42090963151, 5.75221416852, 4.25243426113, 0.5989755124, 5.4780137768, 4.02829547071, 0.85768945907, 2.26660468565, 3.02450680654, 1.09203232944, 2.66290097432, 1.36798976406, 5.02007434299, 2.05227643484, 1.21776131888, 3.18968574411, 5.95013449282, 3.65338850674, 1.06126729936, 4.30296275012, 3.46658763633, 3.50785804761, 4.42922662864, 1.11267726523, 1.42594865875, 6.09778115923, 4.54237345712, 4.68204073064, 4.99112466662, 0.87602065813, 5.46330573132, 4.63888431687, 6.26538093406, 1.82149883986, 0.68216396598, 5.93410776393, 6.07777893059, 3.70668603785, 3.17195852109, 5.56847234629, 4.53991511859, 0.43138538654, 2.165991341, 4.79823251497, 4.34259218946, 5.68078111352, 6.00094576166, 0.66912545661, 2.3155421074, 3.18243221495, 2.73244620528, 0.22372520009, 1.45001600721, 1.80447328493, 3.67617510107, 3.17045499445, 4.98580572759, 0.21623312501, 4.07593821324, 5.31784128034, 5.12285857348, 2.51491286893, 1.22070775546, 1.64290799201, 0.68022152849, 3.04789845179, 4.2433318882, 4.81739365185, 0.80954637051, 5.67893828134, 4.8729166436, 3.21278850975, 2.50359725386, 4.13352060999, 0.80775184774, 4.06616105867, 2.18706277371, 1.79915109205, 2.26785827403, 2.76898193474, 0.56758990747, 0.40713285174, 0.70751931715, 6.24621518908, 3.6351698801, 2.39242858566, 4.45435464785, 2.61342989032, 4.1378241187, 1.96765772501, 5.60932378402, 5.37997051996, 0.51266920771, 5.27404987073, 0.39406209616, 4.105296856, 1.53880932897, 2.41910116753, 0.30300511757, 3.53618023271, 4.40773297118, 2.66034748981, 3.95075537336, 3.04970743906, 0.84061745785, 3.10446906052, 3.63209087311, 2.23091315346, 4.959524106, 0.09929724563, 2.602900434, 5.98749446465, 0.70632876133, 3.92505951821, 0.42825389697, 2.19153498916, 2.55294637714, 5.94322042199, 5.99067773035, 4.99956015956, 5.02285128905, 1.96034093811, 2.52906622396, 2.58678833053, 3.81200106179, 5.97812516445, 5.23410298912, 2.5224824135, 4.84268946755, 3.94604483748, 1.6407993527, 1.49154565635, 2.12316916648, 5.18466509768, 3.23094444076, 2.21535532938, 2.24364878116, 4.40970135798, 5.15488505358, 4.51996316476, 5.33774590597, 2.04067717162, 6.20022544523, 1.9566970965, 3.81393239996, 2.82636067861, 5.86021469295, 0.90085517811, 5.47911308336, 2.5089595702, 3.93140481871, 5.61355223, 0.53944014317, 0.15499921281, 0.9798455507, 1.11733310909, 4.41826131323, 5.65959938774, 1.38575591729, 5.61732376806, 3.45407340381, 0.69647593831, 5.43974830479, 0.80058820514, 5.7868943383, 3.26384247748, 4.41664687493, 1.88345295944, 3.87252932348, 0.45595739946, 5.52071600644, 0.60119736394, 0.71176167314, 3.04333652471, 2.09021029647, 3.20715016441, 0.32502884515, 2.17863705978, 4.82590950931, 1.02950628439, 3.14467908991, 3.21288696705, 2.38623798159, 3.59989563011, 2.7717927724, 2.2028692608, 5.1066646464, 5.36525328799, 2.47582665567, 4.85508264889, 6.23679853613, 2.64768344463, 1.24340851761, 2.89835524904, 3.14350306699, 2.96004801328, 3.12347768998, 4.902764942, 1.13909733386, 5.43460350187, 0.82655936469, 0.47799392266, 2.80799572996, 5.28864619208, 0.21391675163, 5.80786469706, 0.30991526634, 0.6752635301, 1.54770241799, 0.36722951229, 4.84303300061, 4.48229440272, 5.89241784221, 4.07842068364, 0.98564127078, 0.62034181586, 6.20390809264, 2.66921279687, 5.10849785178, ], [ 6283.3196674749, 0.2438174835, 12566.3955174663, 18849.4713674577, 6282.83203250789, 6279.7965491259, 6286.84278582391, 6309.61798727471, 6257.0213476751, 6127.8992680407, 6438.7400669091, 83997.09113559539, 710.1768660418, 4705.9761250271, 5507.7970561509, 25132.5472174491, 7058.8422787989, 775.7664288075, 6290.4332144757, 6276.2061204741, 7860.6632099227, 5487.0216606585, 1059.6257476727, 5753.6287023803, 7079.61767429131, 6040.5910635009, 5885.1706640667, 6526.04827144891, 6681.46867088311, 6813.0106325695, 5729.7502646325, 6282.3393464067, 529.9347825781, 6284.2999885431, 6836.8890703173, 5331.6012612243, 4933.4522578161, 167284.005405149, 1577.0997249643, 7235.0380737255, 11790.8729061423, 4137.1542509997, 11856.462468908, 7633.1870771337, 1194.6908277081, 11507.0135872771, 4535.3032544079, 155.17658195069, 5088.8726572503, 2353.1099712553, 801.5771136403, 796.5418242999, 3128.6325825793, 12569.91863581531, 8031.3360805419, 1589.3167127673, 8429.4850839501, 6496.6187629129, 4693.75913722409, 7477.7666776995, 6070.0205720369, 3739.0052475915, 1592.8398311163, 26.0545023163, 553.32558535889, 12036.7045523717, 5223.4501023187, 10213.5293636945, 156137.71980228278, 951.4745887671, 1990.9888345245, 12565.9078824993, 12721.8159169005, 398.3928208917, 4690.7236538421, 5481.4987363511, 242.97242145751, 9438.0067523705, 8827.6340873583, 3154.4432674121, 11371.9485072417, 14143.7390599141, 1747.7725955835, 7085.1405985987, 1349.62359217529, 11770.0975106499, 4164.0681721295, 7875.91568110771, 2389.1378379327, 10977.32262218251, 7342.7015976641, 5223.93773728571, 10973.7995038335, 13368.2164485901, 10575.6505004253, 12410.9751180321, 3930.4535137031, 397.9051859247, 12592.6938372661, 8636.18582124671, 13119.9649203087, 5507.3094211839, 17260.3984721739, 4292.5746504339, 17790.08943726851, 12562.8723991173, 13518.1139237169, 12168.2465140581, 10989.0519750185, 2145.92159899169, 6283.25235717211, 13096.0864825609, 6283.3869777777, 16730.70750707931, 12540.0971976665, 10177.5014970171, 12323.6669134923, 6709.91785835091, 5642.4420600927, 5856.7214765989, 250570.9196747026, 5753.14106741329, 14314.4119305333, 13916.2629271251, 7084.6529636317, 6924.1972748571, 31415.6230674405, 71430.45180064559, 529.44714761109, 95143.3767384616, 8274.0646845159, 16496.6052136859, 5642.93474619389, 213.5429129215, 640.1411037975, 4690.23601887509, 13341.9181287903, 4731.7868098599, 3893.93801205869, 12573.5090644671, 3634.37720703489, 18319.7804023631, 2787.2868413409, 13362.6935242827, 12964.5445208745, 14919.2616712381, 1577.5873599313, 15721.0826023619, 4292.0870154669, 24073.1652872599, 10447.14402212089, 20426.8149099055, 84672.2320270212, 6370.62787201471, 6196.0114629351, 2119.00767786191, 3185.43584474911, 10976.83498721549, 9437.5191174035, 239424.6340718364, 3495.78900865049, 18139.5383188994, 3929.96587873609, 8661.9965060795, 3894.4256470257, 6262.5442719825, 6304.0950629673, 18875.2820522905, 10420.23010099111, 23013.7833570707, 7.3573644843, 3340.8562441833, 10213.0417287275, 14712.5609339415, 12809.12412144031, 9779.3524936089, 82576.73740351178, 22779.6810636773, 2942.7072407751, 5429.63565075589, 11014.8626598513, 9623.9320941747, 18209.5740811437, 9381.2034902007, 3583.5848481573, 10447.6316570879, 796.0541893329, 9917.45305702629, 12012.8261146239, 14143.2514249471, 26709.8907598969, 7632.6994421667, 17256.8753538249, 12353.0964220283, 77714.015285604, 6993.2527160332, 6836.40143535029, 1748.2602305505, 9225.7830907665, 149854.6439522914, 2544.07060239989, 11614.6771112157, 426.8420083595, 30640.1004561165, 155.6642169177, 11926.4982311523, 17298.4261448097, 18073.46112116669, 19651.2922985815, 5856.23384163189, 72850.8055327292, 8983.0544867925, 16460.5773470085, 17259.91083720689, 16858.7263504167, 23543.4743221653, 13367.7288136231, 2146.4092339587, 22484.0923919761, 16200.52890701769, 20199.3387771165, 8672.21368792411, 18073.9487561337, 16201.0165419847, 7860.17557495569, 18451.3223640495, 5572.8989839496, 17996.2749857057, 19403.0407703001, 14945.0723560709, 12559.2819704655, 10818.3791043993, 12567.37583853451, 28767.1682419675, 90280.1669855868, 22805.4917485101, 35372.1310834599, 11506.52595231009, 21228.63584102931, 12779.6946129043, 23141.8022004081, 1350.1112271423, 10575.1628654583, 22345.5041935917, 9778.8648586419, 29826.5501721567, 23581.5019948011, 25158.8455372489, ], ]; pub const Y3: [[f64; 46]; 3] = [ [ 0.0000023279, 0.00000076843, 0.00000035331, 0.00000005282, 0.00000001631, 0.00000001483, 0.00000001479, 0.00000000652, 0.00000000656, 0.00000000317, 0.00000000318, 0.00000000227, 0.00000000201, 0.00000000201, 0.00000000036, 0.00000000034, 0.00000000033, 0.00000000032, 0.00000000032, 0.00000000026, 0.00000000023, 0.00000000025, 0.00000000027, 0.0000000002, 0.00000000019, 0.00000000019, 0.00000000018, 0.00000000017, 0.00000000013, 0.00000000011, 0.0000000001, 0.0000000001, 0.00000000009, 0.00000000011, 0.00000000009, 0.00000000008, 0.00000000008, 0.00000000008, 0.00000000007, 0.00000000007, 0.00000000005, 0.00000000005, 0.00000000006, 0.00000000006, 0.00000000005, 0.00000000005, ], [ 1.83555296287, 0.95359770708, 1.77537067174, 0.8341018591, 0.72620862558, 0.65599216587, 2.83072127404, 3.13796451313, 0.01615422945, 1.4315769584, 2.05944515679, 0.70881980797, 5.52615570373, 4.2356326783, 6.05003898151, 0.36912822345, 2.65665718326, 3.81269087187, 2.841331865, 5.21573736647, 0.44696909593, 0.0132635736, 0.46730161827, 2.19213288615, 1.44435756454, 4.47976718197, 0.72211012099, 5.20474716177, 2.92478174105, 3.72062261949, 2.89167021825, 1.46762801985, 6.21784065295, 4.68801103302, 3.82179163254, 5.97770881958, 0.68313431813, 1.45990791265, 4.15465801739, 0.35078036011, 3.29483739022, 4.64160679165, 2.38483297622, 4.26851560652, 1.89668032657, 2.01213704309, ], [ 0.2438174835, 12566.3955174663, 6283.3196674749, 18849.4713674577, 6282.83203250789, 6438.7400669091, 6127.8992680407, 6279.7965491259, 6286.84278582391, 6526.04827144891, 6040.5910635009, 25132.5472174491, 6836.8890703173, 5729.7502646325, 12569.91863581531, 4705.9761250271, 12410.9751180321, 6257.0213476751, 6309.61798727471, 775.7664288075, 1059.6257476727, 7860.6632099227, 12565.9078824993, 5753.6287023803, 5885.1706640667, 6813.0106325695, 12721.8159169005, 6681.46867088311, 5487.0216606585, 7079.61767429131, 5507.7970561509, 11790.8729061423, 11507.0135872771, 12592.6938372661, 7058.8422787989, 6290.4332144757, 6276.2061204741, 796.5418242999, 4693.75913722409, 7.3573644843, 3739.0052475915, 6070.0205720369, 6284.2999885431, 6282.3393464067, 4137.1542509997, 6496.6187629129, ], ]; pub const Y4: [[f64; 20]; 3] = [ [ 0.00000114918, 0.00000006817, 0.00000003158, 0.00000000211, 0.0000000021, 0.00000000253, 0.00000000073, 0.00000000042, 0.00000000023, 0.00000000022, 0.00000000012, 0.00000000009, 0.00000000009, 0.00000000008, 0.00000000005, 0.00000000005, 0.00000000005, 0.00000000005, 0.00000000004, 0.00000000003, ], [ 4.77291921544, 2.90545031303, 5.19149443854, 2.15272014034, 1.31410288968, 5.35904773722, 5.49456429263, 3.03243163257, 4.47433896564, 4.47061131203, 5.22878976906, 2.63928422881, 3.62312855703, 4.59507616558, 4.40834364231, 2.21798830782, 1.11835906029, 3.99770824807, 4.97197978751, 3.60141861387, ], [ 6283.3196674749, 0.2438174835, 12566.3955174663, 6438.7400669091, 6127.8992680407, 18849.4713674577, 6282.83203250789, 710.1768660418, 6279.7965491259, 6286.84278582391, 25132.5472174491, 83997.09113559539, 11856.462468908, 167284.005405149, 6257.0213476751, 6309.61798727471, 12410.9751180321, 156137.71980228278, 12565.9078824993, 529.9347825781, ], ]; pub const Y5: [[f64; 7]; 3] = [ [ 0.00000000877, 0.00000000305, 0.00000000101, 0.00000000025, 0.00000000025, 0.0000000001, 0.00000000003, ], [ 4.87375194107, 4.05893642248, 3.3099706647, 3.73514325706, 5.99118011879, 3.54319653898, 4.13285368647, ], [ 6283.3196674749, 0.2438174835, 12566.3955174663, 6438.7400669091, 6127.8992680407, 18849.4713674577, 6282.83203250789, ], ]; pub const Z0: [[f64; 178]; 3] = [ [ 0.0000027962, 0.00000101625, 0.00000080461, 0.00000043855, 0.00000031853, 0.00000022724, 0.00000016395, 0.0000001815, 0.00000014477, 0.00000014325, 0.00000011204, 0.00000010896, 0.00000009716, 0.00000010363, 0.00000008792, 0.00000008337, 0.00000006921, 0.00000009145, 0.00000007205, 0.00000007698, 0.00000005186, 0.00000005027, 0.00000004529, 0.00000004754, 0.00000004292, 0.00000003855, 0.00000005256, 0.00000004025, 0.00000004061, 0.00000003798, 0.00000002933, 0.00000003424, 0.0000000367, 0.00000002912, 0.00000002506, 0.0000000268, 0.0000000212, 0.00000002235, 0.00000001819, 0.0000000223, 0.00000001945, 0.00000001529, 0.00000001581, 0.00000001424, 0.00000001405, 0.00000001588, 0.00000001478, 0.00000001693, 0.00000001123, 0.0000000099, 0.00000000923, 0.00000000863, 0.00000000984, 0.00000001086, 0.00000000824, 0.00000000829, 0.00000000908, 0.00000000742, 0.0000000085, 0.00000000762, 0.00000000711, 0.00000000766, 0.00000000708, 0.0000000081, 0.00000000751, 0.00000000589, 0.00000000513, 0.0000000055, 0.00000000592, 0.00000000519, 0.00000000515, 0.00000000503, 0.00000000476, 0.00000000463, 0.00000000411, 0.00000000504, 0.00000000552, 0.00000000394, 0.00000000476, 0.00000000503, 0.00000000417, 0.00000000363, 0.00000000363, 0.00000000353, 0.00000000381, 0.0000000042, 0.00000000335, 0.00000000387, 0.00000000349, 0.00000000418, 0.00000000396, 0.00000000322, 0.00000000323, 0.00000000372, 0.00000000305, 0.00000000265, 0.0000000025, 0.00000000266, 0.00000000262, 0.00000000263, 0.00000000302, 0.00000000316, 0.00000000226, 0.00000000216, 0.00000000276, 0.0000000023, 0.000000002, 0.00000000277, 0.00000000199, 0.00000000206, 0.0000000021, 0.00000000181, 0.00000000249, 0.00000000167, 0.00000000183, 0.00000000225, 0.00000000192, 0.00000000188, 0.0000000016, 0.00000000192, 0.00000000159, 0.00000000214, 0.00000000184, 0.0000000016, 0.00000000144, 0.00000000126, 0.00000000149, 0.00000000127, 0.00000000118, 0.00000000123, 0.00000000113, 0.0000000013, 0.0000000011, 0.00000000147, 0.00000000113, 0.00000000108, 0.00000000148, 0.00000000121, 0.00000000119, 0.00000000124, 0.00000000117, 0.00000000127, 0.0000000012, 0.0000000012, 0.00000000127, 0.00000000113, 0.00000000097, 0.00000000123, 0.00000000099, 0.00000000087, 0.00000000122, 0.00000000102, 0.00000000084, 0.00000000103, 0.00000000081, 0.00000000092, 0.00000000094, 0.00000000076, 0.000000001, 0.00000000078, 0.00000000086, 0.00000000093, 0.00000000076, 0.00000000081, 0.000000001, 0.00000000072, 0.00000000082, 0.00000000082, 0.00000000096, 0.00000000075, 0.00000000075, 0.00000000087, 0.0000000008, 0.00000000079, 0.00000000054, 0.00000000056, 0.00000000055, 0.00000000054, ], [ 3.19870156017, 5.42248110597, 3.88027157914, 3.70430347723, 3.99997840986, 3.9847383156, 3.56456162523, 4.98479613321, 3.70258423465, 3.41020246931, 4.83021499098, 2.08023708321, 3.47560205064, 4.05663928093, 4.4489072928, 4.99167706048, 4.32559054073, 1.14182646613, 3.62441599378, 5.55425745881, 6.25384533126, 2.49727910749, 2.33827747356, 0.71100829534, 1.10034019036, 1.8233147776, 4.42445744523, 5.11990285618, 6.02923989849, 0.44370219832, 5.12428135363, 5.420651917, 4.58210192227, 1.92688087702, 0.60484952637, 1.39497359287, 4.30691000285, 0.81363184041, 3.75748003107, 2.76407822446, 5.69949789177, 1.98639348122, 3.19976230948, 6.26116472313, 4.69394873481, 0.25704624784, 2.81808207569, 4.95689385293, 2.38605285936, 4.29600699156, 3.07195736431, 0.55119493097, 5.96784225392, PI, 1.50050055147, 3.51336978167, 0.12102885474, 1.99159139281, 4.24120016095, 2.90028034892, 1.38596151724, 0.61397570576, 1.91406542362, 5.13961498599, 1.67479850166, 2.02193316047, 2.60734651128, 1.61119298963, 4.59481504319, 5.72925039114, 4.09976487552, 5.66433137112, 3.69640472448, 1.24987240483, 0.10769444525, 3.2620766916, 1.02926440457, 5.81496021156, 3.52810472421, 4.85802444134, 0.81920713533, 5.70015720452, 1.28376436579, 4.7005913311, 2.61890749829, 0.97821135132, 6.2205796732, 3.09145061418, 2.94840720073, 3.75759994446, 1.22507712354, 1.21162178805, 5.50254808471, 1.72256107938, 0.80429352049, 6.10358507671, 4.56452895547, 2.62926282354, 1.34297269105, 6.22089501237, 2.81139045072, 1.62662805006, 2.42346415873, 3.68721275185, 2.33399767923, 0.36165162947, 5.86073159059, 4.65400292395, 5.05186622555, 3.70556027982, 4.50691909144, 6.00294783127, 0.12900984422, 6.27348370813, 3.19836584401, 3.18339652605, 0.87192032514, 2.22746128596, 5.20207795189, 3.89678943865, 5.32590846475, 4.08171403539, 3.75465072369, 4.5389752997, 5.19486374726, 1.69446958184, 1.55306832217, 5.31068233515, 2.73268114062, 2.55361087146, 6.07178776726, 3.94161517411, 3.51203379263, 4.63371971408, 1.20711498905, 3.76359880753, 0.65447253687, 3.13748782783, 5.92110458985, 2.9363842184, 3.6506527164, 4.74596574209, 1.04211499785, 5.60638811846, 2.70766997307, 5.39691616452, 1.07908724794, 5.15992792934, 4.45774681732, 3.9363781295, 2.2395606868, 3.97386522171, 4.21241958885, 4.63519841733, 4.0165524043, 3.24182657569, 4.338739728, 2.8389755442, 6.07733097102, 0.72462427283, 5.2602963825, 4.31900620254, 6.22743405935, 2.16420552322, 1.38002787119, 1.55820597747, 4.95202664555, 1.69647647075, 6.16038106485, 2.29836095644, 2.66367876557, 0.26630214764, 5.00001604436, 0.01398391548, 5.59738773448, 2.60133794851, 5.81483150022, 3.38482031504, ], [ 84334.66158130829, 5507.5532386674, 5223.6939198022, 2352.8661537718, 1577.3435424478, 1047.7473117547, 5856.4776591154, 6283.0758499914, 9437.762934887, 10213.285546211, 14143.4952424306, 6812.766815086, 4694.0029547076, 71092.88135493269, 5753.3848848968, 7084.8967811152, 6275.9623029906, 6620.8901131878, 529.6909650946, 167621.5758508619, 18073.7049386502, 4705.7323075436, 6309.3741697912, 5884.9268465832, 6681.2248533996, 5486.777843175, 7860.4193924392, 13367.9726311066, 3930.2096962196, 3154.6870848956, 1059.3819301892, 6069.7767545534, 12194.0329146209, 10977.078804699, 6496.3749454294, 22003.9146348698, 5643.1785636774, 8635.9420037632, 3340.6124266998, 12036.4607348882, 11790.6290886588, 398.1490034082, 5088.6288397668, 2544.3144198834, 7058.5984613154, 17298.1823273262, 25934.1243310894, 156475.2902479957, 3738.761430108, 9225.539273283, 4164.311989613, 8429.2412664666, 7079.3738568078, 0.0, 10447.3878396044, 11506.7697697936, 11015.1064773348, 26087.9031415742, 29864.334027309, 4732.0306273434, 2146.1654164752, 796.2980068164, 8031.0922630584, 2942.4634232916, 21228.3920235458, 775.522611324, 12566.1516999828, 801.8209311238, 4690.4798363586, 8827.3902698748, 64809.80550494129, 33794.5437235286, 213.299095438, 15720.8387848784, 3128.3887650958, 7632.9432596502, 239762.20451754928, 426.598190876, 16496.3613962024, 6290.1893969922, 5216.5803728014, 1589.0728952838, 6206.8097787158, 7234.794256242, 7342.4577801806, 4136.9104335162, 12168.0026965746, 25158.6017197654, 9623.6882766912, 5230.807466803, 6438.4962494256, 8662.240323563, 1194.4470102246, 14945.3161735544, 37724.7534197482, 6836.6452528338, 7477.522860216, 7238.6755916, 11769.8536931664, 6133.5126528568, 1748.016413067, 250908.4901204155, 11371.7046897582, 5849.3641121146, 19651.048481098, 5863.5912061162, 4535.0594369244, 82239.1669577989, 5429.8794682394, 10973.55568635, 29088.811415985, 4292.3308329504, 154379.7956244863, 10988.808157535, 16730.4636895958, 18875.525869774, 77375.95720492408, 41654.9631159678, 5481.2549188676, 17789.845619785, 7.1135470008, 337.8142631964, 23581.2581773176, 18477.1087646123, 20426.571092422, 15110.4661198662, 10021.8372800994, 639.897286314, 18849.2275499742, 12592.4500197826, 6709.6740408674, 7330.8231617461, 18052.9295431578, 22805.7355659936, 14919.0178537546, 14314.1681130498, 95480.9471841745, 14712.317116458, 33019.0211122046, 32217.2001810808, 45585.1728121874, 49515.382508407, 6915.8595893046, 5650.2921106782, 12352.8526045448, 5235.3285382367, 9917.6968745098, 27511.4678735372, 4933.2084403326, 17654.7805397496, 83997.09113559539, 10818.1352869158, 22779.4372461938, 1349.8674096588, 1592.5960136328, 78051.5857313169, 36147.4098773004, 17260.1546546904, 26735.9452622132, 12779.4507954208, 28313.288804661, 44809.6502008634, 13521.7514415914, 13095.8426650774, 28286.9904848612, 6256.7775301916, 10575.4066829418, 1990.745017041, 24356.7807886416, 3634.6210245184, 16200.7727245012, 31441.6775697568, 150192.2143980043, 90617.7374312997, 161338.5000008705, 73188.3759784421, 143233.51002162008, 323049.11878710287, ], ]; pub const Z1: [[f64; 97]; 3] = [ [ 0.00000009031, 0.00000006179, 0.00000003793, 0.0000000284, 0.00000001817, 0.00000001499, 0.00000001463, 0.00000001302, 0.00000001239, 0.00000001029, 0.00000000975, 0.00000000851, 0.00000000581, 0.00000000515, 0.00000000473, 0.00000000449, 0.0000000036, 0.00000000372, 0.0000000026, 0.00000000322, 0.00000000232, 0.00000000217, 0.00000000232, 0.00000000204, 0.00000000189, 0.00000000179, 0.00000000222, 0.00000000213, 0.00000000157, 0.00000000154, 0.00000000137, 0.00000000179, 0.00000000121, 0.00000000125, 0.0000000015, 0.00000000149, 0.00000000118, 0.00000000161, 0.00000000115, 0.00000000118, 0.00000000128, 0.00000000109, 0.00000000099, 0.00000000122, 0.00000000103, 0.00000000083, 0.00000000097, 0.00000000073, 0.00000000083, 0.00000000072, 0.00000000071, 0.00000000074, 0.00000000063, 0.00000000047, 0.00000000061, 0.00000000047, 0.00000000049, 0.00000000057, 0.00000000049, 0.00000000041, 0.00000000041, 0.00000000045, 0.00000000045, 0.0000000005, 0.00000000046, 0.00000000036, 0.00000000036, 0.00000000036, 0.00000000032, 0.00000000032, 0.00000000041, 0.00000000037, 0.00000000031, 0.00000000028, 0.0000000003, 0.00000000028, 0.00000000026, 0.00000000031, 0.00000000026, 0.00000000023, 0.00000000025, 0.00000000028, 0.00000000028, 0.00000000028, 0.00000000025, 0.00000000022, 0.00000000026, 0.0000000002, 0.00000000021, 0.00000000021, 0.00000000022, 0.0000000002, 0.0000000002, 0.0000000002, 0.0000000002, 0.00000000018, 0.00000000019, ], [ 3.89751156799, 1.73051337995, 5.24575814515, 2.47694599818, 0.41874743765, 1.83320979291, 5.68891324948, 2.18800611215, 4.95327097854, 0.09367831611, 0.0883325688, 1.79547916132, 2.26949174067, 5.64196681593, 6.22750969242, 1.52767374606, 3.62344325932, 3.2247072132, 1.87645933242, 0.94084045832, 0.27531852596, 6.03652873142, 2.93325646109, 3.86264841382, 2.88937704419, 4.90537280911, 3.98495366315, 1.57516933652, 1.08259734788, 5.99434678412, 2.67760436027, 2.05905949693, 5.90212574947, 2.24111392416, 2.00175038718, 5.06157254516, 5.39979058038, 3.32421999691, 5.92406672373, 4.40207874911, 4.35489873365, 2.52157834166, 2.70727488041, 0.0, 0.93782340879, 4.12473540351, 5.50959692365, 1.73905345744, 5.69169692653, 0.21891639822, 2.86755026812, 2.20184828895, 4.45586625948, 2.04946724464, 0.63918772258, 3.325438433, 1.60680905005, 0.11215813438, 3.0283220405, 5.5532939489, 5.91861144924, 2.00068583743, 4.95273290181, 3.62740835096, 1.65798680284, 5.61836577943, 6.24373396652, 0.40465162918, 6.09025731476, 6.03707103538, 4.86809570283, 1.04055368426, 3.6264114503, 4.38359423735, 2.03616887071, 6.03334294232, 3.88971333608, 1.44666331503, 6.26376705837, 4.4438898555, 4.13395006026, 1.53862289477, 1.96831814872, 5.78094918529, 0.62040343662, 6.02390113954, 2.48165809843, 3.85655029499, 5.83006047147, 0.69628570421, 5.02222806555, 3.4761126529, 0.90769829044, 0.03081589303, 3.74220084927, 1.58348238359, 0.85407021371, ], [ 5507.5532386674, 5223.6939198022, 2352.8661537718, 1577.3435424478, 6283.0758499914, 5856.4776591154, 5753.3848848968, 9437.762934887, 10213.285546211, 7860.4193924392, 14143.4952424306, 3930.2096962196, 5884.9268465832, 529.6909650946, 6309.3741697912, 18073.7049386502, 13367.9726311066, 6275.9623029906, 11790.6290886588, 6069.7767545534, 7058.5984613154, 10977.078804699, 22003.9146348698, 6496.3749454294, 15720.8387848784, 12036.4607348882, 6812.766815086, 4694.0029547076, 5643.1785636774, 5486.777843175, 6290.1893969922, 7084.8967811152, 9225.539273283, 1059.3819301892, 5230.807466803, 17298.1823273262, 3340.6124266998, 6283.3196674749, 4705.7323075436, 19651.048481098, 25934.1243310894, 6438.4962494256, 5216.5803728014, 0.0, 8827.3902698748, 8635.9420037632, 29864.334027309, 11506.7697697936, 775.522611324, 21228.3920235458, 6681.2248533996, 37724.7534197482, 7079.3738568078, 3128.3887650958, 33794.5437235286, 26087.9031415742, 6702.5604938666, 29088.811415985, 20426.571092422, 11015.1064773348, 23581.2581773176, 426.598190876, 5863.5912061162, 41654.9631159678, 25158.6017197654, 12566.1516999828, 6283.14316029419, 6283.0085396886, 64809.80550494129, 2942.4634232916, 1592.5960136328, 213.299095438, 13095.8426650774, 7632.9432596502, 12139.5535091068, 17789.845619785, 5331.3574437408, 16730.4636895958, 23543.23050468179, 18849.2275499742, 3154.6870848956, 6279.4854213396, 6286.6662786432, 15110.4661198662, 10988.808157535, 16496.3613962024, 5729.506447149, 9623.6882766912, 7234.794256242, 398.1490034082, 6127.6554505572, 6148.010769956, 5481.2549188676, 6418.1409300268, 1589.0728952838, 2118.7638603784, 14712.317116458, ], ]; pub const Z2: [[f64; 47]; 3] = [ [ 0.00000001662, 0.00000000492, 0.00000000344, 0.00000000258, 0.00000000131, 0.00000000086, 0.0000000009, 0.0000000009, 0.00000000089, 0.00000000075, 0.00000000052, 0.00000000057, 0.00000000051, 0.00000000051, 0.00000000034, 0.00000000038, 0.00000000046, 0.00000000021, 0.00000000018, 0.00000000019, 0.00000000017, 0.00000000018, 0.00000000017, 0.00000000017, 0.00000000018, 0.00000000022, 0.00000000017, 0.00000000015, 0.00000000018, 0.00000000017, 0.00000000013, 0.00000000012, 0.00000000013, 0.00000000012, 0.00000000015, 0.00000000014, 0.00000000011, 0.00000000011, 0.00000000014, 0.00000000011, 0.0000000001, 0.00000000014, 0.0000000001, 0.00000000011, 0.0000000001, 0.00000000013, 0.00000000009, ], [ 1.62703209173, 2.41382223971, 2.24353004539, 6.00906896311, 0.9544734524, 1.69139956945, 0.97606804452, 0.37899871725, 6.25807507963, 0.84213523741, 1.70501566089, 6.15295833679, 1.2761601674, 5.37229738682, 1.73672994279, 2.77761031485, 3.38617099014, 1.95248349228, 3.33419222028, 4.32945160287, 0.66191210656, 3.74885333072, 4.23058370776, 1.78116162721, 6.14348240716, 1.34376831204, 2.79601092529, 1.17032155085, 2.85221514199, 0.21780913672, 1.21201504386, 5.13714452592, 3.79842135217, 4.89407978213, 6.05682328852, 4.81029291856, 0.61684523405, 5.328765385, 5.27227350286, 2.39292099451, 4.4529653271, 4.66400985037, 3.22472385926, 3.80913404437, 5.15032130575, 0.98720797401, 5.94191743597, ], [ 84334.66158130829, 1047.7473117547, 5507.5532386674, 5223.6939198022, 6283.0758499914, 7860.4193924392, 1577.3435424478, 2352.8661537718, 10213.285546211, 167621.5758508619, 14143.4952424306, 12194.0329146209, 5753.3848848968, 6812.766815086, 7058.5984613154, 10988.808157535, 156475.2902479957, 8827.3902698748, 8429.2412664666, 17789.845619785, 6283.0085396886, 11769.8536931664, 10977.078804699, 5486.777843175, 11790.6290886588, 12036.4607348882, 796.2980068164, 213.299095438, 5088.6288397668, 6283.14316029419, 25132.3033999656, 7079.3738568078, 4933.2084403326, 3738.761430108, 398.1490034082, 4694.0029547076, 3128.3887650958, 6040.3472460174, 4535.0594369244, 5331.3574437408, 6525.8044539654, 8031.0922630584, 9437.762934887, 801.8209311238, 11371.7046897582, 5729.506447149, 7632.9432596502, ], ]; pub const Z3: [[f64; 11]; 3] = [ [ 0.00000000011, 0.00000000009, 0.00000000008, 0.00000000008, 0.00000000007, 0.00000000007, 0.00000000008, 0.00000000008, 0.00000000006, 0.00000000006, 0.00000000007, ], [ 0.23877262399, 1.16069982609, 1.65357552925, 2.86720038197, 3.04818741666, 2.59437103785, 4.02863090524, 2.42003508927, 0.84181087594, 5.40160929468, 2.73399865247, ], [ 7860.4193924392, 5507.5532386674, 5884.9268465832, 7058.5984613154, 5486.777843175, 529.6909650946, 6256.7775301916, 5753.3848848968, 6275.9623029906, 1577.3435424478, 6309.3741697912, ], ];
23.59893
34
0.536003
e615b14110443f3210370e983575dbe433f8840f
24,209
//! This file contains objects for encoding/decoding data stored in ZooKeeper nodes (znodes). //! core/src/main/scala/kafka/zk/ZkData.scala use crate::common::feature::features::FeaturesError; use crate::common::feature::features::{Features, VersionRangeType}; use crate::server::dynamic_config_manager::ConfigType; use rafka_derive::{SubZNodeHandle, ZNodeHandle}; use serde_json::json; use std::collections::HashMap; use std::convert::TryFrom; use tracing::{debug, error, trace, warn}; use zookeeper_async::Acl; // NOTE: Maybe all of this could be moved into a hashmap or something? /// `ZNode` contains a known path or parent path of a node that could be stored in ZK #[derive(Debug, ZNodeHandle)] pub struct ZNode { path: String, } #[derive(thiserror::Error, Debug)] pub enum ZNodeDecodeError { #[error("Serde {0:?}")] Serde(#[from] serde_json::Error), #[error("TryFromInt {0:?}")] TryFromInt(#[from] std::num::TryFromIntError), #[error("KeyNotFound {0} in {1}")] KeyNotFound(String, String), #[error("Unsupported version: {0} of feature information: {1:?})")] UnsupportedVersion(i32, String), #[error("Unable to transform data to String: {0}")] Utf8Error(std::string::FromUtf8Error), #[error("Features {0:?}")] Features(#[from] FeaturesError), #[error("MalformedStatus {0} found in feature information")] MalformedStatus(i32, String), } impl Default for ZNode { fn default() -> Self { Self { path: String::from("unset") } } } pub trait ZNodeHandle { fn path(&self) -> &str; // fn decode(input: &str) -> Self; // fn encode(self) -> String; } /// `ZkData` contains a set of known paths in zookeeper #[derive(Debug)] pub struct ZkData { /// old consumer path znode consumer_path: ConsumerPathZNode, config: ConfigZNode, pub config_types: ConfigType, topics: TopicsZNode, broker_ids: BrokerIdsZNode, delegation_token_auth: DelegationTokenAuthZNode, delegation_tokens: DelegationTokensZNode, config_entity_change_notification: ConfigEntityChangeNotificationZNode, delete_topics: DeleteTopicsZNode, pub broker_sequence_id: BrokerSequenceIdZNode, isr_change_notification: IsrChangeNotificationZNode, producer_id_block: ProducerIdBlockZNode, log_dir_event_notification: LogDirEventNotificationZNode, admin: AdminZNode, pub cluster_id: ClusterIdZNode, /* brokers: ZNode, * cluster: ZNode, * config: ZNode, * controller: ZNode, * controller_epoch: ZNode, * extended_acl: ZNode, */ } impl ZkData { pub fn default_acls(&self, path: &str) -> Vec<Acl> { // NOTE: For now not caring about secure setup let is_secure = false; let mut acls: Vec<Acl> = vec![]; // Old Consumer path is kept open as different consumers will write under this node. if self.consumer_path.path() != path && is_secure { acls.extend_from_slice(Acl::creator_all()); if !self.is_sensitive_path(path) { acls.extend_from_slice(Acl::read_unsafe()); } } else { acls.extend_from_slice(Acl::open_unsafe()); } acls } pub fn is_sensitive_path(&self, path: &str) -> bool { !path.is_empty() // This used to be path != null in scala code && self.sensitive_root_paths().iter().any(|sensitive_path| path.starts_with(sensitive_path)) } // Important: it is necessary to add any new top level Zookeeper path to the Seq pub fn secure_root_paths(&self) -> Vec<&str> { unimplemented!(); // let mut paths = vec![ // self.admin.path, // self.brokers.path, // self.cluster.path, // self.config.path, // self.controller.path, // self.controller_epoch.path, // self.isr_change_notification.path, // self.producer_id_block.path, // self.log_dir_event_notification.path, // self.delegation_token_auth.path, // self.extended_acl.path, // ]; // paths.extend_from_slice(&ZkAclStore.securePaths); // paths } // These are persistent ZK paths that should exist on kafka broker startup. pub fn persistent_zk_paths(&self) -> Vec<&str> { let mut paths: Vec<&str> = vec![ &self.consumer_path.path(), // old consumer path &self.broker_ids.path(), &self.topics.path(), &self.config_entity_change_notification.path(), &self.delete_topics.path(), &self.broker_sequence_id.path(), &self.isr_change_notification.path(), &self.producer_id_block.path(), &self.log_dir_event_notification.path(), ]; // ConfigType.all.map(ConfigEntityTypeZNode.path) // NOTE: This depends on config_znode, but it's not obvious here... Maybe it should be // refactored. for path in self.config_types.all() { paths.push(path); } paths } pub fn sensitive_root_paths(&self) -> Vec<&str> { vec![&self.config_types.user, &self.config_types.broker, &self.delegation_tokens.path()] } } // source line: 70 #[derive(Debug, SubZNodeHandle)] pub struct ConfigZNode(ZNode); impl ConfigZNode { pub fn build() -> Self { Self(ZNode { path: String::from("/config") }) } } // source line: 74 #[derive(Debug, SubZNodeHandle)] pub struct BrokersZNode(ZNode); impl BrokersZNode { pub fn build() -> Self { Self(ZNode { path: String::from("/brokers") }) } } // source line: 78 #[derive(Debug, SubZNodeHandle)] pub struct BrokerIdsZNode(ZNode); impl BrokerIdsZNode { pub fn build(brokers_znode: &BrokersZNode) -> Self { Self(ZNode { path: format!("{}/ids", brokers_znode.path()) }) } } // source line: 277 this may defeat the purpose of the below User/Broker structs that I think are // also present in DynamicConfigManager... #[derive(Debug, SubZNodeHandle)] pub struct TopicsZNode(ZNode); impl TopicsZNode { pub fn build(brokers_znode: &BrokersZNode) -> Self { Self(ZNode { path: format!("{}/topics", brokers_znode.path()) }) } } // source line: 361 #[derive(Debug, SubZNodeHandle)] pub struct ConfigEntityTypeZNode(ZNode); impl ConfigEntityTypeZNode { pub fn build(config_znode: &ConfigZNode, entity_type: &str) -> Self { Self(ZNode { path: format!("{}/{}", config_znode.path(), entity_type) }) } } #[derive(Debug, SubZNodeHandle)] pub struct ConfigEntityZNode(ZNode); impl ConfigEntityZNode { pub fn build(config_znode: &ConfigZNode, entity_type: &str, entity_name: &str) -> Self { let config_entity_path = ConfigEntityTypeZNode::build(config_znode, entity_type).path().to_string(); Self(ZNode { path: format!("{}/{}", config_entity_path, entity_name) }) } pub fn encode(config: HashMap<String, String>) -> Vec<u8> { // RAFKA NOTE: This is asJava, how much could this change? serde_json::to_vec(&json!({ "version": 1, "config": config })) .unwrap() } pub fn decode(bytes: Option<Vec<u8>>) -> Result<HashMap<String, String>, ZNodeDecodeError> { let mut res = HashMap::new(); if bytes.is_none() { return Ok(res); } let bytes = bytes.unwrap(); if bytes.len() > 0 { let parsed_json: serde_json::Value = serde_json::from_slice(&bytes)?; match parsed_json { serde_json::Value::Object(map) => match map.get(&String::from("config")) { Some(val) => { match val { serde_json::Value::Object(val) => { for (key, value) in val { match value { serde_json::Value::String(value) => { trace!("Inserting key: {} -> value {}", key, value); res.insert(key.to_string(), value.to_string()); }, _ => warn!( "value type is not of type String(String), input: {:?}", bytes ), }; } }, _ => warn!( "config key does not contain an Object(Map<String, Value). input: \ {:?}", bytes ), }; }, None => { warn!( "Unable to find .config key on the ConfigEntityZNode json, input: {:?}", bytes ); }, }, _ => { error!( "ConfigEntityZNode does not contain Object(Map<String, Value). input: {:?}", bytes ); }, } } Ok(res) } } // source line: 382 #[derive(Debug, SubZNodeHandle)] pub struct ConfigEntityChangeNotificationZNode(ZNode); impl ConfigEntityChangeNotificationZNode { pub fn build(config_znode: &ConfigZNode) -> Self { Self(ZNode { path: format!("{}/changes", config_znode.path()) }) } } // source line: 393 #[derive(Debug, SubZNodeHandle)] pub struct IsrChangeNotificationZNode(ZNode); impl IsrChangeNotificationZNode { pub fn build() -> Self { Self(ZNode { path: String::from("/isr_change_notification") }) } } // source line: 419 #[derive(Debug, SubZNodeHandle)] pub struct LogDirEventNotificationZNode(ZNode); impl LogDirEventNotificationZNode { pub fn build() -> Self { Self(ZNode { path: String::from("/log_dir_event_notification") }) } } // source line: 436 #[derive(Debug, SubZNodeHandle)] pub struct AdminZNode(ZNode); impl AdminZNode { pub fn build() -> Self { Self(ZNode { path: String::from("/admin") }) } } // source line: 440 #[derive(Debug, SubZNodeHandle)] pub struct DeleteTopicsZNode(ZNode); impl DeleteTopicsZNode { pub fn build(admin_znode: &AdminZNode) -> Self { Self(ZNode { path: format!("{}/delete_topics", admin_znode.path()) }) } } // old consumer path znode // source line: 511 #[derive(Debug, SubZNodeHandle)] pub struct ConsumerPathZNode(ZNode); impl ConsumerPathZNode { pub fn build() -> Self { Self(ZNode { path: String::from("/consumers") }) } } // source line: 520 #[derive(Debug)] pub enum ZkVersion { MatchAnyVersion = -1, /* if used in a conditional set, matches any version (the value * should match ZooKeeper codebase) */ UnknownVersion = -2, /* Version returned from get if node does not exist (internal * constant for Kafka codebase, unused value in ZK) */ } // source line: 526 //#[derive(Debug, PartialEq)] // pub enum ZkStat { // NoStat, /* NOTE: Originally this is org.apache.zookeeper.data.Stat constructor: // * val NoStat = new Stat() */ //} // source line: 736 #[derive(Debug, SubZNodeHandle)] pub struct ClusterZNode(ZNode); impl ClusterZNode { pub fn build() -> Self { Self(ZNode { path: String::from("/cluster") }) } } // source line: 740 #[derive(Debug, SubZNodeHandle)] pub struct ClusterIdZNode(ZNode); impl ClusterIdZNode { pub fn build(cluster_znode: &ClusterZNode) -> Self { Self(ZNode { path: format!("{}/id", cluster_znode.path()) }) } pub fn to_json(&self, id: &str) -> Vec<u8> { serde_json::to_vec(&json!({ "version": "1", "id": id })) .unwrap() } pub fn from_json(cluster_id_json: &Vec<u8>) -> Result<String, serde_json::Error> { let res: serde_json::Value = serde_json::from_slice(cluster_id_json)?; Ok(res["id"].to_string()) } } // source line: 754 #[derive(Debug, SubZNodeHandle)] pub struct BrokerSequenceIdZNode(ZNode); impl BrokerSequenceIdZNode { pub fn build(brokers_znode: &BrokersZNode) -> Self { Self(ZNode { path: format!("{}/seqid", brokers_znode.path()) }) } } // source line: 758 #[derive(Debug, SubZNodeHandle)] pub struct ProducerIdBlockZNode(ZNode); impl ProducerIdBlockZNode { pub fn build() -> Self { Self(ZNode { path: String::from("/latest_producer_id_block") }) } } // source line: 762 #[derive(Debug, SubZNodeHandle)] pub struct DelegationTokenAuthZNode(ZNode); impl DelegationTokenAuthZNode { pub fn build() -> Self { Self(ZNode { path: String::from("/delegation_token") }) } } // source line: 778 #[derive(Debug, SubZNodeHandle)] pub struct DelegationTokensZNode(ZNode); impl DelegationTokensZNode { pub fn build(delegation_token_auth: &DelegationTokenAuthZNode) -> Self { Self(ZNode { path: format!("{}/tokens", delegation_token_auth.path()) }) } } /// Represents the status of the FeatureZNode. /// /// Enabled -> This status means the feature versioning system (KIP-584) is enabled, and, the /// finalized features stored in the FeatureZNode are active. This status is written by /// the controller to the FeatureZNode only when the broker IBP config is greater than /// or equal to KAFKA_2_7_IV0. /// /// Disabled -> This status means the feature versioning system (KIP-584) is disabled, and, the /// the finalized features stored in the FeatureZNode is not relevant. This status is /// written by the controller to the FeatureZNode only when the broker IBP config /// is less than KAFKA_2_7_IV0. /// /// The purpose behind the FeatureZNodeStatus is that it helps differentiates between the following /// cases: /// /// 1. New cluster bootstrap: /// For a new Kafka cluster (i.e. it is deployed first time), we would like to start the cluster /// with all the possible supported features finalized immediately. The new cluster will almost /// never be started with an old IBP config that’s less than KAFKA_2_7_IV0. In such a case, the /// controller will start up and notice that the FeatureZNode is absent in the new cluster. /// To handle the requirement, the controller will create a FeatureZNode (with enabled status) /// containing the entire list of supported features as its finalized features. /// /// 2. Cluster upgrade: /// Imagine there is an existing Kafka cluster with IBP config less than KAFKA_2_7_IV0, but /// the Broker binary has been upgraded to a state where it supports the feature versioning /// system (KIP-584). This means the user is upgrading from an earlier version of the Broker /// binary. In this case, we want to start with no finalized features and allow the user to /// enable them whenever they are ready i.e. in the future whenever the user sets IBP config /// to be greater than or equal to KAFKA_2_7_IV0. The reason is that enabling all the possible /// features immediately after an upgrade could be harmful to the cluster. /// In such a case: /// - Before the Broker upgrade (i.e. IBP config set to less than KAFKA_2_7_IV0), the /// controller will start up and check if the FeatureZNode is absent. If true, then it will /// react by creating a FeatureZNode with disabled status and empty features. /// - After the Broker upgrade (i.e. IBP config set to greater than or equal to KAFKA_2_7_IV0), /// when the controller starts up it will check if the FeatureZNode exists and whether it is /// disabled. In such a case, it won’t upgrade all features immediately. Instead it will just /// switch the FeatureZNode status to enabled status. This lets the user finalize the /// features later. /// /// 3. Cluster downgrade: /// Imagine that a Kafka cluster exists already and the IBP config is greater than or equal to /// KAFKA_2_7_IV0. Then, the user decided to downgrade the cluster by setting IBP config to a /// value less than KAFKA_2_7_IV0. This means the user is also disabling the feature versioning /// system (KIP-584). In this case, when the controller starts up with the lower IBP config, it /// will switch the FeatureZNode status to disabled with empty features. // source line: 837 #[derive(Debug, PartialEq)] pub enum FeatureZNodeStatus { Disabled, Enabled, } impl FeatureZNodeStatus { pub fn with_name_opt(value: i32) -> Option<Self> { match value { 0 => Some(FeatureZNodeStatus::Disabled), // RAFKA TODO: verify this is 0-based enum 1 => Some(FeatureZNodeStatus::Enabled), _ => None, } } } // source line: 854 #[derive(Debug)] pub enum FeatureZNodeVersion { V1 = 1, } // source line: 854 /// A helper function that builds the FeatureZNode #[derive(Debug)] pub struct FeatureZNodeBuilder { version_key: String, status_key: String, features_key: String, } impl Default for FeatureZNodeBuilder { fn default() -> Self { Self { version_key: String::from("version"), status_key: String::from("status"), features_key: String::from("features"), } } } impl FeatureZNodeBuilder { /// Attempts to create a FeatureZNode from an input Vec<u8> read from ??? /// See the tests for the format of the data. pub fn build(input: Vec<u8>) -> Result<FeatureZNode, ZNodeDecodeError> { let data = match String::from_utf8(input) { Ok(val) => val, Err(err) => { error!("Unable to transform data string: {}", err); return Err(ZNodeDecodeError::Utf8Error(err)); }, }; let decoded_data: serde_json::Value = match serde_json::from_str(&data) { Err(err) => { // Instead of using the `?` operator we do the match here to preserve the previous // error message. Granted, the error message does some convertion that should be // emulated, right after the `:` below: s"${new String(jsonBytes, UTF_8)}", e) error!("Failed to parse feature information: {:?} ", err); return Err(ZNodeDecodeError::Serde(err)); }, Ok(val) => val, }; let builder = Self::default(); let version = match &decoded_data[&builder.version_key].as_u64() { Some(val) => i32::try_from(*val)?, None => { return Err(ZNodeDecodeError::KeyNotFound( builder.version_key.to_string(), decoded_data.to_string(), )) }, }; if version < FeatureZNodeVersion::V1 as i32 { return Err(ZNodeDecodeError::UnsupportedVersion(version, data)); } let status_int = match &decoded_data[&builder.status_key].as_u64() { Some(val) => i32::try_from(*val)?, None => { return Err(ZNodeDecodeError::KeyNotFound( builder.version_key.to_string(), decoded_data.to_string(), )) }, }; let status = match FeatureZNodeStatus::with_name_opt(status_int) { Some(val) => val, None => { return Err(ZNodeDecodeError::MalformedStatus(status_int, decoded_data.to_string())) }, }; Ok(FeatureZNode { path: String::from("/feature"), current_version: FeatureZNodeVersion::V1, status, features: Features::parse_finalized_features_json_value( &decoded_data, &builder.features_key, )?, }) } } // source line: 854 /// `FeatureZNode` Represents the contents of the ZK node containing finalized feature information. #[derive(Debug, ZNodeHandle)] pub struct FeatureZNode { path: String, current_version: FeatureZNodeVersion, pub status: FeatureZNodeStatus, pub features: Features, } impl FeatureZNode { pub fn decode(data: Vec<u8>) -> Result<Self, ZNodeDecodeError> { FeatureZNodeBuilder::build(data) } pub fn default_path() -> String { String::from("/feature") } } impl Default for ZkData { fn default() -> Self { let config = ConfigZNode::build(); let config_types = ConfigType::build(&config); let brokers_znode = BrokersZNode::build(); let admin_znode = AdminZNode::build(); let delegation_token_auth = DelegationTokenAuthZNode::build(); let delegation_tokens = DelegationTokensZNode::build(&delegation_token_auth); let broker_ids = BrokerIdsZNode::build(&brokers_znode); let topics = TopicsZNode::build(&brokers_znode); let config_entity_change_notification = ConfigEntityChangeNotificationZNode::build(&config); let delete_topics = DeleteTopicsZNode::build(&admin_znode); let broker_sequence_id = BrokerSequenceIdZNode::build(&brokers_znode); let isr_change_notification = IsrChangeNotificationZNode::build(); let producer_id_block = ProducerIdBlockZNode::build(); let log_dir_event_notification = LogDirEventNotificationZNode::build(); let cluster_znode = ClusterZNode::build(); let cluster_id = ClusterIdZNode::build(&cluster_znode); ZkData { delegation_token_auth, delegation_tokens, admin: admin_znode, consumer_path: ConsumerPathZNode::build(), broker_ids, topics, config_entity_change_notification, delete_topics, broker_sequence_id, isr_change_notification, producer_id_block, log_dir_event_notification, config_types, config, cluster_id, } } } #[cfg(test)] mod test { use super::*; use crate::common::feature::finalized_version_range::FinalizedVersionRange; use tracing::info; // From core/src/test/scala/kafka/zk/FeatureZNodeTest.scala #[test_env_log::test] fn feature_znode_builder_decodes() { let valid_features = serde_json::json!({ "version":1, "status":1, "features": r#"{"feature1":{ "min_version_level": 1, "max_version_level": 2}, "feature2": {"min_version_level": 2, "max_version_level": 4}}"# }); info!("valid_features.version: {:?}", valid_features["version"]); info!("features_json_str: {}", valid_features.to_string()); let build_res = FeatureZNode::decode(valid_features.to_string().as_bytes().to_vec()); let built_znode = build_res.unwrap(); assert_eq!(built_znode.status, FeatureZNodeStatus::Enabled); let mut expected_features: HashMap<String, FinalizedVersionRange> = HashMap::new(); expected_features .insert(String::from("feature1"), FinalizedVersionRange::new(1, 2).unwrap()); expected_features .insert(String::from("feature2"), FinalizedVersionRange::new(2, 4).unwrap()); assert_eq!( Features { features: VersionRangeType::Finalized(expected_features) }, built_znode.features ); let empty_features = serde_json::json!({ "version":1, "status":1, "features": "{}", }); let empty_features_build_res = FeatureZNode::decode(empty_features.to_string().as_bytes().to_vec()); info!("Empty Feature ZNode: {:?}", empty_features_build_res); let empty_features_built_znode = empty_features_build_res.unwrap(); let expected_features: HashMap<String, FinalizedVersionRange> = HashMap::new(); assert_eq!( Features { features: VersionRangeType::Finalized(expected_features) }, empty_features_built_znode.features ); } }
37.01682
153
0.611549
2823acbe8090a1b6efdba9f0ae451803bb60fc04
5,173
// Copyright 2018 The Grin Developers // // 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. //! Lightweight readonly view into output MMR for convenience. use crate::core::core::hash::{Hash, Hashed}; use crate::core::core::pmmr::{self, ReadonlyPMMR}; use crate::core::core::{Block, BlockHeader, Input, Output, Transaction}; use crate::core::global; use crate::core::ser::PMMRIndexHashable; use crate::error::{Error, ErrorKind}; use crate::store::Batch; use grin_store::pmmr::PMMRBackend; /// Readonly view of the UTXO set (based on output MMR). pub struct UTXOView<'a> { output_pmmr: ReadonlyPMMR<'a, Output, PMMRBackend<Output>>, header_pmmr: ReadonlyPMMR<'a, BlockHeader, PMMRBackend<BlockHeader>>, batch: &'a Batch<'a>, } impl<'a> UTXOView<'a> { /// Build a new UTXO view. pub fn new( output_pmmr: ReadonlyPMMR<'a, Output, PMMRBackend<Output>>, header_pmmr: ReadonlyPMMR<'a, BlockHeader, PMMRBackend<BlockHeader>>, batch: &'a Batch<'_>, ) -> UTXOView<'a> { UTXOView { output_pmmr, header_pmmr, batch, } } /// Validate a block against the current UTXO set. /// Every input must spend an output that currently exists in the UTXO set. /// No duplicate outputs. pub fn validate_block(&self, block: &Block) -> Result<(), Error> { for output in block.outputs() { self.validate_output(output)?; } for input in block.inputs() { self.validate_input(input)?; } Ok(()) } /// Validate a transaction against the current UTXO set. /// Every input must spend an output that currently exists in the UTXO set. /// No duplicate outputs. pub fn validate_tx(&self, tx: &Transaction) -> Result<(), Error> { for output in tx.outputs() { self.validate_output(output)?; } for input in tx.inputs() { self.validate_input(input)?; } Ok(()) } // Input is valid if it is spending an (unspent) output // that currently exists in the output MMR. // Compare the hash in the output MMR at the expected pos. fn validate_input(&self, input: &Input) -> Result<(), Error> { if let Ok(pos) = self.batch.get_output_pos(&input.commitment()) { if let Some(hash) = self.output_pmmr.get_hash(pos) { if hash == input.hash_with_index(pos - 1) { return Ok(()); } } } Err(ErrorKind::AlreadySpent(input.commitment()).into()) } // Output is valid if it would not result in a duplicate commitment in the output MMR. fn validate_output(&self, output: &Output) -> Result<(), Error> { if let Ok(pos) = self.batch.get_output_pos(&output.commitment()) { if let Some(out_mmr) = self.output_pmmr.get_data(pos) { if out_mmr.commitment() == output.commitment() { return Err(ErrorKind::DuplicateCommitment(output.commitment()).into()); } } } Ok(()) } /// Verify we are not attempting to spend any coinbase outputs /// that have not sufficiently matured. pub fn verify_coinbase_maturity(&self, inputs: &Vec<Input>, height: u64) -> Result<(), Error> { // Find the greatest output pos of any coinbase // outputs we are attempting to spend. let pos = inputs .iter() .filter(|x| x.is_coinbase()) .filter_map(|x| self.batch.get_output_pos(&x.commitment()).ok()) .max() .unwrap_or(0); if pos > 0 { // If we have not yet reached 1,000 / 1,440 blocks then // we can fail immediately as coinbase cannot be mature. if height < global::coinbase_maturity() { return Err(ErrorKind::ImmatureCoinbase.into()); } // Find the "cutoff" pos in the output MMR based on the // header from 1,000 blocks ago. let cutoff_height = height.checked_sub(global::coinbase_maturity()).unwrap_or(0); let cutoff_header = self.get_header_by_height(cutoff_height)?; let cutoff_pos = cutoff_header.output_mmr_size; // If any output pos exceed the cutoff_pos // we know they have not yet sufficiently matured. if pos > cutoff_pos { return Err(ErrorKind::ImmatureCoinbase.into()); } } Ok(()) } /// Get the header hash for the specified pos from the underlying MMR backend. fn get_header_hash(&self, pos: u64) -> Option<Hash> { self.header_pmmr.get_data(pos).map(|x| x.hash()) } /// Get the header at the specified height based on the current state of the extension. /// Derives the MMR pos from the height (insertion index) and retrieves the header hash. /// Looks the header up in the db by hash. pub fn get_header_by_height(&self, height: u64) -> Result<BlockHeader, Error> { let pos = pmmr::insertion_to_pmmr_index(height + 1); if let Some(hash) = self.get_header_hash(pos) { let header = self.batch.get_block_header(&hash)?; Ok(header) } else { Err(ErrorKind::Other(format!("get header by height")).into()) } } }
33.590909
96
0.692248
ed77685b1553b4150e4fbea5d132607e14fb358f
718
#![no_std] #![feature(alloc, cell_update)] extern crate alloc; extern crate cl_std; use cl_std::contract_api::{add_associated_key, get_arg, revert, set_action_threshold}; use cl_std::value::account::{ActionType, PublicKey, Weight}; #[no_mangle] pub extern "C" fn call() { add_associated_key(PublicKey::new([123; 32]), Weight::new(254)).unwrap_or_else(|_| revert(50)); let key_management_threshold: Weight = get_arg(0); let deployment_threshold: Weight = get_arg(1); set_action_threshold(ActionType::KeyManagement, key_management_threshold) .unwrap_or_else(|_| revert(100)); set_action_threshold(ActionType::Deployment, deployment_threshold) .unwrap_or_else(|_| revert(200)); }
32.636364
99
0.735376
f5ef47449a0eb29d47c100a40784022d3b964726
870
extern crate futures; extern crate tokio_core; extern crate zmq_tokio; use futures::Stream; use tokio_core::reactor::Core; use zmq_tokio::zmq; use zmq_tokio::{Context}; fn main() { let ctx = Context::new(); let mut core = Core::new().unwrap(); let handle = core.handle(); let server = ctx.socket(zmq::REP, &handle).unwrap(); let _ = server.bind("tcp://127.0.0.1:78999").unwrap(); let server_stream = (&server) .incoming() .and_then(|msg| { println!("server got: {:?}", msg.as_str()); Ok(msg) }) .and_then(|msg| { (&server).send(msg) }) .and_then(|_| { println!("server replied"); Ok(()) }) .for_each(|_| { Ok(()) }); let _ = core.run(server_stream).unwrap(); ::std::process::exit(0); }
21.219512
58
0.516092
5b0421a84b6d4e2998fdde9b4202f2915d7be3ad
1,396
use futures::stream::TryStreamExt; use rtnetlink::{new_connection, Error, Handle}; use std::env; #[tokio::main] async fn main() -> Result<(), String> { let args: Vec<String> = env::args().collect(); if args.len() != 2 { usage(); return Ok(()); } let link_name = &args[1]; let (connection, handle, _) = new_connection().unwrap(); tokio::spawn(connection); create_vxlan(handle, link_name.to_string()) .await .map_err(|e| format!("{}", e)) } async fn create_vxlan(handle: Handle, name: String) -> Result<(), Error> { let mut links = handle.link().get().set_name_filter(name.clone()).execute(); if let Some(link) = links.try_next().await? { handle .link() .add() .vxlan("vxlan0".into(), 10u32) .link(link.header.index) .port(4789) .up() .execute() .await? } else { println!("no link link {} found", name); } Ok(()) } fn usage() { eprintln!( "usage: cargo run --example create_vxlan -- <link name> Note that you need to run this program as root. Instead of running cargo as root, build the example normally: cd netlink-ip ; cargo build --example create_vxlan Then find the binary in the target directory: cd ../target/debug/example ; sudo ./create_vxlan <link_name>" ); }
25.381818
81
0.573066
2284f34ffea527edd23cb482e5a13529ef304ad6
3,798
use std::{ convert::TryFrom, fmt::{self, Alignment, Write}, }; use crate::{ chunk::{JoinBytes, Lines, OpCode, OpCodeError}, repr::Value, }; pub trait DebugInstruction { fn debug_chunk<'a, I>( &mut self, bytes: &mut I, lines: &Lines, constants: &[Value], ) -> fmt::Result where I: Iterator<Item = (usize, &'a u8)> + ExactSizeIterator + JoinBytes; fn debug_next_instr<I: JoinBytes>( &mut self, bytes: &mut I, lines: &Lines, constants: &[Value], offset: usize, byte: u8, ) -> fmt::Result; fn print_offset(&mut self, offset: usize) -> fmt::Result; fn print_line_number(&mut self, lines: &Lines, offset: usize) -> fmt::Result; fn print_opcode(&mut self, op: OpCode) -> fmt::Result; fn print_opcode_and_value( &mut self, op: OpCode, handle: usize, value: Value, ) -> fmt::Result; } impl<T: Write> DebugInstruction for T { fn debug_chunk<'a, I>( &mut self, bytes: &mut I, lines: &Lines, constants: &[Value], ) -> fmt::Result where I: Iterator<Item = (usize, &'a u8)> + ExactSizeIterator + JoinBytes, { while let Some((offset, byte)) = bytes.next() { self.debug_next_instr(bytes, lines, constants, offset, *byte)?; // Insert newline if this isn't the last instruction if bytes.len() > 0 { writeln!(self)?; } } Ok(()) } fn debug_next_instr<I: JoinBytes>( &mut self, bytes: &mut I, lines: &Lines, constants: &[Value], offset: usize, byte: u8, ) -> fmt::Result { self.print_offset(offset)?; self.print_line_number(lines, offset)?; // Print the OpCode match OpCode::try_from(byte) { // For constants, we also print the index of the value in the pool, // followed by the value itself Ok( op @ OpCode::Constant | op @ OpCode::Constant16 | op @ OpCode::Constant24, ) => { let handle = match op { OpCode::Constant => bytes.join_bytes(1), OpCode::Constant16 => bytes.join_bytes(2), OpCode::Constant24 => bytes.join_bytes(3), _ => unreachable!(), } .ok_or(fmt::Error)?; let value = constants[handle]; self.print_opcode_and_value(op, handle, value) } Ok(op) => self.print_opcode(op), Err(OpCodeError(msg)) => write!(self, "<{}>", msg), }?; Ok(()) } fn print_offset(&mut self, offset: usize) -> fmt::Result { write!(self, "{:04} ", offset) } fn print_line_number(&mut self, lines: &Lines, offset: usize) -> fmt::Result { let line = lines.find_line(offset); let prev_line = if offset > 0 { Some(lines.find_line(offset - 1)) } else { None }; if prev_line.is_some() && prev_line.unwrap() == line { write!(self, " | ") } else { write!(self, "{:>4} ", line) } } fn print_opcode(&mut self, op: OpCode) -> fmt::Result { write!(self, "{:?}", op) } fn print_opcode_and_value( &mut self, op: OpCode, handle: usize, value: Value, ) -> fmt::Result { write!(self, "{:<16?} [{}] '{}'", op, handle, value) } } pub fn print_aligned(f: &mut fmt::Formatter, text: &str) -> fmt::Result { let len = text.len(); let width = f.width().unwrap_or(len); let pad = (width - len).max(0); let fill = f.fill(); match f.align() { None => write!(f, "{}", text), Some(Alignment::Center) => { // Err to the left if the space can't be evenly split let lw = (pad as f32 / 2.0).floor() as usize; let rw = pad - lw; let lp = fill.repeat(lw); let rp = fill.repeat(rw); write!(f, "{}{}{}", lp, text, rp) } Some(Alignment::Left) => write!(f, "{}{}", text, fill.repeat(pad)), Some(Alignment::Right) => write!(f, "{}{}", fill.repeat(pad), text), } } pub trait Repeat { fn repeat(&self, n: usize) -> String; } impl Repeat for char { fn repeat(&self, n: usize) -> String { let mut result = String::with_capacity(n); for _ in 0..n { result.push(*self); } result } }
22.473373
79
0.604002
678bcde8fa737a6891df77273b8ff26b1d906a87
30,738
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. //! Serde code to convert from protocol buffers to Rust data structures. use std::collections::HashMap; use std::convert::{TryFrom, TryInto}; use std::sync::Arc; use crate::error::BallistaError; use crate::execution_plans::{ ShuffleReaderExec, ShuffleWriterExec, UnresolvedShuffleExec, }; use crate::serde::protobuf::repartition_exec_node::PartitionMethod; use crate::serde::protobuf::ShuffleReaderPartition; use crate::serde::scheduler::PartitionLocation; use crate::serde::{from_proto_binary_op, proto_error, protobuf}; use crate::{convert_box_required, convert_required, into_required}; use datafusion::arrow::datatypes::{DataType, Schema, SchemaRef}; use datafusion::catalog::catalog::{ CatalogList, CatalogProvider, MemoryCatalogList, MemoryCatalogProvider, }; use datafusion::execution::context::{ ExecutionConfig, ExecutionContextState, ExecutionProps, }; use datafusion::logical_plan::{ window_frames::WindowFrame, DFSchema, Expr, JoinConstraint, JoinType, }; use datafusion::physical_plan::aggregates::{create_aggregate_expr, AggregateFunction}; use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec; use datafusion::physical_plan::hash_aggregate::{AggregateMode, HashAggregateExec}; use datafusion::physical_plan::hash_join::PartitionMode; use datafusion::physical_plan::planner::DefaultPhysicalPlanner; use datafusion::physical_plan::window_functions::{ BuiltInWindowFunction, WindowFunction, }; use datafusion::physical_plan::windows::{create_window_expr, WindowAggExec}; use datafusion::physical_plan::{ coalesce_batches::CoalesceBatchesExec, csv::CsvExec, empty::EmptyExec, expressions::{ col, Avg, BinaryExpr, CaseExpr, CastExpr, Column, InListExpr, IsNotNullExpr, IsNullExpr, Literal, NegativeExpr, NotExpr, PhysicalSortExpr, TryCastExpr, DEFAULT_DATAFUSION_CAST_OPTIONS, }, filter::FilterExec, functions::{self, BuiltinScalarFunction, ScalarFunctionExpr}, hash_join::HashJoinExec, limit::{GlobalLimitExec, LocalLimitExec}, parquet::ParquetExec, projection::ProjectionExec, repartition::RepartitionExec, sort::{SortExec, SortOptions}, Partitioning, }; use datafusion::physical_plan::{AggregateExpr, ExecutionPlan, PhysicalExpr, WindowExpr}; use datafusion::prelude::CsvReadOptions; use log::debug; use protobuf::physical_expr_node::ExprType; use protobuf::physical_plan_node::PhysicalPlanType; impl TryInto<Arc<dyn ExecutionPlan>> for &protobuf::PhysicalPlanNode { type Error = BallistaError; fn try_into(self) -> Result<Arc<dyn ExecutionPlan>, Self::Error> { let plan = self.physical_plan_type.as_ref().ok_or_else(|| { proto_error(format!( "physical_plan::from_proto() Unsupported physical plan '{:?}'", self )) })?; match plan { PhysicalPlanType::Projection(projection) => { let input: Arc<dyn ExecutionPlan> = convert_box_required!(projection.input)?; let exprs = projection .expr .iter() .zip(projection.expr_name.iter()) .map(|(expr, name)| Ok((expr.try_into()?, name.to_string()))) .collect::<Result<Vec<(Arc<dyn PhysicalExpr>, String)>, Self::Error>>( )?; Ok(Arc::new(ProjectionExec::try_new(exprs, input)?)) } PhysicalPlanType::Filter(filter) => { let input: Arc<dyn ExecutionPlan> = convert_box_required!(filter.input)?; let predicate = filter .expr .as_ref() .ok_or_else(|| { BallistaError::General( "filter (FilterExecNode) in PhysicalPlanNode is missing." .to_owned(), ) })? .try_into()?; Ok(Arc::new(FilterExec::try_new(predicate, input)?)) } PhysicalPlanType::CsvScan(scan) => { let schema = Arc::new(convert_required!(scan.schema)?); let options = CsvReadOptions::new() .has_header(scan.has_header) .file_extension(&scan.file_extension) .delimiter(scan.delimiter.as_bytes()[0]) .schema(&schema); let projection = scan.projection.iter().map(|i| *i as usize).collect(); Ok(Arc::new(CsvExec::try_new( &scan.path, options, Some(projection), scan.batch_size as usize, None, )?)) } PhysicalPlanType::ParquetScan(scan) => { let projection = scan.projection.iter().map(|i| *i as usize).collect(); let filenames: Vec<&str> = scan.filename.iter().map(|s| s.as_str()).collect(); Ok(Arc::new(ParquetExec::try_from_files( &filenames, Some(projection), None, scan.batch_size as usize, scan.num_partitions as usize, None, )?)) } PhysicalPlanType::CoalesceBatches(coalesce_batches) => { let input: Arc<dyn ExecutionPlan> = convert_box_required!(coalesce_batches.input)?; Ok(Arc::new(CoalesceBatchesExec::new( input, coalesce_batches.target_batch_size as usize, ))) } PhysicalPlanType::Merge(merge) => { let input: Arc<dyn ExecutionPlan> = convert_box_required!(merge.input)?; Ok(Arc::new(CoalescePartitionsExec::new(input))) } PhysicalPlanType::Repartition(repart) => { let input: Arc<dyn ExecutionPlan> = convert_box_required!(repart.input)?; match repart.partition_method { Some(PartitionMethod::Hash(ref hash_part)) => { let expr = hash_part .hash_expr .iter() .map(|e| e.try_into()) .collect::<Result<Vec<Arc<dyn PhysicalExpr>>, _>>()?; Ok(Arc::new(RepartitionExec::try_new( input, Partitioning::Hash( expr, hash_part.partition_count.try_into().unwrap(), ), )?)) } Some(PartitionMethod::RoundRobin(partition_count)) => { Ok(Arc::new(RepartitionExec::try_new( input, Partitioning::RoundRobinBatch( partition_count.try_into().unwrap(), ), )?)) } Some(PartitionMethod::Unknown(partition_count)) => { Ok(Arc::new(RepartitionExec::try_new( input, Partitioning::UnknownPartitioning( partition_count.try_into().unwrap(), ), )?)) } _ => Err(BallistaError::General( "Invalid partitioning scheme".to_owned(), )), } } PhysicalPlanType::GlobalLimit(limit) => { let input: Arc<dyn ExecutionPlan> = convert_box_required!(limit.input)?; Ok(Arc::new(GlobalLimitExec::new(input, limit.limit as usize))) } PhysicalPlanType::LocalLimit(limit) => { let input: Arc<dyn ExecutionPlan> = convert_box_required!(limit.input)?; Ok(Arc::new(LocalLimitExec::new(input, limit.limit as usize))) } PhysicalPlanType::Window(window_agg) => { let input: Arc<dyn ExecutionPlan> = convert_box_required!(window_agg.input)?; let input_schema = window_agg .input_schema .as_ref() .ok_or_else(|| { BallistaError::General( "input_schema in WindowAggrNode is missing.".to_owned(), ) })? .clone(); let physical_schema: SchemaRef = SchemaRef::new((&input_schema).try_into()?); let physical_window_expr: Vec<Arc<dyn WindowExpr>> = window_agg .window_expr .iter() .zip(window_agg.window_expr_name.iter()) .map(|(expr, name)| { let expr_type = expr.expr_type.as_ref().ok_or_else(|| { proto_error("Unexpected empty window physical expression") })?; match expr_type { ExprType::WindowExpr(window_node) => Ok(create_window_expr( &convert_required!(window_node.window_function)?, name.to_owned(), &[convert_box_required!(window_node.expr)?], &[], &[], Some(WindowFrame::default()), &physical_schema, )?), _ => Err(BallistaError::General( "Invalid expression for WindowAggrExec".to_string(), )), } }) .collect::<Result<Vec<_>, _>>()?; Ok(Arc::new(WindowAggExec::try_new( physical_window_expr, input, Arc::new((&input_schema).try_into()?), )?)) } PhysicalPlanType::HashAggregate(hash_agg) => { let input: Arc<dyn ExecutionPlan> = convert_box_required!(hash_agg.input)?; let mode = protobuf::AggregateMode::from_i32(hash_agg.mode).ok_or_else(|| { proto_error(format!( "Received a HashAggregateNode message with unknown AggregateMode {}", hash_agg.mode )) })?; let agg_mode: AggregateMode = match mode { protobuf::AggregateMode::Partial => AggregateMode::Partial, protobuf::AggregateMode::Final => AggregateMode::Final, protobuf::AggregateMode::FinalPartitioned => { AggregateMode::FinalPartitioned } }; let group = hash_agg .group_expr .iter() .zip(hash_agg.group_expr_name.iter()) .map(|(expr, name)| { expr.try_into().map(|expr| (expr, name.to_string())) }) .collect::<Result<Vec<_>, _>>()?; let input_schema = hash_agg .input_schema .as_ref() .ok_or_else(|| { BallistaError::General( "input_schema in HashAggregateNode is missing.".to_owned(), ) })? .clone(); let physical_schema: SchemaRef = SchemaRef::new((&input_schema).try_into()?); let physical_aggr_expr: Vec<Arc<dyn AggregateExpr>> = hash_agg .aggr_expr .iter() .zip(hash_agg.aggr_expr_name.iter()) .map(|(expr, name)| { let expr_type = expr.expr_type.as_ref().ok_or_else(|| { proto_error("Unexpected empty aggregate physical expression") })?; match expr_type { ExprType::AggregateExpr(agg_node) => { let aggr_function = protobuf::AggregateFunction::from_i32( agg_node.aggr_function, ) .ok_or_else( || { proto_error(format!( "Received an unknown aggregate function: {}", agg_node.aggr_function )) }, )?; Ok(create_aggregate_expr( &aggr_function.into(), false, &[convert_box_required!(agg_node.expr)?], &physical_schema, name.to_string(), )?) } _ => Err(BallistaError::General( "Invalid aggregate expression for HashAggregateExec" .to_string(), )), } }) .collect::<Result<Vec<_>, _>>()?; Ok(Arc::new(HashAggregateExec::try_new( agg_mode, group, physical_aggr_expr, input, Arc::new((&input_schema).try_into()?), )?)) } PhysicalPlanType::HashJoin(hashjoin) => { let left: Arc<dyn ExecutionPlan> = convert_box_required!(hashjoin.left)?; let right: Arc<dyn ExecutionPlan> = convert_box_required!(hashjoin.right)?; let on: Vec<(Column, Column)> = hashjoin .on .iter() .map(|col| { let left = into_required!(col.left)?; let right = into_required!(col.right)?; Ok((left, right)) }) .collect::<Result<_, Self::Error>>()?; let join_type = protobuf::JoinType::from_i32(hashjoin.join_type) .ok_or_else(|| { proto_error(format!( "Received a HashJoinNode message with unknown JoinType {}", hashjoin.join_type )) })?; let partition_mode = protobuf::PartitionMode::from_i32(hashjoin.partition_mode) .ok_or_else(|| { proto_error(format!( "Received a HashJoinNode message with unknown PartitionMode {}", hashjoin.partition_mode )) })?; let partition_mode = match partition_mode { protobuf::PartitionMode::CollectLeft => PartitionMode::CollectLeft, protobuf::PartitionMode::Partitioned => PartitionMode::Partitioned, }; Ok(Arc::new(HashJoinExec::try_new( left, right, on, &join_type.into(), partition_mode, )?)) } PhysicalPlanType::ShuffleWriter(shuffle_writer) => { let input: Arc<dyn ExecutionPlan> = convert_box_required!(shuffle_writer.input)?; let output_partitioning = parse_protobuf_hash_partitioning( shuffle_writer.output_partitioning.as_ref(), )?; Ok(Arc::new(ShuffleWriterExec::try_new( shuffle_writer.job_id.clone(), shuffle_writer.stage_id as usize, input, "".to_string(), // this is intentional but hacky - the executor will fill this in output_partitioning, )?)) } PhysicalPlanType::ShuffleReader(shuffle_reader) => { let schema = Arc::new(convert_required!(shuffle_reader.schema)?); let partition_location: Vec<Vec<PartitionLocation>> = shuffle_reader .partition .iter() .map(|p| { p.location .iter() .map(|l| l.clone().try_into()) .collect::<Result<Vec<_>, _>>() }) .collect::<Result<Vec<_>, BallistaError>>()?; let shuffle_reader = ShuffleReaderExec::try_new(partition_location, schema)?; Ok(Arc::new(shuffle_reader)) } PhysicalPlanType::Empty(empty) => { let schema = Arc::new(convert_required!(empty.schema)?); Ok(Arc::new(EmptyExec::new(empty.produce_one_row, schema))) } PhysicalPlanType::Sort(sort) => { let input: Arc<dyn ExecutionPlan> = convert_box_required!(sort.input)?; let exprs = sort .expr .iter() .map(|expr| { let expr = expr.expr_type.as_ref().ok_or_else(|| { proto_error(format!( "physical_plan::from_proto() Unexpected expr {:?}", self )) })?; if let protobuf::physical_expr_node::ExprType::Sort(sort_expr) = expr { let expr = sort_expr .expr .as_ref() .ok_or_else(|| { proto_error(format!( "physical_plan::from_proto() Unexpected sort expr {:?}", self )) })? .as_ref(); Ok(PhysicalSortExpr { expr: expr.try_into()?, options: SortOptions { descending: !sort_expr.asc, nulls_first: sort_expr.nulls_first, }, }) } else { Err(BallistaError::General(format!( "physical_plan::from_proto() {:?}", self ))) } }) .collect::<Result<Vec<_>, _>>()?; // Update concurrency here in the future Ok(Arc::new(SortExec::try_new(exprs, input)?)) } PhysicalPlanType::Unresolved(unresolved_shuffle) => { let schema = Arc::new(convert_required!(unresolved_shuffle.schema)?); Ok(Arc::new(UnresolvedShuffleExec { stage_id: unresolved_shuffle.stage_id as usize, schema, input_partition_count: unresolved_shuffle.input_partition_count as usize, output_partition_count: unresolved_shuffle.output_partition_count as usize, })) } } } } impl From<&protobuf::PhysicalColumn> for Column { fn from(c: &protobuf::PhysicalColumn) -> Column { Column::new(&c.name, c.index as usize) } } impl From<&protobuf::ScalarFunction> for BuiltinScalarFunction { fn from(f: &protobuf::ScalarFunction) -> BuiltinScalarFunction { use protobuf::ScalarFunction; match f { ScalarFunction::Sqrt => BuiltinScalarFunction::Sqrt, ScalarFunction::Sin => BuiltinScalarFunction::Sin, ScalarFunction::Cos => BuiltinScalarFunction::Cos, ScalarFunction::Tan => BuiltinScalarFunction::Tan, ScalarFunction::Asin => BuiltinScalarFunction::Asin, ScalarFunction::Acos => BuiltinScalarFunction::Acos, ScalarFunction::Atan => BuiltinScalarFunction::Atan, ScalarFunction::Exp => BuiltinScalarFunction::Exp, ScalarFunction::Log => BuiltinScalarFunction::Log, ScalarFunction::Log2 => BuiltinScalarFunction::Log2, ScalarFunction::Log10 => BuiltinScalarFunction::Log10, ScalarFunction::Floor => BuiltinScalarFunction::Floor, ScalarFunction::Ceil => BuiltinScalarFunction::Ceil, ScalarFunction::Round => BuiltinScalarFunction::Round, ScalarFunction::Trunc => BuiltinScalarFunction::Trunc, ScalarFunction::Abs => BuiltinScalarFunction::Abs, ScalarFunction::Signum => BuiltinScalarFunction::Signum, ScalarFunction::Octetlength => BuiltinScalarFunction::OctetLength, ScalarFunction::Concat => BuiltinScalarFunction::Concat, ScalarFunction::Lower => BuiltinScalarFunction::Lower, ScalarFunction::Upper => BuiltinScalarFunction::Upper, ScalarFunction::Trim => BuiltinScalarFunction::Trim, ScalarFunction::Ltrim => BuiltinScalarFunction::Ltrim, ScalarFunction::Rtrim => BuiltinScalarFunction::Rtrim, ScalarFunction::Totimestamp => BuiltinScalarFunction::ToTimestamp, ScalarFunction::Array => BuiltinScalarFunction::Array, ScalarFunction::Nullif => BuiltinScalarFunction::NullIf, ScalarFunction::Datepart => BuiltinScalarFunction::DatePart, ScalarFunction::Datetrunc => BuiltinScalarFunction::DateTrunc, ScalarFunction::Md5 => BuiltinScalarFunction::MD5, ScalarFunction::Sha224 => BuiltinScalarFunction::SHA224, ScalarFunction::Sha256 => BuiltinScalarFunction::SHA256, ScalarFunction::Sha384 => BuiltinScalarFunction::SHA384, ScalarFunction::Sha512 => BuiltinScalarFunction::SHA512, ScalarFunction::Ln => BuiltinScalarFunction::Ln, } } } impl TryFrom<&protobuf::PhysicalExprNode> for Arc<dyn PhysicalExpr> { type Error = BallistaError; fn try_from(expr: &protobuf::PhysicalExprNode) -> Result<Self, Self::Error> { let expr_type = expr .expr_type .as_ref() .ok_or_else(|| proto_error("Unexpected empty physical expression"))?; let pexpr: Arc<dyn PhysicalExpr> = match expr_type { ExprType::Column(c) => { let pcol: Column = c.into(); Arc::new(pcol) } ExprType::Literal(scalar) => { Arc::new(Literal::new(convert_required!(scalar.value)?)) } ExprType::BinaryExpr(binary_expr) => Arc::new(BinaryExpr::new( convert_box_required!(&binary_expr.l)?, from_proto_binary_op(&binary_expr.op)?, convert_box_required!(&binary_expr.r)?, )), ExprType::AggregateExpr(_) => { return Err(BallistaError::General( "Cannot convert aggregate expr node to physical expression" .to_owned(), )); } ExprType::WindowExpr(_) => { return Err(BallistaError::General( "Cannot convert window expr node to physical expression".to_owned(), )); } ExprType::Sort(_) => { return Err(BallistaError::General( "Cannot convert sort expr node to physical expression".to_owned(), )); } ExprType::IsNullExpr(e) => { Arc::new(IsNullExpr::new(convert_box_required!(e.expr)?)) } ExprType::IsNotNullExpr(e) => { Arc::new(IsNotNullExpr::new(convert_box_required!(e.expr)?)) } ExprType::NotExpr(e) => { Arc::new(NotExpr::new(convert_box_required!(e.expr)?)) } ExprType::Negative(e) => { Arc::new(NegativeExpr::new(convert_box_required!(e.expr)?)) } ExprType::InList(e) => Arc::new(InListExpr::new( convert_box_required!(e.expr)?, e.list .iter() .map(|x| x.try_into()) .collect::<Result<Vec<_>, _>>()?, e.negated, )), ExprType::Case(e) => Arc::new(CaseExpr::try_new( e.expr.as_ref().map(|e| e.as_ref().try_into()).transpose()?, e.when_then_expr .iter() .map(|e| { Ok(( convert_required!(e.when_expr)?, convert_required!(e.then_expr)?, )) }) .collect::<Result<Vec<_>, BallistaError>>()? .as_slice(), e.else_expr .as_ref() .map(|e| e.as_ref().try_into()) .transpose()?, )?), ExprType::Cast(e) => Arc::new(CastExpr::new( convert_box_required!(e.expr)?, convert_required!(e.arrow_type)?, DEFAULT_DATAFUSION_CAST_OPTIONS, )), ExprType::TryCast(e) => Arc::new(TryCastExpr::new( convert_box_required!(e.expr)?, convert_required!(e.arrow_type)?, )), ExprType::ScalarFunction(e) => { let scalar_function = protobuf::ScalarFunction::from_i32(e.fun) .ok_or_else(|| { proto_error(format!( "Received an unknown scalar function: {}", e.fun, )) })?; let args = e .args .iter() .map(|x| x.try_into()) .collect::<Result<Vec<_>, _>>()?; let catalog_list = Arc::new(MemoryCatalogList::new()) as Arc<dyn CatalogList>; let ctx_state = ExecutionContextState { catalog_list, scalar_functions: Default::default(), var_provider: Default::default(), aggregate_functions: Default::default(), config: ExecutionConfig::new(), execution_props: ExecutionProps::new(), }; let fun_expr = functions::create_physical_fun( &(&scalar_function).into(), &ctx_state, )?; Arc::new(ScalarFunctionExpr::new( &e.name, fun_expr, args, &convert_required!(e.return_type)?, )) } }; Ok(pexpr) } } impl TryFrom<&protobuf::physical_window_expr_node::WindowFunction> for WindowFunction { type Error = BallistaError; fn try_from( expr: &protobuf::physical_window_expr_node::WindowFunction, ) -> Result<Self, Self::Error> { match expr { protobuf::physical_window_expr_node::WindowFunction::AggrFunction(n) => { let f = protobuf::AggregateFunction::from_i32(*n).ok_or_else(|| { proto_error(format!( "Received an unknown window aggregate function: {}", n )) })?; Ok(WindowFunction::AggregateFunction(f.into())) } protobuf::physical_window_expr_node::WindowFunction::BuiltInFunction(n) => { let f = protobuf::BuiltInWindowFunction::from_i32(*n).ok_or_else(|| { proto_error(format!( "Received an unknown window builtin function: {}", n )) })?; Ok(WindowFunction::BuiltInWindowFunction(f.into())) } } } } pub fn parse_protobuf_hash_partitioning( partitioning: Option<&protobuf::PhysicalHashRepartition>, ) -> Result<Option<Partitioning>, BallistaError> { match partitioning { Some(hash_part) => { let expr = hash_part .hash_expr .iter() .map(|e| e.try_into()) .collect::<Result<Vec<Arc<dyn PhysicalExpr>>, _>>()?; Ok(Some(Partitioning::Hash( expr, hash_part.partition_count.try_into().unwrap(), ))) } None => Ok(None), } }
44.227338
101
0.481554
29e51727edcfd8c3f576d8cfd9892f681794cc69
778
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct Foo; impl Foo { fn foo(self: *const Self) {} //~^ ERROR raw pointer `self` is unstable } trait Bar { fn bar(self: *const Self); //~^ ERROR raw pointer `self` is unstable } impl Bar for () { fn bar(self: *const Self) {} //~^ ERROR raw pointer `self` is unstable } fn main() {}
26.827586
68
0.679949
48b5875b4bcf0fdfd780bec66a37b5e53235bddc
4,696
use crate::time::FormatTime; use crate::AsciiString; use core::fmt::{Display, Formatter}; use core::time::Duration; use std::time::SystemTime; #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum SameSite { Strict, Lax, None, } #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct Cookie { name: AsciiString, value: AsciiString, domain: AsciiString, expires: SystemTime, http_only: bool, path: AsciiString, max_age: Duration, same_site: SameSite, secure: bool, } impl Cookie { /// Makes a new cookie with the specified name and value. /// /// The cookie has `max_age` set to 30 days, /// `same_site` strict, /// `secure` true, /// and `http_only` true. /// /// # Panics /// Panics when `name` is empty. /// Panics when `name` is not US-ASCII. #[must_use] pub fn new(name: impl AsRef<str>, value: AsciiString) -> Self { assert!( !name.as_ref().is_empty(), "Cookie::new called with empty `name`" ); Self { name: name.as_ref().to_string().try_into().unwrap(), value, domain: AsciiString::new(), expires: SystemTime::UNIX_EPOCH, http_only: true, max_age: Duration::from_secs(30 * 24 * 60 * 60), path: AsciiString::new(), same_site: SameSite::Strict, secure: true, } } /// # Panics /// Panics when `domain` is not US-ASCII. #[must_use] pub fn with_domain(mut self, d: impl AsRef<str>) -> Self { self.domain = d.as_ref().try_into().unwrap(); self } /// To un-set this value, pass `SystemTime::UNIX_EPOCH`. #[must_use] pub fn with_expires(mut self, t: SystemTime) -> Self { self.expires = t; self } #[must_use] pub fn with_http_only(mut self, b: bool) -> Self { self.http_only = b; self } /// To un-set duration, pass `Duration::ZERO`. #[must_use] pub fn with_max_age(mut self, d: Duration) -> Self { self.max_age = d; self } /// # Panics /// Panics when `p` is not US-ASCII. #[must_use] pub fn with_path(mut self, p: impl AsRef<str>) -> Self { self.path = p.as_ref().try_into().unwrap(); self } #[must_use] pub fn with_same_site(mut self, s: SameSite) -> Self { self.same_site = s; self } #[must_use] pub fn with_secure(mut self, b: bool) -> Self { self.secure = b; self } } impl Display for Cookie { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie // Set-Cookie: <cookie-name>=<cookie-value> // Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date> // Set-Cookie: <cookie-name>=<cookie-value>; Max-Age=<number> // Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value> // Set-Cookie: <cookie-name>=<cookie-value>; Path=<path-value> // Set-Cookie: <cookie-name>=<cookie-value>; Secure // Set-Cookie: <cookie-name>=<cookie-value>; HttpOnly // // Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Strict // Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Lax // Set-Cookie: <cookie-name>=<cookie-value>; SameSite=None; Secure // // // Multiple attributes are also possible, for example: // Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly write!(f, "{}={}", self.name.as_str(), self.value.as_str())?; if !self.domain.is_empty() { write!(f, "; Domain={}", self.domain.as_str())?; } if self.expires != SystemTime::UNIX_EPOCH { write!(f, "; Expires={}", self.expires.iso8601_utc())?; } if self.http_only { write!(f, "; HttpOnly")?; } if self.max_age > Duration::ZERO { write!(f, "; Max-Age={}", self.max_age.as_secs())?; } if !self.path.is_empty() { write!(f, "; Path={}", self.path.as_str())?; } match self.same_site { SameSite::Strict => write!(f, "; SameSite=Strict")?, SameSite::Lax => write!(f, "; SameSite=Lax")?, SameSite::None => write!(f, "; SameSite=None")?, } if self.secure { write!(f, "; Secure")?; } Ok(()) } } impl From<Cookie> for AsciiString { fn from(cookie: Cookie) -> Self { AsciiString::try_from(format!("{}", cookie)).unwrap() } }
30.69281
92
0.5477
08487aec3f2e41a2efcaba6b0a6be602d5f9131b
19,635
#![deny(rust_2018_idioms)] #[macro_use] extern crate log; //extern crate lru_cache; pub mod lru_cache; use std::borrow::Borrow; use std::boxed::Box; use std::collections::hash_map::RandomState; use std::error::Error as StdError; use std::ffi::{OsStr, OsString}; use std::fmt; use std::fs::{self, File}; use std::hash::BuildHasher; use std::io; use std::io::prelude::*; use std::path::{Path, PathBuf}; pub use crate::lru_cache::{LruCache, Meter}; use filetime::{set_file_times, FileTime}; use walkdir::WalkDir; struct FileSize; /// Given a tuple of (path, filesize), use the filesize for measurement. impl<K> Meter<K, u64> for FileSize { type Measure = usize; fn measure<Q: ?Sized>(&self, _: &Q, v: &u64) -> usize where K: Borrow<Q>, { *v as usize } } /// Return an iterator of `(path, size)` of files under `path` sorted by ascending last-modified /// time, such that the oldest modified file is returned first. fn get_all_files<P: AsRef<Path>>(path: P) -> Box<dyn Iterator<Item = (PathBuf, u64)>> { let mut files: Vec<_> = WalkDir::new(path.as_ref()) .into_iter() .filter_map(|e| { e.ok().and_then(|f| { // Only look at files if f.file_type().is_file() { // Get the last-modified time, size, and the full path. f.metadata().ok().and_then(|m| { m.modified() .ok() .map(|mtime| (mtime, f.path().to_owned(), m.len())) }) } else { None } }) }) .collect(); // Sort by last-modified-time, so oldest file first. files.sort_by_key(|k| k.0); Box::new(files.into_iter().map(|(_mtime, path, size)| (path, size))) } /// An LRU cache of files on disk. pub struct LruDiskCache<S: BuildHasher = RandomState> { lru: LruCache<OsString, u64, S, FileSize>, root: PathBuf, } /// Errors returned by this crate. #[derive(Debug)] pub enum Error { /// The file was too large to fit in the cache. FileTooLarge, /// The file was not in the cache. FileNotInCache, /// An IO Error occurred. Io(io::Error), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self) } } impl StdError for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::FileTooLarge => None, Error::FileNotInCache => None, Error::Io(ref e) => Some(e), } } } impl From<io::Error> for Error { fn from(e: io::Error) -> Error { Error::Io(e) } } /// A convenience `Result` type pub type Result<T> = std::result::Result<T, Error>; /// Trait objects can't be bounded by more than one non-builtin trait. pub trait ReadSeek: Read + Seek + Send {} impl<T: Read + Seek + Send> ReadSeek for T {} enum AddFile<'a> { AbsPath(PathBuf), RelPath(&'a OsStr), } impl LruDiskCache { /// Create an `LruDiskCache` that stores files in `path`, limited to `size` bytes. /// /// Existing files in `path` will be stored with their last-modified time from the filesystem /// used as the order for the recency of their use. Any files that are individually larger /// than `size` bytes will be removed. /// /// The cache is not observant of changes to files under `path` from external sources, it /// expects to have sole maintence of the contents. pub fn new<T>(path: T, size: u64) -> Result<Self> where PathBuf: From<T>, { LruDiskCache { lru: LruCache::with_meter(size, FileSize), root: PathBuf::from(path), } .init() } /// Return the current size of all the files in the cache. pub fn size(&self) -> u64 { self.lru.size() } /// Return the count of entries in the cache. pub fn len(&self) -> usize { self.lru.len() } pub fn is_empty(&self) -> bool { self.lru.len() == 0 } /// Return the maximum size of the cache. pub fn capacity(&self) -> u64 { self.lru.capacity() } /// Return the path in which the cache is stored. pub fn path(&self) -> &Path { self.root.as_path() } /// Return the path that `key` would be stored at. fn rel_to_abs_path<K: AsRef<Path>>(&self, rel_path: K) -> PathBuf { self.root.join(rel_path) } /// Scan `self.root` for existing files and store them. fn init(mut self) -> Result<Self> { fs::create_dir_all(&self.root)?; for (file, size) in get_all_files(&self.root) { if !self.can_store(size) { fs::remove_file(file).unwrap_or_else(|e| { error!( "Error removing file `{}` which is too large for the cache ({} bytes)", e, size ) }); } else { self.add_file(AddFile::AbsPath(file), size) .unwrap_or_else(|e| error!("Error adding file: {}", e)); } } Ok(self) } /// Returns `true` if the disk cache can store a file of `size` bytes. pub fn can_store(&self, size: u64) -> bool { size <= self.lru.capacity() as u64 } /// Add the file at `path` of size `size` to the cache. fn add_file(&mut self, addfile_path: AddFile<'_>, size: u64) -> Result<()> { if !self.can_store(size) { return Err(Error::FileTooLarge); } let rel_path = match addfile_path { AddFile::AbsPath(ref p) => p.strip_prefix(&self.root).expect("Bad path?").as_os_str(), AddFile::RelPath(p) => p, }; //TODO: ideally LRUCache::insert would give us back the entries it had to remove. while self.lru.size() as u64 + size > self.lru.capacity() as u64 { let (rel_path, _) = self.lru.remove_lru().expect("Unexpectedly empty cache!"); let remove_path = self.rel_to_abs_path(rel_path); //TODO: check that files are removable during `init`, so that this is only // due to outside interference. fs::remove_file(&remove_path).unwrap_or_else(|e| { panic!("Error removing file from cache: `{:?}`: {}", remove_path, e) }); } self.lru.insert(rel_path.to_owned(), size); Ok(()) } fn insert_by<K: AsRef<OsStr>, F: FnOnce(&Path) -> io::Result<()>>( &mut self, key: K, size: Option<u64>, by: F, ) -> Result<()> { if let Some(size) = size { if !self.can_store(size) { return Err(Error::FileTooLarge); } } let rel_path = key.as_ref(); let path = self.rel_to_abs_path(rel_path); fs::create_dir_all(path.parent().expect("Bad path?"))?; by(&path)?; let size = match size { Some(size) => size, None => fs::metadata(path)?.len(), }; self.add_file(AddFile::RelPath(rel_path), size) .map_err(|e| { error!( "Failed to insert file `{}`: {}", rel_path.to_string_lossy(), e ); fs::remove_file(&self.rel_to_abs_path(rel_path)) .expect("Failed to remove file we just created!"); e }) } /// Add a file by calling `with` with the open `File` corresponding to the cache at path `key`. pub fn insert_with<K: AsRef<OsStr>, F: FnOnce(File) -> io::Result<()>>( &mut self, key: K, with: F, ) -> Result<()> { self.insert_by(key, None, |path| with(File::create(&path)?)) } /// Add a file with `bytes` as its contents to the cache at path `key`. pub fn insert_bytes<K: AsRef<OsStr>>(&mut self, key: K, bytes: &[u8]) -> Result<()> { self.insert_by(key, Some(bytes.len() as u64), |path| { let mut f = File::create(&path)?; f.write_all(bytes)?; Ok(()) }) } /// Add an existing file at `path` to the cache at path `key`. pub fn insert_file<K: AsRef<OsStr>, P: AsRef<OsStr>>(&mut self, key: K, path: P) -> Result<()> { let size = fs::metadata(path.as_ref())?.len(); self.insert_by(key, Some(size), |new_path| { fs::rename(path.as_ref(), new_path).or_else(|_| { warn!("fs::rename failed, falling back to copy!"); fs::copy(path.as_ref(), new_path)?; fs::remove_file(path.as_ref()).unwrap_or_else(|e| { error!("Failed to remove original file in insert_file: {}", e) }); Ok(()) }) }) } /// Return `true` if a file with path `key` is in the cache. pub fn contains_key<K: AsRef<OsStr>>(&self, key: K) -> bool { self.lru.contains_key(key.as_ref()) } /// Get an opened `File` for `key`, if one exists and can be opened. Updates the LRU state /// of the file if present. Avoid using this method if at all possible, prefer `.get`. pub fn get_file<K: AsRef<OsStr>>(&mut self, key: K) -> Result<File> { let rel_path = key.as_ref(); let path = self.rel_to_abs_path(rel_path); self.lru .get(rel_path) .ok_or(Error::FileNotInCache) .and_then(|_| { let t = FileTime::now(); set_file_times(&path, t, t)?; File::open(path).map_err(Into::into) }) } /// Get an opened readable and seekable handle to the file at `key`, if one exists and can /// be opened. Updates the LRU state of the file if present. pub fn get<K: AsRef<OsStr>>(&mut self, key: K) -> Result<Box<dyn ReadSeek>> { self.get_file(key).map(|f| Box::new(f) as Box<dyn ReadSeek>) } /// Remove the given key from the cache. pub fn remove<K: AsRef<OsStr>>(&mut self, key: K) -> Result<()> { match self.lru.remove(key.as_ref()) { Some(_) => { let path = self.rel_to_abs_path(key.as_ref()); fs::remove_file(&path).map_err(|e| { error!("Error removing file from cache: `{:?}`: {}", path, e); Into::into(e) }) } None => Ok(()), } } } #[cfg(test)] mod tests { use super::{Error, LruDiskCache}; use filetime::{set_file_times, FileTime}; use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use tempfile::TempDir; struct TestFixture { /// Temp directory. pub tempdir: TempDir, } fn create_file<T: AsRef<Path>, F: FnOnce(File) -> io::Result<()>>( dir: &Path, path: T, fill_contents: F, ) -> io::Result<PathBuf> { let b = dir.join(path); fs::create_dir_all(b.parent().unwrap())?; let f = fs::File::create(&b)?; fill_contents(f)?; b.canonicalize() } /// Set the last modified time of `path` backwards by `seconds` seconds. fn set_mtime_back<T: AsRef<Path>>(path: T, seconds: usize) { let m = fs::metadata(path.as_ref()).unwrap(); let t = FileTime::from_last_modification_time(&m); let t = FileTime::from_unix_time(t.unix_seconds() - seconds as i64, t.nanoseconds()); set_file_times(path, t, t).unwrap(); } fn read_all<R: Read>(r: &mut R) -> io::Result<Vec<u8>> { let mut v = vec![]; r.read_to_end(&mut v)?; Ok(v) } impl TestFixture { pub fn new() -> TestFixture { TestFixture { tempdir: tempfile::Builder::new() .prefix("lru-disk-cache-test") .tempdir() .unwrap(), } } pub fn tmp(&self) -> &Path { self.tempdir.path() } pub fn create_file<T: AsRef<Path>>(&self, path: T, size: usize) -> PathBuf { create_file(self.tempdir.path(), path, |mut f| { f.write_all(&vec![0; size]) }) .unwrap() } } #[test] fn test_empty_dir() { let f = TestFixture::new(); LruDiskCache::new(f.tmp(), 1024).unwrap(); } #[test] fn test_missing_root() { let f = TestFixture::new(); LruDiskCache::new(f.tmp().join("not-here"), 1024).unwrap(); } #[test] fn test_some_existing_files() { let f = TestFixture::new(); f.create_file("file1", 10); f.create_file("file2", 10); let c = LruDiskCache::new(f.tmp(), 20).unwrap(); assert_eq!(c.size(), 20); assert_eq!(c.len(), 2); } #[test] fn test_existing_file_too_large() { let f = TestFixture::new(); // Create files explicitly in the past. set_mtime_back(f.create_file("file1", 10), 10); set_mtime_back(f.create_file("file2", 10), 5); let c = LruDiskCache::new(f.tmp(), 15).unwrap(); assert_eq!(c.size(), 10); assert_eq!(c.len(), 1); assert!(!c.contains_key("file1")); assert!(c.contains_key("file2")); } #[test] fn test_existing_files_lru_mtime() { let f = TestFixture::new(); // Create files explicitly in the past. set_mtime_back(f.create_file("file1", 10), 5); set_mtime_back(f.create_file("file2", 10), 10); let mut c = LruDiskCache::new(f.tmp(), 25).unwrap(); assert_eq!(c.size(), 20); c.insert_bytes("file3", &vec![0; 10]).unwrap(); assert_eq!(c.size(), 20); // The oldest file on disk should have been removed. assert!(!c.contains_key("file2")); assert!(c.contains_key("file1")); } #[test] fn test_insert_bytes() { let f = TestFixture::new(); let mut c = LruDiskCache::new(f.tmp(), 25).unwrap(); c.insert_bytes("a/b/c", &vec![0; 10]).unwrap(); assert!(c.contains_key("a/b/c")); c.insert_bytes("a/b/d", &vec![0; 10]).unwrap(); assert_eq!(c.size(), 20); // Adding this third file should put the cache above the limit. c.insert_bytes("x/y/z", &vec![0; 10]).unwrap(); assert_eq!(c.size(), 20); // The least-recently-used file should have been removed. assert!(!c.contains_key("a/b/c")); assert!(!f.tmp().join("a/b/c").exists()); } #[test] fn test_insert_bytes_exact() { // Test that files adding up to exactly the size limit works. let f = TestFixture::new(); let mut c = LruDiskCache::new(f.tmp(), 20).unwrap(); c.insert_bytes("file1", &vec![1; 10]).unwrap(); c.insert_bytes("file2", &vec![2; 10]).unwrap(); assert_eq!(c.size(), 20); c.insert_bytes("file3", &vec![3; 10]).unwrap(); assert_eq!(c.size(), 20); assert!(!c.contains_key("file1")); } #[test] fn test_add_get_lru() { let f = TestFixture::new(); { let mut c = LruDiskCache::new(f.tmp(), 25).unwrap(); c.insert_bytes("file1", &vec![1; 10]).unwrap(); c.insert_bytes("file2", &vec![2; 10]).unwrap(); // Get the file to bump its LRU status. assert_eq!( read_all(&mut c.get("file1").unwrap()).unwrap(), vec![1u8; 10] ); // Adding this third file should put the cache above the limit. c.insert_bytes("file3", &vec![3; 10]).unwrap(); assert_eq!(c.size(), 20); // The least-recently-used file should have been removed. assert!(!c.contains_key("file2")); } // Get rid of the cache, to test that the LRU persists on-disk as mtimes. // This is hacky, but mtime resolution on my mac with HFS+ is only 1 second, so we either // need to have a 1 second sleep in the test (boo) or adjust the mtimes back a bit so // that updating one file to the current time actually works to make it newer. set_mtime_back(f.tmp().join("file1"), 5); set_mtime_back(f.tmp().join("file3"), 5); { let mut c = LruDiskCache::new(f.tmp(), 25).unwrap(); // Bump file1 again. c.get("file1").unwrap(); } // Now check that the on-disk mtimes were updated and used. { let mut c = LruDiskCache::new(f.tmp(), 25).unwrap(); assert!(c.contains_key("file1")); assert!(c.contains_key("file3")); assert_eq!(c.size(), 20); // Add another file to bump out the least-recently-used. c.insert_bytes("file4", &vec![4; 10]).unwrap(); assert_eq!(c.size(), 20); assert!(!c.contains_key("file3")); assert!(c.contains_key("file1")); } } #[test] fn test_insert_bytes_too_large() { let f = TestFixture::new(); let mut c = LruDiskCache::new(f.tmp(), 1).unwrap(); match c.insert_bytes("a/b/c", &vec![0; 2]) { Err(Error::FileTooLarge) => assert!(true), x @ _ => panic!("Unexpected result: {:?}", x), } } #[test] fn test_insert_file() { let f = TestFixture::new(); let p1 = f.create_file("file1", 10); let p2 = f.create_file("file2", 10); let p3 = f.create_file("file3", 10); let mut c = LruDiskCache::new(f.tmp().join("cache"), 25).unwrap(); c.insert_file("file1", &p1).unwrap(); assert_eq!(c.len(), 1); c.insert_file("file2", &p2).unwrap(); assert_eq!(c.len(), 2); // Get the file to bump its LRU status. assert_eq!( read_all(&mut c.get("file1").unwrap()).unwrap(), vec![0u8; 10] ); // Adding this third file should put the cache above the limit. c.insert_file("file3", &p3).unwrap(); assert_eq!(c.len(), 2); assert_eq!(c.size(), 20); // The least-recently-used file should have been removed. assert!(!c.contains_key("file2")); assert!(!p1.exists()); assert!(!p2.exists()); assert!(!p3.exists()); } #[test] fn test_remove() { let f = TestFixture::new(); let p1 = f.create_file("file1", 10); let p2 = f.create_file("file2", 10); let p3 = f.create_file("file3", 10); let mut c = LruDiskCache::new(f.tmp().join("cache"), 25).unwrap(); c.insert_file("file1", &p1).unwrap(); c.insert_file("file2", &p2).unwrap(); c.remove("file1").unwrap(); c.insert_file("file3", &p3).unwrap(); assert_eq!(c.len(), 2); assert_eq!(c.size(), 20); // file1 should have been removed. assert!(!c.contains_key("file1")); assert!(!f.tmp().join("cache").join("file1").exists()); assert!(f.tmp().join("cache").join("file2").exists()); assert!(f.tmp().join("cache").join("file3").exists()); assert!(!p1.exists()); assert!(!p2.exists()); assert!(!p3.exists()); let p4 = f.create_file("file1", 10); c.insert_file("file1", &p4).unwrap(); assert_eq!(c.len(), 2); // file2 should have been removed. assert!(c.contains_key("file1")); assert!(!c.contains_key("file2")); assert!(!f.tmp().join("cache").join("file2").exists()); assert!(!p4.exists()); } }
34.326923
100
0.533231
09300cfd857fd315321e6e8b190d4ffd0ae85445
787
struct Solution; use rustgym_util::*; impl Solution { fn inorder_traversal(root: TreeLink) -> Vec<i32> { let mut cur = root; let mut stack: Vec<TreeLink> = vec![]; let mut res = vec![]; while cur.is_some() || !stack.is_empty() { while let Some(node) = cur { let left = node.borrow_mut().left.take(); stack.push(Some(node)); cur = left; } let node = stack.pop().unwrap().unwrap(); res.push(node.borrow().val); cur = node.borrow_mut().right.take(); } res } } #[test] fn test() { let root = tree!(1, None, tree!(2, tree!(3), None)); let res = vec![1, 3, 2]; assert_eq!(Solution::inorder_traversal(root), res); }
27.137931
57
0.504447
f48a5c5ad80055d60a4563775e48491b971e2a1a
2,592
#[doc = r" Value read from the register"] pub struct R { bits: u16, } #[doc = r" Value to write to the register"] pub struct W { bits: u16, } impl super::PACKET_BUFFER_17 { #[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 PACKET_BUFFERR { bits: u16, } impl PACKET_BUFFERR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u16 { self.bits } } #[doc = r" Proxy"] pub struct _PACKET_BUFFERW<'a> { w: &'a mut W, } impl<'a> _PACKET_BUFFERW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u16) -> &'a mut W { const MASK: u16 = 65535; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u16) << OFFSET); self.w.bits |= ((value & MASK) as u16) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u16 { self.bits } #[doc = "Bits 0:15 - PACKET BUFFER RAM"] #[inline] pub fn packet_buffer(&self) -> PACKET_BUFFERR { let bits = { const MASK: u16 = 65535; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u16) as u16 }; PACKET_BUFFERR { 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: u16) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:15 - PACKET BUFFER RAM"] #[inline] pub fn packet_buffer(&mut self) -> _PACKET_BUFFERW { _PACKET_BUFFERW { w: self } } }
24.45283
59
0.51196
d7fe5512e026b605bae533b0a7ac627387e8c3bb
1,354
// SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2021 Andre Richter <[email protected]> //! Printing. use crate::{bsp, console}; use core::fmt; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- // QEMUの簡易UARTで書式で表示するよ. #[doc(hidden)] pub fn _print(args: fmt::Arguments) { use console::interface::Write; // bsp/raspberrypi/console.rsのconsole関数がQEMUの怪しげなdeviceを返す // その怪しげなdeviceに,同様にbsp/raspberrypi/console.rsで定義されているwrite_fmtを呼び出して1文字列argsを書き込む. bsp::console::console().write_fmt(args).unwrap(); } /// Prints without a newline. /// QEMUの簡易UARTで改行なしで表示するmacroだよ. /// Carbon copy from <https://doc.rust-lang.org/src/std/macros.rs.html> #[macro_export] macro_rules! print { // 上の関数を実行して改行なしの書式で表示するよ. ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); } /// Prints with a newline. /// QEMUの簡易UARTで1行表示するよ. /// Carbon copy from <https://doc.rust-lang.org/src/std/macros.rs.html> #[macro_export] macro_rules! println { // 引数がない場合改行だけ表示するmacroだよ. () => ($crate::print!("\n")); ($($arg:tt)*) => ({ // 上の関数を実行して引数がある場合改行付きの書式で表示するよ. $crate::print::_print(format_args_nl!($($arg)*)); }) }
30.772727
100
0.573855
2f5c72c1107d4ae5b052f85e21d2a9bd324973b8
24,718
use std::collections::HashSet; use std::fmt; use typename::TypeName; use super::{*, ValType::*}; use self::{GlobalOp::*, LoadOp::*, LocalOp::*, StoreOp::*}; /* High-level AST: - types are inlined instead of referenced by type idx (i.e., no manual handling of Type "pool") - Function + Code sections are merged into one list of functions, same for tables: Table + Element sections and memories: Memory + Data sections. - imports and exports are part of the respective item, not stored externally and referring to their item by index. - similar instructions are grouped together, for easier uniform handling, e.g., T.const instructions, loads, stores, and numeric instructions. */ #[derive(Debug, Clone, Default)] pub struct Module { pub functions: Vec<Function>, pub globals: Vec<Global>, pub tables: Vec<Table>, pub memories: Vec<Memory>, pub start: Option<Idx<Function>>, pub custom_sections: Vec<Vec<u8>>, } #[derive(Debug, Clone, TypeName)] pub struct Function { // type is inlined here compared to low-level/binary/spec representation pub type_: FunctionType, // import and code are mutually exclusive, i.e., exactly one of both must be Some(...) pub import: Option<(String, String)>, pub code: Option<Code>, // functions (and other elements) can be exported multiple times under different names pub export: Vec<String>, } #[derive(Debug, Clone, TypeName)] pub struct Global { pub type_: GlobalType, // import and init are mutually exclusive, i.e., exactly one of both must be Some(...) pub import: Option<(String, String)>, pub init: Option<Expr>, pub export: Vec<String>, } #[derive(Debug, Clone, TypeName)] pub struct Table { pub type_: TableType, pub import: Option<(String, String)>, pub elements: Vec<Element>, pub export: Vec<String>, } #[derive(Debug, Clone, TypeName)] pub struct Memory { pub type_: MemoryType, pub import: Option<(String, String)>, pub data: Vec<Data>, pub export: Vec<String>, } #[derive(Debug, Clone)] pub struct Code { pub locals: Vec<ValType>, pub body: Expr, } #[derive(Debug, Clone)] pub struct Element { pub offset: Expr, pub functions: Vec<Idx<Function>>, } #[derive(Debug, Clone)] pub struct Data { pub offset: Expr, pub bytes: Vec<u8>, } pub type Expr = Vec<Instr>; #[derive(Debug, Clone, PartialEq, TypeName)] pub enum Instr { Unreachable, Nop, Block(BlockType), Loop(BlockType), If(BlockType), Else, End, Br(Idx<Label>), BrIf(Idx<Label>), BrTable(Vec<Idx<Label>>, Idx<Label>), Return, Call(Idx<Function>), CallIndirect(FunctionType, Idx<Table>), Drop, Select, Local(LocalOp, Idx<Local>), Global(GlobalOp, Idx<Global>), Load(LoadOp, Memarg), Store(StoreOp, Memarg), MemorySize(Idx<Memory>), MemoryGrow(Idx<Memory>), Const(Val), Numeric(NumericOp), } #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] pub enum LocalOp { LocalGet, LocalSet, LocalTee } #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] pub enum GlobalOp { GlobalGet, GlobalSet } #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] pub enum LoadOp { I32Load, I64Load, F32Load, F64Load, I32Load8S, I32Load8U, I32Load16S, I32Load16U, I64Load8S, I64Load8U, I64Load16S, I64Load16U, I64Load32S, I64Load32U, } #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] pub enum StoreOp { I32Store, I64Store, F32Store, F64Store, I32Store8, I32Store16, I64Store8, I64Store16, I64Store32, } #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] pub enum NumericOp { /* Unary */ I32Eqz, I64Eqz, I32Clz, I32Ctz, I32Popcnt, I64Clz, I64Ctz, I64Popcnt, F32Abs, F32Neg, F32Ceil, F32Floor, F32Trunc, F32Nearest, F32Sqrt, F64Abs, F64Neg, F64Ceil, F64Floor, F64Trunc, F64Nearest, F64Sqrt, I32WrapI64, I32TruncF32S, I32TruncF32U, I32TruncF64S, I32TruncF64U, I64ExtendI32S, I64ExtendI32U, I64TruncF32S, I64TruncF32U, I64TruncF64S, I64TruncF64U, F32ConvertI32S, F32ConvertI32U, F32ConvertI64S, F32ConvertI64U, F32DemoteF64, F64ConvertI32S, F64ConvertI32U, F64ConvertI64S, F64ConvertI64U, F64PromoteF32, I32ReinterpretF32, I64ReinterpretF64, F32ReinterpretI32, F64ReinterpretI64, /* Binary */ I32Eq, I32Ne, I32LtS, I32LtU, I32GtS, I32GtU, I32LeS, I32LeU, I32GeS, I32GeU, I64Eq, I64Ne, I64LtS, I64LtU, I64GtS, I64GtU, I64LeS, I64LeU, I64GeS, I64GeU, F32Eq, F32Ne, F32Lt, F32Gt, F32Le, F32Ge, F64Eq, F64Ne, F64Lt, F64Gt, F64Le, F64Ge, I32Add, I32Sub, I32Mul, I32DivS, I32DivU, I32RemS, I32RemU, I32And, I32Or, I32Xor, I32Shl, I32ShrS, I32ShrU, I32Rotl, I32Rotr, I64Add, I64Sub, I64Mul, I64DivS, I64DivU, I64RemS, I64RemU, I64And, I64Or, I64Xor, I64Shl, I64ShrS, I64ShrU, I64Rotl, I64Rotr, F32Add, F32Sub, F32Mul, F32Div, F32Min, F32Max, F32Copysign, F64Add, F64Sub, F64Mul, F64Div, F64Min, F64Max, F64Copysign, } /* Type information for each instruction */ impl LocalOp { pub fn to_type(&self, local_ty: ValType) -> InstrType { match *self { LocalOp::LocalGet => InstrType::new(&[], &[local_ty]), LocalOp::LocalSet => InstrType::new(&[local_ty], &[]), LocalOp::LocalTee => InstrType::new(&[local_ty], &[local_ty]), } } } impl GlobalOp { pub fn to_type(&self, global_ty: ValType) -> InstrType { match *self { GlobalOp::GlobalGet => InstrType::new(&[], &[global_ty]), GlobalOp::GlobalSet => InstrType::new(&[global_ty], &[]), } } } impl NumericOp { pub fn to_type(&self) -> InstrType { use self::NumericOp::*; match *self { /* Unary */ I32Eqz => InstrType::new(&[I32], &[I32]), I64Eqz => InstrType::new(&[I64], &[I32]), I32Clz | I32Ctz | I32Popcnt => InstrType::new(&[I32], &[I32]), I64Clz | I64Ctz | I64Popcnt => InstrType::new(&[I64], &[I64]), F32Abs | F32Neg | F32Ceil | F32Floor | F32Trunc | F32Nearest | F32Sqrt => InstrType::new(&[F32], &[F32]), F64Abs | F64Neg | F64Ceil | F64Floor | F64Trunc | F64Nearest | F64Sqrt => InstrType::new(&[F64], &[F64]), // conversions I32WrapI64 => InstrType::new(&[I64], &[I32]), I32TruncF32S | I32TruncF32U => InstrType::new(&[F32], &[I32]), I32TruncF64S | I32TruncF64U => InstrType::new(&[F64], &[I32]), I64ExtendI32S | I64ExtendI32U => InstrType::new(&[I32], &[I64]), I64TruncF32S | I64TruncF32U => InstrType::new(&[F32], &[I64]), I64TruncF64S | I64TruncF64U => InstrType::new(&[F64], &[I64]), F32ConvertI32S | F32ConvertI32U => InstrType::new(&[I32], &[F32]), F32ConvertI64S | F32ConvertI64U => InstrType::new(&[I64], &[F32]), F32DemoteF64 => InstrType::new(&[F64], &[F32]), F64ConvertI32S | F64ConvertI32U => InstrType::new(&[I32], &[F64]), F64ConvertI64S | F64ConvertI64U => InstrType::new(&[I64], &[F64]), F64PromoteF32 => InstrType::new(&[F32], &[F64]), I32ReinterpretF32 => InstrType::new(&[F32], &[I32]), I64ReinterpretF64 => InstrType::new(&[F64], &[I64]), F32ReinterpretI32 => InstrType::new(&[I32], &[F32]), F64ReinterpretI64 => InstrType::new(&[I64], &[F64]), /* Binary */ I32Eq | I32Ne | I32LtS | I32LtU | I32GtS | I32GtU | I32LeS | I32LeU | I32GeS | I32GeU => InstrType::new(&[I32, I32], &[I32]), I64Eq | I64Ne | I64LtS | I64LtU | I64GtS | I64GtU | I64LeS | I64LeU | I64GeS | I64GeU => InstrType::new(&[I64, I64], &[I32]), F32Eq | F32Ne | F32Lt | F32Gt | F32Le | F32Ge => InstrType::new(&[F32, F32], &[I32]), F64Eq | F64Ne | F64Lt | F64Gt | F64Le | F64Ge => InstrType::new(&[F64, F64], &[I32]), I32Add | I32Sub | I32Mul | I32DivS | I32DivU | I32RemS | I32RemU | I32And | I32Or | I32Xor | I32Shl | I32ShrS | I32ShrU | I32Rotl | I32Rotr => InstrType::new(&[I32, I32], &[I32]), I64Add | I64Sub | I64Mul | I64DivS | I64DivU | I64RemS | I64RemU | I64And | I64Or | I64Xor | I64Shl | I64ShrS | I64ShrU | I64Rotl | I64Rotr => InstrType::new(&[I64, I64], &[I64]), F32Add | F32Sub | F32Mul | F32Div | F32Min | F32Max | F32Copysign => InstrType::new(&[F32, F32], &[F32]), F64Add | F64Sub | F64Mul | F64Div | F64Min | F64Max | F64Copysign => InstrType::new(&[F64, F64], &[F64]), } } } impl LoadOp { pub fn to_type(&self) -> InstrType { match *self { I32Load => InstrType::new(&[I32], &[I32]), I64Load => InstrType::new(&[I32], &[I64]), F32Load => InstrType::new(&[I32], &[F32]), F64Load => InstrType::new(&[I32], &[F64]), I32Load8S => InstrType::new(&[I32], &[I32]), I32Load8U => InstrType::new(&[I32], &[I32]), I32Load16S => InstrType::new(&[I32], &[I32]), I32Load16U => InstrType::new(&[I32], &[I32]), I64Load8S => InstrType::new(&[I32], &[I64]), I64Load8U => InstrType::new(&[I32], &[I64]), I64Load16S => InstrType::new(&[I32], &[I64]), I64Load16U => InstrType::new(&[I32], &[I64]), I64Load32S => InstrType::new(&[I32], &[I64]), I64Load32U => InstrType::new(&[I32], &[I64]), } } } impl StoreOp { pub fn to_type(&self) -> InstrType { match *self { I32Store => InstrType::new(&[I32, I32], &[]), I64Store => InstrType::new(&[I32, I64], &[]), F32Store => InstrType::new(&[I32, F32], &[]), F64Store => InstrType::new(&[I32, F64], &[]), I32Store8 => InstrType::new(&[I32, I32], &[]), I32Store16 => InstrType::new(&[I32, I32], &[]), I64Store8 => InstrType::new(&[I32, I64], &[]), I64Store16 => InstrType::new(&[I32, I64], &[]), I64Store32 => InstrType::new(&[I32, I64], &[]), } } } impl Instr { /// for all where the type can be determined by just looking at the instruction, not additional /// information like the function or module etc. pub fn to_type(&self) -> Option<InstrType> { use self::Instr::*; match *self { Unreachable | Nop => Some(InstrType::default()), Load(ref op, _) => Some(op.to_type()), Store(ref op, _) => Some(op.to_type()), MemorySize(_) => Some(InstrType::new(&[], &[I32])), MemoryGrow(_) => Some(InstrType::new(&[I32], &[I32])), Const(ref val) => Some(InstrType::new(&[], &[val.to_type()])), Numeric(ref op) => Some(op.to_type()), CallIndirect(ref func_ty, _) => Some(InstrType::new(&[&func_ty.params[..], &[I32]].concat(), &func_ty.results)), // nesting... Block(_) | Loop(_) | If(_) | Else | End => None, // depends on branch target? Br(_) | BrIf(_) | BrTable(_, _) => None, // need to inspect function type Return | Call(_) => None, // need abstract type stack "evaluation" Drop | Select => None, // need lookup in locals/globals Local(_, _) | Global(_, _) => None, } } /// returns instruction name as in Wasm spec pub fn to_name(&self) -> &'static str { use self::Instr::*; use self::NumericOp::*; match *self { Unreachable => "unreachable", Nop => "nop", Block(_) => "block", Loop(_) => "loop", If(_) => "if", Else => "else", End => "end", Br(_) => "br", BrIf(_) => "br_if", BrTable(_, _) => "br_table", Return => "return", Call(_) => "call", CallIndirect(_, _) => "call_indirect", Drop => "drop", Select => "select", Local(LocalGet, _) => "local.get", Local(LocalSet, _) => "local.set", Local(LocalTee, _) => "local.tee", Global(GlobalGet, _) => "global.get", Global(GlobalSet, _) => "global.set", MemorySize(_) => "memory.size", MemoryGrow(_) => "memory.grow", Const(Val::I32(_)) => "i32.const", Const(Val::I64(_)) => "i64.const", Const(Val::F32(_)) => "f32.const", Const(Val::F64(_)) => "f64.const", Load(I32Load, _) => "i32.load", Load(I64Load, _) => "i64.load", Load(F32Load, _) => "f32.load", Load(F64Load, _) => "f64.load", Load(I32Load8S, _) => "i32.load8_s", Load(I32Load8U, _) => "i32.load8_u", Load(I32Load16S, _) => "i32.load16_s", Load(I32Load16U, _) => "i32.load16_u", Load(I64Load8S, _) => "i64.load8_s", Load(I64Load8U, _) => "i64.load8_u", Load(I64Load16S, _) => "i64.load16_s", Load(I64Load16U, _) => "i64.load16_u", Load(I64Load32S, _) => "i64.load32_s", Load(I64Load32U, _) => "i64.load32_u", Store(I32Store, _) => "i32.store", Store(I64Store, _) => "i64.store", Store(F32Store, _) => "f32.store", Store(F64Store, _) => "f64.store", Store(I32Store8, _) => "i32.store8", Store(I32Store16, _) => "i32.store16", Store(I64Store8, _) => "i64.store8", Store(I64Store16, _) => "i64.store16", Store(I64Store32, _) => "i64.store32", Numeric(I32Eqz) => "i32.eqz", Numeric(I64Eqz) => "i64.eqz", Numeric(I32Clz) => "i32.clz", Numeric(I32Ctz) => "i32.ctz", Numeric(I32Popcnt) => "i32.popcnt", Numeric(I64Clz) => "i64.clz", Numeric(I64Ctz) => "i64.ctz", Numeric(I64Popcnt) => "i64.popcnt", Numeric(F32Abs) => "f32.abs", Numeric(F32Neg) => "f32.neg", Numeric(F32Ceil) => "f32.ceil", Numeric(F32Floor) => "f32.floor", Numeric(F32Trunc) => "f32.trunc", Numeric(F32Nearest) => "f32.nearest", Numeric(F32Sqrt) => "f32.sqrt", Numeric(F64Abs) => "f64.abs", Numeric(F64Neg) => "f64.neg", Numeric(F64Ceil) => "f64.ceil", Numeric(F64Floor) => "f64.floor", Numeric(F64Trunc) => "f64.trunc", Numeric(F64Nearest) => "f64.nearest", Numeric(F64Sqrt) => "f64.sqrt", Numeric(I32WrapI64) => "i32.wrap_i64", Numeric(I32TruncF32S) => "i32.trunc_f32_s", Numeric(I32TruncF32U) => "i32.trunc_f32_u", Numeric(I32TruncF64S) => "i32.trunc_f64_s", Numeric(I32TruncF64U) => "i32.trunc_f64_u", Numeric(I64ExtendI32S) => "i64.extend_i32_s", Numeric(I64ExtendI32U) => "i64.extend_i32_u", Numeric(I64TruncF32S) => "i64.trunc_f32_s", Numeric(I64TruncF32U) => "i64.trunc_f32_u", Numeric(I64TruncF64S) => "i64.trunc_f64_s", Numeric(I64TruncF64U) => "i64.trunc_f64_u", Numeric(F32ConvertI32S) => "f32.convert_i32_s", Numeric(F32ConvertI32U) => "f32.convert_i32_u", Numeric(F32ConvertI64S) => "f32.convert_i64_s", Numeric(F32ConvertI64U) => "f32.convert_i64_u", Numeric(F32DemoteF64) => "f32.demote_f64", Numeric(F64ConvertI32S) => "f64.convert_i32_s", Numeric(F64ConvertI32U) => "f64.convert_i32_u", Numeric(F64ConvertI64S) => "f64.convert_i64_s", Numeric(F64ConvertI64U) => "f64.convert_i64_u", Numeric(F64PromoteF32) => "f64.promote_f32", Numeric(I32ReinterpretF32) => "i32.reinterpret_f32", Numeric(I64ReinterpretF64) => "i64.reinterpret_f64", Numeric(F32ReinterpretI32) => "f32.reinterpret_i32", Numeric(F64ReinterpretI64) => "f64.reinterpret_i64", Numeric(I32Eq) => "i32.eq", Numeric(I32Ne) => "i32.ne", Numeric(I32LtS) => "i32.lt_s", Numeric(I32LtU) => "i32.lt_u", Numeric(I32GtS) => "i32.gt_s", Numeric(I32GtU) => "i32.gt_u", Numeric(I32LeS) => "i32.le_s", Numeric(I32LeU) => "i32.le_u", Numeric(I32GeS) => "i32.ge_s", Numeric(I32GeU) => "i32.ge_u", Numeric(I64Eq) => "i64.eq", Numeric(I64Ne) => "i64.ne", Numeric(I64LtS) => "i64.lt_s", Numeric(I64LtU) => "i64.lt_u", Numeric(I64GtS) => "i64.gt_s", Numeric(I64GtU) => "i64.gt_u", Numeric(I64LeS) => "i64.le_s", Numeric(I64LeU) => "i64.le_u", Numeric(I64GeS) => "i64.ge_s", Numeric(I64GeU) => "i64.ge_u", Numeric(F32Eq) => "f32.eq", Numeric(F32Ne) => "f32.ne", Numeric(F32Lt) => "f32.lt", Numeric(F32Gt) => "f32.gt", Numeric(F32Le) => "f32.le", Numeric(F32Ge) => "f32.ge", Numeric(F64Eq) => "f64.eq", Numeric(F64Ne) => "f64.ne", Numeric(F64Lt) => "f64.lt", Numeric(F64Gt) => "f64.gt", Numeric(F64Le) => "f64.le", Numeric(F64Ge) => "f64.ge", Numeric(I32Add) => "i32.add", Numeric(I32Sub) => "i32.sub", Numeric(I32Mul) => "i32.mul", Numeric(I32DivS) => "i32.div_s", Numeric(I32DivU) => "i32.div_u", Numeric(I32RemS) => "i32.rem_s", Numeric(I32RemU) => "i32.rem_u", Numeric(I32And) => "i32.and", Numeric(I32Or) => "i32.or", Numeric(I32Xor) => "i32.xor", Numeric(I32Shl) => "i32.shl", Numeric(I32ShrS) => "i32.shr_s", Numeric(I32ShrU) => "i32.shr_u", Numeric(I32Rotl) => "i32.rotl", Numeric(I32Rotr) => "i32.rotr", Numeric(I64Add) => "i64.add", Numeric(I64Sub) => "i64.sub", Numeric(I64Mul) => "i64.mul", Numeric(I64DivS) => "i64.div_s", Numeric(I64DivU) => "i64.div_u", Numeric(I64RemS) => "i64.rem_s", Numeric(I64RemU) => "i64.rem_u", Numeric(I64And) => "i64.and", Numeric(I64Or) => "i64.or", Numeric(I64Xor) => "i64.xor", Numeric(I64Shl) => "i64.shl", Numeric(I64ShrS) => "i64.shr_s", Numeric(I64ShrU) => "i64.shr_u", Numeric(I64Rotl) => "i64.rotl", Numeric(I64Rotr) => "i64.rotr", Numeric(F32Add) => "f32.add", Numeric(F32Sub) => "f32.sub", Numeric(F32Mul) => "f32.mul", Numeric(F32Div) => "f32.div", Numeric(F32Min) => "f32.min", Numeric(F32Max) => "f32.max", Numeric(F32Copysign) => "f32.copysign", Numeric(F64Add) => "f64.add", Numeric(F64Sub) => "f64.sub", Numeric(F64Mul) => "f64.mul", Numeric(F64Div) => "f64.div", Numeric(F64Min) => "f64.min", Numeric(F64Max) => "f64.max", Numeric(F64Copysign) => "f64.copysign", } } } impl fmt::Display for Instr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.to_name())?; // add arguments if instructions has any use self::Instr::*; match self { // instructions without arguments Unreachable | Nop | Drop | Select | Return | Block(_) | Loop(_) | If(_) | Else | End | MemorySize(_) | MemoryGrow(_) | Numeric(_) => Ok(()), Br(label) => write!(f, " {}", label.0), BrIf(label) => write!(f, " {}", label.0), BrTable(table, default_label) => { for label in table { write!(f, " {}", label.0)?; } write!(f, " {}", default_label.0) } Call(func_idx) => write!(f, " {}", func_idx.0), CallIndirect(_, table_idx) => write!(f, " {}", table_idx.0), Local(_, local_idx) => write!(f, " {}", local_idx.0), Global(_, global_idx) => write!(f, " {}", global_idx.0), Load(_, memarg) | Store(_, memarg) => { if memarg.offset != 0 { write!(f, " offset={}", memarg.offset)?; } if memarg.alignment != 0 { write!(f, " align={}", memarg.alignment)?; } Ok(()) } Const(val) => write!(f, " {}", val) } } } /* Impls/functions for typical use cases on WASM modules. */ impl Module { pub fn add_function(&mut self, type_: FunctionType, locals: Vec<ValType>, body: Vec<Instr>) -> Idx<Function> { self.functions.push(Function { type_, import: None, code: Some(Code { locals, body, }), export: Vec::new(), }); (self.functions.len() - 1).into() } pub fn add_function_import(&mut self, type_: FunctionType, module: String, name: String) -> Idx<Function> { self.functions.push(Function { type_, import: Some((module, name)), code: None, export: Vec::new(), }); (self.functions.len() - 1).into() } pub fn add_global(&mut self, type_: ValType, mut_: Mutability, init: Vec<Instr>) -> Idx<Global> { self.globals.push(Global { type_: GlobalType(type_, mut_), import: None, init: Some(init), export: Vec::new(), }); (self.globals.len() - 1).into() } pub fn function(&mut self, idx: Idx<Function>) -> &mut Function { &mut self.functions[idx.0] } pub fn functions(&mut self) -> impl Iterator<Item=(Idx<Function>, &mut Function)> { self.functions.iter_mut().enumerate().map(|(i, f)| (i.into(), f)) } pub fn types(&self) -> HashSet<&FunctionType> { let mut types = HashSet::new(); for function in &self.functions { types.insert(&function.type_); } types } } impl Function { pub fn instructions(&mut self) -> impl Iterator<Item=(Idx<Instr>, &mut Instr)> { self.code.iter_mut().flat_map(|code| code.body.iter_mut().enumerate().map(|(i, f)| (i.into(), f))) } pub fn modify_instr(&mut self, f: impl Fn(Instr) -> Vec<Instr>) { if let Some(Code { ref mut body, .. }) = self.code { let new_body = Vec::with_capacity(body.len()); let old_body = ::std::mem::replace(body, new_body); for instr in old_body.into_iter() { body.append(&mut f(instr)); } } } /// add a new local with type ty and return its index pub fn add_fresh_local(&mut self, ty: ValType) -> Idx<Local> { let locals = &mut self.code.as_mut() .expect("cannot add local to imported function") .locals; let idx = locals.len() + self.type_.params.len(); locals.push(ty); idx.into() } pub fn add_fresh_locals(&mut self, tys: &[ValType]) -> Vec<Idx<Local>> { tys.iter() .map(|ty| self.add_fresh_local(*ty)) .collect() } /// get type of the local with index idx pub fn local_type(&self, idx: Idx<Local>) -> ValType { let param_count = self.type_.params.len(); if (idx.0) < param_count { self.type_.params[idx.0] } else { let locals = &self.code.as_ref() .expect("cannot get type of a local in an imported function") .locals; *locals.get(idx.0 - param_count) .expect(&format!("invalid local index {}, function has {} parameters and {} locals", idx.0, param_count, locals.len())) } } pub fn instr_count(&self) -> usize { self.code.as_ref().map(|code| code.body.len()).unwrap_or(0) } }
32.101299
191
0.529533
e5b4a57a023654e9fcd935d13cdab9f519d08bef
2,246
//////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2018, the Perspective Authors. // // This file is part of the Perspective library, distributed under the terms // of the Apache License 2.0. The full license can be found in the LICENSE // file. use std::cell::RefCell; use std::collections::VecDeque; use std::future::Future; use std::rc::Rc; use web_sys::*; #[derive(Default, Clone)] pub struct MovingWindowRenderTimer(Rc<RefCell<RenderTimerType>>); enum RenderTimerType { Moving(VecDeque<f64>), Constant(f64), } impl Default for RenderTimerType { fn default() -> RenderTimerType { RenderTimerType::Moving(VecDeque::new()) } } impl MovingWindowRenderTimer { pub async fn capture_time<T>(&self, f: impl Future<Output = T>) -> T { let perf = window().unwrap().performance().unwrap(); let start = match *self.0.borrow() { RenderTimerType::Constant(_) => 0_f64, RenderTimerType::Moving(_) => perf.now(), }; let result = f.await; match &mut *self.0.borrow_mut() { RenderTimerType::Moving(timings) => { timings.push_back(perf.now() - start); if timings.len() > 5 { timings.pop_front(); } } RenderTimerType::Constant(_) => (), }; result } pub fn set_throttle(&mut self, val: Option<f64>) { match val { None => { *self.0.borrow_mut() = RenderTimerType::default(); } Some(val) => { *self.0.borrow_mut() = RenderTimerType::Constant(val); } } } pub fn get_avg(&self) -> i32 { match &*self.0.borrow() { RenderTimerType::Constant(constant) => *constant as i32, RenderTimerType::Moving(timings) => { let len = timings.len(); if len < 5 { 0_i32 } else { let sum = timings.iter().sum::<f64>(); let avg: f64 = sum / len as f64; f64::min(5000_f64, avg.floor()) as i32 } } } } }
28.794872
80
0.501781
ab62461475db5cc0167c8a1756531bacf70c7ae0
240
// Copyright 2020-2021 The FuseQuery Authors. // // SPDX-License-Identifier: Apache-2.0. pub static METRIC_SESSION_CONNECT_NUMBERS: &str = "session.connect_numbers"; pub static METRIC_SESSION_CLOSE_NUMBERS: &str = "session.close_numbers";
34.285714
76
0.7875
f7cd8fb700a1face61432eb4346d39cd9f1e28dd
2,778
//! Adds support for automatic Breadcrumb, Event and Transaction capturing from //! tracing events, similar to the `sentry-log` crate. //! //! The `tracing` crate is supported in three ways. First, events can be captured //! as breadcrumbs for later. Secondly, error events can be captured as events //! to Sentry. Finally, spans can be recorded as structured transaction events. //! By default, events above `Info` are recorded as breadcrumbs, events above //! `Error` are captured as error events, and spans above `Info` are recorded //! as transactions. //! //! By using this crate in combination with `tracing-subscriber` and its `log` //! integration, `sentry-log` does not need to be used, as logs will be ingested //! in the tracing system and generate events, thus be relayed to this crate. It //! effectively replaces `sentry-log` when tracing is used. //! //! # Examples //! //! ```rust //! use std::time::Duration; //! //! use tokio::time::sleep; //! use tracing_subscriber::prelude::*; //! //! #[tokio::main] //! async fn main() { //! let _guard = sentry::init(sentry::ClientOptions { //! // Set this a to lower value in production //! traces_sample_rate: 1.0, //! ..sentry::ClientOptions::default() //! }); //! //! tracing_subscriber::registry() //! .with(tracing_subscriber::fmt::layer()) //! .with(sentry_tracing::layer()) //! .init(); //! //! outer().await; //! } //! //! // Functions instrumented by tracing automatically report //! // their span as transactions //! #[tracing::instrument] //! async fn outer() { //! tracing::info!("Generates a breadcrumb"); //! //! for _ in 0..10 { //! inner().await; //! } //! //! tracing::error!("Generates an event"); //! } //! //! #[tracing::instrument] //! async fn inner() { //! // Also works, since log events are ingested by the tracing system //! log::info!("Generates a breadcrumb"); //! //! sleep(Duration::from_millis(100)).await; //! //! log::error!("Generates an event"); //! } //! ``` //! //! Or one might also set an explicit filter, to customize how to treat log //! records: //! //! ```rust //! use sentry_tracing::EventFilter; //! use tracing_subscriber::prelude::*; //! //! let layer = sentry_tracing::layer().event_filter(|md| match md.level() { //! &tracing::Level::ERROR => EventFilter::Event, //! _ => EventFilter::Ignore, //! }); //! //! tracing_subscriber::registry() //! .with(layer) //! .init(); //! ``` #![doc(html_favicon_url = "https://sentry-brand.storage.googleapis.com/favicon.ico")] #![doc(html_logo_url = "https://sentry-brand.storage.googleapis.com/sentry-glyph-black.png")] #![warn(missing_docs)] mod converters; mod layer; pub use converters::*; pub use layer::*;
30.866667
93
0.632109
38ee7446a52c2f8437642cf7ace28080039245f9
106,276
use alloc::vec::Vec; use core::fmt; use core::result; use crate::common::{ DebugLineOffset, DebugLineStrOffset, DebugStrOffset, DebugStrOffsetsIndex, Encoding, Format, LineEncoding, SectionId, }; use crate::constants; use crate::endianity::Endianity; use crate::read::{AttributeValue, EndianSlice, Error, Reader, ReaderOffset, Result, Section}; /// The `DebugLine` struct contains the source location to instruction mapping /// found in the `.debug_line` section. #[derive(Debug, Default, Clone, Copy)] pub struct DebugLine<R> { debug_line_section: R, } impl<'input, Endian> DebugLine<EndianSlice<'input, Endian>> where Endian: Endianity, { /// Construct a new `DebugLine` instance from the data in the `.debug_line` /// section. /// /// It is the caller's responsibility to read the `.debug_line` section and /// present it as a `&[u8]` slice. That means using some ELF loader on /// Linux, a Mach-O loader on OSX, etc. /// /// ``` /// use gimli::{DebugLine, LittleEndian}; /// /// # let buf = [0x00, 0x01, 0x02, 0x03]; /// # let read_debug_line_section_somehow = || &buf; /// let debug_line = DebugLine::new(read_debug_line_section_somehow(), LittleEndian); /// ``` pub fn new(debug_line_section: &'input [u8], endian: Endian) -> Self { Self::from(EndianSlice::new(debug_line_section, endian)) } } impl<R: Reader> DebugLine<R> { /// Parse the line number program whose header is at the given `offset` in the /// `.debug_line` section. /// /// The `address_size` must match the compilation unit that the lines apply to. /// The `comp_dir` should be from the `DW_AT_comp_dir` attribute of the compilation /// unit. The `comp_name` should be from the `DW_AT_name` attribute of the /// compilation unit. /// /// ```rust,no_run /// use gimli::{DebugLine, DebugLineOffset, IncompleteLineProgram, EndianSlice, LittleEndian}; /// /// # let buf = []; /// # let read_debug_line_section_somehow = || &buf; /// let debug_line = DebugLine::new(read_debug_line_section_somehow(), LittleEndian); /// /// // In a real example, we'd grab the offset via a compilation unit /// // entry's `DW_AT_stmt_list` attribute, and the address size from that /// // unit directly. /// let offset = DebugLineOffset(0); /// let address_size = 8; /// /// let program = debug_line.program(offset, address_size, None, None) /// .expect("should have found a header at that offset, and parsed it OK"); /// ``` pub fn program( &self, offset: DebugLineOffset<R::Offset>, address_size: u8, comp_dir: Option<R>, comp_name: Option<R>, ) -> Result<IncompleteLineProgram<R>> { let input = &mut self.debug_line_section.clone(); input.skip(offset.0)?; let header = LineProgramHeader::parse(input, offset, address_size, comp_dir, comp_name)?; let program = IncompleteLineProgram { header }; Ok(program) } } impl<T> DebugLine<T> { /// Create a `DebugLine` section that references the data in `self`. /// /// This is useful when `R` implements `Reader` but `T` does not. /// /// ## Example Usage /// /// ```rust,no_run /// # let load_section = || unimplemented!(); /// // Read the DWARF section into a `Vec` with whatever object loader you're using. /// let owned_section: gimli::DebugLine<Vec<u8>> = load_section(); /// // Create a reference to the DWARF section. /// let section = owned_section.borrow(|section| { /// gimli::EndianSlice::new(&section, gimli::LittleEndian) /// }); /// ``` pub fn borrow<'a, F, R>(&'a self, mut borrow: F) -> DebugLine<R> where F: FnMut(&'a T) -> R, { borrow(&self.debug_line_section).into() } } impl<R> Section<R> for DebugLine<R> { fn id() -> SectionId { SectionId::DebugLine } fn reader(&self) -> &R { &self.debug_line_section } } impl<R> From<R> for DebugLine<R> { fn from(debug_line_section: R) -> Self { DebugLine { debug_line_section } } } /// Deprecated. `LineNumberProgram` has been renamed to `LineProgram`. #[deprecated(note = "LineNumberProgram has been renamed to LineProgram, use that instead.")] pub type LineNumberProgram<R, Offset> = dyn LineProgram<R, Offset>; /// A `LineProgram` provides access to a `LineProgramHeader` and /// a way to add files to the files table if necessary. Gimli consumers should /// never need to use or see this trait. pub trait LineProgram<R, Offset = <R as Reader>::Offset> where R: Reader<Offset = Offset>, Offset: ReaderOffset, { /// Get a reference to the held `LineProgramHeader`. fn header(&self) -> &LineProgramHeader<R, Offset>; /// Add a file to the file table if necessary. fn add_file(&mut self, file: FileEntry<R, Offset>); } impl<R, Offset> LineProgram<R, Offset> for IncompleteLineProgram<R, Offset> where R: Reader<Offset = Offset>, Offset: ReaderOffset, { fn header(&self) -> &LineProgramHeader<R, Offset> { &self.header } fn add_file(&mut self, file: FileEntry<R, Offset>) { self.header.file_names.push(file); } } impl<'program, R, Offset> LineProgram<R, Offset> for &'program CompleteLineProgram<R, Offset> where R: Reader<Offset = Offset>, Offset: ReaderOffset, { fn header(&self) -> &LineProgramHeader<R, Offset> { &self.header } fn add_file(&mut self, _: FileEntry<R, Offset>) { // Nop. Our file table is already complete. } } /// Deprecated. `StateMachine` has been renamed to `LineRows`. #[deprecated(note = "StateMachine has been renamed to LineRows, use that instead.")] pub type StateMachine<R, Program, Offset> = LineRows<R, Program, Offset>; /// Executes a `LineProgram` to iterate over the rows in the matrix of line number information. /// /// "The hypothetical machine used by a consumer of the line number information /// to expand the byte-coded instruction stream into a matrix of line number /// information." -- Section 6.2.1 #[derive(Debug, Clone)] pub struct LineRows<R, Program, Offset = <R as Reader>::Offset> where Program: LineProgram<R, Offset>, R: Reader<Offset = Offset>, Offset: ReaderOffset, { program: Program, row: LineRow, instructions: LineInstructions<R>, } type OneShotLineRows<R, Offset = <R as Reader>::Offset> = LineRows<R, IncompleteLineProgram<R, Offset>, Offset>; type ResumedLineRows<'program, R, Offset = <R as Reader>::Offset> = LineRows<R, &'program CompleteLineProgram<R, Offset>, Offset>; impl<R, Program, Offset> LineRows<R, Program, Offset> where Program: LineProgram<R, Offset>, R: Reader<Offset = Offset>, Offset: ReaderOffset, { #[allow(clippy::new_ret_no_self)] fn new(program: IncompleteLineProgram<R, Offset>) -> OneShotLineRows<R, Offset> { let row = LineRow::new(program.header()); let instructions = LineInstructions { input: program.header().program_buf.clone(), }; LineRows { program, row, instructions, } } fn resume<'program>( program: &'program CompleteLineProgram<R, Offset>, sequence: &LineSequence<R>, ) -> ResumedLineRows<'program, R, Offset> { let row = LineRow::new(program.header()); let instructions = sequence.instructions.clone(); LineRows { program, row, instructions, } } /// Get a reference to the header for this state machine's line number /// program. #[inline] pub fn header(&self) -> &LineProgramHeader<R, Offset> { self.program.header() } /// Parse and execute the next instructions in the line number program until /// another row in the line number matrix is computed. /// /// The freshly computed row is returned as `Ok(Some((header, row)))`. /// If the matrix is complete, and there are no more new rows in the line /// number matrix, then `Ok(None)` is returned. If there was an error parsing /// an instruction, then `Err(e)` is returned. /// /// Unfortunately, the references mean that this cannot be a /// `FallibleIterator`. pub fn next_row(&mut self) -> Result<Option<(&LineProgramHeader<R, Offset>, &LineRow)>> { // Perform any reset that was required after copying the previous row. self.row.reset(self.program.header()); loop { // Split the borrow here, rather than calling `self.header()`. match self.instructions.next_instruction(self.program.header()) { Err(err) => return Err(err), Ok(None) => return Ok(None), Ok(Some(instruction)) => { if self.row.execute(instruction, &mut self.program) { return Ok(Some((self.header(), &self.row))); } // Fall through, parse the next instruction, and see if that // yields a row. } } } } } /// Deprecated. `Opcode` has been renamed to `LineInstruction`. #[deprecated(note = "Opcode has been renamed to LineInstruction, use that instead.")] pub type Opcode<R> = LineInstruction<R, <R as Reader>::Offset>; /// A parsed line number program instruction. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum LineInstruction<R, Offset = <R as Reader>::Offset> where R: Reader<Offset = Offset>, Offset: ReaderOffset, { /// > ### 6.2.5.1 Special Opcodes /// > /// > Each ubyte special opcode has the following effect on the state machine: /// > /// > 1. Add a signed integer to the line register. /// > /// > 2. Modify the operation pointer by incrementing the address and /// > op_index registers as described below. /// > /// > 3. Append a row to the matrix using the current values of the state /// > machine registers. /// > /// > 4. Set the basic_block register to “false.” /// > /// > 5. Set the prologue_end register to “false.” /// > /// > 6. Set the epilogue_begin register to “false.” /// > /// > 7. Set the discriminator register to 0. /// > /// > All of the special opcodes do those same seven things; they differ from /// > one another only in what values they add to the line, address and /// > op_index registers. Special(u8), /// "[`LineInstruction::Copy`] appends a row to the matrix using the current /// values of the state machine registers. Then it sets the discriminator /// register to 0, and sets the basic_block, prologue_end and epilogue_begin /// registers to “false.”" Copy, /// "The DW_LNS_advance_pc opcode takes a single unsigned LEB128 operand as /// the operation advance and modifies the address and op_index registers /// [the same as `LineInstruction::Special`]" AdvancePc(u64), /// "The DW_LNS_advance_line opcode takes a single signed LEB128 operand and /// adds that value to the line register of the state machine." AdvanceLine(i64), /// "The DW_LNS_set_file opcode takes a single unsigned LEB128 operand and /// stores it in the file register of the state machine." SetFile(u64), /// "The DW_LNS_set_column opcode takes a single unsigned LEB128 operand and /// stores it in the column register of the state machine." SetColumn(u64), /// "The DW_LNS_negate_stmt opcode takes no operands. It sets the is_stmt /// register of the state machine to the logical negation of its current /// value." NegateStatement, /// "The DW_LNS_set_basic_block opcode takes no operands. It sets the /// basic_block register of the state machine to “true.”" SetBasicBlock, /// > The DW_LNS_const_add_pc opcode takes no operands. It advances the /// > address and op_index registers by the increments corresponding to /// > special opcode 255. /// > /// > When the line number program needs to advance the address by a small /// > amount, it can use a single special opcode, which occupies a single /// > byte. When it needs to advance the address by up to twice the range of /// > the last special opcode, it can use DW_LNS_const_add_pc followed by a /// > special opcode, for a total of two bytes. Only if it needs to advance /// > the address by more than twice that range will it need to use both /// > DW_LNS_advance_pc and a special opcode, requiring three or more bytes. ConstAddPc, /// > The DW_LNS_fixed_advance_pc opcode takes a single uhalf (unencoded) /// > operand and adds it to the address register of the state machine and /// > sets the op_index register to 0. This is the only standard opcode whose /// > operand is not a variable length number. It also does not multiply the /// > operand by the minimum_instruction_length field of the header. FixedAddPc(u16), /// "[`LineInstruction::SetPrologueEnd`] sets the prologue_end register to “true”." SetPrologueEnd, /// "[`LineInstruction::SetEpilogueBegin`] sets the epilogue_begin register to /// “true”." SetEpilogueBegin, /// "The DW_LNS_set_isa opcode takes a single unsigned LEB128 operand and /// stores that value in the isa register of the state machine." SetIsa(u64), /// An unknown standard opcode with zero operands. UnknownStandard0(constants::DwLns), /// An unknown standard opcode with one operand. UnknownStandard1(constants::DwLns, u64), /// An unknown standard opcode with multiple operands. UnknownStandardN(constants::DwLns, R), /// > [`LineInstruction::EndSequence`] sets the end_sequence register of the state /// > machine to “true” and appends a row to the matrix using the current /// > values of the state-machine registers. Then it resets the registers to /// > the initial values specified above (see Section 6.2.2). Every line /// > number program sequence must end with a DW_LNE_end_sequence instruction /// > which creates a row whose address is that of the byte after the last /// > target machine instruction of the sequence. EndSequence, /// > The DW_LNE_set_address opcode takes a single relocatable address as an /// > operand. The size of the operand is the size of an address on the target /// > machine. It sets the address register to the value given by the /// > relocatable address and sets the op_index register to 0. /// > /// > All of the other line number program opcodes that affect the address /// > register add a delta to it. This instruction stores a relocatable value /// > into it instead. SetAddress(u64), /// Defines a new source file in the line number program and appends it to /// the line number program header's list of source files. DefineFile(FileEntry<R, Offset>), /// "The DW_LNE_set_discriminator opcode takes a single parameter, an /// unsigned LEB128 integer. It sets the discriminator register to the new /// value." SetDiscriminator(u64), /// An unknown extended opcode and the slice of its unparsed operands. UnknownExtended(constants::DwLne, R), } impl<R, Offset> LineInstruction<R, Offset> where R: Reader<Offset = Offset>, Offset: ReaderOffset, { fn parse<'header>( header: &'header LineProgramHeader<R>, input: &mut R, ) -> Result<LineInstruction<R>> where R: 'header, { let opcode = input.read_u8()?; if opcode == 0 { let length = input.read_uleb128().and_then(R::Offset::from_u64)?; let mut instr_rest = input.split(length)?; let opcode = instr_rest.read_u8()?; match constants::DwLne(opcode) { constants::DW_LNE_end_sequence => Ok(LineInstruction::EndSequence), constants::DW_LNE_set_address => { let address = instr_rest.read_address(header.address_size())?; Ok(LineInstruction::SetAddress(address)) } constants::DW_LNE_define_file => { if header.version() <= 4 { let path_name = instr_rest.read_null_terminated_slice()?; let entry = FileEntry::parse(&mut instr_rest, path_name)?; Ok(LineInstruction::DefineFile(entry)) } else { Ok(LineInstruction::UnknownExtended( constants::DW_LNE_define_file, instr_rest, )) } } constants::DW_LNE_set_discriminator => { let discriminator = instr_rest.read_uleb128()?; Ok(LineInstruction::SetDiscriminator(discriminator)) } otherwise => Ok(LineInstruction::UnknownExtended(otherwise, instr_rest)), } } else if opcode >= header.opcode_base { Ok(LineInstruction::Special(opcode)) } else { match constants::DwLns(opcode) { constants::DW_LNS_copy => Ok(LineInstruction::Copy), constants::DW_LNS_advance_pc => { let advance = input.read_uleb128()?; Ok(LineInstruction::AdvancePc(advance)) } constants::DW_LNS_advance_line => { let increment = input.read_sleb128()?; Ok(LineInstruction::AdvanceLine(increment)) } constants::DW_LNS_set_file => { let file = input.read_uleb128()?; Ok(LineInstruction::SetFile(file)) } constants::DW_LNS_set_column => { let column = input.read_uleb128()?; Ok(LineInstruction::SetColumn(column)) } constants::DW_LNS_negate_stmt => Ok(LineInstruction::NegateStatement), constants::DW_LNS_set_basic_block => Ok(LineInstruction::SetBasicBlock), constants::DW_LNS_const_add_pc => Ok(LineInstruction::ConstAddPc), constants::DW_LNS_fixed_advance_pc => { let advance = input.read_u16()?; Ok(LineInstruction::FixedAddPc(advance)) } constants::DW_LNS_set_prologue_end => Ok(LineInstruction::SetPrologueEnd), constants::DW_LNS_set_epilogue_begin => Ok(LineInstruction::SetEpilogueBegin), constants::DW_LNS_set_isa => { let isa = input.read_uleb128()?; Ok(LineInstruction::SetIsa(isa)) } otherwise => { let mut opcode_lengths = header.standard_opcode_lengths().clone(); opcode_lengths.skip(R::Offset::from_u8(opcode - 1))?; let num_args = opcode_lengths.read_u8()? as usize; match num_args { 0 => Ok(LineInstruction::UnknownStandard0(otherwise)), 1 => { let arg = input.read_uleb128()?; Ok(LineInstruction::UnknownStandard1(otherwise, arg)) } _ => { let mut args = input.clone(); for _ in 0..num_args { input.read_uleb128()?; } let len = input.offset_from(&args); args.truncate(len)?; Ok(LineInstruction::UnknownStandardN(otherwise, args)) } } } } } } } impl<R, Offset> fmt::Display for LineInstruction<R, Offset> where R: Reader<Offset = Offset>, Offset: ReaderOffset, { fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> { match *self { LineInstruction::Special(opcode) => write!(f, "Special opcode {}", opcode), LineInstruction::Copy => write!(f, "{}", constants::DW_LNS_copy), LineInstruction::AdvancePc(advance) => { write!(f, "{} by {}", constants::DW_LNS_advance_pc, advance) } LineInstruction::AdvanceLine(increment) => { write!(f, "{} by {}", constants::DW_LNS_advance_line, increment) } LineInstruction::SetFile(file) => { write!(f, "{} to {}", constants::DW_LNS_set_file, file) } LineInstruction::SetColumn(column) => { write!(f, "{} to {}", constants::DW_LNS_set_column, column) } LineInstruction::NegateStatement => write!(f, "{}", constants::DW_LNS_negate_stmt), LineInstruction::SetBasicBlock => write!(f, "{}", constants::DW_LNS_set_basic_block), LineInstruction::ConstAddPc => write!(f, "{}", constants::DW_LNS_const_add_pc), LineInstruction::FixedAddPc(advance) => { write!(f, "{} by {}", constants::DW_LNS_fixed_advance_pc, advance) } LineInstruction::SetPrologueEnd => write!(f, "{}", constants::DW_LNS_set_prologue_end), LineInstruction::SetEpilogueBegin => { write!(f, "{}", constants::DW_LNS_set_epilogue_begin) } LineInstruction::SetIsa(isa) => write!(f, "{} to {}", constants::DW_LNS_set_isa, isa), LineInstruction::UnknownStandard0(opcode) => write!(f, "Unknown {}", opcode), LineInstruction::UnknownStandard1(opcode, arg) => { write!(f, "Unknown {} with operand {}", opcode, arg) } LineInstruction::UnknownStandardN(opcode, ref args) => { write!(f, "Unknown {} with operands {:?}", opcode, args) } LineInstruction::EndSequence => write!(f, "{}", constants::DW_LNE_end_sequence), LineInstruction::SetAddress(address) => { write!(f, "{} to {}", constants::DW_LNE_set_address, address) } LineInstruction::DefineFile(_) => write!(f, "{}", constants::DW_LNE_define_file), LineInstruction::SetDiscriminator(discr) => { write!(f, "{} to {}", constants::DW_LNE_set_discriminator, discr) } LineInstruction::UnknownExtended(opcode, _) => write!(f, "Unknown {}", opcode), } } } /// Deprecated. `OpcodesIter` has been renamed to `LineInstructions`. #[deprecated(note = "OpcodesIter has been renamed to LineInstructions, use that instead.")] pub type OpcodesIter<R> = LineInstructions<R>; /// An iterator yielding parsed instructions. /// /// See /// [`LineProgramHeader::instructions`](./struct.LineProgramHeader.html#method.instructions) /// for more details. #[derive(Clone, Debug)] pub struct LineInstructions<R: Reader> { input: R, } impl<R: Reader> LineInstructions<R> { fn remove_trailing(&self, other: &LineInstructions<R>) -> Result<LineInstructions<R>> { let offset = other.input.offset_from(&self.input); let mut input = self.input.clone(); input.truncate(offset)?; Ok(LineInstructions { input }) } } impl<R: Reader> LineInstructions<R> { /// Advance the iterator and return the next instruction. /// /// Returns the newly parsed instruction as `Ok(Some(instruction))`. Returns /// `Ok(None)` when iteration is complete and all instructions have already been /// parsed and yielded. If an error occurs while parsing the next attribute, /// then this error is returned as `Err(e)`, and all subsequent calls return /// `Ok(None)`. /// /// Unfortunately, the `header` parameter means that this cannot be a /// `FallibleIterator`. #[allow(clippy::inline_always)] #[inline(always)] pub fn next_instruction( &mut self, header: &LineProgramHeader<R>, ) -> Result<Option<LineInstruction<R>>> { if self.input.is_empty() { return Ok(None); } match LineInstruction::parse(header, &mut self.input) { Ok(instruction) => Ok(Some(instruction)), Err(e) => { self.input.empty(); Err(e) } } } } /// Deprecated. `LineNumberRow` has been renamed to `LineRow`. #[deprecated(note = "LineNumberRow has been renamed to LineRow, use that instead.")] pub type LineNumberRow = LineRow; /// A row in the line number program's resulting matrix. /// /// Each row is a copy of the registers of the state machine, as defined in section 6.2.2. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct LineRow { address: u64, op_index: u64, file: u64, line: u64, column: u64, is_stmt: bool, basic_block: bool, end_sequence: bool, prologue_end: bool, epilogue_begin: bool, isa: u64, discriminator: u64, } impl LineRow { /// Create a line number row in the initial state for the given program. pub fn new<R: Reader>(header: &LineProgramHeader<R>) -> Self { LineRow { // "At the beginning of each sequence within a line number program, the // state of the registers is:" -- Section 6.2.2 address: 0, op_index: 0, file: 1, line: 1, column: 0, // "determined by default_is_stmt in the line number program header" is_stmt: header.line_encoding.default_is_stmt, basic_block: false, end_sequence: false, prologue_end: false, epilogue_begin: false, // "The isa value 0 specifies that the instruction set is the // architecturally determined default instruction set. This may be fixed // by the ABI, or it may be specified by other means, for example, by // the object file description." isa: 0, discriminator: 0, } } /// "The program-counter value corresponding to a machine instruction /// generated by the compiler." #[inline] pub fn address(&self) -> u64 { self.address } /// > An unsigned integer representing the index of an operation within a VLIW /// > instruction. The index of the first operation is 0. For non-VLIW /// > architectures, this register will always be 0. /// > /// > The address and op_index registers, taken together, form an operation /// > pointer that can reference any individual operation with the /// > instruction stream. #[inline] pub fn op_index(&self) -> u64 { self.op_index } /// "An unsigned integer indicating the identity of the source file /// corresponding to a machine instruction." #[inline] pub fn file_index(&self) -> u64 { self.file } /// The source file corresponding to the current machine instruction. #[inline] pub fn file<'header, R: Reader>( &self, header: &'header LineProgramHeader<R>, ) -> Option<&'header FileEntry<R>> { header.file(self.file) } /// "An unsigned integer indicating a source line number. Lines are numbered /// beginning at 1. The compiler may emit the value 0 in cases where an /// instruction cannot be attributed to any source line." #[inline] pub fn line(&self) -> Option<u64> { if self.line == 0 { None } else { Some(self.line) } } /// "An unsigned integer indicating a column number within a source /// line. Columns are numbered beginning at 1. The value 0 is reserved to /// indicate that a statement begins at the “left edge” of the line." #[inline] pub fn column(&self) -> ColumnType { if self.column == 0 { ColumnType::LeftEdge } else { ColumnType::Column(self.column) } } /// "A boolean indicating that the current instruction is a recommended /// breakpoint location. A recommended breakpoint location is intended to /// “represent” a line, a statement and/or a semantically distinct subpart /// of a statement." #[inline] pub fn is_stmt(&self) -> bool { self.is_stmt } /// "A boolean indicating that the current instruction is the beginning of a /// basic block." #[inline] pub fn basic_block(&self) -> bool { self.basic_block } /// "A boolean indicating that the current address is that of the first byte /// after the end of a sequence of target machine instructions. end_sequence /// terminates a sequence of lines; therefore other information in the same /// row is not meaningful." #[inline] pub fn end_sequence(&self) -> bool { self.end_sequence } /// "A boolean indicating that the current address is one (of possibly many) /// where execution should be suspended for an entry breakpoint of a /// function." #[inline] pub fn prologue_end(&self) -> bool { self.prologue_end } /// "A boolean indicating that the current address is one (of possibly many) /// where execution should be suspended for an exit breakpoint of a /// function." #[inline] pub fn epilogue_begin(&self) -> bool { self.epilogue_begin } /// Tag for the current instruction set architecture. /// /// > An unsigned integer whose value encodes the applicable instruction set /// > architecture for the current instruction. /// > /// > The encoding of instruction sets should be shared by all users of a /// > given architecture. It is recommended that this encoding be defined by /// > the ABI authoring committee for each architecture. #[inline] pub fn isa(&self) -> u64 { self.isa } /// "An unsigned integer identifying the block to which the current /// instruction belongs. Discriminator values are assigned arbitrarily by /// the DWARF producer and serve to distinguish among multiple blocks that /// may all be associated with the same source file, line, and column. Where /// only one block exists for a given source position, the discriminator /// value should be zero." #[inline] pub fn discriminator(&self) -> u64 { self.discriminator } /// Execute the given instruction, and return true if a new row in the /// line number matrix needs to be generated. /// /// Unknown opcodes are treated as no-ops. #[inline] pub fn execute<R, Program>( &mut self, instruction: LineInstruction<R>, program: &mut Program, ) -> bool where Program: LineProgram<R>, R: Reader, { match instruction { LineInstruction::Special(opcode) => { self.exec_special_opcode(opcode, program.header()); true } LineInstruction::Copy => true, LineInstruction::AdvancePc(operation_advance) => { self.apply_operation_advance(operation_advance, program.header()); false } LineInstruction::AdvanceLine(line_increment) => { self.apply_line_advance(line_increment); false } LineInstruction::SetFile(file) => { self.file = file; false } LineInstruction::SetColumn(column) => { self.column = column; false } LineInstruction::NegateStatement => { self.is_stmt = !self.is_stmt; false } LineInstruction::SetBasicBlock => { self.basic_block = true; false } LineInstruction::ConstAddPc => { let adjusted = self.adjust_opcode(255, program.header()); let operation_advance = adjusted / program.header().line_encoding.line_range; self.apply_operation_advance(u64::from(operation_advance), program.header()); false } LineInstruction::FixedAddPc(operand) => { self.address += u64::from(operand); self.op_index = 0; false } LineInstruction::SetPrologueEnd => { self.prologue_end = true; false } LineInstruction::SetEpilogueBegin => { self.epilogue_begin = true; false } LineInstruction::SetIsa(isa) => { self.isa = isa; false } LineInstruction::EndSequence => { self.end_sequence = true; true } LineInstruction::SetAddress(address) => { self.address = address; self.op_index = 0; false } LineInstruction::DefineFile(entry) => { program.add_file(entry); false } LineInstruction::SetDiscriminator(discriminator) => { self.discriminator = discriminator; false } // Compatibility with future opcodes. LineInstruction::UnknownStandard0(_) | LineInstruction::UnknownStandard1(_, _) | LineInstruction::UnknownStandardN(_, _) | LineInstruction::UnknownExtended(_, _) => false, } } /// Perform any reset that was required after copying the previous row. #[inline] pub fn reset<R: Reader>(&mut self, header: &LineProgramHeader<R>) { if self.end_sequence { // Previous instruction was EndSequence, so reset everything // as specified in Section 6.2.5.3. *self = Self::new(header); } else { // Previous instruction was one of: // - Special - specified in Section 6.2.5.1, steps 4-7 // - Copy - specified in Section 6.2.5.2 // The reset behaviour is the same in both cases. self.discriminator = 0; self.basic_block = false; self.prologue_end = false; self.epilogue_begin = false; } } /// Step 1 of section 6.2.5.1 fn apply_line_advance(&mut self, line_increment: i64) { if line_increment < 0 { let decrement = -line_increment as u64; if decrement <= self.line { self.line -= decrement; } else { self.line = 0; } } else { self.line += line_increment as u64; } } /// Step 2 of section 6.2.5.1 fn apply_operation_advance<R: Reader>( &mut self, operation_advance: u64, header: &LineProgramHeader<R>, ) { let minimum_instruction_length = u64::from(header.line_encoding.minimum_instruction_length); let maximum_operations_per_instruction = u64::from(header.line_encoding.maximum_operations_per_instruction); if maximum_operations_per_instruction == 1 { self.address += minimum_instruction_length * operation_advance; self.op_index = 0; } else { let op_index_with_advance = self.op_index + operation_advance; self.address += minimum_instruction_length * (op_index_with_advance / maximum_operations_per_instruction); self.op_index = op_index_with_advance % maximum_operations_per_instruction; } } #[inline] fn adjust_opcode<R: Reader>(&self, opcode: u8, header: &LineProgramHeader<R>) -> u8 { opcode - header.opcode_base } /// Section 6.2.5.1 fn exec_special_opcode<R: Reader>(&mut self, opcode: u8, header: &LineProgramHeader<R>) { let adjusted_opcode = self.adjust_opcode(opcode, header); let line_range = header.line_encoding.line_range; let line_advance = adjusted_opcode % line_range; let operation_advance = adjusted_opcode / line_range; // Step 1 let line_base = i64::from(header.line_encoding.line_base); self.apply_line_advance(line_base + i64::from(line_advance)); // Step 2 self.apply_operation_advance(u64::from(operation_advance), header); } } /// The type of column that a row is referring to. #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum ColumnType { /// The `LeftEdge` means that the statement begins at the start of the new /// line. LeftEdge, /// A column number, whose range begins at 1. Column(u64), } /// Deprecated. `LineNumberSequence` has been renamed to `LineSequence`. #[deprecated(note = "LineNumberSequence has been renamed to LineSequence, use that instead.")] pub type LineNumberSequence<R> = LineSequence<R>; /// A sequence within a line number program. A sequence, as defined in section /// 6.2.5 of the standard, is a linear subset of a line number program within /// which addresses are monotonically increasing. #[derive(Clone, Debug)] pub struct LineSequence<R: Reader> { /// The first address that is covered by this sequence within the line number /// program. pub start: u64, /// The first address that is *not* covered by this sequence within the line /// number program. pub end: u64, instructions: LineInstructions<R>, } /// Deprecated. `LineNumberProgramHeader` has been renamed to `LineProgramHeader`. #[deprecated( note = "LineNumberProgramHeader has been renamed to LineProgramHeader, use that instead." )] pub type LineNumberProgramHeader<R, Offset> = LineProgramHeader<R, Offset>; /// A header for a line number program in the `.debug_line` section, as defined /// in section 6.2.4 of the standard. #[derive(Clone, Debug, Eq, PartialEq)] pub struct LineProgramHeader<R, Offset = <R as Reader>::Offset> where R: Reader<Offset = Offset>, Offset: ReaderOffset, { encoding: Encoding, offset: DebugLineOffset<Offset>, unit_length: Offset, header_length: Offset, line_encoding: LineEncoding, /// "The number assigned to the first special opcode." opcode_base: u8, /// "This array specifies the number of LEB128 operands for each of the /// standard opcodes. The first element of the array corresponds to the /// opcode whose value is 1, and the last element corresponds to the opcode /// whose value is `opcode_base - 1`." standard_opcode_lengths: R, /// "A sequence of directory entry format descriptions." directory_entry_format: Vec<FileEntryFormat>, /// > Entries in this sequence describe each path that was searched for /// > included source files in this compilation. (The paths include those /// > directories specified explicitly by the user for the compiler to search /// > and those the compiler searches without explicit direction.) Each path /// > entry is either a full path name or is relative to the current directory /// > of the compilation. /// > /// > The last entry is followed by a single null byte. include_directories: Vec<AttributeValue<R, Offset>>, /// "A sequence of file entry format descriptions." file_name_entry_format: Vec<FileEntryFormat>, /// "Entries in this sequence describe source files that contribute to the /// line number information for this compilation unit or is used in other /// contexts." file_names: Vec<FileEntry<R, Offset>>, /// The encoded line program instructions. program_buf: R, /// The current directory of the compilation. comp_dir: Option<R>, /// The primary source file. comp_file: Option<FileEntry<R, Offset>>, } impl<R, Offset> LineProgramHeader<R, Offset> where R: Reader<Offset = Offset>, Offset: ReaderOffset, { /// Return the offset of the line number program header in the `.debug_line` section. pub fn offset(&self) -> DebugLineOffset<R::Offset> { self.offset } /// Return the length of the line number program and header, not including /// the length of the encoded length itself. pub fn unit_length(&self) -> R::Offset { self.unit_length } /// Return the encoding parameters for this header's line program. pub fn encoding(&self) -> Encoding { self.encoding } /// Get the version of this header's line program. pub fn version(&self) -> u16 { self.encoding.version } /// Get the length of the encoded line number program header, not including /// the length of the encoded length itself. pub fn header_length(&self) -> R::Offset { self.header_length } /// Get the size in bytes of a target machine address. pub fn address_size(&self) -> u8 { self.encoding.address_size } /// Whether this line program is encoded in 64- or 32-bit DWARF. pub fn format(&self) -> Format { self.encoding.format } /// Get the line encoding parameters for this header's line program. pub fn line_encoding(&self) -> LineEncoding { self.line_encoding } /// Get the minimum instruction length any instruction in this header's line /// program may have. pub fn minimum_instruction_length(&self) -> u8 { self.line_encoding.minimum_instruction_length } /// Get the maximum number of operations each instruction in this header's /// line program may have. pub fn maximum_operations_per_instruction(&self) -> u8 { self.line_encoding.maximum_operations_per_instruction } /// Get the default value of the `is_stmt` register for this header's line /// program. pub fn default_is_stmt(&self) -> bool { self.line_encoding.default_is_stmt } /// Get the line base for this header's line program. pub fn line_base(&self) -> i8 { self.line_encoding.line_base } /// Get the line range for this header's line program. pub fn line_range(&self) -> u8 { self.line_encoding.line_range } /// Get opcode base for this header's line program. pub fn opcode_base(&self) -> u8 { self.opcode_base } /// An array of `u8` that specifies the number of LEB128 operands for /// each of the standard opcodes. pub fn standard_opcode_lengths(&self) -> &R { &self.standard_opcode_lengths } /// Get the format of a directory entry. pub fn directory_entry_format(&self) -> &[FileEntryFormat] { &self.directory_entry_format[..] } /// Get the set of include directories for this header's line program. /// /// For DWARF version <= 4, the compilation's current directory is not included /// in the return value, but is implicitly considered to be in the set per spec. pub fn include_directories(&self) -> &[AttributeValue<R, Offset>] { &self.include_directories[..] } /// The include directory with the given directory index. /// /// A directory index of 0 corresponds to the compilation unit directory. pub fn directory(&self, directory: u64) -> Option<AttributeValue<R, Offset>> { if self.encoding.version <= 4 { if directory == 0 { self.comp_dir.clone().map(AttributeValue::String) } else { let directory = directory as usize - 1; self.include_directories.get(directory).cloned() } } else { self.include_directories.get(directory as usize).cloned() } } /// Get the format of a file name entry. pub fn file_name_entry_format(&self) -> &[FileEntryFormat] { &self.file_name_entry_format[..] } /// Return true if the file entries may have valid timestamps. /// /// Only returns false if we definitely know that all timestamp fields /// are invalid. pub fn file_has_timestamp(&self) -> bool { self.encoding.version <= 4 || self .file_name_entry_format .iter() .any(|x| x.content_type == constants::DW_LNCT_timestamp) } /// Return true if the file entries may have valid sizes. /// /// Only returns false if we definitely know that all size fields /// are invalid. pub fn file_has_size(&self) -> bool { self.encoding.version <= 4 || self .file_name_entry_format .iter() .any(|x| x.content_type == constants::DW_LNCT_size) } /// Return true if the file name entry format contains an MD5 field. pub fn file_has_md5(&self) -> bool { self.file_name_entry_format .iter() .any(|x| x.content_type == constants::DW_LNCT_MD5) } /// Get the list of source files that appear in this header's line program. pub fn file_names(&self) -> &[FileEntry<R, Offset>] { &self.file_names[..] } /// The source file with the given file index. /// /// A file index of 0 corresponds to the compilation unit file. /// Note that a file index of 0 is invalid for DWARF version <= 4, /// but we support it anyway. pub fn file(&self, file: u64) -> Option<&FileEntry<R, Offset>> { if self.encoding.version <= 4 { if file == 0 { self.comp_file.as_ref() } else { let file = file as usize - 1; self.file_names.get(file) } } else { self.file_names.get(file as usize) } } /// Get the raw, un-parsed `EndianSlice` containing this header's line number /// program. /// /// ``` /// # fn foo() { /// use gimli::{LineProgramHeader, EndianSlice, NativeEndian}; /// /// fn get_line_number_program_header<'a>() -> LineProgramHeader<EndianSlice<'a, NativeEndian>> { /// // Get a line number program header from some offset in a /// // `.debug_line` section... /// # unimplemented!() /// } /// /// let header = get_line_number_program_header(); /// let raw_program = header.raw_program_buf(); /// println!("The length of the raw program in bytes is {}", raw_program.len()); /// # } /// ``` pub fn raw_program_buf(&self) -> R { self.program_buf.clone() } /// Iterate over the instructions in this header's line number program, parsing /// them as we go. pub fn instructions(&self) -> LineInstructions<R> { LineInstructions { input: self.program_buf.clone(), } } fn parse( input: &mut R, offset: DebugLineOffset<Offset>, mut address_size: u8, mut comp_dir: Option<R>, comp_name: Option<R>, ) -> Result<LineProgramHeader<R, Offset>> { let (unit_length, format) = input.read_initial_length()?; let rest = &mut input.split(unit_length)?; let version = rest.read_u16()?; if version < 2 || version > 5 { return Err(Error::UnknownVersion(u64::from(version))); } if version >= 5 { address_size = rest.read_u8()?; let segment_selector_size = rest.read_u8()?; if segment_selector_size != 0 { return Err(Error::UnsupportedSegmentSize); } } let encoding = Encoding { format, version, address_size, }; let header_length = rest.read_length(format)?; let mut program_buf = rest.clone(); program_buf.skip(header_length)?; rest.truncate(header_length)?; let minimum_instruction_length = rest.read_u8()?; if minimum_instruction_length == 0 { return Err(Error::MinimumInstructionLengthZero); } // This field did not exist before DWARF 4, but is specified to be 1 for // non-VLIW architectures, which makes it a no-op. let maximum_operations_per_instruction = if version >= 4 { rest.read_u8()? } else { 1 }; if maximum_operations_per_instruction == 0 { return Err(Error::MaximumOperationsPerInstructionZero); } let default_is_stmt = rest.read_u8()? != 0; let line_base = rest.read_i8()?; let line_range = rest.read_u8()?; if line_range == 0 { return Err(Error::LineRangeZero); } let line_encoding = LineEncoding { minimum_instruction_length, maximum_operations_per_instruction, default_is_stmt, line_base, line_range, }; let opcode_base = rest.read_u8()?; if opcode_base == 0 { return Err(Error::OpcodeBaseZero); } let standard_opcode_count = R::Offset::from_u8(opcode_base - 1); let standard_opcode_lengths = rest.split(standard_opcode_count)?; let directory_entry_format; let mut include_directories = Vec::new(); if version <= 4 { directory_entry_format = Vec::new(); loop { let directory = rest.read_null_terminated_slice()?; if directory.is_empty() { break; } include_directories.push(AttributeValue::String(directory)); } } else { comp_dir = None; directory_entry_format = FileEntryFormat::parse(rest)?; let count = rest.read_uleb128()?; for _ in 0..count { include_directories.push(parse_directory_v5( rest, encoding, &directory_entry_format, )?); } } let comp_file; let file_name_entry_format; let mut file_names = Vec::new(); if version <= 4 { comp_file = comp_name.map(|name| FileEntry { path_name: AttributeValue::String(name), directory_index: 0, timestamp: 0, size: 0, md5: [0; 16], }); file_name_entry_format = Vec::new(); loop { let path_name = rest.read_null_terminated_slice()?; if path_name.is_empty() { break; } file_names.push(FileEntry::parse(rest, path_name)?); } } else { comp_file = None; file_name_entry_format = FileEntryFormat::parse(rest)?; let count = rest.read_uleb128()?; for _ in 0..count { file_names.push(parse_file_v5(rest, encoding, &file_name_entry_format)?); } } let header = LineProgramHeader { encoding, offset, unit_length, header_length, line_encoding, opcode_base, standard_opcode_lengths, directory_entry_format, include_directories, file_name_entry_format, file_names, program_buf, comp_dir, comp_file, }; Ok(header) } } /// Deprecated. `IncompleteLineNumberProgram` has been renamed to `IncompleteLineProgram`. #[deprecated( note = "IncompleteLineNumberProgram has been renamed to IncompleteLineProgram, use that instead." )] pub type IncompleteLineNumberProgram<R, Offset> = IncompleteLineProgram<R, Offset>; /// A line number program that has not been run to completion. #[derive(Clone, Debug, Eq, PartialEq)] pub struct IncompleteLineProgram<R, Offset = <R as Reader>::Offset> where R: Reader<Offset = Offset>, Offset: ReaderOffset, { header: LineProgramHeader<R, Offset>, } impl<R, Offset> IncompleteLineProgram<R, Offset> where R: Reader<Offset = Offset>, Offset: ReaderOffset, { /// Retrieve the `LineProgramHeader` for this program. pub fn header(&self) -> &LineProgramHeader<R, Offset> { &self.header } /// Construct a new `LineRows` for executing this program to iterate /// over rows in the line information matrix. pub fn rows(self) -> OneShotLineRows<R, Offset> { OneShotLineRows::new(self) } /// Execute the line number program, completing the `IncompleteLineProgram` /// into a `CompleteLineProgram` and producing an array of sequences within /// the line number program that can later be used with /// `CompleteLineProgram::resume_from`. /// /// ``` /// # fn foo() { /// use gimli::{IncompleteLineProgram, EndianSlice, NativeEndian}; /// /// fn get_line_number_program<'a>() -> IncompleteLineProgram<EndianSlice<'a, NativeEndian>> { /// // Get a line number program from some offset in a /// // `.debug_line` section... /// # unimplemented!() /// } /// /// let program = get_line_number_program(); /// let (program, sequences) = program.sequences().unwrap(); /// println!("There are {} sequences in this line number program", sequences.len()); /// # } /// ``` #[allow(clippy::type_complexity)] pub fn sequences(self) -> Result<(CompleteLineProgram<R, Offset>, Vec<LineSequence<R>>)> { let mut sequences = Vec::new(); let mut rows = self.rows(); let mut instructions = rows.instructions.clone(); let mut sequence_start_addr = None; loop { let sequence_end_addr; if rows.next_row()?.is_none() { break; } let row = &rows.row; if row.end_sequence() { sequence_end_addr = row.address(); } else if sequence_start_addr.is_none() { sequence_start_addr = Some(row.address()); continue; } else { continue; } // We just finished a sequence. sequences.push(LineSequence { // In theory one could have multiple DW_LNE_end_sequence instructions // in a row. start: sequence_start_addr.unwrap_or(0), end: sequence_end_addr, instructions: instructions.remove_trailing(&rows.instructions)?, }); sequence_start_addr = None; instructions = rows.instructions.clone(); } let program = CompleteLineProgram { header: rows.program.header, }; Ok((program, sequences)) } } /// Deprecated. `CompleteLineNumberProgram` has been renamed to `CompleteLineProgram`. #[deprecated( note = "CompleteLineNumberProgram has been renamed to CompleteLineProgram, use that instead." )] pub type CompleteLineNumberProgram<R, Offset> = CompleteLineProgram<R, Offset>; /// A line number program that has previously been run to completion. #[derive(Clone, Debug, Eq, PartialEq)] pub struct CompleteLineProgram<R, Offset = <R as Reader>::Offset> where R: Reader<Offset = Offset>, Offset: ReaderOffset, { header: LineProgramHeader<R, Offset>, } impl<R, Offset> CompleteLineProgram<R, Offset> where R: Reader<Offset = Offset>, Offset: ReaderOffset, { /// Retrieve the `LineProgramHeader` for this program. pub fn header(&self) -> &LineProgramHeader<R, Offset> { &self.header } /// Construct a new `LineRows` for executing the subset of the line /// number program identified by 'sequence' and generating the line information /// matrix. /// /// ``` /// # fn foo() { /// use gimli::{IncompleteLineProgram, EndianSlice, NativeEndian}; /// /// fn get_line_number_program<'a>() -> IncompleteLineProgram<EndianSlice<'a, NativeEndian>> { /// // Get a line number program from some offset in a /// // `.debug_line` section... /// # unimplemented!() /// } /// /// let program = get_line_number_program(); /// let (program, sequences) = program.sequences().unwrap(); /// for sequence in &sequences { /// let mut sm = program.resume_from(sequence); /// } /// # } /// ``` pub fn resume_from<'program>( &'program self, sequence: &LineSequence<R>, ) -> ResumedLineRows<'program, R, Offset> { ResumedLineRows::resume(self, sequence) } } /// An entry in the `LineProgramHeader`'s `file_names` set. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct FileEntry<R, Offset = <R as Reader>::Offset> where R: Reader<Offset = Offset>, Offset: ReaderOffset, { path_name: AttributeValue<R, Offset>, directory_index: u64, timestamp: u64, size: u64, md5: [u8; 16], } impl<R, Offset> FileEntry<R, Offset> where R: Reader<Offset = Offset>, Offset: ReaderOffset, { // version 2-4 fn parse(input: &mut R, path_name: R) -> Result<FileEntry<R, Offset>> { let directory_index = input.read_uleb128()?; let timestamp = input.read_uleb128()?; let size = input.read_uleb128()?; let entry = FileEntry { path_name: AttributeValue::String(path_name), directory_index, timestamp, size, md5: [0; 16], }; Ok(entry) } /// > A slice containing the full or relative path name of /// > a source file. If the entry contains a file name or a relative path /// > name, the file is located relative to either the compilation directory /// > (as specified by the DW_AT_comp_dir attribute given in the compilation /// > unit) or one of the directories in the include_directories section. pub fn path_name(&self) -> AttributeValue<R, Offset> { self.path_name.clone() } /// > An unsigned LEB128 number representing the directory index of the /// > directory in which the file was found. /// > /// > ... /// > /// > The directory index represents an entry in the include_directories /// > section of the line number program header. The index is 0 if the file /// > was found in the current directory of the compilation, 1 if it was found /// > in the first directory in the include_directories section, and so /// > on. The directory index is ignored for file names that represent full /// > path names. pub fn directory_index(&self) -> u64 { self.directory_index } /// Get this file's directory. /// /// A directory index of 0 corresponds to the compilation unit directory. pub fn directory(&self, header: &LineProgramHeader<R>) -> Option<AttributeValue<R, Offset>> { header.directory(self.directory_index) } /// The implementation-defined time of last modification of the file, /// or 0 if not available. pub fn timestamp(&self) -> u64 { self.timestamp } /// "An unsigned LEB128 number representing the time of last modification of /// the file, or 0 if not available." // Terminology changed in DWARF version 5. #[doc(hidden)] pub fn last_modification(&self) -> u64 { self.timestamp } /// The size of the file in bytes, or 0 if not available. pub fn size(&self) -> u64 { self.size } /// "An unsigned LEB128 number representing the length in bytes of the file, /// or 0 if not available." // Terminology changed in DWARF version 5. #[doc(hidden)] pub fn length(&self) -> u64 { self.size } /// A 16-byte MD5 digest of the file contents. /// /// Only valid if `LineProgramHeader::file_has_md5` returns `true`. pub fn md5(&self) -> &[u8; 16] { &self.md5 } } /// The format of a component of an include directory or file name entry. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct FileEntryFormat { /// The type of information that is represented by the component. pub content_type: constants::DwLnct, /// The encoding form of the component value. pub form: constants::DwForm, } impl FileEntryFormat { fn parse<R: Reader>(input: &mut R) -> Result<Vec<FileEntryFormat>> { let format_count = input.read_u8()? as usize; let mut format = Vec::with_capacity(format_count); let mut path_count = 0; for _ in 0..format_count { let content_type = input.read_uleb128()?; let content_type = if content_type > u64::from(u16::max_value()) { constants::DwLnct(u16::max_value()) } else { constants::DwLnct(content_type as u16) }; if content_type == constants::DW_LNCT_path { path_count += 1; } let form = constants::DwForm(input.read_uleb128_u16()?); format.push(FileEntryFormat { content_type, form }); } if path_count != 1 { return Err(Error::MissingFileEntryFormatPath); } Ok(format) } } fn parse_directory_v5<R: Reader>( input: &mut R, encoding: Encoding, formats: &[FileEntryFormat], ) -> Result<AttributeValue<R>> { let mut path_name = None; for format in formats { let value = parse_attribute(input, encoding, format.form)?; if format.content_type == constants::DW_LNCT_path { path_name = Some(value); } } Ok(path_name.unwrap()) } fn parse_file_v5<R: Reader>( input: &mut R, encoding: Encoding, formats: &[FileEntryFormat], ) -> Result<FileEntry<R>> { let mut path_name = None; let mut directory_index = 0; let mut timestamp = 0; let mut size = 0; let mut md5 = [0; 16]; for format in formats { let value = parse_attribute(input, encoding, format.form)?; match format.content_type { constants::DW_LNCT_path => path_name = Some(value), constants::DW_LNCT_directory_index => { if let Some(value) = value.udata_value() { directory_index = value; } } constants::DW_LNCT_timestamp => { if let Some(value) = value.udata_value() { timestamp = value; } } constants::DW_LNCT_size => { if let Some(value) = value.udata_value() { size = value; } } constants::DW_LNCT_MD5 => { if let AttributeValue::Block(mut value) = value { if value.len().into_u64() == 16 { md5 = value.read_u8_array()?; } } } // Ignore unknown content types. _ => {} } } Ok(FileEntry { path_name: path_name.unwrap(), directory_index, timestamp, size, md5, }) } // TODO: this should be shared with unit::parse_attribute(), but that is hard to do. fn parse_attribute<R: Reader>( input: &mut R, encoding: Encoding, form: constants::DwForm, ) -> Result<AttributeValue<R>> { Ok(match form { constants::DW_FORM_block1 => { let len = input.read_u8().map(R::Offset::from_u8)?; let block = input.split(len)?; AttributeValue::Block(block) } constants::DW_FORM_block2 => { let len = input.read_u16().map(R::Offset::from_u16)?; let block = input.split(len)?; AttributeValue::Block(block) } constants::DW_FORM_block4 => { let len = input.read_u32().map(R::Offset::from_u32)?; let block = input.split(len)?; AttributeValue::Block(block) } constants::DW_FORM_block => { let len = input.read_uleb128().and_then(R::Offset::from_u64)?; let block = input.split(len)?; AttributeValue::Block(block) } constants::DW_FORM_data1 => { let data = input.read_u8()?; AttributeValue::Data1(data) } constants::DW_FORM_data2 => { let data = input.read_u16()?; AttributeValue::Data2(data) } constants::DW_FORM_data4 => { let data = input.read_u32()?; AttributeValue::Data4(data) } constants::DW_FORM_data8 => { let data = input.read_u64()?; AttributeValue::Data8(data) } constants::DW_FORM_data16 => { let block = input.split(R::Offset::from_u8(16))?; AttributeValue::Block(block) } constants::DW_FORM_udata => { let data = input.read_uleb128()?; AttributeValue::Udata(data) } constants::DW_FORM_sdata => { let data = input.read_sleb128()?; AttributeValue::Sdata(data) } constants::DW_FORM_flag => { let present = input.read_u8()?; AttributeValue::Flag(present != 0) } constants::DW_FORM_sec_offset => { let offset = input.read_offset(encoding.format)?; AttributeValue::SecOffset(offset) } constants::DW_FORM_string => { let string = input.read_null_terminated_slice()?; AttributeValue::String(string) } constants::DW_FORM_strp => { let offset = input.read_offset(encoding.format)?; AttributeValue::DebugStrRef(DebugStrOffset(offset)) } constants::DW_FORM_strp_sup | constants::DW_FORM_GNU_strp_alt => { let offset = input.read_offset(encoding.format)?; AttributeValue::DebugStrRefSup(DebugStrOffset(offset)) } constants::DW_FORM_line_strp => { let offset = input.read_offset(encoding.format)?; AttributeValue::DebugLineStrRef(DebugLineStrOffset(offset)) } constants::DW_FORM_strx | constants::DW_FORM_GNU_str_index => { let index = input.read_uleb128().and_then(R::Offset::from_u64)?; AttributeValue::DebugStrOffsetsIndex(DebugStrOffsetsIndex(index)) } constants::DW_FORM_strx1 => { let index = input.read_u8().map(R::Offset::from_u8)?; AttributeValue::DebugStrOffsetsIndex(DebugStrOffsetsIndex(index)) } constants::DW_FORM_strx2 => { let index = input.read_u16().map(R::Offset::from_u16)?; AttributeValue::DebugStrOffsetsIndex(DebugStrOffsetsIndex(index)) } constants::DW_FORM_strx3 => { let index = input.read_uint(3).and_then(R::Offset::from_u64)?; AttributeValue::DebugStrOffsetsIndex(DebugStrOffsetsIndex(index)) } constants::DW_FORM_strx4 => { let index = input.read_u32().map(R::Offset::from_u32)?; AttributeValue::DebugStrOffsetsIndex(DebugStrOffsetsIndex(index)) } _ => { return Err(Error::UnknownForm); } }) } #[cfg(test)] mod tests { use super::*; use crate::constants; use crate::endianity::LittleEndian; use crate::read::{EndianSlice, Error}; use crate::test_util::GimliSectionMethods; use core::u8; use test_assembler::{Endian, Label, LabelMaker, Section}; #[test] fn test_parse_debug_line_32_ok() { #[rustfmt::skip] let buf = [ // 32-bit length = 62. 0x3e, 0x00, 0x00, 0x00, // Version. 0x04, 0x00, // Header length = 40. 0x28, 0x00, 0x00, 0x00, // Minimum instruction length. 0x01, // Maximum operations per byte. 0x01, // Default is_stmt. 0x01, // Line base. 0x00, // Line range. 0x01, // Opcode base. 0x03, // Standard opcode lengths for opcodes 1 .. opcode base - 1. 0x01, 0x02, // Include directories = '/', 'i', 'n', 'c', '\0', '/', 'i', 'n', 'c', '2', '\0', '\0' 0x2f, 0x69, 0x6e, 0x63, 0x00, 0x2f, 0x69, 0x6e, 0x63, 0x32, 0x00, 0x00, // File names // foo.rs 0x66, 0x6f, 0x6f, 0x2e, 0x72, 0x73, 0x00, 0x00, 0x00, 0x00, // bar.h 0x62, 0x61, 0x72, 0x2e, 0x68, 0x00, 0x01, 0x00, 0x00, // End file names. 0x00, // Dummy line program data. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Dummy next line program. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; let rest = &mut EndianSlice::new(&buf, LittleEndian); let comp_dir = EndianSlice::new(b"/comp_dir", LittleEndian); let comp_name = EndianSlice::new(b"/comp_name", LittleEndian); let header = LineProgramHeader::parse(rest, DebugLineOffset(0), 4, Some(comp_dir), Some(comp_name)) .expect("should parse header ok"); assert_eq!( *rest, EndianSlice::new(&buf[buf.len() - 16..], LittleEndian) ); assert_eq!(header.offset, DebugLineOffset(0)); assert_eq!(header.version(), 4); assert_eq!(header.minimum_instruction_length(), 1); assert_eq!(header.maximum_operations_per_instruction(), 1); assert_eq!(header.default_is_stmt(), true); assert_eq!(header.line_base(), 0); assert_eq!(header.line_range(), 1); assert_eq!(header.opcode_base(), 3); assert_eq!(header.directory(0), Some(AttributeValue::String(comp_dir))); assert_eq!( header.file(0).unwrap().path_name, AttributeValue::String(comp_name) ); let expected_lengths = [1, 2]; assert_eq!(header.standard_opcode_lengths().slice(), &expected_lengths); let expected_include_directories = [ AttributeValue::String(EndianSlice::new(b"/inc", LittleEndian)), AttributeValue::String(EndianSlice::new(b"/inc2", LittleEndian)), ]; assert_eq!(header.include_directories(), &expected_include_directories); let expected_file_names = [ FileEntry { path_name: AttributeValue::String(EndianSlice::new(b"foo.rs", LittleEndian)), directory_index: 0, timestamp: 0, size: 0, md5: [0; 16], }, FileEntry { path_name: AttributeValue::String(EndianSlice::new(b"bar.h", LittleEndian)), directory_index: 1, timestamp: 0, size: 0, md5: [0; 16], }, ]; assert_eq!(&*header.file_names(), &expected_file_names); } #[test] fn test_parse_debug_line_header_length_too_short() { #[rustfmt::skip] let buf = [ // 32-bit length = 62. 0x3e, 0x00, 0x00, 0x00, // Version. 0x04, 0x00, // Header length = 20. TOO SHORT!!! 0x15, 0x00, 0x00, 0x00, // Minimum instruction length. 0x01, // Maximum operations per byte. 0x01, // Default is_stmt. 0x01, // Line base. 0x00, // Line range. 0x01, // Opcode base. 0x03, // Standard opcode lengths for opcodes 1 .. opcode base - 1. 0x01, 0x02, // Include directories = '/', 'i', 'n', 'c', '\0', '/', 'i', 'n', 'c', '2', '\0', '\0' 0x2f, 0x69, 0x6e, 0x63, 0x00, 0x2f, 0x69, 0x6e, 0x63, 0x32, 0x00, 0x00, // File names // foo.rs 0x66, 0x6f, 0x6f, 0x2e, 0x72, 0x73, 0x00, 0x00, 0x00, 0x00, // bar.h 0x62, 0x61, 0x72, 0x2e, 0x68, 0x00, 0x01, 0x00, 0x00, // End file names. 0x00, // Dummy line program data. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Dummy next line program. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; let input = &mut EndianSlice::new(&buf, LittleEndian); match LineProgramHeader::parse(input, DebugLineOffset(0), 4, None, None) { Err(Error::UnexpectedEof(_)) => return, otherwise => panic!("Unexpected result: {:?}", otherwise), } } #[test] fn test_parse_debug_line_unit_length_too_short() { #[rustfmt::skip] let buf = [ // 32-bit length = 40. TOO SHORT!!! 0x28, 0x00, 0x00, 0x00, // Version. 0x04, 0x00, // Header length = 40. 0x28, 0x00, 0x00, 0x00, // Minimum instruction length. 0x01, // Maximum operations per byte. 0x01, // Default is_stmt. 0x01, // Line base. 0x00, // Line range. 0x01, // Opcode base. 0x03, // Standard opcode lengths for opcodes 1 .. opcode base - 1. 0x01, 0x02, // Include directories = '/', 'i', 'n', 'c', '\0', '/', 'i', 'n', 'c', '2', '\0', '\0' 0x2f, 0x69, 0x6e, 0x63, 0x00, 0x2f, 0x69, 0x6e, 0x63, 0x32, 0x00, 0x00, // File names // foo.rs 0x66, 0x6f, 0x6f, 0x2e, 0x72, 0x73, 0x00, 0x00, 0x00, 0x00, // bar.h 0x62, 0x61, 0x72, 0x2e, 0x68, 0x00, 0x01, 0x00, 0x00, // End file names. 0x00, // Dummy line program data. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Dummy next line program. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; let input = &mut EndianSlice::new(&buf, LittleEndian); match LineProgramHeader::parse(input, DebugLineOffset(0), 4, None, None) { Err(Error::UnexpectedEof(_)) => return, otherwise => panic!("Unexpected result: {:?}", otherwise), } } const OPCODE_BASE: u8 = 13; const STANDARD_OPCODE_LENGTHS: &[u8] = &[0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1]; fn make_test_header( buf: EndianSlice<LittleEndian>, ) -> LineProgramHeader<EndianSlice<LittleEndian>> { let encoding = Encoding { format: Format::Dwarf32, version: 4, address_size: 8, }; let line_encoding = LineEncoding { line_base: -3, line_range: 12, ..Default::default() }; LineProgramHeader { encoding, offset: DebugLineOffset(0), unit_length: 1, header_length: 1, line_encoding, opcode_base: OPCODE_BASE, standard_opcode_lengths: EndianSlice::new(STANDARD_OPCODE_LENGTHS, LittleEndian), file_names: vec![ FileEntry { path_name: AttributeValue::String(EndianSlice::new(b"foo.c", LittleEndian)), directory_index: 0, timestamp: 0, size: 0, md5: [0; 16], }, FileEntry { path_name: AttributeValue::String(EndianSlice::new(b"bar.rs", LittleEndian)), directory_index: 0, timestamp: 0, size: 0, md5: [0; 16], }, ], include_directories: vec![], directory_entry_format: vec![], file_name_entry_format: vec![], program_buf: buf, comp_dir: None, comp_file: None, } } fn make_test_program( buf: EndianSlice<LittleEndian>, ) -> IncompleteLineProgram<EndianSlice<LittleEndian>> { IncompleteLineProgram { header: make_test_header(buf), } } #[test] fn test_parse_special_opcodes() { for i in OPCODE_BASE..u8::MAX { let input = [i, 0, 0, 0]; let input = EndianSlice::new(&input, LittleEndian); let header = make_test_header(input); let mut rest = input; let opcode = LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK"); assert_eq!(*rest, *input.range_from(1..)); assert_eq!(opcode, LineInstruction::Special(i)); } } #[test] fn test_parse_standard_opcodes() { fn test<Operands>( raw: constants::DwLns, operands: Operands, expected: LineInstruction<EndianSlice<LittleEndian>>, ) where Operands: AsRef<[u8]>, { let mut input = Vec::new(); input.push(raw.0); input.extend_from_slice(operands.as_ref()); let expected_rest = [0, 1, 2, 3, 4]; input.extend_from_slice(&expected_rest); let input = EndianSlice::new(&*input, LittleEndian); let header = make_test_header(input); let mut rest = input; let opcode = LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK"); assert_eq!(opcode, expected); assert_eq!(*rest, expected_rest); } test(constants::DW_LNS_copy, [], LineInstruction::Copy); test( constants::DW_LNS_advance_pc, [42], LineInstruction::AdvancePc(42), ); test( constants::DW_LNS_advance_line, [9], LineInstruction::AdvanceLine(9), ); test(constants::DW_LNS_set_file, [7], LineInstruction::SetFile(7)); test( constants::DW_LNS_set_column, [1], LineInstruction::SetColumn(1), ); test( constants::DW_LNS_negate_stmt, [], LineInstruction::NegateStatement, ); test( constants::DW_LNS_set_basic_block, [], LineInstruction::SetBasicBlock, ); test( constants::DW_LNS_const_add_pc, [], LineInstruction::ConstAddPc, ); test( constants::DW_LNS_fixed_advance_pc, [42, 0], LineInstruction::FixedAddPc(42), ); test( constants::DW_LNS_set_prologue_end, [], LineInstruction::SetPrologueEnd, ); test( constants::DW_LNS_set_isa, [57 + 0x80, 100], LineInstruction::SetIsa(12857), ); } #[test] fn test_parse_unknown_standard_opcode_no_args() { let input = [OPCODE_BASE, 1, 2, 3]; let input = EndianSlice::new(&input, LittleEndian); let mut standard_opcode_lengths = Vec::new(); let mut header = make_test_header(input); standard_opcode_lengths.extend(header.standard_opcode_lengths.slice()); standard_opcode_lengths.push(0); header.opcode_base += 1; header.standard_opcode_lengths = EndianSlice::new(&standard_opcode_lengths, LittleEndian); let mut rest = input; let opcode = LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK"); assert_eq!( opcode, LineInstruction::UnknownStandard0(constants::DwLns(OPCODE_BASE)) ); assert_eq!(*rest, *input.range_from(1..)); } #[test] fn test_parse_unknown_standard_opcode_one_arg() { let input = [OPCODE_BASE, 1, 2, 3]; let input = EndianSlice::new(&input, LittleEndian); let mut standard_opcode_lengths = Vec::new(); let mut header = make_test_header(input); standard_opcode_lengths.extend(header.standard_opcode_lengths.slice()); standard_opcode_lengths.push(1); header.opcode_base += 1; header.standard_opcode_lengths = EndianSlice::new(&standard_opcode_lengths, LittleEndian); let mut rest = input; let opcode = LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK"); assert_eq!( opcode, LineInstruction::UnknownStandard1(constants::DwLns(OPCODE_BASE), 1) ); assert_eq!(*rest, *input.range_from(2..)); } #[test] fn test_parse_unknown_standard_opcode_many_args() { let input = [OPCODE_BASE, 1, 2, 3]; let input = EndianSlice::new(&input, LittleEndian); let args = EndianSlice::new(&input[1..], LittleEndian); let mut standard_opcode_lengths = Vec::new(); let mut header = make_test_header(input); standard_opcode_lengths.extend(header.standard_opcode_lengths.slice()); standard_opcode_lengths.push(3); header.opcode_base += 1; header.standard_opcode_lengths = EndianSlice::new(&standard_opcode_lengths, LittleEndian); let mut rest = input; let opcode = LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK"); assert_eq!( opcode, LineInstruction::UnknownStandardN(constants::DwLns(OPCODE_BASE), args) ); assert_eq!(*rest, []); } #[test] fn test_parse_extended_opcodes() { fn test<Operands>( raw: constants::DwLne, operands: Operands, expected: LineInstruction<EndianSlice<LittleEndian>>, ) where Operands: AsRef<[u8]>, { let mut input = Vec::new(); input.push(0); let operands = operands.as_ref(); input.push(1 + operands.len() as u8); input.push(raw.0); input.extend_from_slice(operands); let expected_rest = [0, 1, 2, 3, 4]; input.extend_from_slice(&expected_rest); let input = EndianSlice::new(&input, LittleEndian); let header = make_test_header(input); let mut rest = input; let opcode = LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK"); assert_eq!(opcode, expected); assert_eq!(*rest, expected_rest); } test( constants::DW_LNE_end_sequence, [], LineInstruction::EndSequence, ); test( constants::DW_LNE_set_address, [1, 2, 3, 4, 5, 6, 7, 8], LineInstruction::SetAddress(578_437_695_752_307_201), ); test( constants::DW_LNE_set_discriminator, [42], LineInstruction::SetDiscriminator(42), ); let mut file = Vec::new(); // "foo.c" let path_name = [b'f', b'o', b'o', b'.', b'c', 0]; file.extend_from_slice(&path_name); // Directory index. file.push(0); // Last modification of file. file.push(1); // Size of file. file.push(2); test( constants::DW_LNE_define_file, file, LineInstruction::DefineFile(FileEntry { path_name: AttributeValue::String(EndianSlice::new(b"foo.c", LittleEndian)), directory_index: 0, timestamp: 1, size: 2, md5: [0; 16], }), ); // Unknown extended opcode. let operands = [1, 2, 3, 4, 5, 6]; let opcode = constants::DwLne(99); test( opcode, operands, LineInstruction::UnknownExtended(opcode, EndianSlice::new(&operands, LittleEndian)), ); } #[test] fn test_file_entry_directory() { let path_name = [b'f', b'o', b'o', b'.', b'r', b's', 0]; let mut file = FileEntry { path_name: AttributeValue::String(EndianSlice::new(&path_name, LittleEndian)), directory_index: 1, timestamp: 0, size: 0, md5: [0; 16], }; let mut header = make_test_header(EndianSlice::new(&[], LittleEndian)); let dir = AttributeValue::String(EndianSlice::new(b"dir", LittleEndian)); header.include_directories.push(dir); assert_eq!(file.directory(&header), Some(dir)); // Now test the compilation's current directory. file.directory_index = 0; assert_eq!(file.directory(&header), None); } fn assert_exec_opcode<'input>( header: LineProgramHeader<EndianSlice<'input, LittleEndian>>, mut registers: LineRow, opcode: LineInstruction<EndianSlice<'input, LittleEndian>>, expected_registers: LineRow, expect_new_row: bool, ) { let mut program = IncompleteLineProgram { header }; let is_new_row = registers.execute(opcode, &mut program); assert_eq!(is_new_row, expect_new_row); assert_eq!(registers, expected_registers); } #[test] fn test_exec_special_noop() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::Special(16); let expected_registers = initial_registers; assert_exec_opcode(header, initial_registers, opcode, expected_registers, true); } #[test] fn test_exec_special_negative_line_advance() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let mut initial_registers = LineRow::new(&header); initial_registers.line = 10; let opcode = LineInstruction::Special(13); let mut expected_registers = initial_registers; expected_registers.line -= 3; assert_exec_opcode(header, initial_registers, opcode, expected_registers, true); } #[test] fn test_exec_special_positive_line_advance() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::Special(19); let mut expected_registers = initial_registers; expected_registers.line += 3; assert_exec_opcode(header, initial_registers, opcode, expected_registers, true); } #[test] fn test_exec_special_positive_address_advance() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::Special(52); let mut expected_registers = initial_registers; expected_registers.address += 3; assert_exec_opcode(header, initial_registers, opcode, expected_registers, true); } #[test] fn test_exec_special_positive_address_and_line_advance() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::Special(55); let mut expected_registers = initial_registers; expected_registers.address += 3; expected_registers.line += 3; assert_exec_opcode(header, initial_registers, opcode, expected_registers, true); } #[test] fn test_exec_special_positive_address_and_negative_line_advance() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let mut initial_registers = LineRow::new(&header); initial_registers.line = 10; let opcode = LineInstruction::Special(49); let mut expected_registers = initial_registers; expected_registers.address += 3; expected_registers.line -= 3; assert_exec_opcode(header, initial_registers, opcode, expected_registers, true); } #[test] fn test_exec_special_line_underflow() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let mut initial_registers = LineRow::new(&header); initial_registers.line = 2; // -3 line advance. let opcode = LineInstruction::Special(13); let mut expected_registers = initial_registers; // Clamp at 0. No idea if this is the best way to handle this situation // or not... expected_registers.line = 0; assert_exec_opcode(header, initial_registers, opcode, expected_registers, true); } #[test] fn test_exec_copy() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let mut initial_registers = LineRow::new(&header); initial_registers.address = 1337; initial_registers.line = 42; let opcode = LineInstruction::Copy; let expected_registers = initial_registers; assert_exec_opcode(header, initial_registers, opcode, expected_registers, true); } #[test] fn test_exec_advance_pc() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::AdvancePc(42); let mut expected_registers = initial_registers; expected_registers.address += 42; assert_exec_opcode(header, initial_registers, opcode, expected_registers, false); } #[test] fn test_exec_advance_line() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::AdvanceLine(42); let mut expected_registers = initial_registers; expected_registers.line += 42; assert_exec_opcode(header, initial_registers, opcode, expected_registers, false); } #[test] fn test_exec_set_file_in_bounds() { for file_idx in 1..3 { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::SetFile(file_idx); let mut expected_registers = initial_registers; expected_registers.file = file_idx; assert_exec_opcode(header, initial_registers, opcode, expected_registers, false); } } #[test] fn test_exec_set_file_out_of_bounds() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::SetFile(100); // The spec doesn't say anything about rejecting input programs // that set the file register out of bounds of the actual number // of files that have been defined. Instead, we cross our // fingers and hope that one gets defined before // `LineRow::file` gets called and handle the error at // that time if need be. let mut expected_registers = initial_registers; expected_registers.file = 100; assert_exec_opcode(header, initial_registers, opcode, expected_registers, false); } #[test] fn test_file_entry_file_index_out_of_bounds() { // These indices are 1-based, so 0 is invalid. 100 is way more than the // number of files defined in the header. let out_of_bounds_indices = [0, 100]; for file_idx in &out_of_bounds_indices[..] { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let mut row = LineRow::new(&header); row.file = *file_idx; assert_eq!(row.file(&header), None); } } #[test] fn test_file_entry_file_index_in_bounds() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let mut row = LineRow::new(&header); row.file = 2; assert_eq!(row.file(&header), Some(&header.file_names()[1])); } #[test] fn test_exec_set_column() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::SetColumn(42); let mut expected_registers = initial_registers; expected_registers.column = 42; assert_exec_opcode(header, initial_registers, opcode, expected_registers, false); } #[test] fn test_exec_negate_statement() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::NegateStatement; let mut expected_registers = initial_registers; expected_registers.is_stmt = !initial_registers.is_stmt; assert_exec_opcode(header, initial_registers, opcode, expected_registers, false); } #[test] fn test_exec_set_basic_block() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let mut initial_registers = LineRow::new(&header); initial_registers.basic_block = false; let opcode = LineInstruction::SetBasicBlock; let mut expected_registers = initial_registers; expected_registers.basic_block = true; assert_exec_opcode(header, initial_registers, opcode, expected_registers, false); } #[test] fn test_exec_const_add_pc() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::ConstAddPc; let mut expected_registers = initial_registers; expected_registers.address += 20; assert_exec_opcode(header, initial_registers, opcode, expected_registers, false); } #[test] fn test_exec_fixed_add_pc() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let mut initial_registers = LineRow::new(&header); initial_registers.op_index = 1; let opcode = LineInstruction::FixedAddPc(10); let mut expected_registers = initial_registers; expected_registers.address += 10; expected_registers.op_index = 0; assert_exec_opcode(header, initial_registers, opcode, expected_registers, false); } #[test] fn test_exec_set_prologue_end() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let mut initial_registers = LineRow::new(&header); initial_registers.prologue_end = false; let opcode = LineInstruction::SetPrologueEnd; let mut expected_registers = initial_registers; expected_registers.prologue_end = true; assert_exec_opcode(header, initial_registers, opcode, expected_registers, false); } #[test] fn test_exec_set_isa() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::SetIsa(1993); let mut expected_registers = initial_registers; expected_registers.isa = 1993; assert_exec_opcode(header, initial_registers, opcode, expected_registers, false); } #[test] fn test_exec_unknown_standard_0() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::UnknownStandard0(constants::DwLns(111)); let expected_registers = initial_registers; assert_exec_opcode(header, initial_registers, opcode, expected_registers, false); } #[test] fn test_exec_unknown_standard_1() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::UnknownStandard1(constants::DwLns(111), 2); let expected_registers = initial_registers; assert_exec_opcode(header, initial_registers, opcode, expected_registers, false); } #[test] fn test_exec_unknown_standard_n() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::UnknownStandardN( constants::DwLns(111), EndianSlice::new(&[2, 2, 2], LittleEndian), ); let expected_registers = initial_registers; assert_exec_opcode(header, initial_registers, opcode, expected_registers, false); } #[test] fn test_exec_end_sequence() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::EndSequence; let mut expected_registers = initial_registers; expected_registers.end_sequence = true; assert_exec_opcode(header, initial_registers, opcode, expected_registers, true); } #[test] fn test_exec_set_address() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::SetAddress(3030); let mut expected_registers = initial_registers; expected_registers.address = 3030; assert_exec_opcode(header, initial_registers, opcode, expected_registers, false); } #[test] fn test_exec_define_file() { let mut program = make_test_program(EndianSlice::new(&[], LittleEndian)); let mut row = LineRow::new(program.header()); let file = FileEntry { path_name: AttributeValue::String(EndianSlice::new(b"test.cpp", LittleEndian)), directory_index: 0, timestamp: 0, size: 0, md5: [0; 16], }; let opcode = LineInstruction::DefineFile(file); let is_new_row = row.execute(opcode, &mut program); assert_eq!(is_new_row, false); assert_eq!(Some(&file), program.header().file_names.last()); } #[test] fn test_exec_set_discriminator() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::SetDiscriminator(9); let mut expected_registers = initial_registers; expected_registers.discriminator = 9; assert_exec_opcode(header, initial_registers, opcode, expected_registers, false); } #[test] fn test_exec_unknown_extended() { let header = make_test_header(EndianSlice::new(&[], LittleEndian)); let initial_registers = LineRow::new(&header); let opcode = LineInstruction::UnknownExtended( constants::DwLne(74), EndianSlice::new(&[], LittleEndian), ); let expected_registers = initial_registers; assert_exec_opcode(header, initial_registers, opcode, expected_registers, false); } /// Ensure that `LineRows<R,P>` is covariant wrt R. /// This only needs to compile. #[allow(dead_code, unreachable_code, unused_variables)] fn test_line_rows_variance<'a, 'b>(_: &'a [u8], _: &'b [u8]) where 'a: 'b, { let a: &OneShotLineRows<EndianSlice<'a, LittleEndian>> = unimplemented!(); let _: &OneShotLineRows<EndianSlice<'b, LittleEndian>> = a; } #[test] fn test_parse_debug_line_v5_ok() { let expected_lengths = &[1, 2]; let expected_program = &[0, 1, 2, 3, 4]; let expected_rest = &[5, 6, 7, 8, 9]; let expected_include_directories = [ AttributeValue::String(EndianSlice::new(b"dir1", LittleEndian)), AttributeValue::String(EndianSlice::new(b"dir2", LittleEndian)), ]; let expected_file_names = [ FileEntry { path_name: AttributeValue::String(EndianSlice::new(b"file1", LittleEndian)), directory_index: 0, timestamp: 0, size: 0, md5: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], }, FileEntry { path_name: AttributeValue::String(EndianSlice::new(b"file2", LittleEndian)), directory_index: 1, timestamp: 0, size: 0, md5: [ 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, ], }, ]; for format in vec![Format::Dwarf32, Format::Dwarf64] { let length = Label::new(); let header_length = Label::new(); let start = Label::new(); let header_start = Label::new(); let end = Label::new(); let header_end = Label::new(); let section = Section::with_endian(Endian::Little) .initial_length(format, &length, &start) .D16(5) // Address size. .D8(4) // Segment selector size. .D8(0) .word_label(format.word_size(), &header_length) .mark(&header_start) // Minimum instruction length. .D8(1) // Maximum operations per byte. .D8(1) // Default is_stmt. .D8(1) // Line base. .D8(0) // Line range. .D8(1) // Opcode base. .D8(expected_lengths.len() as u8 + 1) // Standard opcode lengths for opcodes 1 .. opcode base - 1. .append_bytes(expected_lengths) // Directory entry format count. .D8(1) .uleb(constants::DW_LNCT_path.0 as u64) .uleb(constants::DW_FORM_string.0 as u64) // Directory count. .D8(2) .append_bytes(b"dir1\0") .append_bytes(b"dir2\0") // File entry format count. .D8(3) .uleb(constants::DW_LNCT_path.0 as u64) .uleb(constants::DW_FORM_string.0 as u64) .uleb(constants::DW_LNCT_directory_index.0 as u64) .uleb(constants::DW_FORM_data1.0 as u64) .uleb(constants::DW_LNCT_MD5.0 as u64) .uleb(constants::DW_FORM_data16.0 as u64) // File count. .D8(2) .append_bytes(b"file1\0") .D8(0) .append_bytes(&expected_file_names[0].md5) .append_bytes(b"file2\0") .D8(1) .append_bytes(&expected_file_names[1].md5) .mark(&header_end) // Dummy line program data. .append_bytes(expected_program) .mark(&end) // Dummy trailing data. .append_bytes(expected_rest); length.set_const((&end - &start) as u64); header_length.set_const((&header_end - &header_start) as u64); let section = section.get_contents().unwrap(); let input = &mut EndianSlice::new(&section, LittleEndian); let header = LineProgramHeader::parse(input, DebugLineOffset(0), 0, None, None) .expect("should parse header ok"); assert_eq!(header.raw_program_buf().slice(), expected_program); assert_eq!(input.slice(), expected_rest); assert_eq!(header.offset, DebugLineOffset(0)); assert_eq!(header.version(), 5); assert_eq!(header.address_size(), 4); assert_eq!(header.minimum_instruction_length(), 1); assert_eq!(header.maximum_operations_per_instruction(), 1); assert_eq!(header.default_is_stmt(), true); assert_eq!(header.line_base(), 0); assert_eq!(header.line_range(), 1); assert_eq!(header.opcode_base(), expected_lengths.len() as u8 + 1); assert_eq!(header.standard_opcode_lengths().slice(), expected_lengths); assert_eq!( header.directory_entry_format(), &[FileEntryFormat { content_type: constants::DW_LNCT_path, form: constants::DW_FORM_string, }] ); assert_eq!(header.include_directories(), expected_include_directories); assert_eq!(header.directory(0), Some(expected_include_directories[0])); assert_eq!( header.file_name_entry_format(), &[ FileEntryFormat { content_type: constants::DW_LNCT_path, form: constants::DW_FORM_string, }, FileEntryFormat { content_type: constants::DW_LNCT_directory_index, form: constants::DW_FORM_data1, }, FileEntryFormat { content_type: constants::DW_LNCT_MD5, form: constants::DW_FORM_data16, } ] ); assert_eq!(header.file_names(), expected_file_names); assert_eq!(header.file(0), Some(&expected_file_names[0])); } } }
35.413529
101
0.586087
39368714aba4225ae46e3c28c200d01f6107f430
331
mod bench; mod index; mod merge; mod new; mod search; mod serve; mod inpect; pub use self::bench::run_bench_cli; pub use self::index::run_index_cli; pub use self::merge::run_merge_cli; pub use self::new::run_new_cli; pub use self::search::run_search_cli; pub use self::serve::run_serve_cli; pub use self::inpect::run_inspect_cli;
20.6875
38
0.76435
3af02ffc49e5b6335a242510d843d266082af56a
8,284
#![allow(clippy::upper_case_acronyms)] // Allow uppercase acronyms like QA and MacOS. //! This program builds the github workflow files for the rust-skia project. use std::{fmt, fs, ops::Deref, path::PathBuf}; mod config; const QA_WORKFLOW: &str = include_str!("templates/qa-workflow.yaml"); const RELEASE_WORKFLOW: &str = include_str!("templates/release-workflow.yaml"); const LINUX_JOB: &str = include_str!("templates/linux-job.yaml"); const WINDOWS_JOB: &str = include_str!("templates/windows-job.yaml"); const MACOS_JOB: &str = include_str!("templates/macos-job.yaml"); const TARGET_TEMPLATE: &str = include_str!("templates/target.yaml"); fn main() { for workflow in config::workflows() { build_workflow(&workflow, &config::jobs(&workflow)); } } #[derive(Clone, Debug)] pub struct Workflow { kind: WorkflowKind, host_os: HostOS, host_target: &'static str, job_template: &'static str, targets: Vec<Target>, host_bin_ext: &'static str, } #[derive(Copy, Clone, PartialEq, Eq, Debug)] enum WorkflowKind { QA, Release, } impl fmt::Display for WorkflowKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let n = match self { WorkflowKind::QA => "qa", WorkflowKind::Release => "release", }; f.write_str(n) } } #[derive(Copy, Clone, PartialEq, Eq, Debug)] enum HostOS { Windows, Linux, MacOS, } impl fmt::Display for HostOS { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { use HostOS::*; f.write_str(match self { Windows => "windows", Linux => "linux", MacOS => "macos", }) } } #[derive(Default)] pub struct Job { name: &'static str, toolchain: &'static str, features: Features, skia_debug: bool, // we may need to disable clippy for beta builds temporarily. disable_clippy: bool, example_args: Option<String>, } fn build_workflow(workflow: &Workflow, jobs: &[Job]) { let host_os = workflow.host_os; let job_template = workflow.job_template; let targets = &workflow.targets; let workflow_name = format!("{}-{}", host_os, workflow.kind); let output_filename = PathBuf::new() .join(".github") .join("workflows") .join(format!("{}.yaml", workflow_name)); let header = build_header(&workflow_name, workflow.kind); let mut parts = vec![header]; for job in jobs { { let job_name = workflow_name.clone() + "-" + job.name; let job_name = format!("{}:", job_name).indented(1); parts.push(job_name); } { let job_header = build_job(workflow, job_template, job, targets).indented(2); parts.push(job_header); } let targets: Vec<String> = targets .iter() .map(|t| build_target(workflow, job, t).indented(2)) .collect(); parts.extend(targets); } // some parts won't end with \n, so be safe and join them with a newline. let contents = parts .iter() .map(|p| p.trim_end().to_owned()) .collect::<Vec<_>>() .join("\n"); fs::create_dir_all(output_filename.parent().unwrap()).unwrap(); fs::write(output_filename, contents).unwrap(); } fn build_header(workflow_name: &str, workflow_kind: WorkflowKind) -> String { let replacements: Vec<_> = [("workflowName".to_owned(), workflow_name.to_owned())].into(); let workflow = match workflow_kind { WorkflowKind::QA => QA_WORKFLOW, WorkflowKind::Release => RELEASE_WORKFLOW, }; render_template(workflow, &replacements) } fn build_job(workflow: &Workflow, template: &str, job: &Job, targets: &[Target]) -> String { let skia_debug = if job.skia_debug { "1" } else { "0" }; let mut replacements = vec![ ("rustToolchain".into(), job.toolchain.into()), ("skiaDebug".into(), skia_debug.into()), ]; if let Some(macosx_deployment_target) = macosx_deployment_target(workflow, job, targets) { replacements.push(( "macosxDeploymentTarget".into(), macosx_deployment_target.into(), )) } render_template(template, &replacements) } fn macosx_deployment_target( workflow: &Workflow, job: &Job, targets: &[Target], ) -> Option<&'static str> { if let HostOS::MacOS = workflow.host_os { let metal = "metal".to_owned(); if targets .iter() .any(|target| effective_features(workflow, job, target).contains(&metal)) { Some("10.14") } else { Some("10.13") } } else { None } } fn build_target(workflow: &Workflow, job: &Job, target: &Target) -> String { let features = effective_features(workflow, job, target); let native_target = workflow.host_target == target.target; let example_args = if native_target { job.example_args.clone() } else { None } .unwrap_or_default(); let generate_artifacts = !example_args.is_empty(); let run_clippy = native_target && !job.disable_clippy; let release_binaries = workflow.kind == WorkflowKind::Release; let template_arguments: &[(&'static str, &dyn fmt::Display)] = &[ ("target", &target.target), ("androidEnv", &target.android_env), ("emscriptenEnv", &target.emscripten_env), ("androidAPILevel", &config::DEFAULT_ANDROID_API_LEVEL), ("features", &features), ("runTests", &native_target), ("runClippy", &run_clippy), ("exampleArgs", &example_args), ("generateArtifacts", &generate_artifacts), ("releaseBinaries", &release_binaries), ("hostBinExt", &workflow.host_bin_ext), ]; let replacements: Vec<(String, String)> = template_arguments .iter() .map(|(name, value)| (name.to_string(), value.to_string())) .collect(); render_template(TARGET_TEMPLATE, &replacements) } fn effective_features(workflow: &Workflow, job: &Job, target: &Target) -> Features { let mut features = job.features.clone(); // if we are releasing binaries, we want the exact set of features specified. if workflow.kind == WorkflowKind::QA { features = features.join(&target.platform_features); } features } fn render_template(template: &str, replacements: &[(String, String)]) -> String { let mut template = template.to_owned(); replacements.iter().for_each(|(pattern, value)| { template = template.replace(&format!("$[[{}]]", pattern), value) }); assert!( !template.contains("$[["), "Template contains template patterns after replacement: \n{}", template ); template } #[derive(Clone, Default, Debug)] struct Target { target: &'static str, android_env: bool, emscripten_env: bool, platform_features: Features, } #[derive(Clone, Default, Debug)] struct Features(Vec<String>); impl Features { pub fn join(&self, other: &Self) -> Self { let mut features = self.0.clone(); features.extend(other.0.iter().cloned()); features.sort(); features.dedup(); Self(features) } } impl Deref for Features { type Target = Vec<String>; fn deref(&self) -> &Self::Target { &self.0 } } impl fmt::Display for Features { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result { let features = self.0.join(","); f.write_str(&features) } } impl From<&str> for Features { fn from(s: &str) -> Self { let strs: Vec<String> = s .split(',') .filter_map(|s| { let f = s.trim().to_owned(); if !f.is_empty() { Some(f) } else { None } }) .collect(); Features(strs) } } trait Indented { fn indented(&self, i: usize) -> Self; } impl Indented for String { fn indented(&self, i: usize) -> String { let prefix: String = " ".repeat(i); let indented_lines: Vec<String> = self.lines().map(|l| prefix.clone() + l).collect(); indented_lines.join("\n") } }
27.892256
94
0.595606
0a46b2b1337e0b6ee31b6b692f378a11103ff31d
41,642
use holo_hash::AgentPubKey; use holo_hash::DnaHash; use holo_hash::HasHash; use holo_hash::HeaderHash; use holochain_sqlite::rusqlite::Transaction; use holochain_types::dht_op::produce_op_lights_from_elements; use holochain_types::dht_op::produce_op_lights_from_iter; use holochain_types::dht_op::DhtOpLight; use holochain_types::dht_op::DhtOpType; use holochain_types::dht_op::OpOrder; use holochain_types::dht_op::UniqueForm; use holochain_types::element::SignedHeaderHashedExt; use holochain_types::env::EnvRead; use holochain_types::env::EnvWrite; use holochain_types::timestamp; use holochain_zome_types::entry::EntryHashed; use holochain_zome_types::header; use holochain_zome_types::CapAccess; use holochain_zome_types::CapGrant; use holochain_zome_types::CapSecret; use holochain_zome_types::Element; use holochain_zome_types::Entry; use holochain_zome_types::EntryVisibility; use holochain_zome_types::GrantedFunction; use holochain_zome_types::Header; use holochain_zome_types::HeaderBuilder; use holochain_zome_types::HeaderBuilderCommon; use holochain_zome_types::HeaderHashed; use holochain_zome_types::HeaderInner; use holochain_zome_types::QueryFilter; use holochain_zome_types::Signature; use holochain_zome_types::SignedHeader; use holochain_zome_types::SignedHeaderHashed; use crate::prelude::*; use crate::query::chain_head::ChainHeadQuery; use crate::scratch::Scratch; use crate::scratch::SyncScratch; use holochain_serialized_bytes::prelude::*; pub use error::*; mod error; #[derive(Clone)] pub struct SourceChain { scratch: SyncScratch, vault: EnvWrite, author: Arc<AgentPubKey>, persisted_seq: u32, persisted_head: HeaderHash, public_only: bool, } // TODO fix this. We shouldn't really have nil values but this would // show if the database is corrupted and doesn't have an element #[derive(Serialize, Deserialize)] pub struct SourceChainJsonDump { pub elements: Vec<SourceChainJsonElement>, pub published_ops_count: usize, } #[derive(Serialize, Deserialize)] pub struct SourceChainJsonElement { pub signature: Signature, pub header_address: HeaderHash, pub header: Header, pub entry: Option<Entry>, } // TODO: document that many functions here are only reading from the scratch, // not the entire source chain! impl SourceChain { pub async fn new(vault: EnvWrite, author: AgentPubKey) -> SourceChainResult<Self> { let scratch = Scratch::new().into_sync(); let author = Arc::new(author); let (persisted_head, persisted_seq) = vault .async_reader({ let author = author.clone(); move |txn| chain_head_db(&txn, author) }) .await?; Ok(Self { scratch, vault, author, persisted_seq, persisted_head, public_only: false, }) } pub fn public_only(&mut self) { self.public_only = true; } /// Take a snapshot of the scratch space that will /// not remain in sync with future updates. pub fn snapshot(&self) -> SourceChainResult<Scratch> { Ok(self.scratch.apply(|scratch| scratch.clone())?) } pub fn scratch(&self) -> SyncScratch { self.scratch.clone() } pub fn agent_pubkey(&self) -> &AgentPubKey { self.author.as_ref() } /// This has to clone all the data because we can't return /// references to constructed data. // TODO: Maybe we should store data as elements in the scratch? // TODO: document that this is only the elemnts in the SCRATCH, not the // entire source chain! pub fn elements(&self) -> SourceChainResult<Vec<Element>> { Ok(self.scratch.apply(|scratch| scratch.elements().collect())?) } pub fn chain_head(&self) -> SourceChainResult<(HeaderHash, u32)> { // Check scratch for newer head. Ok(self.scratch.apply(|scratch| { let chain_head = chain_head_scratch(&(*scratch), self.author.as_ref()); let (prev_header, header_seq) = chain_head.unwrap_or_else(|| (self.persisted_head.clone(), self.persisted_seq)); (prev_header, header_seq) })?) } pub async fn put<H: HeaderInner, B: HeaderBuilder<H>>( &self, header_builder: B, maybe_entry: Option<Entry>, ) -> SourceChainResult<HeaderHash> { let (prev_header, chain_head_seq) = self.chain_head()?; let header_seq = chain_head_seq + 1; // Build the header. let common = HeaderBuilderCommon { author: (*self.author).clone(), timestamp: timestamp::now(), header_seq, prev_header, }; let header = header_builder.build(common).into(); let header = HeaderHashed::from_content_sync(header); let hash = header.as_hash().clone(); // Sign the header. let header = SignedHeaderHashed::new(&self.vault.keystore(), header).await?; let element = Element::new(header, maybe_entry); // Put into scratch. self.scratch .apply(|scratch| insert_element_scratch(scratch, element))?; Ok(hash) } pub fn has_initialized(&self) -> SourceChainResult<bool> { Ok(self.len()? > 3) } pub fn is_empty(&self) -> SourceChainResult<bool> { Ok(self.len()? == 0) } #[allow(clippy::len_without_is_empty)] pub fn len(&self) -> SourceChainResult<u32> { Ok(self.scratch.apply(|scratch| { let scratch_max = chain_head_scratch(&(*scratch), self.author.as_ref()).map(|(_, s)| s); scratch_max .map(|s| std::cmp::max(s, self.persisted_seq)) .unwrap_or(self.persisted_seq) + 1 })?) } pub fn valid_cap_grant( &self, check_function: &GrantedFunction, check_agent: &AgentPubKey, check_secret: Option<&CapSecret>, ) -> SourceChainResult<Option<CapGrant>> { let author_grant = CapGrant::from(self.agent_pubkey().clone()); if author_grant.is_valid(check_function, check_agent, check_secret) { return Ok(Some(author_grant)); } // TODO: SQL_PERF: This query could have a fast upper bound if we add indexes. let valid_cap_grant = self.vault.conn()?.with_reader(|txn| { let not_referenced_header = " SELECT COUNT(H_REF.hash) FROM Header AS H_REF JOIN DhtOp AS D_REF ON D_REF.header_hash = H_REF.hash WHERE D_REF.is_authored = 1 AND ( H_REF.original_header_hash = Header.hash OR H_REF.deletes_header_hash = Header.hash ) "; let sql = format!( " SELECT DISTINCT Entry.blob FROM Entry JOIN Header ON Header.entry_hash = Entry.hash JOIN DhtOp ON Header.hash = DhtOp.header_hash WHERE DhtOp.is_authored = 1 AND Entry.access_type IS NOT NULL AND ({}) = 0 ", not_referenced_header ); txn.prepare(&sql)? .query_and_then([], |row| from_blob(row.get("blob")?))? .filter_map(|result: StateQueryResult<Entry>| match result { Ok(entry) => entry .as_cap_grant() .filter(|grant| !matches!(grant, CapGrant::ChainAuthor(_))) .filter(|grant| grant.is_valid(check_function, check_agent, check_secret)) .map(|cap| Some(Ok(cap))) .unwrap_or(None), Err(e) => Some(Err(e)), }) // if there are still multiple grants, fold them down based on specificity // authorship > assigned > transferable > unrestricted .fold( Ok(None), |acc: StateQueryResult<Option<CapGrant>>, grant| { let grant = grant?; let acc = acc?; let acc = match &grant { CapGrant::RemoteAgent(zome_call_cap_grant) => { match &zome_call_cap_grant.access { CapAccess::Assigned { .. } => match &acc { Some(CapGrant::RemoteAgent(acc_zome_call_cap_grant)) => { match acc_zome_call_cap_grant.access { // an assigned acc takes precedence CapAccess::Assigned { .. } => acc, // current grant takes precedence over all other accs _ => Some(grant), } } None => Some(grant), // authorship should be short circuit and filtered _ => unreachable!(), }, CapAccess::Transferable { .. } => match &acc { Some(CapGrant::RemoteAgent(acc_zome_call_cap_grant)) => { match acc_zome_call_cap_grant.access { // an assigned acc takes precedence CapAccess::Assigned { .. } => acc, // transferable acc takes precedence CapAccess::Transferable { .. } => acc, // current grant takes preference over other accs _ => Some(grant), } } None => Some(grant), // authorship should be short circuited and filtered by now _ => unreachable!(), }, CapAccess::Unrestricted => match acc { Some(_) => acc, None => Some(grant), }, } } // ChainAuthor should have short circuited and be filtered out already _ => unreachable!(), }; Ok(acc) }, ) })?; Ok(valid_cap_grant) } /// Query Headers in the source chain. /// This returns a Vec rather than an iterator because it is intended to be /// used by the `query` host function, which crosses the wasm boundary // FIXME: This query needs to be tested. pub async fn query(&self, query: QueryFilter) -> SourceChainResult<Vec<Element>> { let (range_min, range_max) = match query.sequence_range.clone() { Some(range) => (Some(range.start), Some(range.end)), None => (None, None), }; let author = self.author.clone(); let mut elements = self .vault .async_reader({ let query = query.clone(); move |txn| { let mut sql = " SELECT DISTINCT Header.hash AS header_hash, Header.blob AS header_blob " .to_string(); if query.include_entries { sql.push_str( " , Entry.blob AS entry_blob ", ); } sql.push_str( " FROM Header ", ); if query.include_entries { sql.push_str( " LEFT JOIN Entry On Header.entry_hash = Entry.hash ", ); } sql.push_str( " JOIN DhtOp On DhtOp.header_hash = Header.hash WHERE Header.author = :author AND DhtOp.is_authored = 1 AND (:range_min IS NULL OR Header.seq >= :range_min) AND (:range_max IS NULL OR Header.seq < :range_max) AND (:entry_type IS NULL OR Header.entry_type = :entry_type) AND (:header_type IS NULL OR Header.type = :header_type) ", ); let mut stmt = txn.prepare(&sql)?; let elements = stmt .query_and_then( named_params! { ":author": author.as_ref(), ":range_min": range_min, ":range_max": range_max, ":entry_type": query.entry_type, ":header_type": query.header_type, }, |row| { let header = from_blob::<SignedHeader>(row.get("header_blob")?)?; let SignedHeader(header, signature) = header; let hash: HeaderHash = row.get("header_hash")?; let header = HeaderHashed::with_pre_hashed(header, hash); let shh = SignedHeaderHashed::with_presigned(header, signature); let entry = if query.include_entries { let entry: Option<Vec<u8>> = row.get("entry_blob")?; match entry { Some(entry) => Some(from_blob::<Entry>(entry)?), None => None, } } else { None }; StateQueryResult::Ok(Element::new(shh, entry)) }, )? .collect::<StateQueryResult<Vec<_>>>(); elements } }) .await?; self.scratch.apply(|scratch| { let scratch_iter = scratch .headers() .filter(|shh| query.check(shh.header())) .filter_map(|shh| { let entry = match shh.header().entry_hash() { Some(eh) if query.include_entries => scratch.get_entry(eh).ok()?, _ => None, }; Some(Element::new(shh.clone(), entry)) }); elements.extend(scratch_iter); })?; Ok(elements) } pub async fn flush(&self) -> SourceChainResult<()> { // Nothing to write if self.scratch.apply(|s| s.is_empty())? { return Ok(()); } let (headers, ops, entries) = self.scratch.apply_and_then(|scratch| { let length = scratch.num_headers(); // The op related data ends up here. let mut ops = Vec::with_capacity(length); // Drain out the headers. let signed_headers = scratch.drain_headers().collect::<Vec<_>>(); // Headers end up back in here. let mut headers = Vec::with_capacity(signed_headers.len()); // Loop through each header and produce op related data. for shh in signed_headers { // &HeaderHash, &Header, EntryHash are needed to produce the ops. let entry_hash = shh.header().entry_hash().cloned(); let item = (shh.as_hash(), shh.header(), entry_hash); let ops_inner = produce_op_lights_from_iter(vec![item].into_iter(), 1)?; // Break apart the SignedHeaderHashed. let (header, sig) = shh.into_header_and_signature(); let (header, hash) = header.into_inner(); // We need to take the header by value and put it back each loop. let mut h = Some(header); for op in ops_inner { let op_type = op.get_type(); // Header is required by value to produce the DhtOpHash. let (header, op_hash) = UniqueForm::op_hash(op_type, h.expect("This can't be empty"))?; let op_order = OpOrder::new(op_type, header.timestamp()); let timestamp = header.timestamp(); let visibility = header.entry_type().map(|et| *et.visibility()); // Put the header back by value. let dependency = get_dependency(op_type, &header); h = Some(header); // Collect the DhtOpLight, DhtOpHash and OpOrder. ops.push((op, op_hash, op_order, timestamp, visibility, dependency)); } // Put the SignedHeaderHashed back together. let shh = SignedHeaderHashed::with_presigned( HeaderHashed::with_pre_hashed(h.expect("This can't be empty"), hash), sig, ); // Put the header back in the list. headers.push(shh); } // Drain out any entries. let entries = scratch.drain_entries().collect::<Vec<_>>(); SourceChainResult::Ok((headers, ops, entries)) })?; // Write the entries, headers and ops to the database in one transaction. let author = self.author.clone(); let persisted_head = self.persisted_head.clone(); self.vault .async_commit(move |txn| { // As at check. let (new_persisted_head, _) = chain_head_db(&txn, author)?; if headers.last().is_none() { // Nothing to write return Ok(()); } if persisted_head != new_persisted_head { return Err(SourceChainError::HeadMoved( Some(persisted_head), Some(new_persisted_head), )); } for entry in entries { insert_entry(txn, entry)?; } for header in headers { insert_header(txn, header)?; } for (op, op_hash, op_order, timestamp, visibility, dependency) in ops { let op_type = op.get_type(); insert_op_lite(txn, op, op_hash.clone(), true, op_order, timestamp)?; set_validation_status( txn, op_hash.clone(), holochain_zome_types::ValidationStatus::Valid, )?; set_dependency(txn, op_hash.clone(), dependency)?; // TODO: SHARDING: Check if we are the authority here. // StoreEntry ops with private entries are never gossiped or published // so we don't need to integrate them. // TODO: Can anything every depend on a private store entry op? I don't think so. if !(op_type == DhtOpType::StoreEntry && visibility == Some(EntryVisibility::Private)) { set_validation_stage( txn, op_hash, ValidationLimboStatus::AwaitingIntegration, )?; } } SourceChainResult::Ok(()) }) .await?; Ok(()) } } pub async fn genesis( vault: EnvWrite, dna_hash: DnaHash, agent_pubkey: AgentPubKey, membrane_proof: Option<SerializedBytes>, ) -> SourceChainResult<()> { let keystore = vault.keystore().clone(); let dna_header = Header::Dna(header::Dna { author: agent_pubkey.clone(), timestamp: timestamp::now(), hash: dna_hash, }); let dna_header = HeaderHashed::from_content_sync(dna_header); let dna_header = SignedHeaderHashed::new(&keystore, dna_header).await?; let dna_header_address = dna_header.as_hash().clone(); let element = Element::new(dna_header, None); let dna_ops = produce_op_lights_from_elements(vec![&element])?; let (dna_header, _) = element.into_inner(); // create the agent validation entry and add it directly to the store let agent_validation_header = Header::AgentValidationPkg(header::AgentValidationPkg { author: agent_pubkey.clone(), timestamp: timestamp::now(), header_seq: 1, prev_header: dna_header_address, membrane_proof, }); let agent_validation_header = HeaderHashed::from_content_sync(agent_validation_header); let agent_validation_header = SignedHeaderHashed::new(&keystore, agent_validation_header).await?; let avh_addr = agent_validation_header.as_hash().clone(); let element = Element::new(agent_validation_header, None); let avh_ops = produce_op_lights_from_elements(vec![&element])?; let (agent_validation_header, _) = element.into_inner(); // create a agent chain element and add it directly to the store let agent_header = Header::Create(header::Create { author: agent_pubkey.clone(), timestamp: timestamp::now(), header_seq: 2, prev_header: avh_addr, entry_type: header::EntryType::AgentPubKey, entry_hash: agent_pubkey.clone().into(), }); let agent_header = HeaderHashed::from_content_sync(agent_header); let agent_header = SignedHeaderHashed::new(&keystore, agent_header).await?; let element = Element::new(agent_header, Some(Entry::Agent(agent_pubkey))); let agent_ops = produce_op_lights_from_elements(vec![&element])?; let (agent_header, agent_entry) = element.into_inner(); let agent_entry = agent_entry.into_option(); vault .async_commit(move |txn| { source_chain::put_raw(txn, dna_header, dna_ops, None)?; source_chain::put_raw(txn, agent_validation_header, avh_ops, None)?; source_chain::put_raw(txn, agent_header, agent_ops, agent_entry)?; SourceChainResult::Ok(()) }) .await } pub fn put_raw( txn: &mut Transaction, shh: SignedHeaderHashed, ops: Vec<DhtOpLight>, entry: Option<Entry>, ) -> StateMutationResult<()> { let (header, signature) = shh.into_header_and_signature(); let (header, hash) = header.into_inner(); let mut header = Some(header); let mut hashes = Vec::with_capacity(ops.len()); for op in &ops { let op_type = op.get_type(); let (h, op_hash) = UniqueForm::op_hash(op_type, header.take().expect("This can't be empty"))?; let op_order = OpOrder::new(op_type, h.timestamp()); let timestamp = h.timestamp(); let visibility = h.entry_type().map(|et| *et.visibility()); let dependency = get_dependency(op_type, &h); header = Some(h); hashes.push(( op_hash, op_type, op_order, timestamp, visibility, dependency, )); } let shh = SignedHeaderHashed::with_presigned( HeaderHashed::with_pre_hashed(header.expect("This can't be empty"), hash), signature, ); if let Some(entry) = entry { insert_entry(txn, EntryHashed::from_content_sync(entry))?; } insert_header(txn, shh)?; for (op, (op_hash, op_type, op_order, timestamp, visibility, dependency)) in ops.into_iter().zip(hashes) { insert_op_lite(txn, op, op_hash.clone(), true, op_order, timestamp)?; set_dependency(txn, op_hash.clone(), dependency)?; // TODO: SHARDING: Check if we are the authority here. // StoreEntry ops with private entries are never gossiped or published // so we don't need to integrate them. // TODO: Can anything every depend on a private store entry op? I don't think so. if !(op_type == DhtOpType::StoreEntry && visibility == Some(EntryVisibility::Private)) { set_validation_stage(txn, op_hash, ValidationLimboStatus::Pending)?; } } Ok(()) } fn chain_head_db( txn: &Transaction, author: Arc<AgentPubKey>, ) -> SourceChainResult<(HeaderHash, u32)> { let chain_head = ChainHeadQuery::new(author); let (prev_header, last_header_seq) = chain_head .run(Txn::from(txn))? .ok_or(SourceChainError::ChainEmpty)?; Ok((prev_header, last_header_seq)) } fn chain_head_scratch(scratch: &Scratch, author: &AgentPubKey) -> Option<(HeaderHash, u32)> { scratch .headers() .filter_map(|shh| { if shh.header().author() == author { Some((shh.header_address().clone(), shh.header().header_seq())) } else { None } }) .max_by_key(|h| h.1) } #[cfg(test)] async fn _put_db<H: HeaderInner, B: HeaderBuilder<H>>( vault: holochain_types::env::EnvWrite, author: Arc<AgentPubKey>, header_builder: B, maybe_entry: Option<Entry>, ) -> SourceChainResult<HeaderHash> { let (prev_header, last_header_seq) = fresh_reader!(vault, |txn| { chain_head_db(&txn, author.clone()) })?; let header_seq = last_header_seq + 1; let common = HeaderBuilderCommon { author: (*author).clone(), timestamp: timestamp::now(), header_seq, prev_header: prev_header.clone(), }; let header = header_builder.build(common).into(); let header = HeaderHashed::from_content_sync(header); let header = SignedHeaderHashed::new(&vault.keystore(), header).await?; let element = Element::new(header, maybe_entry); let ops = produce_op_lights_from_elements(vec![&element])?; let (header, entry) = element.into_inner(); let entry = entry.into_option(); let hash = header.as_hash().clone(); vault.conn()?.with_commit_sync(|txn| { let (new_head, _) = chain_head_db(txn, author.clone())?; if new_head != prev_header { return Err(SourceChainError::HeadMoved( Some(prev_header), Some(new_head), )); } SourceChainResult::Ok(put_raw(txn, header, ops, entry)?) })?; Ok(hash) } /// dump the entire source chain as a pretty-printed json string pub async fn dump_state( vault: EnvRead, author: AgentPubKey, ) -> Result<SourceChainJsonDump, SourceChainError> { Ok(vault .async_reader(move |txn| { let elements = txn .prepare( " SELECT DISTINCT Header.blob AS header_blob, Entry.blob AS entry_blob, Header.hash AS header_hash FROM Header JOIN DhtOp ON DhtOp.header_hash = Header.hash LEFT JOIN Entry ON Header.entry_hash = Entry.hash WHERE DhtOp.is_authored = 1 AND Header.author = :author ORDER BY Header.seq ASC ", )? .query_and_then( named_params! { ":author": author, }, |row| { let SignedHeader(header, signature) = from_blob(row.get("header_blob")?)?; let header_address = row.get("header_hash")?; let entry: Option<Vec<u8>> = row.get("entry_blob")?; let entry: Option<Entry> = match entry { Some(entry) => Some(from_blob(entry)?), None => None, }; StateQueryResult::Ok(SourceChainJsonElement { signature, header_address, header, entry, }) }, )? .collect::<StateQueryResult<Vec<_>>>()?; let published_ops_count = txn.query_row( " SELECT COUNT(DhtOp.hash) FROM DhtOp JOIN Header ON DhtOp.header_hash = Header.hash WHERE DhtOp.is_authored = 1 AND Header.author = :author AND last_publish_time IS NOT NULL ", named_params! { ":author": author, }, |row| row.get(0), )?; StateQueryResult::Ok(SourceChainJsonDump { elements, published_ops_count, }) }) .await?) } #[cfg(test)] pub mod tests { use super::*; use crate::prelude::*; use ::fixt::prelude::*; use hdk::prelude::*; use matches::assert_matches; use crate::source_chain::SourceChainResult; use holochain_zome_types::Entry; #[tokio::test(flavor = "multi_thread")] async fn test_get_cap_grant() -> SourceChainResult<()> { let test_env = test_cell_env(); let env = test_env.env(); let secret = Some(CapSecretFixturator::new(Unpredictable).next().unwrap()); let access = CapAccess::from(secret.unwrap()); // @todo curry let _curry = CurryPayloadsFixturator::new(Empty).next().unwrap(); let function: GrantedFunction = ("foo".into(), "bar".into()); let mut functions: GrantedFunctions = BTreeSet::new(); functions.insert(function.clone()); let grant = ZomeCallCapGrant::new("tag".into(), access.clone(), functions.clone()); let mut agents = AgentPubKeyFixturator::new(Predictable); let alice = agents.next().unwrap(); let bob = agents.next().unwrap(); source_chain::genesis(env.clone(), fake_dna_hash(1), alice.clone(), None) .await .unwrap(); { let chain = SourceChain::new(env.clone().into(), alice.clone()).await?; assert_eq!( chain.valid_cap_grant(&function, &alice, secret.as_ref())?, Some(CapGrant::ChainAuthor(alice.clone())), ); // bob should not match anything as the secret hasn't been committed yet assert_eq!( chain.valid_cap_grant(&function, &bob, secret.as_ref())?, None ); } let (original_header_address, original_entry_address) = { let chain = SourceChain::new(env.clone().into(), alice.clone()).await?; let (entry, entry_hash) = EntryHashed::from_content_sync(Entry::CapGrant(grant.clone())).into_inner(); let header_builder = builder::Create { entry_type: EntryType::CapGrant, entry_hash: entry_hash.clone(), }; let header = chain.put(header_builder, Some(entry)).await?; chain.flush().await.unwrap(); (header, entry_hash) }; { let chain = SourceChain::new(env.clone().into(), alice.clone()).await?; // alice should find her own authorship with higher priority than the committed grant // even if she passes in the secret assert_eq!( chain.valid_cap_grant(&function, &alice, secret.as_ref())?, Some(CapGrant::ChainAuthor(alice.clone())), ); // bob should be granted with the committed grant as it matches the secret he passes to // alice at runtime assert_eq!( chain.valid_cap_grant(&function, &bob, secret.as_ref())?, Some(grant.clone().into()) ); } // let's roll the secret and assign the grant to bob specifically let mut assignees = BTreeSet::new(); assignees.insert(bob.clone()); let updated_secret = Some(CapSecretFixturator::new(Unpredictable).next().unwrap()); let updated_access = CapAccess::from((updated_secret.clone().unwrap(), assignees)); let updated_grant = ZomeCallCapGrant::new("tag".into(), updated_access.clone(), functions); let (updated_header_hash, updated_entry_hash) = { let chain = SourceChain::new(env.clone().into(), alice.clone()).await?; let (entry, entry_hash) = EntryHashed::from_content_sync(Entry::CapGrant(updated_grant.clone())).into_inner(); let header_builder = builder::Update { entry_type: EntryType::CapGrant, entry_hash: entry_hash.clone(), original_header_address, original_entry_address, }; let header = chain.put(header_builder, Some(entry)).await?; chain.flush().await.unwrap(); (header, entry_hash) }; { let chain = SourceChain::new(env.clone().into(), alice.clone()).await?; // alice should find her own authorship with higher priority than the committed grant // even if she passes in the secret assert_eq!( chain.valid_cap_grant(&function, &alice, secret.as_ref())?, Some(CapGrant::ChainAuthor(alice.clone())), ); assert_eq!( chain.valid_cap_grant(&function, &alice, updated_secret.as_ref())?, Some(CapGrant::ChainAuthor(alice.clone())), ); // bob MUST provide the updated secret as the old one is invalidated by the new one assert_eq!( chain.valid_cap_grant(&function, &bob, secret.as_ref())?, None ); assert_eq!( chain.valid_cap_grant(&function, &bob, updated_secret.as_ref())?, Some(updated_grant.into()) ); } { let chain = SourceChain::new(env.clone().into(), alice.clone()).await?; let header_builder = builder::Delete { deletes_address: updated_header_hash, deletes_entry_address: updated_entry_hash, }; chain.put(header_builder, None).await?; chain.flush().await.unwrap(); } { let chain = SourceChain::new(env.clone().into(), alice.clone()).await?; // alice should find her own authorship assert_eq!( chain.valid_cap_grant(&function, &alice, secret.as_ref())?, Some(CapGrant::ChainAuthor(alice.clone())), ); assert_eq!( chain.valid_cap_grant(&function, &alice, updated_secret.as_ref())?, Some(CapGrant::ChainAuthor(alice)), ); // bob has no access assert_eq!( chain.valid_cap_grant(&function, &bob, secret.as_ref())?, None ); assert_eq!( chain.valid_cap_grant(&function, &bob, updated_secret.as_ref())?, None ); } Ok(()) } // @todo bring all this back when we want to administer cap claims better // #[tokio::test(flavor = "multi_thread")] // async fn test_get_cap_claim() -> SourceChainResult<()> { // let test_env = test_cell_env(); // let env = test_env.env(); // let env = env.conn().unwrap().await; // let secret = CapSecretFixturator::new(Unpredictable).next().unwrap(); // let agent_pubkey = fake_agent_pubkey_1().into(); // let claim = CapClaim::new("tag".into(), agent_pubkey, secret.clone()); // { // let mut store = SourceChainBuf::new(env.clone().into(), &env).await?; // store // .genesis(fake_dna_hash(1), fake_agent_pubkey_1(), None) // .await?; // arc.conn().unwrap().with_commit(|writer| store.flush_to_txn(writer))?; // } // // { // let mut chain = SourceChain::new(env.clone().into(), &env).await?; // chain.put_cap_claim(claim.clone()).await?; // // // ideally the following would work, but it won't because currently // // we can't get claims from the scratch space // // this will be fixed once we add the capability index // // // assert_eq!( // // chain.get_persisted_cap_claim_by_secret(&secret)?, // // Some(claim.clone()) // // ); // // arc.conn().unwrap().with_commit(|writer| chain.flush_to_txn(writer))?; // } // // { // let chain = SourceChain::new(env.clone().into(), &env).await?; // assert_eq!( // chain.get_persisted_cap_claim_by_secret(&secret).await?, // Some(claim) // ); // } // // Ok(()) #[tokio::test(flavor = "multi_thread")] async fn source_chain_buffer_iter_back() -> SourceChainResult<()> { observability::test_run().ok(); let test_env = test_cell_env(); let vault = test_env.env(); let author = test_env.cell_id().unwrap().agent_pubkey().clone(); let author = Arc::new(author); fresh_reader_test!(vault, |txn| { assert_matches!( chain_head_db(&txn, author.clone()), Err(SourceChainError::ChainEmpty) ); }); genesis( vault.clone().into(), fixt!(DnaHash), (*author).clone(), None, ) .await .unwrap(); let source_chain = SourceChain::new(vault.clone().into(), (*author).clone()) .await .unwrap(); let entry = Entry::App(fixt!(AppEntryBytes)); let create = builder::Create { entry_type: EntryType::App(fixt!(AppEntryType)), entry_hash: EntryHash::with_data_sync(&entry), }; let h1 = source_chain.put(create, Some(entry)).await.unwrap(); let entry = Entry::App(fixt!(AppEntryBytes)); let create = builder::Create { entry_type: EntryType::App(fixt!(AppEntryType)), entry_hash: EntryHash::with_data_sync(&entry), }; let h2 = source_chain.put(create, Some(entry)).await.unwrap(); source_chain.flush().await.unwrap(); fresh_reader_test!(vault, |txn| { assert_eq!(chain_head_db(&txn, author.clone()).unwrap().0, h2); // get the full element let store = Txn::from(&txn); let h1_element_fetched = store .get_element(&h1.clone().into()) .expect("error retrieving") .expect("entry not found"); let h2_element_fetched = store .get_element(&h2.clone().into()) .expect("error retrieving") .expect("entry not found"); assert_eq!(h1, *h1_element_fetched.header_address()); assert_eq!(h2, *h2_element_fetched.header_address()); }); // check that you can iterate on the chain let source_chain = SourceChain::new(vault.clone().into(), (*author).clone()) .await .unwrap(); let res = source_chain.query(QueryFilter::new()).await.unwrap(); assert_eq!(res.len(), 5); assert_eq!(*res[3].header_address(), h1); assert_eq!(*res[4].header_address(), h2); Ok(()) } #[tokio::test(flavor = "multi_thread")] async fn source_chain_buffer_dump_entries_json() -> SourceChainResult<()> { let test_env = test_cell_env(); let vault = test_env.env(); let author = test_env.cell_id().unwrap().agent_pubkey().clone(); genesis(vault.clone().into(), fixt!(DnaHash), author.clone(), None) .await .unwrap(); let json = dump_state(vault.clone().into(), author.clone()).await?; let json = serde_json::to_string_pretty(&json)?; let parsed: serde_json::Value = serde_json::from_str(&json).unwrap(); assert_eq!(parsed["elements"][0]["header"]["type"], "Dna"); assert_eq!(parsed["elements"][0]["entry"], serde_json::Value::Null); assert_eq!(parsed["elements"][2]["header"]["type"], "Create"); assert_eq!(parsed["elements"][2]["header"]["entry_type"], "AgentPubKey"); assert_eq!(parsed["elements"][2]["entry"]["entry_type"], "Agent"); assert_ne!( parsed["elements"][2]["entry"]["entry"], serde_json::Value::Null ); Ok(()) } }
40.272727
101
0.526175
eb28b4addc2b61a723af839fdcce0c3ca2ffed4f
69,833
use std::collections::{HashMap, HashSet}; use std::fmt::Write; use std::mem; use failure::{Error, ResultExt}; use parity_wasm; use parity_wasm::elements::*; use shared; use wasm_gc; use super::Bindgen; use descriptor::{Descriptor, VectorKind}; mod js2rust; use self::js2rust::Js2Rust; mod rust2js; use self::rust2js::Rust2Js; pub struct Context<'a> { pub globals: String, pub imports: String, pub footer: String, pub typescript: String, pub exposed_globals: HashSet<&'static str>, pub required_internal_exports: HashSet<&'static str>, pub config: &'a Bindgen, pub module: &'a mut Module, /// A map which maintains a list of what identifiers we've imported and what /// they're named locally. /// /// The `Option<String>` key is the module that identifiers were imported /// from, `None` being the global module. The second key is a map of /// identifiers we've already imported from the module to what they're /// called locally. pub imported_names: HashMap<Option<String>, HashMap<String, String>>, /// A set of all imported identifiers to the number of times they've been /// imported, used to generate new identifiers. pub imported_identifiers: HashMap<String, usize>, pub exported_classes: HashMap<String, ExportedClass>, pub function_table_needed: bool, pub run_descriptor: &'a Fn(&str) -> Option<Vec<u32>>, } #[derive(Default)] pub struct ExportedClass { comments: String, contents: String, typescript: String, constructor: Option<String>, fields: Vec<ClassField>, } struct ClassField { comments: Vec<String>, name: String, readonly: bool, } pub struct SubContext<'a, 'b: 'a> { pub program: &'a shared::Program, pub cx: &'a mut Context<'b>, } const INITIAL_SLAB_VALUES: &[&str] = &["undefined", "null", "true", "false"]; impl<'a> Context<'a> { fn export(&mut self, name: &str, contents: &str, comments: Option<String>) { let contents = contents.trim(); if let Some(ref c) = comments { self.globals.push_str(c); } let global = if self.use_node_require() { if contents.starts_with("class") { format!("{1}\nmodule.exports.{0} = {0};\n", name, contents) } else { format!("module.exports.{} = {};\n", name, contents) } } else if self.config.no_modules { if contents.starts_with("class") { format!("{1}\n__exports.{0} = {0};\n", name, contents) } else { format!("__exports.{} = {};\n", name, contents) } } else { if contents.starts_with("function") { format!("export function {}{}\n", name, &contents[8..]) } else if contents.starts_with("class") { format!("export {}\n", contents) } else { format!("export const {} = {};\n", name, contents) } }; self.global(&global); } fn require_internal_export(&mut self, name: &'static str) -> Result<(), Error> { if !self.required_internal_exports.insert(name) { return Ok(()); } if let Some(s) = self.module.export_section() { if s.entries().iter().any(|e| e.field() == name) { return Ok(()); } } bail!( "the exported function `{}` is required to generate bindings \ but it was not found in the wasm file, perhaps the `std` feature \ of the `wasm-bindgen` crate needs to be enabled?", name ); } pub fn finalize(&mut self, module_name: &str) -> Result<(String, String), Error> { self.write_classes()?; self.bind("__wbindgen_object_clone_ref", &|me| { me.expose_add_heap_object(); me.expose_get_object(); let bump_cnt = if me.config.debug { String::from( " if (typeof(val) === 'number') throw new Error('corrupt slab'); val.cnt += 1; ", ) } else { String::from("val.cnt += 1;") }; Ok(format!( " function(idx) {{ // If this object is on the stack promote it to the heap. if ((idx & 1) === 1) return addHeapObject(getObject(idx)); // Otherwise if the object is on the heap just bump the // refcount and move on const val = slab[idx >> 1]; {} return idx; }} ", bump_cnt )) })?; self.bind("__wbindgen_object_drop_ref", &|me| { me.expose_drop_ref(); Ok(String::from( " function(i) { dropRef(i); } ", )) })?; self.bind("__wbindgen_string_new", &|me| { me.expose_add_heap_object(); me.expose_get_string_from_wasm(); Ok(String::from( " function(p, l) { return addHeapObject(getStringFromWasm(p, l)); } ", )) })?; self.bind("__wbindgen_number_new", &|me| { me.expose_add_heap_object(); Ok(String::from( " function(i) { return addHeapObject(i); } ", )) })?; self.bind("__wbindgen_number_get", &|me| { me.expose_get_object(); me.expose_uint8_memory(); Ok(String::from( " function(n, invalid) { let obj = getObject(n); if (typeof(obj) === 'number') return obj; getUint8Memory()[invalid] = 1; return 0; } ", )) })?; self.bind("__wbindgen_is_null", &|me| { me.expose_get_object(); Ok(String::from( " function(idx) { return getObject(idx) === null ? 1 : 0; } ", )) })?; self.bind("__wbindgen_is_undefined", &|me| { me.expose_get_object(); Ok(String::from( " function(idx) { return getObject(idx) === undefined ? 1 : 0; } ", )) })?; self.bind("__wbindgen_boolean_get", &|me| { me.expose_get_object(); Ok(String::from( " function(i) { let v = getObject(i); if (typeof(v) === 'boolean') { return v ? 1 : 0; } else { return 2; } } ", )) })?; self.bind("__wbindgen_symbol_new", &|me| { me.expose_get_string_from_wasm(); me.expose_add_heap_object(); Ok(String::from( " function(ptr, len) { let a; if (ptr === 0) { a = Symbol(); } else { a = Symbol(getStringFromWasm(ptr, len)); } return addHeapObject(a); } ", )) })?; self.bind("__wbindgen_is_symbol", &|me| { me.expose_get_object(); Ok(String::from( " function(i) { return typeof(getObject(i)) === 'symbol' ? 1 : 0; } ", )) })?; self.bind("__wbindgen_is_object", &|me| { me.expose_get_object(); Ok(String::from( " function(i) { const val = getObject(i); return typeof(val) === 'object' && val !== null ? 1 : 0; } ", )) })?; self.bind("__wbindgen_is_function", &|me| { me.expose_get_object(); Ok(String::from( " function(i) { return typeof(getObject(i)) === 'function' ? 1 : 0; } ", )) })?; self.bind("__wbindgen_is_string", &|me| { me.expose_get_object(); Ok(String::from( " function(i) { return typeof(getObject(i)) === 'string' ? 1 : 0; } ", )) })?; self.bind("__wbindgen_string_get", &|me| { me.expose_pass_string_to_wasm()?; me.expose_get_object(); me.expose_uint32_memory(); Ok(String::from( " function(i, len_ptr) { let obj = getObject(i); if (typeof(obj) !== 'string') return 0; const [ptr, len] = passStringToWasm(obj); getUint32Memory()[len_ptr / 4] = len; return ptr; } ", )) })?; self.bind("__wbindgen_cb_drop", &|me| { me.expose_drop_ref(); Ok(String::from( " function(i) { let obj = getObject(i).original; obj.a = obj.b = 0; dropRef(i); } ", )) })?; self.bind("__wbindgen_cb_forget", &|me| { me.expose_drop_ref(); Ok(String::from( " function(i) { dropRef(i); } ", )) })?; self.bind("__wbindgen_json_parse", &|me| { me.expose_add_heap_object(); me.expose_get_string_from_wasm(); Ok(String::from( " function(ptr, len) { return addHeapObject(JSON.parse(getStringFromWasm(ptr, len))); } ", )) })?; self.bind("__wbindgen_json_serialize", &|me| { me.expose_get_object(); me.expose_pass_string_to_wasm()?; me.expose_uint32_memory(); Ok(String::from( " function(idx, ptrptr) { const [ptr, len] = passStringToWasm(JSON.stringify(getObject(idx))); getUint32Memory()[ptrptr / 4] = ptr; return len; } ", )) })?; self.bind("__wbindgen_jsval_eq", &|me| { me.expose_get_object(); Ok(String::from( " function(a, b) { return getObject(a) === getObject(b) ? 1 : 0; } ", )) })?; self.unexport_unused_internal_exports(); self.gc()?; // Note that it's important `throw` comes last *after* we gc. The // `__wbindgen_malloc` function may call this but we only want to // generate code for this if it's actually live (and __wbindgen_malloc // isn't gc'd). self.bind("__wbindgen_throw", &|me| { me.expose_get_string_from_wasm(); Ok(String::from( " function(ptr, len) { throw new Error(getStringFromWasm(ptr, len)); } ", )) })?; self.rewrite_imports(module_name); let mut js = if self.config.no_modules { format!( " (function() {{ var wasm; const __exports = {{}}; {globals} function init(wasm_path) {{ const fetchPromise = fetch(wasm_path); let resultPromise; if (typeof WebAssembly.instantiateStreaming === 'function') {{ resultPromise = WebAssembly.instantiateStreaming(fetchPromise, {{ './{module}': __exports }}); }} else {{ resultPromise = fetchPromise .then(response => response.arrayBuffer()) .then(buffer => WebAssembly.instantiate(buffer, {{ './{module}': __exports }})); }} return resultPromise.then(({{instance}}) => {{ wasm = init.wasm = instance.exports; return; }}); }}; self.{global_name} = Object.assign(init, __exports); }})(); ", globals = self.globals, module = module_name, global_name = self.config.no_modules_global .as_ref() .map(|s| &**s) .unwrap_or("wasm_bindgen"), ) } else { let import_wasm = if self.globals.len() == 0 { String::new() } else if self.use_node_require() { self.footer .push_str(&format!("wasm = require('./{}_bg');", module_name)); format!("var wasm;") } else { format!("import * as wasm from './{}_bg';", module_name) }; format!( "\ /* tslint:disable */\n\ {import_wasm}\n\ {imports}\n\ {globals}\n\ {footer}", import_wasm = import_wasm, globals = self.globals, imports = self.imports, footer = self.footer, ) }; self.export_table(); self.gc()?; while js.contains("\n\n\n") { js = js.replace("\n\n\n", "\n\n"); } Ok((js, self.typescript.clone())) } fn bind( &mut self, name: &str, f: &Fn(&mut Self) -> Result<String, Error>, ) -> Result<(), Error> { if !self.wasm_import_needed(name) { return Ok(()); } let contents = f(self) .with_context(|_| format!("failed to generate internal JS function `{}`", name))?; self.export(name, &contents, None); Ok(()) } fn write_classes(&mut self) -> Result<(), Error> { let classes = mem::replace(&mut self.exported_classes, Default::default()); for (class, exports) in classes { self.write_class(&class, &exports)?; } Ok(()) } fn write_class(&mut self, name: &str, class: &ExportedClass) -> Result<(), Error> { let mut dst = format!("class {} {{\n", name); let mut ts_dst = format!("export {}", dst); if self.config.debug || class.constructor.is_some() { self.expose_constructor_token(); dst.push_str(&format!( " static __construct(ptr) {{ return new {}(new ConstructorToken(ptr)); }} constructor(...args) {{ if (args.length === 1 && args[0] instanceof ConstructorToken) {{ this.ptr = args[0].ptr; return; }} ", name )); if let Some(ref constructor) = class.constructor { ts_dst.push_str(&format!("constructor(...args: any[]);\n")); dst.push_str(&format!( " // This invocation of new will call this constructor with a ConstructorToken let instance = {class}.{constructor}(...args); this.ptr = instance.ptr; ", class = name, constructor = constructor )); } else { dst.push_str( "throw new Error('you cannot invoke `new` directly without having a \ method annotated a constructor');\n", ); } dst.push_str("}"); } else { dst.push_str(&format!( " static __construct(ptr) {{ return new {}(ptr); }} constructor(ptr) {{ this.ptr = ptr; }} ", name )); } let new_name = shared::new_function(&name); if self.wasm_import_needed(&new_name) { self.expose_add_heap_object(); self.export( &new_name, &format!( " function(ptr) {{ return addHeapObject({}.__construct(ptr)); }} ", name ), None, ); } for field in class.fields.iter() { let wasm_getter = shared::struct_field_get(name, &field.name); let wasm_setter = shared::struct_field_set(name, &field.name); let descriptor = match self.describe(&wasm_getter) { None => continue, Some(d) => d, }; let set = { let mut cx = Js2Rust::new(&field.name, self); cx.method(true, false).argument(&descriptor)?.ret(&None)?; ts_dst.push_str(&format!( "{}{}: {}\n", if field.readonly { "readonly " } else { "" }, field.name, &cx.js_arguments[0].1 )); cx.finish("", &format!("wasm.{}", wasm_setter)).0 }; let (get, _ts, js_doc) = Js2Rust::new(&field.name, self) .method(true, false) .ret(&Some(descriptor))? .finish("", &format!("wasm.{}", wasm_getter)); if !dst.ends_with("\n") { dst.push_str("\n"); } dst.push_str(&format_doc_comments(&field.comments, Some(js_doc))); dst.push_str("get "); dst.push_str(&field.name); dst.push_str(&get); dst.push_str("\n"); if !field.readonly { dst.push_str("set "); dst.push_str(&field.name); dst.push_str(&set); } } dst.push_str(&format!( " free() {{ const ptr = this.ptr; this.ptr = 0; wasm.{}(ptr); }} ", shared::free_function(&name) )); ts_dst.push_str("free(): void;\n"); dst.push_str(&class.contents); ts_dst.push_str(&class.typescript); dst.push_str("}\n"); ts_dst.push_str("}\n"); self.export(&name, &dst, Some(class.comments.clone())); self.typescript.push_str(&ts_dst); Ok(()) } fn export_table(&mut self) { if !self.function_table_needed { return; } for section in self.module.sections_mut() { let exports = match *section { Section::Export(ref mut s) => s, _ => continue, }; let entry = ExportEntry::new("__wbg_function_table".to_string(), Internal::Table(0)); exports.entries_mut().push(entry); break; } } fn rewrite_imports(&mut self, module_name: &str) { for (name, contents) in self._rewrite_imports(module_name) { self.export(&name, &contents, None); } } fn _rewrite_imports(&mut self, module_name: &str) -> Vec<(String, String)> { let mut math_imports = Vec::new(); let imports = self .module .sections_mut() .iter_mut() .filter_map(|s| match *s { Section::Import(ref mut s) => Some(s), _ => None, }) .flat_map(|s| s.entries_mut()); for import in imports { if import.module() == "__wbindgen_placeholder__" { import.module_mut().truncate(0); import.module_mut().push_str("./"); import.module_mut().push_str(module_name); continue; } if import.module() != "env" { continue; } let renamed_import = format!("__wbindgen_{}", import.field()); let mut bind_math = |expr: &str| { math_imports.push((renamed_import.clone(), format!("function{}", expr))); }; // FIXME(#32): try to not use function shims match import.field() { "Math_acos" => bind_math("(x) { return Math.acos(x); }"), "Math_asin" => bind_math("(x) { return Math.asin(x); }"), "Math_atan" => bind_math("(x) { return Math.atan(x); }"), "Math_atan2" => bind_math("(x, y) { return Math.atan2(x, y); }"), "Math_cbrt" => bind_math("(x) { return Math.cbrt(x); }"), "Math_cosh" => bind_math("(x) { return Math.cosh(x); }"), "Math_expm1" => bind_math("(x) { return Math.expm1(x); }"), "Math_hypot" => bind_math("(x, y) { return Math.hypot(x, y); }"), "Math_log1p" => bind_math("(x) { return Math.log1p(x); }"), "Math_sinh" => bind_math("(x) { return Math.sinh(x); }"), "Math_tan" => bind_math("(x) { return Math.tan(x); }"), "Math_tanh" => bind_math("(x) { return Math.tanh(x); }"), "cos" => bind_math("(x) { return Math.cos(x); }"), "cosf" => bind_math("(x) { return Math.cos(x); }"), "exp" => bind_math("(x) { return Math.exp(x); }"), "expf" => bind_math("(x) { return Math.exp(x); }"), "log2" => bind_math("(x) { return Math.log2(x); }"), "log2f" => bind_math("(x) { return Math.log2(x); }"), "log10" => bind_math("(x) { return Math.log10(x); }"), "log10f" => bind_math("(x) { return Math.log10(x); }"), "log" => bind_math("(x) { return Math.log(x); }"), "logf" => bind_math("(x) { return Math.log(x); }"), "round" => bind_math("(x) { return Math.round(x); }"), "roundf" => bind_math("(x) { return Math.round(x); }"), "sin" => bind_math("(x) { return Math.sin(x); }"), "sinf" => bind_math("(x) { return Math.sin(x); }"), "pow" => bind_math("(x, y) { return Math.pow(x, y); }"), "powf" => bind_math("(x, y) { return Math.pow(x, y); }"), "exp2" => bind_math("(a) { return Math.pow(2, a); }"), "exp2f" => bind_math("(a) { return Math.pow(2, a); }"), "fmod" => bind_math("(a, b) { return a % b; }"), "fmodf" => bind_math("(a, b) { return a % b; }"), "fma" => bind_math("(a, b, c) { return (a * b) + c; }"), "fmaf" => bind_math("(a, b, c) { return (a * b) + c; }"), _ => continue, } import.module_mut().truncate(0); import.module_mut().push_str("./"); import.module_mut().push_str(module_name); *import.field_mut() = renamed_import.clone(); } math_imports } fn unexport_unused_internal_exports(&mut self) { let required = &self.required_internal_exports; for section in self.module.sections_mut() { let exports = match *section { Section::Export(ref mut s) => s, _ => continue, }; exports.entries_mut().retain(|export| { !export.field().starts_with("__wbindgen") || required.contains(export.field()) }); } } fn expose_drop_ref(&mut self) { if !self.exposed_globals.insert("drop_ref") { return; } self.expose_global_slab(); self.expose_global_slab_next(); let validate_owned = if self.config.debug { String::from( " if ((idx & 1) === 1) throw new Error('cannot drop ref of stack objects'); ", ) } else { String::new() }; let dec_ref = if self.config.debug { String::from( " if (typeof(obj) === 'number') throw new Error('corrupt slab'); obj.cnt -= 1; if (obj.cnt > 0) return; ", ) } else { String::from( " obj.cnt -= 1; if (obj.cnt > 0) return; ", ) }; self.global(&format!( " function dropRef(idx) {{ {} idx = idx >> 1; if (idx < {}) return; let obj = slab[idx]; {} // If we hit 0 then free up our space in the slab slab[idx] = slab_next; slab_next = idx; }} ", validate_owned, INITIAL_SLAB_VALUES.len(), dec_ref )); } fn expose_global_stack(&mut self) { if !self.exposed_globals.insert("stack") { return; } self.global(&format!( " const stack = []; " )); if self.config.debug { self.export( "assertStackEmpty", " function() { if (stack.length === 0) return; throw new Error('stack is not currently empty'); } ", None, ); } } fn expose_global_slab(&mut self) { if !self.exposed_globals.insert("slab") { return; } let initial_values = INITIAL_SLAB_VALUES.iter() .map(|s| format!("{{ obj: {} }}", s)) .collect::<Vec<_>>(); self.global(&format!("const slab = [{}];", initial_values.join(", "))); if self.config.debug { self.export( "assertSlabEmpty", &format!( " function() {{ for (let i = {}; i < slab.length; i++) {{ if (typeof(slab[i]) === 'number') continue; throw new Error('slab is not currently empty'); }} }} ", initial_values.len() ), None, ); } } fn expose_global_slab_next(&mut self) { if !self.exposed_globals.insert("slab_next") { return; } self.expose_global_slab(); self.global( " let slab_next = slab.length; ", ); } fn expose_get_object(&mut self) { if !self.exposed_globals.insert("get_object") { return; } self.expose_global_stack(); self.expose_global_slab(); let get_obj = if self.config.debug { String::from( " if (typeof(val) === 'number') throw new Error('corrupt slab'); return val.obj; ", ) } else { String::from( " return val.obj; ", ) }; self.global(&format!( " function getObject(idx) {{ if ((idx & 1) === 1) {{ return stack[idx >> 1]; }} else {{ const val = slab[idx >> 1]; {} }} }} ", get_obj )); } fn expose_assert_num(&mut self) { if !self.exposed_globals.insert("assert_num") { return; } self.global(&format!( " function _assertNum(n) {{ if (typeof(n) !== 'number') throw new Error('expected a number argument'); }} " )); } fn expose_assert_bool(&mut self) { if !self.exposed_globals.insert("assert_bool") { return; } self.global(&format!( " function _assertBoolean(n) {{ if (typeof(n) !== 'boolean') {{ throw new Error('expected a boolean argument'); }} }} " )); } fn expose_pass_string_to_wasm(&mut self) -> Result<(), Error> { if !self.exposed_globals.insert("pass_string_to_wasm") { return Ok(()); } self.require_internal_export("__wbindgen_malloc")?; self.expose_text_encoder(); self.expose_uint8_memory(); let debug = if self.config.debug { " if (typeof(arg) !== 'string') throw new Error('expected a string argument'); " } else { "" }; self.global(&format!( " function passStringToWasm(arg) {{ {} const buf = cachedEncoder.encode(arg); const ptr = wasm.__wbindgen_malloc(buf.length); getUint8Memory().set(buf, ptr); return [ptr, buf.length]; }} ", debug )); Ok(()) } fn expose_pass_array8_to_wasm(&mut self) -> Result<(), Error> { self.expose_uint8_memory(); self.pass_array_to_wasm("passArray8ToWasm", "getUint8Memory", 1) } fn expose_pass_array16_to_wasm(&mut self) -> Result<(), Error> { self.expose_uint16_memory(); self.pass_array_to_wasm("passArray16ToWasm", "getUint16Memory", 2) } fn expose_pass_array32_to_wasm(&mut self) -> Result<(), Error> { self.expose_uint32_memory(); self.pass_array_to_wasm("passArray32ToWasm", "getUint32Memory", 4) } fn expose_pass_array64_to_wasm(&mut self) -> Result<(), Error> { self.expose_uint64_memory(); self.pass_array_to_wasm("passArray64ToWasm", "getUint64Memory", 8) } fn expose_pass_array_f32_to_wasm(&mut self) -> Result<(), Error> { self.expose_f32_memory(); self.pass_array_to_wasm("passArrayF32ToWasm", "getFloat32Memory", 4) } fn expose_pass_array_f64_to_wasm(&mut self) -> Result<(), Error> { self.expose_f64_memory(); self.pass_array_to_wasm("passArrayF64ToWasm", "getFloat64Memory", 8) } fn expose_pass_array_jsvalue_to_wasm(&mut self) -> Result<(), Error> { if !self.exposed_globals.insert("pass_array_jsvalue") { return Ok(()); } self.require_internal_export("__wbindgen_malloc")?; self.expose_uint32_memory(); self.expose_add_heap_object(); self.global(" function passArrayJsValueToWasm(array) { const ptr = wasm.__wbindgen_malloc(array.length * 4); const mem = getUint32Memory(); for (let i = 0; i < array.length; i++) { mem[ptr / 4 + i] = addHeapObject(array[i]); } return [ptr, array.length]; } "); Ok(()) } fn pass_array_to_wasm( &mut self, name: &'static str, delegate: &str, size: usize, ) -> Result<(), Error> { if !self.exposed_globals.insert(name) { return Ok(()); } self.require_internal_export("__wbindgen_malloc")?; self.global(&format!( " function {}(arg) {{ const ptr = wasm.__wbindgen_malloc(arg.length * {size}); {}().set(arg, ptr / {size}); return [ptr, arg.length]; }} ", name, delegate, size = size )); Ok(()) } fn expose_text_encoder(&mut self) { if !self.exposed_globals.insert("text_encoder") { return; } if self.config.nodejs_experimental_modules { self.imports .push_str("import { TextEncoder } from 'util';\n"); } else if self.config.nodejs { self.global( " const TextEncoder = require('util').TextEncoder; ", ); } else if !(self.config.browser || self.config.no_modules) { self.global( " const TextEncoder = typeof self === 'object' && self.TextEncoder ? self.TextEncoder : require('util').TextEncoder; ", ); } self.global( " let cachedEncoder = new TextEncoder('utf-8'); ", ); } fn expose_text_decoder(&mut self) { if !self.exposed_globals.insert("text_decoder") { return; } if self.config.nodejs_experimental_modules { self.imports .push_str("import { TextDecoder } from 'util';\n"); } else if self.config.nodejs { self.global( " const TextDecoder = require('util').TextDecoder; ", ); } else if !(self.config.browser || self.config.no_modules) { self.global( " const TextDecoder = typeof self === 'object' && self.TextDecoder ? self.TextDecoder : require('util').TextDecoder; ", ); } self.global( " let cachedDecoder = new TextDecoder('utf-8'); ", ); } fn expose_constructor_token(&mut self) { if !self.exposed_globals.insert("ConstructorToken") { return; } self.global( " class ConstructorToken { constructor(ptr) { this.ptr = ptr; } } ", ); } fn expose_get_string_from_wasm(&mut self) { if !self.exposed_globals.insert("get_string_from_wasm") { return; } self.expose_text_decoder(); self.expose_uint8_memory(); self.global( " function getStringFromWasm(ptr, len) { return cachedDecoder.decode(getUint8Memory().subarray(ptr, ptr + len)); } ", ); } fn expose_get_array_js_value_from_wasm(&mut self) { if !self.exposed_globals.insert("get_array_js_value_from_wasm") { return; } self.expose_uint32_memory(); self.expose_take_object(); self.global( " function getArrayJsValueFromWasm(ptr, len) { const mem = getUint32Memory(); const slice = mem.subarray(ptr / 4, ptr / 4 + len); const result = []; for (let i = 0; i < slice.length; i++) { result.push(takeObject(slice[i])); } return result; } ", ); } fn expose_get_array_i8_from_wasm(&mut self) { self.expose_int8_memory(); self.arrayget("getArrayI8FromWasm", "getInt8Memory", 1); } fn expose_get_array_u8_from_wasm(&mut self) { self.expose_uint8_memory(); self.arrayget("getArrayU8FromWasm", "getUint8Memory", 1); } fn expose_get_array_i16_from_wasm(&mut self) { self.expose_int16_memory(); self.arrayget("getArrayI16FromWasm", "getInt16Memory", 2); } fn expose_get_array_u16_from_wasm(&mut self) { self.expose_uint16_memory(); self.arrayget("getArrayU16FromWasm", "getUint16Memory", 2); } fn expose_get_array_i32_from_wasm(&mut self) { self.expose_int32_memory(); self.arrayget("getArrayI32FromWasm", "getInt32Memory", 4); } fn expose_get_array_u32_from_wasm(&mut self) { self.expose_uint32_memory(); self.arrayget("getArrayU32FromWasm", "getUint32Memory", 4); } fn expose_get_array_i64_from_wasm(&mut self) { self.expose_int64_memory(); self.arrayget("getArrayI64FromWasm", "getInt64Memory", 8); } fn expose_get_array_u64_from_wasm(&mut self) { self.expose_uint64_memory(); self.arrayget("getArrayU64FromWasm", "getUint64Memory", 8); } fn expose_get_array_f32_from_wasm(&mut self) { self.expose_f32_memory(); self.arrayget("getArrayF32FromWasm", "getFloat32Memory", 4); } fn expose_get_array_f64_from_wasm(&mut self) { self.expose_f64_memory(); self.arrayget("getArrayF64FromWasm", "getFloat64Memory", 8); } fn arrayget(&mut self, name: &'static str, mem: &'static str, size: usize) { if !self.exposed_globals.insert(name) { return; } self.global(&format!( " function {name}(ptr, len) {{ return {mem}().subarray(ptr / {size}, ptr / {size} + len); }} ", name = name, mem = mem, size = size, )); } fn expose_int8_memory(&mut self) { self.memview("getInt8Memory", "Int8Array"); } fn expose_uint8_memory(&mut self) { self.memview("getUint8Memory", "Uint8Array"); } fn expose_int16_memory(&mut self) { self.memview("getInt16Memory", "Int16Array"); } fn expose_uint16_memory(&mut self) { self.memview("getUint16Memory", "Uint16Array"); } fn expose_int32_memory(&mut self) { self.memview("getInt32Memory", "Int32Array"); } fn expose_uint32_memory(&mut self) { self.memview("getUint32Memory", "Uint32Array"); } fn expose_int64_memory(&mut self) { self.memview("getInt64Memory", "BigInt64Array"); } fn expose_uint64_memory(&mut self) { self.memview("getUint64Memory", "BigUint64Array"); } fn expose_f32_memory(&mut self) { self.memview("getFloat32Memory", "Float32Array"); } fn expose_f64_memory(&mut self) { self.memview("getFloat64Memory", "Float64Array"); } fn memview_function(&mut self, t: VectorKind) -> &'static str { match t { VectorKind::String => { self.expose_uint8_memory(); "getUint8Memory" } VectorKind::I8 => { self.expose_int8_memory(); "getInt8Memory" } VectorKind::U8 => { self.expose_uint8_memory(); "getUint8Memory" } VectorKind::I16 => { self.expose_int16_memory(); "getInt16Memory" } VectorKind::U16 => { self.expose_uint16_memory(); "getUint16Memory" } VectorKind::I32 => { self.expose_int32_memory(); "getInt32Memory" } VectorKind::U32 => { self.expose_uint32_memory(); "getUint32Memory" } VectorKind::I64 => { self.expose_int64_memory(); "getInt64Memory" } VectorKind::U64 => { self.expose_uint64_memory(); "getUint64Memory" } VectorKind::F32 => { self.expose_f32_memory(); "getFloat32Memory" } VectorKind::F64 => { self.expose_f64_memory(); "getFloat64Memory" } VectorKind::Anyref => { self.expose_uint32_memory(); "getUint32Memory" } } } fn memview(&mut self, name: &'static str, js: &str) { if !self.exposed_globals.insert(name) { return; } self.global(&format!( " let cache{name} = null; function {name}() {{ if (cache{name} === null || cache{name}.buffer !== wasm.memory.buffer) {{ cache{name} = new {js}(wasm.memory.buffer); }} return cache{name}; }} ", name = name, js = js, )); } fn expose_assert_class(&mut self) { if !self.exposed_globals.insert("assert_class") { return; } self.global( " function _assertClass(instance, klass) { if (!(instance instanceof klass)) { throw new Error(`expected instance of ${klass.name}`); } return instance.ptr; } ", ); } fn expose_borrowed_objects(&mut self) { if !self.exposed_globals.insert("borrowed_objects") { return; } self.expose_global_stack(); self.global( " function addBorrowedObject(obj) { stack.push(obj); return ((stack.length - 1) << 1) | 1; } ", ); } fn expose_take_object(&mut self) { if !self.exposed_globals.insert("take_object") { return; } self.expose_get_object(); self.expose_drop_ref(); self.global( " function takeObject(idx) { const ret = getObject(idx); dropRef(idx); return ret; } ", ); } fn expose_add_heap_object(&mut self) { if !self.exposed_globals.insert("add_heap_object") { return; } self.expose_global_slab(); self.expose_global_slab_next(); let set_slab_next = if self.config.debug { String::from( " if (typeof(next) !== 'number') throw new Error('corrupt slab'); slab_next = next; ", ) } else { String::from( " slab_next = next; ", ) }; self.global(&format!( " function addHeapObject(obj) {{ if (slab_next === slab.length) slab.push(slab.length + 1); const idx = slab_next; const next = slab[idx]; {} slab[idx] = {{ obj, cnt: 1 }}; return idx << 1; }} ", set_slab_next )); } fn wasm_import_needed(&self, name: &str) -> bool { let imports = match self.module.import_section() { Some(s) => s, None => return false, }; imports .entries() .iter() .any(|i| i.module() == "__wbindgen_placeholder__" && i.field() == name) } fn pass_to_wasm_function(&mut self, t: VectorKind) -> Result<&'static str, Error> { let s = match t { VectorKind::String => { self.expose_pass_string_to_wasm()?; "passStringToWasm" } VectorKind::I8 | VectorKind::U8 => { self.expose_pass_array8_to_wasm()?; "passArray8ToWasm" } VectorKind::U16 | VectorKind::I16 => { self.expose_pass_array16_to_wasm()?; "passArray16ToWasm" } VectorKind::I32 | VectorKind::U32 => { self.expose_pass_array32_to_wasm()?; "passArray32ToWasm" } VectorKind::I64 | VectorKind::U64 => { self.expose_pass_array64_to_wasm()?; "passArray64ToWasm" } VectorKind::F32 => { self.expose_pass_array_f32_to_wasm()?; "passArrayF32ToWasm" } VectorKind::F64 => { self.expose_pass_array_f64_to_wasm()?; "passArrayF64ToWasm" } VectorKind::Anyref => { self.expose_pass_array_jsvalue_to_wasm()?; "passArrayJsValueToWasm" } }; Ok(s) } fn expose_get_vector_from_wasm(&mut self, ty: VectorKind) -> &'static str { match ty { VectorKind::String => { self.expose_get_string_from_wasm(); "getStringFromWasm" } VectorKind::I8 => { self.expose_get_array_i8_from_wasm(); "getArrayI8FromWasm" } VectorKind::U8 => { self.expose_get_array_u8_from_wasm(); "getArrayU8FromWasm" } VectorKind::I16 => { self.expose_get_array_i16_from_wasm(); "getArrayI16FromWasm" } VectorKind::U16 => { self.expose_get_array_u16_from_wasm(); "getArrayU16FromWasm" } VectorKind::I32 => { self.expose_get_array_i32_from_wasm(); "getArrayI32FromWasm" } VectorKind::U32 => { self.expose_get_array_u32_from_wasm(); "getArrayU32FromWasm" } VectorKind::I64 => { self.expose_get_array_i64_from_wasm(); "getArrayI64FromWasm" } VectorKind::U64 => { self.expose_get_array_u64_from_wasm(); "getArrayU64FromWasm" } VectorKind::F32 => { self.expose_get_array_f32_from_wasm(); "getArrayF32FromWasm" } VectorKind::F64 => { self.expose_get_array_f64_from_wasm(); "getArrayF64FromWasm" } VectorKind::Anyref => { self.expose_get_array_js_value_from_wasm(); "getArrayJsValueFromWasm" } } } fn expose_get_global_argument(&mut self) -> Result<(), Error> { if !self.exposed_globals.insert("get_global_argument") { return Ok(()); } self.expose_uint32_memory(); self.expose_global_argument_ptr()?; self.global( " function getGlobalArgument(arg) { const idx = globalArgumentPtr() / 4 + arg; return getUint32Memory()[idx]; } ", ); Ok(()) } fn expose_global_argument_ptr(&mut self) -> Result<(), Error> { if !self.exposed_globals.insert("global_argument_ptr") { return Ok(()); } self.require_internal_export("__wbindgen_global_argument_ptr")?; self.global( " let cachedGlobalArgumentPtr = null; function globalArgumentPtr() { if (cachedGlobalArgumentPtr === null) { cachedGlobalArgumentPtr = wasm.__wbindgen_global_argument_ptr(); } return cachedGlobalArgumentPtr; } ", ); Ok(()) } fn expose_get_inherited_descriptor(&mut self) { if !self.exposed_globals.insert("get_inherited_descriptor") { return; } // It looks like while rare some browsers will move descriptors up the // property chain which runs the risk of breaking wasm-bindgen-generated // code because we're looking for precise descriptor functions rather // than relying on the prototype chain like most "normal JS" projects // do. // // As a result we have a small helper here which will walk the prototype // chain looking for a descriptor. For some more information on this see // #109 self.global( " function GetOwnOrInheritedPropertyDescriptor(obj, id) { while (obj) { let desc = Object.getOwnPropertyDescriptor(obj, id); if (desc) return desc; obj = Object.getPrototypeOf(obj); } throw new Error(`descriptor for id='${id}' not found`); } ", ); } fn expose_u32_cvt_shim(&mut self) -> &'static str { let name = "u32CvtShim"; if !self.exposed_globals.insert(name) { return name; } self.global(&format!("const {} = new Uint32Array(2);", name)); name } fn expose_int64_cvt_shim(&mut self) -> &'static str { let name = "int64CvtShim"; if !self.exposed_globals.insert(name) { return name; } let n = self.expose_u32_cvt_shim(); self.global(&format!( "const {} = new BigInt64Array({}.buffer);", name, n )); name } fn expose_uint64_cvt_shim(&mut self) -> &'static str { let name = "uint64CvtShim"; if !self.exposed_globals.insert(name) { return name; } let n = self.expose_u32_cvt_shim(); self.global(&format!( "const {} = new BigUint64Array({}.buffer);", name, n )); name } fn expose_is_like_none(&mut self) { if !self.exposed_globals.insert("is_like_none") { return } self.global(" function isLikeNone(x) { return x === undefined || x === null; } "); } fn gc(&mut self) -> Result<(), Error> { let module = mem::replace(self.module, Module::default()); let module = module.parse_names().unwrap_or_else(|p| p.1); let result = wasm_gc::Config::new() .demangle(self.config.demangle) .keep_debug(self.config.keep_debug || self.config.debug) .run(module, |m| parity_wasm::serialize(m).unwrap())?; *self.module = match result.into_module() { Ok(m) => m, Err(result) => deserialize_buffer(&result.into_bytes()?)?, }; Ok(()) } fn describe(&self, name: &str) -> Option<Descriptor> { let name = format!("__wbindgen_describe_{}", name); (self.run_descriptor)(&name).map(|d| Descriptor::decode(&d)) } fn global(&mut self, s: &str) { let s = s; let s = s.trim(); // Ensure a blank line between adjacent items, and ensure everything is // terminated with a newline. while !self.globals.ends_with("\n\n\n") && !self.globals.ends_with("*/\n") { self.globals.push_str("\n"); } self.globals.push_str(s); self.globals.push_str("\n"); } fn use_node_require(&self) -> bool { self.config.nodejs && !self.config.nodejs_experimental_modules } } impl<'a, 'b> SubContext<'a, 'b> { pub fn generate(&mut self) -> Result<(), Error> { for f in self.program.exports.iter() { self.generate_export(f).with_context(|_| { format!( "failed to generate bindings for Rust export `{}`", f.function.name ) })?; } for f in self.program.imports.iter() { self.generate_import(f)?; } for e in self.program.enums.iter() { self.generate_enum(e); } for s in self.program.structs.iter() { let mut class = self .cx .exported_classes .entry(s.name.clone()) .or_insert_with(Default::default); class.comments = format_doc_comments(&s.comments, None); class.fields.extend(s.fields.iter().map(|f| ClassField { name: f.name.clone(), readonly: f.readonly, comments: f.comments.clone(), })); } Ok(()) } fn generate_export(&mut self, export: &shared::Export) -> Result<(), Error> { if let Some(ref class) = export.class { return self.generate_export_for_class(class, export); } let descriptor = match self.cx.describe(&export.function.name) { None => return Ok(()), Some(d) => d, }; let (js, ts, js_doc) = Js2Rust::new(&export.function.name, self.cx) .process(descriptor.unwrap_function())? .finish("function", &format!("wasm.{}", export.function.name)); self.cx.export( &export.function.name, &js, Some(format_doc_comments(&export.comments, Some(js_doc))), ); self.cx.globals.push_str("\n"); self.cx.typescript.push_str("export "); self.cx.typescript.push_str(&ts); self.cx.typescript.push_str("\n"); Ok(()) } fn generate_export_for_class( &mut self, class_name: &str, export: &shared::Export, ) -> Result<(), Error> { let wasm_name = shared::struct_function_export_name(class_name, &export.function.name); let descriptor = match self.cx.describe(&wasm_name) { None => return Ok(()), Some(d) => d, }; let (js, ts, js_doc) = Js2Rust::new(&export.function.name, self.cx) .method(export.method, export.consumed) .process(descriptor.unwrap_function())? .finish("", &format!("wasm.{}", wasm_name)); let class = self .cx .exported_classes .entry(class_name.to_string()) .or_insert(ExportedClass::default()); class .contents .push_str(&format_doc_comments(&export.comments, Some(js_doc))); if !export.method { class.contents.push_str("static "); class.typescript.push_str("static "); } let constructors: Vec<String> = self .program .exports .iter() .filter(|x| x.class == Some(class_name.to_string())) .filter_map(|x| x.constructor.clone()) .collect(); class.constructor = match constructors.len() { 0 => None, 1 => Some(constructors[0].clone()), x @ _ => bail!("there must be only one constructor, not {}", x), }; class.contents.push_str(&export.function.name); class.contents.push_str(&js); class.contents.push_str("\n"); class.typescript.push_str(&ts); class.typescript.push_str("\n"); Ok(()) } fn generate_import(&mut self, import: &shared::Import) -> Result<(), Error> { match import.kind { shared::ImportKind::Function(ref f) => { self.generate_import_function(import, f).with_context(|_| { format!( "failed to generate bindings for JS import `{}`", f.function.name ) })?; } shared::ImportKind::Static(ref s) => { self.generate_import_static(import, s).with_context(|_| { format!("failed to generate bindings for JS import `{}`", s.name) })?; } shared::ImportKind::Type(ref ty) => { self.generate_import_type(import, ty).with_context(|_| { format!( "failed to generate bindings for JS import `{}`", ty.name, ) })?; } shared::ImportKind::Enum(_) => {} } Ok(()) } fn generate_import_static( &mut self, info: &shared::Import, import: &shared::ImportStatic, ) -> Result<(), Error> { // TODO: should support more types to import here let obj = self.import_name(info, &import.name)?; self.cx.expose_add_heap_object(); self.cx.export( &import.shim, &format!( " function() {{ return addHeapObject({}); }} ", obj ), None, ); Ok(()) } fn generate_import_function( &mut self, info: &shared::Import, import: &shared::ImportFunction, ) -> Result<(), Error> { if !self.cx.wasm_import_needed(&import.shim) { return Ok(()); } let descriptor = match self.cx.describe(&import.shim) { None => return Ok(()), Some(d) => d, }; let target = match &import.method { Some(shared::MethodData { class, kind }) => { let class = self.import_name(info, class)?; match kind { shared::MethodKind::Constructor => format!("new {}", class), shared::MethodKind::Operation(shared::Operation { is_static, kind }) => { let target = if import.structural { let location = if *is_static { &class } else { "this" }; match kind { shared::OperationKind::Regular => { let nargs = descriptor.unwrap_function().arguments.len(); let mut s = format!("function("); for i in 0..nargs - 1 { if i > 0 { drop(write!(s, ", ")); } drop(write!(s, "x{}", i)); } s.push_str(") { \nreturn this."); s.push_str(&import.function.name); s.push_str("("); for i in 0..nargs - 1 { if i > 0 { drop(write!(s, ", ")); } drop(write!(s, "x{}", i)); } s.push_str(");\n}"); s } shared::OperationKind::Getter(g) => format!( "function() {{ return {}.{}; }}", location, g ), shared::OperationKind::Setter(s) => format!( "function(y) {{ {}.{} = y; }}", location, s ), shared::OperationKind::IndexingGetter => format!( "function(y) {{ return {}[y]; }}", location ), shared::OperationKind::IndexingSetter => format!( "function(y, z) {{ {}[y] = z; }}", location ), shared::OperationKind::IndexingDeleter => format!( "function(y) {{ delete {}[y]; }}", location ), } } else { let (location, binding) = if *is_static { ("", format!(".bind({})", class)) } else { (".prototype", "".into()) }; match kind { shared::OperationKind::Regular => { format!("{}{}.{}{}", class, location, import.function.name, binding) } shared::OperationKind::Getter(g) => { self.cx.expose_get_inherited_descriptor(); format!( "GetOwnOrInheritedPropertyDescriptor({}{}, '{}').get{}", class, location, g, binding, ) } shared::OperationKind::Setter(s) => { self.cx.expose_get_inherited_descriptor(); format!( "GetOwnOrInheritedPropertyDescriptor({}{}, '{}').set{}", class, location, s, binding, ) } shared::OperationKind::IndexingGetter => panic!("indexing getter should be structural"), shared::OperationKind::IndexingSetter => panic!("indexing setter should be structural"), shared::OperationKind::IndexingDeleter => panic!("indexing deleter should be structural"), } }; let fallback = if import.structural { "".to_string() } else { format!( " || function() {{ throw new Error(`wasm-bindgen: {} does not exist`); }}", target ) }; self.cx.global(&format!( " const {}_target = {} {} ; ", import.shim, target, fallback )); format!( "{}_target{}", import.shim, if *is_static { "" } else { ".call" } ) } } } None => { let name = self.import_name(info, &import.function.name)?; if name.contains(".") { self.cx.global(&format!( " const {}_target = {}; ", import.shim, name )); format!("{}_target", import.shim) } else { name } } }; let js = Rust2Js::new(self.cx) .catch(import.catch) .process(descriptor.unwrap_function())? .finish(&target); self.cx.export(&import.shim, &js, None); Ok(()) } fn generate_import_type( &mut self, info: &shared::Import, import: &shared::ImportType, ) -> Result<(), Error> { if !self.cx.wasm_import_needed(&import.instanceof_shim) { return Ok(()); } let name = self.import_name(info, &import.name)?; self.cx.expose_get_object(); let body = format!(" function(idx) {{ return getObject(idx) instanceof {} ? 1 : 0; }} ", name, ); self.cx.export(&import.instanceof_shim, &body, None); Ok(()) } fn generate_enum(&mut self, enum_: &shared::Enum) { let mut variants = String::new(); for variant in enum_.variants.iter() { variants.push_str(&format!("{}:{},", variant.name, variant.value)); } self.cx.export( &enum_.name, &format!("Object.freeze({{ {} }})", variants), Some(format_doc_comments(&enum_.comments, None)), ); self.cx .typescript .push_str(&format!("export enum {} {{", enum_.name)); variants.clear(); for variant in enum_.variants.iter() { variants.push_str(&format!("{},", variant.name)); } self.cx.typescript.push_str(&variants); self.cx.typescript.push_str("}\n"); } fn import_name(&mut self, import: &shared::Import, item: &str) -> Result<String, Error> { // First up, imports don't work at all in `--no-modules` mode as we're // not sure how to import them. if self.cx.config.no_modules { if let Some(module) = &import.module { bail!( "import from `{}` module not allowed with `--no-modules`; \ use `--nodejs` or `--browser` instead", module ); } } // Figure out what identifier we're importing from the module. If we've // got a namespace we use that, otherwise it's the name specified above. let name_to_import = import.js_namespace .as_ref() .map(|s| &**s) .unwrap_or(item); // Here's where it's a bit tricky. We need to make sure that importing // the same identifier from two different modules works, and they're // named uniquely below. Additionally if we've already imported the same // identifier from the module in question then we'd like to reuse the // one that was previously imported. // // Our `imported_names` map keeps track of all imported identifiers from // modules, mapping the imported names onto names actually available for // use in our own module. If our identifier isn't present then we // generate a new identifier and are sure to generate the appropriate JS // import for our new identifier. let use_node_require = self.cx.use_node_require(); let imported_identifiers = &mut self.cx.imported_identifiers; let imports = &mut self.cx.imports; let identifier = self.cx.imported_names.entry(import.module.clone()) .or_insert_with(Default::default) .entry(name_to_import.to_string()) .or_insert_with(|| { let name = generate_identifier(name_to_import, imported_identifiers); if let Some(module) = &import.module { if use_node_require { imports.push_str(&format!( "const {} = require('{}').{};\n", name, module, name_to_import )); } else if name_to_import == name { imports.push_str(&format!( "import {{ {} }} from '{}';\n", name, module )); } else { imports.push_str(&format!( "import {{ {} as {} }} from '{}';\n", name_to_import, name, module )); } } name }); // If there's a namespace we didn't actually import `item` but rather // the namespace, so access through that. if import.js_namespace.is_some() { Ok(format!("{}.{}", identifier, item)) } else { Ok(identifier.to_string()) } } } fn generate_identifier(name: &str, used_names: &mut HashMap<String, usize>) -> String { let cnt = used_names.entry(name.to_string()).or_insert(0); *cnt += 1; if *cnt == 1 { name.to_string() } else { format!("{}{}", name, cnt) } } fn format_doc_comments(comments: &Vec<String>, js_doc_comments: Option<String>) -> String { let body: String = comments .iter() .map(|c| format!("*{}\n", c.trim_matches('"'))) .collect(); let doc = if let Some(docs) = js_doc_comments { docs.lines().map(|l| format!("* {} \n", l)).collect() } else { String::new() }; format!("/**\n{}{}*/\n", body, doc) }
33.476989
126
0.445935
e571d1e9a066c2c491430404b896cc355c2ce39e
3,538
use std::fs::File; use std::io::prelude::*; use rustc_serialize::json::{self}; static CONFIGFILE: &'static str = "cnf/webserver.json"; static DEFAULTMAPPINGFILE: &'static str = "cnf/mapping.json"; static LASTMAPPINGFILE: &'static str = "cnf/lastMapping.json"; #[derive(RustcEncodable, RustcDecodable)] pub struct Config { pub hash: String, pub websocket_port: i32, pub status_port: i32, pub telldus_client: String, pub telldus_password: String } #[allow(dead_code)] pub fn write_config() { //hash is for user=a and password=a let hash = "98398f51aa78aaf6309be3d93ad27fb1c1b21cb6".to_string(); let port = 8876; let config = Config{ hash: hash, websocket_port: port, status_port: port-1, telldus_client: "localhost:8890".to_string(), telldus_password: "passord".to_string() }; let data: String = json::encode(&config).unwrap(); println!("use echo '[data]' | jq . to prettyfi. Remember the quotes!"); println!("{}", data); } pub fn read_config() -> Option<Config> { let mut file = match File::open(CONFIGFILE) { Ok(file) => file, Err(_) => panic!("no such file") }; let mut json = String::new(); match file.read_to_string(&mut json) { Ok(file) => file, Err(_) => panic!("could not read file to string") }; return Some(json::decode(&json).unwrap()); } #[derive(RustcEncodable, RustcDecodable, Clone)] pub struct Mapping { pub zones: Vec<Zone> } pub fn read_mapping() -> Option<Mapping> { let mut file = match File::open(LASTMAPPINGFILE) { Ok(file) => file, Err(_) => match File::open(DEFAULTMAPPINGFILE) { Ok(file) => file, Err(_) => panic!("no such file") } }; let mut json = String::new(); match file.read_to_string(&mut json) { Ok(file) => file, Err(_) => panic!("could not read file to string") }; return Some(json::decode(&json).unwrap()); } pub fn write_mapping(mapping: &Mapping) { let data: String = json::encode(&mapping).unwrap(); let mut file = match File::create(LASTMAPPINGFILE) { Ok(file) => file, Err(_) => panic!("Could not create file {}",LASTMAPPINGFILE) }; match file.write_all(data.as_bytes()) { Ok(_) => println!("Wrote to file!"), Err(_) => panic!("Could not write to file {}", LASTMAPPINGFILE) }; } #[allow(dead_code)] pub fn write_mapping_test() { let sw1 = Switch{ id: 1, name: "sw1".to_string() }; let sw2 = Switch{ id: 2, name: "sw2".to_string() }; let mut switches = Vec::new(); switches.push(sw1); switches.push(sw2); let sw3 = Switch{ id: 3, name: "sw3".to_string() }; let sw4 = Switch{ id: 4, name: "sw4".to_string() }; let mut switches2 = Vec::new(); switches2.push(sw3); switches2.push(sw4); let zone1 = Zone{ id: 1, name: "zone1".to_string(), target: 1.0, switches: switches }; //let zone2 = Zone{ id: 2, name: "zone2".to_string(), target: 3.0, switches: switches2 }; let mut zones = Vec::new(); zones.push(zone1); //zones.push(zone2); let mapping = Mapping {zones: zones}; let data: String = json::encode(&mapping).unwrap(); println!("use echo '[data]' | jq . to prettyfi. Remember the quotes!"); println!("{}", data); } #[derive(RustcEncodable, RustcDecodable, Clone)] pub struct Zone { pub id: i32, pub name: String, pub target: f32, pub switches: Vec<Switch> } #[derive(RustcEncodable, RustcDecodable, Clone)] pub struct Switch { pub id: i32, pub name: String }
31.873874
172
0.622668
3904dc37556a9c6153db02ddb4cce7153f325d36
1,609
use crate::common::*; /// An expression. Note that the Just language grammar has both an /// `expression` production of additions (`a + b`) and values, and a /// `value` production of all other value types (for example strings, /// function calls, and parenthetical groups). /// /// The parser parses both values and expressions into `Expression`s. #[derive(PartialEq, Debug)] pub(crate) enum Expression<'src> { /// `contents` Backtick { contents: &'src str, token: Token<'src>, }, /// `name(arguments)` Call { thunk: Thunk<'src> }, /// `lhs + rhs` Concatination { lhs: Box<Expression<'src>>, rhs: Box<Expression<'src>>, }, /// `(contents)` Group { contents: Box<Expression<'src>> }, /// `"string_literal"` or `'string_literal'` StringLiteral { string_literal: StringLiteral<'src> }, /// `variable` Variable { name: Name<'src> }, } impl<'src> Expression<'src> { pub(crate) fn variables<'expression>(&'expression self) -> Variables<'expression, 'src> { Variables::new(self) } } impl<'src> Display for Expression<'src> { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { match self { Expression::Backtick { contents, .. } => write!(f, "`{}`", contents), Expression::Concatination { lhs, rhs } => write!(f, "{} + {}", lhs, rhs), Expression::StringLiteral { string_literal } => write!(f, "{}", string_literal), Expression::Variable { name } => write!(f, "{}", name.lexeme()), Expression::Call { thunk } => write!(f, "{}", thunk), Expression::Group { contents } => write!(f, "({})", contents), } } }
32.836735
91
0.610938
33020c66dcf4d9c8144d7f8a2a90a894d41ae87c
1,469
use gtk::prelude::*; use gtk::{Align, BoxBuilder, Orientation, Switch}; use gtk::{Application, ApplicationWindowBuilder}; fn main() { // Create a new application let app = Application::new(Some("org.gtk.example"), Default::default()); app.connect_activate(build_ui); // Run the application app.run(); } // ANCHOR: activate fn build_ui(application: &Application) { // Create a window let window = ApplicationWindowBuilder::new() .application(application) .title("My GTK App") .build(); // ANCHOR: switch // Create the switch let switch = Switch::new(); // Set and then immediately obtain state switch.set_property("state", &true).unwrap(); let current_state = switch .property("state") .expect("The property needs to exist and be readable.") .get::<bool>() .expect("The property needs to be of type `bool`."); // This prints: "The current state is true" println!("The current state is {}", current_state); // ANCHOR_END: switch // Set up box let gtk_box = BoxBuilder::new() .margin_top(12) .margin_bottom(12) .margin_start(12) .margin_end(12) .valign(Align::Center) .halign(Align::Center) .spacing(12) .orientation(Orientation::Vertical) .build(); gtk_box.append(&switch); window.set_child(Some(&gtk_box)); window.present(); } // ANCHOR_END: activate
27.203704
76
0.617427
1e2a8d8b55845131b969fdd3ae93c6f0eabd9f60
1,859
#[doc = "Register `CH9_DBG_CTDREQ` reader"] pub struct R(crate::R<CH9_DBG_CTDREQ_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CH9_DBG_CTDREQ_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CH9_DBG_CTDREQ_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<CH9_DBG_CTDREQ_SPEC>) -> Self { R(reader) } } #[doc = "Field `CH9_DBG_CTDREQ` reader - "] pub struct CH9_DBG_CTDREQ_R(crate::FieldReader<u8, u8>); impl CH9_DBG_CTDREQ_R { pub(crate) fn new(bits: u8) -> Self { CH9_DBG_CTDREQ_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for CH9_DBG_CTDREQ_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bits 0:5"] #[inline(always)] pub fn ch9_dbg_ctdreq(&self) -> CH9_DBG_CTDREQ_R { CH9_DBG_CTDREQ_R::new((self.bits & 0x3f) as u8) } } #[doc = "Read: get channel DREQ counter (i.e. how many accesses the DMA expects it can perform on the peripheral without overflow/underflow. Write any value: clears the counter, and cause channel to re-initiate DREQ handshake. This register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api). For information about available fields see [ch9_dbg_ctdreq](index.html) module"] pub struct CH9_DBG_CTDREQ_SPEC; impl crate::RegisterSpec for CH9_DBG_CTDREQ_SPEC { type Ux = u32; } #[doc = "`read()` method returns [ch9_dbg_ctdreq::R](R) reader structure"] impl crate::Readable for CH9_DBG_CTDREQ_SPEC { type Reader = R; } #[doc = "`reset()` method sets CH9_DBG_CTDREQ to value 0"] impl crate::Resettable for CH9_DBG_CTDREQ_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
32.614035
228
0.664874
abd7ee758545aef067df87a3c8e5a63875b735d7
15,291
use super::*; use std::hash::Hash; use std::marker::PhantomData; use std::sync::Arc; //use std::sync::Mutex; //use parking_lot::Mutex; // Trait containing pair rdd methods. No need of implicit conversion like in Spark version pub trait PairRdd<K: Data + Eq + Hash, V: Data>: Rdd<(K, V)> + Send + Sync { // fn iterator_any_in_pair_rdd(&self, split: Box<dyn Split>) -> Box<dyn Iterator<Item = Box<dyn AnyData>>> { // let log_output = format!("inside iterator_any pair rdd",); // env::log_file.lock().write(&log_output.as_bytes()); // Box::new(self.iterator(split).map(|(k, v)| { // Box::new(( // k, // Box::new(v) as Box<dyn AnyData>, // )) as Box<dyn AnyData> // })) // } fn combine_by_key<C: Data>( &self, create_combiner: Box<dyn serde_traitobject::Fn(V) -> C + Send + Sync>, merge_value: Box<dyn serde_traitobject::Fn((C, V)) -> C + Send + Sync>, merge_combiners: Box<dyn serde_traitobject::Fn((C, C)) -> C + Send + Sync>, partitioner: Box<dyn Partitioner>, // ) -> Arc<RddBox<(K, C)>> ) -> ShuffledRdd<K, V, C, Self> where // RT: RddBox<(K, V)>, Self: Sized + Serialize + Deserialize + 'static, { let aggregator = Arc::new(Aggregator::<K, V, C>::new( create_combiner, merge_value, merge_combiners, )); ShuffledRdd::new(self.get_rdd(), aggregator, partitioner) } fn group_by_key(&self, num_splits: usize) -> ShuffledRdd<K, V, Vec<V>, Self> where Self: Sized + Serialize + Deserialize + 'static, { self.group_by_key_using_partitioner( Box::new(HashPartitioner::<K>::new(num_splits)) as Box<dyn Partitioner> ) } fn group_by_key_using_partitioner( &self, partitioner: Box<dyn Partitioner>, ) -> ShuffledRdd<K, V, Vec<V>, Self> where Self: Sized + Serialize + Deserialize + 'static, { let create_combiner = Box::new(Fn!(|v: V| vec![v])); fn merge_value<V: Data>(mut buf: Vec<V>, v: V) -> Vec<V> { buf.push(v); buf // buf } let merge_value = Box::new(Fn!(|(buf, v)| merge_value::<V>(buf, v))); fn merge_combiners<V: Data>(mut b1: Vec<V>, mut b2: Vec<V>) -> Vec<V> { b1.append(&mut b2); b1 // b1 } let merge_combiners = Box::new(Fn!(|(b1, b2)| merge_combiners::<V>(b1, b2))); let bufs = self.combine_by_key(create_combiner, merge_value, merge_combiners, partitioner); bufs // unimplemented!() } fn reduce_by_key<F>(&self, func: F, num_splits: usize) -> ShuffledRdd<K, V, V, Self> where F: Fn((V, V)) -> V + PartialEq + Eq + Send + Sync + std::clone::Clone + serde::ser::Serialize + serde::de::DeserializeOwned + 'static, Self: Sized + Serialize + Deserialize + 'static, { self.reduce_by_key_using_partitioner( func, Box::new(HashPartitioner::<K>::new(num_splits)) as Box<dyn Partitioner>, ) } fn reduce_by_key_using_partitioner<F>( &self, func: F, partitioner: Box<dyn Partitioner>, ) -> ShuffledRdd<K, V, V, Self> where F: Fn((V, V)) -> V + PartialEq + Eq + Send + Sync + std::clone::Clone + serde::ser::Serialize + serde::de::DeserializeOwned + 'static, Self: Sized + Serialize + Deserialize + 'static, { let create_combiner = Box::new(Fn!(|v: V| v)); fn merge_value<V: Data, F>(buf: V, v: V, func: F) -> V where F: Fn((V, V)) -> V + PartialEq + Eq + Send + Sync + Clone + serde::ser::Serialize + serde::de::DeserializeOwned + 'static, { let p = buf; let res = func((p, v)); //*buf.lock() = res res // buf } let func_clone = func.clone(); let merge_value = Box::new( Fn!([func_clone] move | (buf, v) | merge_value::<V, F>(buf, v, func_clone.clone())), ); fn merge_combiners<V: Data, F>(b1: V, b2: V, func: F) -> V where F: Fn((V, V)) -> V + PartialEq + Eq + Send + Sync + Clone + serde::ser::Serialize + serde::de::DeserializeOwned + 'static, { let p = b1; let res = func((p, b2)); // *b1.lock() = func(p, b2) // b1 res } let func_clone = func.clone(); let merge_combiners = Box::new( Fn!([func_clone] move | (b1, b2) | merge_combiners::<V, F>(b1, b2, func_clone.clone())), ); let bufs = self.combine_by_key(create_combiner, merge_value, merge_combiners, partitioner); bufs } fn map_values<U: Data>(&self, f: Arc<dyn Func<V, U>>) -> MappedValuesRdd<Self, K, V, U> where Self: Sized, { MappedValuesRdd::new(self.get_rdd(), f) } fn flat_map_values<U: Data>( &self, f: Arc<dyn Func<V, Box<dyn Iterator<Item = U>>>>, ) -> FlatMappedValuesRdd<Self, K, V, U> where Self: Sized, { FlatMappedValuesRdd::new(self.get_rdd(), f) } fn join<W: Data, RT: Rdd<(K, W)>>( &self, other: RT, num_splits: usize, ) -> FlatMappedValuesRdd< MappedValuesRdd<CoGroupedRdd<K>, K, Vec<Vec<Box<dyn AnyData>>>, (Vec<V>, Vec<W>)>, K, (Vec<V>, Vec<W>), (V, W), > { let f = Fn!(|v: (Vec<V>, Vec<W>)| { let (vs, ws) = v; let combine = vs .into_iter() .flat_map(move |v| ws.clone().into_iter().map(move |w| (v.clone(), w))); Box::new(combine) as Box<dyn Iterator<Item = (V, W)>> }); self.cogroup( other, Box::new(HashPartitioner::<K>::new(num_splits)) as Box<dyn Partitioner>, ) .flat_map_values(Arc::new(f)) } fn cogroup<W: Data, RT: Rdd<(K, W)>>( &self, other: RT, partitioner: Box<dyn Partitioner>, ) -> MappedValuesRdd<CoGroupedRdd<K>, K, Vec<Vec<Box<dyn AnyData>>>, (Vec<V>, Vec<W>)> { let rdds: Vec<serde_traitobject::Arc<dyn RddBase>> = vec![ serde_traitobject::Arc::from(self.get_rdd_base()), serde_traitobject::Arc::from(other.get_rdd_base()), ]; let cg_rdd = CoGroupedRdd::<K>::new(rdds, partitioner); let f = Fn!(|v: Vec<Vec<Box<dyn AnyData>>>| -> (Vec<V>, Vec<W>) { let mut count = 0; let mut vs: Vec<V> = Vec::new(); let mut ws: Vec<W> = Vec::new(); for v in v.into_iter() { if count >= 2 { break; } if count == 0 { for i in v { vs.push(*(i.into_any().downcast::<V>().unwrap())) } } else if count == 1 { for i in v { ws.push(*(i.into_any().downcast::<W>().unwrap())) } } count += 1; } (vs, ws) }); cg_rdd.map_values(Arc::new(f)) } // fn map_values<U:Data,F>(&self, f: F) -> MappedValuesRdd<Self, K, V, U, F> where // F: Fn(V) -> U + 'static + Send + Sync + PartialEq + Eq + Clone + serde::ser::Serialize + serde::de::DeserializeOwned, // Self: Sized, // { // MappedValuesRdd::new(self.get_rdd(), f) // } } // Implementing the PairRdd trait for all types which implements Rdd impl<K: Data + Eq + Hash, V: Data, T> PairRdd<K, V> for T where T: Rdd<(K, V)> {} #[derive(Serialize, Deserialize)] pub struct MappedValuesRdd<RT: 'static, K: Data, V: Data, U: Data> where RT: Rdd<(K, V)>, { #[serde(with = "serde_traitobject")] prev: Arc<RT>, vals: Arc<RddVals>, #[serde(with = "serde_traitobject")] f: Arc<dyn Func<V, U>>, _marker_t: PhantomData<K>, // phantom data is necessary because of type parameter T _marker_v: PhantomData<V>, _marker_u: PhantomData<U>, } impl<RT: 'static, K: Data, V: Data, U: Data> MappedValuesRdd<RT, K, V, U> where RT: Rdd<(K, V)>, { fn new(prev: Arc<RT>, f: Arc<dyn Func<V, U>>) -> Self { let mut vals = RddVals::new(prev.get_context()); vals.dependencies .push(Dependency::OneToOneDependency(Arc::new( // OneToOneDependencyVals::new(prev.get_rdd(), prev.get_rdd()), OneToOneDependencyVals::new(prev.get_rdd_base()), ))); let vals = Arc::new(vals); MappedValuesRdd { prev, vals, f, _marker_t: PhantomData, _marker_v: PhantomData, _marker_u: PhantomData, } } // // Due to some problem with auto deriving clone for Arc types, implementing clone manually. // // But have to move this to the general Clone trait fn clone(&self) -> Self { MappedValuesRdd { prev: self.prev.clone(), vals: self.vals.clone(), f: self.f.clone(), _marker_t: PhantomData, _marker_v: PhantomData, _marker_u: PhantomData, } } } impl<RT: 'static, K: Data, V: Data, U: Data> RddBase for MappedValuesRdd<RT, K, V, U> where RT: Rdd<(K, V)>, { fn get_rdd_id(&self) -> usize { self.vals.id } fn get_context(&self) -> Context { self.vals.context.clone() } fn get_dependencies(&self) -> &[Dependency] { &self.vals.dependencies } fn splits(&self) -> Vec<Box<dyn Split>> { self.prev.splits() } fn iterator_any(&self, split: Box<dyn Split>) -> Box<dyn Iterator<Item = Box<dyn AnyData>>> { info!("inside iterator_any mapvaluesrdd",); Box::new( self.iterator(split) .map(|(k, v)| Box::new((k, Box::new(v) as Box<dyn AnyData>)) as Box<dyn AnyData>), ) } } impl<RT: 'static, K: Data, V: Data, U: Data> Rdd<(K, U)> for MappedValuesRdd<RT, K, V, U> where RT: Rdd<(K, V)>, { fn get_rdd_base(&self) -> Arc<dyn RddBase> { Arc::new(self.clone()) as Arc<dyn RddBase> } fn get_rdd(&self) -> Arc<Self> { Arc::new(self.clone()) } fn compute(&self, split: Box<dyn Split>) -> Box<dyn Iterator<Item = (K, U)>> { let f = self.f.clone(); let res = Box::new(self.prev.iterator(split).map(move |(k, v)| (k, f(v)))); res // let res = res.collect::<Vec<_>>(); // let log_output = format!("inside iterator maprdd values {:?}", res.get(0)); // env::log_file.lock().write(&log_output.as_bytes()); // Box::new(res.into_iter()) as Box<dyn Iterator<Item = (K, U)>> } } #[derive(Serialize, Deserialize)] pub struct FlatMappedValuesRdd<RT: 'static, K: Data, V: Data, U: Data> where RT: Rdd<(K, V)>, { #[serde(with = "serde_traitobject")] prev: Arc<RT>, vals: Arc<RddVals>, #[serde(with = "serde_traitobject")] f: Arc<dyn Func<V, Box<dyn Iterator<Item = U>>>>, _marker_t: PhantomData<K>, // phantom data is necessary because of type parameter T _marker_v: PhantomData<V>, _marker_u: PhantomData<U>, } impl<RT: 'static, K: Data, V: Data, U: Data> FlatMappedValuesRdd<RT, K, V, U> where RT: Rdd<(K, V)>, { fn new(prev: Arc<RT>, f: Arc<dyn Func<V, Box<dyn Iterator<Item = U>>>>) -> Self { let mut vals = RddVals::new(prev.get_context()); vals.dependencies .push(Dependency::OneToOneDependency(Arc::new( // OneToOneDependencyVals::new(prev.get_rdd(), prev.get_rdd()), OneToOneDependencyVals::new(prev.get_rdd_base()), ))); let vals = Arc::new(vals); FlatMappedValuesRdd { prev, vals, f, _marker_t: PhantomData, _marker_v: PhantomData, _marker_u: PhantomData, } } // // Due to some problem with auto deriving clone for Arc types, implementing clone manually. // // But have to move this to the general Clone trait fn clone(&self) -> Self { FlatMappedValuesRdd { prev: self.prev.clone(), vals: self.vals.clone(), f: self.f.clone(), _marker_t: PhantomData, _marker_v: PhantomData, _marker_u: PhantomData, } } } impl<RT: 'static, K: Data, V: Data, U: Data> RddBase for FlatMappedValuesRdd<RT, K, V, U> where RT: Rdd<(K, V)>, { fn get_rdd_id(&self) -> usize { self.vals.id } fn get_context(&self) -> Context { self.vals.context.clone() } fn get_dependencies(&self) -> &[Dependency] { &self.vals.dependencies } fn splits(&self) -> Vec<Box<dyn Split>> { self.prev.splits() } fn iterator_any(&self, split: Box<dyn Split>) -> Box<dyn Iterator<Item = Box<dyn AnyData>>> { info!("inside iterator_any flatmapvaluesrdd",); Box::new( self.iterator(split) .map(|(k, v)| Box::new((k, v)) as Box<dyn AnyData>), ) } fn cogroup_iterator_any( &self, split: Box<dyn Split>, ) -> Box<dyn Iterator<Item = Box<dyn AnyData>>> { info!("inside cogroup iterator_any flatmapvaluesrdd",); Box::new( self.iterator(split) .map(|(k, v)| Box::new((k, Box::new(v) as Box<dyn AnyData>)) as Box<dyn AnyData>), ) } } impl<RT: 'static, K: Data, V: Data, U: Data> Rdd<(K, U)> for FlatMappedValuesRdd<RT, K, V, U> where RT: Rdd<(K, V)>, { fn get_rdd_base(&self) -> Arc<dyn RddBase> { Arc::new(self.clone()) as Arc<dyn RddBase> } fn get_rdd(&self) -> Arc<Self> { Arc::new(self.clone()) } fn compute(&self, split: Box<dyn Split>) -> Box<dyn Iterator<Item = (K, U)>> { let f = self.f.clone(); let res = Box::new( self.prev .iterator(split) .flat_map( move |(k,v)| f(v).map(move |x| (k.clone(),x))) // .collect::<Vec<_>>() // .into_iter(), ); res // let res = res.collect::<Vec<_>>(); // let log_output = format!("inside iterator flatmaprdd values {:?}", res.get(0)); // env::log_file.lock().write(&log_output.as_bytes()); // Box::new(res.into_iter()) as Box<dyn Iterator<Item = (K, U)>> // Box::new(self.prev.iterator(split).map(move |(k,v)| (k, f(v)))) } }
33.754967
135
0.503564
336ce6dcf3e604b8faa13fccf9eda0ebbcfce9e7
20,383
/** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // @Generated by gentest/gentest.rb from gentest/fixtures/YGFlexTest.html extern crate ordered_float; extern crate yoga; use yoga::*; #[test] fn test_flex_basis_flex_grow_column() { let mut config = Config::new(); let mut root = Node::new_with_config(&mut config); root.set_width(StyleUnit::Point((100 as f32).into())); root.set_height(StyleUnit::Point((100 as f32).into())); let mut root_child0 = Node::new_with_config(&mut config); root_child0.set_flex_grow(1 as f32); root_child0.set_flex_basis(StyleUnit::Point((50 as f32).into())); root_child0.set_min_width(StyleUnit::Auto); root_child0.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child0, 0); let mut root_child1 = Node::new_with_config(&mut config); root_child1.set_flex_grow(1 as f32); root_child1.set_min_width(StyleUnit::Auto); root_child1.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child1, 1); root.calculate_layout(Undefined, Undefined, Direction::LTR); assert_eq!(0 as f32, root.get_layout_left()); assert_eq!(0 as f32, root.get_layout_top()); assert_eq!(100 as f32, root.get_layout_width()); assert_eq!(100 as f32, root.get_layout_height()); assert_eq!(0 as f32, root_child0.get_layout_left()); assert_eq!(0 as f32, root_child0.get_layout_top()); assert_eq!(100 as f32, root_child0.get_layout_width()); assert_eq!(75 as f32, root_child0.get_layout_height()); assert_eq!(0 as f32, root_child1.get_layout_left()); assert_eq!(75 as f32, root_child1.get_layout_top()); assert_eq!(100 as f32, root_child1.get_layout_width()); assert_eq!(25 as f32, root_child1.get_layout_height()); root.calculate_layout(Undefined, Undefined, Direction::RTL); assert_eq!(0 as f32, root.get_layout_left()); assert_eq!(0 as f32, root.get_layout_top()); assert_eq!(100 as f32, root.get_layout_width()); assert_eq!(100 as f32, root.get_layout_height()); assert_eq!(0 as f32, root_child0.get_layout_left()); assert_eq!(0 as f32, root_child0.get_layout_top()); assert_eq!(100 as f32, root_child0.get_layout_width()); assert_eq!(75 as f32, root_child0.get_layout_height()); assert_eq!(0 as f32, root_child1.get_layout_left()); assert_eq!(75 as f32, root_child1.get_layout_top()); assert_eq!(100 as f32, root_child1.get_layout_width()); assert_eq!(25 as f32, root_child1.get_layout_height()); } #[test] fn test_flex_basis_flex_grow_row() { let mut config = Config::new(); let mut root = Node::new_with_config(&mut config); root.set_flex_direction(FlexDirection::Row); root.set_width(StyleUnit::Point((100 as f32).into())); root.set_height(StyleUnit::Point((100 as f32).into())); let mut root_child0 = Node::new_with_config(&mut config); root_child0.set_flex_grow(1 as f32); root_child0.set_flex_basis(StyleUnit::Point((50 as f32).into())); root_child0.set_min_width(StyleUnit::Auto); root_child0.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child0, 0); let mut root_child1 = Node::new_with_config(&mut config); root_child1.set_flex_grow(1 as f32); root_child1.set_min_width(StyleUnit::Auto); root_child1.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child1, 1); root.calculate_layout(Undefined, Undefined, Direction::LTR); assert_eq!(0 as f32, root.get_layout_left()); assert_eq!(0 as f32, root.get_layout_top()); assert_eq!(100 as f32, root.get_layout_width()); assert_eq!(100 as f32, root.get_layout_height()); assert_eq!(0 as f32, root_child0.get_layout_left()); assert_eq!(0 as f32, root_child0.get_layout_top()); assert_eq!(75 as f32, root_child0.get_layout_width()); assert_eq!(100 as f32, root_child0.get_layout_height()); assert_eq!(75 as f32, root_child1.get_layout_left()); assert_eq!(0 as f32, root_child1.get_layout_top()); assert_eq!(25 as f32, root_child1.get_layout_width()); assert_eq!(100 as f32, root_child1.get_layout_height()); root.calculate_layout(Undefined, Undefined, Direction::RTL); assert_eq!(0 as f32, root.get_layout_left()); assert_eq!(0 as f32, root.get_layout_top()); assert_eq!(100 as f32, root.get_layout_width()); assert_eq!(100 as f32, root.get_layout_height()); assert_eq!(25 as f32, root_child0.get_layout_left()); assert_eq!(0 as f32, root_child0.get_layout_top()); assert_eq!(75 as f32, root_child0.get_layout_width()); assert_eq!(100 as f32, root_child0.get_layout_height()); assert_eq!(0 as f32, root_child1.get_layout_left()); assert_eq!(0 as f32, root_child1.get_layout_top()); assert_eq!(25 as f32, root_child1.get_layout_width()); assert_eq!(100 as f32, root_child1.get_layout_height()); } #[test] fn test_flex_basis_flex_shrink_column() { let mut config = Config::new(); let mut root = Node::new_with_config(&mut config); root.set_width(StyleUnit::Point((100 as f32).into())); root.set_height(StyleUnit::Point((100 as f32).into())); let mut root_child0 = Node::new_with_config(&mut config); root_child0.set_flex_shrink(1 as f32 as f32); root_child0.set_flex_basis(StyleUnit::Point((100 as f32).into())); root_child0.set_min_width(StyleUnit::Auto); root_child0.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child0, 0); let mut root_child1 = Node::new_with_config(&mut config); root_child1.set_flex_basis(StyleUnit::Point((50 as f32).into())); root_child1.set_min_width(StyleUnit::Auto); root_child1.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child1, 1); root.calculate_layout(Undefined, Undefined, Direction::LTR); assert_eq!(0 as f32, root.get_layout_left()); assert_eq!(0 as f32, root.get_layout_top()); assert_eq!(100 as f32, root.get_layout_width()); assert_eq!(100 as f32, root.get_layout_height()); assert_eq!(0 as f32, root_child0.get_layout_left()); assert_eq!(0 as f32, root_child0.get_layout_top()); assert_eq!(100 as f32, root_child0.get_layout_width()); assert_eq!(50 as f32, root_child0.get_layout_height()); assert_eq!(0 as f32, root_child1.get_layout_left()); assert_eq!(50 as f32, root_child1.get_layout_top()); assert_eq!(100 as f32, root_child1.get_layout_width()); assert_eq!(50 as f32, root_child1.get_layout_height()); root.calculate_layout(Undefined, Undefined, Direction::RTL); assert_eq!(0 as f32, root.get_layout_left()); assert_eq!(0 as f32, root.get_layout_top()); assert_eq!(100 as f32, root.get_layout_width()); assert_eq!(100 as f32, root.get_layout_height()); assert_eq!(0 as f32, root_child0.get_layout_left()); assert_eq!(0 as f32, root_child0.get_layout_top()); assert_eq!(100 as f32, root_child0.get_layout_width()); assert_eq!(50 as f32, root_child0.get_layout_height()); assert_eq!(0 as f32, root_child1.get_layout_left()); assert_eq!(50 as f32, root_child1.get_layout_top()); assert_eq!(100 as f32, root_child1.get_layout_width()); assert_eq!(50 as f32, root_child1.get_layout_height()); } #[test] fn test_flex_basis_flex_shrink_row() { let mut config = Config::new(); let mut root = Node::new_with_config(&mut config); root.set_flex_direction(FlexDirection::Row); root.set_width(StyleUnit::Point((100 as f32).into())); root.set_height(StyleUnit::Point((100 as f32).into())); let mut root_child0 = Node::new_with_config(&mut config); root_child0.set_flex_shrink(1 as f32 as f32); root_child0.set_flex_basis(StyleUnit::Point((100 as f32).into())); root_child0.set_min_width(StyleUnit::Auto); root_child0.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child0, 0); let mut root_child1 = Node::new_with_config(&mut config); root_child1.set_flex_basis(StyleUnit::Point((50 as f32).into())); root_child1.set_min_width(StyleUnit::Auto); root_child1.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child1, 1); root.calculate_layout(Undefined, Undefined, Direction::LTR); assert_eq!(0 as f32, root.get_layout_left()); assert_eq!(0 as f32, root.get_layout_top()); assert_eq!(100 as f32, root.get_layout_width()); assert_eq!(100 as f32, root.get_layout_height()); assert_eq!(0 as f32, root_child0.get_layout_left()); assert_eq!(0 as f32, root_child0.get_layout_top()); assert_eq!(50 as f32, root_child0.get_layout_width()); assert_eq!(100 as f32, root_child0.get_layout_height()); assert_eq!(50 as f32, root_child1.get_layout_left()); assert_eq!(0 as f32, root_child1.get_layout_top()); assert_eq!(50 as f32, root_child1.get_layout_width()); assert_eq!(100 as f32, root_child1.get_layout_height()); root.calculate_layout(Undefined, Undefined, Direction::RTL); assert_eq!(0 as f32, root.get_layout_left()); assert_eq!(0 as f32, root.get_layout_top()); assert_eq!(100 as f32, root.get_layout_width()); assert_eq!(100 as f32, root.get_layout_height()); assert_eq!(50 as f32, root_child0.get_layout_left()); assert_eq!(0 as f32, root_child0.get_layout_top()); assert_eq!(50 as f32, root_child0.get_layout_width()); assert_eq!(100 as f32, root_child0.get_layout_height()); assert_eq!(0 as f32, root_child1.get_layout_left()); assert_eq!(0 as f32, root_child1.get_layout_top()); assert_eq!(50 as f32, root_child1.get_layout_width()); assert_eq!(100 as f32, root_child1.get_layout_height()); } #[test] fn test_flex_shrink_to_zero() { let mut config = Config::new(); let mut root = Node::new_with_config(&mut config); root.set_height(StyleUnit::Point((75 as f32).into())); let mut root_child0 = Node::new_with_config(&mut config); root_child0.set_width(StyleUnit::Point((50 as f32).into())); root_child0.set_min_width(StyleUnit::Auto); root_child0.set_height(StyleUnit::Point((50 as f32).into())); root_child0.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child0, 0); let mut root_child1 = Node::new_with_config(&mut config); root_child1.set_flex_shrink(1 as f32 as f32); root_child1.set_width(StyleUnit::Point((50 as f32).into())); root_child1.set_min_width(StyleUnit::Auto); root_child1.set_height(StyleUnit::Point((50 as f32).into())); root_child1.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child1, 1); let mut root_child2 = Node::new_with_config(&mut config); root_child2.set_width(StyleUnit::Point((50 as f32).into())); root_child2.set_min_width(StyleUnit::Auto); root_child2.set_height(StyleUnit::Point((50 as f32).into())); root_child2.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child2, 2); root.calculate_layout(Undefined, Undefined, Direction::LTR); assert_eq!(0 as f32, root.get_layout_left()); assert_eq!(0 as f32, root.get_layout_top()); assert_eq!(50 as f32, root.get_layout_width()); assert_eq!(75 as f32, root.get_layout_height()); assert_eq!(0 as f32, root_child0.get_layout_left()); assert_eq!(0 as f32, root_child0.get_layout_top()); assert_eq!(50 as f32, root_child0.get_layout_width()); assert_eq!(50 as f32, root_child0.get_layout_height()); assert_eq!(0 as f32, root_child1.get_layout_left()); assert_eq!(50 as f32, root_child1.get_layout_top()); assert_eq!(50 as f32, root_child1.get_layout_width()); assert_eq!(0 as f32, root_child1.get_layout_height()); assert_eq!(0 as f32, root_child2.get_layout_left()); assert_eq!(50 as f32, root_child2.get_layout_top()); assert_eq!(50 as f32, root_child2.get_layout_width()); assert_eq!(50 as f32, root_child2.get_layout_height()); root.calculate_layout(Undefined, Undefined, Direction::RTL); assert_eq!(0 as f32, root.get_layout_left()); assert_eq!(0 as f32, root.get_layout_top()); assert_eq!(50 as f32, root.get_layout_width()); assert_eq!(75 as f32, root.get_layout_height()); assert_eq!(0 as f32, root_child0.get_layout_left()); assert_eq!(0 as f32, root_child0.get_layout_top()); assert_eq!(50 as f32, root_child0.get_layout_width()); assert_eq!(50 as f32, root_child0.get_layout_height()); assert_eq!(0 as f32, root_child1.get_layout_left()); assert_eq!(50 as f32, root_child1.get_layout_top()); assert_eq!(50 as f32, root_child1.get_layout_width()); assert_eq!(0 as f32, root_child1.get_layout_height()); assert_eq!(0 as f32, root_child2.get_layout_left()); assert_eq!(50 as f32, root_child2.get_layout_top()); assert_eq!(50 as f32, root_child2.get_layout_width()); assert_eq!(50 as f32, root_child2.get_layout_height()); } #[test] fn test_flex_basis_overrides_main_size() { let mut config = Config::new(); let mut root = Node::new_with_config(&mut config); root.set_width(StyleUnit::Point((100 as f32).into())); root.set_height(StyleUnit::Point((100 as f32).into())); let mut root_child0 = Node::new_with_config(&mut config); root_child0.set_flex_grow(1 as f32); root_child0.set_flex_basis(StyleUnit::Point((50 as f32).into())); root_child0.set_min_width(StyleUnit::Auto); root_child0.set_height(StyleUnit::Point((20 as f32).into())); root_child0.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child0, 0); let mut root_child1 = Node::new_with_config(&mut config); root_child1.set_flex_grow(1 as f32); root_child1.set_min_width(StyleUnit::Auto); root_child1.set_height(StyleUnit::Point((10 as f32).into())); root_child1.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child1, 1); let mut root_child2 = Node::new_with_config(&mut config); root_child2.set_flex_grow(1 as f32); root_child2.set_min_width(StyleUnit::Auto); root_child2.set_height(StyleUnit::Point((10 as f32).into())); root_child2.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child2, 2); root.calculate_layout(Undefined, Undefined, Direction::LTR); assert_eq!(0 as f32, root.get_layout_left()); assert_eq!(0 as f32, root.get_layout_top()); assert_eq!(100 as f32, root.get_layout_width()); assert_eq!(100 as f32, root.get_layout_height()); assert_eq!(0 as f32, root_child0.get_layout_left()); assert_eq!(0 as f32, root_child0.get_layout_top()); assert_eq!(100 as f32, root_child0.get_layout_width()); assert_eq!(60 as f32, root_child0.get_layout_height()); assert_eq!(0 as f32, root_child1.get_layout_left()); assert_eq!(60 as f32, root_child1.get_layout_top()); assert_eq!(100 as f32, root_child1.get_layout_width()); assert_eq!(20 as f32, root_child1.get_layout_height()); assert_eq!(0 as f32, root_child2.get_layout_left()); assert_eq!(80 as f32, root_child2.get_layout_top()); assert_eq!(100 as f32, root_child2.get_layout_width()); assert_eq!(20 as f32, root_child2.get_layout_height()); root.calculate_layout(Undefined, Undefined, Direction::RTL); assert_eq!(0 as f32, root.get_layout_left()); assert_eq!(0 as f32, root.get_layout_top()); assert_eq!(100 as f32, root.get_layout_width()); assert_eq!(100 as f32, root.get_layout_height()); assert_eq!(0 as f32, root_child0.get_layout_left()); assert_eq!(0 as f32, root_child0.get_layout_top()); assert_eq!(100 as f32, root_child0.get_layout_width()); assert_eq!(60 as f32, root_child0.get_layout_height()); assert_eq!(0 as f32, root_child1.get_layout_left()); assert_eq!(60 as f32, root_child1.get_layout_top()); assert_eq!(100 as f32, root_child1.get_layout_width()); assert_eq!(20 as f32, root_child1.get_layout_height()); assert_eq!(0 as f32, root_child2.get_layout_left()); assert_eq!(80 as f32, root_child2.get_layout_top()); assert_eq!(100 as f32, root_child2.get_layout_width()); assert_eq!(20 as f32, root_child2.get_layout_height()); } #[test] fn test_flex_grow_shrink_at_most() { let mut config = Config::new(); let mut root = Node::new_with_config(&mut config); root.set_width(StyleUnit::Point((100 as f32).into())); root.set_height(StyleUnit::Point((100 as f32).into())); let mut root_child0 = Node::new_with_config(&mut config); root_child0.set_min_width(StyleUnit::Auto); root_child0.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child0, 0); let mut root_child0_child0 = Node::new_with_config(&mut config); root_child0_child0.set_flex_grow(1 as f32); root_child0_child0.set_flex_shrink(1 as f32 as f32); root_child0_child0.set_min_width(StyleUnit::Auto); root_child0_child0.set_min_height(StyleUnit::Auto); root_child0.insert_child(&mut root_child0_child0, 0); root.calculate_layout(Undefined, Undefined, Direction::LTR); assert_eq!(0 as f32, root.get_layout_left()); assert_eq!(0 as f32, root.get_layout_top()); assert_eq!(100 as f32, root.get_layout_width()); assert_eq!(100 as f32, root.get_layout_height()); assert_eq!(0 as f32, root_child0.get_layout_left()); assert_eq!(0 as f32, root_child0.get_layout_top()); assert_eq!(100 as f32, root_child0.get_layout_width()); assert_eq!(0 as f32, root_child0.get_layout_height()); assert_eq!(0 as f32, root_child0_child0.get_layout_left()); assert_eq!(0 as f32, root_child0_child0.get_layout_top()); assert_eq!(100 as f32, root_child0_child0.get_layout_width()); assert_eq!(0 as f32, root_child0_child0.get_layout_height()); root.calculate_layout(Undefined, Undefined, Direction::RTL); assert_eq!(0 as f32, root.get_layout_left()); assert_eq!(0 as f32, root.get_layout_top()); assert_eq!(100 as f32, root.get_layout_width()); assert_eq!(100 as f32, root.get_layout_height()); assert_eq!(0 as f32, root_child0.get_layout_left()); assert_eq!(0 as f32, root_child0.get_layout_top()); assert_eq!(100 as f32, root_child0.get_layout_width()); assert_eq!(0 as f32, root_child0.get_layout_height()); assert_eq!(0 as f32, root_child0_child0.get_layout_left()); assert_eq!(0 as f32, root_child0_child0.get_layout_top()); assert_eq!(100 as f32, root_child0_child0.get_layout_width()); assert_eq!(0 as f32, root_child0_child0.get_layout_height()); } #[test] fn test_flex_grow_less_than_factor_one() { let mut config = Config::new(); let mut root = Node::new_with_config(&mut config); root.set_width(StyleUnit::Point((200 as f32).into())); root.set_height(StyleUnit::Point((500 as f32).into())); let mut root_child0 = Node::new_with_config(&mut config); root_child0.set_flex_grow(0.2 as f32); root_child0.set_flex_basis(StyleUnit::Point((40 as f32).into())); root_child0.set_min_width(StyleUnit::Auto); root_child0.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child0, 0); let mut root_child1 = Node::new_with_config(&mut config); root_child1.set_flex_grow(0.2 as f32); root_child1.set_min_width(StyleUnit::Auto); root_child1.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child1, 1); let mut root_child2 = Node::new_with_config(&mut config); root_child2.set_flex_grow(0.4 as f32); root_child2.set_min_width(StyleUnit::Auto); root_child2.set_min_height(StyleUnit::Auto); root.insert_child(&mut root_child2, 2); root.calculate_layout(Undefined, Undefined, Direction::LTR); assert_eq!(0 as f32, root.get_layout_left()); assert_eq!(0 as f32, root.get_layout_top()); assert_eq!(200 as f32, root.get_layout_width()); assert_eq!(500 as f32, root.get_layout_height()); assert_eq!(0 as f32, root_child0.get_layout_left()); assert_eq!(0 as f32, root_child0.get_layout_top()); assert_eq!(200 as f32, root_child0.get_layout_width()); assert_eq!(132 as f32, root_child0.get_layout_height()); assert_eq!(0 as f32, root_child1.get_layout_left()); assert_eq!(132 as f32, root_child1.get_layout_top()); assert_eq!(200 as f32, root_child1.get_layout_width()); assert_eq!(92 as f32, root_child1.get_layout_height()); assert_eq!(0 as f32, root_child2.get_layout_left()); assert_eq!(224 as f32, root_child2.get_layout_top()); assert_eq!(200 as f32, root_child2.get_layout_width()); assert_eq!(184 as f32, root_child2.get_layout_height()); root.calculate_layout(Undefined, Undefined, Direction::RTL); assert_eq!(0 as f32, root.get_layout_left()); assert_eq!(0 as f32, root.get_layout_top()); assert_eq!(200 as f32, root.get_layout_width()); assert_eq!(500 as f32, root.get_layout_height()); assert_eq!(0 as f32, root_child0.get_layout_left()); assert_eq!(0 as f32, root_child0.get_layout_top()); assert_eq!(200 as f32, root_child0.get_layout_width()); assert_eq!(132 as f32, root_child0.get_layout_height()); assert_eq!(0 as f32, root_child1.get_layout_left()); assert_eq!(132 as f32, root_child1.get_layout_top()); assert_eq!(200 as f32, root_child1.get_layout_width()); assert_eq!(92 as f32, root_child1.get_layout_height()); assert_eq!(0 as f32, root_child2.get_layout_left()); assert_eq!(224 as f32, root_child2.get_layout_top()); assert_eq!(200 as f32, root_child2.get_layout_width()); assert_eq!(184 as f32, root_child2.get_layout_height()); }
40.124016
73
0.757788
ebbb77806bfcb606d5c12ce3779ac81d3c7f3837
24,769
//! ## FileTransferActivity //! //! `filetransfer_activiy` is the module which implements the Filetransfer activity, which is the main activity afterall /** * MIT License * * termscp - Copyright (c) 2021 Christian Visintin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // locals use super::{FileExplorerTab, FileTransferActivity, FsEntry, LogLevel}; use crate::ui::layout::Payload; // externals use std::path::PathBuf; impl FileTransferActivity { /// ### action_change_local_dir /// /// Change local directory reading value from input pub(super) fn action_change_local_dir(&mut self, input: String) { let dir_path: PathBuf = PathBuf::from(input.as_str()); let abs_dir_path: PathBuf = match dir_path.is_relative() { true => { let mut d: PathBuf = self.local.wrkdir.clone(); d.push(dir_path); d } false => dir_path, }; self.local_changedir(abs_dir_path.as_path(), true); } /// ### action_change_remote_dir /// /// Change remote directory reading value from input pub(super) fn action_change_remote_dir(&mut self, input: String) { let dir_path: PathBuf = PathBuf::from(input.as_str()); let abs_dir_path: PathBuf = match dir_path.is_relative() { true => { let mut wrkdir: PathBuf = self.remote.wrkdir.clone(); wrkdir.push(dir_path); wrkdir } false => dir_path, }; self.remote_changedir(abs_dir_path.as_path(), true); } /// ### action_local_copy /// /// Copy file on local pub(super) fn action_local_copy(&mut self, input: String) { if let Some(idx) = self.get_local_file_idx() { let dest_path: PathBuf = PathBuf::from(input); let entry: FsEntry = self.local.get(idx).unwrap().clone(); if let Some(ctx) = self.context.as_mut() { match ctx.local.copy(&entry, dest_path.as_path()) { Ok(_) => { self.log( LogLevel::Info, format!( "Copied \"{}\" to \"{}\"", entry.get_abs_path().display(), dest_path.display() ) .as_str(), ); // Reload entries let wrkdir: PathBuf = self.local.wrkdir.clone(); self.local_scan(wrkdir.as_path()); } Err(err) => self.log_and_alert( LogLevel::Error, format!( "Could not copy \"{}\" to \"{}\": {}", entry.get_abs_path().display(), dest_path.display(), err ), ), } } } } /// ### action_remote_copy /// /// Copy file on remote pub(super) fn action_remote_copy(&mut self, input: String) { if let Some(idx) = self.get_remote_file_idx() { let dest_path: PathBuf = PathBuf::from(input); let entry: FsEntry = self.remote.get(idx).unwrap().clone(); match self.client.as_mut().copy(&entry, dest_path.as_path()) { Ok(_) => { self.log( LogLevel::Info, format!( "Copied \"{}\" to \"{}\"", entry.get_abs_path().display(), dest_path.display() ) .as_str(), ); self.reload_remote_dir(); } Err(err) => self.log_and_alert( LogLevel::Error, format!( "Could not copy \"{}\" to \"{}\": {}", entry.get_abs_path().display(), dest_path.display(), err ), ), } } } pub(super) fn action_local_mkdir(&mut self, input: String) { match self .context .as_mut() .unwrap() .local .mkdir(PathBuf::from(input.as_str()).as_path()) { Ok(_) => { // Reload files self.log( LogLevel::Info, format!("Created directory \"{}\"", input).as_ref(), ); let wrkdir: PathBuf = self.local.wrkdir.clone(); self.local_scan(wrkdir.as_path()); } Err(err) => { // Report err self.log_and_alert( LogLevel::Error, format!("Could not create directory \"{}\": {}", input, err), ); } } } pub(super) fn action_remote_mkdir(&mut self, input: String) { match self .client .as_mut() .mkdir(PathBuf::from(input.as_str()).as_path()) { Ok(_) => { // Reload files self.log( LogLevel::Info, format!("Created directory \"{}\"", input).as_ref(), ); self.reload_remote_dir(); } Err(err) => { // Report err self.log_and_alert( LogLevel::Error, format!("Could not create directory \"{}\": {}", input, err), ); } } } pub(super) fn action_local_rename(&mut self, input: String) { let entry: Option<FsEntry> = self.get_local_file_entry().cloned(); if let Some(entry) = entry { let mut dst_path: PathBuf = PathBuf::from(input); // Check if path is relative if dst_path.as_path().is_relative() { let mut wrkdir: PathBuf = self.local.wrkdir.clone(); wrkdir.push(dst_path); dst_path = wrkdir; } let full_path: PathBuf = entry.get_abs_path(); // Rename file or directory and report status as popup match self .context .as_mut() .unwrap() .local .rename(&entry, dst_path.as_path()) { Ok(_) => { // Reload files let path: PathBuf = self.local.wrkdir.clone(); self.local_scan(path.as_path()); // Log self.log( LogLevel::Info, format!( "Renamed file \"{}\" to \"{}\"", full_path.display(), dst_path.display() ) .as_ref(), ); } Err(err) => { self.log_and_alert( LogLevel::Error, format!("Could not rename file \"{}\": {}", full_path.display(), err), ); } } } } pub(super) fn action_remote_rename(&mut self, input: String) { if let Some(idx) = self.get_remote_file_idx() { if let Some(entry) = self.remote.get(idx) { let dst_path: PathBuf = PathBuf::from(input); let full_path: PathBuf = entry.get_abs_path(); // Rename file or directory and report status as popup match self.client.as_mut().rename(entry, dst_path.as_path()) { Ok(_) => { // Reload files let path: PathBuf = self.remote.wrkdir.clone(); self.remote_scan(path.as_path()); // Log self.log( LogLevel::Info, format!( "Renamed file \"{}\" to \"{}\"", full_path.display(), dst_path.display() ) .as_ref(), ); } Err(err) => { self.log_and_alert( LogLevel::Error, format!("Could not rename file \"{}\": {}", full_path.display(), err), ); } } } } } pub(super) fn action_local_delete(&mut self) { let entry: Option<FsEntry> = self.get_local_file_entry().cloned(); if let Some(entry) = entry { let full_path: PathBuf = entry.get_abs_path(); // Delete file or directory and report status as popup match self.context.as_mut().unwrap().local.remove(&entry) { Ok(_) => { // Reload files let p: PathBuf = self.local.wrkdir.clone(); self.local_scan(p.as_path()); // Log self.log( LogLevel::Info, format!("Removed file \"{}\"", full_path.display()).as_ref(), ); } Err(err) => { self.log_and_alert( LogLevel::Error, format!("Could not delete file \"{}\": {}", full_path.display(), err), ); } } } } pub(super) fn action_remote_delete(&mut self) { if let Some(idx) = self.get_remote_file_idx() { // Check if file entry exists if let Some(entry) = self.remote.get(idx) { let full_path: PathBuf = entry.get_abs_path(); // Delete file match self.client.remove(entry) { Ok(_) => { self.reload_remote_dir(); self.log( LogLevel::Info, format!("Removed file \"{}\"", full_path.display()).as_ref(), ); } Err(err) => { self.log_and_alert( LogLevel::Error, format!("Could not delete file \"{}\": {}", full_path.display(), err), ); } } } } } pub(super) fn action_local_saveas(&mut self, input: String) { if let Some(idx) = self.get_local_file_idx() { // Get pwd let wrkdir: PathBuf = self.remote.wrkdir.clone(); if self.local.get(idx).is_some() { let file: FsEntry = self.local.get(idx).unwrap().clone(); // Call upload; pass realfile, keep link name self.filetransfer_send(&file.get_realfile(), wrkdir.as_path(), Some(input)); } } } pub(super) fn action_remote_saveas(&mut self, input: String) { if let Some(idx) = self.get_remote_file_idx() { // Get pwd let wrkdir: PathBuf = self.local.wrkdir.clone(); if self.remote.get(idx).is_some() { let file: FsEntry = self.remote.get(idx).unwrap().clone(); // Call upload; pass realfile, keep link name self.filetransfer_recv(&file.get_realfile(), wrkdir.as_path(), Some(input)); } } } pub(super) fn action_local_newfile(&mut self, input: String) { // Check if file exists let mut file_exists: bool = false; for file in self.local.iter_files_all() { if input == file.get_name() { file_exists = true; } } if file_exists { self.log_and_alert( LogLevel::Warn, format!("File \"{}\" already exists", input,), ); return; } // Create file let file_path: PathBuf = PathBuf::from(input.as_str()); if let Some(ctx) = self.context.as_mut() { if let Err(err) = ctx.local.open_file_write(file_path.as_path()) { self.log_and_alert( LogLevel::Error, format!("Could not create file \"{}\": {}", file_path.display(), err), ); } else { self.log( LogLevel::Info, format!("Created file \"{}\"", file_path.display()).as_str(), ); } // Reload files let path: PathBuf = self.local.wrkdir.clone(); self.local_scan(path.as_path()); } } pub(super) fn action_remote_newfile(&mut self, input: String) { // Check if file exists let mut file_exists: bool = false; for file in self.remote.iter_files_all() { if input == file.get_name() { file_exists = true; } } if file_exists { self.log_and_alert( LogLevel::Warn, format!("File \"{}\" already exists", input,), ); return; } // Get path on remote let file_path: PathBuf = PathBuf::from(input.as_str()); // Create file (on local) match tempfile::NamedTempFile::new() { Err(err) => self.log_and_alert( LogLevel::Error, format!("Could not create tempfile: {}", err), ), Ok(tfile) => { // Stat tempfile if let Some(ctx) = self.context.as_mut() { let local_file: FsEntry = match ctx.local.stat(tfile.path()) { Err(err) => { self.log_and_alert( LogLevel::Error, format!("Could not stat tempfile: {}", err), ); return; } Ok(f) => f, }; if let FsEntry::File(local_file) = local_file { // Create file match self.client.send_file(&local_file, file_path.as_path()) { Err(err) => self.log_and_alert( LogLevel::Error, format!( "Could not create file \"{}\": {}", file_path.display(), err ), ), Ok(writer) => { // Finalize write if let Err(err) = self.client.on_sent(writer) { self.log_and_alert( LogLevel::Warn, format!("Could not finalize file: {}", err), ); } else { self.log( LogLevel::Info, format!("Created file \"{}\"", file_path.display()) .as_str(), ); } // Reload files let path: PathBuf = self.remote.wrkdir.clone(); self.remote_scan(path.as_path()); } } } } } } } pub(super) fn action_local_exec(&mut self, input: String) { match self.context.as_mut().unwrap().local.exec(input.as_str()) { Ok(output) => { // Reload files self.log( LogLevel::Info, format!("\"{}\": {}", input, output).as_ref(), ); let wrkdir: PathBuf = self.local.wrkdir.clone(); self.local_scan(wrkdir.as_path()); } Err(err) => { // Report err self.log_and_alert( LogLevel::Error, format!("Could not execute command \"{}\": {}", input, err), ); } } } pub(super) fn action_remote_exec(&mut self, input: String) { match self.client.as_mut().exec(input.as_str()) { Ok(output) => { // Reload files self.log( LogLevel::Info, format!("\"{}\": {}", input, output).as_ref(), ); self.reload_remote_dir(); } Err(err) => { // Report err self.log_and_alert( LogLevel::Error, format!("Could not execute command \"{}\": {}", input, err), ); } } } pub(super) fn action_local_find(&mut self, input: String) -> Result<Vec<FsEntry>, String> { match self.context.as_mut().unwrap().local.find(input.as_str()) { Ok(entries) => Ok(entries), Err(err) => Err(format!("Could not search for files: {}", err)), } } pub(super) fn action_remote_find(&mut self, input: String) -> Result<Vec<FsEntry>, String> { match self.client.as_mut().find(input.as_str()) { Ok(entries) => Ok(entries), Err(err) => Err(format!("Could not search for files: {}", err)), } } pub(super) fn action_find_changedir(&mut self, idx: usize) { // Match entry if let Some(entry) = self.found.as_ref().unwrap().get(idx) { // Get path: if a directory, use directory path; if it is a File, get parent path let path: PathBuf = match entry { FsEntry::Directory(dir) => dir.abs_path.clone(), FsEntry::File(file) => match file.abs_path.parent() { None => PathBuf::from("."), Some(p) => p.to_path_buf(), }, }; // Change directory match self.tab { FileExplorerTab::FindLocal | FileExplorerTab::Local => { self.local_changedir(path.as_path(), true) } FileExplorerTab::FindRemote | FileExplorerTab::Remote => { self.remote_changedir(path.as_path(), true) } } } } pub(super) fn action_find_transfer(&mut self, idx: usize, name: Option<String>) { let entry: Option<FsEntry> = self.found.as_ref().unwrap().get(idx).cloned(); if let Some(entry) = entry { // Download file match self.tab { FileExplorerTab::FindLocal | FileExplorerTab::Local => { let wrkdir: PathBuf = self.remote.wrkdir.clone(); self.filetransfer_send(&entry.get_realfile(), wrkdir.as_path(), name); } FileExplorerTab::FindRemote | FileExplorerTab::Remote => { let wrkdir: PathBuf = self.local.wrkdir.clone(); self.filetransfer_recv(&entry.get_realfile(), wrkdir.as_path(), name); } } } } pub(super) fn action_find_delete(&mut self, idx: usize) { let entry: Option<FsEntry> = self.found.as_ref().unwrap().get(idx).cloned(); if let Some(entry) = entry { // Download file match self.tab { FileExplorerTab::FindLocal | FileExplorerTab::Local => { let full_path: PathBuf = entry.get_abs_path(); // Delete file or directory and report status as popup match self.context.as_mut().unwrap().local.remove(&entry) { Ok(_) => { // Reload files let p: PathBuf = self.local.wrkdir.clone(); self.local_scan(p.as_path()); // Log self.log( LogLevel::Info, format!("Removed file \"{}\"", full_path.display()).as_ref(), ); } Err(err) => { self.log_and_alert( LogLevel::Error, format!( "Could not delete file \"{}\": {}", full_path.display(), err ), ); } } } FileExplorerTab::FindRemote | FileExplorerTab::Remote => { let full_path: PathBuf = entry.get_abs_path(); // Delete file match self.client.remove(&entry) { Ok(_) => { self.reload_remote_dir(); self.log( LogLevel::Info, format!("Removed file \"{}\"", full_path.display()).as_ref(), ); } Err(err) => { self.log_and_alert( LogLevel::Error, format!( "Could not delete file \"{}\": {}", full_path.display(), err ), ); } } } } } } /// ### get_local_file_entry /// /// Get local file entry pub(super) fn get_local_file_entry(&self) -> Option<&FsEntry> { match self.get_local_file_idx() { None => None, Some(idx) => self.local.get(idx), } } /// ### get_remote_file_entry /// /// Get remote file entry pub(super) fn get_remote_file_entry(&self) -> Option<&FsEntry> { match self.get_remote_file_idx() { None => None, Some(idx) => self.remote.get(idx), } } // -- private /// ### get_local_file_idx /// /// Get index of selected file in the local tab fn get_local_file_idx(&self) -> Option<usize> { match self.view.get_value(super::COMPONENT_EXPLORER_LOCAL) { Some(Payload::Unsigned(idx)) => Some(idx), _ => None, } } /// ### get_remote_file_idx /// /// Get index of selected file in the remote file fn get_remote_file_idx(&self) -> Option<usize> { match self.view.get_value(super::COMPONENT_EXPLORER_REMOTE) { Some(Payload::Unsigned(idx)) => Some(idx), _ => None, } } }
38.641186
120
0.427874
fe7fa0222f0552ac9d7043b30ced1e6a27aea954
373
use std::thread; fn main() { let my_vec = vec![10, 33, 54]; let handle = thread::Builder::new() .name("my thread".to_owned()) .spawn(move || { println!("This is my vector: {:?}", my_vec); }) .expect("could not create the thread"); if handle.join().is_err() { println!("Something bad happened :("); } }
21.941176
56
0.512064
e58fccfe202ccc43bac88b6725c78f9b4a73ada2
15,538
//! This module implements lexing for number literals (123, 787) used in the JavaScript programing language. use super::{Cursor, Error, TokenKind, Tokenizer}; use crate::{ builtins::BigInt, profiler::BoaProfiler, syntax::{ ast::{Position, Span}, lexer::{token::Numeric, Token}, }, }; use std::io::Read; use std::str; /// Number literal lexing. /// /// Assumes the digit is consumed by the cursor (stored in init). /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-literals-numeric-literals /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type #[derive(Debug, Clone, Copy)] pub(super) struct NumberLiteral { init: u8, } impl NumberLiteral { /// Creates a new string literal lexer. pub(super) fn new(init: u8) -> Self { Self { init } } } /// This is a helper structure /// /// This structure helps with identifying what numerical type it is and what base is it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum NumericKind { Rational, Integer(u32), BigInt(u32), } impl NumericKind { /// Get the base of the number kind. fn base(self) -> u32 { match self { Self::Rational => 10, Self::Integer(base) => base, Self::BigInt(base) => base, } } /// Converts `self` to BigInt kind. fn to_bigint(self) -> Self { match self { Self::Rational => unreachable!("can not convert rational number to BigInt"), Self::Integer(base) => Self::BigInt(base), Self::BigInt(base) => Self::BigInt(base), } } } #[inline] fn take_signed_integer<R>( buf: &mut Vec<u8>, cursor: &mut Cursor<R>, kind: &NumericKind, ) -> Result<(), Error> where R: Read, { // The next part must be SignedInteger. // This is optionally a '+' or '-' followed by 1 or more DecimalDigits. match cursor.next_byte()? { Some(b'+') => { buf.push(b'+'); if !cursor.next_is_ascii_pred(&|ch| ch.is_digit(kind.base()))? { // A digit must follow the + or - symbol. return Err(Error::syntax("No digit found after + symbol", cursor.pos())); } } Some(b'-') => { buf.push(b'-'); if !cursor.next_is_ascii_pred(&|ch| ch.is_digit(kind.base()))? { // A digit must follow the + or - symbol. return Err(Error::syntax("No digit found after - symbol", cursor.pos())); } } Some(byte) => { let ch = char::from(byte); if ch.is_ascii() && ch.is_digit(kind.base()) { buf.push(byte); } else { return Err(Error::syntax( "When lexing exponential value found unexpected char", cursor.pos(), )); } } None => { return Err(Error::syntax( "Abrupt end: No exponential value found", cursor.pos(), )); } } // Consume the decimal digits. take_integer(buf, cursor, kind, true)?; Ok(()) } fn take_integer<R>( buf: &mut Vec<u8>, cursor: &mut Cursor<R>, kind: &NumericKind, separator_allowed: bool, ) -> Result<(), Error> where R: Read, { let mut prev_is_underscore = false; let mut pos = cursor.pos(); while cursor.next_is_ascii_pred(&|c| c.is_digit(kind.base()) || c == '_')? { pos = cursor.pos(); match cursor.next_byte()? { Some(c) if char::from(c).is_digit(kind.base()) => { prev_is_underscore = false; buf.push(c); } Some(b'_') if separator_allowed => { if prev_is_underscore { return Err(Error::syntax( "only one underscore is allowed as numeric separator", cursor.pos(), )); } prev_is_underscore = true; } Some(b'_') if !separator_allowed => { return Err(Error::syntax("separator is not allowed", pos)); } _ => (), } } if prev_is_underscore { return Err(Error::syntax( "underscores are not allowed at the end of numeric literals", pos, )); } Ok(()) } /// Utility function for checking the NumericLiteral is not followed by an `IdentifierStart` or `DecimalDigit` character. /// /// More information: /// - [ECMAScript Specification][spec] /// /// [spec]: https://tc39.es/ecma262/#sec-literals-numeric-literals #[inline] fn check_after_numeric_literal<R>(cursor: &mut Cursor<R>) -> Result<(), Error> where R: Read, { if cursor.next_is_ascii_pred(&|ch| ch.is_ascii_alphanumeric() || ch == '$' || ch == '_')? { Err(Error::syntax( "a numeric literal must not be followed by an alphanumeric, $ or _ characters", cursor.pos(), )) } else { Ok(()) } } impl<R> Tokenizer<R> for NumberLiteral { fn lex(&mut self, cursor: &mut Cursor<R>, start_pos: Position) -> Result<Token, Error> where R: Read, { let _timer = BoaProfiler::global().start_event("NumberLiteral", "Lexing"); let mut buf = vec![self.init]; // Default assume the number is a base 10 integer. let mut kind = NumericKind::Integer(10); let c = cursor.peek(); let mut legacy_octal = false; if self.init == b'0' { if let Some(ch) = c? { match ch { b'x' | b'X' => { // Remove the initial '0' from buffer. cursor.next_char()?.expect("x or X character vanished"); buf.pop(); // HexIntegerLiteral kind = NumericKind::Integer(16); // Checks if the next char after '0x' is a digit of that base. if not return an error. if !cursor.next_is_ascii_pred(&|ch| ch.is_digit(16))? { return Err(Error::syntax( "expected hexadecimal digit after number base prefix", cursor.pos(), )); } } b'o' | b'O' => { // Remove the initial '0' from buffer. cursor.next_char()?.expect("o or O character vanished"); buf.pop(); // OctalIntegerLiteral kind = NumericKind::Integer(8); // Checks if the next char after '0o' is a digit of that base. if not return an error. if !cursor.next_is_ascii_pred(&|ch| ch.is_digit(8))? { return Err(Error::syntax( "expected octal digit after number base prefix", cursor.pos(), )); } } b'b' | b'B' => { // Remove the initial '0' from buffer. cursor.next_char()?.expect("b or B character vanished"); buf.pop(); // BinaryIntegerLiteral kind = NumericKind::Integer(2); // Checks if the next char after '0b' is a digit of that base. if not return an error. if !cursor.next_is_ascii_pred(&|ch| ch.is_digit(2))? { return Err(Error::syntax( "expected binary digit after number base prefix", cursor.pos(), )); } } b'n' => { cursor.next_char()?.expect("n character vanished"); // DecimalBigIntegerLiteral '0n' return Ok(Token::new( TokenKind::NumericLiteral(Numeric::BigInt(0.into())), Span::new(start_pos, cursor.pos()), )); } byte => { legacy_octal = true; let ch = char::from(byte); if ch.is_digit(8) { // LegacyOctalIntegerLiteral if cursor.strict_mode() { // LegacyOctalIntegerLiteral is forbidden with strict mode true. return Err(Error::syntax( "implicit octal literals are not allowed in strict mode", start_pos, )); } else { // Remove the initial '0' from buffer. buf.pop(); buf.push(cursor.next_byte()?.expect("'0' character vanished")); kind = NumericKind::Integer(8); } } else if ch.is_digit(10) { // Indicates a numerical digit comes after then 0 but it isn't an octal digit // so therefore this must be a number with an unneeded leading 0. This is // forbidden in strict mode. if cursor.strict_mode() { return Err(Error::syntax( "leading 0's are not allowed in strict mode", start_pos, )); } } // Else indicates that the symbol is a non-number. } } } else { // DecimalLiteral lexing. // Indicates that the number is just a single 0. return Ok(Token::new( TokenKind::NumericLiteral(Numeric::Integer(0)), Span::new(start_pos, cursor.pos()), )); } } let next = if self.init == b'.' { Some(b'.') } else { // Consume digits and separators until a non-digit non-separator // character is encountered or all the characters are consumed. take_integer(&mut buf, cursor, &kind, !legacy_octal)?; cursor.peek()? }; // The non-digit character could be: // 'n' To indicate a BigIntLiteralSuffix. // '.' To indicate a decimal separator. // 'e' | 'E' To indicate an ExponentPart. match next { Some(b'n') => { // DecimalBigIntegerLiteral // Lexing finished. // Consume the n if legacy_octal { return Err(Error::syntax( "'n' suffix not allowed in octal representation", cursor.pos(), )); } cursor.next_byte()?.expect("n character vanished"); kind = kind.to_bigint(); } Some(b'.') => { if kind.base() == 10 { // Only base 10 numbers can have a decimal separator. // Number literal lexing finished if a . is found for a number in a different base. if self.init != b'.' { cursor.next_byte()?.expect("'.' token vanished"); buf.push(b'.'); // Consume the . } kind = NumericKind::Rational; if cursor.peek()? == Some(b'_') { return Err(Error::syntax( "numeric separator not allowed after '.'", cursor.pos(), )); } // Consume digits and separators until a non-digit non-separator // character is encountered or all the characters are consumed. take_integer(&mut buf, cursor, &kind, true)?; // The non-digit character at this point must be an 'e' or 'E' to indicate an Exponent Part. // Another '.' or 'n' is not allowed. match cursor.peek()? { Some(b'e') | Some(b'E') => { // Consume the ExponentIndicator. cursor.next_byte()?.expect("e or E token vanished"); buf.push(b'E'); take_signed_integer(&mut buf, cursor, &kind)?; } Some(_) | None => { // Finished lexing. } } } } Some(b'e') | Some(b'E') => { kind = NumericKind::Rational; cursor.next_byte()?.expect("e or E character vanished"); // Consume the ExponentIndicator. buf.push(b'E'); take_signed_integer(&mut buf, cursor, &kind)?; } Some(_) | None => { // Indicates lexing finished. } } check_after_numeric_literal(cursor)?; let num_str = unsafe { str::from_utf8_unchecked(buf.as_slice()) }; let num = match kind { NumericKind::BigInt(base) => { Numeric::BigInt( BigInt::from_string_radix(num_str, base).expect("Could not convert to BigInt") ) } NumericKind::Rational /* base: 10 */ => { let val: f64 = fast_float::parse(num_str).expect("Failed to parse float after checks"); let int_val = val as i32; // The truncated float should be identically to the non-truncated float for the conversion to be loss-less, // any other different and the number must be stored as a rational. #[allow(clippy::float_cmp)] if (int_val as f64) == val { // For performance reasons we attempt to store values as integers if possible. Numeric::Integer(int_val) } else { Numeric::Rational(val) } }, NumericKind::Integer(base) => { if let Ok(num) = i32::from_str_radix(num_str, base) { Numeric::Integer(num) } else { let b = f64::from(base); let mut result = 0.0_f64; for c in num_str.chars() { let digit = f64::from(c.to_digit(base).expect("could not parse digit after already checking validity")); result = result * b + digit; } Numeric::Rational(result) } } }; Ok(Token::new( TokenKind::NumericLiteral(num), Span::new(start_pos, cursor.pos()), )) } }
37.172249
128
0.456816
0376512d968b439420d34c85295d4ad1528ccb7e
4,333
//! With this module you can perform actions that are terminal related. //! Like clearing and scrolling in the terminal or getting the size of the terminal. use super::*; use shared::functions; use {Construct, Context}; use std::ops::Drop; /// Struct that stores an specific platform implementation for terminal related actions. pub struct Terminal { terminal: Option<Box<ITerminal>>, } impl Terminal { /// Create new terminal instance whereon terminal related actions can be performed. pub fn new() -> Terminal { #[cfg(target_os = "windows")] let terminal = functions::get_module::<Box<ITerminal>>(WinApiTerminal::new(), AnsiTerminal::new()); #[cfg(not(target_os = "windows"))] let terminal = Some(AnsiTerminal::new() as Box<ITerminal>); Terminal { terminal: terminal } } /// Clear the current cursor by specifying the clear type /// /// #Example /// /// ```rust /// /// extern crate crossterm; /// use crossterm::terminal; /// /// let mut term = terminal::terminal(); /// /// // clear all cells in terminal. /// term.clear(terminal::ClearType::All); /// // clear all cells from the cursor position downwards in terminal. /// term.clear(terminal::ClearType::FromCursorDown); /// // clear all cells from the cursor position upwards in terminal. /// term.clear(terminal::ClearType::FromCursorUp); /// // clear current line cells in terminal. /// term.clear(terminal::ClearType::CurrentLine); /// // clear all cells from cursor position until new line in terminal. /// term.clear(terminal::ClearType::UntilNewLine); /// /// ``` pub fn clear(&mut self, clear_type: ClearType) { if let Some(ref terminal) = self.terminal { terminal.clear(clear_type); } } /// Get the terminal size (x,y). /// /// #Example /// /// ```rust /// /// extern crate crossterm; /// use crossterm::terminal; /// /// let mut term = terminal::terminal(); /// /// let size = term.terminal_size(); /// println!("{:?}", size); /// /// ``` pub fn terminal_size(&mut self) -> (u16, u16) { if let Some(ref terminal) = self.terminal { return terminal.terminal_size(); } (0, 0) } /// Scroll `n` lines up in the current terminal. /// /// #Example /// /// ```rust /// /// extern crate crossterm; /// use crossterm::terminal; /// /// let mut term = terminal::terminal(); /// /// // scroll up by 5 lines /// let size = term.scroll_up(5); /// /// ``` pub fn scroll_up(&mut self, count: i16) { if let Some(ref terminal) = self.terminal { terminal.scroll_up(count); } } /// Scroll `n` lines up in the current terminal. /// /// #Example /// /// ```rust /// /// extern crate crossterm; /// use crossterm::terminal; /// /// let mut term = terminal::terminal(); /// /// // scroll down by 5 lines /// let size = term.scroll_down(5); /// /// ``` pub fn scroll_down(&mut self, count: i16) { if let Some(ref terminal) = self.terminal { terminal.scroll_down(count); } } /// Set the terminal size. Note that not all terminals can be set to a very small scale. /// /// #Example /// /// ```rust /// /// extern crate crossterm; /// use crossterm::terminal; /// /// let mut term = terminal::terminal(); /// /// // Set of the size to X: 10 and Y: 10 /// let size = term.set_size(10,10); /// /// ``` pub fn set_size(&mut self, width: i16, height: i16) { if let Some(ref terminal) = self.terminal { terminal.set_size(width, height); } } } /// Get an Terminal implementation whereon terminal related actions can be performed. /// /// Check `/examples/terminal` in the libary for more spesific examples. /// /// #Example /// /// ```rust /// /// extern crate crossterm; /// use crossterm::terminal; /// /// let mut term = terminal::terminal(); /// /// // scroll down by 5 lines /// let size = term.scroll_down(5); /// /// ``` /// pub fn terminal() -> Box<Terminal> { Box::from(Terminal::new()) }
26.420732
96
0.564274
03df6008386acf796cd42bcd3e1ab154f635e59c
12,342
/* automatically generated by rust-bindgen */ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)] #[repr(C)] #[derive(Copy)] pub struct A { pub c: ::std::os::raw::c_uint, pub named_union: A__bindgen_ty_1, pub __bindgen_anon_1: A__bindgen_ty_2, } #[repr(C)] #[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] pub struct A_Segment { pub begin: ::std::os::raw::c_int, pub end: ::std::os::raw::c_int, } #[test] fn bindgen_test_layout_A_Segment() { assert_eq!(::std::mem::size_of::<A_Segment>() , 8usize , concat ! ( "Size of: " , stringify ! ( A_Segment ) )); assert_eq! (::std::mem::align_of::<A_Segment>() , 4usize , concat ! ( "Alignment of " , stringify ! ( A_Segment ) )); assert_eq! (unsafe { & ( * ( 0 as * const A_Segment ) ) . begin as * const _ as usize } , 0usize , concat ! ( "Alignment of field: " , stringify ! ( A_Segment ) , "::" , stringify ! ( begin ) )); assert_eq! (unsafe { & ( * ( 0 as * const A_Segment ) ) . end as * const _ as usize } , 4usize , concat ! ( "Alignment of field: " , stringify ! ( A_Segment ) , "::" , stringify ! ( end ) )); } impl Clone for A_Segment { fn clone(&self) -> Self { *self } } #[repr(C)] #[derive(Copy)] pub union A__bindgen_ty_1 { pub f: ::std::os::raw::c_int, _bindgen_union_align: u32, } #[test] fn bindgen_test_layout_A__bindgen_ty_1() { assert_eq!(::std::mem::size_of::<A__bindgen_ty_1>() , 4usize , concat ! ( "Size of: " , stringify ! ( A__bindgen_ty_1 ) )); assert_eq! (::std::mem::align_of::<A__bindgen_ty_1>() , 4usize , concat ! ( "Alignment of " , stringify ! ( A__bindgen_ty_1 ) )); assert_eq! (unsafe { & ( * ( 0 as * const A__bindgen_ty_1 ) ) . f as * const _ as usize } , 0usize , concat ! ( "Alignment of field: " , stringify ! ( A__bindgen_ty_1 ) , "::" , stringify ! ( f ) )); } impl Clone for A__bindgen_ty_1 { fn clone(&self) -> Self { *self } } impl Default for A__bindgen_ty_1 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub union A__bindgen_ty_2 { pub d: ::std::os::raw::c_int, _bindgen_union_align: u32, } #[test] fn bindgen_test_layout_A__bindgen_ty_2() { assert_eq!(::std::mem::size_of::<A__bindgen_ty_2>() , 4usize , concat ! ( "Size of: " , stringify ! ( A__bindgen_ty_2 ) )); assert_eq! (::std::mem::align_of::<A__bindgen_ty_2>() , 4usize , concat ! ( "Alignment of " , stringify ! ( A__bindgen_ty_2 ) )); assert_eq! (unsafe { & ( * ( 0 as * const A__bindgen_ty_2 ) ) . d as * const _ as usize } , 0usize , concat ! ( "Alignment of field: " , stringify ! ( A__bindgen_ty_2 ) , "::" , stringify ! ( d ) )); } impl Clone for A__bindgen_ty_2 { fn clone(&self) -> Self { *self } } impl Default for A__bindgen_ty_2 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[test] fn bindgen_test_layout_A() { assert_eq!(::std::mem::size_of::<A>() , 12usize , concat ! ( "Size of: " , stringify ! ( A ) )); assert_eq! (::std::mem::align_of::<A>() , 4usize , concat ! ( "Alignment of " , stringify ! ( A ) )); assert_eq! (unsafe { & ( * ( 0 as * const A ) ) . c as * const _ as usize } , 0usize , concat ! ( "Alignment of field: " , stringify ! ( A ) , "::" , stringify ! ( c ) )); assert_eq! (unsafe { & ( * ( 0 as * const A ) ) . named_union as * const _ as usize } , 4usize , concat ! ( "Alignment of field: " , stringify ! ( A ) , "::" , stringify ! ( named_union ) )); } impl Clone for A { fn clone(&self) -> Self { *self } } impl Default for A { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] pub struct B { pub d: ::std::os::raw::c_uint, } #[repr(C)] #[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] pub struct B_Segment { pub begin: ::std::os::raw::c_int, pub end: ::std::os::raw::c_int, } #[test] fn bindgen_test_layout_B_Segment() { assert_eq!(::std::mem::size_of::<B_Segment>() , 8usize , concat ! ( "Size of: " , stringify ! ( B_Segment ) )); assert_eq! (::std::mem::align_of::<B_Segment>() , 4usize , concat ! ( "Alignment of " , stringify ! ( B_Segment ) )); assert_eq! (unsafe { & ( * ( 0 as * const B_Segment ) ) . begin as * const _ as usize } , 0usize , concat ! ( "Alignment of field: " , stringify ! ( B_Segment ) , "::" , stringify ! ( begin ) )); assert_eq! (unsafe { & ( * ( 0 as * const B_Segment ) ) . end as * const _ as usize } , 4usize , concat ! ( "Alignment of field: " , stringify ! ( B_Segment ) , "::" , stringify ! ( end ) )); } impl Clone for B_Segment { fn clone(&self) -> Self { *self } } #[test] fn bindgen_test_layout_B() { assert_eq!(::std::mem::size_of::<B>() , 4usize , concat ! ( "Size of: " , stringify ! ( B ) )); assert_eq! (::std::mem::align_of::<B>() , 4usize , concat ! ( "Alignment of " , stringify ! ( B ) )); assert_eq! (unsafe { & ( * ( 0 as * const B ) ) . d as * const _ as usize } , 0usize , concat ! ( "Alignment of field: " , stringify ! ( B ) , "::" , stringify ! ( d ) )); } impl Clone for B { fn clone(&self) -> Self { *self } } #[repr(i32)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum StepSyntax { Keyword = 0, FunctionalWithoutKeyword = 1, FunctionalWithStartKeyword = 2, FunctionalWithEndKeyword = 3, } #[repr(C)] #[derive(Copy)] pub struct C { pub d: ::std::os::raw::c_uint, pub __bindgen_anon_1: C__bindgen_ty_1, } #[repr(C)] #[derive(Copy)] pub union C__bindgen_ty_1 { pub mFunc: C__bindgen_ty_1__bindgen_ty_1, pub __bindgen_anon_1: C__bindgen_ty_1__bindgen_ty_2, _bindgen_union_align: [u32; 4usize], } #[repr(C)] #[derive(Debug, Default, Copy, PartialEq)] pub struct C__bindgen_ty_1__bindgen_ty_1 { pub mX1: f32, pub mY1: f32, pub mX2: f32, pub mY2: f32, } #[test] fn bindgen_test_layout_C__bindgen_ty_1__bindgen_ty_1() { assert_eq!(::std::mem::size_of::<C__bindgen_ty_1__bindgen_ty_1>() , 16usize , concat ! ( "Size of: " , stringify ! ( C__bindgen_ty_1__bindgen_ty_1 ) )); assert_eq! (::std::mem::align_of::<C__bindgen_ty_1__bindgen_ty_1>() , 4usize , concat ! ( "Alignment of " , stringify ! ( C__bindgen_ty_1__bindgen_ty_1 ) )); assert_eq! (unsafe { & ( * ( 0 as * const C__bindgen_ty_1__bindgen_ty_1 ) ) . mX1 as * const _ as usize } , 0usize , concat ! ( "Alignment of field: " , stringify ! ( C__bindgen_ty_1__bindgen_ty_1 ) , "::" , stringify ! ( mX1 ) )); assert_eq! (unsafe { & ( * ( 0 as * const C__bindgen_ty_1__bindgen_ty_1 ) ) . mY1 as * const _ as usize } , 4usize , concat ! ( "Alignment of field: " , stringify ! ( C__bindgen_ty_1__bindgen_ty_1 ) , "::" , stringify ! ( mY1 ) )); assert_eq! (unsafe { & ( * ( 0 as * const C__bindgen_ty_1__bindgen_ty_1 ) ) . mX2 as * const _ as usize } , 8usize , concat ! ( "Alignment of field: " , stringify ! ( C__bindgen_ty_1__bindgen_ty_1 ) , "::" , stringify ! ( mX2 ) )); assert_eq! (unsafe { & ( * ( 0 as * const C__bindgen_ty_1__bindgen_ty_1 ) ) . mY2 as * const _ as usize } , 12usize , concat ! ( "Alignment of field: " , stringify ! ( C__bindgen_ty_1__bindgen_ty_1 ) , "::" , stringify ! ( mY2 ) )); } impl Clone for C__bindgen_ty_1__bindgen_ty_1 { fn clone(&self) -> Self { *self } } #[repr(C)] #[derive(Debug, Copy, Hash, PartialEq, Eq)] pub struct C__bindgen_ty_1__bindgen_ty_2 { pub mStepSyntax: StepSyntax, pub mSteps: ::std::os::raw::c_uint, } #[test] fn bindgen_test_layout_C__bindgen_ty_1__bindgen_ty_2() { assert_eq!(::std::mem::size_of::<C__bindgen_ty_1__bindgen_ty_2>() , 8usize , concat ! ( "Size of: " , stringify ! ( C__bindgen_ty_1__bindgen_ty_2 ) )); assert_eq! (::std::mem::align_of::<C__bindgen_ty_1__bindgen_ty_2>() , 4usize , concat ! ( "Alignment of " , stringify ! ( C__bindgen_ty_1__bindgen_ty_2 ) )); assert_eq! (unsafe { & ( * ( 0 as * const C__bindgen_ty_1__bindgen_ty_2 ) ) . mStepSyntax as * const _ as usize } , 0usize , concat ! ( "Alignment of field: " , stringify ! ( C__bindgen_ty_1__bindgen_ty_2 ) , "::" , stringify ! ( mStepSyntax ) )); assert_eq! (unsafe { & ( * ( 0 as * const C__bindgen_ty_1__bindgen_ty_2 ) ) . mSteps as * const _ as usize } , 4usize , concat ! ( "Alignment of field: " , stringify ! ( C__bindgen_ty_1__bindgen_ty_2 ) , "::" , stringify ! ( mSteps ) )); } impl Clone for C__bindgen_ty_1__bindgen_ty_2 { fn clone(&self) -> Self { *self } } impl Default for C__bindgen_ty_1__bindgen_ty_2 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[test] fn bindgen_test_layout_C__bindgen_ty_1() { assert_eq!(::std::mem::size_of::<C__bindgen_ty_1>() , 16usize , concat ! ( "Size of: " , stringify ! ( C__bindgen_ty_1 ) )); assert_eq! (::std::mem::align_of::<C__bindgen_ty_1>() , 4usize , concat ! ( "Alignment of " , stringify ! ( C__bindgen_ty_1 ) )); assert_eq! (unsafe { & ( * ( 0 as * const C__bindgen_ty_1 ) ) . mFunc as * const _ as usize } , 0usize , concat ! ( "Alignment of field: " , stringify ! ( C__bindgen_ty_1 ) , "::" , stringify ! ( mFunc ) )); } impl Clone for C__bindgen_ty_1 { fn clone(&self) -> Self { *self } } impl Default for C__bindgen_ty_1 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Debug, Default, Copy, Hash, PartialEq, Eq)] pub struct C_Segment { pub begin: ::std::os::raw::c_int, pub end: ::std::os::raw::c_int, } #[test] fn bindgen_test_layout_C_Segment() { assert_eq!(::std::mem::size_of::<C_Segment>() , 8usize , concat ! ( "Size of: " , stringify ! ( C_Segment ) )); assert_eq! (::std::mem::align_of::<C_Segment>() , 4usize , concat ! ( "Alignment of " , stringify ! ( C_Segment ) )); assert_eq! (unsafe { & ( * ( 0 as * const C_Segment ) ) . begin as * const _ as usize } , 0usize , concat ! ( "Alignment of field: " , stringify ! ( C_Segment ) , "::" , stringify ! ( begin ) )); assert_eq! (unsafe { & ( * ( 0 as * const C_Segment ) ) . end as * const _ as usize } , 4usize , concat ! ( "Alignment of field: " , stringify ! ( C_Segment ) , "::" , stringify ! ( end ) )); } impl Clone for C_Segment { fn clone(&self) -> Self { *self } } #[test] fn bindgen_test_layout_C() { assert_eq!(::std::mem::size_of::<C>() , 20usize , concat ! ( "Size of: " , stringify ! ( C ) )); assert_eq! (::std::mem::align_of::<C>() , 4usize , concat ! ( "Alignment of " , stringify ! ( C ) )); assert_eq! (unsafe { & ( * ( 0 as * const C ) ) . d as * const _ as usize } , 0usize , concat ! ( "Alignment of field: " , stringify ! ( C ) , "::" , stringify ! ( d ) )); } impl Clone for C { fn clone(&self) -> Self { *self } } impl Default for C { fn default() -> Self { unsafe { ::std::mem::zeroed() } } }
39.056962
82
0.531356
14c0f7ee2c50cd5b2e5b0a705808101db8b4e265
6,226
// Copyright 2019, The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use super::protocol as proto; use crate::transactions::transaction_protocol::sender::{SingleRoundSenderData, TransactionSenderMessage}; use super::protocol::transaction_sender_message::Message as ProtoTransactionSenderMessage; use std::convert::{TryFrom, TryInto}; use tari_crypto::tari_utilities::ByteArray; // The generated _oneof_ enum use proto::transaction_sender_message::Message as ProtoTxnSenderMessage; use tari_common_types::types::PublicKey; use tari_crypto::script::TariScript; impl proto::TransactionSenderMessage { pub fn none() -> Self { proto::TransactionSenderMessage { message: Some(ProtoTxnSenderMessage::None(true)), } } pub fn single(data: proto::SingleRoundSenderData) -> Self { proto::TransactionSenderMessage { message: Some(ProtoTxnSenderMessage::Single(data)), } } pub fn multiple() -> Self { proto::TransactionSenderMessage { message: Some(ProtoTxnSenderMessage::Multiple(true)), } } } impl TryFrom<proto::TransactionSenderMessage> for TransactionSenderMessage { type Error = String; fn try_from(message: proto::TransactionSenderMessage) -> Result<Self, Self::Error> { let inner_message = message .message .ok_or_else(|| "TransactionSenderMessage.message not provided".to_string())?; let sender_message = match inner_message { ProtoTxnSenderMessage::None(_) => TransactionSenderMessage::None, ProtoTxnSenderMessage::Single(data) => TransactionSenderMessage::Single(Box::new(data.try_into()?)), ProtoTxnSenderMessage::Multiple(_) => TransactionSenderMessage::Multiple, }; Ok(sender_message) } } impl From<TransactionSenderMessage> for proto::TransactionSenderMessage { fn from(message: TransactionSenderMessage) -> Self { let message = match message { TransactionSenderMessage::None => ProtoTransactionSenderMessage::None(true), TransactionSenderMessage::Single(sender_data) => { ProtoTransactionSenderMessage::Single((*sender_data).into()) }, TransactionSenderMessage::Multiple => ProtoTransactionSenderMessage::Multiple(true), }; Self { message: Some(message) } } } //---------------------------------- SingleRoundSenderData --------------------------------------------// impl TryFrom<proto::SingleRoundSenderData> for SingleRoundSenderData { type Error = String; fn try_from(data: proto::SingleRoundSenderData) -> Result<Self, Self::Error> { let public_excess = PublicKey::from_bytes(&data.public_excess).map_err(|err| err.to_string())?; let public_nonce = PublicKey::from_bytes(&data.public_nonce).map_err(|err| err.to_string())?; let sender_offset_public_key = PublicKey::from_bytes(&data.sender_offset_public_key).map_err(|err| err.to_string())?; let metadata = data .metadata .map(Into::into) .ok_or_else(|| "Transaction metadata not provided".to_string())?; let message = data.message; let public_commitment_nonce = PublicKey::from_bytes(&data.public_commitment_nonce).map_err(|err| err.to_string())?; let features = data .features .map(TryInto::try_into) .ok_or_else(|| "Transaction output features not provided".to_string())??; Ok(Self { tx_id: data.tx_id, amount: data.amount.into(), public_excess, public_nonce, metadata, message, features, script: TariScript::from_bytes(&data.script).map_err(|err| err.to_string())?, sender_offset_public_key, public_commitment_nonce, }) } } impl From<SingleRoundSenderData> for proto::SingleRoundSenderData { fn from(sender_data: SingleRoundSenderData) -> Self { Self { tx_id: sender_data.tx_id, // The amount, in µT, being sent to the recipient amount: sender_data.amount.into(), // The offset public excess for this transaction public_excess: sender_data.public_excess.to_vec(), public_nonce: sender_data.public_nonce.to_vec(), metadata: Some(sender_data.metadata.into()), message: sender_data.message, features: Some(sender_data.features.into()), script: sender_data.script.as_bytes(), sender_offset_public_key: sender_data.sender_offset_public_key.to_vec(), public_commitment_nonce: sender_data.public_commitment_nonce.to_vec(), } } }
43.84507
118
0.680854
d94b8884112d66e35a113aeec90d5c619844edcc
24,714
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! rustc compiler intrinsics. //! //! The corresponding definitions are in librustc_trans/trans/intrinsic.rs. //! //! # Volatiles //! //! The volatile intrinsics provide operations intended to act on I/O //! memory, which are guaranteed to not be reordered by the compiler //! across other volatile intrinsics. See the LLVM documentation on //! [[volatile]]. //! //! [volatile]: http://llvm.org/docs/LangRef.html#volatile-memory-accesses //! //! # Atomics //! //! The atomic intrinsics provide common atomic operations on machine //! words, with multiple possible memory orderings. They obey the same //! semantics as C++11. See the LLVM documentation on [[atomics]]. //! //! [atomics]: http://llvm.org/docs/Atomics.html //! //! A quick refresher on memory ordering: //! //! * Acquire - a barrier for acquiring a lock. Subsequent reads and writes //! take place after the barrier. //! * Release - a barrier for releasing a lock. Preceding reads and writes //! take place before the barrier. //! * Sequentially consistent - sequentially consistent operations are //! guaranteed to happen in order. This is the standard mode for working //! with atomic types and is equivalent to Java's `volatile`. #![unstable(feature = "core")] #![allow(missing_docs)] use marker::Sized; extern "rust-intrinsic" { // NB: These intrinsics take unsafe pointers because they mutate aliased // memory, which is not valid for either `&` or `&mut`. pub fn atomic_cxchg<T>(dst: *mut T, old: T, src: T) -> T; pub fn atomic_cxchg_acq<T>(dst: *mut T, old: T, src: T) -> T; pub fn atomic_cxchg_rel<T>(dst: *mut T, old: T, src: T) -> T; pub fn atomic_cxchg_acqrel<T>(dst: *mut T, old: T, src: T) -> T; pub fn atomic_cxchg_relaxed<T>(dst: *mut T, old: T, src: T) -> T; pub fn atomic_load<T>(src: *const T) -> T; pub fn atomic_load_acq<T>(src: *const T) -> T; pub fn atomic_load_relaxed<T>(src: *const T) -> T; pub fn atomic_load_unordered<T>(src: *const T) -> T; pub fn atomic_store<T>(dst: *mut T, val: T); pub fn atomic_store_rel<T>(dst: *mut T, val: T); pub fn atomic_store_relaxed<T>(dst: *mut T, val: T); pub fn atomic_store_unordered<T>(dst: *mut T, val: T); pub fn atomic_xchg<T>(dst: *mut T, src: T) -> T; pub fn atomic_xchg_acq<T>(dst: *mut T, src: T) -> T; pub fn atomic_xchg_rel<T>(dst: *mut T, src: T) -> T; pub fn atomic_xchg_acqrel<T>(dst: *mut T, src: T) -> T; pub fn atomic_xchg_relaxed<T>(dst: *mut T, src: T) -> T; pub fn atomic_xadd<T>(dst: *mut T, src: T) -> T; pub fn atomic_xadd_acq<T>(dst: *mut T, src: T) -> T; pub fn atomic_xadd_rel<T>(dst: *mut T, src: T) -> T; pub fn atomic_xadd_acqrel<T>(dst: *mut T, src: T) -> T; pub fn atomic_xadd_relaxed<T>(dst: *mut T, src: T) -> T; pub fn atomic_xsub<T>(dst: *mut T, src: T) -> T; pub fn atomic_xsub_acq<T>(dst: *mut T, src: T) -> T; pub fn atomic_xsub_rel<T>(dst: *mut T, src: T) -> T; pub fn atomic_xsub_acqrel<T>(dst: *mut T, src: T) -> T; pub fn atomic_xsub_relaxed<T>(dst: *mut T, src: T) -> T; pub fn atomic_and<T>(dst: *mut T, src: T) -> T; pub fn atomic_and_acq<T>(dst: *mut T, src: T) -> T; pub fn atomic_and_rel<T>(dst: *mut T, src: T) -> T; pub fn atomic_and_acqrel<T>(dst: *mut T, src: T) -> T; pub fn atomic_and_relaxed<T>(dst: *mut T, src: T) -> T; pub fn atomic_nand<T>(dst: *mut T, src: T) -> T; pub fn atomic_nand_acq<T>(dst: *mut T, src: T) -> T; pub fn atomic_nand_rel<T>(dst: *mut T, src: T) -> T; pub fn atomic_nand_acqrel<T>(dst: *mut T, src: T) -> T; pub fn atomic_nand_relaxed<T>(dst: *mut T, src: T) -> T; pub fn atomic_or<T>(dst: *mut T, src: T) -> T; pub fn atomic_or_acq<T>(dst: *mut T, src: T) -> T; pub fn atomic_or_rel<T>(dst: *mut T, src: T) -> T; pub fn atomic_or_acqrel<T>(dst: *mut T, src: T) -> T; pub fn atomic_or_relaxed<T>(dst: *mut T, src: T) -> T; pub fn atomic_xor<T>(dst: *mut T, src: T) -> T; pub fn atomic_xor_acq<T>(dst: *mut T, src: T) -> T; pub fn atomic_xor_rel<T>(dst: *mut T, src: T) -> T; pub fn atomic_xor_acqrel<T>(dst: *mut T, src: T) -> T; pub fn atomic_xor_relaxed<T>(dst: *mut T, src: T) -> T; pub fn atomic_max<T>(dst: *mut T, src: T) -> T; pub fn atomic_max_acq<T>(dst: *mut T, src: T) -> T; pub fn atomic_max_rel<T>(dst: *mut T, src: T) -> T; pub fn atomic_max_acqrel<T>(dst: *mut T, src: T) -> T; pub fn atomic_max_relaxed<T>(dst: *mut T, src: T) -> T; pub fn atomic_min<T>(dst: *mut T, src: T) -> T; pub fn atomic_min_acq<T>(dst: *mut T, src: T) -> T; pub fn atomic_min_rel<T>(dst: *mut T, src: T) -> T; pub fn atomic_min_acqrel<T>(dst: *mut T, src: T) -> T; pub fn atomic_min_relaxed<T>(dst: *mut T, src: T) -> T; pub fn atomic_umin<T>(dst: *mut T, src: T) -> T; pub fn atomic_umin_acq<T>(dst: *mut T, src: T) -> T; pub fn atomic_umin_rel<T>(dst: *mut T, src: T) -> T; pub fn atomic_umin_acqrel<T>(dst: *mut T, src: T) -> T; pub fn atomic_umin_relaxed<T>(dst: *mut T, src: T) -> T; pub fn atomic_umax<T>(dst: *mut T, src: T) -> T; pub fn atomic_umax_acq<T>(dst: *mut T, src: T) -> T; pub fn atomic_umax_rel<T>(dst: *mut T, src: T) -> T; pub fn atomic_umax_acqrel<T>(dst: *mut T, src: T) -> T; pub fn atomic_umax_relaxed<T>(dst: *mut T, src: T) -> T; } extern "rust-intrinsic" { pub fn atomic_fence(); pub fn atomic_fence_acq(); pub fn atomic_fence_rel(); pub fn atomic_fence_acqrel(); /// A compiler-only memory barrier. /// /// Memory accesses will never be reordered across this barrier by the compiler, /// but no instructions will be emitted for it. This is appropriate for operations /// on the same thread that may be preempted, such as when interacting with signal /// handlers. #[cfg(not(stage0))] // SNAP 857ef6e pub fn atomic_singlethreadfence(); #[cfg(not(stage0))] // SNAP 857ef6e pub fn atomic_singlethreadfence_acq(); #[cfg(not(stage0))] // SNAP 857ef6e pub fn atomic_singlethreadfence_rel(); #[cfg(not(stage0))] // SNAP 857ef6e pub fn atomic_singlethreadfence_acqrel(); /// Aborts the execution of the process. pub fn abort() -> !; /// Tells LLVM that this point in the code is not reachable, /// enabling further optimizations. /// /// NB: This is very different from the `unreachable!()` macro! pub fn unreachable() -> !; /// Informs the optimizer that a condition is always true. /// If the condition is false, the behavior is undefined. /// /// No code is generated for this intrinsic, but the optimizer will try /// to preserve it (and its condition) between passes, which may interfere /// with optimization of surrounding code and reduce performance. It should /// not be used if the invariant can be discovered by the optimizer on its /// own, or if it does not enable any significant optimizations. pub fn assume(b: bool); /// Executes a breakpoint trap, for inspection by a debugger. pub fn breakpoint(); /// The size of a type in bytes. /// /// This is the exact number of bytes in memory taken up by a /// value of the given type. In other words, a memset of this size /// would *exactly* overwrite a value. When laid out in vectors /// and structures there may be additional padding between /// elements. pub fn size_of<T>() -> usize; /// Moves a value to an uninitialized memory location. /// /// Drop glue is not run on the destination. pub fn move_val_init<T>(dst: &mut T, src: T); pub fn min_align_of<T>() -> usize; pub fn pref_align_of<T>() -> usize; #[cfg(not(stage0))] pub fn size_of_val<T: ?Sized>(_: &T) -> usize; #[cfg(not(stage0))] pub fn min_align_of_val<T: ?Sized>(_: &T) -> usize; #[cfg(not(stage0))] pub fn drop_in_place<T: ?Sized>(_: *mut T); /// Gets a static string slice containing the name of a type. pub fn type_name<T: ?Sized>() -> &'static str; /// Gets an identifier which is globally unique to the specified type. This /// function will return the same value for a type regardless of whichever /// crate it is invoked in. pub fn type_id<T: ?Sized + 'static>() -> u64; /// Creates a value initialized to so that its drop flag, /// if any, says that it has been dropped. /// /// `init_dropped` is unsafe because it returns a datum with all /// of its bytes set to the drop flag, which generally does not /// correspond to a valid value. /// /// This intrinsic is likely to be deprecated in the future when /// Rust moves to non-zeroing dynamic drop (and thus removes the /// embedded drop flags that are being established by this /// intrinsic). pub fn init_dropped<T>() -> T; /// Creates a value initialized to zero. /// /// `init` is unsafe because it returns a zeroed-out datum, /// which is unsafe unless T is `Copy`. Also, even if T is /// `Copy`, an all-zero value may not correspond to any legitimate /// state for the type in question. pub fn init<T>() -> T; /// Creates an uninitialized value. /// /// `uninit` is unsafe because there is no guarantee of what its /// contents are. In particular its drop-flag may be set to any /// state, which means it may claim either dropped or /// undropped. In the general case one must use `ptr::write` to /// initialize memory previous set to the result of `uninit`. pub fn uninit<T>() -> T; /// Moves a value out of scope without running drop glue. pub fn forget<T>(_: T) -> (); /// Unsafely transforms a value of one type into a value of another type. /// /// Both types must have the same size. /// /// # Examples /// /// ``` /// use std::mem; /// /// let v: &[u8] = unsafe { mem::transmute("L") }; /// assert!(v == [76]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn transmute<T,U>(e: T) -> U; /// Gives the address for the return value of the enclosing function. /// /// Using this intrinsic in a function that does not use an out pointer /// will trigger a compiler error. pub fn return_address() -> *const u8; /// Returns `true` if the actual type given as `T` requires drop /// glue; returns `false` if the actual type provided for `T` /// implements `Copy`. /// /// If the actual type neither requires drop glue nor implements /// `Copy`, then may return `true` or `false`. pub fn needs_drop<T>() -> bool; /// Calculates the offset from a pointer. /// /// This is implemented as an intrinsic to avoid converting to and from an /// integer, since the conversion would throw away aliasing information. /// /// # Safety /// /// Both the starting and resulting pointer must be either in bounds or one /// byte past the end of an allocated object. If either pointer is out of /// bounds or arithmetic overflow occurs then any further use of the /// returned value will result in undefined behavior. pub fn offset<T>(dst: *const T, offset: isize) -> *const T; /// Copies `count * size_of<T>` bytes from `src` to `dst`. The source /// and destination may *not* overlap. /// /// `copy_nonoverlapping` is semantically equivalent to C's `memcpy`. /// /// # Safety /// /// Beyond requiring that the program must be allowed to access both regions /// of memory, it is Undefined Behaviour for source and destination to /// overlap. Care must also be taken with the ownership of `src` and /// `dst`. This method semantically moves the values of `src` into `dst`. /// However it does not drop the contents of `dst`, or prevent the contents /// of `src` from being dropped or used. /// /// # Examples /// /// A safe swap function: /// /// ``` /// # #![feature(core)] /// use std::mem; /// use std::ptr; /// /// fn swap<T>(x: &mut T, y: &mut T) { /// unsafe { /// // Give ourselves some scratch space to work with /// let mut t: T = mem::uninitialized(); /// /// // Perform the swap, `&mut` pointers never alias /// ptr::copy_nonoverlapping(x, &mut t, 1); /// ptr::copy_nonoverlapping(y, x, 1); /// ptr::copy_nonoverlapping(&t, y, 1); /// /// // y and t now point to the same thing, but we need to completely forget `tmp` /// // because it's no longer relevant. /// mem::forget(t); /// } /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize); /// Copies `count * size_of<T>` bytes from `src` to `dst`. The source /// and destination may overlap. /// /// `copy` is semantically equivalent to C's `memmove`. /// /// # Safety /// /// Care must be taken with the ownership of `src` and `dst`. /// This method semantically moves the values of `src` into `dst`. /// However it does not drop the contents of `dst`, or prevent the contents of `src` /// from being dropped or used. /// /// # Examples /// /// Efficiently create a Rust vector from an unsafe buffer: /// /// ``` /// # #![feature(core)] /// use std::ptr; /// /// unsafe fn from_buf_raw<T>(ptr: *const T, elts: usize) -> Vec<T> { /// let mut dst = Vec::with_capacity(elts); /// dst.set_len(elts); /// ptr::copy(ptr, dst.as_mut_ptr(), elts); /// dst /// } /// ``` /// #[stable(feature = "rust1", since = "1.0.0")] pub fn copy<T>(src: *const T, dst: *mut T, count: usize); /// Invokes memset on the specified pointer, setting `count * size_of::<T>()` /// bytes of memory starting at `dst` to `c`. #[stable(feature = "rust1", since = "1.0.0")] pub fn write_bytes<T>(dst: *mut T, val: u8, count: usize); /// Equivalent to the appropriate `llvm.memcpy.p0i8.0i8.*` intrinsic, with /// a size of `count` * `size_of::<T>()` and an alignment of /// `min_align_of::<T>()` /// /// The volatile parameter parameter is set to `true`, so it will not be optimized out. pub fn volatile_copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T, count: usize); /// Equivalent to the appropriate `llvm.memmove.p0i8.0i8.*` intrinsic, with /// a size of `count` * `size_of::<T>()` and an alignment of /// `min_align_of::<T>()` /// /// The volatile parameter parameter is set to `true`, so it will not be optimized out. pub fn volatile_copy_memory<T>(dst: *mut T, src: *const T, count: usize); /// Equivalent to the appropriate `llvm.memset.p0i8.*` intrinsic, with a /// size of `count` * `size_of::<T>()` and an alignment of /// `min_align_of::<T>()`. /// /// The volatile parameter parameter is set to `true`, so it will not be optimized out. pub fn volatile_set_memory<T>(dst: *mut T, val: u8, count: usize); /// Perform a volatile load from the `src` pointer. pub fn volatile_load<T>(src: *const T) -> T; /// Perform a volatile store to the `dst` pointer. pub fn volatile_store<T>(dst: *mut T, val: T); /// Returns the square root of an `f32` pub fn sqrtf32(x: f32) -> f32; /// Returns the square root of an `f64` pub fn sqrtf64(x: f64) -> f64; /// Raises an `f32` to an integer power. pub fn powif32(a: f32, x: i32) -> f32; /// Raises an `f64` to an integer power. pub fn powif64(a: f64, x: i32) -> f64; /// Returns the sine of an `f32`. pub fn sinf32(x: f32) -> f32; /// Returns the sine of an `f64`. pub fn sinf64(x: f64) -> f64; /// Returns the cosine of an `f32`. pub fn cosf32(x: f32) -> f32; /// Returns the cosine of an `f64`. pub fn cosf64(x: f64) -> f64; /// Raises an `f32` to an `f32` power. pub fn powf32(a: f32, x: f32) -> f32; /// Raises an `f64` to an `f64` power. pub fn powf64(a: f64, x: f64) -> f64; /// Returns the exponential of an `f32`. pub fn expf32(x: f32) -> f32; /// Returns the exponential of an `f64`. pub fn expf64(x: f64) -> f64; /// Returns 2 raised to the power of an `f32`. pub fn exp2f32(x: f32) -> f32; /// Returns 2 raised to the power of an `f64`. pub fn exp2f64(x: f64) -> f64; /// Returns the natural logarithm of an `f32`. pub fn logf32(x: f32) -> f32; /// Returns the natural logarithm of an `f64`. pub fn logf64(x: f64) -> f64; /// Returns the base 10 logarithm of an `f32`. pub fn log10f32(x: f32) -> f32; /// Returns the base 10 logarithm of an `f64`. pub fn log10f64(x: f64) -> f64; /// Returns the base 2 logarithm of an `f32`. pub fn log2f32(x: f32) -> f32; /// Returns the base 2 logarithm of an `f64`. pub fn log2f64(x: f64) -> f64; /// Returns `a * b + c` for `f32` values. pub fn fmaf32(a: f32, b: f32, c: f32) -> f32; /// Returns `a * b + c` for `f64` values. pub fn fmaf64(a: f64, b: f64, c: f64) -> f64; /// Returns the absolute value of an `f32`. pub fn fabsf32(x: f32) -> f32; /// Returns the absolute value of an `f64`. pub fn fabsf64(x: f64) -> f64; /// Copies the sign from `y` to `x` for `f32` values. pub fn copysignf32(x: f32, y: f32) -> f32; /// Copies the sign from `y` to `x` for `f64` values. pub fn copysignf64(x: f64, y: f64) -> f64; /// Returns the largest integer less than or equal to an `f32`. pub fn floorf32(x: f32) -> f32; /// Returns the largest integer less than or equal to an `f64`. pub fn floorf64(x: f64) -> f64; /// Returns the smallest integer greater than or equal to an `f32`. pub fn ceilf32(x: f32) -> f32; /// Returns the smallest integer greater than or equal to an `f64`. pub fn ceilf64(x: f64) -> f64; /// Returns the integer part of an `f32`. pub fn truncf32(x: f32) -> f32; /// Returns the integer part of an `f64`. pub fn truncf64(x: f64) -> f64; /// Returns the nearest integer to an `f32`. May raise an inexact floating-point exception /// if the argument is not an integer. pub fn rintf32(x: f32) -> f32; /// Returns the nearest integer to an `f64`. May raise an inexact floating-point exception /// if the argument is not an integer. pub fn rintf64(x: f64) -> f64; /// Returns the nearest integer to an `f32`. pub fn nearbyintf32(x: f32) -> f32; /// Returns the nearest integer to an `f64`. pub fn nearbyintf64(x: f64) -> f64; /// Returns the nearest integer to an `f32`. Rounds half-way cases away from zero. pub fn roundf32(x: f32) -> f32; /// Returns the nearest integer to an `f64`. Rounds half-way cases away from zero. pub fn roundf64(x: f64) -> f64; /// Returns the number of bits set in a `u8`. pub fn ctpop8(x: u8) -> u8; /// Returns the number of bits set in a `u16`. pub fn ctpop16(x: u16) -> u16; /// Returns the number of bits set in a `u32`. pub fn ctpop32(x: u32) -> u32; /// Returns the number of bits set in a `u64`. pub fn ctpop64(x: u64) -> u64; /// Returns the number of leading bits unset in a `u8`. pub fn ctlz8(x: u8) -> u8; /// Returns the number of leading bits unset in a `u16`. pub fn ctlz16(x: u16) -> u16; /// Returns the number of leading bits unset in a `u32`. pub fn ctlz32(x: u32) -> u32; /// Returns the number of leading bits unset in a `u64`. pub fn ctlz64(x: u64) -> u64; /// Returns the number of trailing bits unset in a `u8`. pub fn cttz8(x: u8) -> u8; /// Returns the number of trailing bits unset in a `u16`. pub fn cttz16(x: u16) -> u16; /// Returns the number of trailing bits unset in a `u32`. pub fn cttz32(x: u32) -> u32; /// Returns the number of trailing bits unset in a `u64`. pub fn cttz64(x: u64) -> u64; /// Reverses the bytes in a `u16`. pub fn bswap16(x: u16) -> u16; /// Reverses the bytes in a `u32`. pub fn bswap32(x: u32) -> u32; /// Reverses the bytes in a `u64`. pub fn bswap64(x: u64) -> u64; /// Performs checked `i8` addition. pub fn i8_add_with_overflow(x: i8, y: i8) -> (i8, bool); /// Performs checked `i16` addition. pub fn i16_add_with_overflow(x: i16, y: i16) -> (i16, bool); /// Performs checked `i32` addition. pub fn i32_add_with_overflow(x: i32, y: i32) -> (i32, bool); /// Performs checked `i64` addition. pub fn i64_add_with_overflow(x: i64, y: i64) -> (i64, bool); /// Performs checked `u8` addition. pub fn u8_add_with_overflow(x: u8, y: u8) -> (u8, bool); /// Performs checked `u16` addition. pub fn u16_add_with_overflow(x: u16, y: u16) -> (u16, bool); /// Performs checked `u32` addition. pub fn u32_add_with_overflow(x: u32, y: u32) -> (u32, bool); /// Performs checked `u64` addition. pub fn u64_add_with_overflow(x: u64, y: u64) -> (u64, bool); /// Performs checked `i8` subtraction. pub fn i8_sub_with_overflow(x: i8, y: i8) -> (i8, bool); /// Performs checked `i16` subtraction. pub fn i16_sub_with_overflow(x: i16, y: i16) -> (i16, bool); /// Performs checked `i32` subtraction. pub fn i32_sub_with_overflow(x: i32, y: i32) -> (i32, bool); /// Performs checked `i64` subtraction. pub fn i64_sub_with_overflow(x: i64, y: i64) -> (i64, bool); /// Performs checked `u8` subtraction. pub fn u8_sub_with_overflow(x: u8, y: u8) -> (u8, bool); /// Performs checked `u16` subtraction. pub fn u16_sub_with_overflow(x: u16, y: u16) -> (u16, bool); /// Performs checked `u32` subtraction. pub fn u32_sub_with_overflow(x: u32, y: u32) -> (u32, bool); /// Performs checked `u64` subtraction. pub fn u64_sub_with_overflow(x: u64, y: u64) -> (u64, bool); /// Performs checked `i8` multiplication. pub fn i8_mul_with_overflow(x: i8, y: i8) -> (i8, bool); /// Performs checked `i16` multiplication. pub fn i16_mul_with_overflow(x: i16, y: i16) -> (i16, bool); /// Performs checked `i32` multiplication. pub fn i32_mul_with_overflow(x: i32, y: i32) -> (i32, bool); /// Performs checked `i64` multiplication. pub fn i64_mul_with_overflow(x: i64, y: i64) -> (i64, bool); /// Performs checked `u8` multiplication. pub fn u8_mul_with_overflow(x: u8, y: u8) -> (u8, bool); /// Performs checked `u16` multiplication. pub fn u16_mul_with_overflow(x: u16, y: u16) -> (u16, bool); /// Performs checked `u32` multiplication. pub fn u32_mul_with_overflow(x: u32, y: u32) -> (u32, bool); /// Performs checked `u64` multiplication. pub fn u64_mul_with_overflow(x: u64, y: u64) -> (u64, bool); /// Returns (a + b) mod 2^N, where N is the width of N in bits. pub fn overflowing_add<T>(a: T, b: T) -> T; /// Returns (a - b) mod 2^N, where N is the width of N in bits. pub fn overflowing_sub<T>(a: T, b: T) -> T; /// Returns (a * b) mod 2^N, where N is the width of N in bits. pub fn overflowing_mul<T>(a: T, b: T) -> T; /// Returns the value of the discriminant for the variant in 'v', /// cast to a `u64`; if `T` has no discriminant, returns 0. pub fn discriminant_value<T>(v: &T) -> u64; } #[cfg(not(stage0))] extern "rust-intrinsic" { /// Performs an unchecked signed division, which results in undefined behavior, /// in cases where y == 0, or x == int::MIN and y == -1 pub fn unchecked_sdiv<T>(x: T, y: T) -> T; /// Performs an unchecked unsigned division, which results in undefined behavior, /// in cases where y == 0 pub fn unchecked_udiv<T>(x: T, y: T) -> T; /// Returns the remainder of an unchecked signed division, which results in /// undefined behavior, in cases where y == 0, or x == int::MIN and y == -1 pub fn unchecked_urem<T>(x: T, y: T) -> T; /// Returns the remainder of an unchecked signed division, which results in /// undefined behavior, in cases where y == 0 pub fn unchecked_srem<T>(x: T, y: T) -> T; }
41.053156
94
0.611597
f749bf33c60583a136c7bd8ec1bc692f50218b38
1,425
use dynasm::dynasm; use dynasmrt::{DynasmApi, DynasmLabelApi}; use std::io::{stdout, Write}; // unsafe extern "sysv64" fn print(buf: *const u8, len: u64) -> u8 { // let buf = std::slice::from_raw_parts(buf, len as usize); // stdout().write_all(buf).is_err() as u8 // } // 避免 panic unsafe extern "sysv64" fn print(buf: *const u8, len: u64) -> u8 { let ret = std::panic::catch_unwind(|| { let buf = std::slice::from_raw_parts(buf, len as usize); stdout().write_all(buf).is_err() }); match ret { Ok(false) => 0, Ok(true) => 1, Err(_) => 2, } } fn main() { let mut ops = dynasmrt::x64::Assembler::new().unwrap(); let s = b"Hello, JIT\n"; dynasm!(ops ; .arch x64 ; ->hello: // 字符串label名为 hello ; .bytes s ); let oft = ops.offset(); // 字符串地址偏移 dynasm!(ops ; lea rdi, [->hello] // 将字符串地址存储在 rdi 中 ; mov rsi, QWORD s.len() as _ // 将字符串长度存储在 rsi 中 ; mov rax, QWORD print as _ // 将 print 函数地址放入 rax ; call rax // 调用函数 ; ret // 返回 ); let asm = ops.finalize().unwrap(); let hello_fn: unsafe extern "sysv64" fn() -> u8 = unsafe { // 得到调用函数的汇编便宜地址,并将其作为函数地址返回 std::mem::transmute(asm.ptr(oft)) }; let ret = unsafe { hello_fn() }; assert_eq!(ret, 0); }
26.388889
68
0.510877
dd61225a79217408f4adfce91c31b4aeb8bc83a6
16,669
use crate::{ drawable::Pixel, geometry::{Point, Size}, image::{ImageDimensions, IntoPixelIter}, pixelcolor::{ raw::{BigEndian, ByteOrder, LittleEndian, RawData, RawDataIter}, PixelColor, }, }; use core::marker::PhantomData; /// Image with little endian data. pub type ImageRawLE<'a, C> = ImageRaw<'a, C, LittleEndian>; /// Image with big endian data. pub type ImageRawBE<'a, C> = ImageRaw<'a, C, BigEndian>; /// An image constructed from a slice of raw pixel data. /// /// The `ImageRaw` struct can be used to construct an image from a slice /// of raw image data. The storage format is determined by the [`PixelColor`] /// type `C` and the [`ByteOrder`] `BO`. The byteorder doesn't need to be /// specified for colors which aren't stored in multiple bytes. /// /// For color types with less than 8 bits per pixels the start of each row is /// aligned to the next whole byte. /// /// Details about the conversion of raw data to color types are explained in the /// [`raw` module documentation]. /// /// As `ImageRaw` does not implement [`Drawable`], it cannot be directly drawn to a supported /// display. The [`Image`] struct should be used to wrap an `ImageRaw` to make it drawable. /// /// # Examples /// /// ## Draw a 1BPP image /// /// This example creates an image from 1 bit per pixel data. /// /// ``` /// use embedded_graphics::{ /// image::{Image, ImageRaw}, /// pixelcolor::BinaryColor, /// prelude::*, /// }; /// # use embedded_graphics::mock_display::MockDisplay as Display; /// /// /// Image data with 12 x 5 pixels. /// /// The data for each row is 12 bits long and is padded with zeros on the /// /// end because each row needs to contain a whole number of bytes. /// #[rustfmt::skip] /// const DATA: &[u8] = &[ /// 0b11101111, 0b0101_0000, /// 0b10001000, 0b0101_0000, /// 0b11101011, 0b0101_0000, /// 0b10001001, 0b0101_0000, /// 0b11101111, 0b0101_0000, /// ]; /// /// // The type annotation `ImageRaw<BinaryColor>` is used to specify the format /// // of the stored raw data (`PixelColor::Raw`) and which color type the /// // raw data gets converted into. /// let raw_image: ImageRaw<BinaryColor> = ImageRaw::new(DATA, 12, 5); /// /// let image: Image<_, BinaryColor> = Image::new(&raw_image, Point::zero()); /// /// let mut display = Display::default(); /// /// image.draw(&mut display)?; /// # Ok::<(), core::convert::Infallible>(()) /// ``` /// /// ## Draw an image that uses multibyte pixel encoding /// /// Colors with more than one byte per pixel need an additional type annotation for the byte order. /// For convenience, the [`ImageRawBE`] and [`ImageRawLE`] type aliases can be used to abbreviate /// the type. /// /// ``` /// use embedded_graphics::{ /// image::{Image, ImageRaw, ImageRawBE, ImageRawLE}, /// pixelcolor::{ /// raw::{BigEndian, LittleEndian}, /// Rgb565, Rgb888, /// }, /// prelude::*, /// }; /// # const DATA: &[u8] = &[0x55; 8 * 8 * 3]; /// /// // Rgb888 image with 24 bits per pixel and big endian byte order /// let image1: ImageRawBE<Rgb888> = ImageRaw::new(DATA, 8, 8); /// // or: /// let image2: ImageRaw<Rgb888, BigEndian> = ImageRaw::new(DATA, 8, 8); /// # assert_eq!(image1, image2); /// /// // Rgb565 image with 16 bits per pixel and little endian byte order /// let image1: ImageRawLE<Rgb565> = ImageRaw::new(DATA, 16, 6); /// // or: /// let image2: ImageRaw<Rgb565, LittleEndian> = ImageRaw::new(DATA, 16, 6); /// # assert_eq!(image1, image2); /// ``` /// /// [`raw` module documentation]: ../pixelcolor/raw/index.html /// [`ImageRawBE`]: type.ImageRawBE.html /// [`ImageRawLE`]: type.ImageRawLE.html /// [`Image`]: struct.Image.html /// [`PixelColor`]: ../pixelcolor/trait.PixelColor.html /// [`ByteOrder`]: ../pixelcolor/raw/trait.ByteOrder.html #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] pub struct ImageRaw<'a, C, BO = BigEndian> where C: PixelColor + From<<C as PixelColor>::Raw>, BO: ByteOrder, { /// Image data, packed as dictated by raw data type `C::Raw` data: &'a [u8], /// Image size in pixels size: Size, pixel_type: PhantomData<C>, byte_order: PhantomData<BO>, } impl<'a, C, BO> ImageRaw<'a, C, BO> where C: PixelColor + From<<C as PixelColor>::Raw>, BO: ByteOrder, { /// Creates a new image. /// /// # Panics /// /// If `data` doesn't have the correct length. pub fn new(data: &'a [u8], width: u32, height: u32) -> Self { let ret = Self { data, size: Size::new(width, height), pixel_type: PhantomData, byte_order: PhantomData, }; assert_eq!(data.len(), height as usize * ret.bytes_per_row()); ret } /// Returns the length of each row in bytes. fn bytes_per_row(&self) -> usize { (self.size.width as usize * C::Raw::BITS_PER_PIXEL + 7) / 8 } } impl<'a, 'b, C, BO> IntoPixelIter<C> for &'a ImageRaw<'b, C, BO> where C: PixelColor + From<<C as PixelColor>::Raw>, BO: ByteOrder, RawDataIter<'b, C::Raw, BO>: Iterator<Item = C::Raw>, { type PixelIterator = ImageRawIterator<'a, 'b, C, BO>; fn pixel_iter(self) -> Self::PixelIterator { self.into_iter() } } impl<C, BO> ImageDimensions for ImageRaw<'_, C, BO> where C: PixelColor + From<<C as PixelColor>::Raw>, BO: ByteOrder, { fn width(&self) -> u32 { self.size.width } fn height(&self) -> u32 { self.size.height } } impl<'a, 'b, C, BO> IntoIterator for &'a ImageRaw<'b, C, BO> where C: PixelColor + From<<C as PixelColor>::Raw>, BO: ByteOrder, RawDataIter<'b, C::Raw, BO>: Iterator<Item = C::Raw>, { type Item = Pixel<C>; type IntoIter = ImageRawIterator<'a, 'b, C, BO>; fn into_iter(self) -> Self::IntoIter { ImageRawIterator { data: RawDataIter::new(self.data), x: 0, y: 0, image: self, } } } #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] pub struct ImageRawIterator<'a, 'b, C, BO> where C: PixelColor + From<<C as PixelColor>::Raw>, BO: ByteOrder, { data: RawDataIter<'b, C::Raw, BO>, x: u32, y: u32, image: &'a ImageRaw<'b, C, BO>, } impl<'a, 'b, C, BO> Iterator for ImageRawIterator<'a, 'b, C, BO> where C: PixelColor + From<<C as PixelColor>::Raw>, BO: ByteOrder, RawDataIter<'b, C::Raw, BO>: Iterator<Item = C::Raw>, { type Item = Pixel<C>; fn next(&mut self) -> Option<Self::Item> { if self.y < self.image.size.height { let data = self.data.next()?; let point = Point::new(self.x as i32, self.y as i32); self.x += 1; if self.x >= self.image.size.width { self.data.align(); self.y += 1; self.x = 0; } Some(Pixel(point, data.into())) } else { None } } } #[cfg(test)] mod tests { use super::*; use crate::{ drawable::Pixel, geometry::Dimensions, image::Image, pixelcolor::{raw::RawU32, *}, primitives::Rectangle, transform::Transform, }; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)] struct TestColorU32(RawU32); impl PixelColor for TestColorU32 { type Raw = RawU32; } impl From<RawU32> for TestColorU32 { fn from(data: RawU32) -> Self { Self(data) } } fn assert_next<I, C>(iter: &mut I, x: i32, y: i32, color: C) where I: Iterator<Item = Pixel<C>>, C: PixelColor + core::fmt::Debug, { let p = Point::new(x, y); assert_eq!(iter.next(), Some(Pixel(p, color))); } #[test] fn negative_top_left() { let image: ImageRaw<BinaryColor> = ImageRaw::new(&[0xff, 0x00, 0xff, 0x00], 4, 4); let image = Image::new(&image, Point::zero()).translate(Point::new(-1, -1)); assert_eq!( image.bounding_box(), Rectangle::new(Point::new(-1, -1), Size::new(4, 4)) ); } #[test] fn dimensions() { let image: ImageRaw<BinaryColor> = ImageRaw::new(&[0xff, 0x00, 0xFF, 0x00], 4, 4); let image = Image::new(&image, Point::zero()).translate(Point::new(100, 200)); assert_eq!( image.bounding_box(), Rectangle::new(Point::new(100, 200), Size::new(4, 4)) ); } #[test] fn it_can_have_negative_offsets() { let image: ImageRaw<Gray8> = ImageRaw::new( &[0xff, 0x00, 0xbb, 0x00, 0xcc, 0x00, 0xee, 0x00, 0xaa], 3, 3, ); let image = Image::new(&image, Point::zero()).translate(Point::new(-1, -1)); let mut iter = image.into_iter(); assert_next(&mut iter, -1, -1, Gray8::WHITE); assert_next(&mut iter, 0, -1, Gray8::BLACK); assert_next(&mut iter, 1, -1, Gray8::new(0xbb)); assert_next(&mut iter, -1, 0, Gray8::BLACK); assert_next(&mut iter, 0, 0, Gray8::new(0xcc)); assert_next(&mut iter, 1, 0, Gray8::BLACK); assert_next(&mut iter, -1, 1, Gray8::new(0xee)); assert_next(&mut iter, 0, 1, Gray8::BLACK); assert_next(&mut iter, 1, 1, Gray8::new(0xaa)); assert!(iter.next().is_none()); } #[test] fn bpp1() { let data = [0xAA, 0x00, 0x55, 0xFF, 0xAA, 0x00]; let image: ImageRaw<BinaryColor> = ImageRaw::new(&data, 9, 3); let mut iter = image.into_iter(); assert_next(&mut iter, 0, 0, BinaryColor::On); assert_next(&mut iter, 1, 0, BinaryColor::Off); assert_next(&mut iter, 2, 0, BinaryColor::On); assert_next(&mut iter, 3, 0, BinaryColor::Off); assert_next(&mut iter, 4, 0, BinaryColor::On); assert_next(&mut iter, 5, 0, BinaryColor::Off); assert_next(&mut iter, 6, 0, BinaryColor::On); assert_next(&mut iter, 7, 0, BinaryColor::Off); assert_next(&mut iter, 8, 0, BinaryColor::Off); assert_next(&mut iter, 0, 1, BinaryColor::Off); assert_next(&mut iter, 1, 1, BinaryColor::On); assert_next(&mut iter, 2, 1, BinaryColor::Off); assert_next(&mut iter, 3, 1, BinaryColor::On); assert_next(&mut iter, 4, 1, BinaryColor::Off); assert_next(&mut iter, 5, 1, BinaryColor::On); assert_next(&mut iter, 6, 1, BinaryColor::Off); assert_next(&mut iter, 7, 1, BinaryColor::On); assert_next(&mut iter, 8, 1, BinaryColor::On); assert_next(&mut iter, 0, 2, BinaryColor::On); assert_next(&mut iter, 1, 2, BinaryColor::Off); assert_next(&mut iter, 2, 2, BinaryColor::On); assert_next(&mut iter, 3, 2, BinaryColor::Off); assert_next(&mut iter, 4, 2, BinaryColor::On); assert_next(&mut iter, 5, 2, BinaryColor::Off); assert_next(&mut iter, 6, 2, BinaryColor::On); assert_next(&mut iter, 7, 2, BinaryColor::Off); assert_next(&mut iter, 8, 2, BinaryColor::Off); assert!(iter.next().is_none()); } #[test] fn bpp2() { let data = [0b00011011, 0x0, 0b11100100, 0xFF]; let image: ImageRaw<Gray2> = ImageRaw::new(&data, 5, 2); let mut iter = image.into_iter(); assert_next(&mut iter, 0, 0, Gray2::new(0)); assert_next(&mut iter, 1, 0, Gray2::new(1)); assert_next(&mut iter, 2, 0, Gray2::new(2)); assert_next(&mut iter, 3, 0, Gray2::new(3)); assert_next(&mut iter, 4, 0, Gray2::new(0)); assert_next(&mut iter, 0, 1, Gray2::new(3)); assert_next(&mut iter, 1, 1, Gray2::new(2)); assert_next(&mut iter, 2, 1, Gray2::new(1)); assert_next(&mut iter, 3, 1, Gray2::new(0)); assert_next(&mut iter, 4, 1, Gray2::new(3)); assert!(iter.next().is_none()); } #[test] fn bpp4() { let data = [0b00011000, 0b11110000, 0b01011010, 0x0]; let image: ImageRaw<Gray4> = ImageRaw::new(&data, 3, 2); let mut iter = image.into_iter(); assert_next(&mut iter, 0, 0, Gray4::new(0x1)); assert_next(&mut iter, 1, 0, Gray4::new(0x8)); assert_next(&mut iter, 2, 0, Gray4::new(0xF)); assert_next(&mut iter, 0, 1, Gray4::new(0x5)); assert_next(&mut iter, 1, 1, Gray4::new(0xA)); assert_next(&mut iter, 2, 1, Gray4::new(0x0)); assert!(iter.next().is_none()); } #[test] fn bpp8() { let data = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06]; let image: ImageRaw<Gray8> = ImageRaw::new(&data, 2, 3); let mut iter = image.into_iter(); assert_next(&mut iter, 0, 0, Gray8::new(1)); assert_next(&mut iter, 1, 0, Gray8::new(2)); assert_next(&mut iter, 0, 1, Gray8::new(3)); assert_next(&mut iter, 1, 1, Gray8::new(4)); assert_next(&mut iter, 0, 2, Gray8::new(5)); assert_next(&mut iter, 1, 2, Gray8::new(6)); assert!(iter.next().is_none()); } #[test] fn bpp16_little_endian() { let data = [0x00, 0xF8, 0xE0, 0x07, 0x1F, 0x00, 0x00, 0x00]; let image: ImageRawLE<Rgb565> = ImageRaw::new(&data, 1, 4); let mut iter = image.into_iter(); assert_next(&mut iter, 0, 0, Rgb565::RED); assert_next(&mut iter, 0, 1, Rgb565::GREEN); assert_next(&mut iter, 0, 2, Rgb565::BLUE); assert_next(&mut iter, 0, 3, Rgb565::BLACK); assert!(iter.next().is_none()); } #[test] fn bpp16_big_endian() { let data = [0xF8, 0x00, 0x07, 0xE0, 0x00, 0x1F, 0x00, 0x00]; let image: ImageRawBE<Rgb565> = ImageRaw::new(&data, 2, 2); let mut iter = image.into_iter(); assert_next(&mut iter, 0, 0, Rgb565::RED); assert_next(&mut iter, 1, 0, Rgb565::GREEN); assert_next(&mut iter, 0, 1, Rgb565::BLUE); assert_next(&mut iter, 1, 1, Rgb565::BLACK); assert!(iter.next().is_none()); } #[test] fn bpp24_little_endian() { let data = [ 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, ]; let image: ImageRawLE<Bgr888> = ImageRaw::new(&data, 1, 4); let mut iter = image.into_iter(); assert_next(&mut iter, 0, 0, Bgr888::RED); assert_next(&mut iter, 0, 1, Bgr888::GREEN); assert_next(&mut iter, 0, 2, Bgr888::BLUE); assert_next(&mut iter, 0, 3, Bgr888::BLACK); assert!(iter.next().is_none()); } #[test] fn bpp24_big_endian() { let data = [ 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, ]; let image: ImageRawBE<Rgb888> = ImageRaw::new(&data, 4, 1); let mut iter = image.into_iter(); assert_next(&mut iter, 0, 0, Rgb888::RED); assert_next(&mut iter, 1, 0, Rgb888::GREEN); assert_next(&mut iter, 2, 0, Rgb888::BLUE); assert_next(&mut iter, 3, 0, Rgb888::BLACK); assert!(iter.next().is_none()); } #[test] fn bpp32_little_endian() { #[rustfmt::skip] let data = [ 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, ]; let image: ImageRawLE<TestColorU32> = ImageRaw::new(&data, 2, 2); let mut iter = image.into_iter(); assert_next(&mut iter, 0, 0, TestColorU32(RawU32::new(0x78563412))); assert_next(&mut iter, 1, 0, TestColorU32(RawU32::new(0xF0DEBC9A))); assert_next(&mut iter, 0, 1, TestColorU32(RawU32::new(0x00000000))); assert_next(&mut iter, 1, 1, TestColorU32(RawU32::new(0xFFFFFFFF))); assert!(iter.next().is_none()); } #[test] fn bpp32_big_endian() { #[rustfmt::skip] let data = [ 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, ]; let image: ImageRawBE<TestColorU32> = ImageRaw::new(&data, 4, 1); let mut iter = image.into_iter(); assert_next(&mut iter, 0, 0, TestColorU32(RawU32::new(0x12345678))); assert_next(&mut iter, 1, 0, TestColorU32(RawU32::new(0x9ABCDEF0))); assert_next(&mut iter, 2, 0, TestColorU32(RawU32::new(0x00000000))); assert_next(&mut iter, 3, 0, TestColorU32(RawU32::new(0xFFFFFFFF))); assert!(iter.next().is_none()); } #[test] #[should_panic] fn panics_if_length_of_data_is_too_short() { let data = [0u8; 3]; let _: ImageRaw<BinaryColor> = ImageRaw::new(&data, 12, 2); } }
31.629981
99
0.5722
0af92d7fc37c950cf5ff8ed8ba9ba8983354c991
6,491
use std::io::{ self, Write }; use std::mem; use std::fmt::Debug; #[derive(Debug)] pub struct StartupMessage<'a, 'b> { pub user: &'a str, pub database: &'b str, } #[derive(Debug)] pub struct PasswordMessage<'a> { pub password: &'a str, } #[derive(Debug)] pub struct QueryMessage<'a> { pub query: &'a str, } #[derive(Debug)] pub struct ParseMessage<'a, 'b> { pub stmt_name: &'a str, pub stmt_body: &'b str, } #[derive(Debug)] pub struct BindMessage<'a, 'b, 'c> { pub portal_name: &'a str, pub stmt_name: &'b str, pub params: &'c[Option<&'c str>], } #[derive(Debug)] pub struct ExecuteMessage<'a> { pub portal_name: &'a str, pub row_limit: u32, } #[derive(Debug)] pub struct DescribeStatementMessage<'a> { pub stmt_name: &'a str, } #[derive(Debug)] pub struct CloseStatementMessage<'a> { pub stmt_name: &'a str, } #[derive(Debug)] pub struct TerminateMessage; #[derive(Debug)] pub struct FlushMessage; #[derive(Debug)] pub struct SyncMessage; pub fn write_message<W: Write, M: FrontendMessage>( out: &mut W, msg: M) -> io::Result<()> { println!("<- {:#?}", &msg); let payload_len = { struct CountWriter { count: usize } impl Write for CountWriter { fn flush(&mut self) -> io::Result<()> { Ok(()) } fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let buflen = buf.len(); self.count += buflen; Ok(buflen) } } let mut count_writer = CountWriter { count: 0 }; msg.write_payload(&mut count_writer).unwrap(); count_writer.count }; let msg_len = payload_len + mem::size_of::<i32>(); if let Some(ident) = msg.ident() { try!(out.write_u8(ident)); } out.write_i32_be(msg_len as i32) .and_then(|_| (msg.write_payload(out))) .and_then(|_| (out.flush())) } pub trait FrontendMessage: Debug { fn ident(&self) -> Option<u8> { None } fn write_payload<W: Write>(&self, out: &mut W) -> io::Result<()> { Ok(()) } } impl FrontendMessage for TerminateMessage { fn ident(&self) -> Option<u8> { Some(b'X') } } impl FrontendMessage for FlushMessage { fn ident(&self) -> Option<u8> { Some(b'H') } } impl FrontendMessage for SyncMessage { fn ident(&self) -> Option<u8> { Some(b'S') } } impl<'a, 'b> FrontendMessage for StartupMessage<'a, 'b> { fn write_payload<W: Write>(&self, out: &mut W) -> io::Result<()> { out.write_i32_be(0x0003_0000) .and_then(|_| (out.write_cstr("user"))) .and_then(|_| (out.write_cstr(self.user))) .and_then(|_| (out.write_cstr("database"))) .and_then(|_| (out.write_cstr(self.database))) .and_then(|_| (out.write_u8(0))) } } impl<'a> FrontendMessage for PasswordMessage<'a> { fn ident(&self) -> Option<u8> { Some(b'p') } fn write_payload<W: Write>(&self, out: &mut W) -> io::Result<()> { out.write_cstr(self.password) } } impl<'a> FrontendMessage for QueryMessage<'a> { fn ident(&self) -> Option<u8> { Some(b'Q') } fn write_payload<W: Write>(&self, out: &mut W) -> io::Result<()> { out.write_cstr(self.query) } } impl<'a, 'b> FrontendMessage for ParseMessage<'a, 'b> { fn ident(&self) -> Option<u8> { Some(b'P') } fn write_payload<W: Write>(&self, out: &mut W) -> io::Result<()> { out.write_cstr(self.stmt_name) .and_then(|_| (out.write_cstr(self.stmt_body))) .and_then(|_| (out.write_i16_be(0))) } } impl<'a> FrontendMessage for DescribeStatementMessage<'a> { fn ident(&self) -> Option<u8> { Some(b'D') } fn write_payload<W: Write>(&self, out: &mut W) -> io::Result<()> { out.write_u8(b'S') .and_then(|_| (out.write_cstr(self.stmt_name))) } } impl<'a, 'b, 'c> FrontendMessage for BindMessage<'a, 'b, 'c> { fn ident(&self) -> Option<u8> { Some(b'B') } fn write_payload<W: Write>(&self, out: &mut W) -> io::Result<()> { out.write_cstr(self.portal_name) .and_then(|_| (out.write_cstr(self.stmt_name))) .and_then(|_| (out.write_i16_be(0))) .and_then(|_| (out.write_i16_be(self.params.len() as i16))) .and_then(|_| { for param in self.params { try!(match *param { None => out.write_i32_be(-1), Some(val) => out.write_i32_be(val.len() as i32) .and_then(|_| (out.write_all(val.as_bytes()))), }) } Ok(()) }) .and_then(|_| (out.write_i16_be(0))) } } impl<'a> FrontendMessage for ExecuteMessage<'a> { fn ident(&self) -> Option<u8> { Some(b'E') } fn write_payload<W: Write>(&self, out: &mut W) -> io::Result<()> { out.write_cstr(self.portal_name) .and_then(|_| (out.write_u32_be(self.row_limit))) } } impl<'a> FrontendMessage for CloseStatementMessage<'a> { fn ident(&self) -> Option<u8> { Some(b'C') } fn write_payload<W: Write>(&self, out: &mut W) -> io::Result<()> { out.write_u8(b'S') .and_then(|_| (out.write_cstr(self.stmt_name))) } } trait WriteExt { fn write_i32_be(&mut self, i32) -> io::Result<()>; fn write_u32_be(&mut self, u32) -> io::Result<()>; fn write_i16_be(&mut self, i16) -> io::Result<()>; fn write_u8(&mut self, u8) -> io::Result<()>; fn write_cstr(&mut self, &str) -> io::Result<()>; } impl<W: Write> WriteExt for W { fn write_i32_be(&mut self, value: i32) -> io::Result<()> { self.write_all(& unsafe { mem::transmute::<_, [u8; 4]>(value.to_be()) }) } fn write_u32_be(&mut self, value: u32) -> io::Result<()> { self.write_all(& unsafe { mem::transmute::<_, [u8; 4]>(value.to_be()) }) } fn write_i16_be(&mut self, value: i16) -> io::Result<()> { self.write_all(& unsafe { mem::transmute::<_, [u8; 2]>(value.to_be()) }) } fn write_u8(&mut self, value: u8) -> io::Result<()> { self.write_all(&[value]) } fn write_cstr(&mut self, s: &str) -> io::Result<()> { self.write_all(s.as_bytes()) .and_then(|_| (self.write_all(&[0]))) } } #[cfg(test)] mod test { use super::WriteExt; #[test] fn write_cstr() { let mut buf = vec![]; buf.write_cstr("some awesome").unwrap(); assert_eq!(&buf, b"some awesome\0"); } }
27.858369
80
0.556155
69340c785b2e4a41677754ac6539de660318309f
3,654
#[doc(hidden)] pub extern crate futures; mod apc; mod unbounded; pub use apc::{Complete, Interface}; pub use apc::ApcError as Error; pub use apc::ApcResult as Result; pub use apc::ApcFuture as Future; pub use unbounded::*; #[macro_export] macro_rules! apc_interfaces { // TODO remove parenthesis-workaround in `where ()` ($( $(#[$attrs:meta])* $(@[mod_attrs($($mod_attrs:meta),* $(,)*)])* $(@[call_attrs($($call_attrs:meta),* $(,)*)])* $(@[return_attrs($($return_attrs:meta),* $(,)*)])* $(@[data_attrs($($data_attrs:meta),* $(,)*)])* $(@[backend_attrs($($backend_attrs:meta),* $(,)*)])* intf $mod:ident :: $intf:ident $(<$($ty_params:ident),+>)* $(where ($($ty_bounds:tt)+))* {$( $(#[$m_attrs:meta])* $(@[call_attrs($($m_call_attrs:meta),* $(,)*)])* $(@[return_attrs($($m_return_attrs:meta),* $(,)*)])* $(@[data_attrs($($m_data_attrs:meta),* $(,)*)])* $(@[backend_attrs($($m_backend_attrs:meta),* $(,)*)])* fn $method:ident($($args:ident : $args_ty:ty),* $(,)*) $(-> $ret_ty:ty)*; )*} )*) => {$( $($(#[$mod_attrs])*)* pub mod $mod { $($(#[$call_attrs])*)* $($(#[$data_attrs])*)* #[allow(non_camel_case_types)] pub enum Call {$( $($(#[$m_call_attrs])*)* $($(#[$m_data_attrs])*)* $method{$( $args : $args_ty ),*} ),*} impl Call { pub fn apply(self, __backend: &mut Backend) -> Return { match self {$( Call::$method{ $($args),* } => Return::$method(__backend.$method($($args,)*)) ),*} } } $($(#[$return_attrs])*)* $($(#[$data_attrs])*)* #[allow(non_camel_case_types)] pub enum Return {$( $($(#[$m_return_attrs])*)* $($(#[$m_data_attrs])*)* $method(($($ret_ty)*)) ),*} $(#[$attrs])* pub trait $intf: $crate::Interface<Call = Call, Return = Return> {$( $(#[$m_attrs])* #[allow(unreachable_patterns)] fn $method(&self, $($args : $args_ty),*) -> $crate::ApcFuture<($($ret_ty)*)> { use $crate::futures::Future; Box::new($crate::Interface::start_call(self, Call::$method{$($args),*}) .map(|ret| match ret { Return::$method(r) => r, _ => unreachable!() })) } )*} impl<__T> $intf for __T where __T: $crate::Interface<Call = Call, Return = Return> + ?Sized {} $($(#[$backend_attrs])*)* pub trait Backend { $( $($(#[$m_backend_attrs])*)* fn $method(&mut self, $($args : $args_ty,)*) $(-> $ret_ty)*; )* } pub fn serve<S>(s: &mut S, backend: &mut Backend) -> $crate::futures::Poll<Option<()>, S::Error> where S: $crate::futures::Stream<Item = (Call, $crate::Complete<Return>)> { use $crate::futures::Stream; s.map(|(call, ret_tx)| { let _ = ret_tx.complete(call.apply(backend)); }).poll() } } //FIXME(rustc, look for issue...) remove workaround //pub use self::$mod::$intf; pub type $intf = self::$mod::$intf<Call = self::$mod::Call, Return = self::$mod::Return>; )*} }
36.909091
109
0.431308
d587c87c82cca3b8938356627ea6e8e379e85392
14,647
// Copyright 2019 The Grin Developers // 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. //! Common functions for wallet integration tests extern crate mwc_wallet; use grin_wallet_config as config; use grin_wallet_impls::test_framework::LocalWalletClient; use grin_wallet_util::grin_util as util; use clap::{App, ArgMatches}; use std::path::PathBuf; use std::sync::Arc; use std::{env, fs}; use util::{Mutex, ZeroingString}; use grin_wallet_api::{EncryptedRequest, EncryptedResponse, JsonId}; use grin_wallet_config::{GlobalWalletConfig, WalletConfig, GRIN_WALLET_DIR}; use grin_wallet_impls::{DefaultLCProvider, DefaultWalletImpl}; use grin_wallet_libwallet::{NodeClient, WalletInfo, WalletInst}; use grin_wallet_util::grin_core::global::{self, ChainTypes}; use grin_wallet_util::grin_keychain::ExtKeychain; use grin_wallet_util::grin_util::{from_hex, static_secp_instance}; use util::secp::key::{PublicKey, SecretKey}; use grin_wallet_util::grin_api as api; use mwc_wallet::cmd::wallet_args; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::thread; use std::time::Duration; use url::Url; // Set up 2 wallets and launch the test proxy behind them #[macro_export] macro_rules! setup_proxy { ($test_dir: expr, $chain: ident, $wallet1: ident, $client1: ident, $mask1: ident, $wallet2: ident, $client2: ident, $mask2: ident) => { // Create a new proxy to simulate server and wallet responses let mut wallet_proxy: WalletProxy< DefaultLCProvider<LocalWalletClient, ExtKeychain>, LocalWalletClient, ExtKeychain, > = WalletProxy::new($test_dir); let $chain = wallet_proxy.chain.clone(); // load app yaml. If it don't exist, just say so and exit let yml = load_yaml!("../src/bin/mwc-wallet.yml"); let app = App::from_yaml(yml); // wallet init let arg_vec = vec!["mwc-wallet", "-p", "password", "init", "-h"]; // should create new wallet file let $client1 = LocalWalletClient::new("wallet1", wallet_proxy.tx.clone()); let target = std::path::PathBuf::from(format!("{}/wallet1/mwc-wallet.toml", $test_dir)); println!("{:?}", target); if !target.exists() { execute_command(&app, $test_dir, "wallet1", &$client1, arg_vec.clone())?; } // add wallet to proxy let config1 = initial_setup_wallet($test_dir, "wallet1"); let wallet_config1 = config1.clone().members.unwrap().wallet; //config1.owner_api_listen_port = Some(13420); let ($wallet1, mask1_i) = instantiate_wallet( wallet_config1.clone(), $client1.clone(), "password", "default", )?; let $mask1 = (&mask1_i).as_ref(); wallet_proxy.add_wallet( "wallet1", $client1.get_send_instance(), $wallet1.clone(), mask1_i.clone(), ); // Create wallet 2, which will run a listener let $client2 = LocalWalletClient::new("wallet2", wallet_proxy.tx.clone()); let target = std::path::PathBuf::from(format!("{}/wallet2/mwc-wallet.toml", $test_dir)); if !target.exists() { execute_command(&app, $test_dir, "wallet2", &$client2, arg_vec.clone())?; } let config2 = initial_setup_wallet($test_dir, "wallet2"); let wallet_config2 = config2.clone().members.unwrap().wallet; //config2.api_listen_port = 23415; let ($wallet2, mask2_i) = instantiate_wallet( wallet_config2.clone(), $client2.clone(), "password", "default", )?; let $mask2 = (&mask2_i).as_ref(); wallet_proxy.add_wallet( "wallet2", $client2.get_send_instance(), $wallet2.clone(), mask2_i.clone(), ); // Set the wallet proxy listener running thread::spawn(move || { if let Err(e) = wallet_proxy.run() { error!("Wallet Proxy error: {}", e); } }); }; } #[allow(dead_code)] pub fn clean_output_dir(test_dir: &str) { let _ = fs::remove_dir_all(test_dir); } #[allow(dead_code)] pub fn setup(test_dir: &str) { util::init_test_logger(); clean_output_dir(test_dir); global::set_mining_mode(ChainTypes::AutomatedTesting); } /// Create a wallet config file in the given current directory pub fn config_command_wallet( dir_name: &str, wallet_name: &str, ) -> Result<(), grin_wallet_controller::Error> { let mut current_dir; let mut default_config = GlobalWalletConfig::default(); current_dir = env::current_dir().unwrap_or_else(|e| { panic!("Error creating config file: {}", e); }); current_dir.push(dir_name); current_dir.push(wallet_name); let _ = fs::create_dir_all(current_dir.clone()); let mut config_file_name = current_dir.clone(); config_file_name.push("mwc-wallet.toml"); if config_file_name.exists() { return Err(grin_wallet_controller::ErrorKind::ArgumentError( "mwc-wallet.toml already exists in the target directory. Please remove it first" .to_owned(), ))?; } default_config.update_paths(&current_dir, None); default_config .write_to_file(config_file_name.to_str().unwrap()) .unwrap_or_else(|e| { panic!("Error creating config file: {}", e); }); println!( "File {} configured and created", config_file_name.to_str().unwrap(), ); Ok(()) } /// Handles setup and detection of paths for wallet #[allow(dead_code)] pub fn initial_setup_wallet(dir_name: &str, wallet_name: &str) -> GlobalWalletConfig { let mut current_dir; current_dir = env::current_dir().unwrap_or_else(|e| { panic!("Error creating config file: {}", e); }); current_dir.push(dir_name); current_dir.push(wallet_name); let _ = fs::create_dir_all(current_dir.clone()); let mut config_file_name = current_dir.clone(); config_file_name.push("mwc-wallet.toml"); GlobalWalletConfig::new(config_file_name.to_str().unwrap()).unwrap() } fn get_wallet_subcommand<'a>( wallet_dir: &str, wallet_name: &str, args: ArgMatches<'a>, ) -> ArgMatches<'a> { match args.subcommand() { ("init", Some(init_args)) => { // wallet init command should spit out its config file then continue // (if desired) if init_args.is_present("here") { let _ = config_command_wallet(wallet_dir, wallet_name); } init_args.to_owned() } _ => ArgMatches::new(), } } // // Helper to create an instance of the LMDB wallet #[allow(dead_code)] pub fn instantiate_wallet( mut wallet_config: WalletConfig, node_client: LocalWalletClient, passphrase: &str, account: &str, ) -> Result< ( Arc< Mutex< Box< dyn WalletInst< 'static, DefaultLCProvider<'static, LocalWalletClient, ExtKeychain>, LocalWalletClient, ExtKeychain, >, >, >, >, Option<SecretKey>, ), grin_wallet_controller::Error, > { wallet_config.chain_type = None; let mut wallet = Box::new(DefaultWalletImpl::<LocalWalletClient>::new(node_client).unwrap()) as Box< dyn WalletInst< DefaultLCProvider<'static, LocalWalletClient, ExtKeychain>, LocalWalletClient, ExtKeychain, >, >; let lc = wallet.lc_provider().unwrap(); // legacy hack to avoid the need for changes in existing mwc-wallet.toml files // remove `wallet_data` from end of path as // new lifecycle provider assumes grin_wallet.toml is in root of data directory let mut top_level_wallet_dir = PathBuf::from(wallet_config.clone().data_file_dir); if top_level_wallet_dir.ends_with(GRIN_WALLET_DIR) { top_level_wallet_dir.pop(); wallet_config.data_file_dir = top_level_wallet_dir.to_str().unwrap().into(); } let _ = lc.set_top_level_directory(&wallet_config.data_file_dir); let keychain_mask = lc .open_wallet( None, ZeroingString::from(passphrase), true, false, wallet_config.wallet_data_dir.as_deref(), ) .unwrap(); let wallet_inst = lc.wallet_inst()?; wallet_inst.set_parent_key_id_by_name(account)?; Ok((Arc::new(Mutex::new(wallet)), keychain_mask)) } #[allow(dead_code)] pub fn execute_command( app: &App, test_dir: &str, wallet_name: &str, client: &LocalWalletClient, arg_vec: Vec<&str>, ) -> Result<String, grin_wallet_controller::Error> { let args = app.clone().get_matches_from(arg_vec); let _ = get_wallet_subcommand(test_dir, wallet_name, args.clone()); let config = initial_setup_wallet(test_dir, wallet_name); let mut wallet_config = config.clone().members.unwrap().wallet; let tor_config = config.clone().members.unwrap().tor; let mqs_config = config.clone().members.unwrap().mqs; //unset chain type so it doesn't get reset wallet_config.chain_type = None; wallet_args::wallet_command( &args, wallet_config.clone(), tor_config, mqs_config, client.clone(), true, |_| {}, ) } // as above, but without necessarily setting up the wallet #[allow(dead_code)] pub fn execute_command_no_setup<C, F>( app: &App, test_dir: &str, wallet_name: &str, client: &C, arg_vec: Vec<&str>, f: F, ) -> Result<String, grin_wallet_controller::Error> where C: NodeClient + 'static + Clone, F: FnOnce( Arc< Mutex< Box< dyn WalletInst< 'static, DefaultLCProvider<'static, C, ExtKeychain>, C, ExtKeychain, >, >, >, >, ), { let args = app.clone().get_matches_from(arg_vec); let _ = get_wallet_subcommand(test_dir, wallet_name, args.clone()); let config = config::initial_setup_wallet(&ChainTypes::AutomatedTesting, None, None, true).unwrap(); let mut wallet_config = config.clone().members.unwrap().wallet; wallet_config.chain_type = None; wallet_config.api_secret_path = None; wallet_config.node_api_secret_path = None; let tor_config = config.clone().members.unwrap().tor.clone(); let mqs_config = config.members.unwrap().mqs; wallet_args::wallet_command( &args, wallet_config, tor_config, mqs_config, client.clone(), true, f, ) } pub fn post<IN>(url: &Url, api_secret: Option<String>, input: &IN) -> Result<String, api::Error> where IN: Serialize, { // TODO: change create_post_request to accept a url instead of a &str let req = api::client::create_post_request(url.as_str(), api_secret, input)?; let res = api::client::send_request(req)?; Ok(res) } #[allow(dead_code)] pub fn send_request<OUT>( id: u64, dest: &str, req: &str, ) -> Result<Result<OUT, WalletAPIReturnError>, api::Error> where OUT: DeserializeOwned, { let url = Url::parse(dest).unwrap(); let req_val: Value = serde_json::from_str(req).unwrap(); let res = post(&url, None, &req_val).map_err(|e| { let err_string = format!("{}", e); println!("{}", err_string); thread::sleep(Duration::from_millis(200)); e })?; let res_val: Value = serde_json::from_str(&res).unwrap(); // encryption error, just return the string if res_val["error"] != json!(null) { return Ok(Err(WalletAPIReturnError { message: res_val["error"]["message"].as_str().unwrap().to_owned(), code: res_val["error"]["code"].as_i64().unwrap() as i32, })); } let res = serde_json::from_str(&res).unwrap(); let res = easy_jsonrpc::Response::from_json_response(res).unwrap(); let res = res.outputs.get(&id).unwrap().clone().unwrap(); if res["Err"] != json!(null) { Ok(Err(WalletAPIReturnError { message: res["Err"].as_str().unwrap().to_owned(), code: res["error"]["code"].as_i64().unwrap() as i32, })) } else { // deserialize result into expected type let value: OUT = serde_json::from_value(res["Ok"].clone()).unwrap(); Ok(Ok(value)) } } #[allow(dead_code)] pub fn send_request_enc<OUT>( sec_req_id: &JsonId, internal_request_id: u32, dest: &str, req: &str, shared_key: &SecretKey, ) -> Result<Result<OUT, WalletAPIReturnError>, api::Error> where OUT: DeserializeOwned, { let url = Url::parse(dest).unwrap(); let req_val: Value = serde_json::from_str(req).unwrap(); let req = EncryptedRequest::from_json(sec_req_id, &req_val, &shared_key).unwrap(); let res = post(&url, None, &req).map_err(|e| { let err_string = format!("{}", e); println!("{}", err_string); thread::sleep(Duration::from_millis(200)); e })?; let res_val: Value = serde_json::from_str(&res).unwrap(); //println!("RES_VAL: {}", res_val); // encryption error, just return the string if res_val["error"] != json!(null) { return Ok(Err(WalletAPIReturnError { message: res_val["error"]["message"].as_str().unwrap().to_owned(), code: res_val["error"]["code"].as_i64().unwrap() as i32, })); } let enc_resp: EncryptedResponse = serde_json::from_str(&res).unwrap(); let res = enc_resp.decrypt(shared_key).unwrap(); if res["error"] != json!(null) { return Ok(Err(WalletAPIReturnError { message: res["error"]["message"].as_str().unwrap().to_owned(), code: res["error"]["code"].as_i64().unwrap() as i32, })); } let res = easy_jsonrpc::Response::from_json_response(res).unwrap(); let res = res .outputs .get(&(internal_request_id as u64)) .unwrap() .clone() .unwrap(); //println!("RES: {}", res); if res["Err"] != json!(null) { Ok(Err(WalletAPIReturnError { message: res["Err"].as_str().unwrap().to_owned(), code: res_val["error"]["code"].as_i64().unwrap() as i32, })) } else { // deserialize result into expected type let raw_value = res["Ok"].clone(); let raw_value_str = serde_json::to_string_pretty(&raw_value).unwrap(); //println!("Raw value: {}", raw_value_str); let ok_val = serde_json::from_str(&raw_value_str); match ok_val { Ok(v) => { let value: OUT = v; Ok(Ok(value)) } Err(_) => { //println!("Error deserializing: {:?}", e); let value: OUT = serde_json::from_value(json!("Null")).unwrap(); Ok(Ok(value)) } } } } #[allow(dead_code)] pub fn derive_ecdh_key(sec_key_str: &str, other_pubkey: &PublicKey) -> SecretKey { let sec_key_bytes = from_hex(sec_key_str).unwrap(); let sec_key = { let secp_inst = static_secp_instance(); let secp = secp_inst.lock(); SecretKey::from_slice(&secp, &sec_key_bytes).unwrap() }; let secp_inst = static_secp_instance(); let secp = secp_inst.lock(); let mut shared_pubkey = other_pubkey.clone(); shared_pubkey.mul_assign(&secp, &sec_key).unwrap(); let x_coord = shared_pubkey.serialize_vec(&secp, true); SecretKey::from_slice(&secp, &x_coord[1..]).unwrap() } // Types to make working with json responses easier #[derive(Clone, Debug, Serialize, Deserialize)] pub struct WalletAPIReturnError { pub message: String, pub code: i32, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct RetrieveSummaryInfoResp(pub bool, pub WalletInfo);
29.830957
136
0.696798
488dae6d9be584a09511721e2990ab4bcf78f170
5,778
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Control Register"] pub cr: crate::Reg<cr::CR_SPEC>, #[doc = "0x04 - Configuration Register"] pub cfg: crate::Reg<cfg::CFG_SPEC>, #[doc = "0x08 - Status Register"] pub sr: crate::Reg<sr::SR_SPEC>, #[doc = "0x0c - Status Clear Register"] pub scr: crate::Reg<scr::SCR_SPEC>, #[doc = "0x10 - Resistive Touch Screen Register"] pub rts: crate::Reg<rts::RTS_SPEC>, #[doc = "0x14 - Sequencer Configuration Register"] pub seqcfg: crate::Reg<seqcfg::SEQCFG_SPEC>, _reserved_6_first_dma_word_cdma: [u8; 0x04], #[doc = "0x1c - Timing Configuration Register"] pub tim: crate::Reg<tim::TIM_SPEC>, #[doc = "0x20 - Internal Timer Register"] pub itimer: crate::Reg<itimer::ITIMER_SPEC>, #[doc = "0x24 - Window Monitor Configuration Register"] pub wcfg: crate::Reg<wcfg::WCFG_SPEC>, #[doc = "0x28 - Window Monitor Threshold Configuration Register"] pub wth: crate::Reg<wth::WTH_SPEC>, #[doc = "0x2c - Sequencer Last Converted Value Register"] pub lcv: crate::Reg<lcv::LCV_SPEC>, #[doc = "0x30 - Interrupt Enable Register"] pub ier: crate::Reg<ier::IER_SPEC>, #[doc = "0x34 - Interrupt Disable Register"] pub idr: crate::Reg<idr::IDR_SPEC>, #[doc = "0x38 - Interrupt Mask Register"] pub imr: crate::Reg<imr::IMR_SPEC>, #[doc = "0x3c - Calibration Register"] pub calib: crate::Reg<calib::CALIB_SPEC>, #[doc = "0x40 - Version Register"] pub version: crate::Reg<version::VERSION_SPEC>, #[doc = "0x44 - Parameter Register"] pub parameter: crate::Reg<parameter::PARAMETER_SPEC>, } impl RegisterBlock { #[doc = "0x18 - Configuration Direct Memory Access Register"] #[inline(always)] pub fn second_dma_word_cdma( &self, ) -> &crate::Reg<second_dma_word_cdma::SECOND_DMA_WORD_CDMA_SPEC> { unsafe { &*(((self as *const Self) as *const u8).add(24usize) as *const crate::Reg<second_dma_word_cdma::SECOND_DMA_WORD_CDMA_SPEC>) } } #[doc = "0x18 - Configuration Direct Memory Access Register"] #[inline(always)] pub fn first_dma_word_cdma( &self, ) -> &crate::Reg<first_dma_word_cdma::FIRST_DMA_WORD_CDMA_SPEC> { unsafe { &*(((self as *const Self) as *const u8).add(24usize) as *const crate::Reg<first_dma_word_cdma::FIRST_DMA_WORD_CDMA_SPEC>) } } } #[doc = "CALIB register accessor: an alias for `Reg<CALIB_SPEC>`"] pub type CALIB = crate::Reg<calib::CALIB_SPEC>; #[doc = "Calibration Register"] pub mod calib; #[doc = "FIRST_DMA_WORD_CDMA register accessor: an alias for `Reg<FIRST_DMA_WORD_CDMA_SPEC>`"] pub type FIRST_DMA_WORD_CDMA = crate::Reg<first_dma_word_cdma::FIRST_DMA_WORD_CDMA_SPEC>; #[doc = "Configuration Direct Memory Access Register"] pub mod first_dma_word_cdma; #[doc = "SECOND_DMA_WORD_CDMA register accessor: an alias for `Reg<SECOND_DMA_WORD_CDMA_SPEC>`"] pub type SECOND_DMA_WORD_CDMA = crate::Reg<second_dma_word_cdma::SECOND_DMA_WORD_CDMA_SPEC>; #[doc = "Configuration Direct Memory Access Register"] pub mod second_dma_word_cdma; #[doc = "CFG register accessor: an alias for `Reg<CFG_SPEC>`"] pub type CFG = crate::Reg<cfg::CFG_SPEC>; #[doc = "Configuration Register"] pub mod cfg; #[doc = "CR register accessor: an alias for `Reg<CR_SPEC>`"] pub type CR = crate::Reg<cr::CR_SPEC>; #[doc = "Control Register"] pub mod cr; #[doc = "IDR register accessor: an alias for `Reg<IDR_SPEC>`"] pub type IDR = crate::Reg<idr::IDR_SPEC>; #[doc = "Interrupt Disable Register"] pub mod idr; #[doc = "IER register accessor: an alias for `Reg<IER_SPEC>`"] pub type IER = crate::Reg<ier::IER_SPEC>; #[doc = "Interrupt Enable Register"] pub mod ier; #[doc = "IMR register accessor: an alias for `Reg<IMR_SPEC>`"] pub type IMR = crate::Reg<imr::IMR_SPEC>; #[doc = "Interrupt Mask Register"] pub mod imr; #[doc = "ITIMER register accessor: an alias for `Reg<ITIMER_SPEC>`"] pub type ITIMER = crate::Reg<itimer::ITIMER_SPEC>; #[doc = "Internal Timer Register"] pub mod itimer; #[doc = "LCV register accessor: an alias for `Reg<LCV_SPEC>`"] pub type LCV = crate::Reg<lcv::LCV_SPEC>; #[doc = "Sequencer Last Converted Value Register"] pub mod lcv; #[doc = "PARAMETER register accessor: an alias for `Reg<PARAMETER_SPEC>`"] pub type PARAMETER = crate::Reg<parameter::PARAMETER_SPEC>; #[doc = "Parameter Register"] pub mod parameter; #[doc = "RTS register accessor: an alias for `Reg<RTS_SPEC>`"] pub type RTS = crate::Reg<rts::RTS_SPEC>; #[doc = "Resistive Touch Screen Register"] pub mod rts; #[doc = "SCR register accessor: an alias for `Reg<SCR_SPEC>`"] pub type SCR = crate::Reg<scr::SCR_SPEC>; #[doc = "Status Clear Register"] pub mod scr; #[doc = "SEQCFG register accessor: an alias for `Reg<SEQCFG_SPEC>`"] pub type SEQCFG = crate::Reg<seqcfg::SEQCFG_SPEC>; #[doc = "Sequencer Configuration Register"] pub mod seqcfg; #[doc = "SR register accessor: an alias for `Reg<SR_SPEC>`"] pub type SR = crate::Reg<sr::SR_SPEC>; #[doc = "Status Register"] pub mod sr; #[doc = "TIM register accessor: an alias for `Reg<TIM_SPEC>`"] pub type TIM = crate::Reg<tim::TIM_SPEC>; #[doc = "Timing Configuration Register"] pub mod tim; #[doc = "VERSION register accessor: an alias for `Reg<VERSION_SPEC>`"] pub type VERSION = crate::Reg<version::VERSION_SPEC>; #[doc = "Version Register"] pub mod version; #[doc = "WCFG register accessor: an alias for `Reg<WCFG_SPEC>`"] pub type WCFG = crate::Reg<wcfg::WCFG_SPEC>; #[doc = "Window Monitor Configuration Register"] pub mod wcfg; #[doc = "WTH register accessor: an alias for `Reg<WTH_SPEC>`"] pub type WTH = crate::Reg<wth::WTH_SPEC>; #[doc = "Window Monitor Threshold Configuration Register"] pub mod wth;
41.869565
96
0.68432
878c8e7e5dac58b052b3c42f444056cc1bec33f9
7,923
#![allow(unused_imports, non_camel_case_types)] use crate::models::r4::Address::Address; use crate::models::r4::CodeableConcept::CodeableConcept; use crate::models::r4::ContactPoint::ContactPoint; use crate::models::r4::Extension::Extension; use crate::models::r4::HumanName::HumanName; use serde_json::json; use serde_json::value::Value; use std::borrow::Cow; /// A formally or informally recognized grouping of people or organizations formed /// for the purpose of achieving some form of collective action. Includes companies, /// institutions, corporations, departments, community groups, healthcare practice /// groups, payer/insurer, etc. #[derive(Debug)] pub struct Organization_Contact<'a> { pub(crate) value: Cow<'a, Value>, } impl Organization_Contact<'_> { pub fn new(value: &Value) -> Organization_Contact { Organization_Contact { value: Cow::Borrowed(value), } } pub fn to_json(&self) -> Value { (*self.value).clone() } /// Visiting or postal addresses for the contact. pub fn address(&self) -> Option<Address> { if let Some(val) = self.value.get("address") { return Some(Address { value: Cow::Borrowed(val), }); } return None; } /// May be used to represent additional information that is not part of the basic /// definition of the element. To make the use of extensions safe and manageable, /// there is a strict set of governance applied to the definition and use of /// extensions. Though any implementer can define an extension, there is a set of /// requirements that SHALL be met as part of the definition of the extension. pub fn extension(&self) -> Option<Vec<Extension>> { if let Some(Value::Array(val)) = self.value.get("extension") { return Some( val.into_iter() .map(|e| Extension { value: Cow::Borrowed(e), }) .collect::<Vec<_>>(), ); } return None; } /// Unique id for the element within a resource (for internal references). This may be /// any string value that does not contain spaces. pub fn id(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("id") { return Some(string); } return None; } /// May be used to represent additional information that is not part of the basic /// definition of the element and that modifies the understanding of the element /// in which it is contained and/or the understanding of the containing element's /// descendants. Usually modifier elements provide negation or qualification. To make /// the use of extensions safe and manageable, there is a strict set of governance /// applied to the definition and use of extensions. Though any implementer can define /// an extension, there is a set of requirements that SHALL be met as part of the /// definition of the extension. Applications processing a resource are required to /// check for modifier extensions. Modifier extensions SHALL NOT change the meaning /// of any elements on Resource or DomainResource (including cannot change the meaning /// of modifierExtension itself). pub fn modifier_extension(&self) -> Option<Vec<Extension>> { if let Some(Value::Array(val)) = self.value.get("modifierExtension") { return Some( val.into_iter() .map(|e| Extension { value: Cow::Borrowed(e), }) .collect::<Vec<_>>(), ); } return None; } /// A name associated with the contact. pub fn name(&self) -> Option<HumanName> { if let Some(val) = self.value.get("name") { return Some(HumanName { value: Cow::Borrowed(val), }); } return None; } /// Indicates a purpose for which the contact can be reached. pub fn purpose(&self) -> Option<CodeableConcept> { if let Some(val) = self.value.get("purpose") { return Some(CodeableConcept { value: Cow::Borrowed(val), }); } return None; } /// A contact detail (e.g. a telephone number or an email address) by which the party /// may be contacted. pub fn telecom(&self) -> Option<Vec<ContactPoint>> { if let Some(Value::Array(val)) = self.value.get("telecom") { return Some( val.into_iter() .map(|e| ContactPoint { value: Cow::Borrowed(e), }) .collect::<Vec<_>>(), ); } return None; } pub fn validate(&self) -> bool { if let Some(_val) = self.address() { if !_val.validate() { return false; } } if let Some(_val) = self.extension() { if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) { return false; } } if let Some(_val) = self.id() {} if let Some(_val) = self.modifier_extension() { if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) { return false; } } if let Some(_val) = self.name() { if !_val.validate() { return false; } } if let Some(_val) = self.purpose() { if !_val.validate() { return false; } } if let Some(_val) = self.telecom() { if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) { return false; } } return true; } } #[derive(Debug)] pub struct Organization_ContactBuilder { pub(crate) value: Value, } impl Organization_ContactBuilder { pub fn build(&self) -> Organization_Contact { Organization_Contact { value: Cow::Owned(self.value.clone()), } } pub fn with(existing: Organization_Contact) -> Organization_ContactBuilder { Organization_ContactBuilder { value: (*existing.value).clone(), } } pub fn new() -> Organization_ContactBuilder { let mut __value: Value = json!({}); return Organization_ContactBuilder { value: __value }; } pub fn address<'a>(&'a mut self, val: Address) -> &'a mut Organization_ContactBuilder { self.value["address"] = json!(val.value); return self; } pub fn extension<'a>(&'a mut self, val: Vec<Extension>) -> &'a mut Organization_ContactBuilder { self.value["extension"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; } pub fn id<'a>(&'a mut self, val: &str) -> &'a mut Organization_ContactBuilder { self.value["id"] = json!(val); return self; } pub fn modifier_extension<'a>( &'a mut self, val: Vec<Extension>, ) -> &'a mut Organization_ContactBuilder { self.value["modifierExtension"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; } pub fn name<'a>(&'a mut self, val: HumanName) -> &'a mut Organization_ContactBuilder { self.value["name"] = json!(val.value); return self; } pub fn purpose<'a>(&'a mut self, val: CodeableConcept) -> &'a mut Organization_ContactBuilder { self.value["purpose"] = json!(val.value); return self; } pub fn telecom<'a>( &'a mut self, val: Vec<ContactPoint>, ) -> &'a mut Organization_ContactBuilder { self.value["telecom"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; } }
34.447826
100
0.569103
f4f6127c389c53585a23a0df3c45af0922706fe4
3,958
use crate::{store::packed, FullName, PartialName}; use std::convert::TryInto; /// packed-refs specific functionality impl packed::Buffer { /// Find a reference with the given `name` and return it. pub fn find<'a, Name, E>(&self, name: Name) -> Result<Option<packed::Reference<'_>>, Error> where Name: TryInto<PartialName<'a>, Error = E>, Error: From<E>, { let name = name.try_into()?; match self.binary_search_by(name.0.try_into().expect("our full names are never invalid")) { Ok(line_start) => Ok(Some( packed::decode::reference::<()>(&self.as_ref()[line_start..]) .map_err(|_| Error::Parse)? .1, )), Err(parse_failure) => { if parse_failure { Err(Error::Parse) } else { Ok(None) } } } } /// Find a reference with the given `name` and return it. pub fn find_existing<'a, Name, E>(&self, name: Name) -> Result<packed::Reference<'_>, existing::Error> where Name: TryInto<PartialName<'a>, Error = E>, Error: From<E>, { match self.find(name) { Ok(Some(r)) => Ok(r), Ok(None) => Err(existing::Error::NotFound), Err(err) => Err(existing::Error::Find(err)), } } /// Perform a binary search where `Ok(pos)` is the beginning of the line that matches `name` perfectly and `Err(pos)` /// is the beginning of the line at which `name` could be inserted to still be in sort order. fn binary_search_by(&self, full_name: FullName<'_>) -> Result<usize, bool> { // TODO: remove the runtime constraint once we do lookup correctly let a = self.as_ref(); let search_start_of_record = |ofs: usize| { a[..ofs] .rfind(b"\n") .and_then(|pos| { let candidate = pos + 1; if a[candidate] == b'^' { a[..pos].rfind(b"\n").map(|pos| pos + 1) } else { Some(candidate) } }) .unwrap_or(0) }; let mut encountered_parse_failure = false; a.binary_search_by_key(&full_name.0.as_ref(), |b: &u8| { let ofs = b as *const u8 as usize - a.as_ptr() as usize; packed::decode::reference::<()>(&a[search_start_of_record(ofs)..]) .map(|(_rest, r)| r.full_name.as_ref()) .map_err(|err| { encountered_parse_failure = true; err }) .unwrap_or(&[]) }) .map(search_start_of_record) .map_err(|_| encountered_parse_failure) } } mod error { use quick_error::quick_error; quick_error! { /// The error returned by [`find()`][super::packed::Buffer::find()] #[derive(Debug)] #[allow(missing_docs)] pub enum Error { RefnameValidation(err: crate::name::Error) { display("The ref name or path is not a valid ref name") from() source(err) } Parse { display("The reference could not be parsed") } } } } use bstr::ByteSlice; pub use error::Error; /// pub mod existing { use quick_error::quick_error; quick_error! { /// The error returned by [`find_existing()`][super::packed::Buffer::find_existing()] #[derive(Debug)] #[allow(missing_docs)] pub enum Error { Find(err: super::Error) { display("The find operation failed") from() source(err) } NotFound { display("The reference did not exist even though that was expected") } } } }
33.82906
121
0.499495
48b81efb4092acb4ff96aea72078658a1ac212a4
28,033
pub const JPEG_COM: libc::c_int = 0xfe as libc::c_int; pub type J_BOOLEAN_PARAM = libc::c_uint; pub type J_FLOAT_PARAM = libc::c_uint; pub type J_INT_PARAM = libc::c_uint; pub const JBOOLEAN_OVERSHOOT_DERINGING: crate::jpeglib_h::J_BOOLEAN_PARAM = 1061927929; pub const JBOOLEAN_TRELLIS_Q_OPT: crate::jpeglib_h::J_BOOLEAN_PARAM = 3777684073; pub const JBOOLEAN_USE_SCANS_IN_TRELLIS: crate::jpeglib_h::J_BOOLEAN_PARAM = 4253291573; pub const JBOOLEAN_USE_LAMBDA_WEIGHT_TBL: crate::jpeglib_h::J_BOOLEAN_PARAM = 865973855; pub const JBOOLEAN_TRELLIS_EOB_OPT: crate::jpeglib_h::J_BOOLEAN_PARAM = 3623303040; pub const JBOOLEAN_TRELLIS_QUANT_DC: crate::jpeglib_h::J_BOOLEAN_PARAM = 865946636; pub const JBOOLEAN_TRELLIS_QUANT: crate::jpeglib_h::J_BOOLEAN_PARAM = 3306299443; pub const JBOOLEAN_OPTIMIZE_SCANS: crate::jpeglib_h::J_BOOLEAN_PARAM = 1745618462; pub const JFLOAT_TRELLIS_DELTA_DC_WEIGHT: crate::jpeglib_h::J_FLOAT_PARAM = 326587475; pub const JFLOAT_LAMBDA_LOG_SCALE2: crate::jpeglib_h::J_FLOAT_PARAM = 3116084739; pub const JFLOAT_LAMBDA_LOG_SCALE1: crate::jpeglib_h::J_FLOAT_PARAM = 1533126041; pub const JINT_DC_SCAN_OPT_MODE: crate::jpeglib_h::J_INT_PARAM = 199732540; pub const JINT_BASE_QUANT_TBL_IDX: crate::jpeglib_h::J_INT_PARAM = 1145645745; pub const JINT_TRELLIS_NUM_LOOPS: crate::jpeglib_h::J_INT_PARAM = 3057565497; pub const JINT_TRELLIS_FREQ_SPLIT: crate::jpeglib_h::J_INT_PARAM = 1873801511; pub const JINT_COMPRESS_PROFILE: crate::jpeglib_h::J_INT_PARAM = 3918628389; #[repr(C)] #[derive(Copy, Clone)] pub struct jpeg_marker_struct { pub next: crate::jpeglib_h::jpeg_saved_marker_ptr, pub marker: crate::jmorecfg_h::UINT8, pub original_length: libc::c_uint, pub data_length: libc::c_uint, pub data: *mut crate::jmorecfg_h::JOCTET, } /* The decompressor can save APPn and COM markers in a list of these: */ pub type jpeg_saved_marker_ptr = *mut crate::jpeglib_h::jpeg_marker_struct; pub type J_DITHER_MODE = libc::c_uint; /* Master record for a decompression instance */ #[repr(C)] #[derive(Copy, Clone)] pub struct jpeg_decompress_struct { pub err: *mut crate::jpeglib_h::jpeg_error_mgr, pub mem: *mut crate::jpeglib_h::jpeg_memory_mgr, pub progress: *mut crate::jpeglib_h::jpeg_progress_mgr, pub client_data: *mut libc::c_void, pub is_decompressor: crate::jmorecfg_h::boolean, pub global_state: libc::c_int, pub src: *mut crate::jpeglib_h::jpeg_source_mgr, pub image_width: crate::jmorecfg_h::JDIMENSION, pub image_height: crate::jmorecfg_h::JDIMENSION, pub num_components: libc::c_int, pub jpeg_color_space: crate::jpeglib_h::J_COLOR_SPACE, pub out_color_space: crate::jpeglib_h::J_COLOR_SPACE, pub scale_num: libc::c_uint, pub scale_denom: libc::c_uint, pub output_gamma: libc::c_double, pub buffered_image: crate::jmorecfg_h::boolean, pub raw_data_out: crate::jmorecfg_h::boolean, pub dct_method: crate::jpeglib_h::J_DCT_METHOD, pub do_fancy_upsampling: crate::jmorecfg_h::boolean, pub do_block_smoothing: crate::jmorecfg_h::boolean, pub quantize_colors: crate::jmorecfg_h::boolean, pub dither_mode: crate::jpeglib_h::J_DITHER_MODE, pub two_pass_quantize: crate::jmorecfg_h::boolean, pub desired_number_of_colors: libc::c_int, pub enable_1pass_quant: crate::jmorecfg_h::boolean, pub enable_external_quant: crate::jmorecfg_h::boolean, pub enable_2pass_quant: crate::jmorecfg_h::boolean, pub output_width: crate::jmorecfg_h::JDIMENSION, pub output_height: crate::jmorecfg_h::JDIMENSION, pub out_color_components: libc::c_int, pub output_components: libc::c_int, pub rec_outbuf_height: libc::c_int, pub actual_number_of_colors: libc::c_int, pub colormap: crate::jpeglib_h::JSAMPARRAY, pub output_scanline: crate::jmorecfg_h::JDIMENSION, pub input_scan_number: libc::c_int, pub input_iMCU_row: crate::jmorecfg_h::JDIMENSION, pub output_scan_number: libc::c_int, pub output_iMCU_row: crate::jmorecfg_h::JDIMENSION, pub coef_bits: *mut [libc::c_int; 64], pub quant_tbl_ptrs: [*mut crate::jpeglib_h::JQUANT_TBL; 4], pub dc_huff_tbl_ptrs: [*mut crate::jpeglib_h::JHUFF_TBL; 4], pub ac_huff_tbl_ptrs: [*mut crate::jpeglib_h::JHUFF_TBL; 4], pub data_precision: libc::c_int, pub comp_info: *mut crate::jpeglib_h::jpeg_component_info, pub progressive_mode: crate::jmorecfg_h::boolean, pub arith_code: crate::jmorecfg_h::boolean, pub arith_dc_L: [crate::jmorecfg_h::UINT8; 16], pub arith_dc_U: [crate::jmorecfg_h::UINT8; 16], pub arith_ac_K: [crate::jmorecfg_h::UINT8; 16], pub restart_interval: libc::c_uint, pub saw_JFIF_marker: crate::jmorecfg_h::boolean, pub JFIF_major_version: crate::jmorecfg_h::UINT8, pub JFIF_minor_version: crate::jmorecfg_h::UINT8, pub density_unit: crate::jmorecfg_h::UINT8, pub X_density: crate::jmorecfg_h::UINT16, pub Y_density: crate::jmorecfg_h::UINT16, pub saw_Adobe_marker: crate::jmorecfg_h::boolean, pub Adobe_transform: crate::jmorecfg_h::UINT8, pub CCIR601_sampling: crate::jmorecfg_h::boolean, pub marker_list: crate::jpeglib_h::jpeg_saved_marker_ptr, pub max_h_samp_factor: libc::c_int, pub max_v_samp_factor: libc::c_int, pub min_DCT_scaled_size: libc::c_int, pub total_iMCU_rows: crate::jmorecfg_h::JDIMENSION, pub sample_range_limit: *mut crate::jmorecfg_h::JSAMPLE, pub comps_in_scan: libc::c_int, pub cur_comp_info: [*mut crate::jpeglib_h::jpeg_component_info; 4], pub MCUs_per_row: crate::jmorecfg_h::JDIMENSION, pub MCU_rows_in_scan: crate::jmorecfg_h::JDIMENSION, pub blocks_in_MCU: libc::c_int, pub MCU_membership: [libc::c_int; 10], pub Ss: libc::c_int, pub Se: libc::c_int, pub Ah: libc::c_int, pub Al: libc::c_int, pub unread_marker: libc::c_int, pub master: *mut crate::jpegint_h::jpeg_decomp_master, pub main: *mut crate::jpegint_h::jpeg_d_main_controller, pub coef: *mut crate::jpegint_h::jpeg_d_coef_controller, pub post: *mut crate::jpegint_h::jpeg_d_post_controller, pub inputctl: *mut crate::jpegint_h::jpeg_input_controller, pub marker: *mut crate::jpegint_h::jpeg_marker_reader, pub entropy: *mut crate::jpegint_h::jpeg_entropy_decoder, pub idct: *mut crate::jpegint_h::jpeg_inverse_dct, pub upsample: *mut crate::jpegint_h::jpeg_upsampler, pub cconvert: *mut crate::jpegint_h::jpeg_color_deconverter, pub cquantize: *mut crate::jpegint_h::jpeg_color_quantizer, } pub type j_decompress_ptr = *mut crate::jpeglib_h::jpeg_decompress_struct; /* Routine signature for application-supplied marker processing methods. * Need not pass marker code since it is stored in cinfo->unread_marker. */ pub type jpeg_marker_parser_method = Option< unsafe extern "C" fn(_: crate::jpeglib_h::j_decompress_ptr) -> crate::jmorecfg_h::boolean, >; /* Data source object for decompression */ #[repr(C)] #[derive(Copy, Clone)] pub struct jpeg_source_mgr { pub next_input_byte: *const crate::jmorecfg_h::JOCTET, pub bytes_in_buffer: crate::stddef_h::size_t, pub init_source: Option<unsafe extern "C" fn(_: crate::jpeglib_h::j_decompress_ptr) -> ()>, pub fill_input_buffer: Option< unsafe extern "C" fn(_: crate::jpeglib_h::j_decompress_ptr) -> crate::jmorecfg_h::boolean, >, pub skip_input_data: Option<unsafe extern "C" fn(_: crate::jpeglib_h::j_decompress_ptr, _: libc::c_long) -> ()>, pub resync_to_restart: Option< unsafe extern "C" fn( _: crate::jpeglib_h::j_decompress_ptr, _: libc::c_int, ) -> crate::jmorecfg_h::boolean, >, pub term_source: Option<unsafe extern "C" fn(_: crate::jpeglib_h::j_decompress_ptr) -> ()>, } pub const JDITHER_FS: crate::jpeglib_h::J_DITHER_MODE = 2; pub const JDITHER_ORDERED: crate::jpeglib_h::J_DITHER_MODE = 1; pub const JDITHER_NONE: crate::jpeglib_h::J_DITHER_MODE = 0; /* lasts until master record is destroyed */ /* lasts until done with image/datastream */ pub const JPOOL_NUMPOOLS: libc::c_int = 2 as libc::c_int; /* Read ICC profile. See libjpeg.txt for usage information. */ /* * Permit users to replace the IDCT method dynamically. * The selector callback is called after the default idct implementation was choosen, * and is able to override it. */ /* These marker codes are exported since applications and data source modules * are likely to want to use them. */ /* RST0 marker code */ /* EOI marker code */ pub const JPEG_APP0: libc::c_int = 0xe0 as libc::c_int; /* The basic DCT block is 8x8 samples */ /* DCTSIZE squared; # of elements in a block */ /* Quantization tables are numbered 0..3 */ /* Huffman tables are numbered 0..3 */ /* Arith-coding tables are numbered 0..15 */ /* JPEG limit on # of components in one scan */ /* JPEG limit on sampling factors */ /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard; * the PostScript DCT filter can emit files with many more than 10 blocks/MCU. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU * to handle it. We even let you do this from the jconfig.h file. However, * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe * sometimes emits noncompliant files doesn't mean you should too. */ pub const C_MAX_BLOCKS_IN_MCU: libc::c_int = 10 as libc::c_int; /* Memory manager object. * Allocates "small" objects (a few K total), "large" objects (tens of K), * and "really big" objects (virtual arrays with backing store if needed). * The memory manager does not allow individual objects to be freed; rather, * each created object is assigned to a pool, and whole pools can be freed * at once. This is faster and more convenient than remembering exactly what * to free, especially where malloc()/free() are not too speedy. * NB: alloc routines never return NULL. They exit to error_exit if not * successful. */ /* lasts until master record is destroyed */ pub const JPOOL_IMAGE: libc::c_int = 1 as libc::c_int; /* Quantization tables are numbered 0..3 */ /* Huffman tables are numbered 0..3 */ pub const NUM_ARITH_TBLS: libc::c_int = 16 as libc::c_int; /* may be overridden in jconfig.h */ pub const JDCT_DEFAULT: libc::c_int = crate::jpeglib_h::JDCT_ISLOW as libc::c_int; /* * jpeglib.h * * This file was part of the Independent JPEG Group's software: * Copyright (C) 1991-1998, Thomas G. Lane. * Modified 2002-2009 by Guido Vollbeding. * libjpeg-turbo Modifications: * Copyright (C) 2009-2011, 2013-2014, 2016-2017, D. R. Commander. * Copyright (C) 2015, Google, Inc. * mozjpeg Modifications: * Copyright (C) 2014, Mozilla Corporation. * For conditions of distribution and use, see the accompanying README.ijg * file. * * This file defines the application interface for the JPEG library. * Most applications using the library need only include this file, * and perhaps jerror.h if they want to know the exact error codes. */ /* * First we include the configuration files that record how this * installation of the JPEG library is set up. jconfig.h can be * generated automatically for many systems. jmorecfg.h contains * manual configuration options that most people need not worry about. */ /* in case jinclude.h already did */ /* Various constants determining the sizes of things. * All of these are specified by the JPEG standard, so don't change them * if you want to be compatible. */ pub const DCTSIZE: libc::c_int = 8 as libc::c_int; /* Quantization tables are numbered 0..3 */ /* Huffman tables are numbered 0..3 */ /* Arith-coding tables are numbered 0..15 */ pub const MAX_COMPS_IN_SCAN: libc::c_int = 4 as libc::c_int; /* JPEG limit on # of components in one scan */ pub const MAX_SAMP_FACTOR: libc::c_int = 4 as libc::c_int; /* a 3-D array of coefficient blocks */ pub type JCOEFPTR = *mut crate::jmorecfg_h::JCOEF; /* The basic DCT block is 8x8 samples */ pub const DCTSIZE2: libc::c_int = 64 as libc::c_int; /* Return value is one of: */ /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */ pub const JPEG_REACHED_SOS: libc::c_int = 1 as libc::c_int; /* Reached start of new scan */ /* Reached end of image */ pub const JPEG_ROW_COMPLETED: libc::c_int = 3 as libc::c_int; pub const JPEG_REACHED_EOI: libc::c_int = 2 as libc::c_int; pub const JPEG_SUSPENDED: libc::c_int = 0 as libc::c_int; /* These marker codes are exported since applications and data source modules * are likely to want to use them. */ /* RST0 marker code */ pub const JPEG_EOI: libc::c_int = 0xd9 as libc::c_int; pub const D_MAX_BLOCKS_IN_MCU: libc::c_int = 10 as libc::c_int; pub const JPEG_SCAN_COMPLETED: libc::c_int = 4 as libc::c_int; #[repr(C)] #[derive(Copy, Clone)] pub union C2RustUnnamed_2 { pub i: [libc::c_int; 8], pub s: [libc::c_char; 80], } pub type JSAMPROW = *mut crate::jmorecfg_h::JSAMPLE; pub type JSAMPARRAY = *mut crate::jpeglib_h::JSAMPROW; pub type JSAMPIMAGE = *mut crate::jpeglib_h::JSAMPARRAY; pub type JBLOCK = [crate::jmorecfg_h::JCOEF; 64]; pub type JBLOCKROW = *mut crate::jpeglib_h::JBLOCK; pub type JBLOCKARRAY = *mut crate::jpeglib_h::JBLOCKROW; #[repr(C)] #[derive(Copy, Clone)] pub struct JQUANT_TBL { pub quantval: [crate::jmorecfg_h::UINT16; 64], pub sent_table: crate::jmorecfg_h::boolean, } #[repr(C)] #[derive(Copy, Clone)] pub struct JHUFF_TBL { pub bits: [crate::jmorecfg_h::UINT8; 17], pub huffval: [crate::jmorecfg_h::UINT8; 256], pub sent_table: crate::jmorecfg_h::boolean, } #[repr(C)] #[derive(Copy, Clone)] pub struct jpeg_component_info { pub component_id: libc::c_int, pub component_index: libc::c_int, pub h_samp_factor: libc::c_int, pub v_samp_factor: libc::c_int, pub quant_tbl_no: libc::c_int, pub dc_tbl_no: libc::c_int, pub ac_tbl_no: libc::c_int, pub width_in_blocks: crate::jmorecfg_h::JDIMENSION, pub height_in_blocks: crate::jmorecfg_h::JDIMENSION, pub DCT_scaled_size: libc::c_int, pub downsampled_width: crate::jmorecfg_h::JDIMENSION, pub downsampled_height: crate::jmorecfg_h::JDIMENSION, pub component_needed: crate::jmorecfg_h::boolean, pub MCU_width: libc::c_int, pub MCU_height: libc::c_int, pub MCU_blocks: libc::c_int, pub MCU_sample_width: libc::c_int, pub last_col_width: libc::c_int, pub last_row_height: libc::c_int, pub quant_table: *mut crate::jpeglib_h::JQUANT_TBL, pub dct_table: *mut libc::c_void, } #[repr(C)] #[derive(Copy, Clone)] pub struct jpeg_scan_info { pub comps_in_scan: libc::c_int, pub component_index: [libc::c_int; 4], pub Ss: libc::c_int, pub Se: libc::c_int, pub Ah: libc::c_int, pub Al: libc::c_int, } pub type J_COLOR_SPACE = libc::c_uint; pub type J_DCT_METHOD = libc::c_uint; #[repr(C)] #[derive(Copy, Clone)] pub struct jpeg_common_struct { pub err: *mut crate::jpeglib_h::jpeg_error_mgr, pub mem: *mut crate::jpeglib_h::jpeg_memory_mgr, pub progress: *mut crate::jpeglib_h::jpeg_progress_mgr, pub client_data: *mut libc::c_void, pub is_decompressor: crate::jmorecfg_h::boolean, pub global_state: libc::c_int, } #[repr(C)] #[derive(Copy, Clone)] pub struct jpeg_progress_mgr { pub progress_monitor: Option<unsafe extern "C" fn(_: crate::jpeglib_h::j_common_ptr) -> ()>, pub pass_counter: libc::c_long, pub pass_limit: libc::c_long, pub completed_passes: libc::c_int, pub total_passes: libc::c_int, } pub type j_common_ptr = *mut crate::jpeglib_h::jpeg_common_struct; #[repr(C)] #[derive(Copy, Clone)] pub struct jpeg_memory_mgr { pub alloc_small: Option< unsafe extern "C" fn( _: crate::jpeglib_h::j_common_ptr, _: libc::c_int, _: crate::stddef_h::size_t, ) -> *mut libc::c_void, >, pub alloc_large: Option< unsafe extern "C" fn( _: crate::jpeglib_h::j_common_ptr, _: libc::c_int, _: crate::stddef_h::size_t, ) -> *mut libc::c_void, >, pub alloc_sarray: Option< unsafe extern "C" fn( _: crate::jpeglib_h::j_common_ptr, _: libc::c_int, _: crate::jmorecfg_h::JDIMENSION, _: crate::jmorecfg_h::JDIMENSION, ) -> crate::jpeglib_h::JSAMPARRAY, >, pub alloc_barray: Option< unsafe extern "C" fn( _: crate::jpeglib_h::j_common_ptr, _: libc::c_int, _: crate::jmorecfg_h::JDIMENSION, _: crate::jmorecfg_h::JDIMENSION, ) -> crate::jpeglib_h::JBLOCKARRAY, >, pub request_virt_sarray: Option< unsafe extern "C" fn( _: crate::jpeglib_h::j_common_ptr, _: libc::c_int, _: crate::jmorecfg_h::boolean, _: crate::jmorecfg_h::JDIMENSION, _: crate::jmorecfg_h::JDIMENSION, _: crate::jmorecfg_h::JDIMENSION, ) -> crate::jpeglib_h::jvirt_sarray_ptr, >, pub request_virt_barray: Option< unsafe extern "C" fn( _: crate::jpeglib_h::j_common_ptr, _: libc::c_int, _: crate::jmorecfg_h::boolean, _: crate::jmorecfg_h::JDIMENSION, _: crate::jmorecfg_h::JDIMENSION, _: crate::jmorecfg_h::JDIMENSION, ) -> crate::jpeglib_h::jvirt_barray_ptr, >, pub realize_virt_arrays: Option<unsafe extern "C" fn(_: crate::jpeglib_h::j_common_ptr) -> ()>, pub access_virt_sarray: Option< unsafe extern "C" fn( _: crate::jpeglib_h::j_common_ptr, _: crate::jpeglib_h::jvirt_sarray_ptr, _: crate::jmorecfg_h::JDIMENSION, _: crate::jmorecfg_h::JDIMENSION, _: crate::jmorecfg_h::boolean, ) -> crate::jpeglib_h::JSAMPARRAY, >, pub access_virt_barray: Option< unsafe extern "C" fn( _: crate::jpeglib_h::j_common_ptr, _: crate::jpeglib_h::jvirt_barray_ptr, _: crate::jmorecfg_h::JDIMENSION, _: crate::jmorecfg_h::JDIMENSION, _: crate::jmorecfg_h::boolean, ) -> crate::jpeglib_h::JBLOCKARRAY, >, pub free_pool: Option<unsafe extern "C" fn(_: crate::jpeglib_h::j_common_ptr, _: libc::c_int) -> ()>, pub self_destruct: Option<unsafe extern "C" fn(_: crate::jpeglib_h::j_common_ptr) -> ()>, pub max_memory_to_use: libc::c_long, pub max_alloc_chunk: libc::c_long, } pub type jvirt_barray_ptr = *mut crate::jpeglib_h::jvirt_barray_control; pub type jvirt_sarray_ptr = *mut crate::jpeglib_h::jvirt_sarray_control; #[repr(C)] #[derive(Copy, Clone)] pub struct jpeg_error_mgr { pub error_exit: Option<unsafe extern "C" fn(_: crate::jpeglib_h::j_common_ptr) -> ()>, pub emit_message: Option<unsafe extern "C" fn(_: crate::jpeglib_h::j_common_ptr, _: libc::c_int) -> ()>, pub output_message: Option<unsafe extern "C" fn(_: crate::jpeglib_h::j_common_ptr) -> ()>, pub format_message: Option<unsafe extern "C" fn(_: crate::jpeglib_h::j_common_ptr, _: *mut libc::c_char) -> ()>, pub reset_error_mgr: Option<unsafe extern "C" fn(_: crate::jpeglib_h::j_common_ptr) -> ()>, pub msg_code: libc::c_int, pub msg_parm: crate::jpeglib_h::C2RustUnnamed_2, pub trace_level: libc::c_int, pub num_warnings: libc::c_long, pub jpeg_message_table: *const *const libc::c_char, pub last_jpeg_message: libc::c_int, pub addon_message_table: *const *const libc::c_char, pub first_addon_message: libc::c_int, pub last_addon_message: libc::c_int, } #[repr(C)] #[derive(Copy, Clone)] pub struct jpeg_compress_struct { pub err: *mut crate::jpeglib_h::jpeg_error_mgr, pub mem: *mut crate::jpeglib_h::jpeg_memory_mgr, pub progress: *mut crate::jpeglib_h::jpeg_progress_mgr, pub client_data: *mut libc::c_void, pub is_decompressor: crate::jmorecfg_h::boolean, pub global_state: libc::c_int, pub dest: *mut crate::jpeglib_h::jpeg_destination_mgr, pub image_width: crate::jmorecfg_h::JDIMENSION, pub image_height: crate::jmorecfg_h::JDIMENSION, pub input_components: libc::c_int, pub in_color_space: crate::jpeglib_h::J_COLOR_SPACE, pub input_gamma: libc::c_double, pub data_precision: libc::c_int, pub num_components: libc::c_int, pub jpeg_color_space: crate::jpeglib_h::J_COLOR_SPACE, pub comp_info: *mut crate::jpeglib_h::jpeg_component_info, pub quant_tbl_ptrs: [*mut crate::jpeglib_h::JQUANT_TBL; 4], pub dc_huff_tbl_ptrs: [*mut crate::jpeglib_h::JHUFF_TBL; 4], pub ac_huff_tbl_ptrs: [*mut crate::jpeglib_h::JHUFF_TBL; 4], pub arith_dc_L: [crate::jmorecfg_h::UINT8; 16], pub arith_dc_U: [crate::jmorecfg_h::UINT8; 16], pub arith_ac_K: [crate::jmorecfg_h::UINT8; 16], pub num_scans: libc::c_int, pub scan_info: *const crate::jpeglib_h::jpeg_scan_info, pub raw_data_in: crate::jmorecfg_h::boolean, pub arith_code: crate::jmorecfg_h::boolean, pub optimize_coding: crate::jmorecfg_h::boolean, pub CCIR601_sampling: crate::jmorecfg_h::boolean, pub smoothing_factor: libc::c_int, pub dct_method: crate::jpeglib_h::J_DCT_METHOD, pub restart_interval: libc::c_uint, pub restart_in_rows: libc::c_int, pub write_JFIF_header: crate::jmorecfg_h::boolean, pub JFIF_major_version: crate::jmorecfg_h::UINT8, pub JFIF_minor_version: crate::jmorecfg_h::UINT8, pub density_unit: crate::jmorecfg_h::UINT8, pub X_density: crate::jmorecfg_h::UINT16, pub Y_density: crate::jmorecfg_h::UINT16, pub write_Adobe_marker: crate::jmorecfg_h::boolean, pub next_scanline: crate::jmorecfg_h::JDIMENSION, pub progressive_mode: crate::jmorecfg_h::boolean, pub max_h_samp_factor: libc::c_int, pub max_v_samp_factor: libc::c_int, pub total_iMCU_rows: crate::jmorecfg_h::JDIMENSION, pub comps_in_scan: libc::c_int, pub cur_comp_info: [*mut crate::jpeglib_h::jpeg_component_info; 4], pub MCUs_per_row: crate::jmorecfg_h::JDIMENSION, pub MCU_rows_in_scan: crate::jmorecfg_h::JDIMENSION, pub blocks_in_MCU: libc::c_int, pub MCU_membership: [libc::c_int; 10], pub Ss: libc::c_int, pub Se: libc::c_int, pub Ah: libc::c_int, pub Al: libc::c_int, pub master: *mut crate::jpegint_h::jpeg_comp_master, pub main: *mut crate::jpegint_h::jpeg_c_main_controller, pub prep: *mut crate::jpegint_h::jpeg_c_prep_controller, pub coef: *mut crate::jpegint_h::jpeg_c_coef_controller, pub marker: *mut crate::jpegint_h::jpeg_marker_writer, pub cconvert: *mut crate::jpegint_h::jpeg_color_converter, pub downsample: *mut crate::jpegint_h::jpeg_downsampler, pub fdct: *mut crate::jpegint_h::jpeg_forward_dct, pub entropy: *mut crate::jpegint_h::jpeg_entropy_encoder, pub script_space: *mut crate::jpeglib_h::jpeg_scan_info, pub script_space_size: libc::c_int, } pub type j_compress_ptr = *mut crate::jpeglib_h::jpeg_compress_struct; #[repr(C)] #[derive(Copy, Clone)] pub struct jpeg_destination_mgr { pub next_output_byte: *mut crate::jmorecfg_h::JOCTET, pub free_in_buffer: crate::stddef_h::size_t, pub init_destination: Option<unsafe extern "C" fn(_: crate::jpeglib_h::j_compress_ptr) -> ()>, pub empty_output_buffer: Option< unsafe extern "C" fn(_: crate::jpeglib_h::j_compress_ptr) -> crate::jmorecfg_h::boolean, >, pub term_destination: Option<unsafe extern "C" fn(_: crate::jpeglib_h::j_compress_ptr) -> ()>, } pub type jpeg_idct_method = Option< unsafe extern "C" fn( _: crate::jpeglib_h::j_decompress_ptr, _: *mut crate::jpeglib_h::jpeg_component_info, _: crate::jpeglib_h::JCOEFPTR, _: crate::jpeglib_h::JSAMPARRAY, _: crate::jmorecfg_h::JDIMENSION, ) -> (), >; pub type jpeg_idct_method_selector = Option< unsafe extern "C" fn( _: crate::jpeglib_h::j_decompress_ptr, _: *mut crate::jpeglib_h::jpeg_component_info, _: *mut crate::jpeglib_h::jpeg_idct_method, _: *mut libc::c_int, ) -> (), >; pub const JCS_RGB565: crate::jpeglib_h::J_COLOR_SPACE = 16; pub const JCS_EXT_ARGB: crate::jpeglib_h::J_COLOR_SPACE = 15; pub const JCS_EXT_ABGR: crate::jpeglib_h::J_COLOR_SPACE = 14; pub const JCS_EXT_BGRA: crate::jpeglib_h::J_COLOR_SPACE = 13; pub const JCS_EXT_RGBA: crate::jpeglib_h::J_COLOR_SPACE = 12; pub const JCS_EXT_XRGB: crate::jpeglib_h::J_COLOR_SPACE = 11; pub const JCS_EXT_XBGR: crate::jpeglib_h::J_COLOR_SPACE = 10; pub const JCS_EXT_BGRX: crate::jpeglib_h::J_COLOR_SPACE = 9; pub const JCS_EXT_BGR: crate::jpeglib_h::J_COLOR_SPACE = 8; pub const JCS_EXT_RGBX: crate::jpeglib_h::J_COLOR_SPACE = 7; pub const JCS_EXT_RGB: crate::jpeglib_h::J_COLOR_SPACE = 6; pub const JCS_YCCK: crate::jpeglib_h::J_COLOR_SPACE = 5; pub const JCS_CMYK: crate::jpeglib_h::J_COLOR_SPACE = 4; pub const JCS_YCbCr: crate::jpeglib_h::J_COLOR_SPACE = 3; pub const JCS_RGB: crate::jpeglib_h::J_COLOR_SPACE = 2; pub const JCS_GRAYSCALE: crate::jpeglib_h::J_COLOR_SPACE = 1; pub const JCS_UNKNOWN: crate::jpeglib_h::J_COLOR_SPACE = 0; pub const JDCT_FLOAT: crate::jpeglib_h::J_DCT_METHOD = 2; pub const JDCT_IFAST: crate::jpeglib_h::J_DCT_METHOD = 1; pub const JDCT_ISLOW: crate::jpeglib_h::J_DCT_METHOD = 0; pub const JCP_FASTEST: crate::stdlib::C2RustUnnamed_0 = 720002228; pub const JCP_MAX_COMPRESSION: crate::stdlib::C2RustUnnamed_0 = 1560820397; pub const JPOOL_PERMANENT: libc::c_int = 0 as libc::c_int; pub const NUM_HUFF_TBLS: libc::c_int = 4 as libc::c_int; pub const NUM_QUANT_TBLS: libc::c_int = 4 as libc::c_int; /* Method pointers */ /* Limit on memory allocation for this JPEG object. (Note that this is * merely advisory, not a guaranteed maximum; it only affects the space * used for virtual-array buffers.) May be changed by outer application * after creating the JPEG object. */ /* Maximum allocation request accepted by alloc_large. */ /* Routine signature for application-supplied marker processing methods. * Need not pass marker code since it is stored in cinfo->unread_marker. */ /* Originally, this macro was used as a way of defining function prototypes * for both modern compilers as well as older compilers that did not support * prototype parameters. libjpeg-turbo has never supported these older, * non-ANSI compilers, but the macro is still included because there is some * software out there that uses it. */ /* Default error-management setup */ /* Initialization of JPEG compression objects. * jpeg_create_compress() and jpeg_create_decompress() are the exported * names that applications should call. These expand to calls on * jpeg_CreateCompress and jpeg_CreateDecompress with additional information * passed for version mismatch checking. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx. */ /* Destruction of JPEG compression objects */ /* Standard data source and destination managers: stdio streams. */ /* Caller is responsible for opening the file before and closing after. */ /* Data source and destination managers: memory buffers. */ /* Default parameter setup for compression */ /* Compression parameter setup aids */ /* Main entry points for compression */ /* Replaces jpeg_write_scanlines when writing raw downsampled data. */ /* Write a special marker. See libjpeg.txt concerning safe usage. */ /* Same, but piecemeal. */ /* Alternate compression function: just write an abbreviated table file */ /* Write ICC profile. See libjpeg.txt for usage information. */ /* Decompression startup: read start of JPEG datastream to see what's there */ /* Return value is one of: */ /* Suspended due to lack of input data */ /* Found valid image datastream */ pub const JPEG_HEADER_TABLES_ONLY: libc::c_int = 2 as libc::c_int; pub const JPEG_HEADER_OK: libc::c_int = 1 as libc::c_int; pub use crate::src::jmemmgr::jvirt_barray_control; pub use crate::src::jmemmgr::jvirt_sarray_control; pub const JDCT_FASTEST: libc::c_int = crate::jpeglib_h::JDCT_IFAST as libc::c_int; pub const JMSG_LENGTH_MAX: libc::c_int = 200 as libc::c_int;
42.929556
100
0.715657
e4b472bbac6066356874d304bda40d99199a20de
7,938
use crate::assets::gltf::MeshAssetData; use crate::game_asset_lookup::{ GameLoadedAssetLookupSet, GameLoadedAssetMetrics, MeshAsset, MeshAssetInner, MeshAssetPart, }; use crate::phases::{OpaqueRenderPhase, ShadowMapRenderPhase}; use ash::prelude::VkResult; use atelier_assets::loader::handle::AssetHandle; use atelier_assets::loader::handle::Handle; use atelier_assets::loader::storage::AssetLoadOp; use atelier_assets::loader::Loader; use crossbeam_channel::Sender; use rafx::{assets::{AssetLookup, AssetManager, GenericLoader, LoadQueues}, resources::VertexDataSetLayout}; use std::sync::Arc; #[derive(Debug)] pub struct GameAssetManagerMetrics { pub game_loaded_asset_metrics: GameLoadedAssetMetrics, } #[derive(Default)] pub struct GameLoadQueueSet { pub meshes: LoadQueues<MeshAssetData, MeshAsset>, } pub struct GameAssetManager { loaded_assets: GameLoadedAssetLookupSet, load_queues: GameLoadQueueSet, } impl GameAssetManager { pub fn new(loader: &Loader) -> Self { GameAssetManager { loaded_assets: GameLoadedAssetLookupSet::new(loader), load_queues: Default::default(), } } pub fn create_mesh_loader(&self) -> GenericLoader<MeshAssetData, MeshAsset> { self.load_queues.meshes.create_loader() } pub fn mesh( &self, handle: &Handle<MeshAsset>, ) -> Option<&MeshAsset> { self.loaded_assets .meshes .get_committed(handle.load_handle()) } // Call whenever you want to handle assets loading/unloading #[profiling::function] pub fn update_asset_loaders( &mut self, asset_manager: &AssetManager, ) -> VkResult<()> { self.process_mesh_load_requests(asset_manager); Ok(()) } pub fn metrics(&self) -> GameAssetManagerMetrics { let game_loaded_asset_metrics = self.loaded_assets.metrics(); GameAssetManagerMetrics { game_loaded_asset_metrics, } } #[profiling::function] fn process_mesh_load_requests( &mut self, asset_manager: &AssetManager, ) { for request in self.load_queues.meshes.take_load_requests() { log::trace!("Create mesh {:?}", request.load_handle); let loaded_asset = self.load_mesh(asset_manager, &request.asset); Self::handle_load_result( request.load_op, loaded_asset, &mut self.loaded_assets.meshes, request.result_tx, ); } Self::handle_commit_requests(&mut self.load_queues.meshes, &mut self.loaded_assets.meshes); Self::handle_free_requests(&mut self.load_queues.meshes, &mut self.loaded_assets.meshes); } fn handle_load_result<AssetT: Clone>( load_op: AssetLoadOp, loaded_asset: VkResult<AssetT>, asset_lookup: &mut AssetLookup<AssetT>, result_tx: Sender<AssetT>, ) { match loaded_asset { Ok(loaded_asset) => { asset_lookup.set_uncommitted(load_op.load_handle(), loaded_asset.clone()); result_tx.send(loaded_asset).unwrap(); load_op.complete() } Err(err) => { load_op.error(err); } } } fn handle_commit_requests<AssetDataT, AssetT>( load_queues: &mut LoadQueues<AssetDataT, AssetT>, asset_lookup: &mut AssetLookup<AssetT>, ) { for request in load_queues.take_commit_requests() { log::trace!( "commit asset {:?} {}", request.load_handle, core::any::type_name::<AssetDataT>() ); asset_lookup.commit(request.load_handle); } } fn handle_free_requests<AssetDataT, AssetT>( load_queues: &mut LoadQueues<AssetDataT, AssetT>, asset_lookup: &mut AssetLookup<AssetT>, ) { for request in load_queues.take_commit_requests() { asset_lookup.commit(request.load_handle); } } #[profiling::function] fn load_mesh( &mut self, asset_manager: &AssetManager, mesh_asset: &MeshAssetData, ) -> VkResult<MeshAsset> { let vertex_buffer = asset_manager .loaded_assets() .buffers .get_latest(mesh_asset.buffer.load_handle()) .unwrap() .buffer .clone(); let mesh_parts: Vec<_> = mesh_asset .mesh_parts .iter() .map(|mesh_part| { let material_instance = asset_manager .loaded_assets() .material_instances .get_committed(mesh_part.material_instance.load_handle()) .unwrap(); let opaque_pass_index = material_instance .material .find_pass_by_phase::<OpaqueRenderPhase>(); if opaque_pass_index.is_none() { log::error!( "A mesh part with material {:?} has no opaque phase", material_instance.material_handle ); return None; } let opaque_pass_index = opaque_pass_index.unwrap(); //NOTE: For now require this, but we might want to disable shadow casting, in which // case no material is necessary let shadow_map_pass_index = material_instance .material .find_pass_by_phase::<ShadowMapRenderPhase>(); if shadow_map_pass_index.is_none() { log::error!( "A mesh part with material {:?} has no shadow map phase", material_instance.material_handle ); return None; } const PER_MATERIAL_DESCRIPTOR_SET_LAYOUT_INDEX: usize = 1; let mut layout_offsets = Vec::new(); for (_, offset) in &mesh_part.vertex_layouts { layout_offsets.push(*offset); } let layout_set = VertexDataSetLayout::new(mesh_part.vertex_layouts.iter().map(|(layout, _)| layout.clone()).collect()); Some(MeshAssetPart { opaque_pass: material_instance.material.passes[opaque_pass_index].clone(), opaque_material_descriptor_set: material_instance.material_descriptor_sets [opaque_pass_index][PER_MATERIAL_DESCRIPTOR_SET_LAYOUT_INDEX] .as_ref() .unwrap() .clone(), shadow_map_pass: shadow_map_pass_index .map(|pass_index| material_instance.material.passes[pass_index].clone()), vertex_layouts: layout_set, vertex_binding_buffer_offsets: layout_offsets, index_buffer_offset: mesh_part.index_layout.1, num_vertices: mesh_part.num_vertices, num_indices: mesh_part.num_indices, }) }) .collect(); let inner = MeshAssetInner { vertex_buffer, asset_data: mesh_asset.clone(), mesh_parts, }; Ok(MeshAsset { inner: Arc::new(inner), }) } } impl Drop for GameAssetManager { fn drop(&mut self) { log::info!("Cleaning up game resource manager"); log::trace!("Game Resource Manager Metrics:\n{:#?}", self.metrics()); // Wipe out any loaded assets. This will potentially drop ref counts on resources self.loaded_assets.destroy(); log::info!("Dropping game resource manager"); log::trace!("Resource Game Manager Metrics:\n{:#?}", self.metrics()); } }
34.815789
135
0.578987
5d26059644d17a04dd5832cd2ff4bcdaa98c1dac
344
#![feature(const_fn)] const X : usize = 2; const fn f(x: usize) -> usize { let mut sum = 0; for i in 0..x { //~^ ERROR E0015 //~| ERROR E0658 //~| ERROR E0080 //~| ERROR E0744 //~| ERROR E0019 sum += i; } sum } #[allow(unused_variables)] fn main() { let a : [i32; f(X)]; }
15.636364
31
0.456395
e806ab2a4ec4e60a52dc883ad6ad6a34f52c3d5e
1,560
//! All objects related to context use std::collections::HashMap; use super::senum::{Type,RepeatState}; use super::device::Device; use super::track::FullTrack; use std::time::SystemTime; /// Context object ///[get the users currently playing track](https://developer.spotify.com/web-api/get-the-users-currently-playing-track/) #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Context { pub uri: String, pub href: String, pub external_urls: HashMap<String, String>, #[serde(rename = "type")] pub _type: Type, } /// Full playing context ///[get information about the users current playback](https://developer.spotify.com/web-api/get-information-about-the-users-current-playback/) #[derive(Clone, Debug, Serialize, Deserialize)] pub struct FullPlayingContext { pub device: Device, pub repeat_state: RepeatState, pub shuffle_state: bool, pub context: Option<Context>, pub timestamp: u64, pub progress_ms: Option<u32>, pub is_playing: bool, pub item: Option<FullTrack>, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct FullPlayingContextTimeStamped { pub ctx : FullPlayingContext, pub timestamp_systime: SystemTime, } ///[get the users currently playing track](https://developer.spotify.com/web-api/get-the-users-currently-playing-track/) #[derive(Clone, Debug, Serialize, Deserialize)] pub struct SimplifiedPlayingContext { pub context: Option<Context>, pub timestamp: u64, pub progress_ms: Option<u32>, pub is_playing: bool, pub item: Option<FullTrack>, }
31.836735
142
0.726282
751f86f45856211797329b82b0267123570fde3c
1,999
//! Version support. use crate::{Error, Result}; use core::convert::{TryFrom, TryInto}; /// BIP32 versions are the leading prefix of a Base58-encoded extended key /// interpreted as a 32-bit big endian integer after decoding. #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)] #[non_exhaustive] pub enum Version { /// Mainnet public key. XPub, /// Mainnet private key. XPrv, /// Testnet public key. TPub, /// Testnet private key. TPrv, /// Other types of keys. Other(u32), } impl Version { /// Is this a mainnet key? pub fn is_mainnet(self) -> bool { matches!(self, Version::XPub | Version::XPrv) } /// Is this a testnet key? pub fn is_testnet(self) -> bool { matches!(self, Version::TPub | Version::TPrv) } /// Is this a public key? pub fn is_public(self) -> bool { matches!(self, Version::XPub | Version::TPub) } /// Is this a private key? pub fn is_private(self) -> bool { matches!(self, Version::XPrv | Version::TPrv) } } impl From<u32> for Version { fn from(n: u32) -> Version { match n { // `xpub` (mainnet public) 0x0488B21E => Version::XPub, // `xprv` (mainnet private) 0x0488ADE4 => Version::XPrv, // `tpub` (testnet public) 0x043587CF => Version::TPub, // `tprv` (testnet private) 0x04358394 => Version::TPrv, _ => Version::Other(n), } } } impl From<Version> for u32 { fn from(v: Version) -> u32 { match v { Version::XPub => 0x0488B21E, Version::XPrv => 0x0488ADE4, Version::TPub => 0x043587CF, Version::TPrv => 0x04358394, Version::Other(n) => n, } } } impl TryFrom<&[u8]> for Version { type Error = Error; fn try_from(bytes: &[u8]) -> Result<Version> { Ok(u32::from_be_bytes(bytes.try_into()?).into()) } }
23.797619
74
0.551776
dde4c56e5196645b475fc1f63424f4c88b21354b
601
fn main() { println!("Hello, world!"); let v: Vec<i32> = Vec::new(); println!("v: {:?}", v); let v2 = vec![1, 2, 3]; println!("v2: {:?}", v2); let mut v3 = vec![4, 5, 6]; println!("v3: {:?}", v3); v3.push(7); v3.push(8); v3.push(9); println!("v3: {:?}", v3); let third: &i32 = &v3[2]; println!("The third element is {}", third); match v3.get(2) { Some(third) => println!("The third element is {}", third), None => println!("There is no third element."), } for i in &v3 { println!("iterating {}", i); } }
21.464286
66
0.459235
ab30ff6cf4513588995b0b860f83a0c3f91f4be3
3,108
use crate::errors::ServerReceiveError; use crate::AuthObj; use log::debug; use oauth2::{AuthorizationCode, CsrfToken}; use std::io::{BufRead, BufReader, Write}; use std::net::TcpListener; use url::Url; pub fn naive_server( auth_obj: &AuthObj, port: u32, ) -> Result<AuthorizationCode, ServerReceiveError> { // A very naive implementation of the redirect server. // A ripoff of https://github.com/ramosbugs/oauth2-rs/blob/master/examples/msgraph.rs, stripped // down for simplicity. let listener = TcpListener::bind(format!("127.0.0.1:{}", port)).unwrap(); for stream in listener.incoming() { if let Ok(mut stream) = stream { { let mut reader = BufReader::new(&stream); let mut request_line = String::new(); reader.read_line(&mut request_line).unwrap(); let redirect_url = match request_line.split_whitespace().nth(1) { Some(redirect_url) => redirect_url, None => { return Err(ServerReceiveError::UnexpectedRedirectUrl { url: request_line }) } }; let url = Url::parse(&("http://localhost".to_string() + redirect_url)).unwrap(); debug!("url == {}", url); let code = match url.query_pairs().find(|pair| { let &(ref key, _) = pair; key == "code" }) { Some(qp) => AuthorizationCode::new(qp.1.into_owned()), None => { return Err(ServerReceiveError::QueryPairNotFound { query_pair: "code".to_owned(), }) } }; let state = match url.query_pairs().find(|pair| { let &(ref key, _) = pair; key == "state" }) { Some(qp) => CsrfToken::new(qp.1.into_owned()), None => { return Err(ServerReceiveError::QueryPairNotFound { query_pair: "state".to_owned(), }) } }; if state.secret() != auth_obj.csrf_state.secret() { return Err(ServerReceiveError::StateSecretMismatch { expected_state_secret: auth_obj.csrf_state.secret().to_owned(), received_state_secret: state.secret().to_owned(), }); } let message = "Authentication complete. You can close this window now."; let response = format!( "HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{}", message.len(), message ); stream.write_all(response.as_bytes()).unwrap(); // The server will terminate itself after collecting the first code. return Ok(code); } } } unreachable!() }
37.902439
99
0.483269
fe9b9b61883aa4b4d1bb41c650c23cf2454ccde3
1,443
use super::super::{P, Command}; #[derive(Copy, Clone, Debug)] pub struct Bot { pub bid: usize, pub p: P, } // // Commands invoked in a single time step by the bots // #[derive(Clone, Debug)] pub struct CommandSet { pub commands: Vec<Command>, } impl CommandSet { pub fn new(n_bots: usize) -> CommandSet { CommandSet { commands: vec![Command::Wait; n_bots], } } pub fn new_uniform(n_bots: usize, command: Command) -> CommandSet { CommandSet { commands: vec![command; n_bots], } } pub fn is_all_wait(&self) -> bool { return self.commands.iter().all(|&cmd| cmd == Command::Wait); } pub fn is_all_busy(&self) -> bool { return self.commands.iter().all(|&cmd| cmd != Command::Wait); } pub fn gvoid_below_layer(&mut self, bots: &[&Bot; 4]) { // TODO: 常に真下ではなく斜めを使ってわずかに稼ぐか?(優先度低い) let nd = P::new(0, -1, 0); for i in 0..4 { let b1 = bots[i]; let b2 = bots[i ^ 3]; assert_eq!(self.commands[b1.bid], Command::Wait); self.commands[b1.bid] = Command::GVoid(nd, b2.p - b1.p) } } pub fn flip_by_somebody(&mut self) { for i in 0..self.commands.len() { if self.commands[i] == Command::Wait { self.commands[i] = Command::Flip; return; } } panic!(); } }
23.655738
71
0.524602
efce416308bfb07dc29491a9b612d21026a83b4c
8,703
//! [SRS]-based definitions and implementations. //! //! [SRS]: https://github.com/ossrs/srs use std::{ borrow::Borrow, ops::Deref, panic::AssertUnwindSafe, path::{Path, PathBuf}, process::Stdio, sync::Arc, }; use anyhow::anyhow; use askama::Template; use derive_more::{AsRef, Deref, Display, From, Into}; use ephyr_log::{log, slog}; use futures::future::{self, FutureExt as _, TryFutureExt as _}; use smart_default::SmartDefault; use tokio::{fs, process::Command}; use crate::{api, display_panic, dvr}; /// [SRS] server spawnable as a separate process. /// /// [SRS]: https://github.com/ossrs/srs #[derive(Clone, Debug)] pub struct Server { /// Path where [SRS] configuration file should be created. /// /// [SRS]: https://github.com/ossrs/srs conf_path: PathBuf, /// Handle to the actual spawned [SRS] process. /// /// [SRS]: https://github.com/ossrs/srs _process: Arc<ServerProcess>, } impl Server { /// Tries to create and run a new [SRS] server process. /// /// # Errors /// /// If [SRS] configuration file fails to be created. /// /// [SRS]: https://github.com/ossrs/srs pub async fn try_new<P: AsRef<Path>>( workdir: P, cfg: &Config, ) -> Result<Self, anyhow::Error> { let workdir = workdir.as_ref(); let mut bin_path = workdir.to_path_buf(); bin_path.push("objs/srs"); let mut conf_path = workdir.to_path_buf(); conf_path.push("conf/srs.conf"); let http_dir = if cfg.http_server_dir.is_relative() { let mut dir = workdir.to_path_buf(); dir.push(&cfg.http_server_dir); dir } else { cfg.http_server_dir.clone().into() }; // Pre-create directory for HLS. let mut hls_dir = http_dir.clone(); hls_dir.push("hls"); fs::create_dir_all(&hls_dir).await.map_err(|e| { anyhow!( "Failed to pre-create HLS directory {} : {}", hls_dir.display(), e, ) })?; // Set directory for dvr::Storage served by this SRS instance. let mut dvr_dir = http_dir.clone(); dvr_dir.push("dvr"); dvr::Storage { root_path: dvr_dir }.set_global()?; let mut cmd = Command::new(bin_path); let _ = cmd .stdin(Stdio::null()) .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .kill_on_drop(true) .current_dir(workdir) .arg("-c") .arg(&conf_path); let (spawner, abort_handle) = future::abortable(async move { loop { let cmd = &mut cmd; let _ = AssertUnwindSafe(async move { let process = cmd.spawn().map_err(|e| { log::crit!("Cannot start SRS server: {}", e); })?; let out = process.wait_with_output().await.map_err(|e| { log::crit!("Failed to observe SRS server: {}", e); })?; log::crit!( "SRS server stopped with exit code: {}", out.status, ); Ok(()) }) .unwrap_or_else(|_: ()| ()) .catch_unwind() .await .map_err(|p| { log::crit!( "Panicked while spawning/observing SRS server: {}", display_panic(&p), ); }); } }); let srv = Self { conf_path, _process: Arc::new(ServerProcess(abort_handle)), }; // Pre-create SRS conf file. srv.refresh(cfg).await?; // Start SRS server as a child process. drop(tokio::spawn(spawner)); Ok(srv) } /// Updates [SRS] configuration file and reloads the spawned [SRS] server /// to catch up the changes. /// /// # Errors /// /// If [SRS] configuration file fails to be created. /// /// [SRS]: https://github.com/ossrs/srs pub async fn refresh(&self, cfg: &Config) -> anyhow::Result<()> { // SRS server reloads automatically on its conf file changes. fs::write( &self.conf_path, cfg.render().map_err(|e| { anyhow!("Failed to render SRS config from template: {}", e) })?, ) .await .map_err(|e| anyhow!("Failed to write SRS config file: {}", e)) } } /// Handle to a spawned [SRS] server process. /// /// [SRS]: https://github.com/ossrs/srs #[derive(Clone, Debug)] struct ServerProcess(future::AbortHandle); impl Drop for ServerProcess { #[inline] fn drop(&mut self) { self.0.abort(); } } /// ID of [SRS] server client guarded by its participation. /// /// Once this ID is fully [`Drop`]ped the client will be kicked from [SRS] /// server. /// /// [SRS]: https://github.com/ossrs/srs #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct ClientId(Arc<String>); impl ClientId { /// Returns value of `client_id` #[must_use] pub fn get_value(&self) -> Option<String> { Some(self.0.as_ref().to_string()) } } impl From<String> for ClientId { #[inline] fn from(id: String) -> Self { Self(Arc::new(id)) } } impl Deref for ClientId { type Target = String; #[inline] fn deref(&self) -> &Self::Target { &*self.0 } } impl Borrow<String> for ClientId { #[inline] fn borrow(&self) -> &String { &*self } } impl Drop for ClientId { /// Kicks a client behind this [`ClientId`] from [SRS] server it there are /// no more copies left. /// /// [SRS]: https://github.com/ossrs/srs fn drop(&mut self) { if let Some(client_id) = Arc::get_mut(&mut self.0).cloned() { drop(tokio::spawn( api::srs::Client::kickoff_client(client_id.clone()).map_err( move |e| { log::warn!( "Failed to kickoff client {} from SRS: {}", client_id, e, ); }, ), )); } } } /// Configuration parameters of [SRS] server used by this application. /// /// [SRS]: https://github.com/ossrs/srs #[derive(Clone, Debug, Template)] #[template(path = "restreamer.srs.conf.j2", escape = "none")] pub struct Config { /// Port that [HTTP Callback API][1] is exposed on. /// /// [1]: https://en.wikipedia.org/wiki/Basic_access_authentication pub callback_port: u16, /// Path to the directory served by [SRS] HTTP server (HLS chunks, etc). /// /// [SRS]: https://github.com/ossrs/srs pub http_server_dir: DisplayablePath, /// Severity of [SRS] server logs. /// /// [SRS]: https://github.com/ossrs/srs pub log_level: LogLevel, } /// Severity of [SRS] [server logs][1]. /// /// [SRS]: https://github.com/ossrs/srs /// [1]: https://github.com/ossrs/srs/wiki/v4_EN_SrsLog#loglevel #[derive(Clone, Copy, Debug, Display, SmartDefault)] pub enum LogLevel { /// Error level. #[display(fmt = "error")] Error, /// Warning log, without debug log. #[display(fmt = "warn")] Warn, /// Important log, less and [SRS] enables it as a default level. /// /// [SRS]: https://github.com/ossrs/srs #[default] #[display(fmt = "trace")] Trace, /// Detail log, which huts performance. /// /// [SRS] defaults to disable it when compile. /// /// [SRS]: https://github.com/ossrs/srs #[display(fmt = "info")] Info, /// Lots of log, which hurts performance. /// /// [SRS] defaults to disable it when compile. /// /// [SRS]: https://github.com/ossrs/srs #[display(fmt = "verbose")] Verbose, } impl From<slog::Level> for LogLevel { #[inline] fn from(lvl: slog::Level) -> Self { match lvl { slog::Level::Critical | slog::Level::Error => Self::Error, slog::Level::Warning | slog::Level::Info => Self::Warn, slog::Level::Debug => Self::Trace, slog::Level::Trace => Self::Info, } } } /// [`Display`]able wrapper around [`PathBuf`] for using in /// [`askama::Template`]s. /// /// [`Display`]: std::fmt::Display #[derive(AsRef, Clone, Debug, Deref, Display, From, Into)] #[as_ref(forward)] #[display(fmt = "{}", "_0.display()")] pub struct DisplayablePath(PathBuf);
27.894231
78
0.528209
f802f499ea6b2d8657da70a1ea9382c126d293e0
16,531
#![allow(clippy::too_many_arguments)] use super::commitments::{Commitments, MultiCommitGens}; use super::errors::ProofVerifyError; use super::group::{CompressedGroup, GroupElement, VartimeMultiscalarMul}; use super::math::Math; use super::nizk::{DotProductProofGens, DotProductProofLog}; use super::random::RandomTape; use super::scalar::Scalar; use super::transcript::{AppendToTranscript, ProofTranscript}; use core::ops::Index; use merlin::Transcript; use serde::{Deserialize, Serialize}; #[cfg(feature = "multicore")] use rayon::prelude::*; #[derive(Debug)] pub struct DensePolynomial { num_vars: usize, // the number of variables in the multilinear polynomial len: usize, Z: Vec<Scalar>, // evaluations of the polynomial in all the 2^num_vars Boolean inputs } pub struct PolyCommitmentGens { pub gens: DotProductProofGens, } impl PolyCommitmentGens { // the number of variables in the multilinear polynomial pub fn new(num_vars: usize, label: &'static [u8]) -> PolyCommitmentGens { let (_left, right) = EqPolynomial::compute_factored_lens(num_vars); let gens = DotProductProofGens::new(right.pow2(), label); PolyCommitmentGens { gens } } } pub struct PolyCommitmentBlinds { blinds: Vec<Scalar>, } #[derive(Debug, Serialize, Deserialize)] pub struct PolyCommitment { C: Vec<CompressedGroup>, } #[derive(Debug, Serialize, Deserialize)] pub struct ConstPolyCommitment { C: CompressedGroup, } pub struct EqPolynomial { r: Vec<Scalar>, } impl EqPolynomial { pub fn new(r: Vec<Scalar>) -> Self { EqPolynomial { r } } pub fn evaluate(&self, rx: &[Scalar]) -> Scalar { assert_eq!(self.r.len(), rx.len()); (0..rx.len()) .map(|i| self.r[i] * rx[i] + (Scalar::one() - self.r[i]) * (Scalar::one() - rx[i])) .product() } pub fn evals(&self) -> Vec<Scalar> { let ell = self.r.len(); let mut evals: Vec<Scalar> = vec![Scalar::one(); ell.pow2()]; let mut size = 1; for j in 0..ell { // in each iteration, we double the size of chis size *= 2; for i in (0..size).rev().step_by(2) { // copy each element from the prior iteration twice let scalar = evals[i / 2]; evals[i] = scalar * self.r[j]; evals[i - 1] = scalar - evals[i]; } } evals } pub fn compute_factored_lens(ell: usize) -> (usize, usize) { (ell / 2, ell - ell / 2) } pub fn compute_factored_evals(&self) -> (Vec<Scalar>, Vec<Scalar>) { let ell = self.r.len(); let (left_num_vars, _right_num_vars) = EqPolynomial::compute_factored_lens(ell); let L = EqPolynomial::new(self.r[..left_num_vars].to_vec()).evals(); let R = EqPolynomial::new(self.r[left_num_vars..ell].to_vec()).evals(); (L, R) } } pub struct IdentityPolynomial { size_point: usize, } impl IdentityPolynomial { pub fn new(size_point: usize) -> Self { IdentityPolynomial { size_point } } pub fn evaluate(&self, r: &[Scalar]) -> Scalar { let len = r.len(); assert_eq!(len, self.size_point); (0..len) .map(|i| Scalar::from((len - i - 1).pow2() as u64) * r[i]) .sum() } } impl DensePolynomial { pub fn new(Z: Vec<Scalar>) -> Self { let len = Z.len(); let num_vars = len.log2(); DensePolynomial { num_vars, Z, len } } pub fn get_num_vars(&self) -> usize { self.num_vars } pub fn len(&self) -> usize { self.len } pub fn clone(&self) -> DensePolynomial { DensePolynomial::new(self.Z[0..self.len].to_vec()) } pub fn split(&self, idx: usize) -> (DensePolynomial, DensePolynomial) { assert!(idx < self.len()); ( DensePolynomial::new(self.Z[..idx].to_vec()), DensePolynomial::new(self.Z[idx..2 * idx].to_vec()), ) } #[cfg(feature = "multicore")] fn commit_inner(&self, blinds: &Vec<Scalar>, gens: &MultiCommitGens) -> PolyCommitment { let L_size = blinds.len(); let R_size = self.Z.len() / L_size; assert_eq!(L_size * R_size, self.Z.len()); let C = (0..L_size) .into_par_iter() .map(|&i| { self.Z[R_size * i..R_size * (i + 1)] .commit(&blinds[i], gens) .compress() }) .collect(); PolyCommitment { C } } #[cfg(not(feature = "multicore"))] fn commit_inner(&self, blinds: &[Scalar], gens: &MultiCommitGens) -> PolyCommitment { let L_size = blinds.len(); let R_size = self.Z.len() / L_size; assert_eq!(L_size * R_size, self.Z.len()); let C = (0..L_size) .map(|i| { self.Z[R_size * i..R_size * (i + 1)] .commit(&blinds[i], gens) .compress() }) .collect(); PolyCommitment { C } } pub fn commit( &self, gens: &PolyCommitmentGens, random_tape: Option<&mut RandomTape>, ) -> (PolyCommitment, PolyCommitmentBlinds) { let n = self.Z.len(); let ell = self.get_num_vars(); assert_eq!(n, ell.pow2()); let (left_num_vars, right_num_vars) = EqPolynomial::compute_factored_lens(ell); let L_size = left_num_vars.pow2(); let R_size = right_num_vars.pow2(); assert_eq!(L_size * R_size, n); let blinds = if random_tape.is_some() { PolyCommitmentBlinds { blinds: random_tape.unwrap().random_vector(b"poly_blinds", L_size), } } else { PolyCommitmentBlinds { blinds: vec![Scalar::zero(); L_size], } }; (self.commit_inner(&blinds.blinds, &gens.gens.gens_n), blinds) } pub fn bound(&self, L: &[Scalar]) -> Vec<Scalar> { let (left_num_vars, right_num_vars) = EqPolynomial::compute_factored_lens(self.get_num_vars()); let L_size = left_num_vars.pow2(); let R_size = right_num_vars.pow2(); (0..R_size) .map(|i| (0..L_size).map(|j| L[j] * self.Z[j * R_size + i]).sum()) .collect() } pub fn bound_poly_var_top(&mut self, r: &Scalar) { let n = self.len() / 2; for i in 0..n { self.Z[i] = self.Z[i] + r * (self.Z[i + n] - self.Z[i]); } self.num_vars -= 1; self.len = n; } pub fn bound_poly_var_bot(&mut self, r: &Scalar) { let n = self.len() / 2; for i in 0..n { self.Z[i] = self.Z[2 * i] + r * (self.Z[2 * i + 1] - self.Z[2 * i]); } self.num_vars -= 1; self.len = n; } // returns Z(r) in O(n) time pub fn evaluate(&self, r: &[Scalar]) -> Scalar { // r must have a value for each variable assert_eq!(r.len(), self.get_num_vars()); let chis = EqPolynomial::new(r.to_vec()).evals(); assert_eq!(chis.len(), self.Z.len()); DotProductProofLog::compute_dotproduct(&self.Z, &chis) } fn vec(&self) -> &Vec<Scalar> { &self.Z } pub fn extend(&mut self, other: &DensePolynomial) { // TODO: allow extension even when some vars are bound assert_eq!(self.Z.len(), self.len); let other_vec = other.vec(); assert_eq!(other_vec.len(), self.len); self.Z.extend(other_vec); self.num_vars += 1; self.len *= 2; assert_eq!(self.Z.len(), self.len); } pub fn merge<'a, I>(polys: I) -> DensePolynomial where I: IntoIterator<Item = &'a DensePolynomial>, { let mut Z: Vec<Scalar> = Vec::new(); for poly in polys.into_iter() { Z.extend(poly.vec()); } // pad the polynomial with zero polynomial at the end Z.resize(Z.len().next_power_of_two(), Scalar::zero()); DensePolynomial::new(Z) } pub fn from_usize(Z: &[usize]) -> Self { DensePolynomial::new( (0..Z.len()) .map(|i| Scalar::from(Z[i] as u64)) .collect::<Vec<Scalar>>(), ) } } impl Index<usize> for DensePolynomial { type Output = Scalar; #[inline(always)] fn index(&self, _index: usize) -> &Scalar { &(self.Z[_index]) } } impl AppendToTranscript for PolyCommitment { fn append_to_transcript(&self, label: &'static [u8], transcript: &mut Transcript) { transcript.append_message(label, b"poly_commitment_begin"); for i in 0..self.C.len() { transcript.append_point(b"poly_commitment_share", &self.C[i]); } transcript.append_message(label, b"poly_commitment_end"); } } #[derive(Debug, Serialize, Deserialize)] pub struct PolyEvalProof { proof: DotProductProofLog, } impl PolyEvalProof { fn protocol_name() -> &'static [u8] { b"polynomial evaluation proof" } pub fn prove( poly: &DensePolynomial, blinds_opt: Option<&PolyCommitmentBlinds>, r: &[Scalar], // point at which the polynomial is evaluated Zr: &Scalar, // evaluation of \widetilde{Z}(r) blind_Zr_opt: Option<&Scalar>, // specifies a blind for Zr gens: &PolyCommitmentGens, transcript: &mut Transcript, random_tape: &mut RandomTape, ) -> (PolyEvalProof, CompressedGroup) { transcript.append_protocol_name(PolyEvalProof::protocol_name()); // assert vectors are of the right size assert_eq!(poly.get_num_vars(), r.len()); let (left_num_vars, right_num_vars) = EqPolynomial::compute_factored_lens(r.len()); let L_size = left_num_vars.pow2(); let R_size = right_num_vars.pow2(); let default_blinds = PolyCommitmentBlinds { blinds: vec![Scalar::zero(); L_size], }; let blinds = blinds_opt.map_or(&default_blinds, |p| p); assert_eq!(blinds.blinds.len(), L_size); let zero = Scalar::zero(); let blind_Zr = blind_Zr_opt.map_or(&zero, |p| p); // compute the L and R vectors let eq = EqPolynomial::new(r.to_vec()); let (L, R) = eq.compute_factored_evals(); assert_eq!(L.len(), L_size); assert_eq!(R.len(), R_size); // compute the vector underneath L*Z and the L*blinds // compute vector-matrix product between L and Z viewed as a matrix let LZ = poly.bound(&L); let LZ_blind: Scalar = (0..L.len()).map(|i| blinds.blinds[i] * L[i]).sum(); // a dot product proof of size R_size let (proof, _C_LR, C_Zr_prime) = DotProductProofLog::prove( &gens.gens, transcript, random_tape, &LZ, &LZ_blind, &R, &Zr, blind_Zr, ); (PolyEvalProof { proof }, C_Zr_prime) } pub fn verify( &self, gens: &PolyCommitmentGens, transcript: &mut Transcript, r: &[Scalar], // point at which the polynomial is evaluated C_Zr: &CompressedGroup, // commitment to \widetilde{Z}(r) comm: &PolyCommitment, ) -> Result<(), ProofVerifyError> { transcript.append_protocol_name(PolyEvalProof::protocol_name()); // compute L and R let eq = EqPolynomial::new(r.to_vec()); let (L, R) = eq.compute_factored_evals(); // compute a weighted sum of commitments and L let C_decompressed = comm.C.iter().map(|pt| pt.decompress().unwrap()); let C_LZ = GroupElement::vartime_multiscalar_mul(&L, C_decompressed).compress(); self .proof .verify(R.len(), &gens.gens, transcript, &R, &C_LZ, C_Zr) } pub fn verify_plain( &self, gens: &PolyCommitmentGens, transcript: &mut Transcript, r: &[Scalar], // point at which the polynomial is evaluated Zr: &Scalar, // evaluation \widetilde{Z}(r) comm: &PolyCommitment, ) -> Result<(), ProofVerifyError> { // compute a commitment to Zr with a blind of zero let C_Zr = Zr.commit(&Scalar::zero(), &gens.gens.gens_1).compress(); self.verify(gens, transcript, r, &C_Zr, comm) } } #[cfg(test)] mod tests { use super::super::scalar::ScalarFromPrimitives; use super::*; use rand::rngs::OsRng; fn evaluate_with_LR(Z: &Vec<Scalar>, r: &Vec<Scalar>) -> Scalar { let eq = EqPolynomial::new(r.to_vec()); let (L, R) = eq.compute_factored_evals(); let ell = r.len(); // ensure ell is even assert!(ell % 2 == 0); // compute n = 2^\ell let n = ell.pow2(); // compute m = sqrt(n) = 2^{\ell/2} let m = n.square_root(); // compute vector-matrix product between L and Z viewed as a matrix let LZ = (0..m) .map(|i| (0..m).map(|j| L[j] * Z[j * m + i]).sum()) .collect::<Vec<Scalar>>(); // compute dot product between LZ and R DotProductProofLog::compute_dotproduct(&LZ, &R) } #[test] fn check_polynomial_evaluation() { let mut Z: Vec<Scalar> = Vec::new(); // Z = [1, 2, 1, 4] Z.push(Scalar::one()); Z.push((2 as usize).to_scalar()); Z.push((1 as usize).to_scalar()); Z.push((4 as usize).to_scalar()); // r = [4,3] let mut r: Vec<Scalar> = Vec::new(); r.push((4 as usize).to_scalar()); r.push((3 as usize).to_scalar()); let eval_with_LR = evaluate_with_LR(&Z, &r); let poly = DensePolynomial::new(Z); let eval = poly.evaluate(&r); assert_eq!(eval, (28 as usize).to_scalar()); assert_eq!(eval_with_LR, eval); } pub fn compute_factored_chis_at_r(r: &Vec<Scalar>) -> (Vec<Scalar>, Vec<Scalar>) { let mut L: Vec<Scalar> = Vec::new(); let mut R: Vec<Scalar> = Vec::new(); let ell = r.len(); assert!(ell % 2 == 0); // ensure ell is even let n = ell.pow2(); let m = n.square_root(); // compute row vector L for i in 0..m { let mut chi_i = Scalar::one(); for j in 0..ell / 2 { let bit_j = ((m * i) & (1 << (r.len() - j - 1))) > 0; if bit_j { chi_i *= r[j]; } else { chi_i *= Scalar::one() - r[j]; } } L.push(chi_i); } // compute column vector R for i in 0..m { let mut chi_i = Scalar::one(); for j in ell / 2..ell { let bit_j = (i & (1 << (r.len() - j - 1))) > 0; if bit_j { chi_i *= r[j]; } else { chi_i *= Scalar::one() - r[j]; } } R.push(chi_i); } (L, R) } pub fn compute_chis_at_r(r: &Vec<Scalar>) -> Vec<Scalar> { let ell = r.len(); let n = ell.pow2(); let mut chis: Vec<Scalar> = Vec::new(); for i in 0..n { let mut chi_i = Scalar::one(); for j in 0..r.len() { let bit_j = (i & (1 << (r.len() - j - 1))) > 0; if bit_j { chi_i *= r[j]; } else { chi_i *= Scalar::one() - r[j]; } } chis.push(chi_i); } chis } pub fn compute_outerproduct(L: Vec<Scalar>, R: Vec<Scalar>) -> Vec<Scalar> { assert_eq!(L.len(), R.len()); let mut O: Vec<Scalar> = Vec::new(); let m = L.len(); for i in 0..m { for j in 0..m { O.push(L[i] * R[j]); } } O } #[test] fn check_memoized_chis() { let mut csprng: OsRng = OsRng; let s = 10; let mut r: Vec<Scalar> = Vec::new(); for _i in 0..s { r.push(Scalar::random(&mut csprng)); } let chis = tests::compute_chis_at_r(&r); let chis_m = EqPolynomial::new(r).evals(); assert_eq!(chis, chis_m); } #[test] fn check_factored_chis() { let mut csprng: OsRng = OsRng; let s = 10; let mut r: Vec<Scalar> = Vec::new(); for _i in 0..s { r.push(Scalar::random(&mut csprng)); } let chis = EqPolynomial::new(r.clone()).evals(); let (L, R) = EqPolynomial::new(r).compute_factored_evals(); let O = compute_outerproduct(L, R); assert_eq!(chis, O); } #[test] fn check_memoized_factored_chis() { let mut csprng: OsRng = OsRng; let s = 10; let mut r: Vec<Scalar> = Vec::new(); for _i in 0..s { r.push(Scalar::random(&mut csprng)); } let (L, R) = tests::compute_factored_chis_at_r(&r); let eq = EqPolynomial::new(r); let (L2, R2) = eq.compute_factored_evals(); assert_eq!(L, L2); assert_eq!(R, R2); } #[test] fn check_polynomial_commit() { let mut Z: Vec<Scalar> = Vec::new(); // Z = [1, 2, 1, 4] Z.push((1 as usize).to_scalar()); Z.push((2 as usize).to_scalar()); Z.push((1 as usize).to_scalar()); Z.push((4 as usize).to_scalar()); let poly = DensePolynomial::new(Z); // r = [4,3] let mut r: Vec<Scalar> = Vec::new(); r.push((4 as usize).to_scalar()); r.push((3 as usize).to_scalar()); let eval = poly.evaluate(&r); assert_eq!(eval, (28 as usize).to_scalar()); let gens = PolyCommitmentGens::new(poly.get_num_vars(), b"test-two"); let (poly_commitment, blinds) = poly.commit(&gens, None); let mut random_tape = RandomTape::new(b"proof"); let mut prover_transcript = Transcript::new(b"example"); let (proof, C_Zr) = PolyEvalProof::prove( &poly, Some(&blinds), &r, &eval, None, &gens, &mut prover_transcript, &mut random_tape, ); let mut verifier_transcript = Transcript::new(b"example"); assert!(proof .verify(&gens, &mut verifier_transcript, &r, &C_Zr, &poly_commitment) .is_ok()); } }
27.414594
99
0.593068
d5209f8365cee5fe3bca6b914bf6e246da706e62
2,342
// Copyright 2021 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. use crate::{ component::Component, core::{Core, CoreContext, Object, ObjectRef, OnAdded, Property}, shapes::paint::{Color32, LinearGradient}, status_code::StatusCode, }; #[derive(Debug)] pub struct GradientStop { component: Component, color: Property<Color32>, position: Property<f32>, } impl ObjectRef<'_, GradientStop> { pub fn color(&self) -> Color32 { self.color.get() } pub fn set_color(&self, color: Color32) { if self.color() == color { return; } self.color.set(color); self.linear_gradient().as_ref().mark_gradient_dirty(); } pub fn position(&self) -> f32 { self.position.get() } pub fn set_position(&self, position: f32) { if self.position() == position { return; } self.position.set(position); self.linear_gradient().as_ref().mark_stops_dirty(); } } impl ObjectRef<'_, GradientStop> { fn linear_gradient(&self) -> Object<LinearGradient> { self.cast::<Component>().parent().expect("GradientStop should have a parent").cast() } } impl Core for GradientStop { parent_types![(component, Component)]; properties![(38, color, set_color), (39, position, set_position), component]; } impl OnAdded for ObjectRef<'_, GradientStop> { on_added!([on_added_clean, import], Component); fn on_added_dirty(&self, context: &dyn CoreContext) -> StatusCode { let component = self.cast::<Component>(); let code = component.on_added_dirty(context); if code != StatusCode::Ok { return code; } if let Some(linear_gradient) = component.parent().and_then(|parent| parent.try_cast::<LinearGradient>()) { linear_gradient.as_ref().push_stop(self.as_object()); StatusCode::Ok } else { StatusCode::MissingObject } } } impl Default for GradientStop { fn default() -> Self { Self { component: Component::default(), color: Property::new(Color32::from(0xFFFF_FFFF)), position: Property::new(0.0), } } }
26.022222
92
0.605892
c16f8f4df757a392b72a00c354431a95531242a3
8,333
use crate::commands::WholeStreamCommand; use crate::data::command_dict; use crate::prelude::*; use nu_errors::ShellError; use nu_protocol::{ NamedType, PositionalType, ReturnSuccess, Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, }; use nu_source::{SpannedItem, Tagged}; use nu_value_ext::get_data_by_key; pub struct Help; #[derive(Deserialize)] pub struct HelpArgs { command: Option<Tagged<String>>, } impl WholeStreamCommand for Help { fn name(&self) -> &str { "help" } fn signature(&self) -> Signature { Signature::build("help").optional( "command", SyntaxShape::String, "the name of command(s) to get help on", ) } fn usage(&self) -> &str { "Display help information about commands." } fn run( &self, args: CommandArgs, registry: &CommandRegistry, ) -> Result<OutputStream, ShellError> { args.process(registry, help)?.run() } } fn help( HelpArgs { command }: HelpArgs, RunnableContext { registry, name, .. }: RunnableContext, ) -> Result<OutputStream, ShellError> { if let Some(document) = command { let mut help = VecDeque::new(); if document.item == "commands" { let mut sorted_names = registry.names(); sorted_names.sort(); for cmd in sorted_names { let mut short_desc = TaggedDictBuilder::new(name.clone()); let document_tag = document.tag.clone(); let value = command_dict( registry.get_command(&cmd).ok_or_else(|| { ShellError::labeled_error( format!("Could not load {}", cmd), "could not load command", document_tag, ) })?, name.clone(), ); short_desc.insert_untagged("name", cmd); short_desc.insert_untagged( "description", get_data_by_key(&value, "usage".spanned_unknown()) .ok_or_else(|| { ShellError::labeled_error( "Expected a usage key", "expected a 'usage' key", &value.tag, ) })? .as_string()?, ); help.push_back(ReturnSuccess::value(short_desc.into_value())); } } else if let Some(command) = registry.get_command(&document.item) { return Ok(get_help(&command.name(), &command.usage(), command.signature()).into()); } else { return Err(ShellError::labeled_error( "Can't find command (use 'help commands' for full list)", "can't find command", document.tag, )); } let help = futures::stream::iter(help); Ok(help.to_output_stream()) } else { let msg = r#"Welcome to Nushell. Here are some tips to help you get started. * help commands - list all available commands * help <command name> - display help about a particular command Nushell works on the idea of a "pipeline". Pipelines are commands connected with the '|' character. Each stage in the pipeline works together to load, parse, and display information to you. [Examples] List the files in the current directory, sorted by size: ls | sort-by size Get information about the current system: sys | get host Get the processes on your system actively using CPU: ps | where cpu > 0 You can also learn more at https://www.nushell.sh/book/"#; let output_stream = futures::stream::iter(vec![ReturnSuccess::value( UntaggedValue::string(msg).into_value(name), )]); Ok(output_stream.to_output_stream()) } } pub(crate) fn get_help( cmd_name: &str, cmd_usage: &str, cmd_sig: Signature, ) -> impl Into<OutputStream> { let mut help = VecDeque::new(); let mut long_desc = String::new(); long_desc.push_str(&cmd_usage); long_desc.push_str("\n"); let signature = cmd_sig; let mut one_liner = String::new(); one_liner.push_str(&signature.name); one_liner.push_str(" "); for positional in &signature.positional { match &positional.0 { PositionalType::Mandatory(name, _m) => { one_liner.push_str(&format!("<{}> ", name)); } PositionalType::Optional(name, _o) => { one_liner.push_str(&format!("({}) ", name)); } } } if signature.rest_positional.is_some() { one_liner.push_str(" ...args"); } if !signature.named.is_empty() { one_liner.push_str("{flags} "); } long_desc.push_str(&format!("\nUsage:\n > {}\n", one_liner)); if !signature.positional.is_empty() || signature.rest_positional.is_some() { long_desc.push_str("\nparameters:\n"); for positional in signature.positional { match positional.0 { PositionalType::Mandatory(name, _m) => { long_desc.push_str(&format!(" <{}> {}\n", name, positional.1)); } PositionalType::Optional(name, _o) => { long_desc.push_str(&format!(" ({}) {}\n", name, positional.1)); } } } if let Some(rest_positional) = signature.rest_positional { long_desc.push_str(&format!(" ...args: {}\n", rest_positional.1)); } } if !signature.named.is_empty() { long_desc.push_str("\nflags:\n"); for (flag, ty) in signature.named { let msg = match ty.0 { NamedType::Switch(s) => { if let Some(c) = s { format!( " -{}, --{}{} {}\n", c, flag, if !ty.1.is_empty() { ":" } else { "" }, ty.1 ) } else { format!( " --{}{} {}\n", flag, if !ty.1.is_empty() { ":" } else { "" }, ty.1 ) } } NamedType::Mandatory(s, m) => { if let Some(c) = s { format!( " -{}, --{} <{}> (required parameter){} {}\n", c, flag, m.display(), if !ty.1.is_empty() { ":" } else { "" }, ty.1 ) } else { format!( " --{} <{}> (required parameter){} {}\n", flag, m.display(), if !ty.1.is_empty() { ":" } else { "" }, ty.1 ) } } NamedType::Optional(s, o) => { if let Some(c) = s { format!( " -{}, --{} <{}>{} {}\n", c, flag, o.display(), if !ty.1.is_empty() { ":" } else { "" }, ty.1 ) } else { format!( " --{} <{}>{} {}\n", flag, o.display(), if !ty.1.is_empty() { ":" } else { "" }, ty.1 ) } } }; long_desc.push_str(&msg); } } help.push_back(ReturnSuccess::value( UntaggedValue::string(long_desc).into_value(Tag::from((0, cmd_name.len(), None))), )); help }
32.807087
99
0.441378
9bf1c1e167d2fb1d3eaaed8e8ea65930c6bd327e
1,927
#[allow(unused_imports)] use serde_json::Value; #[allow(unused_imports)] use std::borrow::Borrow; #[allow(unused_imports)] use super::*; #[derive(Debug, Default, Serialize, Deserialize, PartialEq)] pub struct r#PasswordPolicy { #[serde(rename = "conditions", skip_serializing_if = "Option::is_none")] r#conditions: Option<PasswordPolicyConditions>, #[serde(rename = "settings", skip_serializing_if = "Option::is_none")] r#settings: Option<PasswordPolicySettings>, } impl r#PasswordPolicy { pub fn new( ) -> Self { Self { r#conditions: None, r#settings: None, } } pub fn set_conditions(&mut self, r#conditions: PasswordPolicyConditions) { self.r#conditions = Some(r#conditions); } pub fn with_conditions(mut self, r#conditions: PasswordPolicyConditions) -> Self { self.r#conditions = Some(r#conditions); self } pub fn with_option_conditions(mut self, r#conditions: Option<PasswordPolicyConditions>) -> Self { self.r#conditions = r#conditions; self } pub fn r#conditions(&self) -> Option<&PasswordPolicyConditions> { self.r#conditions.as_ref().map(|x| x.borrow()) } pub fn reset_conditions(&mut self) { self.r#conditions = None; } pub fn set_settings(&mut self, r#settings: PasswordPolicySettings) { self.r#settings = Some(r#settings); } pub fn with_settings(mut self, r#settings: PasswordPolicySettings) -> Self { self.r#settings = Some(r#settings); self } pub fn with_option_settings(mut self, r#settings: Option<PasswordPolicySettings>) -> Self { self.r#settings = r#settings; self } pub fn r#settings(&self) -> Option<&PasswordPolicySettings> { self.r#settings.as_ref().map(|x| x.borrow()) } pub fn reset_settings(&mut self) { self.r#settings = None; } }
27.140845
101
0.640893
d6479b0dcb7e43f2e60a66b6e60f9cd8aa6d9493
52
pub mod ws_msg; pub mod rest_msg; pub mod mongo_msg;
17.333333
18
0.788462
016cab88860c9fd11f927ebe9e791c379f1c8ea9
7,934
/// Canonical module and id type /// /// /core/Str /// /core/<Option T> use crate::leema::failure::Lresult; use crate::leema::lstr::Lstr; use crate::leema::sendclone; use std::ffi::OsStr; use std::fmt; use std::path::{Path, PathBuf}; #[macro_export] macro_rules! canonical { ($c:expr) => { crate::leema::canonical::Canonical::new(crate::leema::lstr::Lstr::Sref( $c, )) }; } // imported path pub enum Impath { Absolute, Sibling, Child, Local(&'static Impath, &'static str), Exported(&'static Impath, &'static str), } #[derive(Clone)] #[derive(PartialEq)] #[derive(PartialOrd)] #[derive(Eq)] #[derive(Ord)] #[derive(Hash)] pub struct Canonical(Lstr); impl Canonical { pub const DEFAULT: Canonical = canonical!("_"); pub const fn new(c: Lstr) -> Canonical { Canonical(c) } /// Check if this module is a core module pub fn is_core(&self) -> bool { // convert to a path which knows not to match /core to /corebad self.as_path().starts_with("/core") } pub fn as_path(&self) -> &Path { Path::new(self.0.as_str()) } /// convert this canonical to an Lstr pub fn to_lstr(&self) -> Lstr { self.0.clone() } /// add an identifier to an existing canonical /// fails if sub is Absolute pub fn join<S>(&self, sub: S) -> Lresult<Canonical> where S: AsRef<OsStr> + std::fmt::Debug, { let subpath = Path::new(sub.as_ref()); if subpath.is_absolute() { return Err(rustfail!( "leema_failure", "cannot join an absolute path: {:?}", sub, )); } else if subpath.starts_with("../") { let sib_base = self.as_path().parent().unwrap(); let sib_path = subpath.strip_prefix("../").unwrap(); // recursing in here would be good to allow multiple ../ let sib = sib_base.join(sib_path); Ok(Canonical::new(Lstr::from(format!("{}", sib.display())))) } else { let ch_path = self.as_path().join(subpath); Ok(Canonical::new(Lstr::from(format!("{}", ch_path.display())))) } } /// split the final .extension element off the end of Canonical pub fn split_function(&self) -> Option<(Canonical, Lstr)> { match self.0 { Lstr::Sref(ss) => { let mut ssplit = ss.rsplitn(2, "."); let sfunc = ssplit.next().unwrap(); let smodule = ssplit.next()?; Some((Canonical::new(Lstr::Sref(smodule)), Lstr::Sref(sfunc))) } Lstr::Arc(ref s) => { let mut split = s.rsplitn(2, "."); let func = split.next().unwrap(); let module = split.next()?; Some(( Canonical::new(Lstr::from(module.to_string())), Lstr::from(func.to_string()), )) } ref other => { panic!("not a normal Lstr: {:?}", other); } } } /// split the final module element off the end of Canonical pub fn last_module(&self) -> Option<Lstr> { match self.0 { Lstr::Sref(ss) => { let mut ssplit = ss.rsplitn(2, "/"); let smod = ssplit.next()?; ssplit.next()?; Some(Lstr::Sref(smod)) } Lstr::Arc(ref s) => { let mut split = s.rsplitn(2, "/"); let module = split.next()?; split.next()?; Some(Lstr::from(module.to_string())) } ref other => { panic!("not a normal Lstr: {:?}", other); } } } /// get the Lstr out of the Canonical pub fn as_lstr(&self) -> &Lstr { &self.0 } /// get the str out of the Canonical pub fn as_str(&self) -> &str { self.0.as_str() } pub fn ancestors(path: &Path) -> Vec<&Path> { let av: Vec<&Path> = path.ancestors().collect(); av.into_iter() .rev() .skip(1) .map(|p| { // extensions should be trimmed // is there a way to only do this for the final path // since it's the only one that will ever have an extension? let xlen = match p.extension() { Some(x) => x.len() + 1, None => { return p; } }; let pstr = p.as_os_str().to_str().unwrap(); let (base, _) = pstr.split_at(pstr.len() - xlen); Path::new(base) }) .collect() } pub fn file_path_buf(cpath: &Path) -> Lresult<PathBuf> { cpath .strip_prefix("/") .map(|relative_path| relative_path.with_extension("lma")) .map_err(|path_err| { rustfail!( "load_fail", "unexpected lack of root prefix in {} - error {}", cpath.display(), path_err, ) }) } } impl From<&Path> for Canonical { fn from(cp: &Path) -> Canonical { if !cp.is_absolute() { panic!("canonical must be absolute: {:?}", cp); } let cstr: String = cp.to_str().expect("expected unicode path").to_string(); Canonical(Lstr::from(cstr)) } } impl From<PathBuf> for Canonical { fn from(cp: PathBuf) -> Canonical { if !cp.is_absolute() { panic!("canonical must be absolute: {:?}", cp); } let cstr: String = cp.to_str().expect("expected unicode path").to_string(); Canonical(Lstr::from(cstr)) } } impl PartialEq<Canonical> for str { fn eq(&self, other: &Canonical) -> bool { self == other.0.as_str() } } impl AsRef<str> for Canonical { fn as_ref(&self) -> &str { self.0.as_str() } } impl Default for Canonical { fn default() -> Canonical { Canonical::DEFAULT } } impl fmt::Display for Canonical { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } impl fmt::Debug for Canonical { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } impl sendclone::SendClone for Canonical { type Item = Canonical; fn clone_for_send(&self) -> Canonical { Canonical(self.0.clone_for_send()) } } #[cfg(test)] mod tests { use super::Canonical; use crate::leema::lstr::Lstr; use std::path::Path; #[test] fn test_canonical_ancestors() { let a = Canonical::ancestors(Path::new("/foo/bar/baz")); let mut it = a.iter(); assert_eq!("/foo", it.next().unwrap().as_os_str()); assert_eq!("/foo/bar", it.next().unwrap().as_os_str()); assert_eq!("/foo/bar/baz", it.next().unwrap().as_os_str()); assert_eq!(3, a.len()); } #[test] fn test_canonical_push_sibling() { let cm = Canonical(Lstr::from("/foo/bar")); let result = cm.join(&Path::new("../taco")).unwrap(); assert_eq!("/foo/taco", result.0.str()); } #[test] fn test_canonical_split_id_arc() { let ct = Canonical(Lstr::from("/taco.burrito".to_string())); let (m, t) = ct.split_function().unwrap(); assert_eq!("/taco", m.0.str()); assert_eq!("burrito", t.str()); } #[test] fn test_canonical_split_id_sref() { let ct = Canonical(Lstr::from("/taco.burrito")); let (m, t) = ct.split_function().unwrap(); assert_eq!("/taco", m.0.str()); assert_eq!("burrito", t.str()); } }
25.348243
79
0.495715
db9c7c30899747306d4fa24b0a4262bf4473b280
57,702
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::path::Path; use std::sync::*; use std::thread; use std::time::Duration; use futures::{executor::block_on, future, SinkExt, StreamExt, TryStreamExt}; use grpcio::*; use grpcio_health::proto::HealthCheckRequest; use grpcio_health::*; use tempfile::Builder; use kvproto::{ coprocessor::*, debugpb, kvrpcpb::{self, *}, metapb, raft_serverpb, raft_serverpb::*, tikvpb::*, }; use raft::eraftpb; use concurrency_manager::ConcurrencyManager; use engine_rocks::{raw::Writable, Compat}; use engine_traits::{MiscExt, Peekable, SyncMutable, CF_DEFAULT, CF_LOCK, CF_RAFT, CF_WRITE}; use pd_client::PdClient; use raftstore::coprocessor::CoprocessorHost; use raftstore::store::{fsm::store::StoreMeta, AutoSplitController, SnapManager}; use test_raftstore::*; use tikv::coprocessor::REQ_TYPE_DAG; use tikv::import::Config as ImportConfig; use tikv::import::SSTImporter; use tikv::server; use tikv::server::gc_worker::sync_gc; use tikv::server::service::{batch_commands_request, batch_commands_response}; use tikv_util::worker::{dummy_scheduler, FutureWorker}; use tikv_util::HandyRwLock; use txn_types::{Key, Lock, LockType, TimeStamp}; #[test] fn test_rawkv() { let (_cluster, client, ctx) = must_new_cluster_and_kv_client(); let v0 = b"v0".to_vec(); let v1 = b"v1".to_vec(); let (k, v) = (b"key".to_vec(), b"v2".to_vec()); // Raw cas let mut cas_req = RawCasRequest::default(); cas_req.set_context(ctx.clone()); cas_req.key = k.clone(); cas_req.value = v0.clone(); cas_req.previous_not_exist = true; let resp = client.raw_compare_and_swap(&cas_req).unwrap(); assert!(!resp.has_region_error()); assert!(resp.get_succeed()); // Raw get let mut get_req = RawGetRequest::default(); get_req.set_context(ctx.clone()); get_req.key = k.clone(); let get_resp = client.raw_get(&get_req).unwrap(); assert_eq!(get_resp.value, v0); cas_req.value = v1.clone(); cas_req.previous_not_exist = false; cas_req.previous_value = v0; let resp = client.raw_compare_and_swap(&cas_req).unwrap(); assert!(resp.get_succeed()); let get_resp = client.raw_get(&get_req).unwrap(); assert_eq!(get_resp.value, v1); // Raw put let mut put_req = RawPutRequest::default(); put_req.set_context(ctx.clone()); put_req.key = k.clone(); put_req.value = v.clone(); let put_resp = client.raw_put(&put_req).unwrap(); assert!(!put_resp.has_region_error()); assert!(put_resp.error.is_empty()); // Raw get let get_resp = client.raw_get(&get_req).unwrap(); assert!(!get_resp.has_region_error()); assert!(get_resp.error.is_empty()); assert_eq!(get_resp.value, v); // Raw scan let mut scan_req = RawScanRequest::default(); scan_req.set_context(ctx.clone()); scan_req.start_key = k.clone(); scan_req.limit = 1; let scan_resp = client.raw_scan(&scan_req).unwrap(); assert!(!scan_resp.has_region_error()); assert_eq!(scan_resp.kvs.len(), 1); for kv in scan_resp.kvs.into_iter() { assert!(!kv.has_error()); assert_eq!(kv.key, k); assert_eq!(kv.value, v); } // Raw delete let mut delete_req = RawDeleteRequest::default(); delete_req.set_context(ctx); delete_req.key = k; let delete_resp = client.raw_delete(&delete_req).unwrap(); assert!(!delete_resp.has_region_error()); assert!(delete_resp.error.is_empty()); } #[test] fn test_rawkv_ttl() { let (cluster, leader, ctx) = must_new_and_configure_cluster(|cluster| { cluster.cfg.storage.enable_ttl = true; }); let env = Arc::new(Environment::new(1)); let leader_store = leader.get_store_id(); let channel = ChannelBuilder::new(env).connect(&cluster.sim.rl().get_addr(leader_store)); let client = TikvClient::new(channel); let (v0, v1) = (b"v0".to_vec(), b"v1".to_vec()); let (k, v) = (b"key".to_vec(), b"v2".to_vec()); // Raw cas let mut cas_req = RawCasRequest::default(); cas_req.set_context(ctx.clone()); cas_req.key = k.clone(); cas_req.value = v0.clone(); cas_req.previous_not_exist = false; cas_req.previous_value = v1.clone(); let resp = client.raw_compare_and_swap(&cas_req).unwrap(); assert!(!resp.has_region_error()); assert!(!resp.get_succeed()); let mut cas_req = RawCasRequest::default(); cas_req.set_context(ctx.clone()); cas_req.key = k.clone(); cas_req.value = v0.clone(); cas_req.previous_not_exist = true; cas_req.previous_value = vec![]; cas_req.ttl = 100; let resp = client.raw_compare_and_swap(&cas_req).unwrap(); assert!(!resp.has_region_error()); assert!(resp.get_succeed()); // Raw get let mut get_req = RawGetRequest::default(); get_req.set_context(ctx.clone()); get_req.key = k.clone(); let get_resp = client.raw_get(&get_req).unwrap(); assert!(!get_resp.has_region_error()); assert_eq!(get_resp.value, v0); // cas a new value cas_req.value = v1.clone(); cas_req.previous_not_exist = false; cas_req.previous_value = v0; cas_req.ttl = 140; let resp = client.raw_compare_and_swap(&cas_req).unwrap(); assert!(resp.get_succeed()); let get_resp = client.raw_get(&get_req).unwrap(); assert_eq!(get_resp.value, v1); let mut get_ttl_req = RawGetKeyTtlRequest::default(); get_ttl_req.set_context(ctx.clone()); get_ttl_req.key = k.clone(); let get_ttl_resp = client.raw_get_key_ttl(&get_ttl_req).unwrap(); assert!(!get_ttl_resp.has_region_error()); assert!(get_ttl_resp.error.is_empty()); assert!(get_ttl_resp.ttl > 100); let mut delete_req = RawDeleteRequest::default(); delete_req.set_context(ctx.clone()); delete_req.key = k.clone(); let delete_resp = client.raw_delete(&delete_req).unwrap(); assert!(!delete_resp.has_region_error()); let get_ttl_resp = client.raw_get_key_ttl(&get_ttl_req).unwrap(); assert!(!get_ttl_resp.has_region_error()); assert!(get_ttl_resp.get_not_found()); // Raw put let mut put_req = RawPutRequest::default(); put_req.set_context(ctx.clone()); put_req.key = k.clone(); put_req.value = v.clone(); put_req.ttl = 100; let put_resp = client.raw_put(&put_req).unwrap(); assert!(!put_resp.has_region_error()); assert!(put_resp.error.is_empty()); let get_resp = client.raw_get(&get_req).unwrap(); assert!(!get_resp.has_region_error()); assert!(get_resp.error.is_empty()); assert_eq!(get_resp.value, v); // Raw scan let mut scan_req = RawScanRequest::default(); scan_req.set_context(ctx.clone()); scan_req.start_key = k.clone(); scan_req.limit = 1; let scan_resp = client.raw_scan(&scan_req).unwrap(); assert!(!scan_resp.has_region_error()); assert_eq!(scan_resp.kvs.len(), 1); for kv in scan_resp.kvs.into_iter() { assert!(!kv.has_error()); assert_eq!(kv.key, k); assert_eq!(kv.value, v); } // Raw get key ttl let get_ttl_resp = client.raw_get_key_ttl(&get_ttl_req).unwrap(); assert!(!get_ttl_resp.has_region_error()); assert!(get_ttl_resp.error.is_empty()); assert_ne!(get_ttl_resp.ttl, 0); // Raw delete let mut delete_req = RawDeleteRequest::default(); delete_req.set_context(ctx.clone()); delete_req.key = k.clone(); let delete_resp = client.raw_delete(&delete_req).unwrap(); assert!(!delete_resp.has_region_error()); assert!(delete_resp.error.is_empty()); // Raw get key ttl let mut get_ttl_req = RawGetKeyTtlRequest::default(); get_ttl_req.set_context(ctx.clone()); get_ttl_req.key = k.clone(); let get_ttl_resp = client.raw_get_key_ttl(&get_ttl_req).unwrap(); assert!(!get_ttl_resp.has_region_error()); assert!(get_ttl_resp.error.is_empty()); assert!(get_ttl_resp.not_found); assert_eq!(get_ttl_resp.ttl, 0); // Raw put and exceed ttl let mut put_req = RawPutRequest::default(); put_req.set_context(ctx.clone()); put_req.key = k.clone(); put_req.value = v; put_req.ttl = 1; let put_resp = client.raw_put(&put_req).unwrap(); assert!(!put_resp.has_region_error()); assert!(put_resp.error.is_empty()); std::thread::sleep(Duration::from_secs(1)); let mut get_req = RawGetRequest::default(); get_req.set_context(ctx); get_req.key = k; let get_resp = client.raw_get(&get_req).unwrap(); assert!(!get_resp.has_region_error()); assert!(get_resp.error.is_empty()); assert!(get_resp.value.is_empty()); } #[test] fn test_mvcc_basic() { let (_cluster, client, ctx) = must_new_cluster_and_kv_client(); let (k, v) = (b"key".to_vec(), b"value".to_vec()); let mut ts = 0; // Prewrite ts += 1; let prewrite_start_version = ts; let mut mutation = Mutation::default(); mutation.set_op(Op::Put); mutation.set_key(k.clone()); mutation.set_value(v.clone()); must_kv_prewrite( &client, ctx.clone(), vec![mutation], k.clone(), prewrite_start_version, ); // Commit ts += 1; let commit_version = ts; must_kv_commit( &client, ctx.clone(), vec![k.clone()], prewrite_start_version, commit_version, commit_version, ); // Get ts += 1; let get_version = ts; let mut get_req = GetRequest::default(); get_req.set_context(ctx.clone()); get_req.key = k.clone(); get_req.version = get_version; let get_resp = client.kv_get(&get_req).unwrap(); assert!(!get_resp.has_region_error()); assert!(!get_resp.has_error()); assert!(get_resp.get_exec_details_v2().has_time_detail()); let scan_detail_v2 = get_resp.get_exec_details_v2().get_scan_detail_v2(); assert_eq!(scan_detail_v2.get_total_versions(), 1); assert_eq!(scan_detail_v2.get_processed_versions(), 1); assert!(scan_detail_v2.get_processed_versions_size() > 0); assert_eq!(get_resp.value, v); // Scan ts += 1; let scan_version = ts; let mut scan_req = ScanRequest::default(); scan_req.set_context(ctx.clone()); scan_req.start_key = k.clone(); scan_req.limit = 1; scan_req.version = scan_version; let scan_resp = client.kv_scan(&scan_req).unwrap(); assert!(!scan_resp.has_region_error()); assert_eq!(scan_resp.pairs.len(), 1); for kv in scan_resp.pairs.into_iter() { assert!(!kv.has_error()); assert_eq!(kv.key, k); assert_eq!(kv.value, v); } // Batch get ts += 1; let batch_get_version = ts; let mut batch_get_req = BatchGetRequest::default(); batch_get_req.set_context(ctx); batch_get_req.set_keys(vec![k.clone()].into_iter().collect()); batch_get_req.version = batch_get_version; let batch_get_resp = client.kv_batch_get(&batch_get_req).unwrap(); assert!(batch_get_resp.get_exec_details_v2().has_time_detail()); let scan_detail_v2 = batch_get_resp.get_exec_details_v2().get_scan_detail_v2(); assert_eq!(scan_detail_v2.get_total_versions(), 1); assert_eq!(scan_detail_v2.get_processed_versions(), 1); assert!(scan_detail_v2.get_processed_versions_size() > 0); assert_eq!(batch_get_resp.pairs.len(), 1); for kv in batch_get_resp.pairs.into_iter() { assert!(!kv.has_error()); assert_eq!(kv.key, k); assert_eq!(kv.value, v); } } #[test] fn test_mvcc_rollback_and_cleanup() { let (_cluster, client, ctx) = must_new_cluster_and_kv_client(); let (k, v) = (b"key".to_vec(), b"value".to_vec()); let mut ts = 0; // Prewrite ts += 1; let prewrite_start_version = ts; let mut mutation = Mutation::default(); mutation.set_op(Op::Put); mutation.set_key(k.clone()); mutation.set_value(v); must_kv_prewrite( &client, ctx.clone(), vec![mutation], k.clone(), prewrite_start_version, ); // Commit ts += 1; let commit_version = ts; must_kv_commit( &client, ctx.clone(), vec![k.clone()], prewrite_start_version, commit_version, commit_version, ); // Prewrite puts some locks. ts += 1; let prewrite_start_version2 = ts; let (k2, v2) = (b"key2".to_vec(), b"value2".to_vec()); let mut mut_pri = Mutation::default(); mut_pri.set_op(Op::Put); mut_pri.set_key(k2.clone()); mut_pri.set_value(v2); let mut mut_sec = Mutation::default(); mut_sec.set_op(Op::Put); mut_sec.set_key(k.clone()); mut_sec.set_value(b"foo".to_vec()); must_kv_prewrite( &client, ctx.clone(), vec![mut_pri, mut_sec], k2.clone(), prewrite_start_version2, ); // Scan lock, expects locks ts += 1; let scan_lock_max_version = ts; let mut scan_lock_req = ScanLockRequest::default(); scan_lock_req.set_context(ctx.clone()); scan_lock_req.max_version = scan_lock_max_version; let scan_lock_resp = client.kv_scan_lock(&scan_lock_req).unwrap(); assert!(!scan_lock_resp.has_region_error()); assert_eq!(scan_lock_resp.locks.len(), 2); for (lock, key) in scan_lock_resp .locks .into_iter() .zip(vec![k.clone(), k2.clone()]) { assert_eq!(lock.primary_lock, k2); assert_eq!(lock.key, key); assert_eq!(lock.lock_version, prewrite_start_version2); } // Rollback let rollback_start_version = prewrite_start_version2; let mut rollback_req = BatchRollbackRequest::default(); rollback_req.set_context(ctx.clone()); rollback_req.start_version = rollback_start_version; rollback_req.set_keys(vec![k2.clone()].into_iter().collect()); let rollback_resp = client.kv_batch_rollback(&rollback_req).unwrap(); assert!(!rollback_resp.has_region_error()); assert!(!rollback_resp.has_error()); rollback_req.set_keys(vec![k].into_iter().collect()); let rollback_resp2 = client.kv_batch_rollback(&rollback_req).unwrap(); assert!(!rollback_resp2.has_region_error()); assert!(!rollback_resp2.has_error()); // Cleanup let cleanup_start_version = prewrite_start_version2; let mut cleanup_req = CleanupRequest::default(); cleanup_req.set_context(ctx.clone()); cleanup_req.start_version = cleanup_start_version; cleanup_req.set_key(k2); let cleanup_resp = client.kv_cleanup(&cleanup_req).unwrap(); assert!(!cleanup_resp.has_region_error()); assert!(!cleanup_resp.has_error()); // There should be no locks ts += 1; let scan_lock_max_version2 = ts; let mut scan_lock_req = ScanLockRequest::default(); scan_lock_req.set_context(ctx); scan_lock_req.max_version = scan_lock_max_version2; let scan_lock_resp = client.kv_scan_lock(&scan_lock_req).unwrap(); assert!(!scan_lock_resp.has_region_error()); assert_eq!(scan_lock_resp.locks.len(), 0); } #[test] fn test_mvcc_resolve_lock_gc_and_delete() { use kvproto::kvrpcpb::*; let (cluster, client, ctx) = must_new_cluster_and_kv_client(); let (k, v) = (b"key".to_vec(), b"value".to_vec()); let mut ts = 0; // Prewrite ts += 1; let prewrite_start_version = ts; let mut mutation = Mutation::default(); mutation.set_op(Op::Put); mutation.set_key(k.clone()); mutation.set_value(v); must_kv_prewrite( &client, ctx.clone(), vec![mutation], k.clone(), prewrite_start_version, ); // Commit ts += 1; let commit_version = ts; must_kv_commit( &client, ctx.clone(), vec![k.clone()], prewrite_start_version, commit_version, commit_version, ); // Prewrite puts some locks. ts += 1; let prewrite_start_version2 = ts; let (k2, v2) = (b"key2".to_vec(), b"value2".to_vec()); let new_v = b"new value".to_vec(); let mut mut_pri = Mutation::default(); mut_pri.set_op(Op::Put); mut_pri.set_key(k.clone()); mut_pri.set_value(new_v.clone()); let mut mut_sec = Mutation::default(); mut_sec.set_op(Op::Put); mut_sec.set_key(k2); mut_sec.set_value(v2); must_kv_prewrite( &client, ctx.clone(), vec![mut_pri, mut_sec], k.clone(), prewrite_start_version2, ); // Resolve lock ts += 1; let resolve_lock_commit_version = ts; let mut resolve_lock_req = ResolveLockRequest::default(); let mut temp_txninfo = TxnInfo::default(); temp_txninfo.txn = prewrite_start_version2; temp_txninfo.status = resolve_lock_commit_version; let vec_txninfo = vec![temp_txninfo]; resolve_lock_req.set_context(ctx.clone()); resolve_lock_req.set_txn_infos(vec_txninfo.into()); let resolve_lock_resp = client.kv_resolve_lock(&resolve_lock_req).unwrap(); assert!(!resolve_lock_resp.has_region_error()); assert!(!resolve_lock_resp.has_error()); // Get `k` at the latest ts. ts += 1; let get_version1 = ts; let mut get_req1 = GetRequest::default(); get_req1.set_context(ctx.clone()); get_req1.key = k.clone(); get_req1.version = get_version1; let get_resp1 = client.kv_get(&get_req1).unwrap(); assert!(!get_resp1.has_region_error()); assert!(!get_resp1.has_error()); assert_eq!(get_resp1.value, new_v); // GC `k` at the latest ts. ts += 1; let gc_safe_ponit = TimeStamp::from(ts); let gc_scheduler = cluster.sim.rl().get_gc_worker(1).scheduler(); sync_gc(&gc_scheduler, 0, vec![], vec![], gc_safe_ponit).unwrap(); // the `k` at the old ts should be none. let get_version2 = commit_version + 1; let mut get_req2 = GetRequest::default(); get_req2.set_context(ctx.clone()); get_req2.key = k.clone(); get_req2.version = get_version2; let get_resp2 = client.kv_get(&get_req2).unwrap(); assert!(!get_resp2.has_region_error()); assert!(!get_resp2.has_error()); assert_eq!(get_resp2.value, b"".to_vec()); // Transaction debugger commands // MvccGetByKey let mut mvcc_get_by_key_req = MvccGetByKeyRequest::default(); mvcc_get_by_key_req.set_context(ctx.clone()); mvcc_get_by_key_req.key = k.clone(); let mvcc_get_by_key_resp = client.mvcc_get_by_key(&mvcc_get_by_key_req).unwrap(); assert!(!mvcc_get_by_key_resp.has_region_error()); assert!(mvcc_get_by_key_resp.error.is_empty()); assert!(mvcc_get_by_key_resp.has_info()); // MvccGetByStartTs let mut mvcc_get_by_start_ts_req = MvccGetByStartTsRequest::default(); mvcc_get_by_start_ts_req.set_context(ctx.clone()); mvcc_get_by_start_ts_req.start_ts = prewrite_start_version2; let mvcc_get_by_start_ts_resp = client .mvcc_get_by_start_ts(&mvcc_get_by_start_ts_req) .unwrap(); assert!(!mvcc_get_by_start_ts_resp.has_region_error()); assert!(mvcc_get_by_start_ts_resp.error.is_empty()); assert!(mvcc_get_by_start_ts_resp.has_info()); assert_eq!(mvcc_get_by_start_ts_resp.key, k); // Delete range let mut del_req = DeleteRangeRequest::default(); del_req.set_context(ctx); del_req.start_key = b"a".to_vec(); del_req.end_key = b"z".to_vec(); let del_resp = client.kv_delete_range(&del_req).unwrap(); assert!(!del_resp.has_region_error()); assert!(del_resp.error.is_empty()); } // raft related RPC is tested as parts of test_snapshot.rs, so skip here. #[test] fn test_coprocessor() { let (_cluster, client, _) = must_new_cluster_and_kv_client(); // SQL push down commands let mut req = Request::default(); req.set_tp(REQ_TYPE_DAG); client.coprocessor(&req).unwrap(); } #[test] fn test_split_region() { let (mut cluster, client, ctx) = must_new_cluster_and_kv_client(); // Split region commands let key = b"b"; let mut req = SplitRegionRequest::default(); req.set_context(ctx); req.set_split_key(key.to_vec()); let resp = client.split_region(&req).unwrap(); assert_eq!( Key::from_encoded(resp.get_left().get_end_key().to_vec()) .into_raw() .unwrap() .as_slice(), key ); assert_eq!( resp.get_left().get_end_key(), resp.get_right().get_start_key() ); // Batch split region let region_id = resp.get_right().get_id(); let leader = cluster.leader_of_region(region_id).unwrap(); let mut ctx = Context::default(); ctx.set_region_id(region_id); ctx.set_peer(leader); ctx.set_region_epoch(resp.get_right().get_region_epoch().to_owned()); let mut req = SplitRegionRequest::default(); req.set_context(ctx); let split_keys = vec![b"e".to_vec(), b"c".to_vec(), b"d".to_vec()]; req.set_split_keys(split_keys.into()); let resp = client.split_region(&req).unwrap(); let result_split_keys: Vec<_> = resp .get_regions() .iter() .map(|x| { Key::from_encoded(x.get_start_key().to_vec()) .into_raw() .unwrap() }) .collect(); assert_eq!( result_split_keys, vec![b"b".to_vec(), b"c".to_vec(), b"d".to_vec(), b"e".to_vec()] ); } #[test] fn test_read_index() { let (_cluster, client, ctx) = must_new_cluster_and_kv_client(); // Read index let mut req = ReadIndexRequest::default(); req.set_context(ctx.clone()); let mut resp = client.read_index(&req).unwrap(); let last_index = resp.get_read_index(); assert_eq!(last_index > 0, true); // Raw put let (k, v) = (b"key".to_vec(), b"value".to_vec()); let mut put_req = RawPutRequest::default(); put_req.set_context(ctx); put_req.key = k; put_req.value = v; let put_resp = client.raw_put(&put_req).unwrap(); assert!(!put_resp.has_region_error()); assert!(put_resp.error.is_empty()); // Read index again resp = client.read_index(&req).unwrap(); assert_eq!(last_index + 1, resp.get_read_index()); } #[test] fn test_debug_get() { let (cluster, debug_client, store_id) = must_new_cluster_and_debug_client(); let (k, v) = (b"key", b"value"); // Put some data. let engine = cluster.get_engine(store_id); let key = keys::data_key(k); engine.put(&key, v).unwrap(); assert_eq!(engine.get(&key).unwrap().unwrap(), v); // Debug get let mut req = debugpb::GetRequest::default(); req.set_cf(CF_DEFAULT.to_owned()); req.set_db(debugpb::Db::Kv); req.set_key(key); let mut resp = debug_client.get(&req).unwrap(); assert_eq!(resp.take_value(), v); req.set_key(b"foo".to_vec()); match debug_client.get(&req).unwrap_err() { Error::RpcFailure(status) => { assert_eq!(status.code(), RpcStatusCode::NOT_FOUND); } _ => panic!("expect NotFound"), } } #[test] fn test_debug_raft_log() { let (cluster, debug_client, store_id) = must_new_cluster_and_debug_client(); // Put some data. let engine = cluster.get_raft_engine(store_id); let (region_id, log_index) = (200, 200); let key = keys::raft_log_key(region_id, log_index); let mut entry = eraftpb::Entry::default(); entry.set_term(1); entry.set_index(1); entry.set_entry_type(eraftpb::EntryType::EntryNormal); entry.set_data(vec![42].into()); engine.c().put_msg(&key, &entry).unwrap(); assert_eq!( engine.c().get_msg::<eraftpb::Entry>(&key).unwrap().unwrap(), entry ); // Debug raft_log let mut req = debugpb::RaftLogRequest::default(); req.set_region_id(region_id); req.set_log_index(log_index); let resp = debug_client.raft_log(&req).unwrap(); assert_ne!(resp.get_entry(), &eraftpb::Entry::default()); let mut req = debugpb::RaftLogRequest::default(); req.set_region_id(region_id + 1); req.set_log_index(region_id + 1); match debug_client.raft_log(&req).unwrap_err() { Error::RpcFailure(status) => { assert_eq!(status.code(), RpcStatusCode::NOT_FOUND); } _ => panic!("expect NotFound"), } } #[test] fn test_debug_region_info() { let (cluster, debug_client, store_id) = must_new_cluster_and_debug_client(); let raft_engine = cluster.get_raft_engine(store_id); let kv_engine = cluster.get_engine(store_id); let region_id = 100; let raft_state_key = keys::raft_state_key(region_id); let mut raft_state = raft_serverpb::RaftLocalState::default(); raft_state.set_last_index(42); raft_engine .c() .put_msg(&raft_state_key, &raft_state) .unwrap(); assert_eq!( raft_engine .c() .get_msg::<raft_serverpb::RaftLocalState>(&raft_state_key) .unwrap() .unwrap(), raft_state ); let apply_state_key = keys::apply_state_key(region_id); let mut apply_state = raft_serverpb::RaftApplyState::default(); apply_state.set_applied_index(42); kv_engine .c() .put_msg_cf(CF_RAFT, &apply_state_key, &apply_state) .unwrap(); assert_eq!( kv_engine .c() .get_msg_cf::<raft_serverpb::RaftApplyState>(CF_RAFT, &apply_state_key) .unwrap() .unwrap(), apply_state ); let region_state_key = keys::region_state_key(region_id); let mut region_state = raft_serverpb::RegionLocalState::default(); region_state.set_state(raft_serverpb::PeerState::Tombstone); kv_engine .c() .put_msg_cf(CF_RAFT, &region_state_key, &region_state) .unwrap(); assert_eq!( kv_engine .c() .get_msg_cf::<raft_serverpb::RegionLocalState>(CF_RAFT, &region_state_key) .unwrap() .unwrap(), region_state ); // Debug region_info let mut req = debugpb::RegionInfoRequest::default(); req.set_region_id(region_id); let mut resp = debug_client.region_info(&req).unwrap(); assert_eq!(resp.take_raft_local_state(), raft_state); assert_eq!(resp.take_raft_apply_state(), apply_state); assert_eq!(resp.take_region_local_state(), region_state); req.set_region_id(region_id + 1); match debug_client.region_info(&req).unwrap_err() { Error::RpcFailure(status) => { assert_eq!(status.code(), RpcStatusCode::NOT_FOUND); } _ => panic!("expect NotFound"), } } #[test] fn test_debug_region_size() { let (cluster, debug_client, store_id) = must_new_cluster_and_debug_client(); let engine = cluster.get_engine(store_id); // Put some data. let region_id = 100; let region_state_key = keys::region_state_key(region_id); let mut region = metapb::Region::default(); region.set_id(region_id); region.set_start_key(b"a".to_vec()); region.set_end_key(b"z".to_vec()); let mut state = RegionLocalState::default(); state.set_region(region); engine .c() .put_msg_cf(CF_RAFT, &region_state_key, &state) .unwrap(); let cfs = vec![CF_DEFAULT, CF_LOCK, CF_WRITE]; // At lease 8 bytes for the WRITE cf. let (k, v) = (keys::data_key(b"kkkk_kkkk"), b"v"); for cf in &cfs { let cf_handle = engine.cf_handle(cf).unwrap(); engine.put_cf(cf_handle, k.as_slice(), v).unwrap(); } let mut req = debugpb::RegionSizeRequest::default(); req.set_region_id(region_id); req.set_cfs(cfs.iter().map(|s| s.to_string()).collect()); let entries: Vec<_> = debug_client .region_size(&req) .unwrap() .take_entries() .into(); assert_eq!(entries.len(), 3); for e in entries { cfs.iter().find(|&&c| c == e.cf).unwrap(); assert!(e.size > 0); } req.set_region_id(region_id + 1); match debug_client.region_size(&req).unwrap_err() { Error::RpcFailure(status) => { assert_eq!(status.code(), RpcStatusCode::NOT_FOUND); } _ => panic!("expect NotFound"), } } #[test] #[cfg(feature = "failpoints")] fn test_debug_fail_point() { let (_cluster, debug_client, _) = must_new_cluster_and_debug_client(); let (fp, act) = ("raft_between_save", "off"); let mut inject_req = debugpb::InjectFailPointRequest::default(); inject_req.set_name(fp.to_owned()); inject_req.set_actions(act.to_owned()); debug_client.inject_fail_point(&inject_req).unwrap(); let resp = debug_client .list_fail_points(&debugpb::ListFailPointsRequest::default()) .unwrap(); let entries = resp.get_entries(); assert!( entries .iter() .any(|e| e.get_name() == fp && e.get_actions() == act) ); let mut recover_req = debugpb::RecoverFailPointRequest::default(); recover_req.set_name(fp.to_owned()); debug_client.recover_fail_point(&recover_req).unwrap(); let resp = debug_client .list_fail_points(&debugpb::ListFailPointsRequest::default()) .unwrap(); let entries = resp.get_entries(); assert!( entries .iter() .all(|e| !(e.get_name() == fp && e.get_actions() == act)) ); } #[test] fn test_debug_scan_mvcc() { let (cluster, debug_client, store_id) = must_new_cluster_and_debug_client(); let engine = cluster.get_engine(store_id); // Put some data. let keys = [ keys::data_key(b"meta_lock_1"), keys::data_key(b"meta_lock_2"), ]; for k in &keys { let v = Lock::new( LockType::Put, b"pk".to_vec(), 1.into(), 10, None, TimeStamp::zero(), 0, TimeStamp::zero(), ) .to_bytes(); let cf_handle = engine.cf_handle(CF_LOCK).unwrap(); engine.put_cf(cf_handle, k.as_slice(), &v).unwrap(); } let mut req = debugpb::ScanMvccRequest::default(); req.set_from_key(keys::data_key(b"m")); req.set_to_key(keys::data_key(b"n")); req.set_limit(1); let receiver = debug_client.scan_mvcc(&req).unwrap(); let future = receiver.try_fold(Vec::new(), |mut keys, mut resp| { let key = resp.take_key(); keys.push(key); future::ok::<_, Error>(keys) }); let keys = block_on(future).unwrap(); assert_eq!(keys.len(), 1); assert_eq!(keys[0], keys::data_key(b"meta_lock_1")); } #[test] fn test_double_run_node() { let count = 1; let mut cluster = new_node_cluster(0, count); cluster.run(); let id = *cluster.engines.keys().next().unwrap(); let engines = cluster.engines.values().next().unwrap().clone(); let router = cluster.sim.rl().get_router(id).unwrap(); let mut sim = cluster.sim.wl(); let node = sim.get_node(id).unwrap(); let pd_worker = FutureWorker::new("test-pd-worker"); let simulate_trans = SimulateTransport::new(ChannelTransport::new()); let tmp = Builder::new().prefix("test_cluster").tempdir().unwrap(); let snap_mgr = SnapManager::new(tmp.path().to_str().unwrap()); let coprocessor_host = CoprocessorHost::new(router, raftstore::coprocessor::Config::default()); let importer = { let dir = Path::new(engines.kv.path()).join("import-sst"); Arc::new(SSTImporter::new(&ImportConfig::default(), dir, None).unwrap()) }; let (split_check_scheduler, _) = dummy_scheduler(); let store_meta = Arc::new(Mutex::new(StoreMeta::new(20))); let e = node .start( engines, simulate_trans, snap_mgr, pd_worker, store_meta, coprocessor_host, importer, split_check_scheduler, AutoSplitController::default(), ConcurrencyManager::new(1.into()), ) .unwrap_err(); assert!(format!("{:?}", e).contains("already started"), "{:?}", e); drop(sim); cluster.shutdown(); } #[test] fn test_pessimistic_lock() { let (_cluster, client, ctx) = must_new_cluster_and_kv_client(); let (k, v) = (b"key".to_vec(), b"value".to_vec()); // Prewrite let mut mutation = Mutation::default(); mutation.set_op(Op::Put); mutation.set_key(k.clone()); mutation.set_value(v.clone()); must_kv_prewrite(&client, ctx.clone(), vec![mutation], k.clone(), 10); // KeyIsLocked for &return_values in &[false, true] { let resp = kv_pessimistic_lock(&client, ctx.clone(), vec![k.clone()], 20, 20, return_values); assert!(!resp.has_region_error(), "{:?}", resp.get_region_error()); assert_eq!(resp.errors.len(), 1); assert!(resp.errors[0].has_locked()); assert!(resp.values.is_empty()); assert!(resp.not_founds.is_empty()); } must_kv_commit(&client, ctx.clone(), vec![k.clone()], 10, 30, 30); // WriteConflict for &return_values in &[false, true] { let resp = kv_pessimistic_lock(&client, ctx.clone(), vec![k.clone()], 20, 20, return_values); assert!(!resp.has_region_error(), "{:?}", resp.get_region_error()); assert_eq!(resp.errors.len(), 1); assert!(resp.errors[0].has_conflict()); assert!(resp.values.is_empty()); assert!(resp.not_founds.is_empty()); } // Return multiple values for &return_values in &[false, true] { let resp = kv_pessimistic_lock( &client, ctx.clone(), vec![k.clone(), b"nonexsit".to_vec()], 40, 40, true, ); assert!(!resp.has_region_error(), "{:?}", resp.get_region_error()); assert!(resp.errors.is_empty()); if return_values { assert_eq!(resp.get_values().to_vec(), vec![v.clone(), vec![]]); assert_eq!(resp.get_not_founds().to_vec(), vec![false, true]); } must_kv_pessimistic_rollback(&client, ctx.clone(), k.clone(), 40); } } #[test] fn test_check_txn_status_with_max_ts() { let (_cluster, client, ctx) = must_new_cluster_and_kv_client(); let (k, v) = (b"key".to_vec(), b"value".to_vec()); let lock_ts = 10; // Prewrite let mut mutation = Mutation::default(); mutation.set_op(Op::Put); mutation.set_key(k.clone()); mutation.set_value(v); must_kv_prewrite(&client, ctx.clone(), vec![mutation], k.clone(), lock_ts); // Should return MinCommitTsPushed even if caller_start_ts is max. let status = must_check_txn_status( &client, ctx.clone(), &k, lock_ts, std::u64::MAX, lock_ts + 1, ); assert_eq!(status.lock_ttl, 3000); assert_eq!(status.action, Action::MinCommitTsPushed); // The min_commit_ts of k shouldn't be pushed. must_kv_commit(&client, ctx, vec![k], lock_ts, lock_ts + 1, lock_ts + 1); } fn build_client(cluster: &Cluster<ServerCluster>) -> (TikvClient, Context) { let region = cluster.get_region(b""); let leader = region.get_peers()[0].clone(); let addr = cluster.sim.rl().get_addr(leader.get_store_id()); let env = Arc::new(Environment::new(1)); let channel = ChannelBuilder::new(env).connect(&addr); let client = TikvClient::new(channel); let mut ctx = Context::default(); ctx.set_region_id(leader.get_id()); ctx.set_region_epoch(region.get_region_epoch().clone()); ctx.set_peer(leader); (client, ctx) } #[test] fn test_batch_commands() { let mut cluster = new_server_cluster(0, 1); cluster.run(); let (client, _) = build_client(&cluster); let (mut sender, receiver) = client.batch_commands().unwrap(); for _ in 0..1000 { let mut batch_req = BatchCommandsRequest::default(); for i in 0..10 { batch_req.mut_requests().push(Default::default()); batch_req.mut_request_ids().push(i); } block_on(sender.send((batch_req, WriteFlags::default()))).unwrap(); } block_on(sender.close()).unwrap(); let (tx, rx) = mpsc::sync_channel(1); thread::spawn(move || { // We have send 10k requests to the server, so we should get 10k responses. let mut count = 0; for x in block_on( receiver .map(move |b| b.unwrap().get_responses().len()) .collect::<Vec<usize>>(), ) { count += x; if count == 10000 { tx.send(1).unwrap(); return; } } }); rx.recv_timeout(Duration::from_secs(1)).unwrap(); } #[test] fn test_empty_commands() { let mut cluster = new_server_cluster(0, 1); cluster.run(); let (client, _) = build_client(&cluster); let (mut sender, receiver) = client.batch_commands().unwrap(); for _ in 0..1000 { let mut batch_req = BatchCommandsRequest::default(); for i in 0..10 { let mut req = batch_commands_request::Request::default(); req.cmd = Some(batch_commands_request::request::Cmd::Empty( Default::default(), )); batch_req.mut_requests().push(req); batch_req.mut_request_ids().push(i); } block_on(sender.send((batch_req, WriteFlags::default()))).unwrap(); } block_on(sender.close()).unwrap(); let (tx, rx) = mpsc::sync_channel(1); thread::spawn(move || { // We have send 10k requests to the server, so we should get 10k responses. let mut count = 0; for x in block_on( receiver .map(move |b| b.unwrap().get_responses().len()) .collect::<Vec<usize>>(), ) { count += x; if count == 10000 { tx.send(1).unwrap(); return; } } }); rx.recv_timeout(Duration::from_secs(1)).unwrap(); } #[test] fn test_async_commit_check_txn_status() { let mut cluster = new_server_cluster(0, 1); cluster.run(); let (client, ctx) = build_client(&cluster); let start_ts = block_on(cluster.pd_client.get_tso()).unwrap(); let mut req = PrewriteRequest::default(); req.set_context(ctx.clone()); req.set_primary_lock(b"key".to_vec()); let mut mutation = Mutation::default(); mutation.set_op(Op::Put); mutation.set_key(b"key".to_vec()); mutation.set_value(b"value".to_vec()); req.mut_mutations().push(mutation); req.set_start_version(start_ts.into_inner()); req.set_lock_ttl(20000); req.set_use_async_commit(true); client.kv_prewrite(&req).unwrap(); let mut req = CheckTxnStatusRequest::default(); req.set_context(ctx); req.set_primary_key(b"key".to_vec()); req.set_lock_ts(start_ts.into_inner()); req.set_rollback_if_not_exist(true); let resp = client.kv_check_txn_status(&req).unwrap(); assert_ne!(resp.get_action(), Action::MinCommitTsPushed); } #[test] fn test_read_index_check_memory_locks() { let mut cluster = new_server_cluster(0, 3); cluster.cfg.raft_store.hibernate_regions = false; cluster.run(); // make sure leader has been elected. assert_eq!(cluster.must_get(b"k"), None); let region = cluster.get_region(b""); let leader = cluster.leader_of_region(region.get_id()).unwrap(); let leader_cm = cluster.sim.rl().get_concurrency_manager(leader.get_id()); let keys: Vec<_> = vec![b"k", b"l"] .into_iter() .map(|k| Key::from_raw(k)) .collect(); let guards = block_on(leader_cm.lock_keys(keys.iter())); let lock = Lock::new( LockType::Put, b"k".to_vec(), 1.into(), 20000, None, 1.into(), 1, 2.into(), ); guards[0].with_lock(|l| *l = Some(lock.clone())); // read on follower let mut follower_peer = None; let peers = region.get_peers(); for p in peers { if p.get_id() != leader.get_id() { follower_peer = Some(p.clone()); break; } } let follower_peer = follower_peer.unwrap(); let addr = cluster.sim.rl().get_addr(follower_peer.get_store_id()); let env = Arc::new(Environment::new(1)); let channel = ChannelBuilder::new(env).connect(&addr); let client = TikvClient::new(channel); let mut ctx = Context::default(); ctx.set_region_id(region.get_id()); ctx.set_region_epoch(region.get_region_epoch().clone()); ctx.set_peer(follower_peer); let read_index = |ranges: &[(&[u8], &[u8])]| { let mut req = ReadIndexRequest::default(); let start_ts = block_on(cluster.pd_client.get_tso()).unwrap(); req.set_context(ctx.clone()); req.set_start_ts(start_ts.into_inner()); for &(start_key, end_key) in ranges { let mut range = kvrpcpb::KeyRange::default(); range.set_start_key(start_key.to_vec()); range.set_end_key(end_key.to_vec()); req.mut_ranges().push(range); } let resp = client.read_index(&req).unwrap(); (resp, start_ts) }; // wait a while until the node updates its own max ts thread::sleep(Duration::from_millis(300)); let (resp, start_ts) = read_index(&[(b"l", b"yz")]); assert!(!resp.has_locked()); assert_eq!(leader_cm.max_ts(), start_ts); let (resp, start_ts) = read_index(&[(b"a", b"b"), (b"j", b"k0")]); assert_eq!(resp.get_locked(), &lock.into_lock_info(b"k".to_vec())); assert_eq!(leader_cm.max_ts(), start_ts); drop(guards); let (resp, start_ts) = read_index(&[(b"a", b"z")]); assert!(!resp.has_locked()); assert_eq!(leader_cm.max_ts(), start_ts); } #[test] fn test_prewrite_check_max_commit_ts() { let mut cluster = new_server_cluster(0, 1); cluster.run(); let cm = cluster.sim.read().unwrap().get_concurrency_manager(1); cm.update_max_ts(100.into()); let (client, ctx) = build_client(&cluster); let mut req = PrewriteRequest::default(); req.set_context(ctx.clone()); req.set_primary_lock(b"k1".to_vec()); let mut mutation = Mutation::default(); mutation.set_op(Op::Put); mutation.set_key(b"k1".to_vec()); mutation.set_value(b"v1".to_vec()); req.mut_mutations().push(mutation); req.set_start_version(10); req.set_max_commit_ts(200); req.set_lock_ttl(20000); req.set_use_async_commit(true); let resp = client.kv_prewrite(&req).unwrap(); assert_eq!(resp.get_min_commit_ts(), 101); let mut req = PrewriteRequest::default(); req.set_context(ctx.clone()); req.set_primary_lock(b"k2".to_vec()); let mut mutation = Mutation::default(); mutation.set_op(Op::Put); mutation.set_key(b"k2".to_vec()); mutation.set_value(b"v2".to_vec()); req.mut_mutations().push(mutation); req.set_start_version(20); req.set_min_commit_ts(21); req.set_max_commit_ts(50); req.set_lock_ttl(20000); req.set_use_async_commit(true); // Test the idempotency of prewrite when falling back to 2PC. for _ in 0..2 { let resp = client.kv_prewrite(&req).unwrap(); assert_eq!(resp.get_min_commit_ts(), 0); assert_eq!(resp.get_one_pc_commit_ts(), 0); } // 1PC let mut req = PrewriteRequest::default(); req.set_context(ctx); req.set_primary_lock(b"k3".to_vec()); let mut mutation = Mutation::default(); mutation.set_op(Op::Put); mutation.set_key(b"k3".to_vec()); mutation.set_value(b"v3".to_vec()); req.mut_mutations().push(mutation); req.set_start_version(20); req.set_min_commit_ts(21); req.set_max_commit_ts(50); req.set_lock_ttl(20000); req.set_use_async_commit(true); req.set_try_one_pc(true); // Test the idempotency of prewrite when falling back to 2PC. for _ in 0..2 { let resp = client.kv_prewrite(&req).unwrap(); assert_eq!(resp.get_min_commit_ts(), 0); assert_eq!(resp.get_one_pc_commit_ts(), 0); } // There shouldn't be locks remaining in the lock table. assert!(cm.read_range_check(None, None, |_, _| Err(())).is_ok()); } #[test] fn test_txn_heart_beat() { let (_cluster, client, ctx) = must_new_cluster_and_kv_client(); let mut req = TxnHeartBeatRequest::default(); let k = b"k".to_vec(); let start_ts = 10; req.set_context(ctx); req.set_primary_lock(k.clone()); req.set_start_version(start_ts); req.set_advise_lock_ttl(1000); let resp = client.kv_txn_heart_beat(&req).unwrap(); assert!(!resp.has_region_error()); assert_eq!( resp.get_error().get_txn_not_found(), &TxnNotFound { start_ts, primary_key: k, ..Default::default() } ); } fn test_with_memory_lock_cluster(f: impl FnOnce(TikvClient, Context, /* raw_key */ Vec<u8>, Lock)) { let (cluster, client, ctx) = must_new_cluster_and_kv_client(); let cm = cluster.sim.read().unwrap().get_concurrency_manager(1); let raw_key = b"key".to_vec(); let key = Key::from_raw(&raw_key); let guard = block_on(cm.lock_key(&key)); let lock = Lock::new( LockType::Put, b"key".to_vec(), 10.into(), 20000, None, 10.into(), 1, 20.into(), ) .use_async_commit(vec![]); guard.with_lock(|l| { *l = Some(lock.clone()); }); f(client, ctx, raw_key, lock); } #[test] fn test_batch_get_memory_lock() { test_with_memory_lock_cluster(|client, ctx, raw_key, lock| { let mut req = BatchGetRequest::default(); req.set_context(ctx); req.set_keys(vec![b"unlocked".to_vec(), raw_key.clone()].into()); req.version = 50; let resp = client.kv_batch_get(&req).unwrap(); let lock_info = lock.into_lock_info(raw_key); assert_eq!(resp.pairs[0].get_error().get_locked(), &lock_info); assert_eq!(resp.get_error().get_locked(), &lock_info); }); } #[test] fn test_kv_scan_memory_lock() { test_with_memory_lock_cluster(|client, ctx, raw_key, lock| { let mut req = ScanRequest::default(); req.set_context(ctx); req.set_start_key(b"a".to_vec()); req.version = 50; let resp = client.kv_scan(&req).unwrap(); let lock_info = lock.into_lock_info(raw_key); assert_eq!(resp.pairs[0].get_error().get_locked(), &lock_info); assert_eq!(resp.get_error().get_locked(), &lock_info); }); } macro_rules! test_func { ($client:ident, $ctx:ident, $call_opt:ident, $func:ident, $init:expr) => {{ let mut req = $init; req.set_context($ctx.clone()); // Not setting forwarding should lead to store not match. let resp = paste::paste! { $client.[<$func _opt>](&req, CallOption::default().timeout(Duration::from_secs(3))).unwrap() }; let err = resp.get_region_error(); assert!(err.has_store_not_match() || err.has_not_leader(), "{:?}", resp); // Proxy should redirect the request to the correct store. let resp = paste::paste! { $client.[<$func _opt>](&req, $call_opt.clone()).unwrap() }; let err = resp.get_region_error(); assert!(!err.has_store_not_match() && !err.has_not_leader(), "{:?}", resp); }}; } macro_rules! test_func_init { ($client:ident, $ctx:ident, $call_opt:ident, $func:ident, $req:ident) => {{ test_func!($client, $ctx, $call_opt, $func, $req::default()) }}; ($client:ident, $ctx:ident, $call_opt:ident, $func:ident, $req:ident, batch) => {{ test_func!($client, $ctx, $call_opt, $func, { let mut req = $req::default(); req.set_keys(vec![b"key".to_vec()].into()); req }) }}; ($client:ident, $ctx:ident, $call_opt:ident, $func:ident, $req:ident, $op:expr) => {{ test_func!($client, $ctx, $call_opt, $func, { let mut req = $req::default(); let mut m = Mutation::default(); m.set_op($op); m.key = b"key".to_vec(); req.mut_mutations().push(m); req }) }}; } fn setup_cluster() -> (Cluster<ServerCluster>, TikvClient, CallOption, Context) { let mut cluster = new_server_cluster(0, 3); cluster.run(); let region_id = 1; let leader = cluster.leader_of_region(region_id).unwrap(); let leader_addr = cluster.sim.rl().get_addr(leader.get_store_id()); let region = cluster.get_region(b"k1"); let follower = region .get_peers() .iter() .find(|p| **p != leader) .unwrap() .clone(); let follower_addr = cluster.sim.rl().get_addr(follower.get_store_id()); let epoch = cluster.get_region_epoch(region_id); let mut ctx = Context::default(); ctx.set_region_id(region_id); ctx.set_peer(leader); ctx.set_region_epoch(epoch); let env = Arc::new(Environment::new(1)); let channel = ChannelBuilder::new(env).connect(&follower_addr); let client = TikvClient::new(channel); // Verify not setting forwarding header will result in store not match. let mut put_req = RawPutRequest::default(); put_req.set_context(ctx.clone()); let put_resp = client.raw_put(&put_req).unwrap(); assert!( put_resp.get_region_error().has_store_not_match(), "{:?}", put_resp ); assert!(put_resp.error.is_empty(), "{:?}", put_resp); let call_opt = server::build_forward_option(&leader_addr).timeout(Duration::from_secs(3)); (cluster, client, call_opt, ctx) } /// Check all supported requests can go through proxy correctly. #[test] fn test_tikv_forwarding() { let (_cluster, client, call_opt, ctx) = setup_cluster(); // Verify not setting forwarding header will result in store not match. let mut put_req = RawPutRequest::default(); put_req.set_context(ctx.clone()); let put_resp = client.raw_put(&put_req).unwrap(); assert!( put_resp.get_region_error().has_store_not_match(), "{:?}", put_resp ); assert!(put_resp.error.is_empty(), "{:?}", put_resp); test_func_init!(client, ctx, call_opt, kv_get, GetRequest); test_func_init!(client, ctx, call_opt, kv_scan, ScanRequest); test_func_init!(client, ctx, call_opt, kv_prewrite, PrewriteRequest, Op::Put); test_func_init!( client, ctx, call_opt, kv_pessimistic_lock, PessimisticLockRequest, Op::PessimisticLock ); test_func_init!( client, ctx, call_opt, kv_pessimistic_rollback, PessimisticRollbackRequest, batch ); test_func_init!(client, ctx, call_opt, kv_commit, CommitRequest, batch); test_func_init!(client, ctx, call_opt, kv_cleanup, CleanupRequest); test_func_init!(client, ctx, call_opt, kv_batch_get, BatchGetRequest); test_func_init!( client, ctx, call_opt, kv_batch_rollback, BatchRollbackRequest, batch ); test_func_init!( client, ctx, call_opt, kv_txn_heart_beat, TxnHeartBeatRequest ); test_func_init!( client, ctx, call_opt, kv_check_txn_status, CheckTxnStatusRequest ); test_func_init!( client, ctx, call_opt, kv_check_secondary_locks, CheckSecondaryLocksRequest, batch ); test_func_init!(client, ctx, call_opt, kv_scan_lock, ScanLockRequest); test_func_init!(client, ctx, call_opt, kv_resolve_lock, ResolveLockRequest); test_func_init!(client, ctx, call_opt, kv_delete_range, DeleteRangeRequest); test_func_init!(client, ctx, call_opt, mvcc_get_by_key, MvccGetByKeyRequest); test_func_init!( client, ctx, call_opt, mvcc_get_by_start_ts, MvccGetByStartTsRequest ); test_func_init!(client, ctx, call_opt, raw_get, RawGetRequest); test_func_init!(client, ctx, call_opt, raw_batch_get, RawBatchGetRequest); test_func_init!(client, ctx, call_opt, raw_scan, RawScanRequest); test_func_init!(client, ctx, call_opt, raw_batch_scan, RawBatchScanRequest); test_func_init!(client, ctx, call_opt, raw_put, RawPutRequest); test_func!(client, ctx, call_opt, raw_batch_put, { let mut req = RawBatchPutRequest::default(); req.set_pairs(vec![KvPair::default()].into()); req }); test_func_init!(client, ctx, call_opt, raw_delete, RawDeleteRequest); test_func_init!( client, ctx, call_opt, raw_batch_delete, RawBatchDeleteRequest, batch ); test_func_init!( client, ctx, call_opt, raw_delete_range, RawDeleteRangeRequest ); test_func!(client, ctx, call_opt, coprocessor, { let mut req = Request::default(); req.set_tp(REQ_TYPE_DAG); req }); test_func!(client, ctx, call_opt, split_region, { let mut req = SplitRegionRequest::default(); req.set_split_key(b"k1".to_vec()); req }); test_func_init!(client, ctx, call_opt, read_index, ReadIndexRequest); // Test if duplex can be redirect correctly. let cases = vec![ (CallOption::default().timeout(Duration::from_secs(3)), false), (call_opt, true), ]; for (opt, success) in cases { let (mut sender, receiver) = client.batch_commands_opt(opt).unwrap(); for _ in 0..100 { let mut batch_req = BatchCommandsRequest::default(); for i in 0..10 { let mut get = GetRequest::default(); get.set_context(ctx.clone()); let mut req = batch_commands_request::Request::default(); req.cmd = Some(batch_commands_request::request::Cmd::Get(get)); batch_req.mut_requests().push(req); batch_req.mut_request_ids().push(i); } block_on(sender.send((batch_req, WriteFlags::default()))).unwrap(); } block_on(sender.close()).unwrap(); // We have send 1k requests to the server, so we should get 1k responses. let resps = block_on( receiver .map(move |b| futures::stream::iter(b.unwrap().take_responses().into_vec())) .flatten() .collect::<Vec<_>>(), ); assert_eq!(resps.len(), 1000); for resp in resps { let resp = match resp.cmd { Some(batch_commands_response::response::Cmd::Get(g)) => g, _ => panic!("unexpected response {:?}", resp), }; let error = resp.get_region_error(); if success { assert!(!error.has_store_not_match(), "{:?}", resp); } else { assert!(error.has_store_not_match(), "{:?}", resp); } } } } /// Test if forwarding works correctly if the target node is shutdown and restarted. #[test] fn test_forwarding_reconnect() { let (mut cluster, client, call_opt, ctx) = setup_cluster(); let leader = cluster.leader_of_region(1).unwrap(); cluster.stop_node(leader.get_store_id()); let mut req = RawGetRequest::default(); req.set_context(ctx); // Large timeout value to ensure the error is from proxy instead of client. let timer = std::time::Instant::now(); let timeout = Duration::from_secs(5); let res = client.raw_get_opt(&req, call_opt.clone().timeout(timeout)); let elapsed = timer.elapsed(); assert!(elapsed < timeout, "{:?}", elapsed); // Because leader server is shutdown, reconnecting has to be timeout. match res { Err(grpcio::Error::RpcFailure(s)) => assert_eq!(s.code(), RpcStatusCode::CANCELLED), _ => panic!("unexpected result {:?}", res), } cluster.run_node(leader.get_store_id()).unwrap(); let resp = client.raw_get_opt(&req, call_opt).unwrap(); assert!(!resp.get_region_error().has_store_not_match(), "{:?}", resp); } #[test] fn test_health_check() { let mut cluster = new_server_cluster(0, 1); cluster.run(); let addr = cluster.sim.rl().get_addr(1); let env = Arc::new(Environment::new(1)); let channel = ChannelBuilder::new(env).connect(&addr); let client = HealthClient::new(channel); let req = HealthCheckRequest { service: "".to_string(), ..Default::default() }; let resp = client.check(&req).unwrap(); assert_eq!(ServingStatus::Serving, resp.status); cluster.shutdown(); client.check(&req).unwrap_err(); } #[test] fn test_get_lock_wait_info_api() { let (_cluster, client, ctx) = must_new_cluster_and_kv_client(); let client2 = client.clone(); let mut ctx1 = ctx.clone(); ctx1.set_resource_group_tag(b"resource_group_tag1".to_vec()); must_kv_pessimistic_lock(&client, ctx1, b"a".to_vec(), 20); let mut ctx2 = ctx.clone(); let handle = thread::spawn(move || { ctx2.set_resource_group_tag(b"resource_group_tag2".to_vec()); kv_pessimistic_lock_with_ttl(&client2, ctx2, vec![b"a".to_vec()], 30, 30, false, 1000); }); let mut entries = None; for _retry in 0..100 { thread::sleep(Duration::from_millis(10)); // The lock should be in waiting state here. let req = GetLockWaitInfoRequest::default(); let resp = client.get_lock_wait_info(&req).unwrap(); if resp.entries.len() != 0 { entries = Some(resp.entries.to_vec()); break; } } let entries = entries.unwrap(); assert_eq!(entries.len(), 1); assert_eq!(entries[0].txn, 30); assert_eq!(entries[0].wait_for_txn, 20); assert_eq!(entries[0].key, b"a".to_vec()); assert_eq!( entries[0].resource_group_tag, b"resource_group_tag2".to_vec() ); must_kv_pessimistic_rollback(&client, ctx, b"a".to_vec(), 20); handle.join().unwrap(); }
33.181139
144
0.628002
f4fdebeb40b73525dfd0c55c19bf73af1f3600ab
3,357
//! Extract added/modified times from git history. //! use crate::CError; use chrono::Utc; use tokio::process::Command; pub async fn get_files_on_ref(repo_path: &str, ref_name: &str) -> Result<Vec<String>, CError> { let output = Command::new("git") .arg("ls-tree") .arg("-r") .arg(ref_name) .arg("--name-only") .current_dir(repo_path) .output(); let output = output.await?; if !output.status.success() { return Err(CError::GitCmdError( String::from_utf8(output.stderr).map_err(|e| e.utf8_error())?, )); } Ok(parse_cmd_output(&output)?) } pub async fn get_added_mod_times_for_file(filepath: &str, cwd: &str) -> String { let output = Command::new("git") .arg("log") .arg("--follow") .arg("-m") .arg("--pretty=%ci") .arg(filepath) .current_dir(cwd) .output(); let output = output.await.unwrap().stdout; let commit_years: Vec<String> = std::str::from_utf8(&output) .unwrap() .split('\n') .filter_map(|s| { // Take only first four chars (the year) from strings that are longer than zero let s = s.to_owned(); match s.len() { 0 => None, _ => Some(s.chars().take(4).collect()), } }) .collect(); match commit_years.len() { 0 => { log::debug!("File {} is untracked, add current year", filepath); Utc::now().date().format("%Y").to_string() } 1 => { log::debug!("File {} was only committed once", filepath); commit_years[0].clone() } num_commits => { log::debug!("File {} was modified {} times", filepath, num_commits); let added = commit_years[commit_years.len() - 1].clone(); let last_modified = commit_years[0].clone(); match added == last_modified { true => added, false => format!("{}-{}", added, last_modified), } } } } pub async fn check_for_changes(repo_path: &str, fail_on_diff: bool) -> Result<(), CError> { let diff_files = get_diffs(repo_path).await?; if diff_files.len() > 0 { println!("Files changed:"); for filepath in diff_files.iter() { println!("{}", filepath); } if fail_on_diff { return Err(CError::FilesChanged); } } Ok(()) } async fn get_diffs<'a>(repo_path: &str) -> Result<Vec<String>, CError> { let output = Command::new("git") .arg("diff") .arg("--name-only") .current_dir(repo_path) .output(); let output = output.await?; if !output.status.success() { return Err(CError::GitCmdError( String::from_utf8(output.stderr).map_err(|e| e.utf8_error())?, )); } Ok(parse_cmd_output(&output)?) } fn parse_cmd_output(output: &std::process::Output) -> Result<Vec<String>, CError> { let output = std::str::from_utf8(&output.stdout)?; let lines: Vec<String> = output .split('\n') .filter_map(|s| { let s = s.to_owned(); match s.len() { 0 => None, _ => Some(s), } }) .collect(); Ok(lines) }
28.449153
95
0.519511
5621d18a3c7e48281236609114f1c216b468ff20
13,184
// spell-checker:ignore (regex) SKIPTO UPTO ; (vars) ntimes use crate::csplit_error::CsplitError; use regex::Regex; /// The definition of a pattern to match on a line. #[derive(Debug)] pub enum Pattern { /// Copy the file's content to a split up to, not including, the given line number. The number /// of times the pattern is executed is detailed in [`ExecutePattern`]. UpToLine(usize, ExecutePattern), /// Copy the file's content to a split up to, not including, the line matching the regex. The /// integer is an offset relative to the matched line of what to include (if positive) or /// to exclude (if negative). The number of times the pattern is executed is detailed in /// [`ExecutePattern`]. UpToMatch(Regex, i32, ExecutePattern), /// Skip the file's content up to, not including, the line matching the regex. The integer /// is an offset relative to the matched line of what to include (if positive) or to exclude /// (if negative). The number of times the pattern is executed is detailed in [`ExecutePattern`]. SkipToMatch(Regex, i32, ExecutePattern), } impl ToString for Pattern { fn to_string(&self) -> String { match self { Pattern::UpToLine(n, _) => n.to_string(), Pattern::UpToMatch(regex, 0, _) => format!("/{}/", regex.as_str()), Pattern::UpToMatch(regex, offset, _) => format!("/{}/{:+}", regex.as_str(), offset), Pattern::SkipToMatch(regex, 0, _) => format!("%{}%", regex.as_str()), Pattern::SkipToMatch(regex, offset, _) => format!("%{}%{:+}", regex.as_str(), offset), } } } /// The number of times a pattern can be used. #[derive(Debug)] pub enum ExecutePattern { /// Execute the pattern as many times as possible Always, /// Execute the pattern a fixed number of times Times(usize), } impl ExecutePattern { pub fn iter(&self) -> ExecutePatternIter { match self { ExecutePattern::Times(n) => ExecutePatternIter::new(Some(*n)), ExecutePattern::Always => ExecutePatternIter::new(None), } } } pub struct ExecutePatternIter { max: Option<usize>, cur: usize, } impl ExecutePatternIter { fn new(max: Option<usize>) -> ExecutePatternIter { ExecutePatternIter { max, cur: 0 } } } impl Iterator for ExecutePatternIter { type Item = (Option<usize>, usize); fn next(&mut self) -> Option<(Option<usize>, usize)> { match self.max { // iterate until m is reached Some(m) => { if self.cur == m { None } else { self.cur += 1; Some((self.max, self.cur)) } } // no limit, just increment a counter None => { self.cur += 1; Some((None, self.cur)) } } } } /// Parses the definitions of patterns given on the command line into a list of [`Pattern`]s. /// /// # Errors /// /// If a pattern is incorrect, a [`::CsplitError::InvalidPattern`] error is returned, which may be /// due to, e.g.,: /// - an invalid regular expression; /// - an invalid number for, e.g., the offset. pub fn get_patterns(args: &[String]) -> Result<Vec<Pattern>, CsplitError> { let patterns = extract_patterns(args)?; validate_line_numbers(&patterns)?; Ok(patterns) } fn extract_patterns(args: &[String]) -> Result<Vec<Pattern>, CsplitError> { let mut patterns = Vec::with_capacity(args.len()); let to_match_reg = Regex::new(r"^(/(?P<UPTO>.+)/|%(?P<SKIPTO>.+)%)(?P<OFFSET>[\+-]\d+)?$").unwrap(); let execute_ntimes_reg = Regex::new(r"^\{(?P<TIMES>\d+)|\*\}$").unwrap(); let mut iter = args.iter().peekable(); while let Some(arg) = iter.next() { // get the number of times a pattern is repeated, which is at least once plus whatever is // in the quantifier. let execute_ntimes = match iter.peek() { None => ExecutePattern::Times(1), Some(&next_item) => { match execute_ntimes_reg.captures(next_item) { None => ExecutePattern::Times(1), Some(r) => { // skip the next item iter.next(); if let Some(times) = r.name("TIMES") { ExecutePattern::Times(times.as_str().parse::<usize>().unwrap() + 1) } else { ExecutePattern::Always } } } } }; // get the pattern definition if let Some(captures) = to_match_reg.captures(arg) { let offset = match captures.name("OFFSET") { None => 0, Some(m) => m.as_str().parse().unwrap(), }; if let Some(up_to_match) = captures.name("UPTO") { let pattern = match Regex::new(up_to_match.as_str()) { Err(_) => { return Err(CsplitError::InvalidPattern(arg.to_string())); } Ok(reg) => reg, }; patterns.push(Pattern::UpToMatch(pattern, offset, execute_ntimes)); } else if let Some(skip_to_match) = captures.name("SKIPTO") { let pattern = match Regex::new(skip_to_match.as_str()) { Err(_) => { return Err(CsplitError::InvalidPattern(arg.to_string())); } Ok(reg) => reg, }; patterns.push(Pattern::SkipToMatch(pattern, offset, execute_ntimes)); } } else if let Ok(line_number) = arg.parse::<usize>() { patterns.push(Pattern::UpToLine(line_number, execute_ntimes)); } else { return Err(CsplitError::InvalidPattern(arg.to_string())); } } Ok(patterns) } /// Asserts the line numbers are in increasing order, starting at 1. fn validate_line_numbers(patterns: &[Pattern]) -> Result<(), CsplitError> { patterns .iter() .filter_map(|pattern| match pattern { Pattern::UpToLine(line_number, _) => Some(line_number), _ => None, }) .try_fold(0, |prev_ln, &current_ln| match (prev_ln, current_ln) { // a line number cannot be zero (_, 0) => Err(CsplitError::LineNumberIsZero), // two consecutive numbers should not be equal (n, m) if n == m => { show_warning!("line number '{}' is the same as preceding line number", n); Ok(n) } // a number cannot be greater than the one that follows (n, m) if n > m => Err(CsplitError::LineNumberSmallerThanPrevious(m, n)), (_, m) => Ok(m), })?; Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn bad_pattern() { let input = vec!["bad".to_string()]; assert!(get_patterns(input.as_slice()).is_err()); } #[test] fn up_to_line_pattern() { let input: Vec<String> = vec!["24", "42", "{*}", "50", "{4}"] .into_iter() .map(|v| v.to_string()) .collect(); let patterns = get_patterns(input.as_slice()).unwrap(); assert_eq!(patterns.len(), 3); match patterns.get(0) { Some(Pattern::UpToLine(24, ExecutePattern::Times(1))) => (), _ => panic!("expected UpToLine pattern"), }; match patterns.get(1) { Some(Pattern::UpToLine(42, ExecutePattern::Always)) => (), _ => panic!("expected UpToLine pattern"), }; match patterns.get(2) { Some(Pattern::UpToLine(50, ExecutePattern::Times(5))) => (), _ => panic!("expected UpToLine pattern"), }; } #[test] fn up_to_match_pattern() { let input: Vec<String> = vec![ "/test1.*end$/", "/test2.*end$/", "{*}", "/test3.*end$/", "{4}", "/test4.*end$/+3", "/test5.*end$/-3", ] .into_iter() .map(|v| v.to_string()) .collect(); let patterns = get_patterns(input.as_slice()).unwrap(); assert_eq!(patterns.len(), 5); match patterns.get(0) { Some(Pattern::UpToMatch(reg, 0, ExecutePattern::Times(1))) => { let parsed_reg = format!("{}", reg); assert_eq!(parsed_reg, "test1.*end$"); } _ => panic!("expected UpToMatch pattern"), }; match patterns.get(1) { Some(Pattern::UpToMatch(reg, 0, ExecutePattern::Always)) => { let parsed_reg = format!("{}", reg); assert_eq!(parsed_reg, "test2.*end$"); } _ => panic!("expected UpToMatch pattern"), }; match patterns.get(2) { Some(Pattern::UpToMatch(reg, 0, ExecutePattern::Times(5))) => { let parsed_reg = format!("{}", reg); assert_eq!(parsed_reg, "test3.*end$"); } _ => panic!("expected UpToMatch pattern"), }; match patterns.get(3) { Some(Pattern::UpToMatch(reg, 3, ExecutePattern::Times(1))) => { let parsed_reg = format!("{}", reg); assert_eq!(parsed_reg, "test4.*end$"); } _ => panic!("expected UpToMatch pattern"), }; match patterns.get(4) { Some(Pattern::UpToMatch(reg, -3, ExecutePattern::Times(1))) => { let parsed_reg = format!("{}", reg); assert_eq!(parsed_reg, "test5.*end$"); } _ => panic!("expected UpToMatch pattern"), }; } #[test] fn skip_to_match_pattern() { let input: Vec<String> = vec![ "%test1.*end$%", "%test2.*end$%", "{*}", "%test3.*end$%", "{4}", "%test4.*end$%+3", "%test5.*end$%-3", ] .into_iter() .map(|v| v.to_string()) .collect(); let patterns = get_patterns(input.as_slice()).unwrap(); assert_eq!(patterns.len(), 5); match patterns.get(0) { Some(Pattern::SkipToMatch(reg, 0, ExecutePattern::Times(1))) => { let parsed_reg = format!("{}", reg); assert_eq!(parsed_reg, "test1.*end$"); } _ => panic!("expected SkipToMatch pattern"), }; match patterns.get(1) { Some(Pattern::SkipToMatch(reg, 0, ExecutePattern::Always)) => { let parsed_reg = format!("{}", reg); assert_eq!(parsed_reg, "test2.*end$"); } _ => panic!("expected SkipToMatch pattern"), }; match patterns.get(2) { Some(Pattern::SkipToMatch(reg, 0, ExecutePattern::Times(5))) => { let parsed_reg = format!("{}", reg); assert_eq!(parsed_reg, "test3.*end$"); } _ => panic!("expected SkipToMatch pattern"), }; match patterns.get(3) { Some(Pattern::SkipToMatch(reg, 3, ExecutePattern::Times(1))) => { let parsed_reg = format!("{}", reg); assert_eq!(parsed_reg, "test4.*end$"); } _ => panic!("expected SkipToMatch pattern"), }; match patterns.get(4) { Some(Pattern::SkipToMatch(reg, -3, ExecutePattern::Times(1))) => { let parsed_reg = format!("{}", reg); assert_eq!(parsed_reg, "test5.*end$"); } _ => panic!("expected SkipToMatch pattern"), }; } #[test] fn line_number_zero() { let patterns = vec![Pattern::UpToLine(0, ExecutePattern::Times(1))]; match validate_line_numbers(&patterns) { Err(CsplitError::LineNumberIsZero) => (), _ => panic!("expected LineNumberIsZero error"), } } #[test] fn line_number_smaller_than_previous() { let input: Vec<String> = vec!["10".to_string(), "5".to_string()]; match get_patterns(input.as_slice()) { Err(CsplitError::LineNumberSmallerThanPrevious(5, 10)) => (), _ => panic!("expected LineNumberSmallerThanPrevious error"), } } #[test] fn line_number_smaller_than_previous_separate() { let input: Vec<String> = vec!["10".to_string(), "/20/".to_string(), "5".to_string()]; match get_patterns(input.as_slice()) { Err(CsplitError::LineNumberSmallerThanPrevious(5, 10)) => (), _ => panic!("expected LineNumberSmallerThanPrevious error"), } } #[test] fn line_number_zero_separate() { let input: Vec<String> = vec!["10".to_string(), "/20/".to_string(), "0".to_string()]; match get_patterns(input.as_slice()) { Err(CsplitError::LineNumberIsZero) => (), _ => panic!("expected LineNumberIsZero error"), } } }
36.826816
101
0.519797
11da26cf1cc6869c9cf8bef179258f5ba917da0f
417
use std::process::Command; use std::ffi::OsStr; pub fn get(package_name: &str, should_update: bool) -> bool { match should_update { true => run(&["get", "-u", package_name]), false => run(&["get", package_name]) } } fn run<S: AsRef<OsStr>>(args: &[S]) -> bool { match Command::new("go").args(args).status() { Ok(exit_status) => exit_status.success(), _ => false, } }
24.529412
61
0.563549
50456895192cfd947fb237fe423ef23737de62ac
4,155
use advent2020::*; use std::collections::HashMap; #[macro_use] extern crate scan_fmt; fn main() { let notes = parse_notes("inputs/16.full"); println!("part1: {}", part1(&notes)); println!("part2: {}", part2(&notes, "departure ")); } #[test] fn part1_small() { let notes = parse_notes("inputs/16.test"); assert_eq!(part1(&notes), 71); } fn part1(notes: &Notes) -> usize { notes .tickets .iter() .skip(1) .map(|t| sum_invalid_entries(t, &notes.rules)) .sum() } #[test] fn part2_small() { let notes = parse_notes("inputs/16.test2"); assert_eq!(part2(&notes, "class"), 12); assert_eq!(part2(&notes, "row"), 11); assert_eq!(part2(&notes, "seat"), 13); assert_eq!(part2(&notes, ""), 11 * 12 * 13); } fn part2(notes: &Notes, prefix: &str) -> usize { // transpose valid tickets s.t. each position is on a row let mut valid_cols = vec![vec![]; notes.tickets[0].len()]; for t in notes .tickets .iter() .skip(1) .filter(|t| sum_invalid_entries(t, &notes.rules) == 0) { for (i, x) in t.iter().enumerate() { valid_cols[i].push(x); } } // determine which positions work for which rules let mut assignments = HashMap::new(); for (key, ranges) in notes.rules.iter() { for (i, nums) in valid_cols.iter().enumerate() { if nums .iter() .all(|x| ranges[0].contains(x) || ranges[1].contains(x)) { assignments.entry(key).or_insert_with(Vec::new).push(i); } } } // assign one position per rule key let mut fixed_positions = HashMap::new(); while !assignments.is_empty() { // positions are fixed when only one assignment is available for (key, positions) in assignments.iter() { if positions.len() == 1 { fixed_positions.insert(positions[0], key.to_string()); } } // remove fixed positions from other rules' assignments for pos in fixed_positions.keys() { for positions in assignments.values_mut() { if let Some(idx) = positions.iter().position(|p| p == pos) { positions.remove(idx); } } } // drop rules with no valid assignments (because they've been fixed) assignments.retain(|_, positions| !positions.is_empty()); } // find the product of my ticket's values with the given rule prefix let my_ticket = &notes.tickets[0]; fixed_positions .iter() .filter(|(_, key)| key.starts_with(prefix)) .map(|(pos, _)| my_ticket[*pos]) .product() } type RulesMap = HashMap<String, [std::ops::RangeInclusive<usize>; 2]>; #[derive(Debug)] struct Notes { rules: RulesMap, tickets: Vec<Vec<usize>>, } fn sum_invalid_entries(ticket: &[usize], rules: &RulesMap) -> usize { ticket.iter().filter(|&x| !any_rule_valid(*x, &rules)).sum() } fn any_rule_valid(x: usize, rules: &RulesMap) -> bool { rules .values() .any(|ranges| ranges[0].contains(&x) || ranges[1].contains(&x)) } fn parse_notes(path: &str) -> Notes { let data = read_string(path); let mut chunks = data.split("\n\n"); let rules = parse_rules(chunks.next().unwrap()); let mut tickets = vec![]; for chunk in chunks { for line in chunk.lines().skip(1) { tickets.push(parse_ticket(line)); } } Notes { rules, tickets } } fn parse_ticket(ticket_data: &str) -> Vec<usize> { ticket_data.split(',').map(|x| x.parse().unwrap()).collect() } fn parse_rules(rules_data: &str) -> RulesMap { let mut out = HashMap::new(); for line in rules_data.lines() { let mut parts = line.split(": "); let key = parts.next().unwrap().to_string(); let (a, b, c, d) = scan_fmt!( parts.next().unwrap(), "{d}-{d} or {d}-{d}", usize, usize, usize, usize ) .unwrap(); out.insert(key, [a..=b, c..=d]); } out }
28.854167
76
0.551625
1657512a5c42c90c942a47c120d6499a4c88587e
2,001
use { crate::{ errors::{ConfError, ProgramError}, }, serde::de::DeserializeOwned, std::{ fs, path::Path, }, deser_hjson, toml, }; /// Formats usable for reading configuration files #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub enum SerdeFormat { Hjson, Toml, } pub static FORMATS: &[SerdeFormat] = &[ SerdeFormat::Hjson, SerdeFormat::Toml, ]; impl SerdeFormat { pub fn key(self) -> &'static str { match self { Self::Hjson => "hjson", Self::Toml => "toml", } } pub fn from_key(key: &str) -> Option<Self> { match key { "hjson" => Some(SerdeFormat::Hjson), "toml" => Some(SerdeFormat::Toml), _ => None, } } pub fn from_path(path: &Path) -> Result<Self, ConfError> { path.extension() .and_then(|os| os.to_str()) .map(|ext| ext.to_lowercase()) .and_then(|key| Self::from_key(&key)) .ok_or_else(|| ConfError::UnknownFileExtension { path: path.to_string_lossy().to_string() }) } pub fn read_file<T>(path: &Path) -> Result<T, ProgramError> where T: DeserializeOwned { let format = Self::from_path(&path)?; let file_content = fs::read_to_string(&path)?; match format { Self::Hjson => { deser_hjson::from_str::<T>(&file_content) .map_err(|e| ProgramError::ConfFile { path: path.to_string_lossy().to_string(), details: e.into(), }) } Self::Toml => { toml::from_str::<T>(&file_content) .map_err(|e| ProgramError::ConfFile { path: path.to_string_lossy().to_string(), details: e.into(), }) } } } } impl Default for SerdeFormat { fn default() -> Self { SerdeFormat::Hjson } }
25.987013
104
0.50075
6adcde4b918de1ed03e62286ca9d69fa78ea36e3
971
//! Module for automated tests use regex::Regex; use std::{error::Error, fs::File, io::Read}; pub(crate) const RESOURCES_DIR: &str = "./tests/resources"; pub(crate) const CLTRID: &str = "cltrid:1626454866"; pub(crate) const SVTRID: &str = "RO-6879-1627224678242975"; pub(crate) const SUCCESS_MSG: &str = "Command completed successfully"; /// Reads EPP XML requests and responses from the test/resources directory to run tests on pub(crate) fn get_xml(path: &str) -> Result<String, Box<dyn Error>> { let ws_regex = Regex::new(r"[\s]{2,}")?; let mut f = File::open(format!("{}/{}", RESOURCES_DIR, path))?; let mut buf = String::new(); f.read_to_string(&mut buf)?; if !buf.is_empty() { let mat = Regex::new(r"\?>").unwrap().find(buf.as_str()).unwrap(); let start = mat.end(); buf = format!( "{}\r\n{}", &buf[..start], ws_regex.replace_all(&buf[start..], "") ); } Ok(buf) }
32.366667
90
0.597322
8f33a6604c2195d317c696f806e6802ab0b7c34d
280
#![crate_name = "foo"] mod hidden { #[derive(Clone)] pub struct Foo; } #[doc(hidden)] pub mod __hidden { pub use hidden::Foo; } // @has foo/trait.Clone.html // @!has - 'Foo' // @has implementors/core/clone/trait.Clone.js // @!has - 'Foo' pub use std::clone::Clone;
15.555556
46
0.607143
e91b7cd8b950ed821812b5f7c508689059c20192
907
#[doc = r" Value read from the register"] pub struct R { bits: u32, } impl super::DIEP0_TXFSTS { #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } } #[doc = r" Value of the field"] pub struct SPCAVAILR { bits: u16, } impl SPCAVAILR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u16 { self.bits } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:15 - TxFIFO Space Available"] #[inline] pub fn spcavail(&self) -> SPCAVAILR { let bits = { const MASK: u16 = 0xffff; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u16 }; SPCAVAILR { bits } } }
21.595238
56
0.509372
bf4c5d2ca2b0d2cb4fbc22d0d093ea95d5f7a67a
17,124
mod support; use glam::{vec3, Vec3, Vec3Mask}; use std::f32; #[test] fn test_vec3_align() { use std::mem; assert_eq!(12, mem::size_of::<Vec3>()); assert_eq!(4, mem::align_of::<Vec3>()); assert_eq!(12, mem::size_of::<Vec3Mask>()); assert_eq!(4, mem::align_of::<Vec3Mask>()); } #[test] fn test_vec3_new() { let v = vec3(1.0, 2.0, 3.0); assert_eq!(v.x, 1.0); assert_eq!(v.y, 2.0); assert_eq!(v.z, 3.0); assert_eq!(v.x(), 1.0); assert_eq!(v.y(), 2.0); assert_eq!(v.z(), 3.0); let t = (1.0, 2.0, 3.0); let v = Vec3::from(t); assert_eq!(t, v.into()); let a = [1.0, 2.0, 3.0]; let v = Vec3::from(a); let a1: [f32; 3] = v.into(); assert_eq!(a, a1); let v = Vec3::new(t.0, t.1, t.2); assert_eq!(t, v.into()); assert_eq!(Vec3::new(1.0, 0.0, 0.0), Vec3::unit_x()); assert_eq!(Vec3::new(0.0, 1.0, 0.0), Vec3::unit_y()); assert_eq!(Vec3::new(0.0, 0.0, 1.0), Vec3::unit_z()); } #[test] fn test_vec3_fmt() { let a = Vec3::new(1.0, 2.0, 3.0); assert_eq!(format!("{:?}", a), "Vec3(1.0, 2.0, 3.0)"); // assert_eq!(format!("{:#?}", a), "Vec3(\n 1.0,\n 2.0,\n 3.0\n)"); assert_eq!(format!("{}", a), "[1, 2, 3]"); } #[test] fn test_vec3_zero() { let v = Vec3::zero(); assert_eq!((0.0, 0.0, 0.0), v.into()); assert_eq!(v, Vec3::default()); } #[test] fn test_vec3_splat() { let v = Vec3::splat(1.0); assert_eq!((1.0, 1.0, 1.0), v.into()); } #[test] fn test_vec3_accessors() { let mut a = Vec3::zero(); a.x = 1.0; a.y = 2.0; a.z = 3.0; assert_eq!(1.0, a.x); assert_eq!(2.0, a.y); assert_eq!(3.0, a.z); assert_eq!((1.0, 2.0, 3.0), a.into()); let mut a = Vec3::zero(); a.set_x(1.0); a.set_y(2.0); a.set_z(3.0); assert_eq!(1.0, a.x()); assert_eq!(2.0, a.y()); assert_eq!(3.0, a.z()); assert_eq!((1.0, 2.0, 3.0), a.into()); let mut a = Vec3::zero(); *a.x_mut() = 1.0; *a.y_mut() = 2.0; *a.z_mut() = 3.0; assert_eq!(1.0, a.x()); assert_eq!(2.0, a.y()); assert_eq!(3.0, a.z()); assert_eq!((1.0, 2.0, 3.0), a.into()); let mut a = Vec3::zero(); a[0] = 1.0; a[1] = 2.0; a[2] = 3.0; assert_eq!(1.0, a[0]); assert_eq!(2.0, a[1]); assert_eq!(3.0, a[2]); assert_eq!((1.0, 2.0, 3.0), a.into()); } #[test] fn test_vec3_funcs() { let x = vec3(1.0, 0.0, 0.0); let y = vec3(0.0, 1.0, 0.0); let z = vec3(0.0, 0.0, 1.0); assert_eq!(1.0, x.dot(x)); assert_eq!(0.0, x.dot(y)); assert_eq!(-1.0, z.dot(-z)); assert_eq!(y, z.cross(x)); assert_eq!(z, x.cross(y)); assert_eq!(4.0, (2.0 * x).length_squared()); assert_eq!(9.0, (-3.0 * y).length_squared()); assert_eq!(16.0, (4.0 * z).length_squared()); assert_eq!(2.0, (-2.0 * x).length()); assert_eq!(3.0, (3.0 * y).length()); assert_eq!(4.0, (-4.0 * z).length()); assert_eq!(2.0, x.distance_squared(y)); assert_eq!(13.0, (2.0 * x).distance_squared(-3.0 * z)); assert_eq!(2.0_f32.sqrt(), x.distance(y)); assert_eq!(5.0, (3.0 * x).distance(-4.0 * y)); assert_eq!(13.0, (-5.0 * z).distance(12.0 * y)); assert_eq!(x, (2.0 * x).normalize()); assert_eq!( 1.0 * 4.0 + 2.0 * 5.0 + 3.0 * 6.0, vec3(1.0, 2.0, 3.0).dot(vec3(4.0, 5.0, 6.0)) ); assert_eq!( 2.0 * 2.0 + 3.0 * 3.0 + 4.0 * 4.0, vec3(2.0, 3.0, 4.0).length_squared() ); assert_eq!( (2.0_f32 * 2.0 + 3.0 * 3.0 + 4.0 * 4.0).sqrt(), vec3(2.0, 3.0, 4.0).length() ); assert_eq!( 1.0 / (2.0_f32 * 2.0 + 3.0 * 3.0 + 4.0 * 4.0).sqrt(), vec3(2.0, 3.0, 4.0).length_recip() ); assert!(vec3(2.0, 3.0, 4.0).normalize().is_normalized()); assert_approx_eq!( vec3(2.0, 3.0, 4.0) / (2.0_f32 * 2.0 + 3.0 * 3.0 + 4.0 * 4.0).sqrt(), vec3(2.0, 3.0, 4.0).normalize() ); assert_eq!(vec3(0.5, 0.25, 0.125), vec3(2.0, 4.0, 8.0).recip()); } #[test] fn test_vec3_ops() { let a = vec3(1.0, 2.0, 3.0); assert_eq!((2.0, 4.0, 6.0), (a + a).into()); assert_eq!((0.0, 0.0, 0.0), (a - a).into()); assert_eq!((1.0, 4.0, 9.0), (a * a).into()); assert_eq!((2.0, 4.0, 6.0), (a * 2.0).into()); assert_eq!((2.0, 4.0, 6.0), (2.0 * a).into()); assert_eq!((1.0, 1.0, 1.0), (a / a).into()); assert_eq!((0.5, 1.0, 1.5), (a / 2.0).into()); assert_eq!((2.0, 1.0, 2.0 / 3.0), (2.0 / a).into()); assert_eq!((-1.0, -2.0, -3.0), (-a).into()); } #[test] fn test_vec3_assign_ops() { let a = vec3(1.0, 2.0, 3.0); let mut b = a; b += a; assert_eq!((2.0, 4.0, 6.0), b.into()); b -= a; assert_eq!((1.0, 2.0, 3.0), b.into()); b *= a; assert_eq!((1.0, 4.0, 9.0), b.into()); b /= a; assert_eq!((1.0, 2.0, 3.0), b.into()); b *= 2.0; assert_eq!((2.0, 4.0, 6.0), b.into()); b /= 2.0; assert_eq!((1.0, 2.0, 3.0), b.into()); } #[test] fn test_vec3_min_max() { let a = vec3(-1.0, 2.0, -3.0); let b = vec3(1.0, -2.0, 3.0); assert_eq!((-1.0, -2.0, -3.0), a.min(b).into()); assert_eq!((-1.0, -2.0, -3.0), b.min(a).into()); assert_eq!((1.0, 2.0, 3.0), a.max(b).into()); assert_eq!((1.0, 2.0, 3.0), b.max(a).into()); } #[test] fn test_vec3_hmin_hmax() { let a = vec3(-1.0, 2.0, -3.0); assert_eq!(-3.0, a.min_element()); assert_eq!(2.0, a.max_element()); } #[test] fn test_vec3_eq() { let a = vec3(1.0, 1.0, 1.0); let b = vec3(1.0, 2.0, 3.0); assert!(a.cmpeq(a).all()); assert!(b.cmpeq(b).all()); assert!(a.cmpne(b).any()); assert!(b.cmpne(a).any()); assert!(b.cmpeq(a).any()); } #[test] fn test_vec3_cmp() { assert!(!Vec3Mask::default().any()); assert!(!Vec3Mask::default().all()); assert_eq!(Vec3Mask::default().bitmask(), 0x0); let a = vec3(-1.0, -1.0, -1.0); let b = vec3(1.0, 1.0, 1.0); let c = vec3(-1.0, -1.0, 1.0); let d = vec3(1.0, -1.0, -1.0); assert_eq!(a.cmplt(a).bitmask(), 0x0); assert_eq!(a.cmplt(b).bitmask(), 0x7); assert_eq!(a.cmplt(c).bitmask(), 0x4); assert_eq!(c.cmple(a).bitmask(), 0x3); assert_eq!(a.cmplt(d).bitmask(), 0x1); assert!(a.cmplt(b).all()); assert!(a.cmplt(c).any()); assert!(a.cmple(b).all()); assert!(a.cmple(a).all()); assert!(b.cmpgt(a).all()); assert!(b.cmpge(a).all()); assert!(b.cmpge(b).all()); assert!(!(a.cmpge(c).all())); assert!(c.cmple(c).all()); assert!(c.cmpge(c).all()); assert!(a == a); assert!(a < b); assert!(b > a); } #[test] fn test_extend_truncate() { let a = vec3(1.0, 2.0, 3.0); let b = a.extend(4.0); assert_eq!((1.0, 2.0, 3.0, 4.0), b.into()); let c = Vec3::from(b.truncate()); assert_eq!(a, c); } #[test] fn test_vec3_mask() { let mut a = Vec3::zero(); a.x = 1.0; a.y = 1.0; a.z = 1.0; assert!(!a.cmpeq(Vec3::zero()).any()); assert!(a.cmpeq(Vec3::splat(1.0)).all()); } #[test] fn test_vec3mask_as_ref() { assert_eq!(Vec3Mask::new(false, false, false).as_ref(), &[0, 0, 0]); assert_eq!(Vec3Mask::new(true, false, false).as_ref(), &[!0, 0, 0]); assert_eq!(Vec3Mask::new(false, true, true).as_ref(), &[0, !0, !0]); assert_eq!(Vec3Mask::new(false, true, false).as_ref(), &[0, !0, 0]); assert_eq!(Vec3Mask::new(true, false, true).as_ref(), &[!0, 0, !0]); assert_eq!(Vec3Mask::new(true, true, true).as_ref(), &[!0, !0, !0]); } #[test] fn test_vec3mask_from() { assert_eq!( Into::<[u32; 3]>::into(Vec3Mask::new(false, false, false)), [0, 0, 0] ); assert_eq!( Into::<[u32; 3]>::into(Vec3Mask::new(true, false, false)), [!0, 0, 0] ); assert_eq!( Into::<[u32; 3]>::into(Vec3Mask::new(false, true, true)), [0, !0, !0] ); assert_eq!( Into::<[u32; 3]>::into(Vec3Mask::new(false, true, false)), [0, !0, 0] ); assert_eq!( Into::<[u32; 3]>::into(Vec3Mask::new(true, false, true)), [!0, 0, !0] ); assert_eq!( Into::<[u32; 3]>::into(Vec3Mask::new(true, true, true)), [!0, !0, !0] ); } #[test] fn test_vec3mask_bitmask() { assert_eq!(Vec3Mask::new(false, false, false).bitmask(), 0b000); assert_eq!(Vec3Mask::new(true, false, false).bitmask(), 0b001); assert_eq!(Vec3Mask::new(false, true, true).bitmask(), 0b110); assert_eq!(Vec3Mask::new(false, true, false).bitmask(), 0b010); assert_eq!(Vec3Mask::new(true, false, true).bitmask(), 0b101); assert_eq!(Vec3Mask::new(true, true, true).bitmask(), 0b111); } #[test] fn test_vec3mask_any() { assert_eq!(Vec3Mask::new(false, false, false).any(), false); assert_eq!(Vec3Mask::new(true, false, false).any(), true); assert_eq!(Vec3Mask::new(false, true, false).any(), true); assert_eq!(Vec3Mask::new(false, false, true).any(), true); } #[test] fn test_vec3mask_all() { assert_eq!(Vec3Mask::new(true, true, true).all(), true); assert_eq!(Vec3Mask::new(false, true, true).all(), false); assert_eq!(Vec3Mask::new(true, false, true).all(), false); assert_eq!(Vec3Mask::new(true, true, false).all(), false); } #[test] fn test_vec3mask_select() { let a = Vec3::new(1.0, 2.0, 3.0); let b = Vec3::new(4.0, 5.0, 6.0); assert_eq!( Vec3Mask::new(true, true, true).select(a, b), Vec3::new(1.0, 2.0, 3.0), ); assert_eq!( Vec3Mask::new(true, false, true).select(a, b), Vec3::new(1.0, 5.0, 3.0), ); assert_eq!( Vec3Mask::new(false, true, false).select(a, b), Vec3::new(4.0, 2.0, 6.0), ); assert_eq!( Vec3Mask::new(false, false, false).select(a, b), Vec3::new(4.0, 5.0, 6.0), ); } #[test] fn test_vec3mask_and() { assert_eq!( (Vec3Mask::new(false, false, false) & Vec3Mask::new(false, false, false)).bitmask(), 0b000, ); assert_eq!( (Vec3Mask::new(true, true, true) & Vec3Mask::new(true, true, true)).bitmask(), 0b111, ); assert_eq!( (Vec3Mask::new(true, false, true) & Vec3Mask::new(false, true, false)).bitmask(), 0b000, ); assert_eq!( (Vec3Mask::new(true, false, true) & Vec3Mask::new(true, true, true)).bitmask(), 0b101, ); let mut mask = Vec3Mask::new(true, true, false); mask &= Vec3Mask::new(true, false, false); assert_eq!(mask.bitmask(), 0b001); } #[test] fn test_vec3mask_or() { assert_eq!( (Vec3Mask::new(false, false, false) | Vec3Mask::new(false, false, false)).bitmask(), 0b000, ); assert_eq!( (Vec3Mask::new(true, true, true) | Vec3Mask::new(true, true, true)).bitmask(), 0b111, ); assert_eq!( (Vec3Mask::new(true, false, true) | Vec3Mask::new(false, true, false)).bitmask(), 0b111, ); assert_eq!( (Vec3Mask::new(true, false, true) | Vec3Mask::new(true, false, true)).bitmask(), 0b101, ); let mut mask = Vec3Mask::new(true, true, false); mask |= Vec3Mask::new(true, false, false); assert_eq!(mask.bitmask(), 0b011); } #[test] fn test_vec3mask_not() { assert_eq!((!Vec3Mask::new(false, false, false)).bitmask(), 0b111); assert_eq!((!Vec3Mask::new(true, true, true)).bitmask(), 0b000); assert_eq!((!Vec3Mask::new(true, false, true)).bitmask(), 0b010); assert_eq!((!Vec3Mask::new(false, true, false)).bitmask(), 0b101); } #[test] fn test_vec3mask_fmt() { let a = Vec3Mask::new(true, false, false); // debug fmt assert_eq!(format!("{:?}", a), "Vec3Mask(0xffffffff, 0x0, 0x0)"); // display fmt assert_eq!(format!("{}", a), "[true, false, false]"); } #[test] fn test_vec3mask_eq() { let a = Vec3Mask::new(true, false, true); let b = Vec3Mask::new(true, false, true); let c = Vec3Mask::new(false, true, true); assert_eq!(a, b); assert_eq!(b, a); assert_ne!(a, c); assert_ne!(b, c); assert!(a > c); assert!(c < a); } #[test] fn test_vec3mask_hash() { use std::collections::hash_map::DefaultHasher; use std::hash::Hash; use std::hash::Hasher; let a = Vec3Mask::new(true, false, true); let b = Vec3Mask::new(true, false, true); let c = Vec3Mask::new(false, true, true); let mut hasher = DefaultHasher::new(); a.hash(&mut hasher); let a_hashed = hasher.finish(); let mut hasher = DefaultHasher::new(); b.hash(&mut hasher); let b_hashed = hasher.finish(); let mut hasher = DefaultHasher::new(); c.hash(&mut hasher); let c_hashed = hasher.finish(); assert_eq!(a, b); assert_eq!(a_hashed, b_hashed); assert_ne!(a, c); assert_ne!(a_hashed, c_hashed); } #[test] fn test_vec3_signum() { assert_eq!(Vec3::zero().signum(), Vec3::one()); assert_eq!(-Vec3::zero().signum(), -Vec3::one()); assert_eq!(Vec3::one().signum(), Vec3::one()); assert_eq!((-Vec3::one()).signum(), -Vec3::one()); assert_eq!(Vec3::splat(f32::INFINITY).signum(), Vec3::one()); assert_eq!(Vec3::splat(f32::NEG_INFINITY).signum(), -Vec3::one()); assert!(Vec3::splat(f32::NAN).signum().is_nan().all()); } #[test] fn test_vec3_abs() { assert_eq!(Vec3::zero().abs(), Vec3::zero()); assert_eq!(Vec3::one().abs(), Vec3::one()); assert_eq!((-Vec3::one()).abs(), Vec3::one()); } #[test] fn test_vec3_round() { assert_eq!(Vec3::new(1.35, 0.0, 0.0).round().x, 1.0); assert_eq!(Vec3::new(0.0, 1.5, 0.0).round().y, 2.0); assert_eq!(Vec3::new(0.0, 0.0, -15.5).round().z, -16.0); assert_eq!(Vec3::new(0.0, 0.0, 0.0).round().z, 0.0); assert_eq!(Vec3::new(0.0, 21.1, 0.0).round().y, 21.0); assert_eq!(Vec3::new(0.0, 11.123, 0.0).round().y, 11.0); assert_eq!(Vec3::new(0.0, 11.499, 0.0).round().y, 11.0); assert_eq!( Vec3::new(f32::NEG_INFINITY, f32::INFINITY, 0.0).round(), Vec3::new(f32::NEG_INFINITY, f32::INFINITY, 0.0) ); assert!(Vec3::new(f32::NAN, 0.0, 0.0).round().x.is_nan()); } #[test] fn test_vec3_floor() { assert_eq!( Vec3::new(1.35, 1.5, -1.5).floor(), Vec3::new(1.0, 1.0, -2.0) ); assert_eq!( Vec3::new(f32::INFINITY, f32::NEG_INFINITY, 0.0).floor(), Vec3::new(f32::INFINITY, f32::NEG_INFINITY, 0.0) ); assert!(Vec3::new(f32::NAN, 0.0, 0.0).floor().x.is_nan()); assert_eq!( Vec3::new(-2000000.123, 10000000.123, 1000.9).floor(), Vec3::new(-2000001.0, 10000000.0, 1000.0) ); } #[test] fn test_vec3_ceil() { assert_eq!(Vec3::new(1.35, 1.5, -1.5).ceil(), Vec3::new(2.0, 2.0, -1.0)); assert_eq!( Vec3::new(f32::INFINITY, f32::NEG_INFINITY, 0.0).ceil(), Vec3::new(f32::INFINITY, f32::NEG_INFINITY, 0.0) ); assert!(Vec3::new(f32::NAN, 0.0, 0.0).ceil().x.is_nan()); assert_eq!( Vec3::new(-2000000.123, 1000000.123, 1000.9).ceil(), Vec3::new(-2000000.0, 1000001.0, 1001.0) ); } #[test] fn test_vec3_lerp() { let v0 = Vec3::new(-1.0, -1.0, -1.0); let v1 = Vec3::new(1.0, 1.0, 1.0); assert_approx_eq!(v0, v0.lerp(v1, 0.0)); assert_approx_eq!(v1, v0.lerp(v1, 1.0)); assert_approx_eq!(Vec3::zero(), v0.lerp(v1, 0.5)); } #[test] fn test_vec3_to_from_slice() { let v = Vec3::new(1.0, 2.0, 3.0); let mut a = [0.0, 0.0, 0.0]; v.write_to_slice_unaligned(&mut a); assert_eq!(v, Vec3::from_slice_unaligned(&a)); } #[test] fn test_vec3_angle_between() { let angle = Vec3::new(1.0, 0.0, 1.0).angle_between(Vec3::new(1.0, 1.0, 0.0)); assert_approx_eq!(f32::consts::FRAC_PI_3, angle, 1e-6); let angle = Vec3::new(10.0, 0.0, 10.0).angle_between(Vec3::new(5.0, 5.0, 0.0)); assert_approx_eq!(f32::consts::FRAC_PI_3, angle, 1e-6); let angle = Vec3::new(-1.0, 0.0, -1.0).angle_between(Vec3::new(1.0, -1.0, 0.0)); assert_approx_eq!(2.0 * f32::consts::FRAC_PI_3, angle, 1e-6); } #[cfg(feature = "serde")] #[test] fn test_vec3_serde() { let a = Vec3::new(1.0, 2.0, 3.0); let serialized = serde_json::to_string(&a).unwrap(); assert_eq!(serialized, "[1.0,2.0,3.0]"); let deserialized = serde_json::from_str(&serialized).unwrap(); assert_eq!(a, deserialized); let deserialized = serde_json::from_str::<Vec3>("[]"); assert!(deserialized.is_err()); let deserialized = serde_json::from_str::<Vec3>("[1.0]"); assert!(deserialized.is_err()); let deserialized = serde_json::from_str::<Vec3>("[1.0,2.0]"); assert!(deserialized.is_err()); let deserialized = serde_json::from_str::<Vec3>("[1.0,2.0,3.0,4.0]"); assert!(deserialized.is_err()); } #[cfg(feature = "rand")] #[test] fn test_vec3_rand() { use rand::{Rng, SeedableRng}; use rand_xoshiro::Xoshiro256Plus; let mut rng1 = Xoshiro256Plus::seed_from_u64(0); let a: (f32, f32, f32) = rng1.gen(); let mut rng2 = Xoshiro256Plus::seed_from_u64(0); let b: Vec3 = rng2.gen(); assert_eq!(a, b.into()); } #[cfg(feature = "std")] #[test] fn test_sum() { let one = Vec3::one(); assert_eq!(vec![one, one].iter().sum::<Vec3>(), one + one); } #[cfg(feature = "std")] #[test] fn test_product() { let two = Vec3::new(2.0, 2.0, 2.0); assert_eq!(vec![two, two].iter().product::<Vec3>(), two * two); }
28.974619
92
0.541053
756f17704ff144fd1cefde34139242cb988f6a70
4,246
#[doc = "Register `ALRMASSR` reader"] pub struct R(crate::R<ALRMASSR_SPEC>); impl core::ops::Deref for R { type Target = crate::R<ALRMASSR_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<ALRMASSR_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<ALRMASSR_SPEC>) -> Self { R(reader) } } #[doc = "Register `ALRMASSR` writer"] pub struct W(crate::W<ALRMASSR_SPEC>); impl core::ops::Deref for W { type Target = crate::W<ALRMASSR_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<ALRMASSR_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<ALRMASSR_SPEC>) -> Self { W(writer) } } #[doc = "Field `MASKSS` reader - Mask the most-significant bits starting at this bit"] pub struct MASKSS_R(crate::FieldReader<u8, u8>); impl MASKSS_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { MASKSS_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for MASKSS_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `MASKSS` writer - Mask the most-significant bits starting at this bit"] pub struct MASKSS_W<'a> { w: &'a mut W, } impl<'a> MASKSS_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 24)) | ((value as u32 & 0x0f) << 24); self.w } } #[doc = "Field `SS` reader - Sub seconds value"] pub struct SS_R(crate::FieldReader<u16, u16>); impl SS_R { #[inline(always)] pub(crate) fn new(bits: u16) -> Self { SS_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for SS_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `SS` writer - Sub seconds value"] pub struct SS_W<'a> { w: &'a mut W, } impl<'a> SS_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0x7fff) | (value as u32 & 0x7fff); self.w } } impl R { #[doc = "Bits 24:27 - Mask the most-significant bits starting at this bit"] #[inline(always)] pub fn maskss(&self) -> MASKSS_R { MASKSS_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bits 0:14 - Sub seconds value"] #[inline(always)] pub fn ss(&self) -> SS_R { SS_R::new((self.bits & 0x7fff) as u16) } } impl W { #[doc = "Bits 24:27 - Mask the most-significant bits starting at this bit"] #[inline(always)] pub fn maskss(&mut self) -> MASKSS_W { MASKSS_W { w: self } } #[doc = "Bits 0:14 - Sub seconds value"] #[inline(always)] pub fn ss(&mut self) -> SS_W { SS_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "alarm A sub second register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [alrmassr](index.html) module"] pub struct ALRMASSR_SPEC; impl crate::RegisterSpec for ALRMASSR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [alrmassr::R](R) reader structure"] impl crate::Readable for ALRMASSR_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [alrmassr::W](W) writer structure"] impl crate::Writable for ALRMASSR_SPEC { type Writer = W; } #[doc = "`reset()` method sets ALRMASSR to value 0"] impl crate::Resettable for ALRMASSR_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
30.113475
416
0.593971
4bcdd980f4ff9ade7e15c669f6f4ecbc753eef17
3,018
// AUTOGENERATED FROM index-iso-8859-10.txt, ORIGINAL COMMENT FOLLOWS: // // Any copyright is dedicated to the Public Domain. // http://creativecommons.org/publicdomain/zero/1.0/ // // For details on index-iso-8859-10.txt see the Encoding Standard // http://encoding.spec.whatwg.org/ static FORWARD_TABLE: &'static [u16] = &[ 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 260, 274, 290, 298, 296, 310, 167, 315, 272, 352, 358, 381, 173, 362, 330, 176, 261, 275, 291, 299, 297, 311, 183, 316, 273, 353, 359, 382, 8213, 363, 331, 256, 193, 194, 195, 196, 197, 198, 302, 268, 201, 280, 203, 278, 205, 206, 207, 208, 325, 332, 211, 212, 213, 214, 360, 216, 370, 218, 219, 220, 221, 222, 223, 257, 225, 226, 227, 228, 229, 230, 303, 269, 233, 281, 235, 279, 237, 238, 239, 240, 326, 333, 243, 244, 245, 246, 361, 248, 371, 250, 251, 252, 253, 254, 312, ]; #[inline] pub fn forward(code: u8) -> u16 { FORWARD_TABLE[code as uint] } #[inline] pub fn backward(code: u16) -> u8 { match code { 128 => 0, 129 => 1, 130 => 2, 131 => 3, 132 => 4, 133 => 5, 134 => 6, 135 => 7, 136 => 8, 137 => 9, 138 => 10, 139 => 11, 140 => 12, 141 => 13, 142 => 14, 143 => 15, 144 => 16, 145 => 17, 146 => 18, 147 => 19, 148 => 20, 149 => 21, 150 => 22, 151 => 23, 152 => 24, 153 => 25, 154 => 26, 155 => 27, 156 => 28, 157 => 29, 158 => 30, 159 => 31, 160 => 32, 260 => 33, 274 => 34, 290 => 35, 298 => 36, 296 => 37, 310 => 38, 167 => 39, 315 => 40, 272 => 41, 352 => 42, 358 => 43, 381 => 44, 173 => 45, 362 => 46, 330 => 47, 176 => 48, 261 => 49, 275 => 50, 291 => 51, 299 => 52, 297 => 53, 311 => 54, 183 => 55, 316 => 56, 273 => 57, 353 => 58, 359 => 59, 382 => 60, 8213 => 61, 363 => 62, 331 => 63, 256 => 64, 193 => 65, 194 => 66, 195 => 67, 196 => 68, 197 => 69, 198 => 70, 302 => 71, 268 => 72, 201 => 73, 280 => 74, 203 => 75, 278 => 76, 205 => 77, 206 => 78, 207 => 79, 208 => 80, 325 => 81, 332 => 82, 211 => 83, 212 => 84, 213 => 85, 214 => 86, 360 => 87, 216 => 88, 370 => 89, 218 => 90, 219 => 91, 220 => 92, 221 => 93, 222 => 94, 223 => 95, 257 => 96, 225 => 97, 226 => 98, 227 => 99, 228 => 100, 229 => 101, 230 => 102, 303 => 103, 269 => 104, 233 => 105, 281 => 106, 235 => 107, 279 => 108, 237 => 109, 238 => 110, 239 => 111, 240 => 112, 326 => 113, 333 => 114, 243 => 115, 244 => 116, 245 => 117, 246 => 118, 361 => 119, 248 => 120, 371 => 121, 250 => 122, 251 => 123, 252 => 124, 253 => 125, 254 => 126, 312 => 127, _ => 255 } } #[cfg(test)] mod tests { use super::{forward, backward}; #[test] fn test_correct_table() { for i in range(0u8, 128) { let j = forward(i); if j != 0xffff { assert_eq!(backward(j), i); } } } }
45.727273
79
0.49503
894e8217468d387af674c11c3f59b5ebd8140641
2,843
use core_model::*; use lobby_model::*; pub trait GameLobbyOps { fn open(&self, game: Game) -> Self; fn ready(&self, game: &Game) -> Self; fn abandon(&self, session_id: &SessionId) -> Self; } impl GameLobbyOps for GameLobby { fn open(&self, game: Game) -> Self { let mut r = self.clone(); r.games.insert(game); r } fn ready(&self, game: &Game) -> Self { let mut r = self.clone(); r.games.remove(&game); r } fn abandon(&self, session_id: &SessionId) -> Self { let mut r = self.clone(); if let Some(game) = r.games.clone().iter().find(|g| &g.creator == session_id) { r.games.remove(game); } r } } trait AsBytes { fn as_bytes(&self) -> Result<Vec<u8>, Box<bincode::ErrorKind>>; } impl AsBytes for GameLobby { fn as_bytes(&self) -> Result<Vec<u8>, Box<bincode::ErrorKind>> { bincode::serialize(self) } } #[cfg(test)] mod tests { use super::*; #[test] fn lobby_as_bytes() { let lobby = GameLobby::default(); assert!(lobby.as_bytes().is_ok()); let next = lobby.open(Game { game_id: GameId::new(), board_size: 3, creator: SessionId::new(), visibility: Visibility::Private, }); assert!(!next.games.is_empty()); assert!(next.as_bytes().is_ok()); } #[test] fn lobby_open() { let lobby = GameLobby::default(); let one = lobby.open(Game { game_id: GameId::new(), board_size: 19, creator: SessionId::new(), visibility: Visibility::Public, }); assert_eq!(one.games.len(), 1); let two = one.open(Game { game_id: GameId::new(), board_size: 13, creator: SessionId::new(), visibility: Visibility::Private, }); assert_eq!(two.games.len(), 2) } #[test] fn lobby_ready() { let lobby = GameLobby::default(); let game = Game { game_id: GameId::new(), board_size: 19, creator: SessionId::new(), visibility: Visibility::Public, }; let one = lobby.open(game.clone()); assert_eq!(one.games.len(), 1); let done = one.ready(&game); assert!(done.games.is_empty()) } #[test] fn lobby_abandon() { let lobby = GameLobby::default(); let sid = SessionId::new(); let creator = sid.clone(); let one = lobby.open(Game { game_id: GameId::new(), board_size: 19, creator, visibility: Visibility::Public, }); assert_eq!(one.games.len(), 1); let done = one.abandon(&sid); assert!(done.games.is_empty()); } }
24.938596
87
0.513542
18bf9783b3ec4c73b427682b4af4c245944bd775
5,499
use crate::prelude::*; use rand::Rng; use std::thread::sleep; use std::time::Duration; #[derive(Arcon, Arrow, prost::Message, Copy, Clone)] #[arcon(unsafe_ser_id = 12, reliable_ser_id = 13, version = 1)] pub struct Event { #[prost(uint64)] pub data: u64, #[prost(uint32)] pub key: u32, } #[derive(Arcon, Arrow, prost::Message, Copy, Clone)] #[arcon(unsafe_ser_id = 12, reliable_ser_id = 13, version = 1)] pub struct EnrichedEvent { #[prost(uint64)] pub data: u64, #[prost(uint32)] pub key: u32, #[prost(uint64)] pub first_val: u64, } #[derive(ArconState)] pub struct FirstVal<B: Backend> { #[table = "Count"] events: EagerValue<u64, B>, } const PARALLELISM: usize = 2; const NUM_KEYS: usize = 256; const EVENT_COUNT: u64 = 99946; // Idk what's special about this number but 100k wasn't reliable fn operator_conf() -> OperatorConf { OperatorConf { parallelism_strategy: ParallelismStrategy::Static(PARALLELISM), ..Default::default() } } // Sets up a pipeline of iterator -> event -> key_by -> enriched_event fn enriched_event_stream() -> Stream<EnrichedEvent> { let app_conf = ApplicationConf { epoch_interval: 2500, ctrl_system_host: Some("127.0.0.1:0".to_string()), ..Default::default() }; Application::with_conf(app_conf) .with_debug_node() .iterator(0u64..EVENT_COUNT, |conf| { conf.set_arcon_time(ArconTime::Event); conf.set_timestamp_extractor(|x: &u64| *x); }) .operator(OperatorBuilder { // Map u64 -> Event operator: Arc::new(move || { Map::new({ |i| { let mut rng = rand::thread_rng(); let r: u32 = rng.gen(); Event { data: i, key: r % (NUM_KEYS as u32), } } }) }), state: Arc::new(|_| EmptyState), conf: operator_conf(), }) .key_by(|event| &event.key) .operator(OperatorBuilder { operator: Arc::new(|| { // Map Event -> EnrichedEvent Map::stateful(|event: Event, state: &mut FirstVal<_>| { // Just use state somehow, this should be the same for all events let first_val: u64 = if let Some(value) = state.events().get()? { *value } else { state.events().put(event.data)?; event.data }; Ok(EnrichedEvent { data: event.data, key: event.key, first_val, }) }) }), state: Arc::new(|backend| FirstVal { events: EagerValue::new("_events", backend), }), conf: operator_conf(), }) } #[test] fn key_by_integration() { let mut app = enriched_event_stream().build(); app.start(); sleep(Duration::from_secs(4)); if let Some(debug_node) = app.get_debug_node::<EnrichedEvent>() { debug_node.on_definition(|c| { let mut first_val_vec = Vec::new(); for element in c.data.iter() { first_val_vec.push(element.data.first_val); } // all events were received by the debug node // assert_eq!(first_val_vec.len(), (EVENT_COUNT-2) as usize); // Something funky is happening to the events? first_val_vec.sort_unstable(); first_val_vec.dedup(); // Only NUM_KEYS number of first_val were received, i.e. State was handled properly assert_eq!(first_val_vec.len(), NUM_KEYS); // The DebugNode received events from the same assert_eq!(c.senders.len(), PARALLELISM); }) } else { panic!("Failed to get DebugNode!") } } // Same test as above except we add another Map: EnrichedEvent -> EnrichedEvent with a Forward channel #[test] fn key_by_to_forward_integration() { let mut app = enriched_event_stream() .operator(OperatorBuilder { operator: Arc::new(|| { // Map EnrichedEvent -> EnrichedEvent Map::new(|event: EnrichedEvent| event) }), state: Arc::new(|_| EmptyState), conf: operator_conf(), }) .build(); app.start(); sleep(Duration::from_secs(4)); if let Some(debug_node) = app.get_debug_node::<EnrichedEvent>() { debug_node.on_definition(|c| { let mut first_val_vec = Vec::new(); for element in c.data.iter() { first_val_vec.push(element.data.first_val); } // all events were received by the debug node // assert_eq!(first_val_vec.len(), (EVENT_COUNT-2) as usize); // Something funky is happening to the events? first_val_vec.sort_unstable(); first_val_vec.dedup(); // Only NUM_KEYS number of first_val were received, i.e. State was handled properly assert_eq!(first_val_vec.len(), NUM_KEYS); // The DebugNode received events from two different nodes assert_eq!(c.senders.len(), PARALLELISM); }) } else { panic!("Failed to get DebugNode!") } }
33.944444
120
0.537734
26984dcb6ef53c6f82096116875b91a6e27a72a9
21,321
// Copyright 2020 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. use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::convert::TryFrom; use fidl_fuchsia_media::AudioRenderUsage; use fidl_fuchsia_settings_policy::{PolicyParameters, Volume}; use bitflags::bitflags; use crate::audio::types::AudioStreamType; use crate::audio::utils::round_volume_level; use crate::handler::device_storage::DeviceStorageCompatible; pub mod audio_policy_handler; pub mod volume_policy_fidl_handler; pub type PropertyTarget = AudioStreamType; /// Unique identifier for a policy. #[derive(Debug, Copy, Clone, Hash, Ord, PartialOrd, Eq, PartialEq, Serialize, Deserialize)] pub struct PolicyId(u32); impl PolicyId { pub(crate) fn create(policy_id: u32) -> Self { Self(policy_id) } } /// `StateBuilder` is used to construct a new [`State`] as the internal /// modification of properties should not be available post construction. /// /// [`State`]: struct.State.html pub(crate) struct StateBuilder { properties: HashMap<PropertyTarget, Property>, } impl StateBuilder { pub(crate) fn new() -> Self { Self { properties: HashMap::new() } } pub(crate) fn add_property( mut self, stream_type: PropertyTarget, available_transforms: TransformFlags, ) -> Self { let property = Property::new(stream_type, available_transforms); self.properties.insert(stream_type, property); self } pub(crate) fn build(self) -> State { State { properties: self.properties } } } /// `State` defines the current configuration of the audio policy. This /// includes the available properties, which encompass the active transform /// policies and transforms available to be set. #[derive(PartialEq, Default, Debug, Clone, Serialize, Deserialize)] pub struct State { properties: HashMap<PropertyTarget, Property>, } impl State { #[cfg(test)] pub(crate) fn get_properties(&self) -> Vec<Property> { self.properties.values().cloned().collect::<Vec<Property>>() } #[cfg(test)] pub(crate) fn properties(&mut self) -> &mut HashMap<PropertyTarget, Property> { &mut self.properties } /// Attempts to find the policy with the given ID from the state. Returns the policy target if /// it was found and removed, else returns None. pub(crate) fn find_policy_target(&self, policy_id: PolicyId) -> Option<PropertyTarget> { self.properties .values() .find_map(|property| property.find_policy(policy_id).map(|_| property.target)) } /// Attempts to remove the policy with the given ID from the state. Returns the policy target if /// it was found and removed, else returns None. pub(crate) fn remove_policy(&mut self, policy_id: PolicyId) -> Option<PropertyTarget> { self.properties .values_mut() .find_map(|property| property.remove_policy(policy_id).map(|_| property.target)) } /// Attempts to add a new policy transform to the given target. Returns the [`PolicyId`] of the /// new policy, or None if the target doesn't exist. pub(crate) fn add_transform( &mut self, target: PropertyTarget, transform: Transform, ) -> Option<PolicyId> { let next_id = self.next_id(); // Round policy volume levels to the same precision as the base audio setting. let rounded_transform = match transform { Transform::Max(value) => Transform::Max(round_volume_level(value)), Transform::Min(value) => Transform::Min(round_volume_level(value)), }; self.properties.get_mut(&target)?.add_transform(rounded_transform, next_id); Some(next_id) } /// Returns next [`PolicyId`] to assign for a new transform. The ID will be unique and the /// highest of any existing policy. fn next_id(&self) -> PolicyId { let PolicyId(highest_id) = self .properties .values() .filter_map(|property| property.highest_id()) .max() .unwrap_or_else(|| PolicyId::create(0)); PolicyId::create(highest_id + 1) } } impl DeviceStorageCompatible for State { fn default_value() -> Self { State { properties: Default::default() } } const KEY: &'static str = "audio_policy_state"; } /// `Property` defines the current policy configuration over a given audio /// stream type. #[derive(PartialEq, Debug, Clone, Serialize, Deserialize)] pub(crate) struct Property { /// Identifier used to reference this type over other requests, such as /// setting a policy. pub(crate) target: PropertyTarget, /// The available transforms provided as a bitmask. pub(crate) available_transforms: TransformFlags, /// The active transform definitions on this stream type. pub(crate) active_policies: Vec<Policy>, } impl Property { pub(crate) fn new(stream_type: AudioStreamType, available_transforms: TransformFlags) -> Self { Self { target: stream_type, available_transforms, active_policies: vec![] } } /// Adds the given transform to this property. fn add_transform(&mut self, transform: Transform, id: PolicyId) { self.active_policies.push(Policy { id, transform }); } /// Attempts to find the policy with the given ID in this property. Returns the policy if it /// was found, else returns None. pub(crate) fn find_policy(&self, policy_id: PolicyId) -> Option<Policy> { self.active_policies.iter().find(|policy| policy.id == policy_id).copied() } /// Attempts to remove the policy with the given ID from this property. Returns the policy if it /// was found and removed, else returns None. pub(crate) fn remove_policy(&mut self, policy_id: PolicyId) -> Option<Policy> { match self.active_policies.iter().position(|policy| policy.id == policy_id) { Some(index) => Some(self.active_policies.remove(index)), None => None, } } /// Returns the highest [`PolicyId`] in the active policies of this property, or None if there /// are no active policies. pub(crate) fn highest_id(&self) -> Option<PolicyId> { self.active_policies.iter().map(|policy| policy.id).max() } } impl From<Property> for fidl_fuchsia_settings_policy::Property { fn from(src: Property) -> Self { fidl_fuchsia_settings_policy::Property { target: Some(src.target.into()), available_transforms: Some(src.available_transforms.into()), active_policies: Some( src.active_policies.into_iter().map(Policy::into).collect::<Vec<_>>(), ), ..fidl_fuchsia_settings_policy::Property::EMPTY } } } impl From<fidl_fuchsia_settings_policy::Target> for AudioStreamType { fn from(src: fidl_fuchsia_settings_policy::Target) -> Self { match src { fidl_fuchsia_settings_policy::Target::Stream(AudioRenderUsage::Background) => { AudioStreamType::Background } fidl_fuchsia_settings_policy::Target::Stream(AudioRenderUsage::Media) => { AudioStreamType::Media } fidl_fuchsia_settings_policy::Target::Stream(AudioRenderUsage::Interruption) => { AudioStreamType::Interruption } fidl_fuchsia_settings_policy::Target::Stream(AudioRenderUsage::SystemAgent) => { AudioStreamType::SystemAgent } fidl_fuchsia_settings_policy::Target::Stream(AudioRenderUsage::Communication) => { AudioStreamType::Communication } } } } impl From<AudioStreamType> for fidl_fuchsia_settings_policy::Target { fn from(src: AudioStreamType) -> Self { match src { AudioStreamType::Background => { fidl_fuchsia_settings_policy::Target::Stream(AudioRenderUsage::Background) } AudioStreamType::Media => { fidl_fuchsia_settings_policy::Target::Stream(AudioRenderUsage::Media) } AudioStreamType::Interruption => { fidl_fuchsia_settings_policy::Target::Stream(AudioRenderUsage::Interruption) } AudioStreamType::SystemAgent => { fidl_fuchsia_settings_policy::Target::Stream(AudioRenderUsage::SystemAgent) } AudioStreamType::Communication => { fidl_fuchsia_settings_policy::Target::Stream(AudioRenderUsage::Communication) } } } } bitflags! { /// `TransformFlags` defines the available transform space. #[derive(Serialize, Deserialize)] pub(crate) struct TransformFlags: u64 { const TRANSFORM_MAX = 1 << 0; const TRANSFORM_MIN = 1 << 1; } } impl From<TransformFlags> for Vec<fidl_fuchsia_settings_policy::Transform> { fn from(src: TransformFlags) -> Self { let mut transforms = Vec::new(); if src.contains(TransformFlags::TRANSFORM_MAX) { transforms.push(fidl_fuchsia_settings_policy::Transform::Max); } if src.contains(TransformFlags::TRANSFORM_MIN) { transforms.push(fidl_fuchsia_settings_policy::Transform::Min); } transforms } } /// `Policy` captures a fully specified transform. #[derive(PartialEq, Debug, Copy, Clone, Serialize, Deserialize)] pub(crate) struct Policy { pub(crate) id: PolicyId, pub(crate) transform: Transform, } impl From<Policy> for fidl_fuchsia_settings_policy::Policy { fn from(src: Policy) -> Self { fidl_fuchsia_settings_policy::Policy { policy_id: Some(src.id.0), parameters: Some(src.transform.into()), ..fidl_fuchsia_settings_policy::Policy::EMPTY } } } /// `Transform` provides the parameters for specifying a transform. #[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)] pub enum Transform { // Limits the maximum volume an audio stream can be set to. Max(f32), // Sets a floor for the minimum volume an audio stream can be set to. Min(f32), } impl TryFrom<PolicyParameters> for Transform { type Error = &'static str; fn try_from(src: PolicyParameters) -> Result<Self, Self::Error> { // Support future expansion of FIDL. #[allow(unreachable_patterns)] Ok(match src { PolicyParameters::Max(Volume { volume, .. }) => { if volume.map_or(false, |val| !val.is_finite()) { return Err("max volume is not a finite number"); } else { Transform::Max(volume.ok_or("missing max volume")?) } } PolicyParameters::Min(Volume { volume, .. }) => { if volume.map_or(false, |val| !val.is_finite()) { return Err("min volume is not a finite number"); } else { Transform::Min(volume.ok_or("missing min volume")?) } } _ => return Err("unknown policy parameter"), }) } } impl From<Transform> for PolicyParameters { fn from(src: Transform) -> Self { match src { Transform::Max(vol) => { PolicyParameters::Max(Volume { volume: Some(vol), ..Volume::EMPTY }) } Transform::Min(vol) => { PolicyParameters::Min(Volume { volume: Some(vol), ..Volume::EMPTY }) } } } } /// Available requests to interact with the volume policy. #[derive(PartialEq, Clone, Debug)] pub enum Request { /// Adds a policy transform to the specified property. If successful, this transform will become /// a policy on the property. AddPolicy(PropertyTarget, Transform), /// Removes an existing policy on the property. RemovePolicy(PolicyId), } /// Successful responses for [`Request`] /// /// [`Request`]: enum.Request.html #[derive(PartialEq, Clone, Debug)] pub enum Response { /// Response to any transform addition or policy removal. The returned id /// represents the modified policy. Policy(PolicyId), } #[cfg(test)] mod tests { use crate::audio::policy::{ PolicyId, Property, PropertyTarget, StateBuilder, Transform, TransformFlags, }; use crate::audio::types::AudioStreamType; use crate::audio::utils::round_volume_level; use fidl_fuchsia_settings_policy::{PolicyParameters, Volume}; use matches::assert_matches; use std::collections::{HashMap, HashSet}; use std::convert::TryFrom; /// Verifies that adding a max volume transform with the given volume limit results in a /// transform being added with the expected volume limit. /// /// While the input limit and actual added limit are usually the same, rounding or clamping may /// result in differences. fn set_and_verify_max_volume(input_volume_limit: f32, actual_volume_limit: f32) { let target = AudioStreamType::Background; let mut state = StateBuilder::new().add_property(target, TransformFlags::TRANSFORM_MAX).build(); state.add_transform(target, Transform::Max(input_volume_limit)).expect("add succeeded"); let added_policy = state .properties() .get(&target) .expect("found target") .active_policies .first() .expect("has policy"); // Volume limit values are rounded to two decimal places, similar to audio setting volumes. // When comparing the values, we use an epsilon that's smaller than the threshold for // rounding. let epsilon = 0.0001; assert!(matches!(added_policy.transform, Transform::Max(max_volume_limit) if (max_volume_limit - actual_volume_limit).abs() <= epsilon)); } /// Verifies that using `TryFrom` to convert a `PolicyParameters` into a `Transform` will fail /// if the source did not have required parameters specified. #[test] fn parameter_to_transform_missing_arguments() { let max_params = PolicyParameters::Max(Volume { volume: None, ..Volume::EMPTY }); let min_params = PolicyParameters::Min(Volume { volume: None, ..Volume::EMPTY }); assert_matches!(Transform::try_from(max_params), Err(_)); assert_matches!(Transform::try_from(min_params), Err(_)); } /// Verifies that using `TryFrom` to convert a `PolicyParameters` into a `Transform` will fail /// if the source did not have a finite number. #[test] fn parameter_to_transform_invalid_arguments() { let max_params = PolicyParameters::Max(Volume { volume: Some(f32::NEG_INFINITY), ..Volume::EMPTY }); let min_params = PolicyParameters::Min(Volume { volume: Some(f32::NAN), ..Volume::EMPTY }); assert_matches!(Transform::try_from(max_params), Err(_)); assert_matches!(Transform::try_from(min_params), Err(_)); } /// Verifies that using `TryFrom` to convert a `PolicyParameters` into a `Transform` succeeds /// and that the result contains the same parameters as the source. #[test] fn parameter_to_transform() { let max_volume = 0.5; let min_volume = 0.5; let max_params = PolicyParameters::Max(Volume { volume: Some(max_volume), ..Volume::EMPTY }); let min_params = PolicyParameters::Min(Volume { volume: Some(min_volume), ..Volume::EMPTY }); assert_eq!(Transform::try_from(max_params), Ok(Transform::Max(max_volume))); assert_eq!(Transform::try_from(min_params), Ok(Transform::Min(min_volume))); } // Verifies that the audio policy state builder functions correctly for adding targets and // transforms. #[test] fn test_state_builder() { let properties: HashMap<AudioStreamType, TransformFlags> = [ (AudioStreamType::Background, TransformFlags::TRANSFORM_MAX), (AudioStreamType::Media, TransformFlags::TRANSFORM_MIN), ] .iter() .cloned() .collect(); let mut builder = StateBuilder::new(); for (property, value) in properties.iter() { builder = builder.add_property(*property, *value); } let state = builder.build(); let retrieved_properties = state.get_properties(); assert_eq!(retrieved_properties.len(), properties.len()); let mut seen_targets = HashSet::<PropertyTarget>::new(); for property in retrieved_properties.iter().cloned() { let target = property.target; // Make sure only unique targets are encountered. #[allow(clippy::bool_assert_comparison)] { assert_eq!(seen_targets.contains(&target), false); } seen_targets.insert(target); // Ensure the specified transforms are present. assert_eq!( property.available_transforms, *properties.get(&target).expect("unexpected property") ); } } // Verifies that the next ID for a new transform is 1 when the state is empty. #[test] fn test_state_next_id_when_empty() { let state = StateBuilder::new() .add_property(AudioStreamType::Background, TransformFlags::TRANSFORM_MAX) .build(); assert_eq!(state.next_id(), PolicyId::create(1)); } // Verifies that the audio policy state produces increasing IDs when adding transforms. #[test] fn test_state_add_transform_ids_increasing() { let target = AudioStreamType::Background; let mut state = StateBuilder::new().add_property(target, TransformFlags::TRANSFORM_MAX).build(); let mut last_id = PolicyId::create(0); // Verify that each new policy ID is larger than the last. for _ in 0..10 { let next_id = state.next_id(); let id = state.add_transform(target, Transform::Min(0.0)).expect("target found"); assert!(id > last_id); assert_eq!(next_id, id); // Each new ID should also be the highest ID. last_id = id; } } // Verifies that the audio policy state rounds volume limit levels. #[test] fn test_state_add_transform_inputs_rounded() { // Test various starting volumes to make sure rounding works. let mut input_volume_limit = 0.0; set_and_verify_max_volume(input_volume_limit, round_volume_level(input_volume_limit)); input_volume_limit = 0.000001; set_and_verify_max_volume(input_volume_limit, round_volume_level(input_volume_limit)); input_volume_limit = 0.44444; set_and_verify_max_volume(input_volume_limit, round_volume_level(input_volume_limit)); } // Verifies that the audio policy state clamps volume limit levels. #[test] fn test_state_add_transform_inputs_clamped() { let min_volume = 0.0; let max_volume = 1.0; // Values below the minimum volume level are clamped to the minimum volume level. set_and_verify_max_volume(-0.0, min_volume); set_and_verify_max_volume(-0.1, min_volume); set_and_verify_max_volume(f32::MIN, min_volume); set_and_verify_max_volume(f32::NEG_INFINITY, min_volume); // Values above the maximum volume level are clamped to the maximum volume level. set_and_verify_max_volume(1.1, max_volume); set_and_verify_max_volume(f32::MAX, max_volume); set_and_verify_max_volume(f32::INFINITY, max_volume); } // Verifies that adding transforms to policy properties works. #[test] fn test_property_transforms() { let supported_transforms = TransformFlags::TRANSFORM_MAX | TransformFlags::TRANSFORM_MIN; let transforms = [Transform::Min(0.1), Transform::Max(0.9)]; let mut property = Property::new(AudioStreamType::Media, supported_transforms); let mut property2 = Property::new(AudioStreamType::Background, supported_transforms); for transform in transforms.iter().cloned() { property.add_transform(transform, PolicyId::create(0)); property2.add_transform(transform, PolicyId::create(1)); } // Ensure policy size matches transforms specified. assert_eq!(property.active_policies.len(), transforms.len()); assert_eq!(property2.active_policies.len(), transforms.len()); let mut retrieved_ids: HashSet<PolicyId> = property.active_policies.iter().map(|policy| policy.id).collect(); retrieved_ids.extend(property2.active_policies.iter().map(|policy| policy.id)); // Verify transforms are present. let mut retrieved_transforms = property.active_policies.iter().map(|policy| policy.transform); let mut retrieved_transforms2 = property2.active_policies.iter().map(|policy| policy.transform); for transform in transforms { assert!(retrieved_transforms.any(|x| x == transform)); assert!(retrieved_transforms2.any(|x| x == transform)); } } }
38.278276
100
0.647437
feb405314891aca753291132a6c36f00039f23d6
8,141
#![windows_subsystem = "windows"] mod commands; use alvr_common::prelude::*; use alvr_filesystem as afs; use druid::{ commands::CLOSE_WINDOW, theme, widget::{Button, CrossAxisAlignment, Flex, FlexParams, Label, LineBreaking, ViewSwitcher}, AppDelegate, AppLauncher, Color, Command, Data, DelegateCtx, Env, ExtEventSink, FontDescriptor, Handled, Screen, Selector, Target, Widget, WindowDesc, WindowId, }; use std::{env, thread, time::Duration}; const WINDOW_WIDTH: f64 = 500.0; const WINDOW_HEIGHT: f64 = 300.0; const CHANGE_VIEW_CMD: Selector<View> = Selector::new("change_view"); #[derive(Clone, PartialEq, Data)] enum View { RequirementsCheck { steamvr: String }, Launching { resetting: bool }, } fn launcher_lifecycle(handle: ExtEventSink, window_id: WindowId) { loop { let steamvr_ok = commands::check_steamvr_installation(); if steamvr_ok { break; } else { let steamvr_string = "SteamVR not installed: make sure you launched it at least once, then close it."; handle .submit_command( CHANGE_VIEW_CMD, View::RequirementsCheck { steamvr: steamvr_string.to_owned(), }, Target::Auto, ) .ok(); thread::sleep(Duration::from_millis(500)); } } handle .submit_command( CHANGE_VIEW_CMD, View::Launching { resetting: false }, Target::Auto, ) .ok(); let request_agent = ureq::AgentBuilder::new() .timeout_connect(Duration::from_millis(100)) .build(); let mut tried_steamvr_launch = false; loop { // get a small non-code file let maybe_response = request_agent.get("http://127.0.0.1:8082/index.html").call(); if let Ok(response) = maybe_response { if response.status() == 200 { handle.submit_command(CLOSE_WINDOW, (), window_id).ok(); break; } } // try to launch SteamVR only one time automatically if !tried_steamvr_launch { if alvr_common::show_err(commands::maybe_register_alvr_driver()).is_some() { if commands::is_steamvr_running() { commands::kill_steamvr(); thread::sleep(Duration::from_secs(2)) } commands::maybe_launch_steamvr(); } tried_steamvr_launch = true; } thread::sleep(Duration::from_millis(500)); } } fn reset_and_retry(handle: ExtEventSink) { thread::spawn(move || { handle .submit_command( CHANGE_VIEW_CMD, View::Launching { resetting: true }, Target::Auto, ) .ok(); commands::kill_steamvr(); commands::fix_steamvr(); commands::restart_steamvr(); thread::sleep(Duration::from_secs(2)); handle .submit_command( CHANGE_VIEW_CMD, View::Launching { resetting: false }, Target::Auto, ) .ok(); }); } fn gui() -> impl Widget<View> { ViewSwitcher::new( |view: &View, _| view.clone(), |view, _, _| match view { View::RequirementsCheck { steamvr } => Box::new( Flex::row() .with_default_spacer() .with_flex_child( Flex::column() .cross_axis_alignment(CrossAxisAlignment::Start) .with_flex_spacer(1.0) .with_child( Label::new(steamvr.clone()) .with_line_break_mode(LineBreaking::WordWrap), ) .with_default_spacer() .with_flex_spacer(1.5), FlexParams::new(1.0, None), ) .with_default_spacer(), ), View::Launching { resetting } => { let mut flex = Flex::column() .with_spacer(60.0) .with_child(Label::new("Waiting for server to load...").with_text_size(25.0)) .with_default_spacer(); if !resetting { flex = flex.with_child( Button::new("Reset drivers and retry") .on_click(move |ctx, _, _| reset_and_retry(ctx.get_external_handle())), ) } else { flex = flex.with_child(Label::new("Please wait for multiple restarts")) } Box::new(flex.with_flex_spacer(1.0)) } }, ) } struct Delegate; impl AppDelegate<View> for Delegate { fn command( &mut self, _: &mut DelegateCtx, _: Target, cmd: &Command, view: &mut View, _: &Env, ) -> Handled { if let Some(new_view) = cmd.get(CHANGE_VIEW_CMD) { *view = new_view.clone(); Handled::Yes } else { Handled::No } } } fn get_window_location() -> (f64, f64) { let screen_size = Screen::get_monitors() .into_iter() .find(|m| m.is_primary()) .map(|m| m.virtual_work_rect().size()) .unwrap_or_default(); ( (screen_size.width - WINDOW_WIDTH) / 2.0, (screen_size.height - WINDOW_HEIGHT) / 2.0, ) } fn make_window() -> StrResult { let instance_mutex = trace_err!(single_instance::SingleInstance::new("alvr_launcher_mutex"))?; if instance_mutex.is_single() { let driver_dir = afs::filesystem_layout_from_launcher_exe(&env::current_exe().unwrap()) .openvr_driver_root_dir; if driver_dir.to_str().filter(|s| s.is_ascii()).is_none() { alvr_common::show_e_blocking(format!( "The path of this folder ({}) contains non ASCII characters. {}", driver_dir.to_string_lossy(), "Please move it somewhere else (for example in C:\\Users\\Public\\Documents).", )); return Ok(()); } #[cfg(target_os = "linux")] trace_err!(gtk::init())?; let window = WindowDesc::new(gui) .title("ALVR Launcher") .window_size((WINDOW_WIDTH, WINDOW_HEIGHT)) .with_min_size((WINDOW_WIDTH, WINDOW_HEIGHT)) .resizable(false) .set_position(get_window_location()); let state = View::RequirementsCheck { steamvr: "".into() }; let window_id = window.id; let app = AppLauncher::with_window(window) .use_simple_logger() .configure_env(|env, _| { env.set(theme::UI_FONT, FontDescriptor::default().with_size(15.0)); env.set(theme::LABEL_COLOR, Color::rgb8(0, 0, 0)); env.set( theme::WINDOW_BACKGROUND_COLOR, Color::rgb8(0xFF, 0xFF, 0xFF), ); env.set(theme::WIDGET_PADDING_HORIZONTAL, 35); env.set(theme::WIDGET_PADDING_VERTICAL, 15); // button gradient env.set(theme::BUTTON_LIGHT, Color::rgb8(0xF0, 0xF0, 0xF0)); env.set(theme::BUTTON_DARK, Color::rgb8(0xCC, 0xCC, 0xCC)); }) .delegate(Delegate); let handle = app.get_external_handle(); thread::spawn(move || launcher_lifecycle(handle, window_id)); trace_err!(app.launch(state))?; } Ok(()) } fn main() { let args = env::args().collect::<Vec<_>>(); match args.get(1) { Some(flag) if flag == "--restart-steamvr" => commands::restart_steamvr(), Some(flag) if flag == "--update" => commands::invoke_installer(), Some(_) | None => { alvr_common::show_err_blocking(make_window()); } } }
31.677043
99
0.521066
0181b4b34599f781c1b1829d7fc4ac153cc28abd
5,171
use core::mem::size_of; #[cfg(feature = "std")] use std::io::{self, Write}; use bytemuck::{bytes_of, Pod, Zeroable}; #[cfg(feature = "std")] use crate::std430::Writer; /// Trait implemented for all `std430` primitives. Generally should not be /// implemented outside this crate. pub unsafe trait Std430: Copy + Zeroable + Pod { /// The required alignment of the type. Must be a power of two. /// /// This is distinct from the value returned by `std::mem::align_of` because /// `AsStd430` structs do not use Rust's alignment. This enables them to /// control and zero their padding bytes, making converting them to and from /// slices safe. const ALIGNMENT: usize; /// Whether this type requires a padding at the end (ie, is a struct or an array /// of primitives). /// See https://www.khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159 /// (rule 4 and 9) const PAD_AT_END: bool = false; /// Casts the type to a byte array. Implementors should not override this /// method. /// /// # Safety /// This is always safe due to the requirements of [`bytemuck::Pod`] being a /// prerequisite for this trait. fn as_bytes(&self) -> &[u8] { bytes_of(self) } } /** Trait implemented for all types that can be turned into `std430` values. This trait can often be `#[derive]`'d instead of manually implementing it. Any struct which contains only fields that also implement `AsStd430` can derive `AsStd430`. Types from the mint crate implement `AsStd430`, making them convenient for use in uniform types. Most Rust geometry crates, like cgmath, nalgebra, and ultraviolet support mint. ## Example ```glsl uniform CAMERA { mat4 view; mat4 projection; } camera; ``` ```skip use cgmath::prelude::*; use cgmath::{Matrix4, Deg, perspective}; use crevice::std430::{AsStd430, Std430}; #[derive(AsStd430)] struct CameraUniform { view: mint::ColumnMatrix4<f32>, projection: mint::ColumnMatrix4<f32>, } let camera = CameraUniform { view: Matrix4::identity().into(), projection: perspective(Deg(60.0), 16.0/9.0, 0.01, 100.0).into(), }; # fn write_to_gpu_buffer(bytes: &[u8]) {} let camera_std430 = camera.as_std430(); write_to_gpu_buffer(camera_std430.as_bytes()); ``` */ pub trait AsStd430 { /// The `std430` version of this value. type Std430Type: Std430; /// Convert this value into the `std430` version of itself. fn as_std430(&self) -> Self::Std430Type; /// Returns the size of the `std430` version of this type. Useful for /// pre-sizing buffers. fn std430_size_static() -> usize { size_of::<Self::Std430Type>() } /// Converts from `std430` version of self to self. fn from_std430(value: Self::Std430Type) -> Self; } impl<T> AsStd430 for T where T: Std430, { type Std430Type = Self; fn as_std430(&self) -> Self { *self } fn from_std430(value: Self) -> Self { value } } /// Trait implemented for all types that can be written into a buffer as /// `std430` bytes. This type is more general than [`AsStd430`]: all `AsStd430` /// types implement `WriteStd430`, but not the other way around. /// /// While `AsStd430` requires implementers to return a type that implements the /// `Std430` trait, `WriteStd430` directly writes bytes using a [`Writer`]. This /// makes `WriteStd430` usable for writing slices or other DSTs that could not /// implement `AsStd430` without allocating new memory on the heap. #[cfg(feature = "std")] pub trait WriteStd430 { /// Writes this value into the given [`Writer`] using `std430` layout rules. /// /// Should return the offset of the first byte of this type, as returned by /// the first call to [`Writer::write`]. fn write_std430<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<usize>; /// The space required to write this value using `std430` layout rules. This /// does not include alignment padding that may be needed before or after /// this type when written as part of a larger buffer. fn std430_size(&self) -> usize { let mut writer = Writer::new(io::sink()); self.write_std430(&mut writer).unwrap(); writer.len() } } #[cfg(feature = "std")] impl<T> WriteStd430 for T where T: AsStd430, { fn write_std430<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<usize> { writer.write_std430(&self.as_std430()) } fn std430_size(&self) -> usize { size_of::<<Self as AsStd430>::Std430Type>() } } #[cfg(feature = "std")] impl<T> WriteStd430 for [T] where T: WriteStd430, { fn write_std430<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<usize> { let mut offset = writer.len(); let mut iter = self.iter(); if let Some(item) = iter.next() { offset = item.write_std430(writer)?; } for item in self.iter() { item.write_std430(writer)?; } Ok(offset) } fn std430_size(&self) -> usize { let mut writer = Writer::new(io::sink()); self.write_std430(&mut writer).unwrap(); writer.len() } }
29.214689
87
0.648037
e430e3e745e2445d90dac9b94ccd126eb2b1804a
1,934
#[doc = "Reader of register CMPRB7"] pub type R = crate::R<u32, super::CMPRB7>; #[doc = "Writer for register CMPRB7"] pub type W = crate::W<u32, super::CMPRB7>; #[doc = "Register CMPRB7 `reset()`'s with value 0"] impl crate::ResetValue for super::CMPRB7 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `CMPR1B7`"] pub type CMPR1B7_R = crate::R<u16, u16>; #[doc = "Write proxy for field `CMPR1B7`"] pub struct CMPR1B7_W<'a> { w: &'a mut W, } impl<'a> CMPR1B7_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 << 16)) | (((value as u32) & 0xffff) << 16); self.w } } #[doc = "Reader of field `CMPR0B7`"] pub type CMPR0B7_R = crate::R<u16, u16>; #[doc = "Write proxy for field `CMPR0B7`"] pub struct CMPR0B7_W<'a> { w: &'a mut W, } impl<'a> CMPR0B7_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 16:31 - Counter/Timer B3 Compare Register 1."] #[inline(always)] pub fn cmpr1b7(&self) -> CMPR1B7_R { CMPR1B7_R::new(((self.bits >> 16) & 0xffff) as u16) } #[doc = "Bits 0:15 - Counter/Timer B3 Compare Register 0."] #[inline(always)] pub fn cmpr0b7(&self) -> CMPR0B7_R { CMPR0B7_R::new((self.bits & 0xffff) as u16) } } impl W { #[doc = "Bits 16:31 - Counter/Timer B3 Compare Register 1."] #[inline(always)] pub fn cmpr1b7(&mut self) -> CMPR1B7_W { CMPR1B7_W { w: self } } #[doc = "Bits 0:15 - Counter/Timer B3 Compare Register 0."] #[inline(always)] pub fn cmpr0b7(&mut self) -> CMPR0B7_W { CMPR0B7_W { w: self } } }
29.753846
90
0.57394
fc1d950523d5f9c50d28b221e3cdb4edb6f43bbf
19,387
use std::sync::atomic::Ordering::Relaxed; use bellperson::Circuit; use fil_proofs_tooling::{measure, Metadata}; use filecoin_proofs::constants::{DefaultTreeHasher, POREP_PARTITIONS}; use filecoin_proofs::parameters::post_public_params; use filecoin_proofs::types::PaddedBytesAmount; use filecoin_proofs::types::*; use filecoin_proofs::types::{PoStConfig, SectorSize}; use filecoin_proofs::{ generate_candidates, generate_post, seal_commit_phase1, seal_commit_phase2, verify_post, PoRepConfig, }; use log::info; use paired::bls12_381::Bls12; use serde::{Deserialize, Serialize}; use storage_proofs::circuit::bench::BenchCS; use storage_proofs::circuit::election_post::{ElectionPoStCircuit, ElectionPoStCompound}; use storage_proofs::compound_proof::CompoundProof; use storage_proofs::election_post::ElectionPoSt; use storage_proofs::hasher::Sha256Hasher; #[cfg(feature = "measurements")] use storage_proofs::measurements::Operation; #[cfg(feature = "measurements")] use storage_proofs::measurements::OP_MEASUREMENTS; use storage_proofs::parameter_cache::CacheableParameters; use storage_proofs::proof::ProofScheme; use crate::shared::{create_replicas, CHALLENGE_COUNT, PROVER_ID, RANDOMNESS, TICKET_BYTES}; type FlarpHasher = DefaultTreeHasher; #[derive(Default, Debug, Serialize)] pub struct FlarpReport { inputs: FlarpInputs, outputs: FlarpOutputs, } #[derive(Default, Debug, Deserialize, Serialize)] pub struct FlarpInputs { /// The size of sector. sector_size: String, drg_parents: u64, expander_parents: u64, porep_challenges: u64, porep_partitions: u8, post_challenges: u64, post_challenged_nodes: u64, stacked_layers: u64, /// How many sectors should be created in parallel. num_sectors: u64, } impl FlarpInputs { pub fn sector_size_bytes(&self) -> u64 { bytefmt::parse(&self.sector_size).unwrap() } } #[derive(Default, Debug, Serialize)] pub struct FlarpOutputs { comm_d_cpu_time_ms: u64, comm_d_wall_time_ms: u64, encode_window_time_all_cpu_time_ms: u64, encode_window_time_all_wall_time_ms: u64, encoding_cpu_time_ms: u64, encoding_wall_time_ms: u64, epost_cpu_time_ms: u64, epost_wall_time_ms: u64, generate_tree_c_cpu_time_ms: u64, generate_tree_c_wall_time_ms: u64, porep_commit_time_cpu_time_ms: u64, porep_commit_time_wall_time_ms: u64, porep_proof_gen_cpu_time_ms: u64, porep_proof_gen_wall_time_ms: u64, post_finalize_ticket_cpu_time_ms: u64, post_finalize_ticket_time_ms: u64, epost_inclusions_cpu_time_ms: u64, epost_inclusions_wall_time_ms: u64, post_partial_ticket_hash_cpu_time_ms: u64, post_partial_ticket_hash_time_ms: u64, post_proof_gen_cpu_time_ms: u64, post_proof_gen_wall_time_ms: u64, post_read_challenged_range_cpu_time_ms: u64, post_read_challenged_range_time_ms: u64, post_verify_cpu_time_ms: u64, post_verify_wall_time_ms: u64, tree_r_last_cpu_time_ms: u64, tree_r_last_wall_time_ms: u64, window_comm_leaves_time_cpu_time_ms: u64, window_comm_leaves_time_wall_time_ms: u64, #[serde(flatten)] circuits: CircuitOutputs, } #[cfg(not(feature = "measurements"))] fn augment_with_op_measurements(mut _output: &mut FlarpOutputs) {} #[cfg(feature = "measurements")] fn augment_with_op_measurements(mut output: &mut FlarpOutputs) { // drop the tx side of the channel, causing the iterator to yield None // see also: https://doc.rust-lang.org/src/std/sync/mpsc/mod.rs.html#368 OP_MEASUREMENTS .0 .lock() .expect("failed to acquire mutex") .take(); let measurements = OP_MEASUREMENTS .1 .lock() .expect("failed to acquire lock on rx side of perf channel"); for m in measurements.iter() { use Operation::*; let cpu_time = m.cpu_time.as_millis() as u64; let wall_time = m.wall_time.as_millis() as u64; match m.op { GenerateTreeC => { output.generate_tree_c_cpu_time_ms = cpu_time; output.generate_tree_c_wall_time_ms = wall_time; } GenerateTreeRLast => { output.tree_r_last_cpu_time_ms = cpu_time; output.tree_r_last_wall_time_ms = wall_time; } CommD => { output.comm_d_cpu_time_ms = cpu_time; output.comm_d_wall_time_ms = wall_time; } EncodeWindowTimeAll => { output.encode_window_time_all_cpu_time_ms = cpu_time; output.encode_window_time_all_wall_time_ms = wall_time; } WindowCommLeavesTime => { output.window_comm_leaves_time_cpu_time_ms = cpu_time; output.window_comm_leaves_time_wall_time_ms = wall_time; } PorepCommitTime => { output.porep_commit_time_cpu_time_ms = cpu_time; output.porep_commit_time_wall_time_ms = wall_time; } PostInclusionProofs => { output.epost_inclusions_cpu_time_ms = cpu_time; output.epost_inclusions_wall_time_ms = wall_time; } PostFinalizeTicket => { output.post_finalize_ticket_cpu_time_ms = cpu_time; output.post_finalize_ticket_time_ms = wall_time; } PostReadChallengedRange => { output.post_read_challenged_range_cpu_time_ms = cpu_time; output.post_read_challenged_range_time_ms = wall_time; } PostPartialTicketHash => { output.post_partial_ticket_hash_cpu_time_ms = cpu_time; output.post_partial_ticket_hash_time_ms = wall_time; } } } } fn configure_global_config(inputs: &FlarpInputs) { filecoin_proofs::constants::LAYERS .write() .unwrap() .insert(inputs.sector_size_bytes(), inputs.stacked_layers as usize); filecoin_proofs::constants::POREP_PARTITIONS .write() .unwrap() .insert(inputs.sector_size_bytes(), inputs.porep_partitions); filecoin_proofs::constants::EXP_DEGREE.store(inputs.expander_parents, Relaxed); filecoin_proofs::constants::DRG_DEGREE.store(inputs.drg_parents, Relaxed); filecoin_proofs::constants::POREP_MINIMUM_CHALLENGES .write() .unwrap() .insert(inputs.sector_size_bytes(), inputs.porep_challenges); } pub fn run( inputs: FlarpInputs, skip_seal_proof: bool, skip_post_proof: bool, only_replicate: bool, ) -> Metadata<FlarpReport> { configure_global_config(&inputs); let mut outputs = FlarpOutputs::default(); let sector_size = SectorSize(inputs.sector_size_bytes()); assert!(inputs.num_sectors > 0, "Missing num_sectors"); let (cfg, created, replica_measurement) = create_replicas(sector_size, inputs.num_sectors as usize); if only_replicate { augment_with_op_measurements(&mut outputs); return Metadata::wrap(FlarpReport { inputs, outputs }) .expect("failed to retrieve metadata"); } generate_params(&inputs); if !skip_seal_proof { for (value, (sector_id, replica_info)) in replica_measurement.return_value.iter().zip(created.iter()) { let measured = measure(|| { let phase1_output = seal_commit_phase1( cfg, &replica_info.private_replica_info.cache_dir_path(), PROVER_ID, *sector_id, TICKET_BYTES, RANDOMNESS, value.clone(), &replica_info.piece_info, )?; seal_commit_phase2(cfg, phase1_output, PROVER_ID, *sector_id) }) .expect("failed to prove sector"); outputs.porep_proof_gen_cpu_time_ms += measured.cpu_time.as_millis() as u64; outputs.porep_proof_gen_wall_time_ms += measured.wall_time.as_millis() as u64; } } if !skip_post_proof { let (sector_id, replica_info) = &created[0]; // replica_info is moved into the PoSt scope let encoding_wall_time_ms = replica_measurement.wall_time.as_millis() as u64; let encoding_cpu_time_ms = replica_measurement.cpu_time.as_millis() as u64; // Measure PoSt generation and verification. let post_config = PoStConfig { sector_size, challenge_count: inputs.post_challenges as usize, challenged_nodes: inputs.post_challenged_nodes as usize, priority: true, }; let gen_candidates_measurement = measure(|| { generate_candidates( post_config, &RANDOMNESS, CHALLENGE_COUNT, &vec![(*sector_id, replica_info.private_replica_info.clone())] .into_iter() .collect(), PROVER_ID, ) }) .expect("failed to generate post candidates"); outputs.epost_cpu_time_ms = gen_candidates_measurement.cpu_time.as_millis() as u64; outputs.epost_wall_time_ms = gen_candidates_measurement.wall_time.as_millis() as u64; let candidates = &gen_candidates_measurement.return_value; let gen_post_measurement = measure(|| { generate_post( post_config, &RANDOMNESS, &vec![(*sector_id, replica_info.private_replica_info.clone())] .into_iter() .collect(), candidates.clone(), PROVER_ID, ) }) .expect("failed to generate PoSt"); outputs.post_proof_gen_cpu_time_ms = gen_post_measurement.cpu_time.as_millis() as u64; outputs.post_proof_gen_wall_time_ms = gen_post_measurement.wall_time.as_millis() as u64; let post_proof = &gen_post_measurement.return_value; let verify_post_measurement = measure(|| { verify_post( post_config, &RANDOMNESS, CHALLENGE_COUNT, post_proof, &vec![(*sector_id, replica_info.public_replica_info.clone())] .into_iter() .collect(), &candidates.clone(), PROVER_ID, ) }) .expect("verify_post function returned an error"); assert!( verify_post_measurement.return_value, "generated PoSt was invalid" ); outputs.post_verify_cpu_time_ms = verify_post_measurement.cpu_time.as_millis() as u64; outputs.post_verify_wall_time_ms = verify_post_measurement.wall_time.as_millis() as u64; outputs.encoding_wall_time_ms = encoding_wall_time_ms; outputs.encoding_cpu_time_ms = encoding_cpu_time_ms; } augment_with_op_measurements(&mut outputs); outputs.circuits = run_measure_circuits(&inputs); Metadata::wrap(FlarpReport { inputs, outputs }).expect("failed to retrieve metadata") } #[derive(Default, Debug, Serialize)] struct CircuitOutputs { // porep_snark_partition_constraints pub porep_constraints: usize, // post_snark_constraints pub post_constraints: usize, // replica_inclusion (constraints: single merkle path pedersen) // data_inclusion (constraints: sha merklepath) // window_inclusion (constraints: merkle inclusion path in comm_c) // ticket_constraints - (skip) // replica_inclusion (constraints: single merkle path pedersen) // column_leaf_hash_constraints - (64 byte * stacked layers) pedersen_md // kdf_constraints pub kdf_constraints: usize, // merkle_tree_datahash_constraints - sha2 constraints 64 // merkle_tree_hash_constraints - 64 byte pedersen // ticket_proofs (constraints: pedersen_md inside the election post) } fn run_measure_circuits(i: &FlarpInputs) -> CircuitOutputs { let porep_constraints = measure_porep_circuit(i); let post_constraints = measure_post_circuit(i); let kdf_constraints = measure_kdf_circuit(i); CircuitOutputs { porep_constraints, post_constraints, kdf_constraints, } } fn measure_porep_circuit(i: &FlarpInputs) -> usize { use storage_proofs::circuit::stacked::StackedCompound; use storage_proofs::drgraph::new_seed; use storage_proofs::stacked::{LayerChallenges, SetupParams, StackedDrg}; let layers = i.stacked_layers as usize; let challenge_count = i.porep_challenges as usize; let drg_degree = i.drg_parents as usize; let expansion_degree = i.expander_parents as usize; let nodes = (i.sector_size_bytes() / 32) as usize; let layer_challenges = LayerChallenges::new(layers, challenge_count); let sp = SetupParams { nodes, degree: drg_degree, expansion_degree, seed: new_seed(), layer_challenges, }; let pp = StackedDrg::<FlarpHasher, Sha256Hasher>::setup(&sp).unwrap(); let mut cs = BenchCS::<Bls12>::new(); <StackedCompound<_, _> as CompoundProof<_, StackedDrg<FlarpHasher, Sha256Hasher>, _>>::blank_circuit( &pp, ) .synthesize(&mut cs) .unwrap(); cs.num_constraints() } fn measure_post_circuit(i: &FlarpInputs) -> usize { use filecoin_proofs::parameters::post_setup_params; use storage_proofs::election_post; let post_config = PoStConfig { sector_size: SectorSize(i.sector_size_bytes()), challenge_count: i.post_challenges as usize, challenged_nodes: i.post_challenged_nodes as usize, priority: true, }; let vanilla_params = post_setup_params(post_config); let pp = election_post::ElectionPoSt::<FlarpHasher>::setup(&vanilla_params).unwrap(); let mut cs = BenchCS::<Bls12>::new(); ElectionPoStCompound::<FlarpHasher>::blank_circuit(&pp) .synthesize(&mut cs) .unwrap(); cs.num_constraints() } fn measure_kdf_circuit(i: &FlarpInputs) -> usize { use bellperson::gadgets::boolean::Boolean; use bellperson::ConstraintSystem; use ff::Field; use paired::bls12_381::Fr; use rand::thread_rng; use storage_proofs::circuit::uint64; use storage_proofs::fr32::fr_into_bytes; use storage_proofs::util::bytes_into_boolean_vec_be; let mut cs = BenchCS::<Bls12>::new(); let rng = &mut thread_rng(); let parents = i.drg_parents + i.expander_parents; let id: Vec<u8> = fr_into_bytes::<Bls12>(&Fr::random(rng)); let parents: Vec<Vec<u8>> = (0..parents) .map(|_| fr_into_bytes::<Bls12>(&Fr::random(rng))) .collect(); let id_bits: Vec<Boolean> = { let mut cs = cs.namespace(|| "id"); bytes_into_boolean_vec_be(&mut cs, Some(id.as_slice()), id.len()).unwrap() }; let parents_bits: Vec<Vec<Boolean>> = parents .iter() .enumerate() .map(|(i, p)| { let mut cs = cs.namespace(|| format!("parents {}", i)); bytes_into_boolean_vec_be(&mut cs, Some(p.as_slice()), p.len()).unwrap() }) .collect(); let window_index_raw = 12u64; let node_raw = 123_456_789u64; let window_index = uint64::UInt64::constant(window_index_raw); let node = uint64::UInt64::constant(node_raw); storage_proofs::circuit::create_label::create_label( cs.namespace(|| "create_label"), &id_bits, parents_bits, Some(window_index), Some(node), ) .expect("key derivation function failed"); cs.num_constraints() } fn generate_params(i: &FlarpInputs) { let sector_size = SectorSize(i.sector_size_bytes()); let partitions = PoRepProofPartitions( *POREP_PARTITIONS .read() .unwrap() .get(&i.sector_size_bytes()) .expect("unknown sector size"), ); info!( "generating params: porep: (size: {:?}, partitions: {:?})", &sector_size, &partitions ); cache_porep_params(PoRepConfig { sector_size, partitions, }); info!("generating params: post"); cache_post_params(PoStConfig { sector_size, challenge_count: i.post_challenges as usize, challenged_nodes: i.post_challenged_nodes as usize, priority: true, }); } fn cache_porep_params(porep_config: PoRepConfig) { use filecoin_proofs::parameters::public_params; use storage_proofs::circuit::stacked::StackedCompound; use storage_proofs::stacked::StackedDrg; let public_params = public_params( PaddedBytesAmount::from(porep_config), usize::from(PoRepProofPartitions::from(porep_config)), ) .unwrap(); { let circuit = <StackedCompound<_, _> as CompoundProof< _, StackedDrg<FlarpHasher, Sha256Hasher>, _, >>::blank_circuit(&public_params); StackedCompound::<FlarpHasher, Sha256Hasher>::get_param_metadata(circuit, &public_params) .expect("cannot get param metadata"); } { let circuit = <StackedCompound<_, _> as CompoundProof< _, StackedDrg<FlarpHasher, Sha256Hasher>, _, >>::blank_circuit(&public_params); StackedCompound::<FlarpHasher, Sha256Hasher>::get_groth_params(circuit, &public_params) .expect("failed to get groth params"); } { let circuit = <StackedCompound<_, _> as CompoundProof< _, StackedDrg<FlarpHasher, Sha256Hasher>, _, >>::blank_circuit(&public_params); StackedCompound::<FlarpHasher, Sha256Hasher>::get_verifying_key(circuit, &public_params) .expect("failed to get verifying key"); } } fn cache_post_params(post_config: PoStConfig) { let post_public_params = post_public_params(post_config).unwrap(); { let post_circuit: ElectionPoStCircuit<Bls12, FlarpHasher> = <ElectionPoStCompound<FlarpHasher> as CompoundProof< Bls12, ElectionPoSt<FlarpHasher>, ElectionPoStCircuit<Bls12, FlarpHasher>, >>::blank_circuit(&post_public_params); let _ = <ElectionPoStCompound<FlarpHasher>>::get_param_metadata( post_circuit, &post_public_params, ) .expect("failed to get metadata"); } { let post_circuit: ElectionPoStCircuit<Bls12, FlarpHasher> = <ElectionPoStCompound<FlarpHasher> as CompoundProof< Bls12, ElectionPoSt<FlarpHasher>, ElectionPoStCircuit<Bls12, FlarpHasher>, >>::blank_circuit(&post_public_params); <ElectionPoStCompound<FlarpHasher>>::get_groth_params(post_circuit, &post_public_params) .expect("failed to get groth params"); } { let post_circuit: ElectionPoStCircuit<Bls12, FlarpHasher> = <ElectionPoStCompound<FlarpHasher> as CompoundProof< Bls12, ElectionPoSt<FlarpHasher>, ElectionPoStCircuit<Bls12, FlarpHasher>, >>::blank_circuit(&post_public_params); <ElectionPoStCompound<FlarpHasher>>::get_verifying_key(post_circuit, &post_public_params) .expect("failed to get verifying key"); } }
34.806104
105
0.650745
8f5ae337c3cb8b3632b3cff1373b83fafa09e02f
9,721
use std::{collections::HashMap, env, sync::Arc}; use anyhow::{bail, Context, Error}; use helpers::Helpers; use swc::{ config::{GlobalInliningPassEnvs, InputSourceMap, IsModule, JscConfig, TransformConfig}, try_with_handler, }; use swc_atoms::JsWord; use swc_bundler::{Load, ModuleData}; use swc_common::{ collections::AHashMap, errors::{Handler, HANDLER}, sync::Lrc, FileName, DUMMY_SP, }; use swc_ecma_ast::{EsVersion, Expr, Lit, Module, Program, Str}; use swc_ecma_parser::{parse_file_as_module, Syntax}; use swc_ecma_transforms::{ helpers, optimization::{ inline_globals, simplify::{dead_branch_remover, expr_simplifier}, }, pass::noop, }; use swc_ecma_visit::FoldWith; use crate::loaders::json::load_json_as_module; /// JavaScript loader pub struct SwcLoader { compiler: Arc<swc::Compiler>, options: swc::config::Options, } impl SwcLoader { pub fn new(compiler: Arc<swc::Compiler>, options: swc::config::Options) -> Self { SwcLoader { compiler, options } } fn env_map(&self) -> Lrc<AHashMap<JsWord, Expr>> { let mut m = HashMap::default(); let envs = self .options .config .jsc .transform .as_ref() .and_then(|t| t.optimizer.as_ref()) .and_then(|o| o.globals.as_ref()) .map(|g| g.envs.clone()) .unwrap_or_default(); let envs_map: AHashMap<_, _> = match envs { GlobalInliningPassEnvs::Map(m) => m, GlobalInliningPassEnvs::List(envs) => envs .into_iter() .map(|name| { let value = env::var(&name).ok(); (name.into(), value.unwrap_or_default().into()) }) .collect(), }; for (k, v) in envs_map { m.insert( k, Expr::Lit(Lit::Str(Str { span: DUMMY_SP, value: v, has_escape: false, kind: Default::default(), })), ); } Lrc::new(m) } fn load_with_handler(&self, handler: &Handler, name: &FileName) -> Result<ModuleData, Error> { tracing::debug!("JsLoader.load({})", name); let helpers = Helpers::new(false); if let FileName::Custom(id) = name { // Handle built-in modules if id.starts_with("node:") { let fm = self .compiler .cm .new_source_file(name.clone(), "".to_string()); return Ok(ModuleData { fm, module: Module { span: DUMMY_SP, body: Default::default(), shebang: Default::default(), }, helpers: Default::default(), }); // Handle disabled modules, eg when `browser` has a field // set to `false` } else { // TODO: When we know the calling context is ESM // TODO: switch to `export default {}`. let fm = self .compiler .cm .new_source_file(name.clone(), "module.exports = {}".to_string()); let module = parse_file_as_module( &fm, Syntax::Es(Default::default()), Default::default(), None, &mut vec![], ) .unwrap(); return Ok(ModuleData { fm, module, helpers: Default::default(), }); } } let fm = self .compiler .cm .load_file(match name { FileName::Real(v) => v, _ => bail!("swc-loader only accepts path. Got `{}`", name), }) .with_context(|| format!("failed to load file `{}`", name))?; if let FileName::Real(path) = name { if let Some(ext) = path.extension() { if ext == "json" { let module = load_json_as_module(&fm) .with_context(|| format!("failed to load json file at {}", fm.name))?; return Ok(ModuleData { fm, module, helpers: Default::default(), }); } } } tracing::trace!("JsLoader.load: loaded"); let program = if fm.name.to_string().contains("node_modules") { let program = self.compiler.parse_js( fm.clone(), handler, EsVersion::Es2020, Default::default(), IsModule::Bool(true), true, )?; helpers::HELPERS.set(&helpers, || { HANDLER.set(handler, || { let program = program.fold_with(&mut inline_globals( self.env_map(), Default::default(), Default::default(), )); let program = program.fold_with(&mut expr_simplifier(Default::default())); program.fold_with(&mut dead_branch_remover()) }) }) } else { let config = self.compiler.parse_js_as_input( fm.clone(), None, handler, &swc::config::Options { config: { let c = &self.options.config; swc::config::Config { jsc: JscConfig { transform: { c.jsc.transform.as_ref().map(|c| TransformConfig { react: c.react.clone(), const_modules: c.const_modules.clone(), optimizer: None, legacy_decorator: c.legacy_decorator, decorator_metadata: c.decorator_metadata, hidden: Default::default(), ..Default::default() }) }, external_helpers: true, ..c.jsc.clone() }, module: None, minify: false, input_source_map: InputSourceMap::Bool(false), ..c.clone() } }, skip_helper_injection: true, disable_hygiene: false, disable_fixer: true, global_mark: self.options.global_mark, cwd: self.options.cwd.clone(), caller: None, filename: String::new(), config_file: None, root: None, swcrc: true, env_name: { env::var("NODE_ENV").unwrap_or_else(|_| "development".into()) }, is_module: IsModule::Bool(true), ..Default::default() }, &fm.name, |_| noop(), )?; tracing::trace!("JsLoader.load: loaded config"); // We run transform at this phase to strip out unused dependencies. // // Note that we don't apply compat transform at loading phase. let program = if let Some(config) = config { let program = config.program; let mut pass = config.pass; helpers::HELPERS.set(&helpers, || { HANDLER.set(handler, || { let program = program.fold_with(&mut inline_globals( self.env_map(), Default::default(), Default::default(), )); let program = program.fold_with(&mut expr_simplifier(Default::default())); let program = program.fold_with(&mut dead_branch_remover()); program.fold_with(&mut pass) }) }) } else { self.compiler .parse_js( fm.clone(), handler, EsVersion::Es2020, config.as_ref().map(|v| v.syntax).unwrap_or_default(), IsModule::Bool(true), true, ) .context("tried to parse as ecmascript as it's excluded by .swcrc")? }; tracing::trace!("JsLoader.load: applied transforms"); program }; match program { Program::Module(module) => Ok(ModuleData { fm, module, helpers, }), _ => unreachable!(), } } } impl Load for SwcLoader { fn load(&self, name: &FileName) -> Result<ModuleData, Error> { try_with_handler(self.compiler.cm.clone(), false, |handler| { self.load_with_handler(handler, name) }) } }
34.594306
98
0.423825
c1d9f27e0b10cc5a3d155332bbda6ef91a006056
16
pub mod clases;
8
15
0.75
d61ac27b9cd0dfec3b0a18a8f4c7c82d4269618f
10,873
extern crate cfd_sys; extern crate libc; use self::libc::{c_char, c_uint, c_void}; use crate::common::{ alloc_c_string, byte_from_hex, collect_cstring_and_free, collect_multi_cstring_and_free, hex_from_bytes, ErrorHandle, }; use crate::{ common::{ByteData, CfdError, Network}, transaction::{BlockHash, Transaction, Txid}, }; use std::fmt; use std::ptr; use std::result::Result::{Err, Ok}; use std::str::FromStr; use self::cfd_sys::{ CfdFreeBlockHandle, CfdGetBlockHash, CfdGetBlockHeaderData, CfdGetTransactionFromBlock, CfdGetTxCountInBlock, CfdGetTxOutProof, CfdGetTxidFromBlock, CfdInitializeBlockHandle, }; /// A container that stores a bitcoin block header. #[derive(Debug, PartialEq, Eq, Clone)] pub struct BlockHeader { pub version: u32, pub prev_block_hash: BlockHash, pub merkle_root: BlockHash, pub time: u32, pub bits: u32, pub nonce: u32, } impl Default for BlockHeader { fn default() -> BlockHeader { BlockHeader { version: 0, prev_block_hash: BlockHash::default(), merkle_root: BlockHash::default(), time: 0, bits: 0, nonce: 0, } } } /// A container that stores a bitcoin block. #[derive(Debug, PartialEq, Eq, Clone)] pub struct Block { buffer: Vec<u8>, hash: BlockHash, header: BlockHeader, txid_list: Vec<Txid>, } impl Block { /// Generate from slice. /// /// # Arguments /// * `data` - An unsigned 8bit slice that holds the byte data. #[inline] pub fn from_slice(data: &[u8]) -> Result<Block, CfdError> { Block::parse(data, &Network::Mainnet) } /// Generate from ByteData. /// /// # Arguments /// * `data` - An unsigned 8bit slice that holds the byte data. #[inline] pub fn from_data(data: &ByteData) -> Result<Block, CfdError> { Block::from_slice(&data.to_slice()) } #[inline] pub fn to_slice(&self) -> &Vec<u8> { &self.buffer } #[inline] pub fn to_data(&self) -> ByteData { ByteData::from_slice(&self.buffer) } #[inline] pub fn to_hex(&self) -> String { hex_from_bytes(&self.buffer) } /// Get the block hash pub fn get_hash(&self) -> &BlockHash { &self.hash } /// Get the block header. pub fn get_header(&self) -> &BlockHeader { &self.header } /// Get txid list from block. pub fn get_txid_list(&self) -> &Vec<Txid> { &self.txid_list } /// Get tx count in block. pub fn get_tx_count(&self) -> usize { self.txid_list.len() } /// Exist txid in block /// /// # Arguments /// * `txid` - A transaction id. pub fn exist_txid(&self, txid: &Txid) -> bool { for temp_txid in &self.txid_list { if temp_txid == txid { return true; } } false } #[inline] pub fn is_empty(&self) -> bool { self.buffer.is_empty() } /// Get a transaction from block. /// /// # Arguments /// * `txid` - A transaction id. pub fn get_transaction(&self, txid: &Txid) -> Result<Transaction, CfdError> { let mut handle = ErrorHandle::new()?; let result = { let hex_str = hex_from_bytes(&self.buffer); let block_handle = BlockHandle::new(&handle, &Network::Mainnet, &hex_str)?; let block_result = Block::get_transaction_internal(&handle, &block_handle, txid)?; block_handle.free_handle(&handle); block_result }; handle.free_handle(); Ok(result) } /// Get a txoutproof. /// /// # Arguments /// * `txid` - A transaction id. pub fn get_txoutproof(&self, txid: &Txid) -> Result<ByteData, CfdError> { let mut handle = ErrorHandle::new()?; let result = { let hex_str = hex_from_bytes(&self.buffer); let block_handle = BlockHandle::new(&handle, &Network::Mainnet, &hex_str)?; let block_result = Block::get_txoutproof_internal(&handle, &block_handle, txid)?; block_handle.free_handle(&handle); block_result }; handle.free_handle(); Ok(result) } /// Get transaction and txoutproof. /// /// # Arguments /// * `txid` - A transaction id. pub fn get_tx_data(&self, txid: &Txid) -> Result<(Transaction, ByteData), CfdError> { let mut handle = ErrorHandle::new()?; let result = { let hex_str = hex_from_bytes(&self.buffer); let block_handle = BlockHandle::new(&handle, &Network::Mainnet, &hex_str)?; let block_result = { let tx = Block::get_transaction_internal(&handle, &block_handle, txid)?; let txoutproof = Block::get_txoutproof_internal(&handle, &block_handle, txid)?; Ok((tx, txoutproof)) }?; block_handle.free_handle(&handle); block_result }; handle.free_handle(); Ok(result) } #[inline] pub(in crate) fn parse(data: &[u8], network: &Network) -> Result<Block, CfdError> { let mut handle = ErrorHandle::new()?; let result = { let hex_str = hex_from_bytes(data); let block_handle = BlockHandle::new(&handle, network, &hex_str)?; let block_result = { let hash = Block::get_hash_internal(&handle, &block_handle)?; let header = Block::get_header_internal(&handle, &block_handle)?; let txid_list = Block::get_txid_list_internal(&handle, &block_handle)?; Ok(Block { buffer: data.to_vec(), hash, header, txid_list, }) }?; block_handle.free_handle(&handle); block_result }; handle.free_handle(); Ok(result) } pub(in crate) fn get_hash_internal( handle: &ErrorHandle, block_handle: &BlockHandle, ) -> Result<BlockHash, CfdError> { let mut hash: *mut c_char = ptr::null_mut(); let error_code = unsafe { CfdGetBlockHash(handle.as_handle(), block_handle.as_handle(), &mut hash) }; match error_code { 0 => { let block_hash = unsafe { collect_cstring_and_free(hash) }?; Ok(BlockHash::from_str(&block_hash)?) } _ => Err(handle.get_error(error_code)), } } pub(in crate) fn get_header_internal( handle: &ErrorHandle, block_handle: &BlockHandle, ) -> Result<BlockHeader, CfdError> { let mut version = 0; let mut time = 0; let mut bits = 0; let mut nonce = 0; let mut prev_block_hash: *mut c_char = ptr::null_mut(); let mut merkle_root: *mut c_char = ptr::null_mut(); let error_code = unsafe { CfdGetBlockHeaderData( handle.as_handle(), block_handle.as_handle(), &mut version, &mut prev_block_hash, &mut merkle_root, &mut time, &mut bits, &mut nonce, ) }; match error_code { 0 => { let str_list = unsafe { collect_multi_cstring_and_free(&[prev_block_hash, merkle_root]) }?; let prev_hash = BlockHash::from_str(&str_list[0])?; let merkle_root_obj = BlockHash::from_str(&str_list[1])?; Ok(BlockHeader { version, prev_block_hash: prev_hash, merkle_root: merkle_root_obj, time, bits, nonce, }) } _ => Err(handle.get_error(error_code)), } } pub(in crate) fn get_txid_list_internal( handle: &ErrorHandle, block_handle: &BlockHandle, ) -> Result<Vec<Txid>, CfdError> { let tx_count = { let mut count = 0; let error_code = unsafe { CfdGetTxCountInBlock(handle.as_handle(), block_handle.as_handle(), &mut count) }; match error_code { 0 => Ok(count), _ => Err(handle.get_error(error_code)), } }?; let mut list: Vec<Txid> = vec![]; let mut index = 0; while index < tx_count { let txid = { let mut txid_str: *mut c_char = ptr::null_mut(); let error_code = unsafe { CfdGetTxidFromBlock( handle.as_handle(), block_handle.as_handle(), index as c_uint, &mut txid_str, ) }; match error_code { 0 => { let txid_hex = unsafe { collect_cstring_and_free(txid_str) }?; Ok(Txid::from_str(&txid_hex)?) } _ => Err(handle.get_error(error_code)), } }?; list.push(txid); index += 1; } Ok(list) } pub(in crate) fn get_transaction_internal( handle: &ErrorHandle, block_handle: &BlockHandle, txid: &Txid, ) -> Result<Transaction, CfdError> { let txid_hex = alloc_c_string(&txid.to_hex())?; let mut tx_hex: *mut c_char = ptr::null_mut(); let error_code: i32 = unsafe { CfdGetTransactionFromBlock( handle.as_handle(), block_handle.as_handle(), txid_hex.as_ptr(), &mut tx_hex, ) }; match error_code { 0 => { let tx = unsafe { collect_cstring_and_free(tx_hex) }?; Ok(Transaction::from_str(&tx)?) } _ => Err(handle.get_error(error_code)), } } pub(in crate) fn get_txoutproof_internal( handle: &ErrorHandle, block_handle: &BlockHandle, txid: &Txid, ) -> Result<ByteData, CfdError> { let txid_hex = alloc_c_string(&txid.to_hex())?; let mut proof: *mut c_char = ptr::null_mut(); let error_code: i32 = unsafe { CfdGetTxOutProof( handle.as_handle(), block_handle.as_handle(), txid_hex.as_ptr(), &mut proof, ) }; match error_code { 0 => { let txoutproof = unsafe { collect_cstring_and_free(proof) }?; Ok(ByteData::from_str(&txoutproof)?) } _ => Err(handle.get_error(error_code)), } } } impl FromStr for Block { type Err = CfdError; fn from_str(text: &str) -> Result<Block, CfdError> { let buf = byte_from_hex(text)?; Block::from_slice(&buf) } } impl Default for Block { fn default() -> Block { Block { buffer: vec![], hash: BlockHash::default(), header: BlockHeader::default(), txid_list: vec![], } } } impl fmt::Display for Block { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Block[{}]", &self.hash.to_hex()) } } /// A container that tx data handler. #[derive(Debug, Clone)] pub(in crate) struct BlockHandle { block_handle: *mut c_void, } impl BlockHandle { pub fn new( handle: &ErrorHandle, network: &Network, block: &str, ) -> Result<BlockHandle, CfdError> { let block_str = alloc_c_string(block)?; let mut block_handle: *mut c_void = ptr::null_mut(); let error_code = unsafe { CfdInitializeBlockHandle( handle.as_handle(), network.to_c_value(), block_str.as_ptr(), &mut block_handle, ) }; match error_code { 0 => Ok(BlockHandle { block_handle }), _ => Err(handle.get_error(error_code)), } } #[inline] pub fn as_handle(&self) -> *const c_void { self.block_handle } pub fn free_handle(&self, handle: &ErrorHandle) { unsafe { CfdFreeBlockHandle(handle.as_handle(), self.block_handle); } } }
26.137019
99
0.606364
d5c809ed9c4a58c6ea8c63a85e90fff282482920
4,059
use libc; use strerr::StrErr; extern "C" { static mut auto_home: *const u8; fn finish(); fn getpwnam(arg1: *const u8) -> *mut passwd; fn init(arg1: *const u8, arg2: *const u8); fn makedir(arg1: *const u8); fn makelog(arg1: *const u8, arg2: i32, arg3: i32); fn outs(arg1: *const u8); fn perm(arg1: i32); fn start(arg1: *const u8); } static UUID_NULL: [u8; 16] = [0u8; 16]; #[no_mangle] pub unsafe extern "C" fn usage() { StrErr::die( 100i32, (*b"pickdns-conf: usage: pickdns-conf acct logacct /pickdns myip\0").as_ptr(), 0i32 as (*const u8), 0i32 as (*const u8), 0i32 as (*const u8), 0i32 as (*const u8), 0i32 as (*const u8), 0i32 as (*const StrErr), ); } #[no_mangle] pub static mut dir: *mut u8 = 0 as (*mut u8); #[no_mangle] pub static mut user: *mut u8 = 0 as (*mut u8); #[no_mangle] pub static mut loguser: *mut u8 = 0 as (*mut u8); #[derive(Copy)] #[repr(C)] pub struct passwd { pub pw_name: *mut u8, pub pw_passwd: *mut u8, pub pw_uid: u32, pub pw_gid: u32, pub pw_change: isize, pub pw_class: *mut u8, pub pw_gecos: *mut u8, pub pw_dir: *mut u8, pub pw_shell: *mut u8, pub pw_expire: isize, } impl Clone for passwd { fn clone(&self) -> Self { *self } } #[no_mangle] pub static mut pw: *mut passwd = 0 as (*mut passwd); #[no_mangle] pub static mut myip: *mut u8 = 0 as (*mut u8); fn main() { use std::os::unix::ffi::OsStringExt; let mut argv_storage = ::std::env::args_os() .map(|str| { let mut vec = str.into_vec(); vec.push(b'\0'); vec }) .collect::<Vec<_>>(); let mut argv = argv_storage .iter_mut() .map(|vec| vec.as_mut_ptr()) .chain(Some(::std::ptr::null_mut())) .collect::<Vec<_>>(); let ret = unsafe { _c_main(argv_storage.len() as (i32), argv.as_mut_ptr()) }; ::std::process::exit(ret); } #[no_mangle] pub unsafe extern "C" fn _c_main(mut argc: i32, mut argv: *mut *mut u8) -> i32 { user = *argv.offset(1isize); if user.is_null() { usage(); } loguser = *argv.offset(2isize); if loguser.is_null() { usage(); } dir = *argv.offset(3isize); if dir.is_null() { usage(); } if *dir.offset(0isize) as (i32) != b'/' as (i32) { usage(); } myip = *argv.offset(4isize); if myip.is_null() { usage(); } pw = getpwnam(loguser as (*const u8)); if pw.is_null() { StrErr::die( 111i32, (*b"pickdns-conf: fatal: \0").as_ptr(), (*b"unknown account \0").as_ptr(), loguser as (*const u8), 0i32 as (*const u8), 0i32 as (*const u8), 0i32 as (*const u8), 0i32 as (*const StrErr), ); } init(dir as (*const u8), (*b"pickdns-conf: fatal: \0").as_ptr()); makelog( loguser as (*const u8), (*pw).pw_uid as (i32), (*pw).pw_gid as (i32), ); makedir((*b"env\0").as_ptr()); perm(0o2755i32); start((*b"env/ROOT\0").as_ptr()); outs(dir as (*const u8)); outs((*b"/root\n\0").as_ptr()); finish(); perm(0o644i32); start((*b"env/IP\0").as_ptr()); outs(myip as (*const u8)); outs((*b"\n\0").as_ptr()); finish(); perm(0o644i32); start((*b"run\0").as_ptr()); outs((*b"#!/bin/sh\nexec 2>&1\nexec envuidgid \0").as_ptr()); outs(user as (*const u8)); outs((*b" envdir ./env softlimit -d250000 \0").as_ptr()); outs(auto_home); outs((*b"/bin/pickdns\n\0").as_ptr()); finish(); perm(0o755i32); makedir((*b"root\0").as_ptr()); perm(0o2755i32); start((*b"root/data\0").as_ptr()); finish(); perm(0o644i32); start((*b"root/Makefile\0").as_ptr()); outs((*b"data.cdb: data\n\0").as_ptr()); outs((*b"\t\0").as_ptr()); outs(auto_home); outs((*b"/bin/pickdns-data\n\0").as_ptr()); finish(); perm(0o644i32); libc::_exit(0i32); }
25.36875
86
0.531658
8a0b46a4d6e5e57bda8353ddb18f30e79a7ee064
306
use std::{thread, time::Duration}; use terminal_spinners::{SpinnerBuilder, BOX_BOUNCE}; fn main() { let text = "Loading unicorns"; let handle = SpinnerBuilder::new() .spinner(&BOX_BOUNCE) .text(text) .start(); thread::sleep(Duration::from_secs(3)); handle.done(); }
25.5
52
0.624183
d9da15264f0b5e2c75c47d331e69f79477eb0759
21,693
use std::fmt; use super::parse::{ParsedHand, SetPair, SetPairType}; use super::win::is_kokushimusou_win; use crate::model::*; use SetPairType::*; #[derive(Debug)] pub struct YakuContext { hand: TileTable, // 元々の手牌(鳴きは含まない) 国士, 九蓮宝燈の判定などに使用 parsed_hand: ParsedHand, // 鳴きを含むすべての面子 pair_tile: Tile, // 雀頭の牌 win_tile: Tile, // 上がり牌 is_tsumo: bool, // ツモ和了 is_open: bool, // 鳴きの有無 prevalent_wind: Tnum, // 場風 (東: 1, 南: 2, 西: 3, 北: 4) seat_wind: Tnum, // 自風 (同上) yaku_flags: YakuFlags, // 組み合わせ以外による役 外部から設定を行う counts: Counts, // 面子や牌種別のカウント iipeikou_count: usize, // 一盃口, 二盃口用 yakuhai_check: TileRow, // 役牌面子のカウント(雀頭は含まない) } impl YakuContext { pub fn new( hand: TileTable, parsed_hand: ParsedHand, win_tile: Tile, prevalent_wind: Tnum, seat_wind: Tnum, is_tsumo: bool, yaku_flags: YakuFlags, ) -> Self { let pair_tile = get_pair(&parsed_hand); let win_tile = win_tile.to_normal(); // 赤5は通常5に変換 let counts = count_type(&parsed_hand); let iipeikou_count = count_iipeikou(&parsed_hand); let yakuhai_check = check_yakuhai(&parsed_hand); let is_open = counts.chi + counts.pon + counts.minkan != 0; Self { hand, parsed_hand, pair_tile, win_tile, is_tsumo, is_open, prevalent_wind, seat_wind, yaku_flags, counts, iipeikou_count, yakuhai_check, } } pub fn is_open(&self) -> bool { self.is_open } // (役一覧, 飜数, 役満倍数)を返却. 役満ではない場合,役満倍率は0, 役一覧に鳴き0飜とドラは含まない pub fn calc_yaku(&self) -> (Vec<&'static Yaku>, usize, usize) { let mut yaku = vec![]; for y in YAKU_LIST { if (y.func)(&self) { yaku.push(y) } } let mut yakuman = vec![]; for &y in &yaku { if y.fan_close >= 13 { yakuman.push(y); } } if !yakuman.is_empty() { let mut m = 0; for y in &yakuman { m += y.fan_close - 12; } (yakuman, 0, m) // 役満が含まれている場合,役満以上の役のみを返却 } else { let mut m = 0; for y in &yaku { m += if self.is_open { y.fan_open } else { y.fan_close }; } (yaku, m, 0) // 役満を含んでいない場合 } } pub fn calc_fu(&self) -> usize { if self.is_tsumo && is_pinfu(&self) { return 20; } if is_chiitoitsu(&self) { return 25; } // 副底 let mut fu = 20; // 和了り方 fu += if self.is_tsumo { 2 // ツモ } else if !self.is_open { 10 // 門前ロン } else { 0 }; // 面子, 雀頭 for SetPair(tp, t) in &self.parsed_hand { match tp { Pair => { fu += if t.is_terminal() || t.is_doragon() { 2 } else if t.is_hornor() { if t.1 == self.prevalent_wind || t.1 == self.seat_wind { 2 } else { 0 } } else { 0 } } Koutsu => fu += if t.is_end() { 8 } else { 4 }, Pon => fu += if t.is_end() { 4 } else { 2 }, Minkan => fu += if t.is_end() { 16 } else { 8 }, Ankan => fu += if t.is_end() { 32 } else { 16 }, _ => {} } } // 待ちの形 let mut is_fu2 = true; let wt = &self.win_tile; for SetPair(tp, t) in &self.parsed_hand { match tp { Shuntsu => { if t.0 == wt.0 { if t.1 == wt.1 || (wt.1 > 2 && t.1 == wt.1 - 2) { // 両面待ち is_fu2 = false; break; } } } Koutsu => { if t == wt { // シャンポン待ち is_fu2 = false; break; } } _ => {} } } if is_fu2 { fu += 2; } (fu + 9) / 10 * 10 // 1の位は切り上げ } } #[derive(Debug, Default)] struct Counts { pair: usize, shuntsu: usize, koutsu: usize, chi: usize, pon: usize, minkan: usize, ankan: usize, shuntsu_total: usize, // shuntu + chi koutsu_total: usize, // koutsu + pon + minkan + ankan ankou_total: usize, // koutsu + ankan kantsu_total: usize, // minkan + ankan tis: [usize; TYPE], // tile Type Indices counts nis: [usize; TNUM], // tile Number Indices counts(字牌は除外) } // 特殊形&特殊条件の役 #[derive(Debug, Default, Clone)] pub struct YakuFlags { pub menzentsumo: bool, pub riichi: bool, pub dabururiichi: bool, pub ippatsu: bool, pub haiteiraoyue: bool, pub houteiraoyui: bool, pub rinshankaihou: bool, pub chankan: bool, pub tenhou: bool, pub tiihou: bool, } fn get_pair(ph: &ParsedHand) -> Tile { for &SetPair(tp, t) in ph { if let Pair = tp { return t; } } Z8 // 雀頭なし(国士無双) } fn count_type(ph: &ParsedHand) -> Counts { let mut cnt = Counts::default(); for SetPair(tp, t) in ph { match tp { Pair => cnt.pair += 1, Shuntsu => cnt.shuntsu += 1, Koutsu => cnt.koutsu += 1, Chi => cnt.chi += 1, Pon => cnt.pon += 1, Minkan => cnt.minkan += 1, Ankan => cnt.ankan += 1, } cnt.tis[t.0] += 1; if t.is_suit() { cnt.nis[t.1] += 1; } } cnt.shuntsu_total = cnt.shuntsu + cnt.chi; cnt.koutsu_total = cnt.koutsu + cnt.pon + cnt.minkan + cnt.ankan; cnt.ankou_total = cnt.koutsu + cnt.ankan; cnt.kantsu_total = cnt.minkan + cnt.ankan; cnt } fn count_iipeikou(ph: &ParsedHand) -> usize { let mut n = 0; let mut shuntsu = TileTable::default(); for SetPair(tp, t) in ph { match tp { Shuntsu => { shuntsu[t.0][t.1] += 1; if shuntsu[t.0][t.1] == 2 { n += 1; } } _ => {} } } n } fn check_yakuhai(ph: &ParsedHand) -> TileRow { let mut tr = TileRow::default(); for SetPair(tp, t) in ph { match tp { Koutsu | Pon | Minkan | Ankan => { if t.is_hornor() { tr[t.1] += 1; } } _ => {} } } tr } pub struct Yaku { pub id: usize, // 雀魂のID > for(let y of cfg.fan.fan.rows_) {console.log(y.id, y.name_jp);} pub name: &'static str, // 天鳳の名称 https://tenhou.net/6 pub func: fn(&YakuContext) -> bool, // 役判定関数 pub fan_close: usize, // 鳴きなしの飜 pub fan_open: usize, // 鳴きありの飜(食い下がり) } impl Yaku { pub fn get_from_id(id: usize) -> Option<&'static Yaku> { assert!(id != 10 && id != 11); // 自風, 場風は特定不能 for y in YAKU_LIST { if y.id == id { return Some(y); } } None } } impl fmt::Debug for Yaku { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {}, {})", self.name, self.fan_close, self.fan_open) } } macro_rules! yaku { ($id: expr, $n: expr, $f: expr, $c: expr, $o: expr) => { Yaku { id: $id, name: $n, func: $f, fan_close: $c, fan_open: $o, } }; } static YAKU_LIST: &'static [Yaku] = &[ yaku!(11, "場風 東", is_bakaze_e, 1, 1), yaku!(11, "場風 南", is_bakaze_s, 1, 1), yaku!(11, "場風 西", is_bakaze_w, 1, 1), yaku!(11, "場風 北", is_bakaze_n, 1, 1), yaku!(10, "自風 東", is_jikaze_e, 1, 1), yaku!(10, "自風 南", is_jikaze_s, 1, 1), yaku!(10, "自風 西", is_jikaze_w, 1, 1), yaku!(10, "自風 北", is_jikaze_n, 1, 1), yaku!(7, "役牌 白", is_haku, 1, 1), yaku!(8, "役牌 發", is_hatsu, 1, 1), yaku!(9, "役牌 中", is_chun, 1, 1), yaku!(12, "断幺九", is_tanyaochuu, 1, 1), yaku!(14, "平和", is_pinfu, 1, 0), yaku!(13, "一盃口", is_iipeikou, 1, 0), yaku!(28, "二盃口", is_ryanpeikou, 3, 0), yaku!(16, "一気通貫", is_ikkitsuukan, 2, 1), yaku!(17, "三色同順", is_sanshokudoujun, 2, 1), yaku!(19, "三色同刻", is_sanshokudoukou, 2, 2), yaku!(15, "混全帯幺九", is_chanta, 2, 1), yaku!(26, "純全帯幺九", is_junchan, 3, 2), yaku!(24, "混老頭", is_honroutou, 2, 2), yaku!(41, "清老頭", is_chinroutou, 13, 13), yaku!(21, "対々和", is_toitoihou, 2, 2), yaku!(22, "三暗刻", is_sanankou, 2, 2), yaku!(38, "四暗刻", is_suuankou, 13, 0), yaku!(48, "四暗刻単騎", is_suuankoutanki, 14, 0), yaku!(20, "三槓子", is_sankantsu, 2, 2), yaku!(44, "四槓子", is_suukantsu, 13, 13), yaku!(27, "混一色", is_honiisou, 3, 2), yaku!(29, "清一色", is_chiniisou, 6, 5), yaku!(23, "小三元", is_shousangen, 2, 2), yaku!(37, "大三元", is_daisangen, 13, 13), yaku!(43, "小四喜", is_shousuushii, 13, 13), yaku!(50, "大四喜", is_daisuushii, 14, 14), yaku!(40, "緑一色", is_ryuuiisou, 13, 13), yaku!(39, "字一色", is_tuuiisou, 13, 13), yaku!(45, "九蓮宝燈", is_chuurenpoutou, 13, 0), yaku!(47, "純正九蓮宝燈", is_junseichuurenpoutou, 14, 0), // 特殊な組み合わせ yaku!(42, "国士無双", is_kokushimusou, 13, 0), yaku!(49, "国士無双13面", is_kokushimusoujuusanmenmachi, 14, 0), yaku!(25, "七対子", is_chiitoitsu, 2, 0), // 特殊条件 yaku!(1, "門前清自摸和", is_menzentsumo, 1, 0), yaku!(2, "立直", is_riichi, 1, 0), yaku!(18, "両立直", is_dabururiichi, 2, 0), yaku!(30, "一発", is_ippatsu, 1, 0), yaku!(5, "海底摸月", is_haiteiraoyue, 1, 1), yaku!(6, "河底撈魚", is_houteiraoyui, 1, 1), yaku!(4, "嶺上開花", is_rinshankaihou, 1, 1), yaku!(3, "槍槓", is_chankan, 1, 1), yaku!(35, "天和", is_tenhou, 1, 1), yaku!(36, "地和", is_tiihou, 1, 1), yaku!(31, "ドラ", skip, 0, 0), yaku!(32, "赤ドラ", skip, 0, 0), yaku!(33, "裏ドラ", skip, 0, 0), yaku!(34, "抜きドラ", skip, 0, 0), ]; // [役の優先順位] // * 役満が存在する場合は役満以外の役は削除 // * 以下の役は排他的(包含関係)であり右側を優先 // 一盃口, 二盃口 // チャンタ, 純チャンタ // 混老頭, 清老頭 // 混一色, 清一色 // 三暗刻, 四暗刻, 四暗刻単騎 // 三槓子, 四槓子 // 小四喜, 大四喜 // 九蓮宝燈, 純正九蓮宝燈 // 国士無双, 国士無双十三面待ち // 場風 fn is_bakaze_e(ctx: &YakuContext) -> bool { ctx.prevalent_wind == WE && ctx.yakuhai_check[WE] == 1 } fn is_bakaze_s(ctx: &YakuContext) -> bool { ctx.prevalent_wind == WS && ctx.yakuhai_check[WS] == 1 } fn is_bakaze_w(ctx: &YakuContext) -> bool { ctx.prevalent_wind == WW && ctx.yakuhai_check[WW] == 1 } fn is_bakaze_n(ctx: &YakuContext) -> bool { ctx.prevalent_wind == WN && ctx.yakuhai_check[WN] == 1 } // 自風 fn is_jikaze_e(ctx: &YakuContext) -> bool { ctx.seat_wind == WE && ctx.yakuhai_check[WE] == 1 } fn is_jikaze_s(ctx: &YakuContext) -> bool { ctx.seat_wind == WS && ctx.yakuhai_check[WS] == 1 } fn is_jikaze_w(ctx: &YakuContext) -> bool { ctx.seat_wind == WW && ctx.yakuhai_check[WW] == 1 } fn is_jikaze_n(ctx: &YakuContext) -> bool { ctx.seat_wind == WN && ctx.yakuhai_check[WN] == 1 } // 白 fn is_haku(ctx: &YakuContext) -> bool { ctx.yakuhai_check[DW] == 1 } // 發 fn is_hatsu(ctx: &YakuContext) -> bool { ctx.yakuhai_check[DG] == 1 } // 中 fn is_chun(ctx: &YakuContext) -> bool { ctx.yakuhai_check[DR] == 1 } // 断么九 fn is_tanyaochuu(ctx: &YakuContext) -> bool { if ctx.parsed_hand.is_empty() { return false; // 国士対策 } for SetPair(tp, t) in &ctx.parsed_hand { match tp { Chi | Shuntsu => { if t.1 == 1 || t.1 == 7 { return false; } } _ => { if t.is_end() { return false; } } } } true } // 平和 fn is_pinfu(ctx: &YakuContext) -> bool { if ctx.counts.shuntsu != 4 { return false; } let pt = &ctx.pair_tile; if pt.is_hornor() { if pt.is_doragon() || pt.1 == ctx.prevalent_wind || pt.1 == ctx.seat_wind { return false; } } // 上がり牌の両面待ち判定 let wt = &ctx.win_tile; if wt.is_hornor() { return false; } for SetPair(tp, t) in &ctx.parsed_hand { match tp { Shuntsu => { if t.0 == wt.0 { if t.1 == wt.1 || (wt.1 > 2 && t.1 == wt.1 - 2) { return true; } } } _ => {} } } false } // 一盃口 fn is_iipeikou(ctx: &YakuContext) -> bool { !ctx.is_open && ctx.iipeikou_count == 1 } // 二盃口 fn is_ryanpeikou(ctx: &YakuContext) -> bool { !ctx.is_open && ctx.iipeikou_count == 2 } // 一気通貫 fn is_ikkitsuukan(ctx: &YakuContext) -> bool { if ctx.counts.shuntsu_total < 3 { return false; } let mut f147 = [false; 3]; for SetPair(tp, t) in &ctx.parsed_hand { match tp { Shuntsu | Chi => { if ctx.counts.tis[t.0] >= 3 { match t.1 { 1 | 4 | 7 => f147[t.1 / 3] = true, _ => {} } } } _ => {} } } return f147[0] && f147[1] && f147[2]; } // 三色同順 fn is_sanshokudoujun(ctx: &YakuContext) -> bool { if ctx.counts.shuntsu_total < 3 { return false; } let mut mps = [false; 3]; for SetPair(tp, t) in &ctx.parsed_hand { match tp { Shuntsu | Chi => { if t.is_suit() && ctx.counts.nis[t.1] >= 3 { mps[t.0] = true; } } _ => {} } } mps[0] && mps[1] && mps[2] } // 三色同刻 fn is_sanshokudoukou(ctx: &YakuContext) -> bool { if ctx.counts.koutsu_total < 3 { return false; } let mut mps = [false; 3]; for SetPair(tp, t) in &ctx.parsed_hand { match tp { Koutsu | Pon | Minkan | Ankan => { if t.is_suit() && ctx.counts.nis[t.1] >= 3 { mps[t.0] = true; } } _ => {} } } mps[0] && mps[1] && mps[2] } // チャンタ fn is_chanta(ctx: &YakuContext) -> bool { if ctx.counts.shuntsu_total == 0 { return false; } let mut has_hornor = false; for SetPair(tp, t) in &ctx.parsed_hand { match tp { Pair | Koutsu | Pon | Minkan | Ankan => { if t.is_hornor() { has_hornor = true; } else if !t.is_terminal() { return false; } } Shuntsu | Chi => { if t.1 != 1 && t.1 != 7 { return false; } } } } has_hornor } // 純チャン fn is_junchan(ctx: &YakuContext) -> bool { if ctx.counts.shuntsu_total == 0 { return false; } for SetPair(tp, t) in &ctx.parsed_hand { match tp { Pair | Koutsu | Pon | Minkan | Ankan => { if !t.is_terminal() { return false; } } Shuntsu | Chi => { if t.1 != 1 && t.1 != 7 { return false; } } } } true } // 混老頭 fn is_honroutou(ctx: &YakuContext) -> bool { if ctx.counts.shuntsu_total != 0 { return false; } let mut has_hornor = false; let mut has_terminal = false; for SetPair(_, t) in &ctx.parsed_hand { if t.is_hornor() { has_hornor = true; } else if t.is_terminal() { has_terminal = true; } else { return false; } } has_hornor && has_terminal } // 清老頭 fn is_chinroutou(ctx: &YakuContext) -> bool { if ctx.counts.shuntsu_total != 0 { return false; } let mut has_terminal = false; for SetPair(_, t) in &ctx.parsed_hand { if t.is_terminal() { has_terminal = true; } else { return false; } } has_terminal } // 対々和 fn is_toitoihou(ctx: &YakuContext) -> bool { ctx.counts.koutsu_total == 4 } // 三暗刻 fn is_sanankou(ctx: &YakuContext) -> bool { if ctx.counts.ankou_total < 3 { return false; } let mut cnt = 0; for SetPair(tp, t) in &ctx.parsed_hand { if let Koutsu = tp { if !ctx.is_tsumo && ctx.win_tile == *t { continue; } cnt += 1; } } cnt == 3 } // 四暗刻 fn is_suuankou(ctx: &YakuContext) -> bool { ctx.counts.ankou_total == 4 && ctx.win_tile != ctx.pair_tile && ctx.is_tsumo } // 四暗刻単騎 fn is_suuankoutanki(ctx: &YakuContext) -> bool { ctx.counts.ankou_total == 4 && ctx.win_tile == ctx.pair_tile } // 三槓子 fn is_sankantsu(ctx: &YakuContext) -> bool { ctx.counts.kantsu_total == 3 } // 四槓子 fn is_suukantsu(ctx: &YakuContext) -> bool { ctx.counts.kantsu_total == 4 } // 混一色 fn is_honiisou(ctx: &YakuContext) -> bool { use std::cmp::min; let tis = &ctx.counts.tis; let suit = min(tis[TM], 1) + min(tis[TP], 1) + min(tis[TS], 1); suit == 1 && tis[TZ] > 0 } // 清一色 fn is_chiniisou(ctx: &YakuContext) -> bool { use std::cmp::min; let tis = &ctx.counts.tis; let suit = min(tis[TM], 1) + min(tis[TP], 1) + min(tis[TS], 1); suit == 1 && tis[TZ] == 0 } // 小三元 fn is_shousangen(ctx: &YakuContext) -> bool { let yc = &ctx.yakuhai_check; yc[DW] + yc[DG] + yc[DR] == 2 && ctx.pair_tile.is_doragon() } // 大三元 fn is_daisangen(ctx: &YakuContext) -> bool { let yc = &ctx.yakuhai_check; yc[DW] + yc[DG] + yc[DR] == 3 } // 小四喜 fn is_shousuushii(ctx: &YakuContext) -> bool { let yc = &ctx.yakuhai_check; yc[WE] + yc[WS] + yc[WW] + yc[WN] == 3 && ctx.pair_tile.is_wind() } // 大四喜 fn is_daisuushii(ctx: &YakuContext) -> bool { let yc = &ctx.yakuhai_check; yc[WE] + yc[WS] + yc[WW] + yc[WN] == 4 } // 緑一色 fn is_ryuuiisou(ctx: &YakuContext) -> bool { let tis = &ctx.counts.tis; if tis[TS] + tis[TZ] != 5 { return false; } for SetPair(tp, t) in &ctx.parsed_hand { match tp { Pair | Koutsu | Pon | Minkan | Ankan => { if t.is_hornor() { if t.1 != DG { return false; } } else { match t.1 { 2 | 3 | 4 | 6 | 8 => {} _ => return false, } } } Shuntsu | Chi => { if t.1 != 2 { // 順子は234以外は不可 return false; } } } } true } // 字一色 fn is_tuuiisou(ctx: &YakuContext) -> bool { (ctx.parsed_hand.len() == 5 && ctx.counts.tis[TZ] == 5) || ctx.counts.tis[TZ] == 7 } // 九蓮宝燈 fn is_chuurenpoutou(ctx: &YakuContext) -> bool { let wt = &ctx.win_tile; let cnt = ctx.hand[wt.0][wt.1]; is_chuurenpoutou2(ctx) && (cnt == 1 || cnt == 3) } // 純正九蓮宝燈 fn is_junseichuurenpoutou(ctx: &YakuContext) -> bool { let wt = &ctx.win_tile; let cnt = ctx.hand[wt.0][wt.1]; is_chuurenpoutou2(ctx) && (cnt == 2 || cnt == 4) } // 国士無双 fn is_kokushimusou(ctx: &YakuContext) -> bool { if ctx.parsed_hand.len() != 0 { return false; } let wt = &ctx.win_tile; is_kokushimusou_win(&ctx.hand) && ctx.hand[wt.0][wt.1] != 2 } // 国士無双十三面待ち fn is_kokushimusoujuusanmenmachi(ctx: &YakuContext) -> bool { if ctx.parsed_hand.len() != 0 { return false; } let wt = &ctx.win_tile; is_kokushimusou_win(&ctx.hand) && ctx.hand[wt.0][wt.1] == 2 } // 七対子 fn is_chiitoitsu(ctx: &YakuContext) -> bool { ctx.parsed_hand.len() == 7 } // 門前自摸 fn is_menzentsumo(ctx: &YakuContext) -> bool { ctx.yaku_flags.menzentsumo } // リーチ fn is_riichi(ctx: &YakuContext) -> bool { ctx.yaku_flags.riichi && !ctx.yaku_flags.dabururiichi } // ダブルリーチ fn is_dabururiichi(ctx: &YakuContext) -> bool { ctx.yaku_flags.dabururiichi } // 一発 fn is_ippatsu(ctx: &YakuContext) -> bool { ctx.yaku_flags.ippatsu } // 海底撈月 fn is_haiteiraoyue(ctx: &YakuContext) -> bool { ctx.yaku_flags.haiteiraoyue } // 河底撈魚 fn is_houteiraoyui(ctx: &YakuContext) -> bool { ctx.yaku_flags.houteiraoyui } // 嶺上開花 fn is_rinshankaihou(ctx: &YakuContext) -> bool { ctx.yaku_flags.rinshankaihou } // 槍槓 fn is_chankan(ctx: &YakuContext) -> bool { ctx.yaku_flags.chankan } // 天和 fn is_tenhou(ctx: &YakuContext) -> bool { ctx.yaku_flags.tenhou } // 地和 fn is_tiihou(ctx: &YakuContext) -> bool { ctx.yaku_flags.tiihou } // [共通処理] // 九蓮宝燈(純正を含む) fn is_chuurenpoutou2(ctx: &YakuContext) -> bool { if ctx.is_open { return false; } let tis = &ctx.counts.tis; let ti = if tis[TM] == 5 { TM } else if tis[TP] == 5 { TP } else if tis[TS] == 5 { TS } else { return false; }; let h = &ctx.hand; if h[ti][1] < 3 || h[ti][9] < 3 { return false; } for ni in 2..9 { if h[ti][ni] == 0 { return false; } } true } // 判定スキップ fn skip(_ctx: &YakuContext) -> bool { false }
24.183946
93
0.477896
cc2c7dc664ecda1363e16334ab19aac2e0371b1d
3,174
extern crate tokenizers as tk; use crate::utils::Container; use neon::prelude::*; /// Decoder pub struct Decoder { pub decoder: Container<dyn tk::tokenizer::Decoder + Sync>, } declare_types! { pub class JsDecoder for Decoder { init(_) { // This should not be called from JS Ok(Decoder { decoder: Container::Empty }) } } } /// byte_level() fn byte_level(mut cx: FunctionContext) -> JsResult<JsDecoder> { let mut decoder = JsDecoder::new::<_, JsDecoder, _>(&mut cx, vec![])?; let guard = cx.lock(); decoder .borrow_mut(&guard) .decoder .to_owned(Box::new(tk::decoders::byte_level::ByteLevel::new(false))); Ok(decoder) } /// wordpiece(prefix: String = "##") fn wordpiece(mut cx: FunctionContext) -> JsResult<JsDecoder> { let mut prefix = String::from("##"); if let Some(args) = cx.argument_opt(0) { prefix = args.downcast::<JsString>().or_throw(&mut cx)?.value() as String; } let mut decoder = JsDecoder::new::<_, JsDecoder, _>(&mut cx, vec![])?; let guard = cx.lock(); decoder .borrow_mut(&guard) .decoder .to_owned(Box::new(tk::decoders::wordpiece::WordPiece::new(prefix))); Ok(decoder) } /// metaspace(replacement: String = "_", add_prefix_space: bool = true) fn metaspace(mut cx: FunctionContext) -> JsResult<JsDecoder> { let mut replacement = '▁'; if let Some(args) = cx.argument_opt(0) { let rep = args.downcast::<JsString>().or_throw(&mut cx)?.value() as String; replacement = rep.chars().nth(0).ok_or_else(|| { cx.throw_error::<_, ()>("replacement must be a character") .unwrap_err() })?; }; let mut add_prefix_space = true; if let Some(args) = cx.argument_opt(1) { add_prefix_space = args.downcast::<JsBoolean>().or_throw(&mut cx)?.value() as bool; } let mut decoder = JsDecoder::new::<_, JsDecoder, _>(&mut cx, vec![])?; let guard = cx.lock(); decoder .borrow_mut(&guard) .decoder .to_owned(Box::new(tk::decoders::metaspace::Metaspace::new( replacement, add_prefix_space, ))); Ok(decoder) } /// bpe_decoder(suffix: String = "</w>") fn bpe_decoder(mut cx: FunctionContext) -> JsResult<JsDecoder> { let mut suffix = String::from("</w>"); if let Some(args) = cx.argument_opt(0) { suffix = args.downcast::<JsString>().or_throw(&mut cx)?.value() as String; } let mut decoder = JsDecoder::new::<_, JsDecoder, _>(&mut cx, vec![])?; let guard = cx.lock(); decoder .borrow_mut(&guard) .decoder .to_owned(Box::new(tk::decoders::bpe::BPEDecoder::new(suffix))); Ok(decoder) } /// Register everything here pub fn register(m: &mut ModuleContext, prefix: &str) -> NeonResult<()> { m.export_function(&format!("{}_ByteLevel", prefix), byte_level)?; m.export_function(&format!("{}_WordPiece", prefix), wordpiece)?; m.export_function(&format!("{}_Metaspace", prefix), metaspace)?; m.export_function(&format!("{}_BPEDecoder", prefix), bpe_decoder)?; Ok(()) }
31.425743
91
0.598929
e877e9f4cda6dc3e340e2cc0563618807732723d
27,408
use alloc::vec::Vec; use core::convert::TryInto; use core::fmt::Debug; use core::{mem, str}; use crate::read::{ self, util, Architecture, Error, Export, FileFlags, Import, Object, ReadError, ReadRef, SectionIndex, StringTable, SymbolIndex, }; use crate::{elf, endian, ByteString, Bytes, Endian, Endianness, Pod, U32}; use super::{ CompressionHeader, Dyn, ElfComdat, ElfComdatIterator, ElfDynamicRelocationIterator, ElfSection, ElfSectionIterator, ElfSegment, ElfSegmentIterator, ElfSymbol, ElfSymbolIterator, ElfSymbolTable, NoteHeader, ProgramHeader, Rel, Rela, RelocationSections, SectionHeader, SectionTable, Sym, SymbolTable, }; /// A 32-bit ELF object file. pub type ElfFile32<'data, Endian = Endianness, R = &'data [u8]> = ElfFile<'data, elf::FileHeader32<Endian>, R>; /// A 64-bit ELF object file. pub type ElfFile64<'data, Endian = Endianness, R = &'data [u8]> = ElfFile<'data, elf::FileHeader64<Endian>, R>; /// A partially parsed ELF file. /// /// Most of the functionality of this type is provided by the `Object` trait implementation. #[derive(Debug)] pub struct ElfFile<'data, Elf, R = &'data [u8]> where Elf: FileHeader, R: ReadRef<'data>, { pub(super) endian: Elf::Endian, pub(super) data: R, pub(super) header: &'data Elf, pub(super) segments: &'data [Elf::ProgramHeader], pub(super) sections: SectionTable<'data, Elf>, pub(super) relocations: RelocationSections, pub(super) symbols: SymbolTable<'data, Elf>, pub(super) dynamic_symbols: SymbolTable<'data, Elf>, } impl<'data, Elf, R> ElfFile<'data, Elf, R> where Elf: FileHeader, R: ReadRef<'data>, { /// Parse the raw ELF file data. pub fn parse(data: R) -> read::Result<Self> { let header = Elf::parse(data)?; let endian = header.endian()?; let segments = header.program_headers(endian, data)?; let sections = header.sections(endian, data)?; let symbols = sections.symbols(endian, data, elf::SHT_SYMTAB)?; // TODO: get dynamic symbols from DT_SYMTAB if there are no sections let dynamic_symbols = sections.symbols(endian, data, elf::SHT_DYNSYM)?; // The API we provide requires a mapping from section to relocations, so build it now. let relocations = sections.relocation_sections(endian, symbols.section())?; Ok(ElfFile { endian, data, header, segments, sections, relocations, symbols, dynamic_symbols, }) } /// Returns the endianness. pub fn endian(&self) -> Elf::Endian { self.endian } /// Returns the raw data. pub fn data(&self) -> R { self.data } /// Returns the raw ELF file header. pub fn raw_header(&self) -> &'data Elf { self.header } /// Returns the raw ELF segments. pub fn raw_segments(&self) -> &'data [Elf::ProgramHeader] { self.segments } fn raw_section_by_name<'file>( &'file self, section_name: &str, ) -> Option<ElfSection<'data, 'file, Elf, R>> { self.sections .section_by_name(self.endian, section_name.as_bytes()) .map(|(index, section)| ElfSection { file: self, index: SectionIndex(index), section, }) } #[cfg(feature = "compression")] fn zdebug_section_by_name<'file>( &'file self, section_name: &str, ) -> Option<ElfSection<'data, 'file, Elf, R>> { if !section_name.starts_with(".debug_") { return None; } self.raw_section_by_name(&format!(".zdebug_{}", &section_name[7..])) } #[cfg(not(feature = "compression"))] fn zdebug_section_by_name<'file>( &'file self, _section_name: &str, ) -> Option<ElfSection<'data, 'file, Elf, R>> { None } } impl<'data, Elf, R> read::private::Sealed for ElfFile<'data, Elf, R> where Elf: FileHeader, R: ReadRef<'data>, { } impl<'data, 'file, Elf, R> Object<'data, 'file> for ElfFile<'data, Elf, R> where 'data: 'file, Elf: FileHeader, R: 'file + ReadRef<'data>, { type Segment = ElfSegment<'data, 'file, Elf, R>; type SegmentIterator = ElfSegmentIterator<'data, 'file, Elf, R>; type Section = ElfSection<'data, 'file, Elf, R>; type SectionIterator = ElfSectionIterator<'data, 'file, Elf, R>; type Comdat = ElfComdat<'data, 'file, Elf, R>; type ComdatIterator = ElfComdatIterator<'data, 'file, Elf, R>; type Symbol = ElfSymbol<'data, 'file, Elf>; type SymbolIterator = ElfSymbolIterator<'data, 'file, Elf>; type SymbolTable = ElfSymbolTable<'data, 'file, Elf>; type DynamicRelocationIterator = ElfDynamicRelocationIterator<'data, 'file, Elf, R>; fn architecture(&self) -> Architecture { match ( self.header.e_machine(self.endian), self.header.is_class_64(), ) { (elf::EM_AARCH64, _) => Architecture::Aarch64, (elf::EM_ARM, _) => Architecture::Arm, (elf::EM_AVR, _) => Architecture::Avr, (elf::EM_BPF, _) => Architecture::Bpf, (elf::EM_386, _) => Architecture::I386, (elf::EM_X86_64, false) => Architecture::X86_64_X32, (elf::EM_X86_64, true) => Architecture::X86_64, (elf::EM_HEXAGON, _) => Architecture::Hexagon, (elf::EM_MIPS, false) => Architecture::Mips, (elf::EM_MIPS, true) => Architecture::Mips64, (elf::EM_MSP430, _) => Architecture::Msp430, (elf::EM_PPC, _) => Architecture::PowerPc, (elf::EM_PPC64, _) => Architecture::PowerPc64, (elf::EM_RISCV, false) => Architecture::Riscv32, (elf::EM_RISCV, true) => Architecture::Riscv64, // This is either s390 or s390x, depending on the ELF class. // We only support the 64-bit variant s390x here. (elf::EM_S390, true) => Architecture::S390x, (elf::EM_SPARCV9, true) => Architecture::Sparc64, _ => Architecture::Unknown, } } #[inline] fn is_little_endian(&self) -> bool { self.header.is_little_endian() } #[inline] fn is_64(&self) -> bool { self.header.is_class_64() } fn segments(&'file self) -> ElfSegmentIterator<'data, 'file, Elf, R> { ElfSegmentIterator { file: self, iter: self.segments.iter(), } } fn section_by_name( &'file self, section_name: &str, ) -> Option<ElfSection<'data, 'file, Elf, R>> { self.raw_section_by_name(section_name) .or_else(|| self.zdebug_section_by_name(section_name)) } fn section_by_index( &'file self, index: SectionIndex, ) -> read::Result<ElfSection<'data, 'file, Elf, R>> { let section = self.sections.section(index.0)?; Ok(ElfSection { file: self, index, section, }) } fn sections(&'file self) -> ElfSectionIterator<'data, 'file, Elf, R> { ElfSectionIterator { file: self, iter: self.sections.iter().enumerate(), } } fn comdats(&'file self) -> ElfComdatIterator<'data, 'file, Elf, R> { ElfComdatIterator { file: self, iter: self.sections.iter().enumerate(), } } fn symbol_by_index( &'file self, index: SymbolIndex, ) -> read::Result<ElfSymbol<'data, 'file, Elf>> { let symbol = self.symbols.symbol(index.0)?; Ok(ElfSymbol { endian: self.endian, symbols: &self.symbols, index, symbol, }) } fn symbols(&'file self) -> ElfSymbolIterator<'data, 'file, Elf> { ElfSymbolIterator { endian: self.endian, symbols: &self.symbols, index: 0, } } fn symbol_table(&'file self) -> Option<ElfSymbolTable<'data, 'file, Elf>> { Some(ElfSymbolTable { endian: self.endian, symbols: &self.symbols, }) } fn dynamic_symbols(&'file self) -> ElfSymbolIterator<'data, 'file, Elf> { ElfSymbolIterator { endian: self.endian, symbols: &self.dynamic_symbols, index: 0, } } fn dynamic_symbol_table(&'file self) -> Option<ElfSymbolTable<'data, 'file, Elf>> { Some(ElfSymbolTable { endian: self.endian, symbols: &self.dynamic_symbols, }) } fn dynamic_relocations( &'file self, ) -> Option<ElfDynamicRelocationIterator<'data, 'file, Elf, R>> { Some(ElfDynamicRelocationIterator { section_index: 1, file: self, relocations: None, }) } /// Get the imported symbols. fn imports(&self) -> read::Result<Vec<Import<'data>>> { let mut imports = Vec::new(); for symbol in self.dynamic_symbols.iter() { if symbol.is_undefined(self.endian) { let name = symbol.name(self.endian, self.dynamic_symbols.strings())?; if !name.is_empty() { // TODO: use symbol versioning to determine library imports.push(Import { name: ByteString(name), library: ByteString(&[]), }); } } } Ok(imports) } /// Get the exported symbols. fn exports(&self) -> read::Result<Vec<Export<'data>>> { let mut exports = Vec::new(); for symbol in self.dynamic_symbols.iter() { if symbol.is_definition(self.endian) { let name = symbol.name(self.endian, self.dynamic_symbols.strings())?; let address = symbol.st_value(self.endian).into(); exports.push(Export { name: ByteString(name), address, }); } } Ok(exports) } fn has_debug_symbols(&self) -> bool { for section in self.sections.iter() { if let Ok(name) = self.sections.section_name(self.endian, section) { if name == b".debug_info" || name == b".zdebug_info" { return true; } } } false } fn build_id(&self) -> read::Result<Option<&'data [u8]>> { let endian = self.endian; // Use section headers if present, otherwise use program headers. if !self.sections.is_empty() { for section in self.sections.iter() { if let Some(mut notes) = section.notes(endian, self.data)? { while let Some(note) = notes.next()? { if note.name() == elf::ELF_NOTE_GNU && note.n_type(endian) == elf::NT_GNU_BUILD_ID { return Ok(Some(note.desc())); } } } } } else { for segment in self.segments { if let Some(mut notes) = segment.notes(endian, self.data)? { while let Some(note) = notes.next()? { if note.name() == elf::ELF_NOTE_GNU && note.n_type(endian) == elf::NT_GNU_BUILD_ID { return Ok(Some(note.desc())); } } } } } Ok(None) } fn gnu_debuglink(&self) -> read::Result<Option<(&'data [u8], u32)>> { let section = match self.raw_section_by_name(".gnu_debuglink") { Some(section) => section, None => return Ok(None), }; let data = section .section .data(self.endian, self.data) .read_error("Invalid ELF .gnu_debuglink section offset or size") .map(Bytes)?; let filename = data .read_string_at(0) .read_error("Missing ELF .gnu_debuglink filename")?; let crc_offset = util::align(filename.len() + 1, 4); let crc = data .read_at::<U32<_>>(crc_offset) .read_error("Missing ELF .gnu_debuglink crc")? .get(self.endian); Ok(Some((filename, crc))) } fn gnu_debugaltlink(&self) -> read::Result<Option<(&'data [u8], &'data [u8])>> { let section = match self.raw_section_by_name(".gnu_debugaltlink") { Some(section) => section, None => return Ok(None), }; let mut data = section .section .data(self.endian, self.data) .read_error("Invalid ELF .gnu_debugaltlink section offset or size") .map(Bytes)?; let filename = data .read_string() .read_error("Missing ELF .gnu_debugaltlink filename")?; let build_id = data.0; Ok(Some((filename, build_id))) } fn relative_address_base(&self) -> u64 { 0 } fn entry(&self) -> u64 { self.header.e_entry(self.endian).into() } fn flags(&self) -> FileFlags { FileFlags::Elf { e_flags: self.header.e_flags(self.endian), } } } /// A trait for generic access to `FileHeader32` and `FileHeader64`. #[allow(missing_docs)] pub trait FileHeader: Debug + Pod { // Ideally this would be a `u64: From<Word>`, but can't express that. type Word: Into<u64>; type Sword: Into<i64>; type Endian: endian::Endian; type ProgramHeader: ProgramHeader<Elf = Self, Endian = Self::Endian, Word = Self::Word>; type SectionHeader: SectionHeader<Elf = Self, Endian = Self::Endian, Word = Self::Word>; type CompressionHeader: CompressionHeader<Endian = Self::Endian, Word = Self::Word>; type NoteHeader: NoteHeader<Endian = Self::Endian>; type Dyn: Dyn<Endian = Self::Endian, Word = Self::Word>; type Sym: Sym<Endian = Self::Endian, Word = Self::Word>; type Rel: Rel<Endian = Self::Endian, Word = Self::Word>; type Rela: Rela<Endian = Self::Endian, Word = Self::Word> + From<Self::Rel>; /// Return true if this type is a 64-bit header. /// /// This is a property of the type, not a value in the header data. fn is_type_64(&self) -> bool; fn e_ident(&self) -> &elf::Ident; fn e_type(&self, endian: Self::Endian) -> u16; fn e_machine(&self, endian: Self::Endian) -> u16; fn e_version(&self, endian: Self::Endian) -> u32; fn e_entry(&self, endian: Self::Endian) -> Self::Word; fn e_phoff(&self, endian: Self::Endian) -> Self::Word; fn e_shoff(&self, endian: Self::Endian) -> Self::Word; fn e_flags(&self, endian: Self::Endian) -> u32; fn e_ehsize(&self, endian: Self::Endian) -> u16; fn e_phentsize(&self, endian: Self::Endian) -> u16; fn e_phnum(&self, endian: Self::Endian) -> u16; fn e_shentsize(&self, endian: Self::Endian) -> u16; fn e_shnum(&self, endian: Self::Endian) -> u16; fn e_shstrndx(&self, endian: Self::Endian) -> u16; // Provided methods. /// Read the file header. /// /// Also checks that the ident field in the file header is a supported format. fn parse<'data, R: ReadRef<'data>>(data: R) -> read::Result<&'data Self> { let header = data .read_at::<Self>(0) .read_error("Invalid ELF header size or alignment")?; if !header.is_supported() { return Err(Error("Unsupported ELF header")); } // TODO: Check self.e_ehsize? Ok(header) } /// Check that the ident field in the file header is a supported format. /// /// This checks the magic number, version, class, and endianness. fn is_supported(&self) -> bool { let ident = self.e_ident(); // TODO: Check self.e_version too? Requires endian though. ident.magic == elf::ELFMAG && (self.is_type_64() || self.is_class_32()) && (!self.is_type_64() || self.is_class_64()) && (self.is_little_endian() || self.is_big_endian()) && ident.version == elf::EV_CURRENT } fn is_class_32(&self) -> bool { self.e_ident().class == elf::ELFCLASS32 } fn is_class_64(&self) -> bool { self.e_ident().class == elf::ELFCLASS64 } fn is_little_endian(&self) -> bool { self.e_ident().data == elf::ELFDATA2LSB } fn is_big_endian(&self) -> bool { self.e_ident().data == elf::ELFDATA2MSB } fn endian(&self) -> read::Result<Self::Endian> { Self::Endian::from_big_endian(self.is_big_endian()).read_error("Unsupported ELF endian") } /// Return the first section header, if present. /// /// Section 0 is a special case because getting the section headers normally /// requires `shnum`, but `shnum` may be in the first section header. fn section_0<'data, R: ReadRef<'data>>( &self, endian: Self::Endian, data: R, ) -> read::Result<Option<&'data Self::SectionHeader>> { let shoff: u64 = self.e_shoff(endian).into(); if shoff == 0 { // No section headers is ok. return Ok(None); } let shentsize = usize::from(self.e_shentsize(endian)); if shentsize != mem::size_of::<Self::SectionHeader>() { // Section header size must match. return Err(Error("Invalid ELF section header entry size")); } data.read_at(shoff) .map(Some) .read_error("Invalid ELF section header offset or size") } /// Return the `e_phnum` field of the header. Handles extended values. /// /// Returns `Err` for invalid values. fn phnum<'data, R: ReadRef<'data>>( &self, endian: Self::Endian, data: R, ) -> read::Result<usize> { let e_phnum = self.e_phnum(endian); if e_phnum < elf::PN_XNUM { Ok(e_phnum as usize) } else if let Some(section_0) = self.section_0(endian, data)? { Ok(section_0.sh_info(endian) as usize) } else { // Section 0 must exist if e_phnum overflows. Err(Error("Missing ELF section headers for e_phnum overflow")) } } /// Return the `e_shnum` field of the header. Handles extended values. /// /// Returns `Err` for invalid values. fn shnum<'data, R: ReadRef<'data>>( &self, endian: Self::Endian, data: R, ) -> read::Result<usize> { let e_shnum = self.e_shnum(endian); if e_shnum > 0 { Ok(e_shnum as usize) } else if let Some(section_0) = self.section_0(endian, data)? { section_0 .sh_size(endian) .into() .try_into() .ok() .read_error("Invalid ELF extended e_shnum") } else { // No section headers is ok. Ok(0) } } /// Return the `e_shstrndx` field of the header. Handles extended values. /// /// Returns `Err` for invalid values (including if the index is 0). fn shstrndx<'data, R: ReadRef<'data>>( &self, endian: Self::Endian, data: R, ) -> read::Result<u32> { let e_shstrndx = self.e_shstrndx(endian); let index = if e_shstrndx != elf::SHN_XINDEX { e_shstrndx.into() } else if let Some(section_0) = self.section_0(endian, data)? { section_0.sh_link(endian) } else { // Section 0 must exist if we're trying to read e_shstrndx. return Err(Error("Missing ELF section headers for e_shstrndx overflow")); }; if index == 0 { return Err(Error("Missing ELF e_shstrndx")); } Ok(index) } /// Return the slice of program headers. /// /// Returns `Ok(&[])` if there are no program headers. /// Returns `Err` for invalid values. fn program_headers<'data, R: ReadRef<'data>>( &self, endian: Self::Endian, data: R, ) -> read::Result<&'data [Self::ProgramHeader]> { let phoff: u64 = self.e_phoff(endian).into(); if phoff == 0 { // No program headers is ok. return Ok(&[]); } let phnum = self.phnum(endian, data)?; if phnum == 0 { // No program headers is ok. return Ok(&[]); } let phentsize = self.e_phentsize(endian) as usize; if phentsize != mem::size_of::<Self::ProgramHeader>() { // Program header size must match. return Err(Error("Invalid ELF program header entry size")); } data.read_slice_at(phoff, phnum) .read_error("Invalid ELF program header size or alignment") } /// Return the slice of section headers. /// /// Returns `Ok(&[])` if there are no section headers. /// Returns `Err` for invalid values. fn section_headers<'data, R: ReadRef<'data>>( &self, endian: Self::Endian, data: R, ) -> read::Result<&'data [Self::SectionHeader]> { let shoff: u64 = self.e_shoff(endian).into(); if shoff == 0 { // No section headers is ok. return Ok(&[]); } let shnum = self.shnum(endian, data)?; if shnum == 0 { // No section headers is ok. return Ok(&[]); } let shentsize = usize::from(self.e_shentsize(endian)); if shentsize != mem::size_of::<Self::SectionHeader>() { // Section header size must match. return Err(Error("Invalid ELF section header entry size")); } data.read_slice_at(shoff, shnum) .read_error("Invalid ELF section header offset/size/alignment") } /// Return the string table for the section headers. fn section_strings<'data, R: ReadRef<'data>>( &self, endian: Self::Endian, data: R, sections: &[Self::SectionHeader], ) -> read::Result<StringTable<'data>> { if sections.is_empty() { return Ok(StringTable::default()); } let index = self.shstrndx(endian, data)? as usize; let shstrtab = sections.get(index).read_error("Invalid ELF e_shstrndx")?; let data = shstrtab .data(endian, data) .read_error("Invalid ELF shstrtab data")?; Ok(StringTable::new(data)) } /// Return the section table. fn sections<'data, R: ReadRef<'data>>( &self, endian: Self::Endian, data: R, ) -> read::Result<SectionTable<'data, Self>> { let sections = self.section_headers(endian, data)?; let strings = self.section_strings(endian, data, sections)?; Ok(SectionTable::new(sections, strings)) } /// Returns whether this is a mips64el elf file. fn is_mips64el(&self, endian: Self::Endian) -> bool { self.is_class_64() && self.is_little_endian() && self.e_machine(endian) == elf::EM_MIPS } } impl<Endian: endian::Endian> FileHeader for elf::FileHeader32<Endian> { type Word = u32; type Sword = i32; type Endian = Endian; type ProgramHeader = elf::ProgramHeader32<Endian>; type SectionHeader = elf::SectionHeader32<Endian>; type CompressionHeader = elf::CompressionHeader32<Endian>; type NoteHeader = elf::NoteHeader32<Endian>; type Dyn = elf::Dyn32<Endian>; type Sym = elf::Sym32<Endian>; type Rel = elf::Rel32<Endian>; type Rela = elf::Rela32<Endian>; #[inline] fn is_type_64(&self) -> bool { false } #[inline] fn e_ident(&self) -> &elf::Ident { &self.e_ident } #[inline] fn e_type(&self, endian: Self::Endian) -> u16 { self.e_type.get(endian) } #[inline] fn e_machine(&self, endian: Self::Endian) -> u16 { self.e_machine.get(endian) } #[inline] fn e_version(&self, endian: Self::Endian) -> u32 { self.e_version.get(endian) } #[inline] fn e_entry(&self, endian: Self::Endian) -> Self::Word { self.e_entry.get(endian) } #[inline] fn e_phoff(&self, endian: Self::Endian) -> Self::Word { self.e_phoff.get(endian) } #[inline] fn e_shoff(&self, endian: Self::Endian) -> Self::Word { self.e_shoff.get(endian) } #[inline] fn e_flags(&self, endian: Self::Endian) -> u32 { self.e_flags.get(endian) } #[inline] fn e_ehsize(&self, endian: Self::Endian) -> u16 { self.e_ehsize.get(endian) } #[inline] fn e_phentsize(&self, endian: Self::Endian) -> u16 { self.e_phentsize.get(endian) } #[inline] fn e_phnum(&self, endian: Self::Endian) -> u16 { self.e_phnum.get(endian) } #[inline] fn e_shentsize(&self, endian: Self::Endian) -> u16 { self.e_shentsize.get(endian) } #[inline] fn e_shnum(&self, endian: Self::Endian) -> u16 { self.e_shnum.get(endian) } #[inline] fn e_shstrndx(&self, endian: Self::Endian) -> u16 { self.e_shstrndx.get(endian) } } impl<Endian: endian::Endian> FileHeader for elf::FileHeader64<Endian> { type Word = u64; type Sword = i64; type Endian = Endian; type ProgramHeader = elf::ProgramHeader64<Endian>; type SectionHeader = elf::SectionHeader64<Endian>; type CompressionHeader = elf::CompressionHeader64<Endian>; type NoteHeader = elf::NoteHeader32<Endian>; type Dyn = elf::Dyn64<Endian>; type Sym = elf::Sym64<Endian>; type Rel = elf::Rel64<Endian>; type Rela = elf::Rela64<Endian>; #[inline] fn is_type_64(&self) -> bool { true } #[inline] fn e_ident(&self) -> &elf::Ident { &self.e_ident } #[inline] fn e_type(&self, endian: Self::Endian) -> u16 { self.e_type.get(endian) } #[inline] fn e_machine(&self, endian: Self::Endian) -> u16 { self.e_machine.get(endian) } #[inline] fn e_version(&self, endian: Self::Endian) -> u32 { self.e_version.get(endian) } #[inline] fn e_entry(&self, endian: Self::Endian) -> Self::Word { self.e_entry.get(endian) } #[inline] fn e_phoff(&self, endian: Self::Endian) -> Self::Word { self.e_phoff.get(endian) } #[inline] fn e_shoff(&self, endian: Self::Endian) -> Self::Word { self.e_shoff.get(endian) } #[inline] fn e_flags(&self, endian: Self::Endian) -> u32 { self.e_flags.get(endian) } #[inline] fn e_ehsize(&self, endian: Self::Endian) -> u16 { self.e_ehsize.get(endian) } #[inline] fn e_phentsize(&self, endian: Self::Endian) -> u16 { self.e_phentsize.get(endian) } #[inline] fn e_phnum(&self, endian: Self::Endian) -> u16 { self.e_phnum.get(endian) } #[inline] fn e_shentsize(&self, endian: Self::Endian) -> u16 { self.e_shentsize.get(endian) } #[inline] fn e_shnum(&self, endian: Self::Endian) -> u16 { self.e_shnum.get(endian) } #[inline] fn e_shstrndx(&self, endian: Self::Endian) -> u16 { self.e_shstrndx.get(endian) } }
32.05614
99
0.55991
4ab6c00dd16b561ce2747b6e0f4d4e99264f87f6
4,380
use std::path::Path; use std::sync::{Arc, RwLock}; use wasi_common::pipe::{ReadPipe, WritePipe}; use wasmtime::*; use wasmtime_wasi::*; use crate::request::RequestGlobalContext; use crate::wasm_module::WasmModuleSource; const STDERR_FILE: &str = "module.stderr"; #[derive(Clone, Default)] pub struct WasmLinkOptions { pub http_allowed_hosts: Option<Vec<String>>, pub http_max_concurrency: Option<u32>, } impl WasmLinkOptions { pub fn none() -> Self { Self::default() } pub fn with_http( self, allowed_hosts: Option<Vec<String>>, max_concurrency: Option<u32>) -> Self { let mut result = self.clone(); result.http_allowed_hosts = allowed_hosts; result.http_max_concurrency = max_concurrency; result } pub fn apply_to(&self, linker: &mut Linker<WasiCtx>) -> anyhow::Result<()> { let http = wasi_experimental_http_wasmtime::HttpCtx::new( self.http_allowed_hosts.clone(), self.http_max_concurrency, )?; http.add_to_linker(linker)?; Ok(()) } } pub fn prepare_stdio_streams( body: Vec<u8>, global_context: &RequestGlobalContext, handler_id: String, ) -> Result<crate::wasm_module::IORedirectionInfo, Error> { let stdin = ReadPipe::from(body); let stdout_buf: Vec<u8> = vec![]; let stdout_mutex = Arc::new(RwLock::new(stdout_buf)); let stdout = WritePipe::from_shared(stdout_mutex.clone()); let log_dir = global_context.base_log_dir.join(handler_id); // The spec does not say what to do with STDERR. // See specifically sections 4.2 and 6.1 of RFC 3875. // Currently, we will attach to wherever logs go. tracing::info!(log_dir = %log_dir.display(), "Using log dir"); std::fs::create_dir_all(&log_dir)?; let stderr = cap_std::fs::File::from_std( std::fs::OpenOptions::new() .append(true) .create(true) .open(log_dir.join(STDERR_FILE))?, ambient_authority(), ); let stderr = wasi_cap_std_sync::file::File::from_cap_std(stderr); Ok(crate::wasm_module::IORedirectionInfo { streams: crate::wasm_module::IOStreamRedirects { stdin, stdout, stderr, }, stdout_mutex, }) } pub fn new_store_and_engine( cache_config_path: &Path, ctx: WasiCtx, ) -> Result<(Store<WasiCtx>, Engine), anyhow::Error> { let mut config = Config::default(); // Enable multi memory and module linking support. config.wasm_multi_memory(true); config.wasm_module_linking(true); if let Ok(p) = std::fs::canonicalize(cache_config_path) { config.cache_config_load(p)?; }; let engine = Engine::new(&config)?; Ok((Store::new(&engine, ctx), engine)) } pub fn prepare_wasm_instance( global_context: &RequestGlobalContext, ctx: WasiCtx, wasm_module_source: &WasmModuleSource, link_options: WasmLinkOptions, ) -> Result<(Store<WasiCtx>, Instance), Error> { let (mut store, engine) = new_store_and_engine(&global_context.cache_config_path, ctx)?; let mut linker = Linker::new(&engine); wasmtime_wasi::add_to_linker(&mut linker, |cx| cx)?; link_options.apply_to(&mut linker)?; let module = wasm_module_source.load_module(&store)?; let instance = linker.instantiate(&mut store, &module)?; Ok((store, instance)) } pub fn run_prepared_wasm_instance( instance: Instance, mut store: Store<WasiCtx>, entrypoint: &str, wasm_module_name: &str, ) -> Result<(), Error> { let start = instance.get_func(&mut store, entrypoint).ok_or_else(|| { anyhow::anyhow!("No such function '{}' in {}", entrypoint, wasm_module_name) })?; tracing::trace!("Calling Wasm entry point"); start.call(&mut store, &[], &mut vec![])?; Ok(()) } pub fn run_prepared_wasm_instance_if_present( instance: Instance, mut store: Store<WasiCtx>, entrypoint: &str, ) -> RunWasmResult<(), Error> { match instance.get_func(&mut store, entrypoint) { Some(func) => match func.call(&mut store, &[], &mut vec![]) { Ok(_) => RunWasmResult::Ok(()), Err(e) => RunWasmResult::WasmError(e), }, None => RunWasmResult::EntrypointNotFound, } } pub enum RunWasmResult<T, E> { Ok(T), WasmError(E), EntrypointNotFound, }
29.395973
92
0.640639
fc91142dd7da3d573c00a6f6d6525a102dfb63fe
60,559
use crate::check::FnCtxt; use rustc_ast::ast; use rustc_ast::util::lev_distance::find_best_match_for_name; use rustc_data_structures::fx::FxHashMap; use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder}; use rustc_hir as hir; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::pat_util::EnumerateAndAdjustIterator; use rustc_hir::{HirId, Pat, PatKind}; use rustc_infer::infer; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_middle::ty::subst::GenericArg; use rustc_middle::ty::{self, BindingMode, Ty, TypeFoldable}; use rustc_span::hygiene::DesugaringKind; use rustc_span::source_map::{Span, Spanned}; use rustc_trait_selection::traits::{ObligationCause, Pattern}; use std::cmp; use std::collections::hash_map::Entry::{Occupied, Vacant}; use super::report_unexpected_variant_res; const CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ: &str = "\ This error indicates that a pointer to a trait type cannot be implicitly dereferenced by a \ pattern. Every trait defines a type, but because the size of trait implementors isn't fixed, \ this type has no compile-time size. Therefore, all accesses to trait types must be through \ pointers. If you encounter this error you should try to avoid dereferencing the pointer. You can read more about trait objects in the Trait Objects section of the Reference: \ https://doc.rust-lang.org/reference/types.html#trait-objects"; /// Information about the expected type at the top level of type checking a pattern. /// /// **NOTE:** This is only for use by diagnostics. Do NOT use for type checking logic! #[derive(Copy, Clone)] struct TopInfo<'tcx> { /// The `expected` type at the top level of type checking a pattern. expected: Ty<'tcx>, /// Was the origin of the `span` from a scrutinee expression? /// /// Otherwise there is no scrutinee and it could be e.g. from the type of a formal parameter. origin_expr: bool, /// The span giving rise to the `expected` type, if one could be provided. /// /// If `origin_expr` is `true`, then this is the span of the scrutinee as in: /// /// - `match scrutinee { ... }` /// - `let _ = scrutinee;` /// /// This is used to point to add context in type errors. /// In the following example, `span` corresponds to the `a + b` expression: /// /// ```text /// error[E0308]: mismatched types /// --> src/main.rs:L:C /// | /// L | let temp: usize = match a + b { /// | ----- this expression has type `usize` /// L | Ok(num) => num, /// | ^^^^^^^ expected `usize`, found enum `std::result::Result` /// | /// = note: expected type `usize` /// found type `std::result::Result<_, _>` /// ``` span: Option<Span>, /// This refers to the parent pattern. Used to provide extra diagnostic information on errors. /// ```text /// error[E0308]: mismatched types /// --> $DIR/const-in-struct-pat.rs:8:17 /// | /// L | struct f; /// | --------- unit struct defined here /// ... /// L | let Thing { f } = t; /// | ^ /// | | /// | expected struct `std::string::String`, found struct `f` /// | `f` is interpreted as a unit struct, not a new binding /// | help: bind the struct field to a different name instead: `f: other_f` /// ``` parent_pat: Option<&'tcx Pat<'tcx>>, } impl<'tcx> FnCtxt<'_, 'tcx> { fn pattern_cause(&self, ti: TopInfo<'tcx>, cause_span: Span) -> ObligationCause<'tcx> { let code = Pattern { span: ti.span, root_ty: ti.expected, origin_expr: ti.origin_expr }; self.cause(cause_span, code) } fn demand_eqtype_pat_diag( &self, cause_span: Span, expected: Ty<'tcx>, actual: Ty<'tcx>, ti: TopInfo<'tcx>, ) -> Option<DiagnosticBuilder<'tcx>> { self.demand_eqtype_with_origin(&self.pattern_cause(ti, cause_span), expected, actual) } fn demand_eqtype_pat( &self, cause_span: Span, expected: Ty<'tcx>, actual: Ty<'tcx>, ti: TopInfo<'tcx>, ) { self.demand_eqtype_pat_diag(cause_span, expected, actual, ti).map(|mut err| err.emit()); } } const INITIAL_BM: BindingMode = BindingMode::BindByValue(hir::Mutability::Not); /// Mode for adjusting the expected type and binding mode. enum AdjustMode { /// Peel off all immediate reference types. Peel, /// Reset binding mode to the initial mode. Reset, /// Pass on the input binding mode and expected type. Pass, } impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Type check the given top level pattern against the `expected` type. /// /// If a `Some(span)` is provided and `origin_expr` holds, /// then the `span` represents the scrutinee's span. /// The scrutinee is found in e.g. `match scrutinee { ... }` and `let pat = scrutinee;`. /// /// Otherwise, `Some(span)` represents the span of a type expression /// which originated the `expected` type. pub fn check_pat_top( &self, pat: &'tcx Pat<'tcx>, expected: Ty<'tcx>, span: Option<Span>, origin_expr: bool, ) { let info = TopInfo { expected, origin_expr, span, parent_pat: None }; self.check_pat(pat, expected, INITIAL_BM, info); } /// Type check the given `pat` against the `expected` type /// with the provided `def_bm` (default binding mode). /// /// Outside of this module, `check_pat_top` should always be used. /// Conversely, inside this module, `check_pat_top` should never be used. fn check_pat( &self, pat: &'tcx Pat<'tcx>, expected: Ty<'tcx>, def_bm: BindingMode, ti: TopInfo<'tcx>, ) { debug!("check_pat(pat={:?},expected={:?},def_bm={:?})", pat, expected, def_bm); let path_res = match &pat.kind { PatKind::Path(qpath) => Some(self.resolve_ty_and_res_ufcs(qpath, pat.hir_id, pat.span)), _ => None, }; let adjust_mode = self.calc_adjust_mode(pat, path_res.map(|(res, ..)| res)); let (expected, def_bm) = self.calc_default_binding_mode(pat, expected, def_bm, adjust_mode); let ty = match pat.kind { PatKind::Wild => expected, PatKind::Lit(lt) => self.check_pat_lit(pat.span, lt, expected, ti), PatKind::Range(lhs, rhs, _) => self.check_pat_range(pat.span, lhs, rhs, expected, ti), PatKind::Binding(ba, var_id, _, sub) => { self.check_pat_ident(pat, ba, var_id, sub, expected, def_bm, ti) } PatKind::TupleStruct(ref qpath, subpats, ddpos) => { self.check_pat_tuple_struct(pat, qpath, subpats, ddpos, expected, def_bm, ti) } PatKind::Path(_) => self.check_pat_path(pat, path_res.unwrap(), expected, ti), PatKind::Struct(ref qpath, fields, etc) => { self.check_pat_struct(pat, qpath, fields, etc, expected, def_bm, ti) } PatKind::Or(pats) => { let parent_pat = Some(pat); for pat in pats { self.check_pat(pat, expected, def_bm, TopInfo { parent_pat, ..ti }); } expected } PatKind::Tuple(elements, ddpos) => { self.check_pat_tuple(pat.span, elements, ddpos, expected, def_bm, ti) } PatKind::Box(inner) => self.check_pat_box(pat.span, inner, expected, def_bm, ti), PatKind::Ref(inner, mutbl) => { self.check_pat_ref(pat, inner, mutbl, expected, def_bm, ti) } PatKind::Slice(before, slice, after) => { self.check_pat_slice(pat.span, before, slice, after, expected, def_bm, ti) } }; self.write_ty(pat.hir_id, ty); // (note_1): In most of the cases where (note_1) is referenced // (literals and constants being the exception), we relate types // using strict equality, even though subtyping would be sufficient. // There are a few reasons for this, some of which are fairly subtle // and which cost me (nmatsakis) an hour or two debugging to remember, // so I thought I'd write them down this time. // // 1. There is no loss of expressiveness here, though it does // cause some inconvenience. What we are saying is that the type // of `x` becomes *exactly* what is expected. This can cause unnecessary // errors in some cases, such as this one: // // ``` // fn foo<'x>(x: &'x int) { // let a = 1; // let mut z = x; // z = &a; // } // ``` // // The reason we might get an error is that `z` might be // assigned a type like `&'x int`, and then we would have // a problem when we try to assign `&a` to `z`, because // the lifetime of `&a` (i.e., the enclosing block) is // shorter than `'x`. // // HOWEVER, this code works fine. The reason is that the // expected type here is whatever type the user wrote, not // the initializer's type. In this case the user wrote // nothing, so we are going to create a type variable `Z`. // Then we will assign the type of the initializer (`&'x // int`) as a subtype of `Z`: `&'x int <: Z`. And hence we // will instantiate `Z` as a type `&'0 int` where `'0` is // a fresh region variable, with the constraint that `'x : // '0`. So basically we're all set. // // Note that there are two tests to check that this remains true // (`regions-reassign-{match,let}-bound-pointer.rs`). // // 2. Things go horribly wrong if we use subtype. The reason for // THIS is a fairly subtle case involving bound regions. See the // `givens` field in `region_constraints`, as well as the test // `regions-relate-bound-regions-on-closures-to-inference-variables.rs`, // for details. Short version is that we must sometimes detect // relationships between specific region variables and regions // bound in a closure signature, and that detection gets thrown // off when we substitute fresh region variables here to enable // subtyping. } /// Compute the new expected type and default binding mode from the old ones /// as well as the pattern form we are currently checking. fn calc_default_binding_mode( &self, pat: &'tcx Pat<'tcx>, expected: Ty<'tcx>, def_bm: BindingMode, adjust_mode: AdjustMode, ) -> (Ty<'tcx>, BindingMode) { match adjust_mode { AdjustMode::Pass => (expected, def_bm), AdjustMode::Reset => (expected, INITIAL_BM), AdjustMode::Peel => self.peel_off_references(pat, expected, def_bm), } } /// How should the binding mode and expected type be adjusted? /// /// When the pattern is a path pattern, `opt_path_res` must be `Some(res)`. fn calc_adjust_mode(&self, pat: &'tcx Pat<'tcx>, opt_path_res: Option<Res>) -> AdjustMode { match &pat.kind { // Type checking these product-like types successfully always require // that the expected type be of those types and not reference types. PatKind::Struct(..) | PatKind::TupleStruct(..) | PatKind::Tuple(..) | PatKind::Box(_) | PatKind::Range(..) | PatKind::Slice(..) => AdjustMode::Peel, // String and byte-string literals result in types `&str` and `&[u8]` respectively. // All other literals result in non-reference types. // As a result, we allow `if let 0 = &&0 {}` but not `if let "foo" = &&"foo {}`. PatKind::Lit(lt) => match self.check_expr(lt).kind { ty::Ref(..) => AdjustMode::Pass, _ => AdjustMode::Peel, }, PatKind::Path(_) => match opt_path_res.unwrap() { // These constants can be of a reference type, e.g. `const X: &u8 = &0;`. // Peeling the reference types too early will cause type checking failures. // Although it would be possible to *also* peel the types of the constants too. Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) => AdjustMode::Pass, // In the `ValueNS`, we have `SelfCtor(..) | Ctor(_, Const), _)` remaining which // could successfully compile. The former being `Self` requires a unit struct. // In either case, and unlike constants, the pattern itself cannot be // a reference type wherefore peeling doesn't give up any expressivity. _ => AdjustMode::Peel, }, // When encountering a `& mut? pat` pattern, reset to "by value". // This is so that `x` and `y` here are by value, as they appear to be: // // ``` // match &(&22, &44) { // (&x, &y) => ... // } // ``` // // See issue #46688. PatKind::Ref(..) => AdjustMode::Reset, // A `_` pattern works with any expected type, so there's no need to do anything. PatKind::Wild // Bindings also work with whatever the expected type is, // and moreover if we peel references off, that will give us the wrong binding type. // Also, we can have a subpattern `binding @ pat`. // Each side of the `@` should be treated independently (like with OR-patterns). | PatKind::Binding(..) // An OR-pattern just propagates to each individual alternative. // This is maximally flexible, allowing e.g., `Some(mut x) | &Some(mut x)`. // In that example, `Some(mut x)` results in `Peel` whereas `&Some(mut x)` in `Reset`. | PatKind::Or(_) => AdjustMode::Pass, } } /// Peel off as many immediately nested `& mut?` from the expected type as possible /// and return the new expected type and binding default binding mode. /// The adjustments vector, if non-empty is stored in a table. fn peel_off_references( &self, pat: &'tcx Pat<'tcx>, expected: Ty<'tcx>, mut def_bm: BindingMode, ) -> (Ty<'tcx>, BindingMode) { let mut expected = self.resolve_vars_with_obligations(&expected); // Peel off as many `&` or `&mut` from the scrutinee type as possible. For example, // for `match &&&mut Some(5)` the loop runs three times, aborting when it reaches // the `Some(5)` which is not of type Ref. // // For each ampersand peeled off, update the binding mode and push the original // type into the adjustments vector. // // See the examples in `ui/match-defbm*.rs`. let mut pat_adjustments = vec![]; while let ty::Ref(_, inner_ty, inner_mutability) = expected.kind { debug!("inspecting {:?}", expected); debug!("current discriminant is Ref, inserting implicit deref"); // Preserve the reference type. We'll need it later during HAIR lowering. pat_adjustments.push(expected); expected = inner_ty; def_bm = ty::BindByReference(match def_bm { // If default binding mode is by value, make it `ref` or `ref mut` // (depending on whether we observe `&` or `&mut`). ty::BindByValue(_) | // When `ref mut`, stay a `ref mut` (on `&mut`) or downgrade to `ref` (on `&`). ty::BindByReference(hir::Mutability::Mut) => inner_mutability, // Once a `ref`, always a `ref`. // This is because a `& &mut` cannot mutate the underlying value. ty::BindByReference(m @ hir::Mutability::Not) => m, }); } if !pat_adjustments.is_empty() { debug!("default binding mode is now {:?}", def_bm); self.inh.tables.borrow_mut().pat_adjustments_mut().insert(pat.hir_id, pat_adjustments); } (expected, def_bm) } fn check_pat_lit( &self, span: Span, lt: &hir::Expr<'tcx>, expected: Ty<'tcx>, ti: TopInfo<'tcx>, ) -> Ty<'tcx> { // We've already computed the type above (when checking for a non-ref pat), // so avoid computing it again. let ty = self.node_ty(lt.hir_id); // Byte string patterns behave the same way as array patterns // They can denote both statically and dynamically-sized byte arrays. let mut pat_ty = ty; if let hir::ExprKind::Lit(Spanned { node: ast::LitKind::ByteStr(_), .. }) = lt.kind { let expected = self.structurally_resolved_type(span, expected); if let ty::Ref(_, ty::TyS { kind: ty::Slice(_), .. }, _) = expected.kind { let tcx = self.tcx; pat_ty = tcx.mk_imm_ref(tcx.lifetimes.re_static, tcx.mk_slice(tcx.types.u8)); } } // Somewhat surprising: in this case, the subtyping relation goes the // opposite way as the other cases. Actually what we really want is not // a subtyping relation at all but rather that there exists a LUB // (so that they can be compared). However, in practice, constants are // always scalars or strings. For scalars subtyping is irrelevant, // and for strings `ty` is type is `&'static str`, so if we say that // // &'static str <: expected // // then that's equivalent to there existing a LUB. let cause = self.pattern_cause(ti, span); if let Some(mut err) = self.demand_suptype_with_origin(&cause, expected, pat_ty) { err.emit_unless( ti.span .filter(|&s| { // In the case of `if`- and `while`-expressions we've already checked // that `scrutinee: bool`. We know that the pattern is `true`, // so an error here would be a duplicate and from the wrong POV. s.is_desugaring(DesugaringKind::CondTemporary) }) .is_some(), ); } pat_ty } fn check_pat_range( &self, span: Span, lhs: Option<&'tcx hir::Expr<'tcx>>, rhs: Option<&'tcx hir::Expr<'tcx>>, expected: Ty<'tcx>, ti: TopInfo<'tcx>, ) -> Ty<'tcx> { let calc_side = |opt_expr: Option<&'tcx hir::Expr<'tcx>>| match opt_expr { None => (None, None), Some(expr) => { let ty = self.check_expr(expr); // Check that the end-point is of numeric or char type. let fail = !(ty.is_numeric() || ty.is_char() || ty.references_error()); (Some(ty), Some((fail, ty, expr.span))) } }; let (lhs_ty, lhs) = calc_side(lhs); let (rhs_ty, rhs) = calc_side(rhs); if let (Some((true, ..)), _) | (_, Some((true, ..))) = (lhs, rhs) { // There exists a side that didn't meet our criteria that the end-point // be of a numeric or char type, as checked in `calc_side` above. self.emit_err_pat_range(span, lhs, rhs); return self.tcx.types.err; } // Now that we know the types can be unified we find the unified type // and use it to type the entire expression. let common_type = self.resolve_vars_if_possible(&lhs_ty.or(rhs_ty).unwrap_or(expected)); // Subtyping doesn't matter here, as the value is some kind of scalar. let demand_eqtype = |x, y| { if let Some((_, x_ty, x_span)) = x { self.demand_eqtype_pat_diag(x_span, expected, x_ty, ti).map(|mut err| { if let Some((_, y_ty, y_span)) = y { self.endpoint_has_type(&mut err, y_span, y_ty); } err.emit(); }); } }; demand_eqtype(lhs, rhs); demand_eqtype(rhs, lhs); common_type } fn endpoint_has_type(&self, err: &mut DiagnosticBuilder<'_>, span: Span, ty: Ty<'_>) { if !ty.references_error() { err.span_label(span, &format!("this is of type `{}`", ty)); } } fn emit_err_pat_range( &self, span: Span, lhs: Option<(bool, Ty<'tcx>, Span)>, rhs: Option<(bool, Ty<'tcx>, Span)>, ) { let span = match (lhs, rhs) { (Some((true, ..)), Some((true, ..))) => span, (Some((true, _, sp)), _) => sp, (_, Some((true, _, sp))) => sp, _ => span_bug!(span, "emit_err_pat_range: no side failed or exists but still error?"), }; let mut err = struct_span_err!( self.tcx.sess, span, E0029, "only char and numeric types are allowed in range patterns" ); let msg = |ty| format!("this is of type `{}` but it should be `char` or numeric", ty); let mut one_side_err = |first_span, first_ty, second: Option<(bool, Ty<'tcx>, Span)>| { err.span_label(first_span, &msg(first_ty)); if let Some((_, ty, sp)) = second { self.endpoint_has_type(&mut err, sp, ty); } }; match (lhs, rhs) { (Some((true, lhs_ty, lhs_sp)), Some((true, rhs_ty, rhs_sp))) => { err.span_label(lhs_sp, &msg(lhs_ty)); err.span_label(rhs_sp, &msg(rhs_ty)); } (Some((true, lhs_ty, lhs_sp)), rhs) => one_side_err(lhs_sp, lhs_ty, rhs), (lhs, Some((true, rhs_ty, rhs_sp))) => one_side_err(rhs_sp, rhs_ty, lhs), _ => span_bug!(span, "Impossible, verified above."), } if self.tcx.sess.teach(&err.get_code().unwrap()) { err.note( "In a match expression, only numbers and characters can be matched \ against a range. This is because the compiler checks that the range \ is non-empty at compile-time, and is unable to evaluate arbitrary \ comparison functions. If you want to capture values of an orderable \ type between two end-points, you can use a guard.", ); } err.emit(); } fn check_pat_ident( &self, pat: &'tcx Pat<'tcx>, ba: hir::BindingAnnotation, var_id: HirId, sub: Option<&'tcx Pat<'tcx>>, expected: Ty<'tcx>, def_bm: BindingMode, ti: TopInfo<'tcx>, ) -> Ty<'tcx> { // Determine the binding mode... let bm = match ba { hir::BindingAnnotation::Unannotated => def_bm, _ => BindingMode::convert(ba), }; // ...and store it in a side table: self.inh.tables.borrow_mut().pat_binding_modes_mut().insert(pat.hir_id, bm); debug!("check_pat_ident: pat.hir_id={:?} bm={:?}", pat.hir_id, bm); let local_ty = self.local_ty(pat.span, pat.hir_id).decl_ty; let eq_ty = match bm { ty::BindByReference(mutbl) => { // If the binding is like `ref x | ref mut x`, // then `x` is assigned a value of type `&M T` where M is the // mutability and T is the expected type. // // `x` is assigned a value of type `&M T`, hence `&M T <: typeof(x)` // is required. However, we use equality, which is stronger. // See (note_1) for an explanation. self.new_ref_ty(pat.span, mutbl, expected) } // Otherwise, the type of x is the expected type `T`. ty::BindByValue(_) => { // As above, `T <: typeof(x)` is required, but we use equality, see (note_1). expected } }; self.demand_eqtype_pat(pat.span, eq_ty, local_ty, ti); // If there are multiple arms, make sure they all agree on // what the type of the binding `x` ought to be. if var_id != pat.hir_id { self.check_binding_alt_eq_ty(pat.span, var_id, local_ty, ti); } if let Some(p) = sub { self.check_pat(&p, expected, def_bm, TopInfo { parent_pat: Some(&pat), ..ti }); } local_ty } fn check_binding_alt_eq_ty(&self, span: Span, var_id: HirId, ty: Ty<'tcx>, ti: TopInfo<'tcx>) { let var_ty = self.local_ty(span, var_id).decl_ty; if let Some(mut err) = self.demand_eqtype_pat_diag(span, var_ty, ty, ti) { let hir = self.tcx.hir(); let var_ty = self.resolve_vars_with_obligations(var_ty); let msg = format!("first introduced with type `{}` here", var_ty); err.span_label(hir.span(var_id), msg); let in_match = hir.parent_iter(var_id).any(|(_, n)| { matches!( n, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Match(.., hir::MatchSource::Normal), .. }) ) }); let pre = if in_match { "in the same arm, " } else { "" }; err.note(&format!("{}a binding must have the same type in all alternatives", pre)); err.emit(); } } fn borrow_pat_suggestion( &self, err: &mut DiagnosticBuilder<'_>, pat: &Pat<'_>, inner: &Pat<'_>, expected: Ty<'tcx>, ) { let tcx = self.tcx; if let PatKind::Binding(..) = inner.kind { let binding_parent_id = tcx.hir().get_parent_node(pat.hir_id); let binding_parent = tcx.hir().get(binding_parent_id); debug!("inner {:?} pat {:?} parent {:?}", inner, pat, binding_parent); match binding_parent { hir::Node::Param(hir::Param { span, .. }) => { if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(inner.span) { err.span_suggestion( *span, &format!("did you mean `{}`", snippet), format!(" &{}", expected), Applicability::MachineApplicable, ); } } hir::Node::Arm(_) | hir::Node::Pat(_) => { // rely on match ergonomics or it might be nested `&&pat` if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(inner.span) { err.span_suggestion( pat.span, "you can probably remove the explicit borrow", snippet, Applicability::MaybeIncorrect, ); } } _ => {} // don't provide suggestions in other cases #55175 } } } pub fn check_dereferenceable(&self, span: Span, expected: Ty<'tcx>, inner: &Pat<'_>) -> bool { if let PatKind::Binding(..) = inner.kind { if let Some(mt) = self.shallow_resolve(expected).builtin_deref(true) { if let ty::Dynamic(..) = mt.ty.kind { // This is "x = SomeTrait" being reduced from // "let &x = &SomeTrait" or "let box x = Box<SomeTrait>", an error. let type_str = self.ty_to_string(expected); let mut err = struct_span_err!( self.tcx.sess, span, E0033, "type `{}` cannot be dereferenced", type_str ); err.span_label(span, format!("type `{}` cannot be dereferenced", type_str)); if self.tcx.sess.teach(&err.get_code().unwrap()) { err.note(CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ); } err.emit(); return false; } } } true } fn check_pat_struct( &self, pat: &'tcx Pat<'tcx>, qpath: &hir::QPath<'_>, fields: &'tcx [hir::FieldPat<'tcx>], etc: bool, expected: Ty<'tcx>, def_bm: BindingMode, ti: TopInfo<'tcx>, ) -> Ty<'tcx> { // Resolve the path and check the definition for errors. let (variant, pat_ty) = if let Some(variant_ty) = self.check_struct_path(qpath, pat.hir_id) { variant_ty } else { for field in fields { let ti = TopInfo { parent_pat: Some(&pat), ..ti }; self.check_pat(&field.pat, self.tcx.types.err, def_bm, ti); } return self.tcx.types.err; }; // Type-check the path. self.demand_eqtype_pat(pat.span, expected, pat_ty, ti); // Type-check subpatterns. if self.check_struct_pat_fields(pat_ty, &pat, variant, fields, etc, def_bm, ti) { pat_ty } else { self.tcx.types.err } } fn check_pat_path( &self, pat: &Pat<'_>, path_resolution: (Res, Option<Ty<'tcx>>, &'b [hir::PathSegment<'b>]), expected: Ty<'tcx>, ti: TopInfo<'tcx>, ) -> Ty<'tcx> { let tcx = self.tcx; // We have already resolved the path. let (res, opt_ty, segments) = path_resolution; match res { Res::Err => { self.set_tainted_by_errors(); return tcx.types.err; } Res::Def(DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fictive | CtorKind::Fn), _) => { report_unexpected_variant_res(tcx, res, pat.span); return tcx.types.err; } Res::SelfCtor(..) | Res::Def( DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst | DefKind::ConstParam, _, ) => {} // OK _ => bug!("unexpected pattern resolution: {:?}", res), } // Type-check the path. let (pat_ty, pat_res) = self.instantiate_value_path(segments, opt_ty, res, pat.span, pat.hir_id); if let Some(err) = self.demand_suptype_with_origin(&self.pattern_cause(ti, pat.span), expected, pat_ty) { self.emit_bad_pat_path(err, pat.span, res, pat_res, segments, ti.parent_pat); } pat_ty } fn emit_bad_pat_path( &self, mut e: DiagnosticBuilder<'_>, pat_span: Span, res: Res, pat_res: Res, segments: &'b [hir::PathSegment<'b>], parent_pat: Option<&Pat<'_>>, ) { if let Some(span) = self.tcx.hir().res_span(pat_res) { e.span_label(span, &format!("{} defined here", res.descr())); if let [hir::PathSegment { ident, .. }] = &*segments { e.span_label( pat_span, &format!( "`{}` is interpreted as {} {}, not a new binding", ident, res.article(), res.descr(), ), ); match parent_pat { Some(Pat { kind: hir::PatKind::Struct(..), .. }) => { e.span_suggestion_verbose( ident.span.shrink_to_hi(), "bind the struct field to a different name instead", format!(": other_{}", ident.as_str().to_lowercase()), Applicability::HasPlaceholders, ); } _ => { let msg = "introduce a new binding instead"; let sugg = format!("other_{}", ident.as_str().to_lowercase()); e.span_suggestion(ident.span, msg, sugg, Applicability::HasPlaceholders); } }; } } e.emit(); } fn check_pat_tuple_struct( &self, pat: &'tcx Pat<'tcx>, qpath: &hir::QPath<'_>, subpats: &'tcx [&'tcx Pat<'tcx>], ddpos: Option<usize>, expected: Ty<'tcx>, def_bm: BindingMode, ti: TopInfo<'tcx>, ) -> Ty<'tcx> { let tcx = self.tcx; let on_error = || { let parent_pat = Some(pat); for pat in subpats { self.check_pat(&pat, tcx.types.err, def_bm, TopInfo { parent_pat, ..ti }); } }; let report_unexpected_res = |res: Res| { let sm = tcx.sess.source_map(); let path_str = sm .span_to_snippet(sm.span_until_char(pat.span, '(')) .map_or(String::new(), |s| format!(" `{}`", s.trim_end())); let msg = format!( "expected tuple struct or tuple variant, found {}{}", res.descr(), path_str ); let mut err = struct_span_err!(tcx.sess, pat.span, E0164, "{}", msg); match res { Res::Def(DefKind::Fn | DefKind::AssocFn, _) => { err.span_label(pat.span, "`fn` calls are not allowed in patterns"); err.help( "for more information, visit \ https://doc.rust-lang.org/book/ch18-00-patterns.html", ); } _ => { err.span_label(pat.span, "not a tuple variant or struct"); } } err.emit(); on_error(); }; // Resolve the path and check the definition for errors. let (res, opt_ty, segments) = self.resolve_ty_and_res_ufcs(qpath, pat.hir_id, pat.span); if res == Res::Err { self.set_tainted_by_errors(); on_error(); return self.tcx.types.err; } // Type-check the path. let (pat_ty, res) = self.instantiate_value_path(segments, opt_ty, res, pat.span, pat.hir_id); if !pat_ty.is_fn() { report_unexpected_res(res); return tcx.types.err; } let variant = match res { Res::Err => { self.set_tainted_by_errors(); on_error(); return tcx.types.err; } Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) => { report_unexpected_res(res); return tcx.types.err; } Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) => tcx.expect_variant_res(res), _ => bug!("unexpected pattern resolution: {:?}", res), }; // Replace constructor type with constructed type for tuple struct patterns. let pat_ty = pat_ty.fn_sig(tcx).output(); let pat_ty = pat_ty.no_bound_vars().expect("expected fn type"); // Type-check the tuple struct pattern against the expected type. let diag = self.demand_eqtype_pat_diag(pat.span, expected, pat_ty, ti); let had_err = diag.is_some(); diag.map(|mut err| err.emit()); // Type-check subpatterns. if subpats.len() == variant.fields.len() || subpats.len() < variant.fields.len() && ddpos.is_some() { let substs = match pat_ty.kind { ty::Adt(_, substs) => substs, _ => bug!("unexpected pattern type {:?}", pat_ty), }; for (i, subpat) in subpats.iter().enumerate_and_adjust(variant.fields.len(), ddpos) { let field_ty = self.field_ty(subpat.span, &variant.fields[i], substs); self.check_pat(&subpat, field_ty, def_bm, TopInfo { parent_pat: Some(&pat), ..ti }); self.tcx.check_stability(variant.fields[i].did, Some(pat.hir_id), subpat.span); } } else { // Pattern has wrong number of fields. self.e0023(pat.span, res, qpath, subpats, &variant.fields, expected, had_err); on_error(); return tcx.types.err; } pat_ty } fn e0023( &self, pat_span: Span, res: Res, qpath: &hir::QPath<'_>, subpats: &'tcx [&'tcx Pat<'tcx>], fields: &'tcx [ty::FieldDef], expected: Ty<'tcx>, had_err: bool, ) { let subpats_ending = pluralize!(subpats.len()); let fields_ending = pluralize!(fields.len()); let res_span = self.tcx.def_span(res.def_id()); let mut err = struct_span_err!( self.tcx.sess, pat_span, E0023, "this pattern has {} field{}, but the corresponding {} has {} field{}", subpats.len(), subpats_ending, res.descr(), fields.len(), fields_ending, ); err.span_label( pat_span, format!("expected {} field{}, found {}", fields.len(), fields_ending, subpats.len(),), ) .span_label(res_span, format!("{} defined here", res.descr())); // Identify the case `Some(x, y)` where the expected type is e.g. `Option<(T, U)>`. // More generally, the expected type wants a tuple variant with one field of an // N-arity-tuple, e.g., `V_i((p_0, .., p_N))`. Meanwhile, the user supplied a pattern // with the subpatterns directly in the tuple variant pattern, e.g., `V_i(p_0, .., p_N)`. let missing_parenthesis = match (&expected.kind, fields, had_err) { // #67037: only do this if we could successfully type-check the expected type against // the tuple struct pattern. Otherwise the substs could get out of range on e.g., // `let P() = U;` where `P != U` with `struct P<T>(T);`. (ty::Adt(_, substs), [field], false) => { let field_ty = self.field_ty(pat_span, field, substs); match field_ty.kind { ty::Tuple(_) => field_ty.tuple_fields().count() == subpats.len(), _ => false, } } _ => false, }; if missing_parenthesis { let (left, right) = match subpats { // This is the zero case; we aim to get the "hi" part of the `QPath`'s // span as the "lo" and then the "hi" part of the pattern's span as the "hi". // This looks like: // // help: missing parenthesis // | // L | let A(()) = A(()); // | ^ ^ [] => { let qpath_span = match qpath { hir::QPath::Resolved(_, path) => path.span, hir::QPath::TypeRelative(_, ps) => ps.ident.span, }; (qpath_span.shrink_to_hi(), pat_span) } // Easy case. Just take the "lo" of the first sub-pattern and the "hi" of the // last sub-pattern. In the case of `A(x)` the first and last may coincide. // This looks like: // // help: missing parenthesis // | // L | let A((x, y)) = A((1, 2)); // | ^ ^ [first, ..] => (first.span.shrink_to_lo(), subpats.last().unwrap().span), }; err.multipart_suggestion( "missing parenthesis", vec![(left, "(".to_string()), (right.shrink_to_hi(), ")".to_string())], Applicability::MachineApplicable, ); } err.emit(); } fn check_pat_tuple( &self, span: Span, elements: &'tcx [&'tcx Pat<'tcx>], ddpos: Option<usize>, expected: Ty<'tcx>, def_bm: BindingMode, ti: TopInfo<'tcx>, ) -> Ty<'tcx> { let tcx = self.tcx; let mut expected_len = elements.len(); if ddpos.is_some() { // Require known type only when `..` is present. if let ty::Tuple(ref tys) = self.structurally_resolved_type(span, expected).kind { expected_len = tys.len(); } } let max_len = cmp::max(expected_len, elements.len()); let element_tys_iter = (0..max_len).map(|_| { GenericArg::from(self.next_ty_var( // FIXME: `MiscVariable` for now -- obtaining the span and name information // from all tuple elements isn't trivial. TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span }, )) }); let element_tys = tcx.mk_substs(element_tys_iter); let pat_ty = tcx.mk_ty(ty::Tuple(element_tys)); if let Some(mut err) = self.demand_eqtype_pat_diag(span, expected, pat_ty, ti) { err.emit(); // Walk subpatterns with an expected type of `err` in this case to silence // further errors being emitted when using the bindings. #50333 let element_tys_iter = (0..max_len).map(|_| tcx.types.err); for (_, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) { self.check_pat(elem, &tcx.types.err, def_bm, ti); } tcx.mk_tup(element_tys_iter) } else { for (i, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) { self.check_pat(elem, &element_tys[i].expect_ty(), def_bm, ti); } pat_ty } } fn check_struct_pat_fields( &self, adt_ty: Ty<'tcx>, pat: &'tcx Pat<'tcx>, variant: &'tcx ty::VariantDef, fields: &'tcx [hir::FieldPat<'tcx>], etc: bool, def_bm: BindingMode, ti: TopInfo<'tcx>, ) -> bool { let tcx = self.tcx; let (substs, adt) = match adt_ty.kind { ty::Adt(adt, substs) => (substs, adt), _ => span_bug!(pat.span, "struct pattern is not an ADT"), }; // Index the struct fields' types. let field_map = variant .fields .iter() .enumerate() .map(|(i, field)| (field.ident.normalize_to_macros_2_0(), (i, field))) .collect::<FxHashMap<_, _>>(); // Keep track of which fields have already appeared in the pattern. let mut used_fields = FxHashMap::default(); let mut no_field_errors = true; let mut inexistent_fields = vec![]; // Typecheck each field. for field in fields { let span = field.span; let ident = tcx.adjust_ident(field.ident, variant.def_id); let field_ty = match used_fields.entry(ident) { Occupied(occupied) => { self.error_field_already_bound(span, field.ident, *occupied.get()); no_field_errors = false; tcx.types.err } Vacant(vacant) => { vacant.insert(span); field_map .get(&ident) .map(|(i, f)| { self.write_field_index(field.hir_id, *i); self.tcx.check_stability(f.did, Some(pat.hir_id), span); self.field_ty(span, f, substs) }) .unwrap_or_else(|| { inexistent_fields.push(field.ident); no_field_errors = false; tcx.types.err }) } }; self.check_pat(&field.pat, field_ty, def_bm, TopInfo { parent_pat: Some(&pat), ..ti }); } let mut unmentioned_fields = variant .fields .iter() .map(|field| field.ident.normalize_to_macros_2_0()) .filter(|ident| !used_fields.contains_key(&ident)) .collect::<Vec<_>>(); if !inexistent_fields.is_empty() && !variant.recovered { self.error_inexistent_fields( adt.variant_descr(), &inexistent_fields, &mut unmentioned_fields, variant, ); } // Require `..` if struct has non_exhaustive attribute. if variant.is_field_list_non_exhaustive() && !adt.did.is_local() && !etc { self.error_foreign_non_exhaustive_spat(pat, adt.variant_descr(), fields.is_empty()); } // Report an error if incorrect number of the fields were specified. if adt.is_union() { if fields.len() != 1 { tcx.sess .struct_span_err(pat.span, "union patterns should have exactly one field") .emit(); } if etc { tcx.sess.struct_span_err(pat.span, "`..` cannot be used in union patterns").emit(); } } else if !etc && !unmentioned_fields.is_empty() { self.error_unmentioned_fields(pat.span, &unmentioned_fields, variant); } no_field_errors } fn error_foreign_non_exhaustive_spat(&self, pat: &Pat<'_>, descr: &str, no_fields: bool) { let sess = self.tcx.sess; let sm = sess.source_map(); let sp_brace = sm.end_point(pat.span); let sp_comma = sm.end_point(pat.span.with_hi(sp_brace.hi())); let sugg = if no_fields || sp_brace != sp_comma { ".. }" } else { ", .. }" }; let mut err = struct_span_err!( sess, pat.span, E0638, "`..` required with {} marked as non-exhaustive", descr ); err.span_suggestion_verbose( sp_comma, "add `..` at the end of the field list to ignore all other fields", sugg.to_string(), Applicability::MachineApplicable, ); err.emit(); } fn error_field_already_bound(&self, span: Span, ident: ast::Ident, other_field: Span) { struct_span_err!( self.tcx.sess, span, E0025, "field `{}` bound multiple times in the pattern", ident ) .span_label(span, format!("multiple uses of `{}` in pattern", ident)) .span_label(other_field, format!("first use of `{}`", ident)) .emit(); } fn error_inexistent_fields( &self, kind_name: &str, inexistent_fields: &[ast::Ident], unmentioned_fields: &mut Vec<ast::Ident>, variant: &ty::VariantDef, ) { let tcx = self.tcx; let (field_names, t, plural) = if inexistent_fields.len() == 1 { (format!("a field named `{}`", inexistent_fields[0]), "this", "") } else { ( format!( "fields named {}", inexistent_fields .iter() .map(|ident| format!("`{}`", ident)) .collect::<Vec<String>>() .join(", ") ), "these", "s", ) }; let spans = inexistent_fields.iter().map(|ident| ident.span).collect::<Vec<_>>(); let mut err = struct_span_err!( tcx.sess, spans, E0026, "{} `{}` does not have {}", kind_name, tcx.def_path_str(variant.def_id), field_names ); if let Some(ident) = inexistent_fields.last() { err.span_label( ident.span, format!( "{} `{}` does not have {} field{}", kind_name, tcx.def_path_str(variant.def_id), t, plural ), ); if plural == "" { let input = unmentioned_fields.iter().map(|field| &field.name); let suggested_name = find_best_match_for_name(input, &ident.as_str(), None); if let Some(suggested_name) = suggested_name { err.span_suggestion( ident.span, "a field with a similar name exists", suggested_name.to_string(), Applicability::MaybeIncorrect, ); // we don't want to throw `E0027` in case we have thrown `E0026` for them unmentioned_fields.retain(|&x| x.name != suggested_name); } } } if tcx.sess.teach(&err.get_code().unwrap()) { err.note( "This error indicates that a struct pattern attempted to \ extract a non-existent field from a struct. Struct fields \ are identified by the name used before the colon : so struct \ patterns should resemble the declaration of the struct type \ being matched.\n\n\ If you are using shorthand field patterns but want to refer \ to the struct field by a different name, you should rename \ it explicitly.", ); } err.emit(); } fn error_unmentioned_fields( &self, span: Span, unmentioned_fields: &[ast::Ident], variant: &ty::VariantDef, ) { let field_names = if unmentioned_fields.len() == 1 { format!("field `{}`", unmentioned_fields[0]) } else { let fields = unmentioned_fields .iter() .map(|name| format!("`{}`", name)) .collect::<Vec<String>>() .join(", "); format!("fields {}", fields) }; let mut diag = struct_span_err!( self.tcx.sess, span, E0027, "pattern does not mention {}", field_names ); diag.span_label(span, format!("missing {}", field_names)); if variant.ctor_kind == CtorKind::Fn { diag.note("trying to match a tuple variant with a struct variant pattern"); } if self.tcx.sess.teach(&diag.get_code().unwrap()) { diag.note( "This error indicates that a pattern for a struct fails to specify a \ sub-pattern for every one of the struct's fields. Ensure that each field \ from the struct's definition is mentioned in the pattern, or use `..` to \ ignore unwanted fields.", ); } diag.emit(); } fn check_pat_box( &self, span: Span, inner: &'tcx Pat<'tcx>, expected: Ty<'tcx>, def_bm: BindingMode, ti: TopInfo<'tcx>, ) -> Ty<'tcx> { let tcx = self.tcx; let (box_ty, inner_ty) = if self.check_dereferenceable(span, expected, &inner) { // Here, `demand::subtype` is good enough, but I don't // think any errors can be introduced by using `demand::eqtype`. let inner_ty = self.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span: inner.span, }); let box_ty = tcx.mk_box(inner_ty); self.demand_eqtype_pat(span, expected, box_ty, ti); (box_ty, inner_ty) } else { (tcx.types.err, tcx.types.err) }; self.check_pat(&inner, inner_ty, def_bm, ti); box_ty } fn check_pat_ref( &self, pat: &'tcx Pat<'tcx>, inner: &'tcx Pat<'tcx>, mutbl: hir::Mutability, expected: Ty<'tcx>, def_bm: BindingMode, ti: TopInfo<'tcx>, ) -> Ty<'tcx> { let tcx = self.tcx; let expected = self.shallow_resolve(expected); let (rptr_ty, inner_ty) = if self.check_dereferenceable(pat.span, expected, &inner) { // `demand::subtype` would be good enough, but using `eqtype` turns // out to be equally general. See (note_1) for details. // Take region, inner-type from expected type if we can, // to avoid creating needless variables. This also helps with // the bad interactions of the given hack detailed in (note_1). debug!("check_pat_ref: expected={:?}", expected); match expected.kind { ty::Ref(_, r_ty, r_mutbl) if r_mutbl == mutbl => (expected, r_ty), _ => { let inner_ty = self.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span: inner.span, }); let rptr_ty = self.new_ref_ty(pat.span, mutbl, inner_ty); debug!("check_pat_ref: demanding {:?} = {:?}", expected, rptr_ty); let err = self.demand_eqtype_pat_diag(pat.span, expected, rptr_ty, ti); // Look for a case like `fn foo(&foo: u32)` and suggest // `fn foo(foo: &u32)` if let Some(mut err) = err { self.borrow_pat_suggestion(&mut err, &pat, &inner, &expected); err.emit(); } (rptr_ty, inner_ty) } } } else { (tcx.types.err, tcx.types.err) }; self.check_pat(&inner, inner_ty, def_bm, TopInfo { parent_pat: Some(&pat), ..ti }); rptr_ty } /// Create a reference type with a fresh region variable. fn new_ref_ty(&self, span: Span, mutbl: hir::Mutability, ty: Ty<'tcx>) -> Ty<'tcx> { let region = self.next_region_var(infer::PatternRegion(span)); let mt = ty::TypeAndMut { ty, mutbl }; self.tcx.mk_ref(region, mt) } /// Type check a slice pattern. /// /// Syntactically, these look like `[pat_0, ..., pat_n]`. /// Semantically, we are type checking a pattern with structure: /// ``` /// [before_0, ..., before_n, (slice, after_0, ... after_n)?] /// ``` /// The type of `slice`, if it is present, depends on the `expected` type. /// If `slice` is missing, then so is `after_i`. /// If `slice` is present, it can still represent 0 elements. fn check_pat_slice( &self, span: Span, before: &'tcx [&'tcx Pat<'tcx>], slice: Option<&'tcx Pat<'tcx>>, after: &'tcx [&'tcx Pat<'tcx>], expected: Ty<'tcx>, def_bm: BindingMode, ti: TopInfo<'tcx>, ) -> Ty<'tcx> { let err = self.tcx.types.err; let expected = self.structurally_resolved_type(span, expected); let (inner_ty, slice_ty, expected) = match expected.kind { // An array, so we might have something like `let [a, b, c] = [0, 1, 2];`. ty::Array(inner_ty, len) => { let min = before.len() as u64 + after.len() as u64; let slice_ty = self .check_array_pat_len(span, slice, len, min) .map_or(err, |len| self.tcx.mk_array(inner_ty, len)); (inner_ty, slice_ty, expected) } ty::Slice(inner_ty) => (inner_ty, expected, expected), // The expected type must be an array or slice, but was neither, so error. _ => { if !expected.references_error() { self.error_expected_array_or_slice(span, expected); } (err, err, err) } }; // Type check all the patterns before `slice`. for elt in before { self.check_pat(&elt, inner_ty, def_bm, ti); } // Type check the `slice`, if present, against its expected type. if let Some(slice) = slice { self.check_pat(&slice, slice_ty, def_bm, ti); } // Type check the elements after `slice`, if present. for elt in after { self.check_pat(&elt, inner_ty, def_bm, ti); } expected } /// Type check the length of an array pattern. /// /// Return the length of the variable length pattern, /// if it exists and there are no errors. fn check_array_pat_len( &self, span: Span, slice: Option<&'tcx Pat<'tcx>>, len: &ty::Const<'tcx>, min_len: u64, ) -> Option<u64> { if let Some(len) = len.try_eval_usize(self.tcx, self.param_env) { // Now we know the length... if slice.is_none() { // ...and since there is no variable-length pattern, // we require an exact match between the number of elements // in the array pattern and as provided by the matched type. if min_len != len { self.error_scrutinee_inconsistent_length(span, min_len, len); } } else if let r @ Some(_) = len.checked_sub(min_len) { // The variable-length pattern was there, // so it has an array type with the remaining elements left as its size... return r; } else { // ...however, in this case, there were no remaining elements. // That is, the slice pattern requires more than the array type offers. self.error_scrutinee_with_rest_inconsistent_length(span, min_len, len); } } else { // No idea what the length is, which happens if we have e.g., // `let [a, b] = arr` where `arr: [T; N]` where `const N: usize`. self.error_scrutinee_unfixed_length(span); } None } fn error_scrutinee_inconsistent_length(&self, span: Span, min_len: u64, size: u64) { struct_span_err!( self.tcx.sess, span, E0527, "pattern requires {} element{} but array has {}", min_len, pluralize!(min_len), size, ) .span_label(span, format!("expected {} element{}", size, pluralize!(size))) .emit(); } fn error_scrutinee_with_rest_inconsistent_length(&self, span: Span, min_len: u64, size: u64) { struct_span_err!( self.tcx.sess, span, E0528, "pattern requires at least {} element{} but array has {}", min_len, pluralize!(min_len), size, ) .span_label( span, format!("pattern cannot match array of {} element{}", size, pluralize!(size),), ) .emit(); } fn error_scrutinee_unfixed_length(&self, span: Span) { struct_span_err!( self.tcx.sess, span, E0730, "cannot pattern-match on an array without a fixed length", ) .emit(); } fn error_expected_array_or_slice(&self, span: Span, expected_ty: Ty<'tcx>) { let mut err = struct_span_err!( self.tcx.sess, span, E0529, "expected an array or slice, found `{}`", expected_ty ); if let ty::Ref(_, ty, _) = expected_ty.kind { if let ty::Array(..) | ty::Slice(..) = ty.kind { err.help("the semantics of slice patterns changed recently; see issue #62254"); } } err.span_label(span, format!("pattern cannot match with input type `{}`", expected_ty)); err.emit(); } }
40.725622
100
0.520319
1c79d676dbfecef9bd61f2c492696a16c47a35b1
6,710
use amethyst::{ core::math::Vector2, ecs::{Component, DenseVecStorage}, }; #[derive(Component)] #[storage(DenseVecStorage)] pub struct Boundary { pub left: f32, pub right: f32, pub top: f32, pub bottom: f32, } impl Boundary { pub fn new(left: f32, right: f32, top: f32, bottom: f32) -> Self { Self { left, right, top, bottom, } } } #[derive(Clone)] pub struct GenericBox { pub half_size: Vector2<f32>, pub position: Vector2<f32>, pub old_position: Vector2<f32>, } impl Default for GenericBox { fn default() -> Self { Self { half_size: Vector2::new(0., 0.), position: Vector2::new(0., 0.), old_position: Vector2::new(0., 0.), } } } impl GenericBox { pub fn new(width: f32, height: f32) -> Self { GenericBox { half_size: Vector2::new(width / 2., height / 2.), position: Vector2::new(0., 0.), old_position: Vector2::new(0., 0.), } } } pub struct CollideeDetails { pub name: String, pub position: Vector2<f32>, pub half_size: Vector2<f32>, pub correction: f32, } #[derive(Component)] #[storage(DenseVecStorage)] pub struct Collidee { pub horizontal: Option<CollideeDetails>, pub vertical: Option<CollideeDetails>, } impl Default for Collidee { fn default() -> Self { Self { horizontal: None, vertical: None, } } } impl Collidee { pub fn set_collidee_details( &mut self, name: String, collider_a: &Collider, collider_b: &Collider, velocity_a: Vector2<f32>, velocity_b: Vector2<f32>, use_hit_box: bool, ) { let (box_a, box_b) = if use_hit_box { (&collider_a.hit_box, &collider_b.hit_box) } else { (&collider_a.bounding_box, &collider_b.bounding_box) }; let mut correction = Vector2::new(0., 0.); let speed_sum = Vector2::new( (velocity_a.x - velocity_b.x).abs(), (velocity_a.y - velocity_b.y).abs(), ); let speed_ratio_a = Vector2::new(velocity_a.x / speed_sum.x, velocity_a.y / speed_sum.y); let speed_ratio_b = Vector2::new(velocity_b.x / speed_sum.x, velocity_b.y / speed_sum.y); let min_safe_distance = Vector2::new( box_a.half_size.x + box_b.half_size.x, box_a.half_size.y + box_b.half_size.y, ); let overlap = Vector2::new( min_safe_distance.x - (box_a.position.x - box_b.position.x).abs(), min_safe_distance.y - (box_a.position.y - box_b.position.y).abs(), ); // TODO: Reuse is_overlapping_with logic? let x_overlapped = (box_a.old_position.x - box_b.old_position.x).abs() < box_a.half_size.x + box_b.half_size.x; let y_overlapped = (box_a.old_position.y - box_b.old_position.y).abs() < box_a.half_size.y + box_b.half_size.y; let same_direction = velocity_a.x * velocity_b.x > 0.; let faster = speed_ratio_a.x.abs() > speed_ratio_b.x.abs(); if (y_overlapped || overlap.x.abs() <= overlap.y.abs()) && !x_overlapped { if faster || !same_direction { correction.x = overlap.x * speed_ratio_a.x; } // No correction (correction = 0.) is required if collider is slower // and both bodies are moving in the same direction self.horizontal = Some(CollideeDetails { name, position: box_b.position, half_size: box_b.half_size, correction: correction.x, }); } else if x_overlapped && y_overlapped { // Might happen when an entity is added at run time. // As per the current game design, no correction (correction = 0.) is required for this scenario // This might have to be changed in future self.horizontal = Some(CollideeDetails { name, position: box_b.position, half_size: box_b.half_size, correction: correction.x, }); } else { correction.y = overlap.y * speed_ratio_a.y; self.vertical = Some(CollideeDetails { name, position: box_b.position, half_size: box_b.half_size, correction: correction.y, }); } } } #[derive(Clone, Component)] #[storage(DenseVecStorage)] pub struct Collider { pub bounding_box: GenericBox, pub hit_box: GenericBox, pub hit_box_offset: Vector2<f32>, pub on_ground: bool, pub hit_box_offset_front: f32, pub hit_box_offset_back: f32, pub is_collidable: bool, } impl Default for Collider { fn default() -> Self { Self { bounding_box: GenericBox::default(), hit_box: GenericBox::default(), hit_box_offset: Vector2::new(0., 0.), on_ground: false, hit_box_offset_front: 0., hit_box_offset_back: 0., is_collidable: true, } } } impl Collider { pub fn new(width: f32, height: f32) -> Self { Collider { bounding_box: GenericBox::new(width, height), hit_box: GenericBox::new(width, height), hit_box_offset: Vector2::new(0., 0.), on_ground: false, hit_box_offset_front: 0., hit_box_offset_back: 0., is_collidable: true, } } pub fn set_hit_box_position(&mut self, velocity: Vector2<f32>) { let hbox_position = &mut self.hit_box.position; let bbox_position = self.bounding_box.position; hbox_position.x = if velocity.x >= 0. { bbox_position.x + self.hit_box_offset.x } else { bbox_position.x - self.hit_box_offset.x }; hbox_position.y = if velocity.y >= 0. { bbox_position.y + self.hit_box_offset.y } else { bbox_position.y - self.hit_box_offset.y }; } pub fn is_overlapping_with(&self, other: &Collider, use_hit_box: bool) -> bool { let (self_box, other_box) = if use_hit_box { (&self.hit_box, &other.hit_box) } else { (&self.bounding_box, &other.bounding_box) }; !((self_box.position.x - other_box.position.x).abs() >= (self_box.half_size.x + other_box.half_size.x).abs() || (self_box.position.y - other_box.position.y).abs() >= (self_box.half_size.y + other_box.half_size.y).abs()) } }
30.779817
108
0.563338
080b5b04b738859b1d5a3ca90c6270809b34515e
716
//! Provides validation for text inputs use std::fmt::{Debug, Display}; /// Trait for input validators. /// /// A generic implementation for `Fn(&str) -> Result<(), E>` is provided /// to facilitate development. pub trait Validator<T> { type Err: Debug + Display; /// Invoked with the value to validate. /// /// If this produces `Ok(())` then the value is used and parsed, if /// an error is returned validation fails with that error. fn validate(&mut self, input: &T) -> Result<(), Self::Err>; } impl<T, F: FnMut(&T) -> Result<(), E>, E: Debug + Display> Validator<T> for F { type Err = E; fn validate(&mut self, input: &T) -> Result<(), Self::Err> { self(input) } }
28.64
79
0.608939
1e38118aefc6737e46d57f7e52d20ce2e8433d91
13,221
#[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::U1OTGCONINV { #[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 VBUSDISR { bits: bool, } impl VBUSDISR { #[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 VBUSCHGR { bits: bool, } impl VBUSCHGR { #[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 OTGENR { bits: bool, } impl OTGENR { #[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 VBUSONR { bits: bool, } impl VBUSONR { #[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 DMPULDWNR { bits: bool, } impl DMPULDWNR { #[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 DPPULDWNR { bits: bool, } impl DPPULDWNR { #[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 DMPULUPR { bits: bool, } impl DMPULUPR { #[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 DPPULUPR { bits: bool, } impl DPPULUPR { #[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 _VBUSDISW<'a> { w: &'a mut W, } impl<'a> _VBUSDISW<'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 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _VBUSCHGW<'a> { w: &'a mut W, } impl<'a> _VBUSCHGW<'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 = 1; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _OTGENW<'a> { w: &'a mut W, } impl<'a> _OTGENW<'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 = 2; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _VBUSONW<'a> { w: &'a mut W, } impl<'a> _VBUSONW<'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 = 3; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _DMPULDWNW<'a> { w: &'a mut W, } impl<'a> _DMPULDWNW<'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 = 4; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _DPPULDWNW<'a> { w: &'a mut W, } impl<'a> _DPPULDWNW<'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 = 5; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _DMPULUPW<'a> { w: &'a mut W, } impl<'a> _DMPULUPW<'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 = 6; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _DPPULUPW<'a> { w: &'a mut W, } impl<'a> _DPPULUPW<'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 = 7; 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 = "Bit 0"] #[inline] pub fn vbusdis(&self) -> VBUSDISR { let bits = { const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }; VBUSDISR { bits } } #[doc = "Bit 1"] #[inline] pub fn vbuschg(&self) -> VBUSCHGR { let bits = { const MASK: bool = true; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) != 0 }; VBUSCHGR { bits } } #[doc = "Bit 2"] #[inline] pub fn otgen(&self) -> OTGENR { let bits = { const MASK: bool = true; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) != 0 }; OTGENR { bits } } #[doc = "Bit 3"] #[inline] pub fn vbuson(&self) -> VBUSONR { let bits = { const MASK: bool = true; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u32) != 0 }; VBUSONR { bits } } #[doc = "Bit 4"] #[inline] pub fn dmpuldwn(&self) -> DMPULDWNR { let bits = { const MASK: bool = true; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) != 0 }; DMPULDWNR { bits } } #[doc = "Bit 5"] #[inline] pub fn dppuldwn(&self) -> DPPULDWNR { let bits = { const MASK: bool = true; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) != 0 }; DPPULDWNR { bits } } #[doc = "Bit 6"] #[inline] pub fn dmpulup(&self) -> DMPULUPR { let bits = { const MASK: bool = true; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) != 0 }; DMPULUPR { bits } } #[doc = "Bit 7"] #[inline] pub fn dppulup(&self) -> DPPULUPR { let bits = { const MASK: bool = true; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MASK as u32) != 0 }; DPPULUPR { 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 = "Bit 0"] #[inline] pub fn vbusdis(&mut self) -> _VBUSDISW { _VBUSDISW { w: self } } #[doc = "Bit 1"] #[inline] pub fn vbuschg(&mut self) -> _VBUSCHGW { _VBUSCHGW { w: self } } #[doc = "Bit 2"] #[inline] pub fn otgen(&mut self) -> _OTGENW { _OTGENW { w: self } } #[doc = "Bit 3"] #[inline] pub fn vbuson(&mut self) -> _VBUSONW { _VBUSONW { w: self } } #[doc = "Bit 4"] #[inline] pub fn dmpuldwn(&mut self) -> _DMPULDWNW { _DMPULDWNW { w: self } } #[doc = "Bit 5"] #[inline] pub fn dppuldwn(&mut self) -> _DPPULDWNW { _DPPULDWNW { w: self } } #[doc = "Bit 6"] #[inline] pub fn dmpulup(&mut self) -> _DMPULUPW { _DMPULUPW { w: self } } #[doc = "Bit 7"] #[inline] pub fn dppulup(&mut self) -> _DPPULUPW { _DPPULUPW { w: self } } }
24.620112
59
0.489676
7668249d6166cd950d5ab5c8af48d7977d128f46
1,194
//! Event based Receiver use crate::recv::{Error, InfraredReceiver, InfraredReceiverState, Status}; /// Event driven receiver pub struct EventReceiver<Protocol> where Protocol: InfraredReceiver, { pub state: Protocol::ReceiverState, } impl<Protocol: InfraredReceiver> EventReceiver<Protocol> { /// Create a new Receiver pub fn new(resolution: u32) -> Self { Self { state: Protocol::receiver_state(resolution), } } /// Event happened pub fn update( &mut self, edge: bool, delta: u32, ) -> Result<Option<Protocol::Cmd>, Error> { // Update state machine let state: Status = Protocol::event(&mut self.state, edge, delta).into(); match state { Status::Done => { let cmd = Protocol::command(&mut self.state); self.state.reset(); Ok(cmd) } Status::Error(err) => { self.state.reset(); Err(err) } Status::Idle | Status::Receiving => Ok(None), } } /// Reset receiver pub fn reset(&mut self) { self.state.reset(); } }
23.88
81
0.539363
f45906e1e2208f5f65f549359b28d63b0fd0763f
1,855
//! Asynchronous I/O. //! //! This module is the asynchronous version of `std::io`. Primarily, it //! defines two traits, [`AsyncRead`] and [`AsyncWrite`], which extend the //! `Read` and `Write` traits of the standard library. //! //! # AsyncRead and AsyncWrite //! //! [`AsyncRead`] and [`AsyncWrite`] must only be implemented for //! non-blocking I/O types that integrate with the futures type system. In //! other words, these types must never block the thread, and instead the //! current task is notified when the I/O resource is ready. //! //! # Standard input and output //! //! Tokio provides asynchronous APIs to standard [input], [output], and [error]. //! These APIs are very similar to the ones provided by `std`, but they also //! implement [`AsyncRead`] and [`AsyncWrite`]. //! //! Unlike *most* other Tokio APIs, the standard input / output APIs //! **must** be used from the context of the Tokio runtime as they require //! Tokio specific features to function. //! //! [input]: fn.stdin.html //! [output]: fn.stdout.html //! [error]: fn.stderr.html //! //! # `std` re-exports //! //! Additionally, [`Error`], [`ErrorKind`], and [`Result`] are re-exported //! from `std::io` for ease of use. //! //! [`AsyncRead`]: trait.AsyncRead.html //! [`AsyncWrite`]: trait.AsyncWrite.html //! [`Error`]: struct.Error.html //! [`ErrorKind`]: enum.ErrorKind.html //! [`Result`]: type.Result.html // standard input, output, and error #[cfg(feature = "fs")] pub use tokio_fs::{stderr, stdin, stdout, Stderr, Stdin, Stdout}; pub use tokio_io::split::split; pub use tokio_io::{ AsyncBufRead, AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, BufWriter, }; // Re-export io::Error so that users don't have to deal // with conflicts when `use`ing `tokio::io` and `std::io`. pub use std::io::{Error, ErrorKind, Result};
36.372549
97
0.679784