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
6a09a2891a60eb31414e384fd0a6a511e3af9fff
1,052
#[doc = "Reader of register MDH1"] pub type R = crate::R<u32, super::MDH1>; #[doc = "Writer for register MDH1"] pub type W = crate::W<u32, super::MDH1>; #[doc = "Register MDH1 `reset()`'s with value 0"] impl crate::ResetValue for super::MDH1 { #[inline(always)] fn reset_value() -> Self::Ux { 0 } } #[doc = "Reader of field `MDH`"] pub type MDH_R = crate::R<u32, u32>; #[doc = "Write proxy for field `MDH`"] pub struct MDH_W<'a> { w: &'a mut W, } impl<'a> MDH_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff); self.w } } impl R { #[doc = "Bits 0:31 - Message Data High Value"] #[inline(always)] pub fn mdh(&self) -> MDH_R { MDH_R::new((self.bits & 0xffff_ffff) as u32) } } impl W { #[doc = "Bits 0:31 - Message Data High Value"] #[inline(always)] pub fn mdh(&mut self) -> MDH_W { MDH_W { w: self } } }
26.3
84
0.561787
9b1b7b52a14c79256368fa201ac97b138011e7a7
322
#![doc(html_root_url = "https://docs.rs/tokio-channel/0.1.0")] #![deny(missing_docs, warnings, missing_debug_implementations)] //! Asynchronous channels. //! //! This crate provides channels that can be used to communicate between //! asynchronous tasks. extern crate futures; pub mod mpsc; pub mod oneshot; mod lock;
21.466667
72
0.73913
4ae9bc18b3d633d22c1196b6891ee914bbf0c1e4
917
use dirs::GH_MIRRORS_DIR; use errors::*; use git; use std::path::PathBuf; pub fn repo_dir(url: &str) -> Result<PathBuf> { let (org, name) = gh_url_to_org_and_name(url)?; Ok(GH_MIRRORS_DIR.join(format!("{}.{}", org, name))) } pub fn gh_url_to_org_and_name(url: &str) -> Result<(String, String)> { let mut components = url.split('/').collect::<Vec<_>>(); let name = components.pop(); let org = components.pop(); let (org, name) = if let (Some(org), Some(name)) = (org, name) { (org, name) } else { bail!("malformed repo url: {}", url); }; Ok((org.to_string(), name.to_string())) } pub fn fetch(url: &str) -> Result<()> { let dir = repo_dir(url)?; git::shallow_clone_or_pull(url, &dir) } pub fn reset_to_sha(url: &str, sha: &str) -> Result<()> { let dir = &repo_dir(url)?; git::shallow_fetch_sha(url, dir, sha)?; git::reset_to_sha(dir, sha) }
26.970588
70
0.59651
489427ba1c126202be6eafe31f9d379f7a99074a
2,557
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test where we add a private item into the root of an external. // crate. This should not cause anything we use to be invalidated. // Regression test for #36168. // revisions:rpass1 rpass2 // compile-flags: -Z query-dep-graph // aux-build:point.rs #![feature(rustc_attrs)] #![feature(stmt_expr_attributes)] #![allow(dead_code)] #![rustc_partition_reused(module="struct_point-fn_calls_methods_in_same_impl", cfg="rpass2")] #![rustc_partition_reused(module="struct_point-fn_calls_free_fn", cfg="rpass2")] #![rustc_partition_reused(module="struct_point-fn_read_field", cfg="rpass2")] #![rustc_partition_reused(module="struct_point-fn_write_field", cfg="rpass2")] #![rustc_partition_reused(module="struct_point-fn_make_struct", cfg="rpass2")] extern crate point; /// A fn item that calls (public) methods on `Point` from the same impl mod fn_calls_methods_in_same_impl { use point::Point; #[rustc_clean(label="TypeckItemBody", cfg="rpass2")] pub fn check() { let x = Point { x: 2.0, y: 2.0 }; x.distance_from_origin(); } } /// A fn item that calls (public) methods on `Point` from another impl mod fn_calls_free_fn { use point::{self, Point}; #[rustc_clean(label="TypeckItemBody", cfg="rpass2")] pub fn check() { let x = Point { x: 2.0, y: 2.0 }; point::distance_squared(&x); } } /// A fn item that makes an instance of `Point` but does not invoke methods mod fn_make_struct { use point::Point; #[rustc_clean(label="TypeckItemBody", cfg="rpass2")] pub fn make_origin() -> Point { Point { x: 2.0, y: 2.0 } } } /// A fn item that reads fields from `Point` but does not invoke methods mod fn_read_field { use point::Point; #[rustc_clean(label="TypeckItemBody", cfg="rpass2")] pub fn get_x(p: Point) -> f32 { p.x } } /// A fn item that writes to a field of `Point` but does not invoke methods mod fn_write_field { use point::Point; #[rustc_clean(label="TypeckItemBody", cfg="rpass2")] pub fn inc_x(p: &mut Point) { p.x += 1.0; } } fn main() { }
30.082353
93
0.68244
d9a4bcc28dfe095e2ad32e70420afd0e25405146
19,618
// Copyright 2018-2021 Parity Technologies (UK) Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! The public raw interface towards the host Wasm engine. use crate::{ backend::{ EnvBackend, ReturnFlags, TypedEnvBackend, }, call::{ utils::ReturnType, CallParams, CreateParams, }, engine::{ EnvInstance, OnInstance, }, hash::{ CryptoHash, HashOutput, }, topics::Topics, types::{ RentParams, RentStatus, }, Environment, Result, }; use ink_primitives::Key; /// Returns the address of the caller of the executed contract. /// /// # Errors /// /// If the returned caller cannot be properly decoded. pub fn caller<T>() -> T::AccountId where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::caller::<T>(instance) }) } /// Returns the transferred balance for the contract execution. /// /// # Errors /// /// If the returned value cannot be properly decoded. pub fn transferred_balance<T>() -> T::Balance where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::transferred_balance::<T>(instance) }) } /// Returns the price for the specified amount of gas. /// /// # Errors /// /// If the returned value cannot be properly decoded. pub fn weight_to_fee<T>(gas: u64) -> T::Balance where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::weight_to_fee::<T>(instance, gas) }) } /// Returns the amount of gas left for the contract execution. /// /// # Errors /// /// If the returned value cannot be properly decoded. pub fn gas_left<T>() -> u64 where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::gas_left::<T>(instance) }) } /// Returns the current block timestamp. /// /// # Errors /// /// If the returned value cannot be properly decoded. pub fn block_timestamp<T>() -> T::Timestamp where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::block_timestamp::<T>(instance) }) } /// Returns the account ID of the executed contract. /// /// # Note /// /// This method was formerly known as `address`. /// /// # Errors /// /// If the returned value cannot be properly decoded. pub fn account_id<T>() -> T::AccountId where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::account_id::<T>(instance) }) } /// Returns the balance of the executed contract. /// /// # Errors /// /// If the returned value cannot be properly decoded. pub fn balance<T>() -> T::Balance where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::balance::<T>(instance) }) } /// Returns the current rent allowance for the executed contract. /// /// # Errors /// /// If the returned value cannot be properly decoded. pub fn rent_allowance<T>() -> T::Balance where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::rent_allowance::<T>(instance) }) } /// Returns information needed for rent calculations. /// /// # Errors /// /// If the returned value cannot be properly decoded. pub fn rent_params<T>() -> Result<RentParams<T>> where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::rent_params::<T>(instance) }) } /// Returns information about the required deposit and resulting rent. /// /// # Parameters /// /// - `at_refcount`: The `refcount` assumed for the returned `custom_refcount_*` fields. /// If `None` is supplied the `custom_refcount_*` fields will also be `None`. /// /// The `current_*` fields of `RentStatus` do **not** consider changes to the code's /// `refcount` made during the currently running call. /// /// # Errors /// /// If the returned value cannot be properly decoded. pub fn rent_status<T>(at_refcount: Option<core::num::NonZeroU32>) -> Result<RentStatus<T>> where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::rent_status::<T>(instance, at_refcount) }) } /// Returns the current block number. /// /// # Errors /// /// If the returned value cannot be properly decoded. pub fn block_number<T>() -> T::BlockNumber where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::block_number::<T>(instance) }) } /// Returns the minimum balance that is required for creating an account. /// /// # Errors /// /// If the returned value cannot be properly decoded. pub fn minimum_balance<T>() -> T::Balance where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::minimum_balance::<T>(instance) }) } /// Returns the tombstone deposit for the contracts chain. /// /// # Errors /// /// If the returned value cannot be properly decoded. pub fn tombstone_deposit<T>() -> T::Balance where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::tombstone_deposit::<T>(instance) }) } /// Emits an event with the given event data. pub fn emit_event<T, Event>(event: Event) where T: Environment, Event: Topics + scale::Encode, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::emit_event::<T, Event>(instance, event) }) } /// Sets the rent allowance of the executed contract to the new value. pub fn set_rent_allowance<T>(new_value: T::Balance) where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::set_rent_allowance::<T>(instance, new_value) }) } /// Writes the value to the contract storage under the given key. /// /// # Panics /// /// - If the encode length of value exceeds the configured maximum value length of a storage entry. pub fn set_contract_storage<V>(key: &Key, value: &V) where V: scale::Encode, { <EnvInstance as OnInstance>::on_instance(|instance| { EnvBackend::set_contract_storage::<V>(instance, key, value) }) } /// Returns the value stored under the given key in the contract's storage if any. /// /// # Errors /// /// - If the decoding of the typed value failed (`KeyNotFound`) pub fn get_contract_storage<R>(key: &Key) -> Result<Option<R>> where R: scale::Decode, { <EnvInstance as OnInstance>::on_instance(|instance| { EnvBackend::get_contract_storage::<R>(instance, key) }) } /// Clears the contract's storage key entry. pub fn clear_contract_storage(key: &Key) { <EnvInstance as OnInstance>::on_instance(|instance| { EnvBackend::clear_contract_storage(instance, key) }) } /// Invokes a contract message. /// /// # Note /// /// - Prefer using this over [`eval_contract`] if possible. [`invoke_contract`] /// will generally have a better performance since it won't try to fetch any results. /// - This is a low level way to invoke another smart contract. /// Prefer to use the ink! guided and type safe approach to using this. /// /// # Errors /// /// - If the called account does not exist. /// - If the called account is not a contract. /// - If the called contract is a tombstone. /// - If arguments passed to the called contract message are invalid. /// - If the called contract execution has trapped. /// - If the called contract ran out of gas upon execution. pub fn invoke_contract<T, Args>(params: &CallParams<T, Args, ()>) -> Result<()> where T: Environment, Args: scale::Encode, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::invoke_contract::<T, Args>(instance, params) }) } /// Evaluates a contract message and returns its result. /// /// # Note /// /// This is a low level way to evaluate another smart contract. /// Prefer to use the ink! guided and type safe approach to using this. /// /// # Errors /// /// - If the called account does not exist. /// - If the called account is not a contract. /// - If the called contract is a tombstone. /// - If arguments passed to the called contract message are invalid. /// - If the called contract execution has trapped. /// - If the called contract ran out of gas upon execution. /// - If the returned value failed to decode properly. pub fn eval_contract<T, Args, R>(params: &CallParams<T, Args, ReturnType<R>>) -> Result<R> where T: Environment, Args: scale::Encode, R: scale::Decode, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::eval_contract::<T, Args, R>(instance, params) }) } /// Instantiates another contract. /// /// # Note /// /// This is a low level way to instantiate another smart contract. /// Prefer to use the ink! guided and type safe approach to using this. /// /// # Errors /// /// - If the code hash is invalid. /// - If the arguments passed to the instantiation process are invalid. /// - If the instantiation process traps. /// - If the instantiation process runs out of gas. /// - If given insufficient endowment. /// - If the returned account ID failed to decode properly. pub fn instantiate_contract<T, Args, Salt, C>( params: &CreateParams<T, Args, Salt, C>, ) -> Result<T::AccountId> where T: Environment, Args: scale::Encode, Salt: AsRef<[u8]>, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::instantiate_contract::<T, Args, Salt, C>(instance, params) }) } /// Restores a smart contract in tombstone state. /// /// # Params /// /// - `account_id`: Account ID of the to-be-restored contract. /// - `code_hash`: Code hash of the to-be-restored contract. /// - `rent_allowance`: Rent allowance of the restored contract /// upon successful restoration. /// - `filtered_keys`: Storage keys to be excluded when calculating the tombstone hash, /// which is used to decide whether the original contract and the /// to-be-restored contract have matching storage. /// /// # Usage /// /// A smart contract that has too few funds to pay for its storage fees /// can eventually be evicted. An evicted smart contract `C` leaves behind /// a tombstone associated with a hash that has been computed partially /// by its storage contents. /// /// To restore contract `C` back to a fully working contract the normal /// process is to write another contract `C2` with the only purpose to /// eventually have the absolutely same contract storage as `C` did when /// it was evicted. /// For that purpose `C2` can use other storage keys that have not been in /// use by contract `C`. /// Once `C2` contract storage matches the storage of `C` when it was evicted /// `C2` can invoke this method in order to initiate restoration of `C`. /// A tombstone hash is calculated for `C2` and if it matches the tombstone /// hash of `C` the restoration is going to be successful. /// The `filtered_keys` argument can be used to ignore the extraneous keys /// used by `C2` but not used by `C`. /// /// The process of such a smart contract restoration can generally be very expensive. /// /// # Note /// /// - `filtered_keys` can be used to ignore certain storage regions /// in the restorer contract to not influence the hash calculations. /// - Does *not* perform restoration right away but defers it to the end of /// the contract execution. /// - Restoration is canceled if there is no tombstone in the destination /// address or if the hashes don't match. No changes are made in this case. pub fn restore_contract<T>( account_id: T::AccountId, code_hash: T::Hash, rent_allowance: T::Balance, filtered_keys: &[Key], ) where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::restore_contract::<T>( instance, account_id, code_hash, rent_allowance, filtered_keys, ) }) } /// Terminates the existence of the currently executed smart contract /// without creating a tombstone. /// /// This removes the calling account and transfers all remaining balance /// to the given beneficiary. /// /// No tombstone will be created, this function kills a contract completely! /// /// # Note /// /// This function never returns. Either the termination was successful and the /// execution of the destroyed contract is halted. Or it failed during the termination /// which is considered fatal and results in a trap and rollback. pub fn terminate_contract<T>(beneficiary: T::AccountId) -> ! where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::terminate_contract::<T>(instance, beneficiary) }) } /// Transfers value from the contract to the destination account ID. /// /// # Note /// /// This is more efficient and simpler than the alternative to make a no-op /// contract call or invoke a runtime function that performs the /// transaction. /// /// # Errors /// /// - If the contract does not have sufficient funds. /// - If the transfer had brought the sender's total balance below the /// subsistence threshold. pub fn transfer<T>(destination: T::AccountId, value: T::Balance) -> Result<()> where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::transfer::<T>(instance, destination, value) }) } /// Returns the execution input to the executed contract and decodes it as `T`. /// /// # Note /// /// - The input is the 4-bytes selector followed by the arguments /// of the called function in their SCALE encoded representation. /// - No prior interaction with the environment must take place before /// calling this procedure. /// /// # Usage /// /// Normally contracts define their own `enum` dispatch types respective /// to their exported constructors and messages that implement `scale::Decode` /// according to the constructors or messages selectors and their arguments. /// These `enum` dispatch types are then given to this procedure as the `T`. /// /// When using ink! users do not have to construct those enum dispatch types /// themselves as they are normally generated by the ink! code generation /// automatically. /// /// # Errors /// /// If the given `T` cannot be properly decoded from the expected input. pub fn decode_input<T>() -> Result<T> where T: scale::Decode, { <EnvInstance as OnInstance>::on_instance(|instance| { EnvBackend::decode_input::<T>(instance) }) } /// Returns the value back to the caller of the executed contract. /// /// # Note /// /// This function stops the execution of the contract immediately. pub fn return_value<R>(return_flags: ReturnFlags, return_value: &R) -> ! where R: scale::Encode, { <EnvInstance as OnInstance>::on_instance(|instance| { EnvBackend::return_value::<R>(instance, return_flags, return_value) }) } /// Returns a random hash seed and the block number since which it was determinable /// by chain observers. /// /// # Note /// /// - The subject buffer can be used to further randomize the hash. /// - Within the same execution returns the same random hash for the same subject. /// /// # Errors /// /// If the returned value cannot be properly decoded. /// /// # Important /// /// The returned seed should only be used to distinguish commitments made before /// the returned block number. If the block number is too early (i.e. commitments were /// made afterwards), then ensure no further commitments may be made and repeatedly /// call this on later blocks until the block number returned is later than the latest /// commitment. pub fn random<T>(subject: &[u8]) -> Result<(T::Hash, T::BlockNumber)> where T: Environment, { <EnvInstance as OnInstance>::on_instance(|instance| { TypedEnvBackend::random::<T>(instance, subject) }) } /// Appends the given message to the debug message buffer. pub fn debug_message(message: &str) { <EnvInstance as OnInstance>::on_instance(|instance| { EnvBackend::debug_message(instance, message) }) } /// Conducts the crypto hash of the given input and stores the result in `output`. /// /// # Example /// /// ``` /// use ink_env::hash::{Sha2x256, HashOutput}; /// let input: &[u8] = &[13, 14, 15]; /// let mut output = <Sha2x256 as HashOutput>::Type::default(); // 256-bit buffer /// let hash = ink_env::hash_bytes::<Sha2x256>(input, &mut output); /// ``` pub fn hash_bytes<H>(input: &[u8], output: &mut <H as HashOutput>::Type) where H: CryptoHash, { <EnvInstance as OnInstance>::on_instance(|instance| { instance.hash_bytes::<H>(input, output) }) } /// Conducts the crypto hash of the given encoded input and stores the result in `output`. /// /// # Example /// /// ``` /// # use ink_env::hash::{Sha2x256, HashOutput}; /// const EXPECTED: [u8; 32] = [ /// 243, 242, 58, 110, 205, 68, 100, 244, 187, 55, 188, 248, 29, 136, 145, 115, /// 186, 134, 14, 175, 178, 99, 183, 21, 4, 94, 92, 69, 199, 207, 241, 179, /// ]; /// let encodable = (42, "foo", true); // Implements `scale::Encode` /// let mut output = <Sha2x256 as HashOutput>::Type::default(); // 256-bit buffer /// ink_env::hash_encoded::<Sha2x256, _>(&encodable, &mut output); /// assert_eq!(output, EXPECTED); /// ``` pub fn hash_encoded<H, T>(input: &T, output: &mut <H as HashOutput>::Type) where H: CryptoHash, T: scale::Encode, { <EnvInstance as OnInstance>::on_instance(|instance| { instance.hash_encoded::<H, T>(input, output) }) } /// Recovers the compressed ECDSA public key for given `signature` and `message_hash`, /// and stores the result in `output`. /// /// # Example /// /// ``` /// const signature: [u8; 65] = [ /// 161, 234, 203, 74, 147, 96, 51, 212, 5, 174, 231, 9, 142, 48, 137, 201, /// 162, 118, 192, 67, 239, 16, 71, 216, 125, 86, 167, 139, 70, 7, 86, 241, /// 33, 87, 154, 251, 81, 29, 160, 4, 176, 239, 88, 211, 244, 232, 232, 52, /// 211, 234, 100, 115, 230, 47, 80, 44, 152, 166, 62, 50, 8, 13, 86, 175, /// 28, /// ]; /// const message_hash: [u8; 32] = [ /// 162, 28, 244, 179, 96, 76, 244, 178, 188, 83, 230, 248, 143, 106, 77, 117, /// 239, 95, 244, 171, 65, 95, 62, 153, 174, 166, 182, 28, 130, 73, 196, 208 /// ]; /// const EXPECTED_COMPRESSED_PUBLIC_KEY: [u8; 33] = [ /// 2, 121, 190, 102, 126, 249, 220, 187, 172, 85, 160, 98, 149, 206, 135, 11, /// 7, 2, 155, 252, 219, 45, 206, 40, 217, 89, 242, 129, 91, 22, 248, 23, /// 152, /// ]; /// let mut output = [0; 33]; /// ink_env::ecdsa_recover(&signature, &message_hash, &mut output); /// assert_eq!(output, EXPECTED_COMPRESSED_PUBLIC_KEY); /// ``` pub fn ecdsa_recover( signature: &[u8; 65], message_hash: &[u8; 32], output: &mut [u8; 33], ) -> Result<()> { <EnvInstance as OnInstance>::on_instance(|instance| { instance.ecdsa_recover(signature, message_hash, output) }) }
30.510109
99
0.663931
097812706416317db0ac8fe34ea907c8e0b4bfd4
1,295
#![crate_name = "uu_whoami"] /* * This file is part of the uutils coreutils package. * * (c) Jordi Boggiano <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: whoami (GNU coreutils) 8.21 */ #[macro_use] extern crate clap; #[macro_use] extern crate uucore; mod platform; // force a re-build whenever Cargo.toml changes const _CARGO_TOML: &'static str = include_str!("Cargo.toml"); pub fn uumain(args: Vec<String>) -> i32 { let app = app_from_crate!(); if let Err(err) = app.get_matches_from_safe(args) { if err.kind == clap::ErrorKind::HelpDisplayed || err.kind == clap::ErrorKind::VersionDisplayed { println!("{}", err); 0 } else { show_error!("{}", err); 1 } } else { exec(); 0 } } pub fn exec() { unsafe { match platform::getusername() { Ok(username) => println!("{}", username), Err(err) => match err.raw_os_error() { Some(0) | None => crash!(1, "failed to get username"), Some(_) => crash!(1, "failed to get username: {}", err), }, } } }
23.545455
74
0.555212
628cb08d5cc1409827a6ab1406435f7f55fa2749
705
use bit_vec::BitVec; #[derive(Debug, Default, Clone)] pub struct Buffer(BitVec); impl Buffer { pub fn new() -> Self { Self::default() } pub fn from_elem(n: usize, default: bool) -> Self { Self(BitVec::from_elem(n, default)) } pub fn push_field_list(&mut self, target: Self) { for bit in target.into_inner() { self.0.push(bit); } } fn into_inner(self) -> BitVec { self.0 } } impl std::ops::Deref for Buffer { type Target = BitVec; fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for Buffer { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
18.076923
55
0.548936
56e93b4f57de917176104ba22884e0ab9d33b0e1
4,833
#[doc = "Register `MODE` reader"] pub struct R(crate::R<MODE_SPEC>); impl core::ops::Deref for R { type Target = crate::R<MODE_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<MODE_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<MODE_SPEC>) -> Self { R(reader) } } #[doc = "Register `MODE` writer"] pub struct W(crate::W<MODE_SPEC>); impl core::ops::Deref for W { type Target = crate::W<MODE_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<MODE_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<MODE_SPEC>) -> Self { W(writer) } } #[doc = "I2S mode.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MODE_A { #[doc = "0: Master mode. SCK and LRCK generated from internal master clcok (MCK) and output on pins defined by PSEL.xxx."] MASTER = 0, #[doc = "1: Slave mode. SCK and LRCK generated by external master and received on pins defined by PSEL.xxx"] SLAVE = 1, } impl From<MODE_A> for bool { #[inline(always)] fn from(variant: MODE_A) -> Self { variant as u8 != 0 } } #[doc = "Field `MODE` reader - I2S mode."] pub struct MODE_R(crate::FieldReader<bool, MODE_A>); impl MODE_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { MODE_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> MODE_A { match self.bits { false => MODE_A::MASTER, true => MODE_A::SLAVE, } } #[doc = "Checks if the value of the field is `MASTER`"] #[inline(always)] pub fn is_master(&self) -> bool { **self == MODE_A::MASTER } #[doc = "Checks if the value of the field is `SLAVE`"] #[inline(always)] pub fn is_slave(&self) -> bool { **self == MODE_A::SLAVE } } impl core::ops::Deref for MODE_R { type Target = crate::FieldReader<bool, MODE_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `MODE` writer - I2S mode."] pub struct MODE_W<'a> { w: &'a mut W, } impl<'a> MODE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MODE_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Master mode. SCK and LRCK generated from internal master clcok (MCK) and output on pins defined by PSEL.xxx."] #[inline(always)] pub fn master(self) -> &'a mut W { self.variant(MODE_A::MASTER) } #[doc = "Slave mode. SCK and LRCK generated by external master and received on pins defined by PSEL.xxx"] #[inline(always)] pub fn slave(self) -> &'a mut W { self.variant(MODE_A::SLAVE) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01); self.w } } impl R { #[doc = "Bit 0 - I2S mode."] #[inline(always)] pub fn mode(&self) -> MODE_R { MODE_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 0 - I2S mode."] #[inline(always)] pub fn mode(&mut self) -> MODE_W { MODE_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 = "I2S mode.\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 [mode](index.html) module"] pub struct MODE_SPEC; impl crate::RegisterSpec for MODE_SPEC { type Ux = u32; } #[doc = "`read()` method returns [mode::R](R) reader structure"] impl crate::Readable for MODE_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [mode::W](W) writer structure"] impl crate::Writable for MODE_SPEC { type Writer = W; } #[doc = "`reset()` method sets MODE to value 0"] impl crate::Resettable for MODE_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
30.018634
394
0.581626
4a67973982e390ea7fd215da409da1a3c5c274b7
1,325
//! Represents a margin around an axis-aligned rectangle. use super::vec2::Vec2; /// Represents a margin around an axis-aligned rectangle. #[derive(Copy, Clone, Debug, PartialEq)] #[repr(C)] pub struct Thickness { /// Left x component pub left: f64, /// Top y component pub top: f64, /// Right x component pub right: f64, /// Bottom y component pub bottom: f64, } impl Thickness { /// Constructs the thickness from components. #[inline] pub fn new(left: f64, top: f64, right: f64, bottom: f64) -> Thickness { Thickness { left, top, right, bottom, } } } impl From<Vec2> for Thickness { #[inline] fn from(vec: Vec2) -> Thickness { (vec.x, vec.y).into() } } impl From<f64> for Thickness { #[inline] fn from(f: f64) -> Thickness { (f, f, f, f).into() } } impl From<(f64, f64)> for Thickness { #[inline] fn from((x, y): (f64, f64)) -> Thickness { (x, y, x, y).into() } } impl From<(f64, f64, f64, f64)> for Thickness { #[inline] fn from(values: (f64, f64, f64, f64)) -> Thickness { let (left, top, right, bottom) = values; Thickness { left, top, right, bottom, } } }
20.384615
75
0.524528
f5b80ce6a7b5aea5794074b9c2152f40f767b35c
5,236
//! This module contains the functions and macros for //! sending a payload //! for an HTTP connection, for at least two participants. //! //! *This module is available only if MultiCrusty is built with //! the `"transport"` feature or the `"transport_http"` feature.* use crate::binary::struct_trait::{send::Send, session::Session}; use hyper::client::ResponseFuture; use hyper::{Body, Client, Method, Request}; use hyper_tls::HttpsConnector; use std::boxed::Box; use std::error::Error; use std::marker; use std::panic; /// Send a value of type `T` over http. Returns the /// continuation of the session `S`. May fail. /// /// *This function is available only if MultiCrusty is built with /// the `"transport"` feature or the `"transport_http"` feature.* #[cfg_attr( doc_cfg, doc(cfg(any(feature = "transport", feature = "transport_http"))) )] pub fn send_http<T, S>( x: T, s: Send<T, S>, http: bool, method: Method, uri: &str, header: Vec<(&str, &str)>, body: &'static str, ) -> Result<(S, ResponseFuture), Box<dyn Error>> where T: marker::Send, S: Session, { let (here, there) = S::new(); let respfut = match http { true => { let mut temp = Request::builder().method(method).uri(uri); for elt in header { temp = temp.header(elt.0, elt.1); } let req = temp.body(Body::from(body))?; let https = HttpsConnector::new(); let client = Client::builder().build::<_, Body>(https); client.request(req) } false => { let https = HttpsConnector::new(); let client = Client::builder().build::<_, Body>(https); client.request(Request::default()) } }; //////////////// match s.channel.send((x, there)) { Ok(_) => Ok((here, respfut)), Err(e) => panic!("{}", e.to_string()), } } /// Creates a *send* function to send from a given binary session type of a MeshedChannels with more /// than 3 participants. /// /// # Arguments /// /// * The name of the new *send* function /// * The name of the receiver /// * The name of the sender /// * The name of the *MeshedChannels* type that will be used /// * The number of participants (all together) /// * The index of the binary session type that will receive in the MeshedChannels for this specific /// role. Index starts at 1. /// /// # Example /// /// ```ignore /// use mpstthree::{create_multiple_normal_role, create_send_http_session, create_meshedchannels}; /// /// create_multiple_normal_role!( /// RoleA, RoleADual | /// RoleB, RoleBDual | /// RoleD, RoleDDual | /// ); /// /// create_meshedchannels!(MeshedChannels, 3); /// /// create_send_http_session!(send_http_d_to_a, RoleA, RoleD, MeshedChannels, 3, 1); /// ``` /// /// *This macro is available only if MultiCrusty is built with /// the `"transport"` feature or the `"transport_http"` feature.* #[macro_export] #[cfg_attr( doc_cfg, doc(cfg(any(feature = "transport", feature = "transport_http"))) )] macro_rules! create_send_http_session { ( $func_name:ident, $receiver:ident, $sender:ident, $meshedchannels_name:ident, $n_sessions:literal, $exclusion:literal ) => { mpst_seq::create_send_http_session!( $func_name, $receiver, $sender, $meshedchannels_name, $n_sessions, $exclusion ); }; } /// Creates multiple *send* functions to send from a given binary session type of a MeshedChannels /// with more than 3 participants. /// /// # Arguments /// /// * The name of the new *send* functions /// * The name of the receivers /// * The name of the senders /// * The index of the binary session types that will receive in the MeshedChannels for this /// specific role. Index starts at 1. /// * The name of the *MeshedChannels* type that will be used /// * The number of participants (all together) /// /// # Example /// /// ```ignore /// use mpstthree::{create_multiple_normal_role, create_meshedchannels, create_send_mpst_http_bundle}; /// /// create_multiple_normal_role!( /// RoleA, RoleADual | /// RoleB, RoleBDual | /// RoleD, RoleDDual | /// ); /// /// create_meshedchannels!(MeshedChannels, 3); /// /// create_send_mpst_http_bundle!( /// send_http_d_to_a, /// RoleA, /// 1 | /// send_http_d_to_b, /// RoleB, /// 2 | => /// RoleD, /// MeshedChannels, /// 3 /// ); /// ``` /// /// *This macro is available only if MultiCrusty is built with /// the `"transport"` feature or the `"transport_http"` feature.* #[macro_export] #[cfg_attr( doc_cfg, doc(cfg(any(feature = "transport", feature = "transport_http"))) )] macro_rules! create_send_mpst_http_bundle { ($( $func_name: ident, $receiver: ident, $exclusion: literal | )+ => $sender: ident, $meshedchannels_name: ident, $n_sessions: literal) => { $( mpstthree::create_send_http_session!( $func_name, $receiver, $sender, $meshedchannels_name, $n_sessions, $exclusion ); )+ } }
27.851064
144
0.603896
e9008515cb2707166d87c6e09e6ed2962b0dcd4b
1,933
//! DMA channels. #[cfg(any( stm32_mcu = "stm32f100", stm32_mcu = "stm32f101", stm32_mcu = "stm32f102", stm32_mcu = "stm32f103", stm32_mcu = "stm32f107", ))] mod f1; #[cfg(any(stm32_mcu = "stm32f303"))] mod f3; #[cfg(any( stm32_mcu = "stm32f401", stm32_mcu = "stm32f405", stm32_mcu = "stm32f407", stm32_mcu = "stm32f410", stm32_mcu = "stm32f411", stm32_mcu = "stm32f412", stm32_mcu = "stm32f413", stm32_mcu = "stm32f427", stm32_mcu = "stm32f429", stm32_mcu = "stm32f446", stm32_mcu = "stm32f469", ))] mod f4; #[cfg(any( stm32_mcu = "stm32l4x1", stm32_mcu = "stm32l4x2", stm32_mcu = "stm32l4x3", stm32_mcu = "stm32l4x5", stm32_mcu = "stm32l4x6", ))] mod l4; #[cfg(any( stm32_mcu = "stm32l4r5", stm32_mcu = "stm32l4r7", stm32_mcu = "stm32l4r9", stm32_mcu = "stm32l4s5", stm32_mcu = "stm32l4s7", stm32_mcu = "stm32l4s9" ))] mod l4_plus; #[cfg(any( stm32_mcu = "stm32f100", stm32_mcu = "stm32f101", stm32_mcu = "stm32f102", stm32_mcu = "stm32f103", stm32_mcu = "stm32f107", ))] pub use self::f1::*; #[cfg(any(stm32_mcu = "stm32f303"))] pub use self::f3::*; #[cfg(any( stm32_mcu = "stm32f401", stm32_mcu = "stm32f405", stm32_mcu = "stm32f407", stm32_mcu = "stm32f410", stm32_mcu = "stm32f411", stm32_mcu = "stm32f412", stm32_mcu = "stm32f413", stm32_mcu = "stm32f427", stm32_mcu = "stm32f429", stm32_mcu = "stm32f446", stm32_mcu = "stm32f469", ))] pub use self::f4::*; #[cfg(any( stm32_mcu = "stm32l4x1", stm32_mcu = "stm32l4x2", stm32_mcu = "stm32l4x3", stm32_mcu = "stm32l4x5", stm32_mcu = "stm32l4x6", ))] pub use self::l4::*; #[cfg(any( stm32_mcu = "stm32l4r5", stm32_mcu = "stm32l4r7", stm32_mcu = "stm32l4r9", stm32_mcu = "stm32l4s5", stm32_mcu = "stm32l4s7", stm32_mcu = "stm32l4s9" ))] pub use self::l4_plus::*;
22.476744
36
0.607346
6a81b8e21529e826fca530e9cec20e13bcf39b32
1,985
use wabt::wat2wasm; use wasmer_clif_backend::CraneliftCompiler; use wasmer_runtime_core::{import::ImportObject, Instance}; fn main() { let instance = create_module_1(); let result = instance.call("call-overwritten-element", &[]); println!("result: {:?}", result); } fn create_module_1() -> Instance { let module_str = r#"(module (type (;0;) (func (result i32))) (import "spectest" "table" (table (;0;) 10 anyfunc)) (func (;0;) (type 0) (result i32) i32.const 65) (func (;1;) (type 0) (result i32) i32.const 66) (func (;2;) (type 0) (result i32) i32.const 9 call_indirect (type 0)) (export "call-overwritten-element" (func 2)) (elem (;0;) (i32.const 9) 0) (elem (;1;) (i32.const 9) 1)) "#; let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed"); let module = wasmer_runtime_core::compile_with(&wasm_binary[..], &CraneliftCompiler::new()) .expect("WASM can't be compiled"); module .instantiate(generate_imports()) .expect("WASM can't be instantiated") } static IMPORT_MODULE: &str = r#" (module (type $t0 (func (param i32))) (type $t1 (func)) (func $print_i32 (export "print_i32") (type $t0) (param $lhs i32)) (func $print (export "print") (type $t1)) (table $table (export "table") 10 20 anyfunc) (memory $memory (export "memory") 1 2) (global $global_i32 (export "global_i32") i32 (i32.const 666))) "#; pub fn generate_imports() -> ImportObject { let wasm_binary = wat2wasm(IMPORT_MODULE.as_bytes()).expect("WAST not valid or malformed"); let module = wasmer_runtime_core::compile_with(&wasm_binary[..], &CraneliftCompiler::new()) .expect("WASM can't be compiled"); let instance = module .instantiate(ImportObject::new()) .expect("WASM can't be instantiated"); let mut imports = ImportObject::new(); imports.register("spectest", instance); imports }
35.446429
95
0.631738
edbfded68b97b153fa554c95b77832a4a13cca28
26,685
extern crate vsop87; use vsop87::*; #[test] fn it_mercury() { let coordinates = vsop87d::mercury(2451545.0); assert!(coordinates.longitude() > 4.4293481035 && coordinates.longitude() < 4.4293481037); assert!(coordinates.latitude() > -0.0527573410 && coordinates.latitude() < -0.0527573408); assert!(coordinates.distance() > 0.46647110 && coordinates.distance() < 0.46647186); let coordinates = vsop87d::mercury(2415020.0); assert!(coordinates.longitude() > 3.4851161910 && coordinates.longitude() < 3.4851161912); assert!(coordinates.latitude() > 0.0565906172 && coordinates.latitude() < 0.0565906174); assert!(coordinates.distance() > 0.41834225 && coordinates.distance() < 0.41834301); let coordinates = vsop87d::mercury(2378495.0); assert!(coordinates.longitude() > 2.0737894887 && coordinates.longitude() < 2.0737894889); assert!(coordinates.latitude() > 0.1168184803 && coordinates.latitude() < 0.1168184805); assert!(coordinates.distance() > 0.32339057 && coordinates.distance() < 0.32339133); let coordinates = vsop87d::mercury(2341970.0); assert!(coordinates.longitude() > 0.1910149586 && coordinates.longitude() < 0.1910149588); assert!(coordinates.latitude() > -0.0682441257 && coordinates.latitude() < -0.0682441255); assert!(coordinates.distance() > 0.33815593 && coordinates.distance() < 0.33815669); let coordinates = vsop87d::mercury(2305445.0); assert!(coordinates.longitude() > 5.1836421819 && coordinates.longitude() < 5.1836421821); assert!(coordinates.latitude() > -0.1170914849 && coordinates.latitude() < -0.1170914847); assert!(coordinates.distance() > 0.43265140 && coordinates.distance() < 0.43265216); let coordinates = vsop87d::mercury(2268920.0); assert!(coordinates.longitude() > 4.2636517902 && coordinates.longitude() < 4.2636517904); assert!(coordinates.latitude() > -0.0457048517 && coordinates.latitude() < -0.0457048515); assert!(coordinates.distance() > 0.46615201 && coordinates.distance() < 0.46615277); let coordinates = vsop87d::mercury(2232395.0); assert!(coordinates.longitude() > 3.3115600861 && coordinates.longitude() < 3.3115600863); assert!(coordinates.latitude() > 0.0639722346 && coordinates.latitude() < 0.0639722348); assert!(coordinates.distance() > 0.41523814 && coordinates.distance() < 0.41523890); let coordinates = vsop87d::mercury(2195870.0); assert!(coordinates.longitude() > 1.8738888758 && coordinates.longitude() < 1.8738888760); assert!(coordinates.latitude() > 0.1126774696 && coordinates.latitude() < 0.1126774698); assert!(coordinates.distance() > 0.32093624 && coordinates.distance() < 0.32093700); let coordinates = vsop87d::mercury(2159345.0); assert!(coordinates.longitude() > 6.2819826059 && coordinates.longitude() < 6.2819826061); assert!(coordinates.latitude() > -0.0768697085 && coordinates.latitude() < -0.0768697083); assert!(coordinates.distance() > 0.34143504 && coordinates.distance() < 0.34143581); let coordinates = vsop87d::mercury(2122820.0); assert!(coordinates.longitude() > 5.0128397763 && coordinates.longitude() < 5.0128397765); assert!(coordinates.latitude() > -0.1143275809 && coordinates.latitude() < -0.1143275807); assert!(coordinates.distance() > 0.43520594 && coordinates.distance() < 0.43520670); } #[test] fn it_venus() { let coordinates = vsop87d::venus(2451545.0); assert!(coordinates.longitude() > 3.1870221832 && coordinates.longitude() < 3.1870221834); assert!(coordinates.latitude() > 0.0569782848 && coordinates.latitude() < 0.0569782850); assert!(coordinates.distance() > 0.72021255 && coordinates.distance() < 0.72021331); let coordinates = vsop87d::venus(2415020.0); assert!(coordinates.longitude() > 5.9749622237 && coordinates.longitude() < 5.9749622239); assert!(coordinates.latitude() > -0.0591260015 && coordinates.latitude() < -0.0591260013); assert!(coordinates.distance() > 0.72747156 && coordinates.distance() < 0.72747232); let coordinates = vsop87d::venus(2378495.0); assert!(coordinates.longitude() > 2.5083656667 && coordinates.longitude() < 2.5083656669); assert!(coordinates.latitude() > 0.0552309406 && coordinates.latitude() < 0.0552309408); assert!(coordinates.distance() > 0.71854695 && coordinates.distance() < 0.71854771); let coordinates = vsop87d::venus(2341970.0); assert!(coordinates.longitude() > 5.3115708035 && coordinates.longitude() < 5.3115708037); assert!(coordinates.latitude() > -0.0455979905 && coordinates.latitude() < -0.0455979903); assert!(coordinates.distance() > 0.72834037 && coordinates.distance() < 0.72834113); let coordinates = vsop87d::venus(2305445.0); assert!(coordinates.longitude() > 1.8291359616 && coordinates.longitude() < 1.8291359618); assert!(coordinates.latitude() > 0.0311394083 && coordinates.latitude() < 0.0311394085); assert!(coordinates.distance() > 0.71863712 && coordinates.distance() < 0.71863788); let coordinates = vsop87d::venus(2268920.0); assert!(coordinates.longitude() > 4.6495448743 && coordinates.longitude() < 4.6495448745); assert!(coordinates.latitude() > -0.0145437543 && coordinates.latitude() < -0.0145437541); assert!(coordinates.distance() > 0.72733600 && coordinates.distance() < 0.72733676); let coordinates = vsop87d::venus(2232395.0); assert!(coordinates.longitude() > 1.1527504142 && coordinates.longitude() < 1.1527504144); assert!(coordinates.latitude() > -0.0054100667 && coordinates.latitude() < -0.0054100665); assert!(coordinates.distance() > 0.72054247 && coordinates.distance() < 0.72054323); let coordinates = vsop87d::venus(2195870.0); assert!(coordinates.longitude() > 3.9850309908 && coordinates.longitude() < 3.9850309910); assert!(coordinates.latitude() > 0.0222342484 && coordinates.latitude() < 0.0222342486); assert!(coordinates.distance() > 0.72474374 && coordinates.distance() < 0.72474450); let coordinates = vsop87d::venus(2159345.0); assert!(coordinates.longitude() > 0.4804699930 && coordinates.longitude() < 0.4804699932); assert!(coordinates.latitude() > -0.0395505251 && coordinates.latitude() < -0.0395505249); assert!(coordinates.distance() > 0.72354267 && coordinates.distance() < 0.72354343); let coordinates = vsop87d::venus(2122820.0); assert!(coordinates.longitude() > 3.3145399294 && coordinates.longitude() < 3.3145399296); assert!(coordinates.latitude() > 0.0505016052 && coordinates.latitude() < 0.0505016054); assert!(coordinates.distance() > 0.72158160 && coordinates.distance() < 0.72158236); } #[test] fn it_earth() { let coordinates = vsop87d::earth(2451545.0); assert!(coordinates.longitude() > 1.7519238680 && coordinates.longitude() < 1.7519238682); assert!(coordinates.latitude() > -0.0000039657 && coordinates.latitude() < -0.0000039655); assert!(coordinates.distance() > 0.98332730 && coordinates.distance() < 0.98332806); let coordinates = vsop87d::earth(2415020.0); assert!(coordinates.longitude() > 1.7391225562 && coordinates.longitude() < 1.7391225564); assert!(coordinates.latitude() > -0.0000005680 && coordinates.latitude() < -0.0000005678); assert!(coordinates.distance() > 0.98326860 && coordinates.distance() < 0.98326936); let coordinates = vsop87d::earth(2378495.0); assert!(coordinates.longitude() > 1.7262638915 && coordinates.longitude() < 1.7262638917); assert!(coordinates.latitude() > 0.0000002082 && coordinates.latitude() < 0.0000002084); assert!(coordinates.distance() > 0.98322705 && coordinates.distance() < 0.98322781); let coordinates = vsop87d::earth(2341970.0); assert!(coordinates.longitude() > 1.7134419104 && coordinates.longitude() < 1.7134419106); assert!(coordinates.latitude() > 0.0000025050 && coordinates.latitude() < 0.0000025052); assert!(coordinates.distance() > 0.98314946 && coordinates.distance() < 0.98315022); let coordinates = vsop87d::earth(2305445.0); assert!(coordinates.longitude() > 1.7006065937 && coordinates.longitude() < 1.7006065939); assert!(coordinates.latitude() > -0.0000016360 && coordinates.latitude() < -0.0000016358); assert!(coordinates.distance() > 0.98312506 && coordinates.distance() < 0.98312582); let coordinates = vsop87d::earth(2268920.0); assert!(coordinates.longitude() > 1.6877624959 && coordinates.longitude() < 1.6877624961); assert!(coordinates.latitude() > -0.0000020341 && coordinates.latitude() < -0.0000020339); assert!(coordinates.distance() > 0.98308130 && coordinates.distance() < 0.98308206); let coordinates = vsop87d::earth(2232395.0); assert!(coordinates.longitude() > 1.6750110960 && coordinates.longitude() < 1.6750110962); assert!(coordinates.latitude() > 0.0000037878 && coordinates.latitude() < 0.0000037880); assert!(coordinates.distance() > 0.98307506 && coordinates.distance() < 0.98307582); let coordinates = vsop87d::earth(2195870.0); assert!(coordinates.longitude() > 1.6622048656 && coordinates.longitude() < 1.6622048658); assert!(coordinates.latitude() > 0.0000015132 && coordinates.latitude() < 0.0000015134); assert!(coordinates.distance() > 0.98309386 && coordinates.distance() < 0.98309462); let coordinates = vsop87d::earth(2159345.0); assert!(coordinates.longitude() > 1.6495143196 && coordinates.longitude() < 1.6495143198); assert!(coordinates.latitude() > -0.0000013004 && coordinates.latitude() < -0.0000013002); assert!(coordinates.distance() > 0.98304366 && coordinates.distance() < 0.98304442); let coordinates = vsop87d::earth(2122820.0); assert!(coordinates.longitude() > 1.6367193622 && coordinates.longitude() < 1.6367193624); assert!(coordinates.latitude() > -0.0000031293 && coordinates.latitude() < -0.0000031291); assert!(coordinates.distance() > 0.98303280 && coordinates.distance() < 0.98303356); } #[test] fn it_mars() { let coordinates = vsop87d::mars(2451545.0); assert!(coordinates.longitude() > 6.2735389982 && coordinates.longitude() < 6.2735389984); assert!(coordinates.latitude() > -0.0247779825 && coordinates.latitude() < -0.0247779823); assert!(coordinates.distance() > 1.39120731 && coordinates.distance() < 1.39120807); let coordinates = vsop87d::mars(2415020.0); assert!(coordinates.longitude() > 4.9942005210 && coordinates.longitude() < 4.9942005212); assert!(coordinates.latitude() > -0.0271965870 && coordinates.latitude() < -0.0271965868); assert!(coordinates.distance() > 1.42187739 && coordinates.distance() < 1.42187815); let coordinates = vsop87d::mars(2378495.0); assert!(coordinates.longitude() > 3.8711855477 && coordinates.longitude() < 3.8711855479); assert!(coordinates.latitude() > 0.0034969938 && coordinates.latitude() < 0.0034969940); assert!(coordinates.distance() > 1.56151362 && coordinates.distance() < 1.56151438); let coordinates = vsop87d::mars(2341970.0); assert!(coordinates.longitude() > 2.9166648689 && coordinates.longitude() < 2.9166648691); assert!(coordinates.latitude() > 0.0280268148 && coordinates.latitude() < 0.0280268150); assert!(coordinates.distance() > 1.65846933 && coordinates.distance() < 1.65847009); let coordinates = vsop87d::mars(2305445.0); assert!(coordinates.longitude() > 2.0058210393 && coordinates.longitude() < 2.0058210395); assert!(coordinates.latitude() > 0.0300702180 && coordinates.latitude() < 0.0300702182); assert!(coordinates.distance() > 1.63719934 && coordinates.distance() < 1.63720010); let coordinates = vsop87d::mars(2268920.0); assert!(coordinates.longitude() > 1.0050966938 && coordinates.longitude() < 1.0050966940); assert!(coordinates.latitude() > 0.0066676097 && coordinates.latitude() < 0.0066676099); assert!(coordinates.distance() > 1.51236189 && coordinates.distance() < 1.51236265); let coordinates = vsop87d::mars(2232395.0); assert!(coordinates.longitude() > 6.0979760761 && coordinates.longitude() < 6.0979760763); assert!(coordinates.latitude() > -0.0266794244 && coordinates.latitude() < -0.0266794242); assert!(coordinates.distance() > 1.39259607 && coordinates.distance() < 1.39259683); let coordinates = vsop87d::mars(2195870.0); assert!(coordinates.longitude() > 4.8193924947 && coordinates.longitude() < 4.8193924949); assert!(coordinates.latitude() > -0.0255031924 && coordinates.latitude() < -0.0255031922); assert!(coordinates.distance() > 1.42087034 && coordinates.distance() < 1.42087110); let coordinates = vsop87d::mars(2159345.0); assert!(coordinates.longitude() > 3.6939294874 && coordinates.longitude() < 3.6939294876); assert!(coordinates.latitude() > 0.0065885508 && coordinates.latitude() < 0.0065885510); assert!(coordinates.distance() > 1.55937982 && coordinates.distance() < 1.55938058); let coordinates = vsop87d::mars(2122820.0); assert!(coordinates.longitude() > 2.7367104343 && coordinates.longitude() < 2.7367104345); assert!(coordinates.latitude() > 0.0295522718 && coordinates.latitude() < 0.0295522720); assert!(coordinates.distance() > 1.65709985 && coordinates.distance() < 1.65710061); } #[test] fn it_jupiter() { let coordinates = vsop87d::jupiter(2451545.0); assert!(coordinates.longitude() > 0.6334614185 && coordinates.longitude() < 0.6334614187); assert!(coordinates.latitude() > -0.0205001040 && coordinates.latitude() < -0.0205001038); assert!(coordinates.distance() > 4.96538094 && coordinates.distance() < 4.96538170); let coordinates = vsop87d::jupiter(2415020.0); assert!(coordinates.longitude() > 4.0927527023 && coordinates.longitude() < 4.0927527025); assert!(coordinates.latitude() > 0.0161446617 && coordinates.latitude() < 0.0161446619); assert!(coordinates.distance() > 5.38502729 && coordinates.distance() < 5.38502805); let coordinates = vsop87d::jupiter(2378495.0); assert!(coordinates.longitude() > 1.5255696770 && coordinates.longitude() < 1.5255696772); assert!(coordinates.latitude() > -0.0043606937 && coordinates.latitude() < -0.0043606935); assert!(coordinates.distance() > 5.13184538 && coordinates.distance() < 5.13184614); let coordinates = vsop87d::jupiter(2341970.0); assert!(coordinates.longitude() > 4.8888943124 && coordinates.longitude() < 4.8888943126); assert!(coordinates.latitude() > -0.0011098086 && coordinates.latitude() < -0.0011098084); assert!(coordinates.distance() > 5.18881299 && coordinates.distance() < 5.18881375); let coordinates = vsop87d::jupiter(2305445.0); assert!(coordinates.longitude() > 2.3348832683 && coordinates.longitude() < 2.3348832685); assert!(coordinates.latitude() > 0.0140523906 && coordinates.latitude() < 0.0140523908); assert!(coordinates.distance() > 5.34394512 && coordinates.distance() < 5.34394588); let coordinates = vsop87d::jupiter(2268920.0); assert!(coordinates.longitude() > 5.7527666851 && coordinates.longitude() < 5.7527666853); assert!(coordinates.latitude() > -0.0188346312 && coordinates.latitude() < -0.0188346310); assert!(coordinates.distance() > 5.00180036 && coordinates.distance() < 5.00180112); let coordinates = vsop87d::jupiter(2232395.0); assert!(coordinates.longitude() > 3.0889515349 && coordinates.longitude() < 3.0889515351); assert!(coordinates.latitude() > 0.0231157946 && coordinates.latitude() < 0.0231157948); assert!(coordinates.distance() > 5.44915664 && coordinates.distance() < 5.44915740); let coordinates = vsop87d::jupiter(2195870.0); assert!(coordinates.longitude() > 0.3776503429 && coordinates.longitude() < 0.3776503431); assert!(coordinates.latitude() > -0.0222448937 && coordinates.latitude() < -0.0222448935); assert!(coordinates.distance() > 4.97150672 && coordinates.distance() < 4.97150748); let coordinates = vsop87d::jupiter(2159345.0); assert!(coordinates.longitude() > 3.8455069136 && coordinates.longitude() < 3.8455069138); assert!(coordinates.latitude() > 0.0185554472 && coordinates.latitude() < 0.0185554474); assert!(coordinates.distance() > 5.38962031 && coordinates.distance() < 5.38962107); let coordinates = vsop87d::jupiter(2122820.0); assert!(coordinates.longitude() > 1.2695066545 && coordinates.longitude() < 1.2695066547); assert!(coordinates.latitude() > -0.0075335741 && coordinates.latitude() < -0.0075335739); assert!(coordinates.distance() > 5.11935836 && coordinates.distance() < 5.11935912); } #[test] fn it_saturn() { let coordinates = vsop87d::saturn(2451545.0); assert!(coordinates.longitude() > 0.7980038760 && coordinates.longitude() < 0.7980038762); assert!(coordinates.latitude() > -0.0401984150 && coordinates.latitude() < -0.0401984148); assert!(coordinates.distance() > 9.18384799 && coordinates.distance() < 9.18384875); let coordinates = vsop87d::saturn(2415020.0); assert!(coordinates.longitude() > 4.6512836346 && coordinates.longitude() < 4.6512836348); assert!(coordinates.latitude() > 0.0192701408 && coordinates.latitude() < 0.0192701410); assert!(coordinates.distance() > 10.06685282 && coordinates.distance() < 10.06685358); let coordinates = vsop87d::saturn(2378495.0); assert!(coordinates.longitude() > 2.1956677358 && coordinates.longitude() < 2.1956677360); assert!(coordinates.latitude() > 0.0104156565 && coordinates.latitude() < 0.0104156567); assert!(coordinates.distance() > 9.10430648 && coordinates.distance() < 9.10430724); let coordinates = vsop87d::saturn(2341970.0); assert!(coordinates.longitude() > 5.8113963636 && coordinates.longitude() < 5.8113963638); assert!(coordinates.latitude() > -0.0291472788 && coordinates.latitude() < -0.0291472786); assert!(coordinates.distance() > 9.76299911 && coordinates.distance() < 9.76299987); let coordinates = vsop87d::saturn(2305445.0); assert!(coordinates.longitude() > 3.5217555198 && coordinates.longitude() < 3.5217555200); assert!(coordinates.latitude() > 0.0437035057 && coordinates.latitude() < 0.0437035059); assert!(coordinates.distance() > 9.75710318 && coordinates.distance() < 9.75710394); let coordinates = vsop87d::saturn(2268920.0); assert!(coordinates.longitude() > 0.8594235307 && coordinates.longitude() < 0.8594235309); assert!(coordinates.latitude() > -0.0379350089 && coordinates.latitude() < -0.0379350087); assert!(coordinates.distance() > 9.06692090 && coordinates.distance() < 9.06692166); let coordinates = vsop87d::saturn(2232395.0); assert!(coordinates.longitude() > 4.6913199263 && coordinates.longitude() < 4.6913199265); assert!(coordinates.latitude() > 0.0146771897 && coordinates.latitude() < 0.0146771899); assert!(coordinates.distance() > 10.10656892 && coordinates.distance() < 10.10656968); let coordinates = vsop87d::saturn(2195870.0); assert!(coordinates.longitude() > 2.2948875822 && coordinates.longitude() < 2.2948875824); assert!(coordinates.latitude() > 0.0178533696 && coordinates.latitude() < 0.0178533698); assert!(coordinates.distance() > 9.18575957 && coordinates.distance() < 9.18576033); let coordinates = vsop87d::saturn(2159345.0); assert!(coordinates.longitude() > 5.8660241563 && coordinates.longitude() < 5.8660241565); assert!(coordinates.latitude() > -0.0333866504 && coordinates.latitude() < -0.0333866502); assert!(coordinates.distance() > 9.59271701 && coordinates.distance() < 9.59271777); let coordinates = vsop87d::saturn(2122820.0); assert!(coordinates.longitude() > 3.5570108068 && coordinates.longitude() < 3.5570108070); assert!(coordinates.latitude() > 0.0435371138 && coordinates.latitude() < 0.0435371140); assert!(coordinates.distance() > 9.86699357 && coordinates.distance() < 9.86699433); } #[test] fn it_uranus() { let coordinates = vsop87d::uranus(2451545.0); assert!(coordinates.longitude() > 5.5225485802 && coordinates.longitude() < 5.5225485804); assert!(coordinates.latitude() > -0.0119527839 && coordinates.latitude() < -0.0119527837); assert!(coordinates.distance() > 19.92404789 && coordinates.distance() < 19.92404865); let coordinates = vsop87d::uranus(2415020.0); assert!(coordinates.longitude() > 4.3397761172 && coordinates.longitude() < 4.3397761174); assert!(coordinates.latitude() > 0.0011570306 && coordinates.latitude() < 0.0011570308); assert!(coordinates.distance() > 18.99271598 && coordinates.distance() < 18.99271674); let coordinates = vsop87d::uranus(2378495.0); assert!(coordinates.longitude() > 3.0388348557 && coordinates.longitude() < 3.0388348559); assert!(coordinates.latitude() > 0.0132392954 && coordinates.latitude() < 0.0132392956); assert!(coordinates.distance() > 18.29911506 && coordinates.distance() < 18.29911582); let coordinates = vsop87d::uranus(2341970.0); assert!(coordinates.longitude() > 1.7242204719 && coordinates.longitude() < 1.7242204721); assert!(coordinates.latitude() > 0.0059836564 && coordinates.latitude() < 0.0059836566); assert!(coordinates.distance() > 18.79662051 && coordinates.distance() < 18.79662127); let coordinates = vsop87d::uranus(2305445.0); assert!(coordinates.longitude() > 0.5223325213 && coordinates.longitude() < 0.5223325215); assert!(coordinates.latitude() > -0.0089983886 && coordinates.latitude() < -0.0089983884); assert!(coordinates.distance() > 19.78198789 && coordinates.distance() < 19.78198865); let coordinates = vsop87d::uranus(2268920.0); assert!(coordinates.longitude() > 5.6817615581 && coordinates.longitude() < 5.6817615583); assert!(coordinates.latitude() > -0.0129257255 && coordinates.latitude() < -0.0129257253); assert!(coordinates.distance() > 20.03004592 && coordinates.distance() < 20.03004668); let coordinates = vsop87d::uranus(2232395.0); assert!(coordinates.longitude() > 4.5254482962 && coordinates.longitude() < 4.5254482964); assert!(coordinates.latitude() > -0.0019303341 && coordinates.latitude() < -0.0019303339); assert!(coordinates.distance() > 19.26943073 && coordinates.distance() < 19.26943149); let coordinates = vsop87d::uranus(2195870.0); assert!(coordinates.longitude() > 3.2557221719 && coordinates.longitude() < 3.2557221721); assert!(coordinates.latitude() > 0.0120919638 && coordinates.latitude() < 0.0120919640); assert!(coordinates.distance() > 18.39482248 && coordinates.distance() < 18.39482324); let coordinates = vsop87d::uranus(2159345.0); assert!(coordinates.longitude() > 1.9333853934 && coordinates.longitude() < 1.9333853936); assert!(coordinates.latitude() > 0.0088045917 && coordinates.latitude() < 0.0088045919); assert!(coordinates.distance() > 18.58414975 && coordinates.distance() < 18.58415051); let coordinates = vsop87d::uranus(2122820.0); assert!(coordinates.longitude() > 0.7007226223 && coordinates.longitude() < 0.7007226225); assert!(coordinates.latitude() > -0.0065610612 && coordinates.latitude() < -0.0065610610); assert!(coordinates.distance() > 19.56120745 && coordinates.distance() < 19.56120821); } #[test] fn it_neptune() { let coordinates = vsop87d::neptune(2451545.0); assert!(coordinates.longitude() > 5.3045629251 && coordinates.longitude() < 5.3045629253); assert!(coordinates.latitude() > 0.0042236788 && coordinates.latitude() < 0.0042236790); assert!(coordinates.distance() > 30.12053246 && coordinates.distance() < 30.12053322); let coordinates = vsop87d::neptune(2415020.0); assert!(coordinates.longitude() > 1.4956195224 && coordinates.longitude() < 1.4956195226); assert!(coordinates.latitude() > -0.0219610031 && coordinates.latitude() < -0.0219610029); assert!(coordinates.distance() > 29.87103413 && coordinates.distance() < 29.87103489); let coordinates = vsop87d::neptune(2378495.0); assert!(coordinates.longitude() > 3.9290537976 && coordinates.longitude() < 3.9290537978); assert!(coordinates.latitude() > 0.0310692111 && coordinates.latitude() < 0.0310692113); assert!(coordinates.distance() > 30.32091885 && coordinates.distance() < 30.32091961); let coordinates = vsop87d::neptune(2341970.0); assert!(coordinates.longitude() > 0.0815199678 && coordinates.longitude() < 0.0815199680); assert!(coordinates.latitude() > -0.0260752534 && coordinates.latitude() < -0.0260752532); assert!(coordinates.distance() > 29.86858567 && coordinates.distance() < 29.86858643); let coordinates = vsop87d::neptune(2305445.0); assert!(coordinates.longitude() > 2.5537079777 && coordinates.longitude() < 2.5537079779); assert!(coordinates.latitude() > 0.0102374009 && coordinates.latitude() < 0.0102374011); assert!(coordinates.distance() > 30.13601549 && coordinates.distance() < 30.13601625); let coordinates = vsop87d::neptune(2268920.0); assert!(coordinates.longitude() > 4.9678695784 && coordinates.longitude() < 4.9678695786); assert!(coordinates.latitude() > 0.0116907776 && coordinates.latitude() < 0.0116907778); assert!(coordinates.distance() > 30.17853464 && coordinates.distance() < 30.17853540); let coordinates = vsop87d::neptune(2232395.0); assert!(coordinates.longitude() > 1.1523661583 && coordinates.longitude() < 1.1523661585); assert!(coordinates.latitude() > -0.0273547726 && coordinates.latitude() < -0.0273547724); assert!(coordinates.distance() > 29.83260514 && coordinates.distance() < 29.83260590); let coordinates = vsop87d::neptune(2195870.0); assert!(coordinates.longitude() > 3.5930943432 && coordinates.longitude() < 3.5930943434); assert!(coordinates.latitude() > 0.0316878974 && coordinates.latitude() < 0.0316878976); assert!(coordinates.distance() > 30.31091112 && coordinates.distance() < 30.31091188); let coordinates = vsop87d::neptune(2159345.0); assert!(coordinates.longitude() > 6.0203596579 && coordinates.longitude() < 6.0203596581); assert!(coordinates.latitude() > -0.0215169843 && coordinates.latitude() < -0.0215169841); assert!(coordinates.distance() > 29.90655030 && coordinates.distance() < 29.90655106); let coordinates = vsop87d::neptune(2122820.0); assert!(coordinates.longitude() > 2.2124988266 && coordinates.longitude() < 2.2124988268); assert!(coordinates.latitude() > 0.0027498092 && coordinates.latitude() < 0.0027498094); assert!(coordinates.distance() > 30.06536898 && coordinates.distance() < 30.06536974); }
52.633136
94
0.699232
6a45a67ee03f373a640b11e07d9a795e2db27aec
6,912
// Copyright (c) 2017 Isobel Redelmeier // Copyright (c) 2021 Miguel Barreto // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. use std::env; use std::ffi::OsString; use std::fs::{self, File, OpenOptions, Permissions}; use std::io::{Read, Result, Write}; #[cfg(unix)] use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; #[cfg(feature = "temp")] use tempdir; #[cfg(unix)] use UnixFileSystem; use {DirEntry, FileSystem, ReadDir}; #[cfg(feature = "temp")] use {TempDir, TempFileSystem}; /// Tracks a temporary directory that will be deleted once the struct goes out of scope. /// /// This is a wrapper around a [`TempDir`]. /// /// [`TempDir`]: https://doc.rust-lang.org/tempdir/tempdir/struct.TempDir.html #[cfg(feature = "temp")] #[derive(Debug)] pub struct OsTempDir(tempdir::TempDir); #[cfg(feature = "temp")] impl TempDir for OsTempDir { fn path(&self) -> &Path { self.0.path() } } /// An implementation of `FileSystem` that interacts with the actual operating system's file system. /// /// This is primarily a wrapper for [`fs`] methods. /// /// [`fs`]: https://doc.rust-lang.org/std/fs/index.html #[derive(Clone, Debug, Default)] pub struct OsFileSystem {} impl OsFileSystem { pub fn new() -> Self { OsFileSystem {} } } impl FileSystem for OsFileSystem { type DirEntry = fs::DirEntry; type ReadDir = fs::ReadDir; fn current_dir(&self) -> Result<PathBuf> { env::current_dir() } fn set_current_dir<P: AsRef<Path>>(&self, path: P) -> Result<()> { env::set_current_dir(path) } fn is_dir<P: AsRef<Path>>(&self, path: P) -> bool { path.as_ref().is_dir() } fn is_file<P: AsRef<Path>>(&self, path: P) -> bool { path.as_ref().is_file() } fn create_dir<P: AsRef<Path>>(&self, path: P) -> Result<()> { fs::create_dir(path) } fn create_dir_all<P: AsRef<Path>>(&self, path: P) -> Result<()> { fs::create_dir_all(path) } fn remove_dir<P: AsRef<Path>>(&self, path: P) -> Result<()> { fs::remove_dir(path) } fn remove_dir_all<P: AsRef<Path>>(&self, path: P) -> Result<()> { fs::remove_dir_all(path) } fn read_dir<P: AsRef<Path>>(&self, path: P) -> Result<Self::ReadDir> { fs::read_dir(path) } fn write_file<P, B>(&self, path: P, buf: B) -> Result<()> where P: AsRef<Path>, B: AsRef<[u8]>, { let mut file = File::create(path)?; file.write_all(buf.as_ref()) } fn overwrite_file<P, B>(&self, path: P, buf: B) -> Result<()> where P: AsRef<Path>, B: AsRef<[u8]>, { let mut file = OpenOptions::new().write(true).truncate(true).open(path)?; file.write_all(buf.as_ref()) } fn read_file<P: AsRef<Path>>(&self, path: P) -> Result<Vec<u8>> { let mut contents = Vec::<u8>::new(); let mut file = File::open(path)?; file.read_to_end(&mut contents)?; Ok(contents) } fn read_file_into<P, B>(&self, path: P, mut buf: B) -> Result<usize> where P: AsRef<Path>, B: AsMut<Vec<u8>>, { let mut file = File::open(path)?; file.read_to_end(buf.as_mut()) } fn read_file_to_string<P: AsRef<Path>>(&self, path: P) -> Result<String> { let mut contents = String::new(); let mut file = File::open(path)?; file.read_to_string(&mut contents)?; Ok(contents) } fn create_file<P, B>(&self, path: P, buf: B) -> Result<()> where P: AsRef<Path>, B: AsRef<[u8]>, { let mut file = OpenOptions::new().write(true).create_new(true).open(path)?; file.write_all(buf.as_ref()) } fn remove_file<P: AsRef<Path>>(&self, path: P) -> Result<()> { fs::remove_file(path) } fn copy_file<P, Q>(&self, from: P, to: Q) -> Result<()> where P: AsRef<Path>, Q: AsRef<Path>, { fs::copy(from, to).and(Ok(())) } fn rename<P, Q>(&self, from: P, to: Q) -> Result<()> where P: AsRef<Path>, Q: AsRef<Path>, { fs::rename(from, to) } fn readonly<P: AsRef<Path>>(&self, path: P) -> Result<bool> { permissions(path.as_ref()).map(|p| p.readonly()) } fn set_readonly<P: AsRef<Path>>(&self, path: P, readonly: bool) -> Result<()> { let mut permissions = permissions(path.as_ref())?; permissions.set_readonly(readonly); fs::set_permissions(path, permissions) } fn len<P: AsRef<Path>>(&self, path: P) -> u64 { fs::metadata(path.as_ref()).map(|md| md.len()).unwrap_or(0) } } impl DirEntry for fs::DirEntry { fn file_name(&self) -> OsString { self.file_name() } fn path(&self) -> PathBuf { self.path() } } impl ReadDir<fs::DirEntry> for fs::ReadDir {} #[cfg(unix)] impl UnixFileSystem for OsFileSystem { fn mode<P: AsRef<Path>>(&self, path: P) -> Result<u32> { permissions(path.as_ref()).map(|p| p.mode()) } fn set_mode<P: AsRef<Path>>(&self, path: P, mode: u32) -> Result<()> { let mut permissions = permissions(path.as_ref())?; permissions.set_mode(mode); fs::set_permissions(path, permissions) } fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, dst: Q) -> Result<()> { std::os::unix::fs::symlink(src, dst) } fn get_symlink_src<P: AsRef<Path>>(&self, dst: P) -> Result<PathBuf> { std::fs::read_link(dst) } } #[cfg(feature = "temp")] impl TempFileSystem for OsFileSystem { type TempDir = OsTempDir; fn temp_dir<S: AsRef<str>>(&self, prefix: S) -> Result<Self::TempDir> { tempdir::TempDir::new(prefix.as_ref()).map(OsTempDir) } } fn permissions(path: &Path) -> Result<Permissions> { let metadata = fs::metadata(path)?; Ok(metadata.permissions()) }
27.759036
100
0.603733
336fe345954b0bd0fcb363858722c14a164b977c
3,244
/** * [210] Course Schedule II * * There are a total of n courses you have to take, labeled from 0 to n-1. * * Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] * * Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses. * * There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array. * * Example 1: * * * Input: 2, [[1,0]] * Output: [0,1] * Explanation: There are a total of 2 courses to take. To take course 1 you should have finished * course 0. So the correct course order is [0,1] . * * Example 2: * * * Input: 4, [[1,0],[2,0],[3,1],[3,2]] * Output: [0,1,2,3] or [0,2,1,3] * Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both * courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. * So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3] . * * Note: * * <ol> * The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about <a href="https://www.khanacademy.org/computing/computer-science/algorithms/graph-representation/a/representing-graphs" target="_blank">how a graph is represented</a>. * You may assume that there are no duplicate edges in the input prerequisites. * </ol> * */ pub struct Solution {} // submission codes start here use std::collections::VecDeque; impl Solution { pub fn find_order(num_courses: i32, prerequisites: Vec<Vec<i32>>) -> Vec<i32> { let num = num_courses as usize; let mut matrix = vec![vec![false; num]; num]; let mut in_degree = vec![0; num]; // collects node in degree for pre in prerequisites.iter() { if !matrix[pre[1] as usize][pre[0] as usize] { in_degree[pre[0] as usize] += 1; } matrix[pre[1] as usize][pre[0] as usize] = true; } let mut deq = VecDeque::new(); // BFS starts with nodes with 0 in degree for (node, &v) in in_degree.iter().enumerate() { if v == 0 { deq.push_back(node); } } let mut res = Vec::with_capacity(num); while let Some(node) = deq.pop_front() { res.push(node as i32); for (i, &connect) in matrix[node].iter().enumerate() { if connect { in_degree[i] -= 1; if in_degree[i] == 0 { deq.push_back(i); } } } } if res.len() == num { res } else { vec![] } } } // submission codes end #[cfg(test)] mod tests { use super::*; #[test] fn test_210() { assert_eq!(Solution::find_order(2, vec![vec![1, 0]]), vec![0, 1]); assert_eq!( Solution::find_order(4, vec![vec![1, 0], vec![2, 0], vec![3, 1], vec![3, 2]]), vec![0, 1, 2, 3] ); } }
33.791667
277
0.564735
118a4977ed4585bccf8bfdf8f126066078c11f5e
1,670
// Copyright 2021. 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 serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] pub struct RpcError { pub code: i32, pub message: String, }
55.666667
118
0.777844
f7d0ece1999f1cd790e59804be0369d2989012ad
967
use nu_engine::get_full_help; use nu_protocol::{ ast::Call, engine::{Command, EngineState, Stack}, Category, IntoPipelineData, PipelineData, Signature, Value, }; #[derive(Clone)] pub struct RandomCommand; impl Command for RandomCommand { fn name(&self) -> &str { "random" } fn signature(&self) -> Signature { Signature::build("random").category(Category::Random) } fn usage(&self) -> &str { "Generate a random values." } fn run( &self, engine_state: &EngineState, _stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> { Ok(Value::String { val: get_full_help( &RandomCommand.signature(), &RandomCommand.examples(), engine_state, ), span: call.head, } .into_pipeline_data()) } }
23.02381
69
0.559462
e9e6f922417e1268ae83381ca03485776da5df19
4,925
#![allow(clippy::module_inception)] #![allow(clippy::upper_case_acronyms)] #![allow(clippy::large_enum_variant)] #![allow(clippy::wrong_self_convention)] #![allow(clippy::should_implement_trait)] #![allow(clippy::blacklisted_name)] //! <fullname>WAF</fullname> //! <note> //! <p>This is the latest version of the <b>WAF</b> API, //! released in November, 2019. The names of the entities that you use to access this API, //! like endpoints and namespaces, all have the versioning information added, like "V2" or //! "v2", to distinguish from the prior version. We recommend migrating your resources to //! this version, because it has a number of significant improvements.</p> //! <p>If you used WAF prior to this release, you can't use this WAFV2 API to access any //! WAF resources that you created before. You can access your old rules, web ACLs, and //! other WAF resources only through the WAF Classic APIs. The WAF Classic APIs //! have retained the prior names, endpoints, and namespaces. </p> //! <p>For information, including how to migrate your WAF resources to this version, //! see the <a href="https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html">WAF Developer Guide</a>. </p> //! </note> //! <p>WAF is a web application firewall that lets you monitor the HTTP and HTTPS //! requests that are forwarded to Amazon CloudFront, an Amazon API Gateway REST API, an Application Load Balancer, or an AppSync //! GraphQL API. WAF also lets you control access to your content. Based on conditions that //! you specify, such as the IP addresses that requests originate from or the values of query //! strings, the Amazon API Gateway REST API, CloudFront distribution, the Application Load Balancer, or the AppSync GraphQL //! API responds to requests either with the requested content or with an HTTP 403 status code //! (Forbidden). You also can configure CloudFront to return a custom error page when a request is //! blocked.</p> //! <p>This API guide is for developers who need detailed information about WAF API actions, //! data types, and errors. For detailed information about WAF features and an overview of //! how to use WAF, see the <a href="https://docs.aws.amazon.com/waf/latest/developerguide/what-is-aws-waf.html">WAF Developer //! Guide</a>.</p> //! <p>You can make calls using the endpoints listed in <a href="https://docs.aws.amazon.com/general/latest/gr/waf.html">WAF endpoints and quotas</a>. </p> //! <ul> //! <li> //! <p>For regional applications, you can use any of the endpoints in the list. //! A regional application can be an Application Load Balancer (ALB), an Amazon API Gateway REST API, or an AppSync GraphQL API. </p> //! </li> //! <li> //! <p>For Amazon CloudFront applications, you must use the API endpoint listed for //! US East (N. Virginia): us-east-1.</p> //! </li> //! </ul> //! <p>Alternatively, you can use one of the Amazon Web Services SDKs to access an API that's tailored to the //! programming language or platform that you're using. For more information, see <a href="http://aws.amazon.com/tools/#SDKs">Amazon Web Services SDKs</a>.</p> //! <p>We currently provide two versions of the WAF API: this API and the prior versions, //! the classic WAF APIs. This new API provides the same functionality as the older versions, //! with the following major improvements:</p> //! <ul> //! <li> //! <p>You use one API for both global and regional applications. Where you need to //! distinguish the scope, you specify a <code>Scope</code> parameter and set it to //! <code>CLOUDFRONT</code> or <code>REGIONAL</code>. </p> //! </li> //! <li> //! <p>You can define a web ACL or rule group with a single call, and update it with a //! single call. You define all rule specifications in JSON format, and pass them to your //! rule group or web ACL calls.</p> //! </li> //! <li> //! <p>The limits WAF places on the use of rules more closely reflects the cost of //! running each type of rule. Rule groups include capacity settings, so you know the //! maximum cost of a rule group when you use it.</p> //! </li> //! </ul> // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use error_meta::Error; pub use config::Config; mod aws_endpoint; #[cfg(feature = "client")] pub mod client; pub mod config; pub mod error; mod error_meta; pub mod input; mod json_deser; mod json_errors; mod json_ser; pub mod model; pub mod operation; mod operation_deser; mod operation_ser; pub mod output; pub static PKG_VERSION: &str = env!("CARGO_PKG_VERSION"); pub use smithy_http::byte_stream::ByteStream; pub use smithy_http::result::SdkError; pub use smithy_types::Blob; static API_METADATA: aws_http::user_agent::ApiMetadata = aws_http::user_agent::ApiMetadata::new("wafv2", PKG_VERSION); pub use aws_auth::Credentials; pub use aws_types::region::Region; #[cfg(feature = "client")] pub use client::Client; pub use smithy_http::endpoint::Endpoint;
50.255102
159
0.730964
267010d85630cf974d17e40707fce0c382310757
9,365
// 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. //! Utility functions to build Grin transactions. Handles the blinding of //! inputs and outputs, maintaining the sum of blinding factors, producing //! the excess signature, etc. //! //! Each building function is a combinator that produces a function taking //! a transaction a sum of blinding factors, to return another transaction //! and sum. Combinators can then be chained and executed using the //! _transaction_ function. //! //! Example: //! build::transaction(vec![input_rand(75), output_rand(42), output_rand(32), //! with_fee(1)]) use crate::core::{Input, Output, OutputFeatures, Transaction, TxKernel}; use crate::keychain::{BlindSum, BlindingFactor, Identifier, Keychain}; use crate::libtx::{aggsig, proof, Error}; /// Context information available to transaction combinators. pub struct Context<'a, K> where K: Keychain, { keychain: &'a K, } /// Function type returned by the transaction combinators. Transforms a /// (Transaction, BlindSum) pair into another, provided some context. pub type Append<K> = dyn for<'a> Fn( &'a mut Context<'_, K>, (Transaction, TxKernel, BlindSum), ) -> (Transaction, TxKernel, BlindSum); /// Adds an input with the provided value and blinding key to the transaction /// being built. fn build_input<K>(value: u64, features: OutputFeatures, key_id: Identifier) -> Box<Append<K>> where K: Keychain, { Box::new( move |build, (tx, kern, sum)| -> (Transaction, TxKernel, BlindSum) { let commit = build.keychain.commit(value, &key_id).unwrap(); let input = Input::new(features, commit); (tx.with_input(input), kern, sum.sub_key_id(key_id.to_path())) }, ) } /// Adds an input with the provided value and blinding key to the transaction /// being built. pub fn input<K>(value: u64, key_id: Identifier) -> Box<Append<K>> where K: Keychain, { debug!( "Building input (spending regular output): {}, {}", value, key_id ); build_input(value, OutputFeatures::DEFAULT_OUTPUT, key_id) } /// Adds a coinbase input spending a coinbase output. pub fn coinbase_input<K>(value: u64, key_id: Identifier) -> Box<Append<K>> where K: Keychain, { debug!("Building input (spending coinbase): {}, {}", value, key_id); build_input(value, OutputFeatures::COINBASE_OUTPUT, key_id) } /// Adds an output with the provided value and key identifier from the /// keychain. pub fn output<K>(value: u64, key_id: Identifier) -> Box<Append<K>> where K: Keychain, { Box::new( move |build, (tx, kern, sum)| -> (Transaction, TxKernel, BlindSum) { let commit = build.keychain.commit(value, &key_id).unwrap(); debug!("Building output: {}, {:?}", value, commit); let rproof = proof::create(build.keychain, value, &key_id, commit, None).unwrap(); ( tx.with_output(Output { features: OutputFeatures::DEFAULT_OUTPUT, commit: commit, proof: rproof, }), kern, sum.add_key_id(key_id.to_path()), ) }, ) } /// Sets the fee on the transaction being built. pub fn with_fee<K>(fee: u64) -> Box<Append<K>> where K: Keychain, { Box::new( move |_build, (tx, kern, sum)| -> (Transaction, TxKernel, BlindSum) { (tx, kern.with_fee(fee), sum) }, ) } /// Sets the lock_height on the transaction being built. pub fn with_lock_height<K>(lock_height: u64) -> Box<Append<K>> where K: Keychain, { Box::new( move |_build, (tx, kern, sum)| -> (Transaction, TxKernel, BlindSum) { (tx, kern.with_lock_height(lock_height), sum) }, ) } /// Adds a known excess value on the transaction being built. Usually used in /// combination with the initial_tx function when a new transaction is built /// by adding to a pre-existing one. pub fn with_excess<K>(excess: BlindingFactor) -> Box<Append<K>> where K: Keychain, { Box::new( move |_build, (tx, kern, sum)| -> (Transaction, TxKernel, BlindSum) { (tx, kern, sum.add_blinding_factor(excess.clone())) }, ) } /// Sets a known tx "offset". Used in final step of tx construction. pub fn with_offset<K>(offset: BlindingFactor) -> Box<Append<K>> where K: Keychain, { Box::new( move |_build, (tx, kern, sum)| -> (Transaction, TxKernel, BlindSum) { (tx.with_offset(offset), kern, sum) }, ) } /// Sets an initial transaction to add to when building a new transaction. /// We currently only support building a tx with a single kernel with /// build::transaction() pub fn initial_tx<K>(mut tx: Transaction) -> Box<Append<K>> where K: Keychain, { assert_eq!(tx.kernels().len(), 1); let kern = tx.kernels_mut().remove(0); Box::new( move |_build, (_, _, sum)| -> (Transaction, TxKernel, BlindSum) { (tx.clone(), kern.clone(), sum) }, ) } /// Builds a new transaction by combining all the combinators provided in a /// Vector. Transactions can either be built "from scratch" with a list of /// inputs or outputs or from a pre-existing transaction that gets added to. /// /// Example: /// let (tx1, sum) = build::transaction(vec![input_rand(4), output_rand(1), /// with_fee(1)], keychain).unwrap(); /// let (tx2, _) = build::transaction(vec![initial_tx(tx1), with_excess(sum), /// output_rand(2)], keychain).unwrap(); /// pub fn partial_transaction<K>( elems: Vec<Box<Append<K>>>, keychain: &K, ) -> Result<(Transaction, BlindingFactor), Error> where K: Keychain, { let mut ctx = Context { keychain }; let (tx, kern, sum) = elems.iter().fold( (Transaction::empty(), TxKernel::empty(), BlindSum::new()), |acc, elem| elem(&mut ctx, acc), ); let blind_sum = ctx.keychain.blind_sum(&sum)?; // we only support building a tx with a single kernel via build::transaction() assert!(tx.kernels().is_empty()); let tx = tx.with_kernel(kern); Ok((tx, blind_sum)) } /// Builds a complete transaction. pub fn transaction<K>(elems: Vec<Box<Append<K>>>, keychain: &K) -> Result<Transaction, Error> where K: Keychain, { let mut ctx = Context { keychain }; let (mut tx, mut kern, sum) = elems.iter().fold( (Transaction::empty(), TxKernel::empty(), BlindSum::new()), |acc, elem| elem(&mut ctx, acc), ); let blind_sum = ctx.keychain.blind_sum(&sum)?; // Split the key so we can generate an offset for the tx. let split = blind_sum.split(&keychain.secp())?; let k1 = split.blind_1; let k2 = split.blind_2; // Construct the message to be signed. let msg = kern.msg_to_sign()?; // Generate kernel excess and excess_sig using the split key k1. let skey = k1.secret_key(&keychain.secp())?; kern.excess = ctx.keychain.secp().commit(0, skey)?; let pubkey = &kern.excess.to_pubkey(&keychain.secp())?; kern.excess_sig = aggsig::sign_with_blinding(&keychain.secp(), &msg, &k1, Some(&pubkey)).unwrap(); // Store the kernel offset (k2) on the tx. // Commitments will sum correctly when accounting for the offset. tx.offset = k2.clone(); // Set the kernel on the tx (assert this is now a single-kernel tx). assert!(tx.kernels().is_empty()); let tx = tx.with_kernel(kern); assert_eq!(tx.kernels().len(), 1); Ok(tx) } // Just a simple test, most exhaustive tests in the core. #[cfg(test)] mod test { use crate::util::RwLock; use std::sync::Arc; use super::*; use crate::core::verifier_cache::{LruVerifierCache, VerifierCache}; use crate::keychain::{ExtKeychain, ExtKeychainPath}; fn verifier_cache() -> Arc<RwLock<dyn VerifierCache>> { Arc::new(RwLock::new(LruVerifierCache::new())) } #[test] fn blind_simple_tx() { let keychain = ExtKeychain::from_random_seed().unwrap(); let key_id1 = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier(); let key_id2 = ExtKeychainPath::new(1, 2, 0, 0, 0).to_identifier(); let key_id3 = ExtKeychainPath::new(1, 3, 0, 0, 0).to_identifier(); let vc = verifier_cache(); let tx = transaction( vec![ input(10, key_id1), input(12, key_id2), output(20, key_id3), with_fee(2), ], &keychain, ) .unwrap(); tx.validate(vc.clone()).unwrap(); } #[test] fn blind_simple_tx_with_offset() { let keychain = ExtKeychain::from_random_seed().unwrap(); let key_id1 = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier(); let key_id2 = ExtKeychainPath::new(1, 2, 0, 0, 0).to_identifier(); let key_id3 = ExtKeychainPath::new(1, 3, 0, 0, 0).to_identifier(); let vc = verifier_cache(); let tx = transaction( vec![ input(10, key_id1), input(12, key_id2), output(20, key_id3), with_fee(2), ], &keychain, ) .unwrap(); tx.validate(vc.clone()).unwrap(); } #[test] fn blind_simpler_tx() { let keychain = ExtKeychain::from_random_seed().unwrap(); let key_id1 = ExtKeychainPath::new(1, 1, 0, 0, 0).to_identifier(); let key_id2 = ExtKeychainPath::new(1, 2, 0, 0, 0).to_identifier(); let vc = verifier_cache(); let tx = transaction( vec![input(6, key_id1), output(2, key_id2), with_fee(4)], &keychain, ) .unwrap(); tx.validate(vc.clone()).unwrap(); } }
28.815385
93
0.679765
ebeeb3b31cd5c4d9f8b5bf19575dc84c7493d615
1,526
//! Delays //! //! # What's the difference between these traits and the `timer::CountDown` trait? //! //! The `Timer` trait provides a *non-blocking* timer abstraction and it's meant to be used to build //! higher level abstractions like I/O operations with timeouts. OTOH, these delays traits only //! provide *blocking* functionality. Note that you can also use the `timer::CountDown` trait to //! implement blocking delays. /// Blocking delay traits pub mod blocking { /// Microsecond delay /// pub trait DelayUs { /// Enumeration of `DelayUs` errors type Error: core::fmt::Debug; /// Pauses execution for at minimum `us` microseconds. Pause can be longer /// if the implementation requires it due to precision/timing issues. fn delay_us(&mut self, us: u32) -> Result<(), Self::Error>; /// Pauses execution for at minimum `ms` milliseconds. Pause can be longer /// if the implementation requires it due to precision/timing issues. fn delay_ms(&mut self, ms: u32) -> Result<(), Self::Error> { for _ in 0..ms { self.delay_us(1000)?; } Ok(()) } } impl<T> DelayUs for &mut T where T: DelayUs, { type Error = T::Error; fn delay_us(&mut self, us: u32) -> Result<(), Self::Error> { T::delay_us(self, us) } fn delay_ms(&mut self, ms: u32) -> Result<(), Self::Error> { T::delay_ms(self, ms) } } }
31.791667
100
0.590433
e89d300c908e6d87ccfbadbef2e27c47986b7229
5,532
// Generated from definition io.k8s.api.flowcontrol.v1alpha1.QueuingConfiguration /// QueuingConfiguration holds the configuration parameters for queuing #[derive(Clone, Debug, Default, PartialEq)] pub struct QueuingConfiguration { /// `handSize` is a small positive number that configures the shuffle sharding of requests into queues. When enqueuing a request at this priority level the request's flow identifier (a string pair) is hashed and the hash value is used to shuffle the list of queues and deal a hand of the size specified here. The request is put into one of the shortest queues in that hand. `handSize` must be no larger than `queues`, and should be significantly smaller (so that a few heavy flows do not saturate most of the queues). See the user-facing documentation for more extensive guidance on setting this field. This field has a default value of 8. pub hand_size: Option<i32>, /// `queueLengthLimit` is the maximum number of requests allowed to be waiting in a given queue of this priority level at a time; excess requests are rejected. This value must be positive. If not specified, it will be defaulted to 50. pub queue_length_limit: Option<i32>, /// `queues` is the number of queues for this priority level. The queues exist independently at each apiserver. The value must be positive. Setting it to 1 effectively precludes shufflesharding and thus makes the distinguisher method of associated flow schemas irrelevant. This field has a default value of 64. pub queues: Option<i32>, } impl<'de> serde::Deserialize<'de> for QueuingConfiguration { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { #[allow(non_camel_case_types)] enum Field { Key_hand_size, Key_queue_length_limit, Key_queues, Other, } impl<'de> serde::Deserialize<'de> for Field { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = Field; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("field identifier") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error { Ok(match v { "handSize" => Field::Key_hand_size, "queueLengthLimit" => Field::Key_queue_length_limit, "queues" => Field::Key_queues, _ => Field::Other, }) } } deserializer.deserialize_identifier(Visitor) } } struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = QueuingConfiguration; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("QueuingConfiguration") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de> { let mut value_hand_size: Option<i32> = None; let mut value_queue_length_limit: Option<i32> = None; let mut value_queues: Option<i32> = None; while let Some(key) = serde::de::MapAccess::next_key::<Field>(&mut map)? { match key { Field::Key_hand_size => value_hand_size = serde::de::MapAccess::next_value(&mut map)?, Field::Key_queue_length_limit => value_queue_length_limit = serde::de::MapAccess::next_value(&mut map)?, Field::Key_queues => value_queues = serde::de::MapAccess::next_value(&mut map)?, Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; }, } } Ok(QueuingConfiguration { hand_size: value_hand_size, queue_length_limit: value_queue_length_limit, queues: value_queues, }) } } deserializer.deserialize_struct( "QueuingConfiguration", &[ "handSize", "queueLengthLimit", "queues", ], Visitor, ) } } impl serde::Serialize for QueuingConfiguration { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer { let mut state = serializer.serialize_struct( "QueuingConfiguration", self.hand_size.as_ref().map_or(0, |_| 1) + self.queue_length_limit.as_ref().map_or(0, |_| 1) + self.queues.as_ref().map_or(0, |_| 1), )?; if let Some(value) = &self.hand_size { serde::ser::SerializeStruct::serialize_field(&mut state, "handSize", value)?; } if let Some(value) = &self.queue_length_limit { serde::ser::SerializeStruct::serialize_field(&mut state, "queueLengthLimit", value)?; } if let Some(value) = &self.queues { serde::ser::SerializeStruct::serialize_field(&mut state, "queues", value)?; } serde::ser::SerializeStruct::end(state) } }
48.526316
647
0.585141
0163293c9d4e56446994f5ec18609c37e5bee805
744
//! This is mostly an internal module, no stability guarantees are provided. Use //! at your own risk. mod traits; mod impls; mod slices; mod closures; pub use self::slices::WasmSlice; pub use self::traits::*; pub struct GlobalStack { next: usize, } impl GlobalStack { #[inline] pub unsafe fn new() -> GlobalStack { GlobalStack { next: 0 } } } impl Stack for GlobalStack { #[inline] fn push(&mut self, val: u32) { use __rt::{ __wbindgen_global_argument_ptr as global_ptr, GLOBAL_STACK_CAP, }; unsafe { assert!(self.next < GLOBAL_STACK_CAP); *global_ptr().offset(self.next as isize) = val; self.next += 1; } } }
20.108108
80
0.587366
5037addcac50d7b6cadf13dd5b7901b01955b935
3,186
/* * Associated functions & Methods * * Some functions are connected to a particular type. These come in two forms: * associated functions, and methods. Associated functions are functions that * are defined on a type generally, while methods are associated functions that * are called on a particular instance of a type. */ struct Point { x: f64, y: f64, } // Implementation block, all `Point` associated functions & methods go in here impl Point { // This is an "associated function" because this function is associated with // a particular type, that is, Point. // // Associated functions don't need to be called with an instance. // These functions are generally used like constructors. fn origin() -> Point { Point { x: 0.0, y: 0.0 } } // Another associated function, taking two arguments: fn new(x: f64, y: f64) -> Point { Point { x: x, y: y } } } struct Rectangle { p1: Point, p2: Point, } impl Rectangle { // This is a method // `&self` is sugar for `self: &Self`, where `Self` is the type of the caller // object. In this case `Self` = `Rectangle` fn area(&self) -> f64 { // `self` give access to the struct fields via the dot operator let Point { x: x1, y: y1 } = self.p1; let Point { x: x2, y: y2 } = self.p2; // `abs` is a `f64` method that returns the absolute value of the caller ((x1 - x2) * (y1 - y2)).abs() } fn perimeter(&self) -> f64 { let Point { x: x1, y: y1 } = self.p1; let Point { x: x2, y: y2 } = self.p2; 2.0 * ((x1 - x2).abs() + (y1 - y2).abs()) } // This method requires the caller object to be mutable `&mut self` desugars // to `self: &mut Self` fn translate(&mut self, x: f64, y: f64) { self.p1.x += x; self.p2.x += x; self.p1.y += y; self.p2.y += y; } } // `Pair` owns resources: two heap allocated integers struct Pair(Box<i32>, Box<i32>); impl Pair { // This method "consumes" the resources of the caller object // `self` desugars to `self: Self` fn destroy(self) { // Destructure `self` let Pair(first, second) = self; println!("Destroying Pair({}, {})", first, second); // `first` and `second` go out of scope and get freed } } fn main() { let rectangle = Rectangle { // Associated functions are called using double colons p1: Point::origin(), p2: Point::new(3.0, 4.0), }; // Methods are called using the dot operator // Note that the first argument `&self` is implicitly passed, i.e. // `rectangle.perimeter()` === `Rectangle::perimeter(&rectangle)` println!("Rectangle perimeter: {}", rectangle.perimeter()); println!("Rectangle area: {}", rectangle.area()); let mut square = Rectangle { p1: Point::origin(), p2: Point::new(1.0, 1.0), }; // Error! `rectangle` is immutable, but this method requires a mutable object //rectangle.translate(1.0, 0.0); // TODO ^ Try uncommenting this line // Okay! Mutable objects can call mutable methods square.translate(1.0, 1.0); let pair = Pair(Box::new(1), Box::new(2)); pair.destroy(); // Error! Previous `destroy` call "consumed" `pair` //pair.destroy(); // TODO ^ Try uncommenting this line }
27.230769
79
0.630885
8fb0c7f057f6e68fba6a4238908279ef565b7da4
8,367
use console::style; use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; use lazy_static::lazy_static; use rand::{rngs::ThreadRng, Rng, RngCore}; use std::fmt::Debug; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::thread; use std::time::Duration; #[derive(Debug, Clone)] enum Action { ModifyTree(usize), IncProgressBar(usize), Stop, } #[derive(Clone, Debug)] enum Elem { AddItem(Item), RemoveItem(Index), } #[derive(Clone, Debug)] struct Item { key: String, index: usize, indent: usize, progress_bar: ProgressBar, } #[derive(Clone, Debug)] struct Index(usize); const PB_LEN: u64 = 32; static ELEM_IDX: AtomicUsize = AtomicUsize::new(0); lazy_static! { static ref ELEMENTS: [Elem; 27] = [ Elem::AddItem(Item { indent: 9, index: 0, progress_bar: ProgressBar::new(PB_LEN), key: "dog".to_string() }), Elem::AddItem(Item { indent: 0, index: 0, progress_bar: ProgressBar::new(PB_LEN), key: "temp_1".to_string() }), Elem::AddItem(Item { indent: 8, index: 1, progress_bar: ProgressBar::new(PB_LEN), key: "lazy".to_string() }), Elem::AddItem(Item { indent: 0, index: 1, progress_bar: ProgressBar::new(PB_LEN), key: "temp_2".to_string() }), Elem::AddItem(Item { indent: 1, index: 0, progress_bar: ProgressBar::new(PB_LEN), key: "the".to_string() }), Elem::AddItem(Item { indent: 0, index: 0, progress_bar: ProgressBar::new(PB_LEN), key: "temp_3".to_string() }), Elem::AddItem(Item { indent: 7, index: 3, progress_bar: ProgressBar::new(PB_LEN), key: "a".to_string() }), Elem::AddItem(Item { indent: 0, index: 3, progress_bar: ProgressBar::new(PB_LEN), key: "temp_4".to_string() }), Elem::AddItem(Item { indent: 6, index: 2, progress_bar: ProgressBar::new(PB_LEN), key: "over".to_string() }), Elem::RemoveItem(Index(6)), Elem::RemoveItem(Index(4)), Elem::RemoveItem(Index(3)), Elem::RemoveItem(Index(0)), Elem::AddItem(Item { indent: 0, index: 2, progress_bar: ProgressBar::new(PB_LEN), key: "temp_5".to_string() }), Elem::AddItem(Item { indent: 4, index: 1, progress_bar: ProgressBar::new(PB_LEN), key: "fox".to_string() }), Elem::AddItem(Item { indent: 0, index: 1, progress_bar: ProgressBar::new(PB_LEN), key: "temp_6".to_string() }), Elem::AddItem(Item { indent: 2, index: 1, progress_bar: ProgressBar::new(PB_LEN), key: "quick".to_string() }), Elem::AddItem(Item { indent: 0, index: 1, progress_bar: ProgressBar::new(PB_LEN), key: "temp_7".to_string() }), Elem::AddItem(Item { indent: 5, index: 5, progress_bar: ProgressBar::new(PB_LEN), key: "jumps".to_string() }), Elem::AddItem(Item { indent: 0, index: 5, progress_bar: ProgressBar::new(PB_LEN), key: "temp_8".to_string() }), Elem::AddItem(Item { indent: 3, index: 4, progress_bar: ProgressBar::new(PB_LEN), key: "brown".to_string() }), Elem::AddItem(Item { indent: 0, index: 3, progress_bar: ProgressBar::new(PB_LEN), key: "temp_9".to_string() }), Elem::RemoveItem(Index(10)), Elem::RemoveItem(Index(7)), Elem::RemoveItem(Index(4)), Elem::RemoveItem(Index(3)), Elem::RemoveItem(Index(1)), ]; } /// The example demonstrates the usage of `MultiProgress` and further extends `multi-tree` example. /// Now the example has 3 different actions implemented, and the item tree can be modified /// by inserting or removing progress bars. The progress bars to be removed eventually /// have messages with pattern `"temp_*"`. pub fn main() { let mp = Arc::new(MultiProgress::new()); let sty_main = ProgressStyle::default_bar().template("{bar:40.green/yellow} {pos:>4}/{len:4}"); let sty_aux = ProgressStyle::default_bar().template("[{pos:>2}/{len:2}] {prefix}{spinner:.green} {msg}"); let sty_fin = ProgressStyle::default_bar().template("[{pos:>2}/{len:2}] {prefix}{msg}"); let pb_main = mp.add(ProgressBar::new( ELEMENTS .iter() .map(|e| match e { Elem::AddItem(item) => item.progress_bar.length(), Elem::RemoveItem(_) => 1, }) .sum(), )); pb_main.set_style(sty_main); for e in ELEMENTS.iter() { match e { Elem::AddItem(item) => item.progress_bar.set_style(sty_aux.clone()), Elem::RemoveItem(_) => {} } } let mut items: Vec<&Item> = Vec::with_capacity(ELEMENTS.len()); let mp2 = Arc::clone(&mp); let _ = thread::spawn(move || { let mut rng = ThreadRng::default(); pb_main.tick(); loop { match get_action(&mut rng, &items) { Action::Stop => { // all elements were exhausted pb_main.finish(); return; } Action::ModifyTree(elem_idx) => match &ELEMENTS[elem_idx] { Elem::AddItem(item) => { let pb = mp2.insert(item.index + 1, item.progress_bar.clone()); pb.set_prefix(" ".repeat(item.indent)); pb.set_message(&item.key); items.insert(item.index, &item); } Elem::RemoveItem(Index(index)) => { let item = items.remove(*index); let pb = &item.progress_bar; mp2.remove(pb); pb_main.inc(pb.length() - pb.position()); } }, Action::IncProgressBar(item_idx) => { let item = &items[item_idx]; item.progress_bar.inc(1); let pos = item.progress_bar.position(); let len = item.progress_bar.length(); if pos >= len { item.progress_bar.set_style(sty_fin.clone()); item.progress_bar.finish_with_message(format!( "{} {}", style("✔").green(), item.key )); } pb_main.inc(1); } } thread::sleep(Duration::from_millis(20)); } }); mp.join().unwrap(); } /// The function guarantees to return the action, that is valid for the current tree. fn get_action<'a>(rng: &'a mut dyn RngCore, items: &[&Item]) -> Action { let elem_idx = ELEM_IDX.load(Ordering::SeqCst); // the indices of those items, that not completed yet let uncompleted = items .iter() .enumerate() .filter(|(_, item)| { let pos = item.progress_bar.position(); let len = item.progress_bar.length(); pos < len }) .map(|(idx, _)| idx) .collect::<Vec<usize>>(); let k = rng.gen_range(0..16); if (k > 0 || k == 0 && elem_idx == ELEMENTS.len()) && !uncompleted.is_empty() { let idx = rng.gen_range(0..uncompleted.len() as u64) as usize; Action::IncProgressBar(uncompleted[idx]) } else if elem_idx < ELEMENTS.len() { ELEM_IDX.fetch_add(1, Ordering::SeqCst); Action::ModifyTree(elem_idx) } else { // nothing to do more Action::Stop } }
31.573585
99
0.493725
fcb4cb03774a052a2e03ae33986f4a206601445f
13,617
use crate::duration::Duration; use crate::helpers::{self, Helpers}; use core::cmp::Ordering; use core::ops; /// Represents an instant in time. /// /// The generic `T` can either be `u32` or `u64`, and the const generics represent the ratio of the /// ticks contained within the instant: `instant in seconds = NOM / DENOM * ticks` #[derive(Clone, Copy, Debug)] pub struct Instant<T, const NOM: u32, const DENOM: u32> { ticks: T, } macro_rules! impl_instant_for_integer { ($i:ty) => { impl<const NOM: u32, const DENOM: u32> Instant<$i, NOM, DENOM> { /// Create an `Instant` from a ticks value. /// /// ``` /// # use fugit::*; #[doc = concat!("let _i = Instant::<", stringify!($i), ", 1, 1_000>::from_ticks(1);")] /// ``` #[inline] pub const fn from_ticks(ticks: $i) -> Self { helpers::greater_than_0::<NOM>(); helpers::greater_than_0::<DENOM>(); Instant { ticks } } /// Extract the ticks from an `Instant`. /// /// ``` /// # use fugit::*; #[doc = concat!("let i = Instant::<", stringify!($i), ", 1, 1_000>::from_ticks(234);")] /// /// assert_eq!(i.ticks(), 234); /// ``` #[inline] pub const fn ticks(&self) -> $i { self.ticks } /// Const comparison of `Instant`s. /// /// ``` /// # use fugit::*; #[doc = concat!("let i1 = Instant::<", stringify!($i), ", 1, 1_000>::from_ticks(1);")] #[doc = concat!("let i2 = Instant::<", stringify!($i), ", 1, 1_000>::from_ticks(2);")] /// /// assert_eq!(i1.const_cmp(i2), core::cmp::Ordering::Less); /// ``` #[inline] pub const fn const_cmp(self, other: Self) -> Ordering { if self.ticks == other.ticks { Ordering::Equal } else { let v = self.ticks.wrapping_sub(other.ticks); // not using `v.cmp(<$i>::MAX / 2).reverse()` due to `cmp` being non-const if v > <$i>::MAX / 2 { Ordering::Less } else if v < <$i>::MAX / 2 { Ordering::Greater } else { Ordering::Equal } } } /// Duration between `Instant`s. /// /// ``` /// # use fugit::*; #[doc = concat!("let i1 = Instant::<", stringify!($i), ", 1, 1_000>::from_ticks(1);")] #[doc = concat!("let i2 = Instant::<", stringify!($i), ", 1, 1_000>::from_ticks(2);")] /// /// assert_eq!(i1.checked_duration_since(i2), None); /// assert_eq!(i2.checked_duration_since(i1).unwrap().ticks(), 1); /// ``` #[inline] pub const fn checked_duration_since( self, other: Self, ) -> Option<Duration<$i, NOM, DENOM>> { match self.const_cmp(other) { Ordering::Greater | Ordering::Equal => { Some(Duration::<$i, NOM, DENOM>::from_ticks( self.ticks.wrapping_sub(other.ticks), )) } Ordering::Less => None, } } /// Subtract a `Duration` from an `Instant` while checking for overflow. /// /// ``` /// # use fugit::*; #[doc = concat!("let i = Instant::<", stringify!($i), ", 1, 1_000>::from_ticks(1);")] #[doc = concat!("let d = Duration::<", stringify!($i), ", 1, 1_000>::from_ticks(1);")] /// /// assert_eq!(i.checked_sub_duration(d).unwrap().ticks(), 0); /// ``` pub const fn checked_sub_duration<const O_NOM: u32, const O_DENOM: u32>( self, other: Duration<$i, O_NOM, O_DENOM>, ) -> Option<Self> { if Helpers::<NOM, DENOM, O_NOM, O_DENOM>::SAME_BASE { Some(Instant::<$i, NOM, DENOM>::from_ticks( self.ticks.wrapping_sub(other.ticks()), )) } else { if let Some(lh) = other .ticks() .checked_mul(Helpers::<NOM, DENOM, O_NOM, O_DENOM>::LD_TIMES_RN as $i) { let ticks = lh / Helpers::<NOM, DENOM, O_NOM, O_DENOM>::RD_TIMES_LN as $i; Some(Instant::<$i, NOM, DENOM>::from_ticks( self.ticks.wrapping_sub(ticks), )) } else { None } } } /// Add a `Duration` to an `Instant` while checking for overflow. /// /// ``` /// # use fugit::*; #[doc = concat!("let i = Instant::<", stringify!($i), ", 1, 1_000>::from_ticks(1);")] #[doc = concat!("let d = Duration::<", stringify!($i), ", 1, 1_000>::from_ticks(1);")] /// /// assert_eq!(i.checked_add_duration(d).unwrap().ticks(), 2); /// ``` pub const fn checked_add_duration<const O_NOM: u32, const O_DENOM: u32>( self, other: Duration<$i, O_NOM, O_DENOM>, ) -> Option<Self> { if Helpers::<NOM, DENOM, O_NOM, O_DENOM>::SAME_BASE { Some(Instant::<$i, NOM, DENOM>::from_ticks( self.ticks.wrapping_add(other.ticks()), )) } else { if let Some(lh) = other .ticks() .checked_mul(Helpers::<NOM, DENOM, O_NOM, O_DENOM>::LD_TIMES_RN as $i) { let ticks = lh / Helpers::<NOM, DENOM, O_NOM, O_DENOM>::RD_TIMES_LN as $i; Some(Instant::<$i, NOM, DENOM>::from_ticks( self.ticks.wrapping_add(ticks), )) } else { None } } } } impl<const NOM: u32, const DENOM: u32> PartialOrd for Instant<$i, NOM, DENOM> { #[inline] fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.const_cmp(*other)) } } impl<const NOM: u32, const DENOM: u32> Ord for Instant<$i, NOM, DENOM> { #[inline] fn cmp(&self, other: &Self) -> Ordering { self.const_cmp(*other) } } impl<const NOM: u32, const DENOM: u32> PartialEq for Instant<$i, NOM, DENOM> { #[inline] fn eq(&self, other: &Self) -> bool { self.ticks.eq(&other.ticks) } } impl<const NOM: u32, const DENOM: u32> Eq for Instant<$i, NOM, DENOM> {} // Instant - Instant = Duration // We have limited this to use same numerator and denominator in both left and right hand sides, // this allows for the extension traits to work. For usage with different fraction, use // `checked_duration_since`. impl<const NOM: u32, const DENOM: u32> ops::Sub<Instant<$i, NOM, DENOM>> for Instant<$i, NOM, DENOM> { type Output = Duration<$i, NOM, DENOM>; #[inline] fn sub(self, other: Self) -> Self::Output { if let Some(v) = self.checked_duration_since(other) { v } else { panic!("Sub failed! Other > self"); } } } // Instant - Duration = Instant // We have limited this to use same numerator and denominator in both left and right hand sides, // this allows for the extension traits to work. For usage with different fraction, use // `checked_sub_duration`. impl<const L_NOM: u32, const L_DENOM: u32, const R_NOM: u32, const R_DENOM: u32> ops::Sub<Duration<$i, R_NOM, R_DENOM>> for Instant<$i, L_NOM, L_DENOM> { type Output = Instant<$i, L_NOM, L_DENOM>; #[inline] fn sub(self, other: Duration<$i, R_NOM, R_DENOM>) -> Self::Output { if let Some(v) = self.checked_sub_duration(other) { v } else { panic!("Sub failed! Overflow"); } } } // Instant + Duration = Instant // We have limited this to use same numerator and denominator in both left and right hand sides, // this allows for the extension traits to work. For usage with different fraction, use // `checked_add_duration`. impl<const L_NOM: u32, const L_DENOM: u32, const R_NOM: u32, const R_DENOM: u32> ops::Add<Duration<$i, R_NOM, R_DENOM>> for Instant<$i, L_NOM, L_DENOM> { type Output = Instant<$i, L_NOM, L_DENOM>; #[inline] fn add(self, other: Duration<$i, R_NOM, R_DENOM>) -> Self::Output { if let Some(v) = self.checked_add_duration(other) { v } else { panic!("Add failed! Overflow"); } } } #[cfg(feature = "defmt")] impl<const NOM: u32, const DENOM: u32> defmt::Format for Instant<$i, NOM, DENOM> { fn format(&self, f: defmt::Formatter) { if NOM == 3_600 && DENOM == 1 { defmt::write!(f, "{} h", self.ticks) } else if NOM == 60 && DENOM == 1 { defmt::write!(f, "{} min", self.ticks) } else if NOM == 1 && DENOM == 1 { defmt::write!(f, "{} s", self.ticks) } else if NOM == 1 && DENOM == 1_000 { defmt::write!(f, "{} ms", self.ticks) } else if NOM == 1 && DENOM == 1_000_000 { defmt::write!(f, "{} us", self.ticks) } else if NOM == 1 && DENOM == 1_000_000_000 { defmt::write!(f, "{} ns", self.ticks) } else { defmt::write!(f, "{} ticks @ ({}/{})", self.ticks, NOM, DENOM) } } } impl<const NOM: u32, const DENOM: u32> core::fmt::Display for Instant<$i, NOM, DENOM> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { if NOM == 3_600 && DENOM == 1 { write!(f, "{} h", self.ticks) } else if NOM == 60 && DENOM == 1 { write!(f, "{} min", self.ticks) } else if NOM == 1 && DENOM == 1 { write!(f, "{} s", self.ticks) } else if NOM == 1 && DENOM == 1_000 { write!(f, "{} ms", self.ticks) } else if NOM == 1 && DENOM == 1_000_000 { write!(f, "{} us", self.ticks) } else if NOM == 1 && DENOM == 1_000_000_000 { write!(f, "{} ns", self.ticks) } else { write!(f, "{} ticks @ ({}/{})", self.ticks, NOM, DENOM) } } } }; } impl_instant_for_integer!(u32); impl_instant_for_integer!(u64); // // Operations between u32 Duration and u64 Instant // // Instant - Duration = Instant // We have limited this to use same numerator and denominator in both left and right hand sides, // this allows for the extension traits to work. For usage with different fraction, use // `checked_sub_duration`. impl<const L_NOM: u32, const L_DENOM: u32, const R_NOM: u32, const R_DENOM: u32> ops::Sub<Duration<u32, R_NOM, R_DENOM>> for Instant<u64, L_NOM, L_DENOM> { type Output = Instant<u64, L_NOM, L_DENOM>; #[inline] fn sub(self, other: Duration<u32, R_NOM, R_DENOM>) -> Self::Output { if let Some(v) = self.checked_sub_duration(other.into()) { v } else { panic!("Sub failed! Overflow"); } } } // Instant + Duration = Instant // We have limited this to use same numerator and denominator in both left and right hand sides, // this allows for the extension traits to work. For usage with different fraction, use // `checked_add_duration`. impl<const L_NOM: u32, const L_DENOM: u32, const R_NOM: u32, const R_DENOM: u32> ops::Add<Duration<u32, R_NOM, R_DENOM>> for Instant<u64, L_NOM, L_DENOM> { type Output = Instant<u64, L_NOM, L_DENOM>; #[inline] fn add(self, other: Duration<u32, R_NOM, R_DENOM>) -> Self::Output { if let Some(v) = self.checked_add_duration(other.into()) { v } else { panic!("Add failed! Overflow"); } } } // impl<const L_NOM: u32, const L_DENOM: u32, const R_NOM: u32, const R_DENOM: u32> // ops::Add<Duration<u32, R_NOM, R_DENOM>> for Duration<u64, L_NOM, L_DENOM> // { // type Output = Duration<u64, L_NOM, L_DENOM>; // // #[inline] // fn add(self, other: Duration<u32, R_NOM, R_DENOM>) -> Self::Output { // self.add(Duration::<u64, L_NOM, L_DENOM>::from_ticks( // other.ticks() as u64 // )) // } // }
39.699708
104
0.466549
ab7767eace8085b902842a410e0bc0b3783accba
1,363
use bracket_color::prelude::*; use bracket_noise::prelude::*; use bracket_random::prelude::*; use crossterm::queue; use crossterm::style::{Color::Rgb, Print, SetForegroundColor}; use std::io::{stdout, Write}; fn print_color(color: RGB, text: &str) { queue!( stdout(), SetForegroundColor(Rgb { r: (color.r * 255.0) as u8, g: (color.g * 255.0) as u8, b: (color.b * 255.0) as u8, }) ) .expect("Command Fail"); queue!(stdout(), Print(text)).expect("Command fail"); } fn main() { let mut rng = RandomNumberGenerator::new(); let mut noise = FastNoise::seeded(rng.next_u64()); noise.set_noise_type(NoiseType::PerlinFractal); noise.set_fractal_type(FractalType::FBM); noise.set_fractal_octaves(5); noise.set_fractal_gain(0.6); noise.set_fractal_lacunarity(2.0); noise.set_frequency(2.0); for y in 0..50 { for x in 0..80 { let n = noise.get_noise((x as f32) / 160.0, (y as f32) / 100.0); if n < 0.0 { print_color(RGB::from_f32(0.0, 0.0, 1.0 - (0.0 - n)), "░"); } else { print_color(RGB::from_f32(0.0, n, 0.0), "░"); } } print_color(RGB::named(WHITE), "\n"); } print_color(RGB::named(WHITE), "\n"); stdout().flush().expect("Flush Fail"); }
29
76
0.558327
5b7df88ab3f11c9b0642fa7c21f771671050e295
4,868
// Copyright 2014 Pierre Talbot (IRCAM) // 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. /* Compile the typed AST into Rust code. It generates a recognizer and parser function for each rules. We compile the PEG expressions by continuation-passing style. Basically, it means that the code is generated from bottom-up, right to left. Every PEG expression implements the `CompileExpr` trait which takes a continuation and a context, and returns an Rust expression. A continuation contains the `success` and `failure` components, which are both Rust expression. Basically, when compiling an expression, `success` is the expression to call if the parsing succeeds, and `failure` the one to call otherwise. The compilation is not easy to understand and we only explain it briefly here. A good strategy is to write a simple rule such as `test = (. / .) "a"` and to check what is the generated code with `cargo expand parse_test`. We give the general compilation scheme of different operators below. We write `[e](s,f)` the compilation of the expression `e` with the success continuation `s` and the failed continuation `f`. ``` [r:(T1,...,TN) = e] = [e](s,f) s = state.success((v1,v2,...,vN)) f = state.failure() ["a"](s,f) = if state.consume_prefix("a") { s } else { state.error("a"); f } [e1 e2](s,f) = [e1]([e2](s,f), f) [e?](s,f) = { let mut result = None; let mark1 = state.mark(); state = [e]( (vI = Some((u1,...,uN)); state), f) if state.is_failed() { state = state.restore_from_failure(mark1); } s } ``` A first problem is the name collision. Indeed, we declare `result` and `mark1` when compiling `e?` but maybe the same names are already used in the code outside of this expression. We avoid this problem by generating fresh variables, thanks to the structure `name_factory::NameFactory`, which is kept in the `context` structure. The main challenge comes from the choice expression. A simple compilation would be as follows: ``` [e1 / e2](s,f) = { let mark1 = state.mark(); state = [e1](s,f); if state.is_failed() { state = state.restore_from_failure(mark1); state = [e2](s,f); if state.is_failed() { f } else { state } } else { state } } ``` The problem with this strategy is that the expression `s` is duplicated for each branch of the choice expression. Imagine an expression such as `(e1 / e2) (e3 / e4) (e5 / e6) e7`, then you repeat the code for `e7` 8 times (for each branch combination), the code for `(e5 / e6)` 4 times and the one for `(e3 / e4)` 2 times. Therefore, it is not very ideal. Note that the function `Context::do_not_duplicate_success` allows this behavior if it returns `true`. The strategy is to encapsulate the success continuation in a closure: ``` [e1 / e2](s,f) = { let cont = |mut state: ParseState<Stream<'a>, T>, v1: T1, ..., vN: TN| { s }; let mark1 = state.mark(); state = [e1](cont(v1,...,vN),f); if state.is_failed() { state = state.restore_from_failure(mark1); state = [e2](cont(v1,...,vN),f); if state.is_failed() { f } else { state } } else { state } } ``` The variables `v1...vN` are those occurring free in the success continuation `s`. We must keep the names and types of the variables `v1...vN` somewhere, and this is the purpose of `context.free_variables`. Another subtlety is the usage of context for free variables. For instance, a value of type `(T1, Option<(T2, T3)>)` is given by two variables, let's say `(x, y)`. However, to build `y` of type `Option<(T2, T3)>`, we need two more names `w, z`, so we can build `Some((w, z))`. Thus, the free variables are only interesting for a given scope, and when building the full expression. Scopes are managed by the `context.open_scope` and `context.close_scope` functions. We open a new scope when crossing a type such as Option or List, but also for semantic actions. When building the value `(T2, T3)`, we only care about `w` and `z`, hence if a continuation function should be build for `e`, we only need to pass `w` and `z` to it, and not `x` and `y`. */ mod context; mod continuation; mod name_factory; mod compiler; use middle::typing::ast::*; pub fn compile(grammar: TGrammar) -> proc_macro2::TokenStream { compiler::GrammarCompiler::compile(grammar) }
39.577236
208
0.687551
38f434a3b99cc3fc597e5fb8c3798208b4e68668
4,871
use std::{ fmt::{self, Display, Formatter}, pin::Pin, str::FromStr, }; use tokio::io::{AsyncRead, BufReader}; use crate::{ http::{header, HeaderValue}, Body, IntoResponse, Response, }; /// The compression algorithms. #[cfg_attr(docsrs, doc(cfg(feature = "compression")))] #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum CompressionAlgo { /// brotli BR, /// deflate DEFLATE, /// gzip GZIP, } impl FromStr for CompressionAlgo { type Err = (); fn from_str(s: &str) -> std::prelude::rust_2015::Result<Self, Self::Err> { Ok(match s { "br" => CompressionAlgo::BR, "deflate" => CompressionAlgo::DEFLATE, "gzip" => CompressionAlgo::GZIP, _ => return Err(()), }) } } impl CompressionAlgo { pub(crate) fn as_str(&self) -> &'static str { match self { CompressionAlgo::BR => "br", CompressionAlgo::DEFLATE => "deflate", CompressionAlgo::GZIP => "gzip", } } pub(crate) fn compress<'a>( &self, reader: impl AsyncRead + Send + Unpin + 'a, ) -> Pin<Box<dyn AsyncRead + Send + 'a>> { match self { CompressionAlgo::BR => Box::pin(async_compression::tokio::bufread::BrotliEncoder::new( BufReader::new(reader), )), CompressionAlgo::DEFLATE => Box::pin( async_compression::tokio::bufread::DeflateEncoder::new(BufReader::new(reader)), ), CompressionAlgo::GZIP => Box::pin(async_compression::tokio::bufread::GzipEncoder::new( BufReader::new(reader), )), } } pub(crate) fn decompress<'a>( &self, reader: impl AsyncRead + Send + Unpin + 'a, ) -> Pin<Box<dyn AsyncRead + Send + 'a>> { match self { CompressionAlgo::BR => Box::pin(async_compression::tokio::bufread::BrotliDecoder::new( BufReader::new(reader), )), CompressionAlgo::DEFLATE => Box::pin( async_compression::tokio::bufread::DeflateDecoder::new(BufReader::new(reader)), ), CompressionAlgo::GZIP => Box::pin(async_compression::tokio::bufread::GzipDecoder::new( BufReader::new(reader), )), } } } impl Display for CompressionAlgo { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}", self.as_str()) } } /// Compress the response body with the specified algorithm and set the /// `Content-Encoding` header. /// /// # Example /// /// ``` /// use poem::{ /// handler, /// web::{Compress, CompressionAlgo}, /// }; /// /// #[handler] /// fn index() -> Compress<String> { /// Compress::new("abcdef".to_string(), CompressionAlgo::GZIP) /// } /// ``` #[cfg_attr(docsrs, doc(cfg(feature = "compression")))] pub struct Compress<T> { inner: T, algo: CompressionAlgo, } impl<T> Compress<T> { /// /// Create a compressed response using the specified algorithm. pub fn new(inner: T, algo: CompressionAlgo) -> Self { Self { inner, algo } } } impl<T: IntoResponse> IntoResponse for Compress<T> { fn into_response(self) -> Response { let mut resp = self.inner.into_response(); let body = resp.take_body(); resp.headers_mut().append( header::CONTENT_ENCODING, HeaderValue::from_static(self.algo.as_str()), ); resp.set_body(Body::from_async_read( self.algo.compress(body.into_async_read()), )); resp } } #[cfg(test)] mod tests { use tokio::io::AsyncReadExt; use super::*; use crate::{handler, test::TestClient, EndpointExt}; async fn decompress_data(algo: CompressionAlgo, data: &[u8]) -> String { let mut output = Vec::new(); let mut dec = algo.decompress(data); dec.read_to_end(&mut output).await.unwrap(); String::from_utf8(output).unwrap() } async fn test_algo(algo: CompressionAlgo) { const DATA: &str = "abcdefghijklmnopqrstuvwxyz1234567890"; #[handler(internal)] async fn index() -> &'static str { DATA } let resp = TestClient::new( index.and_then(move |resp| async move { Ok(Compress::new(resp, algo)) }), ) .get("/") .send() .await; resp.assert_status_is_ok(); resp.assert_header(header::CONTENT_ENCODING, algo.as_str()); assert_eq!( decompress_data(algo, &resp.0.into_body().into_bytes().await.unwrap()).await, DATA ); } #[tokio::test] async fn test_compress() { test_algo(CompressionAlgo::BR).await; test_algo(CompressionAlgo::DEFLATE).await; test_algo(CompressionAlgo::GZIP).await; } }
26.911602
98
0.561486
f9d2271624578054e525f20d4ed41fffc93d7fe4
747
use gtk::prelude::*; use crate::gui_data::GuiData; use crate::help_functions::*; use crate::notebook_enums::*; pub fn connect_notebook_tabs(gui_data: &GuiData) { let shared_buttons = gui_data.shared_buttons.clone(); let buttons_array = gui_data.bottom_buttons.buttons_array.clone(); let notebook_main_clone = gui_data.main_notebook.notebook_main.clone(); let buttons_names = gui_data.bottom_buttons.buttons_names.clone(); notebook_main_clone.connect_switch_page(move |_, _, number| { let current_tab_in_main_notebook = to_notebook_main_enum(number); // Buttons set_buttons(&mut *shared_buttons.borrow_mut().get_mut(&current_tab_in_main_notebook).unwrap(), &buttons_array, &buttons_names); }); }
37.35
135
0.746988
dd94fd17fc3a98b924152860a02f3787ba416d9a
54
pub mod script; pub mod nginx_module; mod nginx_utils;
18
21
0.814815
9cdbe0e18eab95abcbaf89ae47b81e59bb2fc506
3,171
use proc_macro2::TokenStream as TokenStream2; use quote::quote; use rtfm_syntax::{ast::App, Context}; use crate::{ analyze::Analysis, codegen::{locals, module, resources_struct, util}, }; pub fn codegen( app: &App, analysis: &Analysis, ) -> ( // const_app Vec<TokenStream2>, // mod_init Vec<TokenStream2>, // init_locals Vec<TokenStream2>, // init_resources Vec<TokenStream2>, // init_late_resources Vec<TokenStream2>, // user_init Vec<TokenStream2>, // call_init Option<TokenStream2>, ) { let mut call_init = None; let mut const_app = vec![]; let mut init_late_resources = vec![]; let mut init_resources = vec![]; let mut locals_struct = vec![]; let mut mod_init = vec![]; let mut user_init = vec![]; for (&core, init) in &app.inits { let mut needs_lt = false; let name = &init.name; if !init.args.resources.is_empty() { let (item, constructor) = resources_struct::codegen(Context::Init(core), 0, &mut needs_lt, app, analysis); init_resources.push(item); const_app.push(constructor); } if core == 0 { call_init = Some(quote!(let late = #name(#name::Locals::new(), #name::Context::new());)); } let late_fields = analysis .late_resources .get(&core) .map(|resources| { resources .iter() .map(|name| { let ty = &app.late_resources[name].ty; quote!(pub #name: #ty) }) .collect::<Vec<_>>() }) .unwrap_or(vec![]); let attrs = &init.attrs; let has_late_resources = !late_fields.is_empty(); let late_resources = util::late_resources_ident(&name); let ret = if has_late_resources { init_late_resources.push(quote!( /// Resources initialized at runtime #[allow(non_snake_case)] pub struct #late_resources { #(#late_fields),* } )); Some(quote!(-> #name::LateResources)) } else { None }; let context = &init.context; let (struct_, locals_pat) = locals::codegen(Context::Init(core), &init.locals, app); locals_struct.push(struct_); let stmts = &init.stmts; user_init.push(quote!( #(#attrs)* #[allow(non_snake_case)] fn #name(#locals_pat, #context: #name::Context) #ret { #(#stmts)* } )); mod_init.push(module::codegen( Context::Init(core), (!init.args.resources.is_empty(), needs_lt), !init.args.schedule.is_empty(), !init.args.spawn.is_empty(), has_late_resources, app, )); } ( const_app, mod_init, locals_struct, init_resources, init_late_resources, user_init, call_init, ) }
26.872881
96
0.509618
fbcfeab99a4deffb9f59a107024aa00c326c282a
4,071
// texture.rs // Texturing functions // Stephen Marz // 15 Dec 2020 use crate::perlin::Perlin; use crate::vector::{Color, Vec3}; use std::fs::File; use std::sync::Arc; pub trait Texture { fn value(&self, u: f64, v: f64, point: &Vec3) -> Color; } // TEXTURES // Solid color #[derive(Default)] pub struct SolidColor { color_value: Color, } unsafe impl Send for SolidColor {} unsafe impl Sync for SolidColor {} impl SolidColor { pub fn new(color_value: Color) -> Self { Self { color_value, } } pub fn from_rgb(r: f64, g: f64, b: f64) -> Self { Self { color_value: Color::new(r, g, b), } } } impl Texture for SolidColor { fn value(&self, _u: f64, _v: f64, _point: &Vec3) -> Color { // A solid color doesn't care about where the ray is being shot self.color_value } } // Checkered texture pub struct CheckeredTexture { odd: Arc<dyn Texture + Send + Sync>, even: Arc<dyn Texture + Send + Sync>, } unsafe impl Send for CheckeredTexture {} unsafe impl Sync for CheckeredTexture {} impl CheckeredTexture { pub fn new(odd: Arc<dyn Texture + Send + Sync>, even: Arc<dyn Texture + Send + Sync>) -> Self { Self { odd, even, } } pub fn new_color(odd: Vec3, even: Vec3) -> Self { let odd = Arc::new(SolidColor::new(odd)); let even = Arc::new(SolidColor::new(even)); Self::new(odd, even) } } impl Texture for CheckeredTexture { fn value(&self, u: f64, v: f64, p: &Vec3) -> Color { let sines = (10.0 * p.x()).sin() * (10.0 * p.y()).sin() * (10.0 * p.z()).sin(); if sines < 0.0 { self.odd.value(u, v, p) } else { self.even.value(u, v, p) } } } // Perlin noise texture pub struct NoiseTexture { perlin: Perlin, } unsafe impl Send for NoiseTexture {} unsafe impl Sync for NoiseTexture {} impl NoiseTexture { pub fn new() -> Self { Self { perlin: Perlin::new(), } } } impl Texture for NoiseTexture { fn value(&self, _u: f64, _v: f64, p: &Vec3) -> Color { Vec3::new(1.0, 1.0, 1.0) * self.perlin.noise(p) } } pub struct ImageTexture { data: Vec<(f64, f64, f64)>, width: usize, height: usize } impl ImageTexture { pub fn new(data: Vec<(f64, f64, f64)>, width: usize, height: usize) -> Self { Self { data, width, height } } pub fn from_file(fname: &str) -> Self { // The decoder is a build for reader and can be used to set various decoding options // via `Transformations`. The default output transformation is `Transformations::EXPAND // | Transformations::STRIP_ALPHA`. let decoder = png::Decoder::new(File::open(fname).unwrap()); let (info, mut reader) = decoder.read_info().unwrap(); let width = info.width as usize; let height = info.height as usize; // Allocate the output buffer. let mut buf = vec![0; info.buffer_size()]; let mut data = Vec::<(f64, f64, f64)>::with_capacity(info.buffer_size() / 3); // Read the next frame. An APNG might contain multiple frames. while let Ok(_) = reader.next_frame(&mut buf) { // Inspect more details of the last read frame. // let in_animation = reader.info().frame_control.is_some(); for i in (0..buf.len()).step_by(4) { let rgb = (buf[i] as f64 / 255.0, buf[i + 1] as f64 / 255.0, buf[i + 2] as f64 / 255.0); data.push(rgb); } } Self { data, width, height, } } } impl Texture for ImageTexture { fn value(&self, u: f64, v: f64, _point: &Vec3) -> Color { if self.data.len() == 0 { return Color::new(0.0, 1.0, 1.0); } // Clamp input texture coordinates to [0,1] x [1,0] let u = clamp(u, 0.0, 1.0); let v = 1.0 - clamp(v, 0.0, 1.0); // Flip V to image coordinates let mut i = (u * self.width as f64) as usize; let mut j = (v * self.height as f64) as usize; // Clamp integer mapping, since actual coordinates should be less than 1.0 if i >= self.width { i = self.width - 1; } if j >= self.height { j = self.height - 1; } let pixel = self.data[j * self.width + i]; Color::new(pixel.0, pixel.1, pixel.2) } } fn clamp(val: f64, min: f64, max: f64) -> f64 { if val < min { min } else if val > max { max } else { val } }
21.770053
96
0.622206
033a84305f00bbcb01ec710830951e091d07e3c9
5,196
use backend::*; struct RoomBuilder {} impl RoomBuilder { fn new() -> Box<Self> { Box::new(Self {}) } } fn noise_map( seed: u64, octaves: i32, gain: f32, lacunarity: f32, freq: f32, frames: &mut Vec<(Map, String)>, x_scale: f32, y_scale: f32, title: &str, ) { let mut map = Map::new(); let mut noise = FastNoise::seeded(seed); noise.set_noise_type(NoiseType::SimplexFractal); noise.set_fractal_type(FractalType::FBM); noise.set_fractal_octaves(octaves); noise.set_fractal_gain(gain); noise.set_fractal_lacunarity(lacunarity); noise.set_frequency(freq); let mut noise2 = FastNoise::seeded(seed * 12); noise2.set_noise_type(NoiseType::SimplexFractal); noise2.set_fractal_type(FractalType::FBM); noise2.set_fractal_octaves(octaves / 2); noise2.set_fractal_gain(gain / 2.0); noise2.set_fractal_lacunarity(lacunarity + 1.0); noise2.set_frequency(freq * 4.0); for y in 0..HEIGHT { for x in 0..WIDTH { let mut n = noise.get_noise(x as f32 * (x_scale * 0.5), y as f32 * (y_scale * 0.5)); n *= f32::max(0.5, x_scale); n += f32::min(0.25, 0.75 - x_scale) * noise2.get_noise(x as f32 * x_scale, y as f32 * y_scale); if n < 0.0 { map.set( Point::new(x, y), to_cp437('~'), RGB::from_f32(0.0, 0.0, 1.0), ); } else if n < 0.5 { map.set( Point::new(x, y), to_cp437(';'), RGB::from_f32(0.0, n + 0.25, 0.0), ); } else { map.set(Point::new(x, y), to_cp437('^'), RGB::from_f32(n, n, n)); } } } frames.push((map.clone(), title.to_string())); } impl MapGen for RoomBuilder { fn setup(&mut self) {} fn build(&mut self) -> Vec<(Map, String)> { let mut frames = Vec::new(); let seed = 4; let octaves = 3; let gain = 0.005; let lacunarity = 4.0; let freq = 0.08; let mut map = Map::new(); let mut noise = FastNoise::seeded(seed); noise.set_noise_type(NoiseType::SimplexFractal); noise.set_fractal_type(FractalType::FBM); noise.set_fractal_octaves(octaves); noise.set_fractal_gain(gain); noise.set_fractal_lacunarity(lacunarity); noise.set_frequency(freq); for y in 0..HEIGHT { for x in 0..WIDTH { let n = noise.get_noise(x as f32 * (1.0 * 0.5), y as f32 * (1.0 * 0.5)); if n < 0.0 { map.set( Point::new(x, y), to_cp437('~'), RGB::from_f32(0.0, 0.0, 1.0), ); } else if n < 0.5 { map.set( Point::new(x, y), to_cp437(';'), RGB::from_f32(0.0, n + 0.25, 0.0), ); } else { map.set(Point::new(x, y), to_cp437('^'), RGB::from_f32(n, n, n)); } } } frames.push((map.clone(), "First Noise Map".to_string())); let mut map = Map::new(); let mut noise = FastNoise::seeded(seed * 12); noise.set_noise_type(NoiseType::SimplexFractal); noise.set_fractal_type(FractalType::FBM); noise.set_fractal_octaves(octaves / 2); noise.set_fractal_gain(gain / 2.0); noise.set_fractal_lacunarity(lacunarity + 1.0); noise.set_frequency(freq * 4.0); for y in 0..HEIGHT { for x in 0..WIDTH { let n = noise.get_noise(x as f32 * (1.0 * 0.5), y as f32 * (1.0 * 0.5)); if n < 0.0 { map.set( Point::new(x, y), to_cp437('~'), RGB::from_f32(0.0, 0.0, 1.0), ); } else if n < 0.5 { map.set( Point::new(x, y), to_cp437(';'), RGB::from_f32(0.0, n + 0.25, 0.0), ); } else { map.set(Point::new(x, y), to_cp437('^'), RGB::from_f32(n, n, n)); } } } frames.push((map.clone(), "Second Noise Map".to_string())); // Build it noise_map( seed, octaves, gain, lacunarity, freq, &mut frames, 1.0, 1.0, "Zoomed Out", ); let mut scale = 1.0; while scale > 0.1 { noise_map( seed, octaves, gain, lacunarity, freq, &mut frames, scale, scale, &format!("Scale {}", scale), ); scale -= 0.01; } frames } } fn main() -> BError { run(RoomBuilder::new()) }
30.034682
96
0.439376
aca50859b6eda9cc7f18ad6bf5080fb8b11a86af
699
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // note that these aux-build directives must be in this order // aux-build:svh-a-base.rs // aux-build:svh-b.rs // aux-build:svh-a-base.rs // pretty-expanded FIXME #23616 extern crate a; extern crate b; fn main() { b::foo() }
29.125
68
0.72103
1abff1d3125b9139bde84f0c7f992e7058b12721
1,772
use crate::helpers::computer::Computer; use crate::helpers::file::{read, write}; pub fn ex02() { let e = "02"; let s = read(e); write( e, &sub1(&s, Some((12, 2))).to_string(), &sub2(&s).to_string(), ); } pub fn sub1(s: &str, args: Option<(i64, i64)>) -> i64 { let program = s .split(',') .map(|x| x.parse::<i64>().unwrap_or(0)) .collect::<Vec<i64>>(); let mut computer = Computer::new("computer", program); if let Some((noun, verb)) = args { computer.set_program(1, noun); computer.set_program(2, verb); } computer.run(); computer.program(0) } pub fn sub2(s: &str) -> i64 { let program = s .split(',') .map(|x| x.parse::<i64>().unwrap_or(0)) .collect::<Vec<i64>>(); let mut noun = 0; let mut verb = 0; 'noun: for n in 0..99 { for v in 0..99 { let mut computer = Computer::new("computer", program.clone()); computer.set_program(1, n); computer.set_program(2, v); computer.run(); if computer.program(0) == 19_690_720 { noun = n; verb = v; break 'noun; } } } 100 * noun + verb } #[cfg(test)] mod tests { use super::*; #[test] fn sub11() { assert_eq!(sub1("1,9,10,3,2,3,11,0,99,30,40,50", None), 3500); } #[test] fn sub12() { assert_eq!(sub1("1,0,0,0,99", None), 2); } #[test] fn sub13() { assert_eq!(sub1("2,3,0,3,99", None), 2); } #[test] fn sub14() { assert_eq!(sub1("2,4,4,5,99,0", None), 2); } #[test] fn sub15() { assert_eq!(sub1("1,1,1,4,99,5,6,0,99", None), 30); } }
22.15
74
0.469526
d771c690c8fc9cd9d368ac48e0564aa498555222
10,177
//! Contains components suitable to create an array out of N other arrays, by slicing //! from each in a random-access fashion. use crate::array::*; use crate::datatypes::*; mod binary; pub use binary::GrowableBinary; mod boolean; pub use boolean::GrowableBoolean; mod fixed_binary; pub use fixed_binary::GrowableFixedSizeBinary; mod null; pub use null::GrowableNull; mod primitive; pub use primitive::GrowablePrimitive; mod list; pub use list::GrowableList; mod structure; pub use structure::GrowableStruct; mod utf8; pub use utf8::GrowableUtf8; mod utils; pub trait Growable<'a> { /// Extends this [`GrowableArray`] with elements from the bounded [`Array`] at `start` /// and for a size of `len`. /// # Panic /// This function panics if the range is out of bounds, i.e. if `start + len >= array.len()`. fn extend(&mut self, index: usize, start: usize, len: usize); /// Extends this [`GrowableArray`] with null elements, disregarding the bound arrays fn extend_validity(&mut self, additional: usize); /// Converts itself to an `Arc<dyn Array>`, thereby finishing the mutation. /// Self will be empty after such operation fn to_arc(&mut self) -> std::sync::Arc<dyn Array> { self.to_box().into() } /// Converts itself to an `Box<dyn Array>`, thereby finishing the mutation. /// Self will be empty after such operation fn to_box(&mut self) -> Box<dyn Array>; } macro_rules! dyn_growable { ($ty:ty, $arrays:expr, $use_validity:expr, $capacity:expr) => {{ let arrays = $arrays .iter() .map(|array| { array .as_any() .downcast_ref::<PrimitiveArray<$ty>>() .unwrap() }) .collect::<Vec<_>>(); Box::new(primitive::GrowablePrimitive::<$ty>::new( &arrays, $use_validity, $capacity, )) }}; } /// # Panics /// This function panics iff the arrays do not have the same data_type. pub fn make_growable<'a>( arrays: &[&'a dyn Array], use_validity: bool, capacity: usize, ) -> Box<dyn Growable<'a> + 'a> { assert!(!arrays.is_empty()); let data_type = arrays[0].data_type(); assert!(arrays.iter().all(|&item| item.data_type() == data_type)); match data_type { DataType::Null => Box::new(null::GrowableNull::new()), DataType::Boolean => Box::new(boolean::GrowableBoolean::new( arrays, use_validity, capacity, )), DataType::Int8 => dyn_growable!(i8, arrays, use_validity, capacity), DataType::Int16 => dyn_growable!(i16, arrays, use_validity, capacity), DataType::Int32 | DataType::Date32 | DataType::Time32(_) | DataType::Interval(IntervalUnit::YearMonth) => { dyn_growable!(i32, arrays, use_validity, capacity) } DataType::Int64 | DataType::Date64 | DataType::Time64(_) | DataType::Timestamp(_, _) | DataType::Duration(_) => { dyn_growable!(i64, arrays, use_validity, capacity) } DataType::Interval(IntervalUnit::DayTime) => { dyn_growable!(days_ms, arrays, use_validity, capacity) } DataType::Decimal(_, _) => dyn_growable!(i128, arrays, use_validity, capacity), DataType::UInt8 => dyn_growable!(u8, arrays, use_validity, capacity), DataType::UInt16 => dyn_growable!(u16, arrays, use_validity, capacity), DataType::UInt32 => dyn_growable!(u32, arrays, use_validity, capacity), DataType::UInt64 => dyn_growable!(u64, arrays, use_validity, capacity), DataType::Float16 => unreachable!(), DataType::Float32 => dyn_growable!(f32, arrays, use_validity, capacity), DataType::Float64 => dyn_growable!(f64, arrays, use_validity, capacity), DataType::Utf8 => { let arrays = arrays .iter() .map(|array| array.as_any().downcast_ref::<Utf8Array<i32>>().unwrap()) .collect::<Vec<_>>(); Box::new(utf8::GrowableUtf8::<i32>::new( &arrays, use_validity, capacity, )) } DataType::LargeUtf8 => { let arrays = arrays .iter() .map(|array| array.as_any().downcast_ref::<Utf8Array<i64>>().unwrap()) .collect::<Vec<_>>(); Box::new(utf8::GrowableUtf8::<i64>::new( &arrays, use_validity, capacity, )) } DataType::Binary => Box::new(binary::GrowableBinary::<i32>::new( arrays, use_validity, capacity, )), DataType::LargeBinary => Box::new(binary::GrowableBinary::<i64>::new( arrays, use_validity, capacity, )), DataType::FixedSizeBinary(_) => Box::new(fixed_binary::GrowableFixedSizeBinary::new( arrays, use_validity, capacity, )), DataType::List(_) => Box::new(list::GrowableList::<i32>::new( arrays, use_validity, capacity, )), DataType::LargeList(_) => Box::new(list::GrowableList::<i64>::new( arrays, use_validity, capacity, )), DataType::Struct(_) => Box::new(structure::GrowableStruct::new( arrays, use_validity, capacity, )), DataType::FixedSizeList(_, _) => todo!(), DataType::Union(_) => todo!(), DataType::Dictionary(_, _) => todo!(), } } /* #[cfg(test)] mod tests { use std::convert::TryFrom; use super::*; use crate::{ array::{ Array, ArrayDataRef, ArrayRef, BooleanArray, DictionaryArray, FixedSizeBinaryArray, Int16Array, Int16Type, Int32Array, Int64Array, Int64Builder, ListBuilder, NullArray, PrimitiveBuilder, StringArray, StringDictionaryBuilder, StructArray, UInt8Array, }, buffer::Buffer, datatypes::Field, }; use crate::{ array::{ListArray, StringBuilder}, error::Result, }; fn create_dictionary_array(values: &[&str], keys: &[Option<&str>]) -> ArrayDataRef { let values = StringArray::from(values.to_vec()); let mut builder = StringDictionaryBuilder::new_with_dictionary( PrimitiveBuilder::<Int16Type>::new(3), &values, ) .unwrap(); for key in keys { if let Some(v) = key { builder.append(v).unwrap(); } else { builder.append_null().unwrap() } } builder.finish().data() } #[test] fn test_dictionary() { // (a, b, c), (0, 1, 0, 2) => (a, b, a, c) let array = create_dictionary_array( &["a", "b", "c"], &[Some("a"), Some("b"), None, Some("c")], ); let arrays = vec![array.as_ref()]; let mut mutable = MutableArrayData::new(arrays, false, 0); mutable.extend(0, 1, 3); let result = mutable.freeze(); let result = DictionaryArray::from(Arc::new(result)); let expected = Int16Array::from(vec![Some(1), None]); assert_eq!(result.keys(), &expected); } /* // this is an old test used on a meanwhile removed dead code // that is still useful when `MutableArrayData` supports fixed-size lists. #[test] fn test_fixed_size_list_append() -> Result<()> { let int_builder = UInt16Builder::new(64); let mut builder = FixedSizeListBuilder::<UInt16Builder>::new(int_builder, 2); builder.values().append_slice(&[1, 2])?; builder.append(true)?; builder.values().append_slice(&[3, 4])?; builder.append(false)?; builder.values().append_slice(&[5, 6])?; builder.append(true)?; let a_builder = UInt16Builder::new(64); let mut a_builder = FixedSizeListBuilder::<UInt16Builder>::new(a_builder, 2); a_builder.values().append_slice(&[7, 8])?; a_builder.append(true)?; a_builder.values().append_slice(&[9, 10])?; a_builder.append(true)?; a_builder.values().append_slice(&[11, 12])?; a_builder.append(false)?; a_builder.values().append_slice(&[13, 14])?; a_builder.append(true)?; a_builder.values().append_null()?; a_builder.values().append_null()?; a_builder.append(true)?; let a = a_builder.finish(); // append array builder.append_data(&[ a.data(), a.slice(1, 3).data(), a.slice(2, 1).data(), a.slice(5, 0).data(), ])?; let finished = builder.finish(); let expected_int_array = UInt16Array::from(vec![ Some(1), Some(2), Some(3), Some(4), Some(5), Some(6), // append first array Some(7), Some(8), Some(9), Some(10), Some(11), Some(12), Some(13), Some(14), None, None, // append slice(1, 3) Some(9), Some(10), Some(11), Some(12), Some(13), Some(14), // append slice(2, 1) Some(11), Some(12), ]); let expected_list_data = ArrayData::new( DataType::FixedSizeList( Box::new(Field::new("item", DataType::UInt16, true)), 2, ), 12, None, None, 0, vec![], vec![expected_int_array.data()], ); let expected_list = FixedSizeListArray::from(Arc::new(expected_list_data) as ArrayDataRef); assert_eq!(&expected_list.values(), &finished.values()); assert_eq!(expected_list.len(), finished.len()); Ok(()) } */ } */
32.104101
97
0.538371
f817df266cb1ce9d1c20488c74bc489f3ac5e80d
12,309
#[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::IER { #[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 DOWNIER { bits: bool, } impl DOWNIER { #[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 UPIER { bits: bool, } impl UPIER { #[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 ARROKIER { bits: bool, } impl ARROKIER { #[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 CMPOKIER { bits: bool, } impl CMPOKIER { #[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 EXTTRIGIER { bits: bool, } impl EXTTRIGIER { #[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 ARRMIER { bits: bool, } impl ARRMIER { #[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 CMPMIER { bits: bool, } impl CMPMIER { #[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 _DOWNIEW<'a> { w: &'a mut W, } impl<'a> _DOWNIEW<'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 _UPIEW<'a> { w: &'a mut W, } impl<'a> _UPIEW<'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 _ARROKIEW<'a> { w: &'a mut W, } impl<'a> _ARROKIEW<'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 _CMPOKIEW<'a> { w: &'a mut W, } impl<'a> _CMPOKIEW<'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 _EXTTRIGIEW<'a> { w: &'a mut W, } impl<'a> _EXTTRIGIEW<'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 _ARRMIEW<'a> { w: &'a mut W, } impl<'a> _ARRMIEW<'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 _CMPMIEW<'a> { w: &'a mut W, } impl<'a> _CMPMIEW<'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 } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 6 - Direction change to down Interrupt Enable"] #[inline] pub fn downie(&self) -> DOWNIER { let bits = { const MASK: bool = true; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) != 0 }; DOWNIER { bits } } #[doc = "Bit 5 - Direction change to UP Interrupt Enable"] #[inline] pub fn upie(&self) -> UPIER { let bits = { const MASK: bool = true; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) != 0 }; UPIER { bits } } #[doc = "Bit 4 - Autoreload register update OK Interrupt Enable"] #[inline] pub fn arrokie(&self) -> ARROKIER { let bits = { const MASK: bool = true; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) != 0 }; ARROKIER { bits } } #[doc = "Bit 3 - Compare register update OK Interrupt Enable"] #[inline] pub fn cmpokie(&self) -> CMPOKIER { let bits = { const MASK: bool = true; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u32) != 0 }; CMPOKIER { bits } } #[doc = "Bit 2 - External trigger valid edge Interrupt Enable"] #[inline] pub fn exttrigie(&self) -> EXTTRIGIER { let bits = { const MASK: bool = true; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) != 0 }; EXTTRIGIER { bits } } #[doc = "Bit 1 - Autoreload match Interrupt Enable"] #[inline] pub fn arrmie(&self) -> ARRMIER { let bits = { const MASK: bool = true; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) != 0 }; ARRMIER { bits } } #[doc = "Bit 0 - Compare match Interrupt Enable"] #[inline] pub fn cmpmie(&self) -> CMPMIER { let bits = { const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }; CMPMIER { 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 6 - Direction change to down Interrupt Enable"] #[inline] pub fn downie(&mut self) -> _DOWNIEW { _DOWNIEW { w: self } } #[doc = "Bit 5 - Direction change to UP Interrupt Enable"] #[inline] pub fn upie(&mut self) -> _UPIEW { _UPIEW { w: self } } #[doc = "Bit 4 - Autoreload register update OK Interrupt Enable"] #[inline] pub fn arrokie(&mut self) -> _ARROKIEW { _ARROKIEW { w: self } } #[doc = "Bit 3 - Compare register update OK Interrupt Enable"] #[inline] pub fn cmpokie(&mut self) -> _CMPOKIEW { _CMPOKIEW { w: self } } #[doc = "Bit 2 - External trigger valid edge Interrupt Enable"] #[inline] pub fn exttrigie(&mut self) -> _EXTTRIGIEW { _EXTTRIGIEW { w: self } } #[doc = "Bit 1 - Autoreload match Interrupt Enable"] #[inline] pub fn arrmie(&mut self) -> _ARRMIEW { _ARRMIEW { w: self } } #[doc = "Bit 0 - Compare match Interrupt Enable"] #[inline] pub fn cmpmie(&mut self) -> _CMPMIEW { _CMPMIEW { w: self } } }
25.751046
69
0.504346
d9ad8d16e7638d29fc8e447b5dc07013d207b95b
1,288
use crate::soon_to_be_lib::spec::Spec; use std::path::PathBuf; #[derive(Debug, StructOpt)] #[structopt(name = "anon-csv", about = "A CSV-file anonymizer")] pub struct Args { /// If set, print all available faker specifications #[structopt(long = "all-specs")] pub print_specs: bool, /// If set, no additional output will be produced on stderr #[structopt(short = "q", long = "quiet")] pub quiet: bool, /// If set, the CSV file is expected to have one header line. It will be reproduced in the output #[structopt(long = "header")] pub header: bool, /// The delimiter of the input CSV file. The same delimiter will be used for output. #[structopt(short = "d", long = "delimiter", default_value = ",")] pub delimiter: char, /// The path to the CSV file to use as input. If '-', the file will be read from stdin. #[structopt(parse(from_os_str))] pub csv_file: PathBuf, /// One or more rewrite specifications. They look like '<column>:<type>', where <column> is /// a zero-based column indexed, separated from the <type> being the type of data to fake. /// Run this command with --all-specs and all required arguments to learn about all possible values. #[structopt(parse(try_from_str))] pub specs: Vec<Spec>, }
46
104
0.670031
644e6d5823167c838d925ed07f1f3faabb954b5f
877
use std::env::current_dir; use std::fs::create_dir_all; use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; use my_first_contract::msg::{AllGardenersResponse, HandleMsg, InitMsg, QueryMsg}; use my_first_contract::state::Bonsai; use my_first_contract::state::BonsaiList; use my_first_contract::state::Gardener; fn main() { let mut out_dir = current_dir().unwrap(); out_dir.push("schema"); create_dir_all(&out_dir).unwrap(); remove_schemas(&out_dir).unwrap(); export_schema(&schema_for!(InitMsg), &out_dir); export_schema(&schema_for!(HandleMsg), &out_dir); export_schema(&schema_for!(QueryMsg), &out_dir); export_schema(&schema_for!(Gardener), &out_dir); export_schema(&schema_for!(Bonsai), &out_dir); export_schema(&schema_for!(BonsaiList), &out_dir); export_schema(&schema_for!(AllGardenersResponse), &out_dir); }
35.08
81
0.738883
086b45c6f17fb1b155c22b4aa227bf29dc716302
10,733
#[doc = "Register `RST_MODE_P0` reader"] pub struct R(crate::R<RST_MODE_P0_SPEC>); impl core::ops::Deref for R { type Target = crate::R<RST_MODE_P0_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<RST_MODE_P0_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<RST_MODE_P0_SPEC>) -> Self { R(reader) } } #[doc = "Register `RST_MODE_P0` writer"] pub struct W(crate::W<RST_MODE_P0_SPEC>); impl core::ops::Deref for W { type Target = crate::W<RST_MODE_P0_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<RST_MODE_P0_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<RST_MODE_P0_SPEC>) -> Self { W(writer) } } #[doc = "Field `pin0` reader - P0.0 Default Output Drive Mode"] pub struct PIN0_R(crate::FieldReader<u8>); impl PIN0_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { PIN0_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for PIN0_R { type Target = crate::FieldReader<u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `pin0` writer - P0.0 Default Output Drive Mode"] pub struct PIN0_W<'a> { w: &'a mut W, } impl<'a> PIN0_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !7) | (value as u32 & 7); self.w } } #[doc = "Field `pin1` reader - P0.1 Default Output Drive Mode"] pub struct PIN1_R(crate::FieldReader<u8>); impl PIN1_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { PIN1_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for PIN1_R { type Target = crate::FieldReader<u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `pin1` writer - P0.1 Default Output Drive Mode"] pub struct PIN1_W<'a> { w: &'a mut W, } impl<'a> PIN1_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(7 << 4)) | ((value as u32 & 7) << 4); self.w } } #[doc = "Field `pin2` reader - P0.2 Default Output Drive Mode"] pub struct PIN2_R(crate::FieldReader<u8>); impl PIN2_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { PIN2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for PIN2_R { type Target = crate::FieldReader<u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `pin2` writer - P0.2 Default Output Drive Mode"] pub struct PIN2_W<'a> { w: &'a mut W, } impl<'a> PIN2_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(7 << 8)) | ((value as u32 & 7) << 8); self.w } } #[doc = "Field `pin3` reader - P0.3 Default Output Drive Mode"] pub struct PIN3_R(crate::FieldReader<u8>); impl PIN3_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { PIN3_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for PIN3_R { type Target = crate::FieldReader<u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `pin3` writer - P0.3 Default Output Drive Mode"] pub struct PIN3_W<'a> { w: &'a mut W, } impl<'a> PIN3_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(7 << 12)) | ((value as u32 & 7) << 12); self.w } } #[doc = "Field `pin4` reader - P0.4 Default Output Drive Mode"] pub struct PIN4_R(crate::FieldReader<u8>); impl PIN4_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { PIN4_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for PIN4_R { type Target = crate::FieldReader<u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `pin4` writer - P0.4 Default Output Drive Mode"] pub struct PIN4_W<'a> { w: &'a mut W, } impl<'a> PIN4_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(7 << 16)) | ((value as u32 & 7) << 16); self.w } } #[doc = "Field `pin5` reader - P0.5 Default Output Drive Mode"] pub struct PIN5_R(crate::FieldReader<u8>); impl PIN5_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { PIN5_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for PIN5_R { type Target = crate::FieldReader<u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `pin5` writer - P0.5 Default Output Drive Mode"] pub struct PIN5_W<'a> { w: &'a mut W, } impl<'a> PIN5_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(7 << 20)) | ((value as u32 & 7) << 20); self.w } } #[doc = "Field `pin6` reader - P0.6 Default Output Drive Mode"] pub struct PIN6_R(crate::FieldReader<u8>); impl PIN6_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { PIN6_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for PIN6_R { type Target = crate::FieldReader<u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `pin6` writer - P0.6 Default Output Drive Mode"] pub struct PIN6_W<'a> { w: &'a mut W, } impl<'a> PIN6_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(7 << 24)) | ((value as u32 & 7) << 24); self.w } } #[doc = "Field `pin7` reader - P0.7 Default Output Drive Mode"] pub struct PIN7_R(crate::FieldReader<u8>); impl PIN7_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { PIN7_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for PIN7_R { type Target = crate::FieldReader<u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `pin7` writer - P0.7 Default Output Drive Mode"] pub struct PIN7_W<'a> { w: &'a mut W, } impl<'a> PIN7_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(7 << 28)) | ((value as u32 & 7) << 28); self.w } } impl R { #[doc = "Bits 0:2 - P0.0 Default Output Drive Mode"] #[inline(always)] pub fn pin0(&self) -> PIN0_R { PIN0_R::new((self.bits & 7) as u8) } #[doc = "Bits 4:6 - P0.1 Default Output Drive Mode"] #[inline(always)] pub fn pin1(&self) -> PIN1_R { PIN1_R::new(((self.bits >> 4) & 7) as u8) } #[doc = "Bits 8:10 - P0.2 Default Output Drive Mode"] #[inline(always)] pub fn pin2(&self) -> PIN2_R { PIN2_R::new(((self.bits >> 8) & 7) as u8) } #[doc = "Bits 12:14 - P0.3 Default Output Drive Mode"] #[inline(always)] pub fn pin3(&self) -> PIN3_R { PIN3_R::new(((self.bits >> 12) & 7) as u8) } #[doc = "Bits 16:18 - P0.4 Default Output Drive Mode"] #[inline(always)] pub fn pin4(&self) -> PIN4_R { PIN4_R::new(((self.bits >> 16) & 7) as u8) } #[doc = "Bits 20:22 - P0.5 Default Output Drive Mode"] #[inline(always)] pub fn pin5(&self) -> PIN5_R { PIN5_R::new(((self.bits >> 20) & 7) as u8) } #[doc = "Bits 24:26 - P0.6 Default Output Drive Mode"] #[inline(always)] pub fn pin6(&self) -> PIN6_R { PIN6_R::new(((self.bits >> 24) & 7) as u8) } #[doc = "Bits 28:30 - P0.7 Default Output Drive Mode"] #[inline(always)] pub fn pin7(&self) -> PIN7_R { PIN7_R::new(((self.bits >> 28) & 7) as u8) } } impl W { #[doc = "Bits 0:2 - P0.0 Default Output Drive Mode"] #[inline(always)] pub fn pin0(&mut self) -> PIN0_W { PIN0_W { w: self } } #[doc = "Bits 4:6 - P0.1 Default Output Drive Mode"] #[inline(always)] pub fn pin1(&mut self) -> PIN1_W { PIN1_W { w: self } } #[doc = "Bits 8:10 - P0.2 Default Output Drive Mode"] #[inline(always)] pub fn pin2(&mut self) -> PIN2_W { PIN2_W { w: self } } #[doc = "Bits 12:14 - P0.3 Default Output Drive Mode"] #[inline(always)] pub fn pin3(&mut self) -> PIN3_W { PIN3_W { w: self } } #[doc = "Bits 16:18 - P0.4 Default Output Drive Mode"] #[inline(always)] pub fn pin4(&mut self) -> PIN4_W { PIN4_W { w: self } } #[doc = "Bits 20:22 - P0.5 Default Output Drive Mode"] #[inline(always)] pub fn pin5(&mut self) -> PIN5_W { PIN5_W { w: self } } #[doc = "Bits 24:26 - P0.6 Default Output Drive Mode"] #[inline(always)] pub fn pin6(&mut self) -> PIN6_W { PIN6_W { w: self } } #[doc = "Bits 28:30 - P0.7 Default Output Drive Mode"] #[inline(always)] pub fn pin7(&mut self) -> PIN7_W { PIN7_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 = "Port P0 Default (Power-On Reset) Output Drive Mode\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 [rst_mode_p0](index.html) module"] pub struct RST_MODE_P0_SPEC; impl crate::RegisterSpec for RST_MODE_P0_SPEC { type Ux = u32; } #[doc = "`read()` method returns [rst_mode_p0::R](R) reader structure"] impl crate::Readable for RST_MODE_P0_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [rst_mode_p0::W](W) writer structure"] impl crate::Writable for RST_MODE_P0_SPEC { type Writer = W; } #[doc = "`reset()` method sets RST_MODE_P0 to value 0"] impl crate::Resettable for RST_MODE_P0_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
29.567493
442
0.569925
1e6a2a7b92860d42a30e8a1835e8792e877c544b
12,843
mod convert; use crate::{CalculatedSize, ControlNode, Node, Style}; use bevy_app::EventReader; use bevy_ecs::{ entity::Entity, query::{Changed, FilterFetch, With, Without, WorldQuery}, system::{Query, Res, ResMut}, }; use bevy_log::warn; use bevy_math::Vec2; use bevy_transform::prelude::{Children, Parent, Transform}; use bevy_utils::HashMap; use bevy_window::{Window, WindowId, WindowScaleFactorChanged, Windows}; use std::fmt; use stretch::{number::Number, Stretch}; pub struct FlexSurface { entity_to_stretch: HashMap<Entity, stretch::node::Node>, window_nodes: HashMap<WindowId, stretch::node::Node>, stretch: Stretch, } // SAFE: as long as MeasureFunc is Send + Sync. https://github.com/vislyhq/stretch/issues/69 unsafe impl Send for FlexSurface {} unsafe impl Sync for FlexSurface {} fn _assert_send_sync_flex_surface_impl_safe() { fn _assert_send_sync<T: Send + Sync>() {} _assert_send_sync::<HashMap<Entity, stretch::node::Node>>(); _assert_send_sync::<HashMap<WindowId, stretch::node::Node>>(); // FIXME https://github.com/vislyhq/stretch/issues/69 // _assert_send_sync::<Stretch>(); } impl fmt::Debug for FlexSurface { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("FlexSurface") .field("entity_to_stretch", &self.entity_to_stretch) .field("window_nodes", &self.window_nodes) .finish() } } impl Default for FlexSurface { fn default() -> Self { Self { entity_to_stretch: Default::default(), window_nodes: Default::default(), stretch: Stretch::new(), } } } impl FlexSurface { pub fn upsert_node(&mut self, entity: Entity, style: &Style, scale_factor: f64) { let mut added = false; let stretch = &mut self.stretch; let stretch_style = convert::from_style(scale_factor, style); let stretch_node = self.entity_to_stretch.entry(entity).or_insert_with(|| { added = true; stretch.new_node(stretch_style, Vec::new()).unwrap() }); if !added { self.stretch .set_style(*stretch_node, stretch_style) .unwrap(); } } pub fn upsert_leaf( &mut self, entity: Entity, style: &Style, calculated_size: CalculatedSize, scale_factor: f64, ) { let stretch = &mut self.stretch; let stretch_style = convert::from_style(scale_factor, style); let measure = Box::new(move |constraints: stretch::geometry::Size<Number>| { let mut size = convert::from_f32_size(scale_factor, calculated_size.size); match (constraints.width, constraints.height) { (Number::Undefined, Number::Undefined) => {} (Number::Defined(width), Number::Undefined) => { size.height = width * size.height / size.width; size.width = width; } (Number::Undefined, Number::Defined(height)) => { size.width = height * size.width / size.height; size.height = height; } (Number::Defined(width), Number::Defined(height)) => { size.width = width; size.height = height; } } Ok(size) }); if let Some(stretch_node) = self.entity_to_stretch.get(&entity) { self.stretch .set_style(*stretch_node, stretch_style) .unwrap(); self.stretch .set_measure(*stretch_node, Some(measure)) .unwrap(); } else { let stretch_node = stretch.new_leaf(stretch_style, measure).unwrap(); self.entity_to_stretch.insert(entity, stretch_node); } } pub fn update_children( &mut self, entity: Entity, children: &Children, control_node_query: &mut Query<&mut ControlNode>, unfiltered_children_query: &Query<&Children>, ) { let mut stretch_children = Vec::with_capacity(children.len()); fn inner( true_parent: Entity, child: Entity, control_node_query: &mut Query<&mut ControlNode>, unfiltered_children_query: &Query<&Children>, do_on_real: &mut impl FnMut(Entity), ) { if let Ok(mut control_node) = control_node_query.get_mut(child) { control_node.true_parent = Some(true_parent); for &child in unfiltered_children_query .get(child) .ok() .into_iter() .map(|c| &**c) .flatten() { inner( true_parent, child, control_node_query, unfiltered_children_query, do_on_real, ); } } else { do_on_real(child); } } for &child in children.iter() { inner( entity, child, control_node_query, unfiltered_children_query, &mut |e| { if let Some(stretch_node) = self.entity_to_stretch.get(&e) { stretch_children.push(*stretch_node); } else { warn!( "Unstyled child in a UI entity hierarchy. You are using an entity \ without UI components as a child of an entity with UI components, results may be unexpected." ); } }, ); } let stretch_node = self.entity_to_stretch.get(&entity).unwrap(); self.stretch .set_children(*stretch_node, stretch_children) .unwrap(); } pub fn update_window(&mut self, window: &Window) { let stretch = &mut self.stretch; let node = self.window_nodes.entry(window.id()).or_insert_with(|| { stretch .new_node(stretch::style::Style::default(), Vec::new()) .unwrap() }); stretch .set_style( *node, stretch::style::Style { size: stretch::geometry::Size { width: stretch::style::Dimension::Points(window.physical_width() as f32), height: stretch::style::Dimension::Points(window.physical_height() as f32), }, ..Default::default() }, ) .unwrap(); } pub fn set_window_children( &mut self, window_id: WindowId, children: impl Iterator<Item = Entity>, ) { let stretch_node = self.window_nodes.get(&window_id).unwrap(); let child_nodes = children .map(|e| *self.entity_to_stretch.get(&e).unwrap()) .collect::<Vec<stretch::node::Node>>(); self.stretch .set_children(*stretch_node, child_nodes) .unwrap(); } pub fn compute_window_layouts(&mut self) { for window_node in self.window_nodes.values() { self.stretch .compute_layout(*window_node, stretch::geometry::Size::undefined()) .unwrap(); } } pub fn get_layout(&self, entity: Entity) -> Result<&stretch::result::Layout, FlexError> { if let Some(stretch_node) = self.entity_to_stretch.get(&entity) { self.stretch .layout(*stretch_node) .map_err(FlexError::StretchError) } else { warn!( "Styled child in a non-UI entity hierarchy. You are using an entity \ with UI components as a child of an entity without UI components, results may be unexpected." ); Err(FlexError::InvalidHierarchy) } } } #[derive(Debug)] pub enum FlexError { InvalidHierarchy, StretchError(stretch::Error), } #[allow(clippy::too_many_arguments, clippy::type_complexity)] pub fn flex_node_system( windows: Res<Windows>, mut scale_factor_events: EventReader<WindowScaleFactorChanged>, mut flex_surface: ResMut<FlexSurface>, root_node_query: Query<Entity, (With<Node>, Without<Parent>)>, node_query: Query<(Entity, &Style, Option<&CalculatedSize>), (With<Node>, Changed<Style>)>, full_node_query: Query<(Entity, &Style, Option<&CalculatedSize>), With<Node>>, changed_size_query: Query< (Entity, &Style, &CalculatedSize), (With<Node>, Changed<CalculatedSize>), >, changed_children_query: Query<(Entity, &Children), (With<Node>, Changed<Children>)>, unfiltered_children_query: Query<&Children>, mut control_node_query: Query<&mut ControlNode>, changed_cnc_query: Query<Entity, (Changed<Children>, With<ControlNode>)>, mut node_transform_query: Query<(Entity, &mut Node, &mut Transform, Option<&Parent>)>, ) { // update window root nodes for window in windows.iter() { flex_surface.update_window(window); } // assume one window for time being... let logical_to_physical_factor = if let Some(primary_window) = windows.get_primary() { primary_window.scale_factor() } else { 1. }; if scale_factor_events.iter().next_back().is_some() { update_changed( &mut *flex_surface, logical_to_physical_factor, full_node_query, ); } else { update_changed(&mut *flex_surface, logical_to_physical_factor, node_query); } fn update_changed<F: WorldQuery>( flex_surface: &mut FlexSurface, scaling_factor: f64, query: Query<(Entity, &Style, Option<&CalculatedSize>), F>, ) where F::Fetch: FilterFetch, { // update changed nodes for (entity, style, calculated_size) in query.iter() { // TODO: remove node from old hierarchy if its root has changed if let Some(calculated_size) = calculated_size { flex_surface.upsert_leaf(entity, style, *calculated_size, scaling_factor); } else { flex_surface.upsert_node(entity, style, scaling_factor); } } } for (entity, style, calculated_size) in changed_size_query.iter() { flex_surface.upsert_leaf(entity, style, *calculated_size, logical_to_physical_factor); } // TODO: handle removed nodes // update window children (for now assuming all Nodes live in the primary window) if let Some(primary_window) = windows.get_primary() { flex_surface.set_window_children(primary_window.id(), root_node_query.iter()); } // update children for (entity, children) in changed_children_query.iter() { flex_surface.update_children( entity, children, &mut control_node_query, &unfiltered_children_query, ); } for entity in changed_cnc_query.iter() { let true_parent = if let Some(e) = control_node_query.get_mut(entity).unwrap().true_parent { e } else { continue; }; let children = unfiltered_children_query.get(true_parent).unwrap(); flex_surface.update_children( true_parent, children, &mut control_node_query, &unfiltered_children_query, ); } // compute layouts flex_surface.compute_window_layouts(); let physical_to_logical_factor = 1. / logical_to_physical_factor; let to_logical = |v| (physical_to_logical_factor * v as f64) as f32; // PERF: try doing this incrementally for (entity, mut node, mut transform, parent) in node_transform_query.iter_mut() { let layout = flex_surface.get_layout(entity).unwrap(); node.size = Vec2::new( to_logical(layout.size.width), to_logical(layout.size.height), ); let position = &mut transform.translation; position.x = to_logical(layout.location.x + layout.size.width / 2.0); position.y = to_logical(layout.location.y + layout.size.height / 2.0); if let Some(parent) = parent { let parent = control_node_query .get_mut(parent.0) .map(|cn| cn.true_parent.unwrap()) .unwrap_or(parent.0); if let Ok(parent_layout) = flex_surface.get_layout(parent) { position.x -= to_logical(parent_layout.size.width / 2.0); position.y -= to_logical(parent_layout.size.height / 2.0); } } } }
35.282967
100
0.573231
c1624c4d2d0f8603a41d971bfd8d949adfc926c2
662
//! OSC (Open Sound Control) protocol implementation. pub mod address; pub mod data; pub mod error; pub mod packet; /// Prelude module, prefixed with `Osc` to avoid identifier conflict. pub mod prelude { pub use crate::address::Address as OscAddress; pub use crate::data::Value as OscValue; pub use crate::error::{Error as OscError, Result as OscResult}; pub use crate::packet::{ Bundle as OscBundle, Message as OscMessage, MessageBuilder as OscMessageBuilder, Packet as OscPacket, }; #[cfg(feature = "address-pattern")] pub use crate::address::{AddressPattern as OscAddressPattern, Expression as OscExpression}; }
31.52381
95
0.71148
d9eff81864f1a1bf89324a98757bc69231c59076
3,665
use regex::Regex; #[derive(Debug, Clone)] pub struct Passport { byr: Option<String>, iyr: Option<String>, eyr: Option<String>, hgt: Option<String>, hcl: Option<String>, ecl: Option<String>, pid: Option<String>, cid: Option<String>, } lazy_static! { static ref CM_REGEX: Regex = Regex::new(r"^(\d+)cm$").unwrap(); static ref IN_REGEX: Regex = Regex::new(r"^(\d+)in$").unwrap(); static ref HCL_REGEX: Regex = Regex::new(r"#[0-9a-f]{6}").unwrap(); static ref ECL_REGEX: Regex = Regex::new(r"amb|blu|brn|gry|grn|hzl|oth").unwrap(); static ref PID_REGEX: Regex = Regex::new(r"[0-9]{9}").unwrap(); } impl Passport { pub fn from(string: &String) -> Passport { let mut passport = Passport { byr: None, iyr: None, eyr: None, hgt: None, hcl: None, ecl: None, pid: None, cid: None, }; string.split(" ").filter(|p| *p != "").for_each(|pair| { let key = pair.split(":").nth(0).unwrap(); let value = pair.split(":").nth(1).unwrap(); if key == "byr" { passport.byr = Some(value.to_string()) } else if key == "iyr" { passport.iyr = Some(value.to_string()) } else if key == "eyr" { passport.eyr = Some(value.to_string()) } else if key == "hgt" { passport.hgt = Some(value.to_string()) } else if key == "hcl" { passport.hcl = Some(value.to_string()) } else if key == "ecl" { passport.ecl = Some(value.to_string()) } else if key == "pid" { passport.pid = Some(value.to_string()) } else if key == "cid" { passport.cid = Some(value.to_string()) } }); return passport; } pub fn is_valid_stage1(&self) -> bool { return self.byr.is_some() && self.iyr.is_some() && self.eyr.is_some() && self.hgt.is_some() && self.hcl.is_some() && self.ecl.is_some() && self.pid.is_some(); } pub fn is_valid_stage2(&self) -> bool { is_within_range(&self.byr, 1920, 2002) && is_within_range(&self.iyr, 2010, 2020) && is_within_range(&self.eyr, 2020, 2030) && self.is_valid_height() && matches_exactly(&self.hcl, &HCL_REGEX) && matches_exactly(&self.ecl, &ECL_REGEX) && matches_exactly(&self.pid, &PID_REGEX) } fn is_valid_height(&self) -> bool { return match &self.hgt { Some(height) => { if CM_REGEX.is_match(&height) { let height = CM_REGEX.captures(&height).unwrap()[1].parse().unwrap(); return 150 <= height && height <= 190; } if IN_REGEX.is_match(&height) { let height = IN_REGEX.captures(&height).unwrap()[1].parse().unwrap(); return 59 <= height && height <= 76; } return false; }, None => false, } } } fn is_within_range(value: &Option<String> , from: i32, to: i32) -> bool { match value { Some(value) => { let parsed = value.parse::<i32>().unwrap(); return from <= parsed || parsed <= to; }, None => false } } fn matches_exactly(value: &Option<String>, regex: &Regex) -> bool { match value { Some(value) => { return regex.is_match(value); }, None => false } }
31.324786
89
0.490314
ab27750269a75e3b3c4fddf48b152e11dd1566ab
11,312
use std::cmp; #[derive(Debug, PartialEq, Clone, Copy, Eq)] pub enum Transform { HeadToTop, HeadToRight, HeadToBottom, HeadToLeft, HeadToTopInv, HeadToRightInv, HeadToBottomInv, HeadToLeftInv, } #[derive(Debug, PartialEq, Clone, Copy)] pub struct LinearCoeffs { pub shift: i16, pub factor: f32 } fn rect_avg(vec: &Vec<Vec<u8>>, x: usize, y: usize, side: usize) -> u8 { (vec[y..y+side].iter() .map(|ln| ln[x..x + side].iter().fold(0, |a, &el| a + el as usize)) .fold(0, |x, y| x + y as usize) / (side * side)) as u8 } pub trait ByteRect where Self: Sized { fn get_rect(&self, x: usize, y: usize, width: usize, height: usize) -> Self; fn get_square(&self, sq: SquareCoords) -> Self { self.get_rect(sq.x, sq.y, sq.side, sq.side) } fn transform(&self, Transform) -> Self; fn scale_down(&self, times: usize) -> Self; fn linear(&self, LinearCoeffs) -> Self; fn best_coeffs_to_match(&self, other: &Self) -> LinearCoeffs; fn dist(&self, other: &Self) -> u64; fn roughness(&self) -> u64 { let w = self.width(); let h = self.height(); if w < 2 || h < 2 { 1 } else { self.get_rect(0, 0, w - 1, h - 1).dist( &self.get_rect(1, 1, w - 1, h - 1) ) } } fn pad_to_divisible_by(&self, divisor: usize) -> Self; fn to_square_chunks(&self, size: usize) -> Vec<(SquareCoords, Self)>; fn width(&self) -> usize; fn height(&self) -> usize; } #[derive(Debug, PartialEq, Clone, Copy, Eq)] pub struct SquareCoords { pub x: usize, pub y: usize, pub side: usize, } impl ByteRect for Vec<Vec<u8>> { fn width(&self) -> usize { self[0].len() } fn height(&self) -> usize { self.len() } fn transform(&self, t: Transform) -> Self { let width = self[0].len(); let height = self.len(); let (x_rev, y_rev, ord_rev) = match t { Transform::HeadToTop => (false, false, false), Transform::HeadToRight => (true, false, true), Transform::HeadToBottom => (true, true, false), Transform::HeadToLeft => (false, true, true), Transform::HeadToTopInv => (true, false, false), Transform::HeadToRightInv => (false, false, true), Transform::HeadToBottomInv => (false, true, false), Transform::HeadToLeftInv => (true, true, true), }; let translate = |x: usize, y: usize| { let x_trans = if x_rev {width - x - 1} else {x}; let y_trans = if y_rev {height - y - 1} else {y}; self[y_trans][x_trans] }; if ord_rev { (0..width).map(|x| (0..height).map(|y| translate(x, y)).collect()).collect() } else { (0..height).map(|y| (0..width).map(|x| translate(x, y)).collect()).collect() } } fn scale_down(&self, times: usize) -> Self { let width = self[0].len(); let height = self.len(); if height % times != 0 || width % times != 0 { panic!(format!("Can only scale the multiples of {}", times)) } (0..height/times).map(|y| (0..width/times).map(|x| rect_avg(self, x * times, y * times, times)).collect()).collect() } fn linear(&self, c: LinearCoeffs) -> Self { self.iter().map(|ln| ln.iter().map(|&x| (x as f32).mul_add(c.factor, c.shift as f32).min(255.0).max(0.0) as u8) .collect()).collect() } fn best_coeffs_to_match(&self, other: &Self) -> LinearCoeffs { let width = self.width(); let height = self.height(); if other.height() != height || other.width() != width { panic!("can't handle different dimensions {}x{} and {}x{}", width, height, other.width(), other.height()); } let self_sum = self.iter().map(|ln| ln.iter().fold(0, |a, &el| a + el as i64)) .fold(0, |x, y| x + y); let other_sum = other.iter().map(|ln| ln.iter().fold(0, |a, &el| a + el as i64)) .fold(0, |x, y| x + y); let self_sqr_sum = self.iter().map(|ln| ln.iter().fold(0, |a, &el| a + el as i64 * el as i64)) .fold(0, |x, y| x + y); let count = (self.len() * self[0].len()) as i64; let prod_sum = (0..height) .map(|y| (0..width) .map(|x| self[y][x] as i64 * other[y][x] as i64) .fold(0, |a, el| a + el)) .fold(0, |a, el| a + el); let det = self_sqr_sum * count - self_sum * self_sum; LinearCoeffs { shift: ((self_sqr_sum * other_sum - prod_sum * self_sum) as f32 / det as f32).round() as i16, factor: ((prod_sum * count) as f32 - (self_sum * other_sum) as f32) / det as f32 } } fn get_rect(&self, x: usize, y: usize, width: usize, height: usize) -> Self { self[y..y + height] .iter() .map(|ln| ln[x..x + width].to_vec()) .collect() } fn dist(&self, other: &Self) -> u64 { let width = self.width(); let height = self.height(); if other.height() != height || other.width() != width { panic!("can't handle different dimensions {}x{} and {}x{}", width, height, other.width(), other.height()); } (0..height) .map(|y| (0..width) .map(|x| self[y][x] as i32 - other[y][x] as i32) .map(|diff| diff * diff) .fold(0, |a, diff| a + diff as u64)) .fold(0, |a, el| a + el) } fn pad_to_divisible_by(&self, divisor: usize) -> Self { let round = |x: usize| { (x + divisor - 1) / divisor * divisor }; let orig_width = self[0].len(); let orig_height = self.len(); let width = round(orig_width); let height = round(orig_height); (0..height) .map(|y| (0..width) .map(|x| self[cmp::min(y, orig_height - 1)][cmp::min(x, orig_width - 1)]) .collect()) .collect() } fn to_square_chunks(&self, size: usize) -> Vec<(SquareCoords, Self)> { let width = self[0].len(); let height = self.len(); if height % size != 0 || width % size != 0 { panic!("can't chunk what is not divisible by chunk size"); } (0..height / size) .flat_map(|chunk_y| (0..width / size) .map(move |chunk_x| SquareCoords { x: chunk_x * size, y: chunk_y * size, side: size, }) .map(|coords| (coords, self.get_square(coords))) ) .collect() } } #[cfg(test)] mod tests { use byte_rect::*; #[test] fn rotates_byte_rect() { let byte_rect = vec![ vec![1, 2], vec![3, 4], vec![5, 6], ]; let transformed = byte_rect.transform(Transform::HeadToRightInv); assert_eq!(transformed, vec![ vec![1, 3, 5], vec![2, 4, 6], ]); } #[test] fn scales_rect_down_twice() { let byte_rect = vec![ vec![1, 2], vec![3, 4], vec![5, 6], vec![7, 8], ]; let scaled = byte_rect.scale_down(2); assert_eq!(scaled, vec![ vec![2], vec![6], ]); } #[test] fn linear_multiplies_and_shifts_all_values() { let byte_rect = vec![ vec![1, 2], vec![3, 4], vec![5, 6], vec![7, 8], ]; let lineared = byte_rect.linear(LinearCoeffs { shift: 10, factor: -2.0 }); assert_eq!(lineared, vec![ vec![8, 6], vec![4, 2], vec![0, 0], vec![0, 0], ]); } #[test] fn least_squares_finds_the_perfect_shift_only_match() { let byte_rect = vec![ vec![10, 20], vec![30, 40], ]; let desired = vec![ vec![120, 130], vec![140, 150], ]; let LinearCoeffs{shift, factor} = byte_rect.best_coeffs_to_match(&desired); assert_eq!(shift, 110); assert!((factor - 1.0).abs() < 0.001, "factor was {}", factor); } #[test] fn linear_with_best_coeffs_yields_perfecly_the_same() { let byte_rect = vec![ vec![6, 5, 4], vec![3, 2, 1], ]; let desired = vec![ vec![10, 20, 30], vec![40, 50, 60], ]; let coeffs = byte_rect.best_coeffs_to_match(&desired); let adjusted = byte_rect.linear(coeffs); assert_eq!(adjusted, desired); } #[test] fn euclid_dist_works_correctly() { let r1 = vec![ vec![10, 20, 30], vec![40, 50, 60], ]; let r2 = vec![ vec![12, 20, 30], vec![40, 50, 58], ]; assert_eq!(r1.dist(&r2), 8); } #[test] fn linear_with_best_coeffs_yields_closer_than_intuitive() { let byte_rect = vec![ vec![6, 5, 4], vec![3, 3, 1], ]; let desired = vec![ vec![10, 20, 30], vec![40, 50, 60], ]; let coeffs = byte_rect.best_coeffs_to_match(&desired); let adjusted = byte_rect.linear(coeffs); let intuitive_adjusted = vec![ vec![10, 20, 30], vec![40, 40, 60], ]; assert!(desired.dist(&intuitive_adjusted) > desired.dist(&adjusted)); } #[test] fn pad_to_divisible_by_3_leaves_divisible_boundaries_untouched() { let byte_rect = vec![ vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9], vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9], ]; let padded = byte_rect.pad_to_divisible_by(3); assert_eq!(padded, byte_rect); } #[test] fn pad_to_divisible_by_3_padds_non_divisible_boundaries() { let byte_rect = vec![ vec![1, 2], vec![3, 4], vec![5, 6], vec![7, 8], ]; let padded = byte_rect.pad_to_divisible_by(3); let expected_padded = vec![ vec![1, 2, 2], vec![3, 4, 4], vec![5, 6, 6], vec![7, 8, 8], vec![7, 8, 8], vec![7, 8, 8], ]; assert_eq!(padded, expected_padded); } #[test] fn to_square_chunks_works() { let byte_rect = vec![ vec![11, 12, 13, 14], vec![21, 22, 23, 24], ]; let chunks = byte_rect.to_square_chunks(2); let expected_chunks = vec![ (SquareCoords { x: 0, y: 0, side: 2 }, vec![ vec![11, 12], vec![21, 22], ]), (SquareCoords { x: 2, y: 0, side: 2 }, vec![ vec![13, 14], vec![23, 24], ]), ]; assert_eq!(chunks, expected_chunks); } }
31.248619
105
0.4718
d57a584f7db80164255c9b9974c610fb384aa3ef
7,765
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 // Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 //! The following macros are slightly modified from rust-bitcoin. The original file may be found //! here: //! //! https://github.com/rust-bitcoin/rust-bitcoin/blob/master/src/internal_macros.rs macro_rules! impl_array_newtype { ($thing:ident, $ty:ty, $len:expr) => { impl $thing { #[inline] /// Converts the object to a raw pointer pub fn as_ptr(&self) -> *const $ty { let &$thing(ref dat) = self; dat.as_ptr() } #[inline] /// Converts the object to a mutable raw pointer pub fn as_mut_ptr(&mut self) -> *mut $ty { let &mut $thing(ref mut dat) = self; dat.as_mut_ptr() } #[inline] /// Returns the length of the object as an array pub fn len(&self) -> usize { $len } #[inline] /// Returns whether the object, as an array, is empty. Always false. pub fn is_empty(&self) -> bool { false } #[inline] /// Returns the underlying bytes. pub fn as_bytes(&self) -> &[$ty; $len] { &self.0 } #[inline] /// Returns the underlying bytes. pub fn to_bytes(&self) -> [$ty; $len] { self.0.clone() } #[inline] /// Returns the underlying bytes. pub fn into_bytes(self) -> [$ty; $len] { self.0 } } impl<'a> From<&'a [$ty]> for $thing { fn from(data: &'a [$ty]) -> $thing { assert_eq!(data.len(), $len); let mut ret = [0; $len]; ret.copy_from_slice(&data[..]); $thing(ret) } } impl ::std::ops::Index<usize> for $thing { type Output = $ty; #[inline] fn index(&self, index: usize) -> &$ty { let &$thing(ref dat) = self; &dat[index] } } impl_index_newtype!($thing, $ty); impl PartialEq for $thing { #[inline] fn eq(&self, other: &$thing) -> bool { &self[..] == &other[..] } } impl Eq for $thing {} impl PartialOrd for $thing { #[inline] fn partial_cmp(&self, other: &$thing) -> Option<::std::cmp::Ordering> { Some(self.cmp(&other)) } } impl Ord for $thing { #[inline] fn cmp(&self, other: &$thing) -> ::std::cmp::Ordering { // manually implement comparison to get little-endian ordering // (we need this for our numeric types; non-numeric ones shouldn't // be ordered anyway except to put them in BTrees or whatever, and // they don't care how we order as long as we're consistent). for i in 0..$len { if self[$len - 1 - i] < other[$len - 1 - i] { return ::std::cmp::Ordering::Less; } if self[$len - 1 - i] > other[$len - 1 - i] { return ::std::cmp::Ordering::Greater; } } ::std::cmp::Ordering::Equal } } #[cfg_attr(feature = "clippy", allow(expl_impl_clone_on_copy))] // we don't define the `struct`, we have to explicitly impl impl Clone for $thing { #[inline] fn clone(&self) -> $thing { $thing::from(&self[..]) } } impl Copy for $thing {} impl ::std::hash::Hash for $thing { #[inline] fn hash<H>(&self, state: &mut H) where H: ::std::hash::Hasher, { (&self[..]).hash(state); } fn hash_slice<H>(data: &[$thing], state: &mut H) where H: ::std::hash::Hasher, { for d in data.iter() { (&d[..]).hash(state); } } } }; } macro_rules! impl_array_newtype_encodable { ($thing:ident, $ty:ty, $len:expr) => { #[cfg(feature = "serde")] impl<'de> $crate::serde::Deserialize<'de> for $thing { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: $crate::serde::Deserializer<'de>, { use $crate::std::fmt::{self, Formatter}; struct Visitor; impl<'de> $crate::serde::de::Visitor<'de> for Visitor { type Value = $thing; fn expecting(&self, formatter: &mut Formatter) -> fmt::Result { formatter.write_str("a fixed size array") } #[inline] fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: $crate::serde::de::SeqAccess<'de>, { let mut ret: [$ty; $len] = [0; $len]; for item in ret.iter_mut() { *item = match seq.next_element()? { Some(c) => c, None => { return Err($crate::serde::de::Error::custom("end of stream")) } }; } Ok($thing(ret)) } } deserializer.deserialize_seq(Visitor) } } #[cfg(feature = "serde")] impl $crate::serde::Serialize for $thing { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: $crate::serde::Serializer, { let &$thing(ref dat) = self; (&dat[..]).serialize(serializer) } } }; } macro_rules! impl_array_newtype_show { ($thing:ident) => { impl ::std::fmt::Debug for $thing { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, concat!(stringify!($thing), "({:?})"), &self[..]) } } }; } macro_rules! impl_index_newtype { ($thing:ident, $ty:ty) => { impl ::std::ops::Index<::std::ops::Range<usize>> for $thing { type Output = [$ty]; #[inline] fn index(&self, index: ::std::ops::Range<usize>) -> &[$ty] { &self.0[index] } } impl ::std::ops::Index<::std::ops::RangeTo<usize>> for $thing { type Output = [$ty]; #[inline] fn index(&self, index: ::std::ops::RangeTo<usize>) -> &[$ty] { &self.0[index] } } impl ::std::ops::Index<::std::ops::RangeFrom<usize>> for $thing { type Output = [$ty]; #[inline] fn index(&self, index: ::std::ops::RangeFrom<usize>) -> &[$ty] { &self.0[index] } } impl ::std::ops::Index<::std::ops::RangeFull> for $thing { type Output = [$ty]; #[inline] fn index(&self, _: ::std::ops::RangeFull) -> &[$ty] { &self.0[..] } } }; }
31.184739
131
0.41906
39be2248fc5ff12bb260bc4794b17f79fcc75112
2,832
// Copyright 2018, Collabora, Ltd. // SPDX-License-Identifier: BSL-1.0 // Author: Ryan A. Pavlik <[email protected]> use crate::{error::*, prelude::*, Buffer, ConstantBufferSize, Unbuffer, WrappedConstantSize}; use bytes::{BufMut, Bytes}; use std::time::{Duration, SystemTime}; #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] pub struct Seconds(pub i32); #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] pub struct Microseconds(pub i32); #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] pub struct TimeVal { sec: Seconds, usec: Microseconds, } impl TimeVal { /// Constructor from components. /// /// TODO normalize? pub fn new(sec: Seconds, usec: Microseconds) -> Self { Self { sec, usec } } /// Get the seconds part pub fn seconds(&self) -> Seconds { self.sec } /// Get the microseconds part pub fn microseconds(&self) -> Microseconds { self.usec } pub fn get_time_of_day() -> TimeVal { TimeVal::from(SystemTime::now()) } } impl Default for TimeVal { fn default() -> Self { Self::new(Seconds(0), Microseconds(0)) } } impl From<SystemTime> for TimeVal { fn from(v: SystemTime) -> Self { // In practice this should always work. let since_epoch = v.duration_since(SystemTime::UNIX_EPOCH).unwrap(); TimeVal::new( Seconds(since_epoch.as_secs() as i32), Microseconds(since_epoch.subsec_micros() as i32), ) } } impl From<TimeVal> for SystemTime { fn from(v: TimeVal) -> Self { SystemTime::UNIX_EPOCH + Duration::from_secs(v.seconds().0 as u64) + Duration::from_micros(v.microseconds().0 as u64) } } impl WrappedConstantSize for Seconds { type WrappedType = i32; fn get(&self) -> Self::WrappedType { self.0 } fn new(v: Self::WrappedType) -> Self { Seconds(v) } } impl WrappedConstantSize for Microseconds { type WrappedType = i32; fn get(&self) -> Self::WrappedType { self.0 } fn new(v: Self::WrappedType) -> Self { Microseconds(v) } } impl ConstantBufferSize for TimeVal { fn constant_buffer_size() -> usize { Seconds::constant_buffer_size() + Microseconds::constant_buffer_size() } } impl Buffer for TimeVal { fn buffer_ref<T: BufMut>(&self, buf: &mut T) -> EmptyResult { buf.buffer(self.seconds()) .and_then(|buf| self.microseconds().buffer_ref(buf)) } } impl Unbuffer for TimeVal { fn unbuffer_ref(buf: &mut Bytes) -> Result<Self> { Seconds::unbuffer_ref(buf) .and_then(|sec| Microseconds::unbuffer_ref(buf).map(|v| (v, sec))) .and_then(|(usec, sec)| Ok(TimeVal::new(sec, usec))) } }
25.745455
93
0.617232
56397106c41d62332525ce3c1b63aa34ff93fef0
7,045
//! `String` impl use crate::avm2::activation::Activation; use crate::avm2::class::{Class, ClassAttributes}; use crate::avm2::method::{Method, NativeMethodImpl}; use crate::avm2::names::{Namespace, QName}; use crate::avm2::object::{primitive_allocator, Object, TObject}; use crate::avm2::value::Value; use crate::avm2::ArrayObject; use crate::avm2::Error; use crate::string::utils as string_utils; use crate::string::AvmString; use gc_arena::{GcCell, MutationContext}; use std::iter; /// Implements `String`'s instance initializer. pub fn instance_init<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { activation.super_init(this, &[])?; if let Some(mut value) = this.as_primitive_mut(activation.context.gc_context) { if !matches!(*value, Value::String(_)) { *value = args .get(0) .unwrap_or(&Value::String("".into())) .coerce_to_string(activation)? .into(); } } } Ok(Value::Undefined) } /// Implements `String`'s class initializer. pub fn class_init<'gc>( _activation: &mut Activation<'_, 'gc, '_>, _this: Option<Object<'gc>>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { Ok(Value::Undefined) } /// Implements `length` property's getter fn length<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { if let Value::String(s) = this.value_of(activation.context.gc_context)? { return Ok(s.encode_utf16().count().into()); } } Ok(Value::Undefined) } /// Implements `String.charAt` fn char_at<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { if let Value::String(s) = this.value_of(activation.context.gc_context)? { // This function takes Number, so if we use coerce_to_i32 instead of coerce_to_number, the value may overflow. let n = args .get(0) .unwrap_or(&Value::Number(0.0)) .coerce_to_number(activation)?; if n < 0.0 { return Ok("".into()); } let index = if !n.is_nan() { n as usize } else { 0 }; let ret = s .encode_utf16() .nth(index) .map(|c| string_utils::utf16_code_unit_to_char(c).to_string()) .unwrap_or_default(); return Ok(AvmString::new(activation.context.gc_context, ret).into()); } } Ok(Value::Undefined) } /// Implements `String.charCodeAt` fn char_code_at<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { if let Value::String(s) = this.value_of(activation.context.gc_context)? { // This function takes Number, so if we use coerce_to_i32 instead of coerce_to_number, the value may overflow. let n = args .get(0) .unwrap_or(&Value::Number(0.0)) .coerce_to_number(activation)?; if n < 0.0 { return Ok(f64::NAN.into()); } let index = if !n.is_nan() { n as usize } else { 0 }; let ret = s .encode_utf16() .nth(index) .map(f64::from) .unwrap_or(f64::NAN); return Ok(ret.into()); } } Ok(Value::Undefined) } /// Implements `String.split` fn split<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { let delimiter = args.get(0).unwrap_or(&Value::Undefined); if matches!(delimiter, Value::Undefined) { let this = Value::from(this); return Ok( ArrayObject::from_storage(activation, iter::once(this).collect()) .unwrap() .into(), ); } if delimiter .coerce_to_object(activation)? .as_regexp() .is_some() { log::warn!("string.split(regex) - not implemented"); } let this = Value::from(this).coerce_to_string(activation)?; let delimiter = delimiter.coerce_to_string(activation)?; let limit = match args.get(1).unwrap_or(&Value::Undefined) { Value::Undefined => usize::MAX, limit => limit.coerce_to_i32(activation)?.max(0) as usize, }; if delimiter.is_empty() { // When using an empty delimiter, Rust's str::split adds an extra beginning and trailing item, but Flash does not. // e.g., split("foo", "") returns ["", "f", "o", "o", ""] in Rust but ["f, "o", "o"] in Flash. // Special case this to match Flash's behavior. return Ok(ArrayObject::from_storage( activation, this.chars() .take(limit) .map(|c| AvmString::new(activation.context.gc_context, c.to_string())) .collect(), ) .unwrap() .into()); } else { return Ok(ArrayObject::from_storage( activation, this.split(delimiter.as_ref()) .take(limit) .map(|c| AvmString::new(activation.context.gc_context, c.to_string())) .collect(), ) .unwrap() .into()); } } Ok(Value::Undefined) } /// Construct `String`'s class. pub fn create_class<'gc>(mc: MutationContext<'gc, '_>) -> GcCell<'gc, Class<'gc>> { let class = Class::new( QName::new(Namespace::public(), "String"), Some(QName::new(Namespace::public(), "Object").into()), Method::from_builtin(instance_init, "<String instance initializer>", mc), Method::from_builtin(class_init, "<String class initializer>", mc), mc, ); let mut write = class.write(mc); write.set_attributes(ClassAttributes::FINAL | ClassAttributes::SEALED); write.set_instance_allocator(primitive_allocator); const PUBLIC_INSTANCE_PROPERTIES: &[( &str, Option<NativeMethodImpl>, Option<NativeMethodImpl>, )] = &[("length", Some(length), None)]; write.define_public_builtin_instance_properties(mc, PUBLIC_INSTANCE_PROPERTIES); const AS3_INSTANCE_METHODS: &[(&str, NativeMethodImpl)] = &[ ("charAt", char_at), ("charCodeAt", char_code_at), ("split", split), ]; write.define_as3_builtin_instance_methods(mc, AS3_INSTANCE_METHODS); class }
33.547619
126
0.550035
d98e4f439af8531a6b7ac030bc6264f32be0ac33
5,124
use super::{rejection::*, FromRequest, RequestParts}; use async_trait::async_trait; use std::sync::Arc; /// Access the path in the router that matches the request. /// /// ``` /// use axum::{ /// Router, /// extract::MatchedPath, /// routing::get, /// }; /// /// let app = Router::new().route( /// "/users/:id", /// get(|path: MatchedPath| async move { /// let path = path.as_str(); /// // `path` will be "/users/:id" /// }) /// ); /// # async { /// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); /// # }; /// ``` /// /// `MatchedPath` can also be accessed from middleware via request extensions. /// This is useful for example with [`Trace`](tower_http::trace::Trace) to /// create a span that contains the matched path: /// /// ``` /// use axum::{ /// Router, /// extract::MatchedPath, /// http::Request, /// routing::get, /// }; /// use tower_http::trace::TraceLayer; /// /// let app = Router::new() /// .route("/users/:id", get(|| async { /* ... */ })) /// .layer( /// TraceLayer::new_for_http().make_span_with(|req: &Request<_>| { /// let path = if let Some(path) = req.extensions().get::<MatchedPath>() { /// path.as_str() /// } else { /// req.uri().path() /// }; /// tracing::info_span!("http-request", %path) /// }), /// ); /// # async { /// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); /// # }; /// ``` #[derive(Clone, Debug)] pub struct MatchedPath(pub(crate) Arc<str>); impl MatchedPath { /// Returns a `str` representation of the path. pub fn as_str(&self) -> &str { &*self.0 } } #[async_trait] impl<B> FromRequest<B> for MatchedPath where B: Send, { type Rejection = MatchedPathRejection; async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { let matched_path = req .extensions() .get::<Self>() .ok_or(MatchedPathRejection::MatchedPathMissing(MatchedPathMissing))? .clone(); Ok(matched_path) } } #[cfg(test)] mod tests { use super::*; use crate::{extract::Extension, handler::Handler, routing::get, test_helpers::*, Router}; use http::Request; use std::task::{Context, Poll}; use tower_service::Service; #[derive(Clone)] struct SetMatchedPathExtension<S>(S); impl<B, S> Service<Request<B>> for SetMatchedPathExtension<S> where S: Service<Request<B>>, { type Response = S::Response; type Error = S::Error; type Future = S::Future; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.0.poll_ready(cx) } fn call(&mut self, mut req: Request<B>) -> Self::Future { let path = req .extensions() .get::<MatchedPath>() .unwrap() .as_str() .to_owned(); req.extensions_mut().insert(MatchedPathFromMiddleware(path)); self.0.call(req) } } #[derive(Clone)] struct MatchedPathFromMiddleware(String); #[tokio::test] async fn access_matched_path() { let api = Router::new().route( "/users/:id", get(|path: MatchedPath| async move { path.as_str().to_owned() }), ); async fn handler( path: MatchedPath, Extension(MatchedPathFromMiddleware(path_from_middleware)): Extension< MatchedPathFromMiddleware, >, ) -> String { format!( "extractor = {}, middleware = {}", path.as_str(), path_from_middleware ) } let app = Router::new() .route( "/:key", get(|path: MatchedPath| async move { path.as_str().to_owned() }), ) .nest("/api", api) .nest( "/public", Router::new().route("/assets/*path", get(handler)), ) .nest("/foo", handler.into_service()) .layer(tower::layer::layer_fn(SetMatchedPathExtension)); let client = TestClient::new(app); let res = client.get("/foo").send().await; assert_eq!(res.text().await, "/:key"); let res = client.get("/api/users/123").send().await; assert_eq!(res.text().await, "/api/users/:id"); let res = client.get("/public/assets/css/style.css").send().await; assert_eq!( res.text().await, "extractor = /public/assets/*path, middleware = /public/assets/*path" ); let res = client.get("/foo/bar/baz").send().await; assert_eq!( res.text().await, format!( "extractor = /foo/*{}, middleware = /foo/*{}", crate::routing::NEST_TAIL_PARAM, crate::routing::NEST_TAIL_PARAM, ), ); } }
28.625698
93
0.516979
aca7ad192b857cc4f5364f35688482cb61c1a1d7
20,149
use crate::{ avm1::SoundObject, avm2::Event as Avm2Event, avm2::SoundChannelObject, display_object::{self, DisplayObject, MovieClip, TDisplayObject}, }; use downcast_rs::Downcast; use gc_arena::Collect; use generational_arena::{Arena, Index}; pub mod decoders; pub mod swf { pub use swf::{ read, AudioCompression, CharacterId, Sound, SoundEnvelope, SoundEnvelopePoint, SoundEvent, SoundFormat, SoundInfo, SoundStreamHead, }; } mod mixer; pub use mixer::*; pub type SoundHandle = Index; pub type SoundInstanceHandle = Index; pub type PreloadStreamHandle = u32; type Error = Box<dyn std::error::Error>; pub trait AudioBackend: Downcast { fn play(&mut self); fn pause(&mut self); fn register_sound(&mut self, swf_sound: &swf::Sound) -> Result<SoundHandle, Error>; /// Used by the web backend to pre-decode sound streams. /// Returns the sound handle to be used to add data to the stream. /// Other backends return `None`. /// TODO: Get rid of the preload_* methods when web backend has a better way /// of decoding audio on the fly. fn preload_sound_stream_head( &mut self, _stream_info: &swf::SoundStreamHead, ) -> Option<PreloadStreamHandle> { None } /// Used by the web backend to add data to a currently preloading sound stream. fn preload_sound_stream_block( &mut self, _stream: PreloadStreamHandle, _clip_frame: u16, _audio_data: &[u8], ) { } /// Used by the web backend to finalize and decode a sound stream. /// Returns true if this was a valid stream. fn preload_sound_stream_end(&mut self, _stream: PreloadStreamHandle) -> Option<SoundHandle> { None } /// Plays a sound. fn start_sound( &mut self, sound: SoundHandle, settings: &swf::SoundInfo, ) -> Result<SoundInstanceHandle, Error>; /// Starts playing a "stream" sound, which is an audio stream that is distributed /// among the frames of a Flash MovieClip. /// On the web backend, `stream_handle` should be the handle for the preloaded stream. /// Other backends can pass `None`. fn start_stream( &mut self, stream_handle: Option<SoundHandle>, clip_frame: u16, clip_data: crate::tag_utils::SwfSlice, handle: &swf::SoundStreamHead, ) -> Result<SoundInstanceHandle, Error>; /// Stops a playing sound instance. /// No-op if the sound is not playing. fn stop_sound(&mut self, sound: SoundInstanceHandle); /// Good ol' stopAllSounds() :-) fn stop_all_sounds(&mut self); /// Get the position of a sound instance in milliseconds. /// Returns `None` if ther sound is not/no longer playing fn get_sound_position(&self, instance: SoundInstanceHandle) -> Option<f64>; /// Get the duration of a sound in milliseconds. /// Returns `None` if sound is not registered. fn get_sound_duration(&self, sound: SoundHandle) -> Option<f64>; /// Get the size of the data stored within a given sound. /// /// This is specifically measured in compressed bytes. fn get_sound_size(&self, sound: SoundHandle) -> Option<u32>; /// Get the sound format that a given sound was added with. fn get_sound_format(&self, sound: SoundHandle) -> Option<&swf::SoundFormat>; /// Set the volume transform for a sound instance. fn set_sound_transform(&mut self, instance: SoundInstanceHandle, transform: SoundTransform); // TODO: Eventually remove this/move it to library. fn is_loading_complete(&self) -> bool { true } /// Allows the audio backend to update. /// /// Runs once per event loop iteration. fn tick(&mut self) {} /// Inform the audio backend of the current stage frame rate. /// /// This is only necessary if your particular audio backend needs to know /// what the stage frame rate is. Otherwise, you are free to avoid /// implementing it. fn set_frame_rate(&mut self, _frame_rate: f64) {} } impl_downcast!(AudioBackend); /// Information about a sound provided to `NullAudioBackend`. struct NullSound { /// The duration of the sound in milliseconds. duration: f64, /// The compressed size of the sound data, excluding MP3 latency seek data. size: u32, /// The stated format of the sound data. format: swf::SoundFormat, } /// Audio backend that ignores all audio. pub struct NullAudioBackend { sounds: Arena<NullSound>, } impl NullAudioBackend { pub fn new() -> NullAudioBackend { NullAudioBackend { sounds: Arena::new(), } } } impl AudioBackend for NullAudioBackend { fn play(&mut self) {} fn pause(&mut self) {} fn register_sound(&mut self, sound: &swf::Sound) -> Result<SoundHandle, Error> { // Slice off latency seek for MP3 data. let data = if sound.format.compression == swf::AudioCompression::Mp3 { &sound.data[2..] } else { sound.data }; // AS duration does not subtract `skip_sample_frames`. let num_sample_frames: f64 = sound.num_samples.into(); let sample_rate: f64 = sound.format.sample_rate.into(); let duration = num_sample_frames * 1000.0 / sample_rate; Ok(self.sounds.insert(NullSound { duration, size: data.len() as u32, format: sound.format.clone(), })) } fn start_sound( &mut self, _sound: SoundHandle, _sound_info: &swf::SoundInfo, ) -> Result<SoundInstanceHandle, Error> { Ok(SoundInstanceHandle::from_raw_parts(0, 0)) } fn start_stream( &mut self, _stream_handle: Option<SoundHandle>, _clip_frame: u16, _clip_data: crate::tag_utils::SwfSlice, _handle: &swf::SoundStreamHead, ) -> Result<SoundInstanceHandle, Error> { Ok(SoundInstanceHandle::from_raw_parts(0, 0)) } fn stop_sound(&mut self, _sound: SoundInstanceHandle) {} fn stop_all_sounds(&mut self) {} fn get_sound_position(&self, _instance: SoundInstanceHandle) -> Option<f64> { Some(0.0) } fn get_sound_duration(&self, sound: SoundHandle) -> Option<f64> { if let Some(sound) = self.sounds.get(sound) { Some(sound.duration) } else { None } } fn get_sound_size(&self, sound: SoundHandle) -> Option<u32> { if let Some(sound) = self.sounds.get(sound) { Some(sound.size) } else { None } } fn get_sound_format(&self, sound: SoundHandle) -> Option<&swf::SoundFormat> { self.sounds.get(sound).map(|s| &s.format) } fn set_sound_transform(&mut self, _instance: SoundInstanceHandle, _transform: SoundTransform) {} } impl Default for NullAudioBackend { fn default() -> Self { NullAudioBackend::new() } } #[derive(Collect)] #[collect(no_drop)] pub struct AudioManager<'gc> { /// The list of actively playing sounds. sounds: Vec<SoundInstance<'gc>>, /// The global sound transform applied to all sounds. global_sound_transform: display_object::SoundTransform, /// The number of seconds that a timeline audio stream should buffer before playing. /// /// This is returned by `_soundbuftime` in AVM1 and `SoundMixer.bufferTime` in AVM2. /// Currently unused by Ruffle. /// [ActionScript 3.0: SoundMixer.bufferTime](https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/media/SoundMixer.html#bufferTime) stream_buffer_time: i32, /// Whether a sound transform has been changed. transforms_dirty: bool, } impl<'gc> AudioManager<'gc> { /// The maximum number of sound instances that can play at once. pub const MAX_SOUNDS: usize = 32; /// The default timeline stream buffer time in seconds. pub const DEFAULT_STREAM_BUFFER_TIME: i32 = 5; pub fn new() -> Self { Self { sounds: Vec::with_capacity(Self::MAX_SOUNDS), global_sound_transform: Default::default(), stream_buffer_time: Self::DEFAULT_STREAM_BUFFER_TIME, transforms_dirty: false, } } /// Update state of active sounds. Should be called once per frame. pub fn update_sounds( &mut self, audio: &mut dyn AudioBackend, gc_context: gc_arena::MutationContext<'gc, '_>, action_queue: &mut crate::context::ActionQueue<'gc>, root: DisplayObject<'gc>, ) { // Update the position of sounds, and remove any completed sounds. self.sounds.retain(|sound| { if let Some(pos) = audio.get_sound_position(sound.instance) { // Sounds still playing; update position. if let Some(avm1_object) = sound.avm1_object { avm1_object.set_position(gc_context, pos.round() as u32); } else if let Some(avm2_object) = sound.avm2_object { avm2_object.set_position(gc_context, pos); } true } else { // Sound ended. let duration = sound .sound .and_then(|sound| audio.get_sound_duration(sound)) .unwrap_or_default(); if let Some(object) = sound.avm1_object { object.set_position(gc_context, duration.round() as u32); // Fire soundComplete event. action_queue.queue_actions( root, crate::context::ActionType::Method { object: object.into(), name: "onSoundComplete", args: vec![], }, false, ); } if let Some(object) = sound.avm2_object { object.set_position(gc_context, duration); //TODO: AVM2 events are usually not queued, but we can't //hold the update context in the audio manager yet. action_queue.queue_actions( root, crate::context::ActionType::Event2 { event: Avm2Event::new("soundComplete"), target: object.into(), }, false, ) } false } }); // Update sound transforms, if dirty. self.update_sound_transforms(audio); } pub fn start_sound( &mut self, audio: &mut dyn AudioBackend, sound: SoundHandle, settings: &swf::SoundInfo, display_object: Option<DisplayObject<'gc>>, avm1_object: Option<SoundObject<'gc>>, ) -> Option<SoundInstanceHandle> { if self.sounds.len() < Self::MAX_SOUNDS { let handle = audio.start_sound(sound, settings).ok()?; let instance = SoundInstance { sound: Some(sound), instance: handle, display_object, transform: display_object::SoundTransform::default(), avm1_object, avm2_object: None, }; audio.set_sound_transform(handle, self.transform_for_sound(&instance)); self.sounds.push(instance); Some(handle) } else { None } } pub fn attach_avm2_sound_channel( &mut self, instance: SoundInstanceHandle, avm2_object: SoundChannelObject<'gc>, ) { if let Some(i) = self .sounds .iter() .position(|other| other.instance == instance) { let instance = &mut self.sounds[i]; instance.avm2_object = Some(avm2_object); } } pub fn stop_sound(&mut self, audio: &mut dyn AudioBackend, instance: SoundInstanceHandle) { if let Some(i) = self .sounds .iter() .position(|other| other.instance == instance) { let instance = &self.sounds[i]; audio.stop_sound(instance.instance); self.sounds.swap_remove(i); } } pub fn stop_sounds_with_handle(&mut self, audio: &mut dyn AudioBackend, sound: SoundHandle) { self.sounds.retain(move |other| { if other.sound == Some(sound) { audio.stop_sound(other.instance); false } else { true } }); } pub fn stop_sounds_with_display_object( &mut self, audio: &mut dyn AudioBackend, display_object: DisplayObject<'gc>, ) { self.sounds.retain(move |sound| { if let Some(other) = sound.display_object { if DisplayObject::ptr_eq(other, display_object) { audio.stop_sound(sound.instance); return false; } } true }); } pub fn stop_all_sounds(&mut self, audio: &mut dyn AudioBackend) { self.sounds.clear(); audio.stop_all_sounds(); } pub fn is_sound_playing_with_handle(&mut self, sound: SoundHandle) -> bool { self.sounds.iter().any(|other| other.sound == Some(sound)) } pub fn start_stream( &mut self, audio: &mut dyn AudioBackend, stream_handle: Option<SoundHandle>, movie_clip: MovieClip<'gc>, clip_frame: u16, data: crate::tag_utils::SwfSlice, stream_info: &swf::SoundStreamHead, ) -> Option<SoundInstanceHandle> { if self.sounds.len() < Self::MAX_SOUNDS { let handle = audio .start_stream(stream_handle, clip_frame, data, stream_info) .ok()?; let instance = SoundInstance { sound: None, instance: handle, display_object: Some(movie_clip.into()), transform: display_object::SoundTransform::default(), avm1_object: None, avm2_object: None, }; audio.set_sound_transform(handle, self.transform_for_sound(&instance)); self.sounds.push(instance); Some(handle) } else { None } } pub fn global_sound_transform(&self) -> &display_object::SoundTransform { &self.global_sound_transform } pub fn set_global_sound_transform(&mut self, sound_transform: display_object::SoundTransform) { self.global_sound_transform = sound_transform; self.transforms_dirty = true; } /// Get the local sound transform of a single sound instance. pub fn local_sound_transform( &self, instance: SoundInstanceHandle, ) -> Option<&display_object::SoundTransform> { if let Some(i) = self .sounds .iter() .position(|other| other.instance == instance) { let instance = &self.sounds[i]; Some(&instance.transform) } else { None } } /// Set the local sound transform of a single sound instance. pub fn set_local_sound_transform( &mut self, instance: SoundInstanceHandle, sound_transform: display_object::SoundTransform, ) { if let Some(i) = self .sounds .iter() .position(|other| other.instance == instance) { let instance = &mut self.sounds[i]; instance.transform = sound_transform; self.transforms_dirty = true; } } /// Returns the number of seconds that a timeline audio stream should buffer before playing. /// /// Currently unused by Ruffle. pub fn stream_buffer_time(&self) -> i32 { self.stream_buffer_time } /// Sets the number of seconds that a timeline audio stream should buffer before playing. /// /// Currently unused by Ruffle. pub fn set_stream_buffer_time(&mut self, stream_buffer_time: i32) { self.stream_buffer_time = stream_buffer_time; } pub fn set_sound_transforms_dirty(&mut self) { self.transforms_dirty = true; } fn transform_for_sound(&self, sound: &SoundInstance<'gc>) -> SoundTransform { let mut transform = sound.transform.clone(); let mut parent = sound.display_object; while let Some(display_object) = parent { transform.concat(display_object.base().sound_transform()); parent = display_object.parent(); } transform.concat(&self.global_sound_transform); transform.into() } /// Update the sound transforms for all sounds. /// This should be called whenever a sound transform changes on a display object. fn update_sound_transforms(&mut self, audio: &mut dyn AudioBackend) { // This updates the sound transform for all sounds, even though the transform has // only changed on a single display object. There are only a small amount // of sounds playing at any time, so this shouldn't be a big deal. if self.transforms_dirty { for sound in &self.sounds { let transform = self.transform_for_sound(sound); audio.set_sound_transform(sound.instance, transform); } self.transforms_dirty = false; } } } impl<'gc> Default for AudioManager<'gc> { fn default() -> Self { Self::new() } } #[derive(Clone, Collect)] #[collect(no_drop)] pub struct SoundInstance<'gc> { /// The handle to the sound instance in the audio backend. #[collect(require_static)] instance: SoundInstanceHandle, /// The handle to the sound definition in the audio backend. /// This will be `None` for stream sounds. #[collect(require_static)] sound: Option<SoundHandle>, /// The display object that this sound is playing in, if any. /// Used for volume mixing and `Sound.stop()`. display_object: Option<DisplayObject<'gc>>, /// The local sound transform of this sound. /// /// Only AVM2 sounds have a local sound transform. In AVM1, sound instances /// instead get the sound transform of the display object they're /// associated with. transform: display_object::SoundTransform, /// The AVM1 `Sound` object associated with this sound, if any. avm1_object: Option<SoundObject<'gc>>, /// The AVM2 `SoundChannel` object associated with this sound, if any. avm2_object: Option<SoundChannelObject<'gc>>, } /// A sound transform for a playing sound, for use by audio backends. /// This differs from `display_object::SoundTransform` by being /// already converted to `f32` and having `volume` baked in. #[derive(Debug, PartialEq, Clone, Collect)] #[collect(require_static)] pub struct SoundTransform { pub left_to_left: f32, pub left_to_right: f32, pub right_to_left: f32, pub right_to_right: f32, } impl From<display_object::SoundTransform> for SoundTransform { /// Converts from a `display_object::SoundTransform` to a `backend::audio::SoundTransform`. fn from(other: display_object::SoundTransform) -> Self { const SCALE: f32 = display_object::SoundTransform::MAX_VOLUME.pow(2) as f32; // The volume multiplication wraps around at `u32::MAX`. Self { left_to_left: other.left_to_left.wrapping_mul(other.volume) as f32 / SCALE, left_to_right: other.left_to_right.wrapping_mul(other.volume) as f32 / SCALE, right_to_left: other.right_to_left.wrapping_mul(other.volume) as f32 / SCALE, right_to_right: other.right_to_right.wrapping_mul(other.volume) as f32 / SCALE, } } } impl Default for SoundTransform { fn default() -> Self { Self { left_to_left: 1.0, left_to_right: 0.0, right_to_left: 0.0, right_to_right: 1.0, } } }
33.414594
157
0.602362
f4511a1cac4864637ae394fa579fdc50373a522b
2,043
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 OR MIT // Manually modify vtable pointers to force a failure with restrictions. // FIXME until the corresponding CBMC path lands: https://github.com/diffblue/cbmc/pull/6376 // kani-expect-fail // kani-flags: --restrict-vtable #![feature(core_intrinsics)] #![feature(ptr_metadata)] use std::any::Any; use std::intrinsics::size_of; use std::ptr::DynMetadata; include!("../Helpers/vtable_utils_ignore.rs"); struct Sheep {} struct Cow {} trait Animal { // Instance method signature fn noise(&self) -> i32; } trait Other { // Instance method signature fn noise(&self) -> i32; } // Implement the `Animal` trait for `Sheep`. impl Animal for Sheep { fn noise(&self) -> i32 { 1 } } // Implement the `Animal` trait for `Cow`. impl Animal for Cow { fn noise(&self) -> i32 { 2 } } impl Other for i32 { fn noise(&self) -> i32 { 3 } } // Returns some struct that implements Animal, but we don't know which one at compile time. fn random_animal(random_number: i64) -> Box<dyn Animal> { if random_number < 5 { Box::new(Sheep {}) } else { Box::new(Cow {}) } } #[kani::proof] fn main() { let random_number = kani::nondet(); let animal = random_animal(random_number); let s = animal.noise(); if random_number < 5 { assert!(s == 1); } else { assert!(s == 2); } let other = &5 as &dyn Other; // Manually transmute other's vtable to point to a different method unsafe { let vtable_metadata: std::ptr::DynMetadata<dyn std::any::Any> = vtable!(other); let vtable_ptr: *mut usize = std::mem::transmute(vtable_metadata); let noise_ptr = vtable_ptr.offset(3); let cow_ptr: *mut usize = std::mem::transmute(&Cow::noise); *noise_ptr = cow_ptr as usize; } // This would pass without the check that the function pointer is in the restricted set assert!(other.noise() == 2); }
24.614458
92
0.638767
d7caf02488a2bd6870ecd6ce4f970fa1d7c38938
14,817
//! This module implements the global `Reflect` object. //! //! The `Reflect` global object is a built-in object that provides methods for interceptable //! JavaScript operations. //! //! More information: //! - [ECMAScript reference][spec] //! - [MDN documentation][mdn] //! //! [spec]: https://tc39.es/ecma262/#sec-reflect-object //! [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect use crate::{ builtins::{self, BuiltIn}, object::{Object, ObjectData, ObjectInitializer}, property::{Attribute, DataDescriptor}, symbol::WellKnownSymbols, BoaProfiler, Context, Result, Value, }; #[cfg(test)] mod tests; /// Javascript `Reflect` object. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub(crate) struct Reflect; impl BuiltIn for Reflect { const NAME: &'static str = "Reflect"; fn attribute() -> Attribute { Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE } fn init(context: &mut Context) -> (&'static str, Value, Attribute) { let _timer = BoaProfiler::global().start_event(Self::NAME, "init"); let to_string_tag = WellKnownSymbols::to_string_tag(); let object = ObjectInitializer::new(context) .function(Self::apply, "apply", 3) .function(Self::construct, "construct", 2) .function(Self::define_property, "defineProperty", 3) .function(Self::delete_property, "deleteProperty", 2) .function(Self::get, "get", 2) .function( Self::get_own_property_descriptor, "getOwnPropertyDescriptor", 2, ) .function(Self::get_prototype_of, "getPrototypeOf", 1) .function(Self::has, "has", 2) .function(Self::is_extensible, "isExtensible", 1) .function(Self::own_keys, "ownKeys", 1) .function(Self::prevent_extensions, "preventExtensions", 1) .function(Self::set, "set", 3) .function(Self::set_prototype_of, "setPrototypeOf", 3) .property( to_string_tag, Self::NAME, Attribute::READONLY | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE, ) .build(); (Self::NAME, object.into(), Self::attribute()) } } impl Reflect { /// Calls a target function with arguments. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-reflect.apply /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/apply pub(crate) fn apply(_: &Value, args: &[Value], context: &mut Context) -> Result<Value> { let undefined = Value::undefined(); let target = args .get(0) .and_then(|v| v.as_object()) .ok_or_else(|| context.construct_type_error("target must be a function"))?; let this_arg = args.get(1).unwrap_or(&undefined); let args_list = args .get(2) .and_then(|v| v.as_object()) .ok_or_else(|| context.construct_type_error("args list must be an object"))?; if !target.is_callable() { return context.throw_type_error("target must be a function"); } let args = args_list.create_list_from_array_like(&[], context)?; target.call(this_arg, &args, context) } /// Calls a target function as a constructor with arguments. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-reflect.construct /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/construct pub(crate) fn construct(_: &Value, args: &[Value], context: &mut Context) -> Result<Value> { let target = args .get(0) .and_then(|v| v.as_object()) .ok_or_else(|| context.construct_type_error("target must be a function"))?; let args_list = args .get(1) .and_then(|v| v.as_object()) .ok_or_else(|| context.construct_type_error("args list must be an object"))?; if !target.is_constructable() { return context.throw_type_error("target must be a constructor"); } let new_target = if let Some(new_target) = args.get(2) { if new_target.as_object().map(|o| o.is_constructable()) != Some(true) { return context.throw_type_error("newTarget must be constructor"); } new_target.clone() } else { target.clone().into() }; let args = args_list.create_list_from_array_like(&[], context)?; target.construct(&args, new_target, context) } /// Defines a property on an object. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-reflect.defineProperty /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/defineProperty pub(crate) fn define_property( _: &Value, args: &[Value], context: &mut Context, ) -> Result<Value> { let undefined = Value::undefined(); let mut target = args .get(0) .and_then(|v| v.as_object()) .ok_or_else(|| context.construct_type_error("target must be an object"))?; let key = args.get(1).unwrap_or(&undefined).to_property_key(context)?; let prop_desc = args .get(2) .and_then(|v| v.as_object()) .ok_or_else(|| context.construct_type_error("property descriptor must be an object"))? .to_property_descriptor(context)?; target .define_own_property(key, prop_desc, context) .map(|b| b.into()) } /// Defines a property on an object. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-reflect.deleteproperty /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/deleteProperty pub(crate) fn delete_property( _: &Value, args: &[Value], context: &mut Context, ) -> Result<Value> { let undefined = Value::undefined(); let mut target = args .get(0) .and_then(|v| v.as_object()) .ok_or_else(|| context.construct_type_error("target must be an object"))?; let key = args.get(1).unwrap_or(&undefined).to_property_key(context)?; Ok(target.delete(&key).into()) } /// Gets a property of an object. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-reflect.get /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/get pub(crate) fn get(_: &Value, args: &[Value], context: &mut Context) -> Result<Value> { let undefined = Value::undefined(); let target = args .get(0) .and_then(|v| v.as_object()) .ok_or_else(|| context.construct_type_error("target must be an object"))?; let key = args.get(1).unwrap_or(&undefined).to_property_key(context)?; let receiver = if let Some(receiver) = args.get(2).cloned() { receiver } else { target.clone().into() }; target.get(&key, receiver, context) } /// Gets a property of an object. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-reflect.getownpropertydescriptor /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/getOwnPropertyDescriptor pub(crate) fn get_own_property_descriptor( _: &Value, args: &[Value], context: &mut Context, ) -> Result<Value> { match args.get(0) { Some(v) if v.is_object() => (), _ => return context.throw_type_error("target must be an object"), } // This function is the same as Object.prototype.getOwnPropertyDescriptor, that why // it is invoked here. builtins::object::Object::get_own_property_descriptor(&Value::undefined(), args, context) } /// Gets the prototype of an object. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-reflect.getprototypeof /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/getPrototypeOf pub(crate) fn get_prototype_of( _: &Value, args: &[Value], context: &mut Context, ) -> Result<Value> { let target = args .get(0) .and_then(|v| v.as_object()) .ok_or_else(|| context.construct_type_error("target must be an object"))?; Ok(target.get_prototype_of()) } /// Returns `true` if the object has the property, `false` otherwise. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-reflect.has /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/has pub(crate) fn has(_: &Value, args: &[Value], context: &mut Context) -> Result<Value> { let target = args .get(0) .and_then(|v| v.as_object()) .ok_or_else(|| context.construct_type_error("target must be an object"))?; let key = args .get(1) .unwrap_or(&Value::undefined()) .to_property_key(context)?; Ok(target.has_property(&key).into()) } /// Returns `true` if the object is extensible, `false` otherwise. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-reflect.isextensible /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible pub(crate) fn is_extensible(_: &Value, args: &[Value], context: &mut Context) -> Result<Value> { let target = args .get(0) .and_then(|v| v.as_object()) .ok_or_else(|| context.construct_type_error("target must be an object"))?; Ok(target.is_extensible().into()) } /// Returns an array of object own property keys. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-reflect.ownkeys /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/ownKeys pub(crate) fn own_keys(_: &Value, args: &[Value], context: &mut Context) -> Result<Value> { let target = args .get(0) .and_then(|v| v.as_object()) .ok_or_else(|| context.construct_type_error("target must be an object"))?; let array_prototype = context.standard_objects().array_object().prototype(); let result: Value = Object::with_prototype(array_prototype.into(), ObjectData::Array).into(); result.set_property( "length", DataDescriptor::new( 0, Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::PERMANENT, ), ); let keys = target.own_property_keys(); for (i, k) in keys.iter().enumerate() { result.set_field(i, k, context)?; } Ok(result) } /// Prevents new properties from ever being added to an object. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-reflect.preventextensions /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions pub(crate) fn prevent_extensions( _: &Value, args: &[Value], context: &mut Context, ) -> Result<Value> { let mut target = args .get(0) .and_then(|v| v.as_object()) .ok_or_else(|| context.construct_type_error("target must be an object"))?; Ok(target.prevent_extensions().into()) } /// Sets a property of an object. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-reflect.set /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/set pub(crate) fn set(_: &Value, args: &[Value], context: &mut Context) -> Result<Value> { let undefined = Value::undefined(); let mut target = args .get(0) .and_then(|v| v.as_object()) .ok_or_else(|| context.construct_type_error("target must be an object"))?; let key = args.get(1).unwrap_or(&undefined).to_property_key(context)?; let value = args.get(2).unwrap_or(&undefined); let receiver = if let Some(receiver) = args.get(3).cloned() { receiver } else { target.clone().into() }; Ok(target.set(key, value.clone(), receiver, context)?.into()) } /// Sets the prototype of an object. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-reflect.setprototypeof /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/setPrototypeOf pub(crate) fn set_prototype_of( _: &Value, args: &[Value], context: &mut Context, ) -> Result<Value> { let undefined = Value::undefined(); let mut target = args .get(0) .and_then(|v| v.as_object()) .ok_or_else(|| context.construct_type_error("target must be an object"))?; let proto = args.get(1).unwrap_or(&undefined); if !proto.is_null() && !proto.is_object() { return context.throw_type_error("proto must be an object or null"); } Ok(target.set_prototype_of(proto.clone()).into()) } }
38.286822
128
0.590133
14d62fefc913556c6bc87bb64ae5b45728cd8e09
4,396
use crate::v1::GENRE_LIST; use std::borrow::Cow; use std::mem::swap; #[derive(Copy, Clone)] pub struct Parser<'a>(&'a str); impl<'a> Parser<'a> { pub fn parse_tcon(s: &'a str) -> Cow<str> { let mut parser = Parser(s); let v1_genre_ids = match parser.one_or_more(Self::content_type) { Ok(v) => v, Err(_) => return Cow::Borrowed(parser.0), }; let trailer = parser.trailer(); let strs: Vec<String> = v1_genre_ids.into_iter().chain(trailer).collect(); Cow::Owned(strs.join(" ")) } fn content_type(&mut self) -> Result<String, ()> { self.first_of([&Self::escaped_content_type, &Self::v1_content_type]) } fn v1_content_type(&mut self) -> Result<String, ()> { self.expect("(")?; let t = self.first_of([ &|p: &mut Self| p.expect("RX").map(|_| "Remix".to_string()), &|p: &mut Self| p.expect("CR").map(|_| "Cover".to_string()), &|p: &mut Self| { p.parse_number() .map(|index| match GENRE_LIST.get(index as usize) { Some(v1_genre) => v1_genre.to_string(), None => format!("({})", index), }) }, ])?; self.expect(")")?; Ok(t) } fn escaped_content_type(&mut self) -> Result<String, ()> { self.expect("((")?; let t = format!("({}", self.0); self.0 = ""; Ok(t) } fn trailer(&mut self) -> Result<String, ()> { let mut tmp = ""; swap(&mut tmp, &mut self.0); if tmp.is_empty() { return Err(()); } Ok(tmp.to_string()) } fn expect<'s>(&mut self, prefix: &'s str) -> Result<&'s str, ()> { if self.0.starts_with(prefix) { self.0 = &self.0[prefix.len()..]; Ok(prefix) } else { Err(()) } } fn one_or_more<T>(&mut self, func: impl Fn(&mut Self) -> Result<T, ()>) -> Result<Vec<T>, ()> { let mut values = Vec::new(); while let Ok(v) = func(self) { values.push(v); } if values.is_empty() { return Err(()); } Ok(values) } fn first_of<T, const N: usize>( &mut self, funcs: [&dyn Fn(&mut Self) -> Result<T, ()>; N], ) -> Result<T, ()> { for func in funcs { let mut p = *self; if let Ok(v) = func(&mut p) { *self = p; return Ok(v); } } Err(()) } fn parse_number(&mut self) -> Result<u32, ()> { let mut ok = false; let mut r = 0u32; while self.0.starts_with(|c| ('0'..='9').contains(&c)) { ok = true; r = if let Some(r) = r .checked_mul(10) .and_then(|r| r.checked_add(u32::from(self.0.as_bytes()[0] - b'0'))) { r } else { return Err(()); }; self.0 = &self.0[1..]; } if ok { Ok(r) } else { Err(()) } } } #[cfg(test)] mod tests { use super::*; #[test] fn plain_genre() { let s = Parser::parse_tcon("Just a regular genre"); assert_eq!(s, "Just a regular genre"); } #[test] fn v1_genre() { let s = Parser::parse_tcon("(0)"); assert_eq!(s, "Blues"); let s = Parser::parse_tcon("(28)(31)"); assert_eq!(s, "Vocal Trance"); } #[test] fn v1_genre_plain_trailer() { let s = Parser::parse_tcon("(28)Trance"); assert_eq!(s, "Vocal Trance"); } #[test] fn escaping() { let s = Parser::parse_tcon("((Foo)"); assert_eq!(s, "(Foo)"); let s = Parser::parse_tcon("(31)((or is it?)"); assert_eq!(s, "Trance (or is it?)"); } #[test] fn v2_genre() { let s = Parser::parse_tcon("(RX)"); assert_eq!(s, "Remix"); let s = Parser::parse_tcon("(CR)"); assert_eq!(s, "Cover"); } #[test] fn malformed() { let s = Parser::parse_tcon("(lol)"); assert_eq!(s, "(lol)"); let s = Parser::parse_tcon("(RXlol)"); assert_eq!(s, "(RXlol)"); let s = Parser::parse_tcon("(CRlol)"); assert_eq!(s, "(CRlol)"); } }
26.642424
99
0.447225
f7de7ec7e18f44a8bb565dce7efa40106634d736
26,278
use rustc::hir; use rustc::hir::def::{Res, DefKind}; use rustc::hir::def_id::DefId; use rustc::lint; use rustc::lint::builtin::UNUSED_ATTRIBUTES; use rustc::ty::{self, Ty}; use rustc::ty::adjustment; use rustc_data_structures::fx::FxHashMap; use lint::{LateContext, EarlyContext, LintContext, LintArray}; use lint::{LintPass, EarlyLintPass, LateLintPass}; use rustc_feature::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP}; use syntax::ast; use syntax::attr; use syntax::errors::{Applicability, pluralize}; use syntax::print::pprust; use syntax::symbol::{kw, sym}; use syntax::symbol::Symbol; use syntax::util::parser; use syntax_pos::{Span, BytePos}; use log::debug; declare_lint! { pub UNUSED_MUST_USE, Warn, "unused result of a type flagged as `#[must_use]`", report_in_external_macro } declare_lint! { pub UNUSED_RESULTS, Allow, "unused result of an expression in a statement" } declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults { fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) { let expr = match s.kind { hir::StmtKind::Semi(ref expr) => &**expr, _ => return, }; if let hir::ExprKind::Ret(..) = expr.kind { return; } let ty = cx.tables.expr_ty(&expr); let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1); let mut fn_warned = false; let mut op_warned = false; let maybe_def_id = match expr.kind { hir::ExprKind::Call(ref callee, _) => { match callee.kind { hir::ExprKind::Path(ref qpath) => { match cx.tables.qpath_res(qpath, callee.hir_id) { Res::Def(DefKind::Fn, def_id) | Res::Def(DefKind::Method, def_id) => Some(def_id), // `Res::Local` if it was a closure, for which we // do not currently support must-use linting _ => None } }, _ => None } }, hir::ExprKind::MethodCall(..) => { cx.tables.type_dependent_def_id(expr.hir_id) }, _ => None }; if let Some(def_id) = maybe_def_id { fn_warned = check_must_use_def(cx, def_id, s.span, "return value of ", ""); } else if type_permits_lack_of_use { // We don't warn about unused unit or uninhabited types. // (See https://github.com/rust-lang/rust/issues/43806 for details.) return; } let must_use_op = match expr.kind { // Hardcoding operators here seemed more expedient than the // refactoring that would be needed to look up the `#[must_use]` // attribute which does exist on the comparison trait methods hir::ExprKind::Binary(bin_op, ..) => { match bin_op.node { hir::BinOpKind::Eq | hir::BinOpKind::Lt | hir::BinOpKind::Le | hir::BinOpKind::Ne | hir::BinOpKind::Ge | hir::BinOpKind::Gt => { Some("comparison") }, hir::BinOpKind::Add | hir::BinOpKind::Sub | hir::BinOpKind::Div | hir::BinOpKind::Mul | hir::BinOpKind::Rem => { Some("arithmetic operation") }, hir::BinOpKind::And | hir::BinOpKind::Or => { Some("logical operation") }, hir::BinOpKind::BitXor | hir::BinOpKind::BitAnd | hir::BinOpKind::BitOr | hir::BinOpKind::Shl | hir::BinOpKind::Shr => { Some("bitwise operation") }, } }, hir::ExprKind::Unary(..) => Some("unary operation"), _ => None }; if let Some(must_use_op) = must_use_op { cx.span_lint(UNUSED_MUST_USE, expr.span, &format!("unused {} that must be used", must_use_op)); op_warned = true; } if !(type_permits_lack_of_use || fn_warned || op_warned) { cx.span_lint(UNUSED_RESULTS, s.span, "unused result"); } // Returns whether an error has been emitted (and thus another does not need to be later). fn check_must_use_ty<'tcx>( cx: &LateContext<'_, 'tcx>, ty: Ty<'tcx>, expr: &hir::Expr, span: Span, descr_pre: &str, descr_post: &str, plural_len: usize, ) -> bool { if ty.is_unit() || cx.tcx.is_ty_uninhabited_from( cx.tcx.hir().get_module_parent(expr.hir_id), ty) { return true; } let plural_suffix = pluralize!(plural_len); match ty.kind { ty::Adt(..) if ty.is_box() => { let boxed_ty = ty.boxed_ty(); let descr_pre = &format!("{}boxed ", descr_pre); check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len) } ty::Adt(def, _) => { check_must_use_def(cx, def.did, span, descr_pre, descr_post) } ty::Opaque(def, _) => { let mut has_emitted = false; for (predicate, _) in cx.tcx.predicates_of(def).predicates { if let ty::Predicate::Trait(ref poly_trait_predicate) = predicate { let trait_ref = poly_trait_predicate.skip_binder().trait_ref; let def_id = trait_ref.def_id; let descr_pre = &format!( "{}implementer{} of ", descr_pre, plural_suffix, ); if check_must_use_def(cx, def_id, span, descr_pre, descr_post) { has_emitted = true; break; } } } has_emitted } ty::Dynamic(binder, _) => { let mut has_emitted = false; for predicate in binder.skip_binder().iter() { if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate { let def_id = trait_ref.def_id; let descr_post = &format!( " trait object{}{}", plural_suffix, descr_post, ); if check_must_use_def(cx, def_id, span, descr_pre, descr_post) { has_emitted = true; break; } } } has_emitted } ty::Tuple(ref tys) => { let mut has_emitted = false; let spans = if let hir::ExprKind::Tup(comps) = &expr.kind { debug_assert_eq!(comps.len(), tys.len()); comps.iter().map(|e| e.span).collect() } else { vec![] }; for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() { let descr_post = &format!(" in tuple element {}", i); let span = *spans.get(i).unwrap_or(&span); if check_must_use_ty( cx, ty, expr, span, descr_pre, descr_post, plural_len ) { has_emitted = true; } } has_emitted } ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) { // If the array is definitely non-empty, we can do `#[must_use]` checking. Some(n) if n != 0 => { let descr_pre = &format!( "{}array{} of ", descr_pre, plural_suffix, ); check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1) } // Otherwise, we don't lint, to avoid false positives. _ => false, } _ => false, } } // Returns whether an error has been emitted (and thus another does not need to be later). fn check_must_use_def( cx: &LateContext<'_, '_>, def_id: DefId, span: Span, descr_pre_path: &str, descr_post_path: &str, ) -> bool { for attr in cx.tcx.get_attrs(def_id).iter() { if attr.check_name(sym::must_use) { let msg = format!("unused {}`{}`{} that must be used", descr_pre_path, cx.tcx.def_path_str(def_id), descr_post_path); let mut err = cx.struct_span_lint(UNUSED_MUST_USE, span, &msg); // check for #[must_use = "..."] if let Some(note) = attr.value_str() { err.note(&note.as_str()); } err.emit(); return true; } } false } } } declare_lint! { pub PATH_STATEMENTS, Warn, "path statements with no effect" } declare_lint_pass!(PathStatements => [PATH_STATEMENTS]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements { fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) { if let hir::StmtKind::Semi(ref expr) = s.kind { if let hir::ExprKind::Path(_) = expr.kind { cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect"); } } } } #[derive(Copy, Clone)] pub struct UnusedAttributes { builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>, } impl UnusedAttributes { pub fn new() -> Self { UnusedAttributes { builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP, } } } impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes { fn check_attribute(&mut self, cx: &LateContext<'_, '_>, attr: &ast::Attribute) { debug!("checking attribute: {:?}", attr); let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name)); if let Some(&&(name, ty, ..)) = attr_info { match ty { AttributeType::Whitelisted => { debug!("{:?} is Whitelisted", name); return; } _ => (), } } if !attr::is_used(attr) { debug!("emitting warning for: {:?}", attr); cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute"); // Is it a builtin attribute that must be used at the crate level? if attr_info.map_or(false, |(_, ty, ..)| ty == &AttributeType::CrateLevel) { let msg = match attr.style { ast::AttrStyle::Outer => { "crate-level attribute should be an inner attribute: add an exclamation \ mark: `#![foo]`" } ast::AttrStyle::Inner => "crate-level attribute should be in the root module", }; cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg); } } else { debug!("Attr was used: {:?}", attr); } } } declare_lint! { pub(super) UNUSED_PARENS, Warn, "`if`, `match`, `while` and `return` do not need parentheses" } declare_lint_pass!(UnusedParens => [UNUSED_PARENS]); impl UnusedParens { fn is_expr_parens_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool { followed_by_block && match inner.kind { ast::ExprKind::Ret(_) | ast::ExprKind::Break(..) => true, _ => parser::contains_exterior_struct_lit(&inner), } } fn check_unused_parens_expr(&self, cx: &EarlyContext<'_>, value: &ast::Expr, msg: &str, followed_by_block: bool, left_pos: Option<BytePos>, right_pos: Option<BytePos>) { match value.kind { ast::ExprKind::Paren(ref inner) => { if !Self::is_expr_parens_necessary(inner, followed_by_block) && value.attrs.is_empty() { let expr_text = if let Ok(snippet) = cx.sess().source_map() .span_to_snippet(value.span) { snippet } else { pprust::expr_to_string(value) }; let keep_space = ( left_pos.map(|s| s >= value.span.lo()).unwrap_or(false), right_pos.map(|s| s <= value.span.hi()).unwrap_or(false), ); Self::remove_outer_parens(cx, value.span, &expr_text, msg, keep_space); } } ast::ExprKind::Let(_, ref expr) => { // FIXME(#60336): Properly handle `let true = (false && true)` // actually needing the parenthesis. self.check_unused_parens_expr( cx, expr, "`let` head expression", followed_by_block, None, None ); } _ => {} } } fn check_unused_parens_pat( &self, cx: &EarlyContext<'_>, value: &ast::Pat, avoid_or: bool, avoid_mut: bool, ) { use ast::{PatKind, BindingMode::ByValue, Mutability::Mutable}; if let PatKind::Paren(inner) = &value.kind { match inner.kind { // The lint visitor will visit each subpattern of `p`. We do not want to lint // any range pattern no matter where it occurs in the pattern. For something like // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume // that if there are unnecessary parens they serve a purpose of readability. PatKind::Range(..) => return, // Avoid `p0 | .. | pn` if we should. PatKind::Or(..) if avoid_or => return, // Avoid `mut x` and `mut x @ p` if we should: PatKind::Ident(ByValue(Mutable), ..) if avoid_mut => return, // Otherwise proceed with linting. _ => {} } let pattern_text = if let Ok(snippet) = cx.sess().source_map() .span_to_snippet(value.span) { snippet } else { pprust::pat_to_string(value) }; Self::remove_outer_parens(cx, value.span, &pattern_text, "pattern", (false, false)); } } fn remove_outer_parens(cx: &EarlyContext<'_>, span: Span, pattern: &str, msg: &str, keep_space: (bool, bool)) { let span_msg = format!("unnecessary parentheses around {}", msg); let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg); let mut ate_left_paren = false; let mut ate_right_paren = false; let parens_removed = pattern .trim_matches(|c| { match c { '(' => { if ate_left_paren { false } else { ate_left_paren = true; true } }, ')' => { if ate_right_paren { false } else { ate_right_paren = true; true } }, _ => false, } }); let replace = { let mut replace = if keep_space.0 { let mut s = String::from(" "); s.push_str(parens_removed); s } else { String::from(parens_removed) }; if keep_space.1 { replace.push(' '); } replace }; err.span_suggestion_short( span, "remove these parentheses", replace, Applicability::MachineApplicable, ); err.emit(); } } impl EarlyLintPass for UnusedParens { fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) { use syntax::ast::ExprKind::*; let (value, msg, followed_by_block, left_pos, right_pos) = match e.kind { Let(ref pat, ..) => { self.check_unused_parens_pat(cx, pat, false, false); return; } If(ref cond, ref block, ..) => { let left = e.span.lo() + syntax_pos::BytePos(2); let right = block.span.lo(); (cond, "`if` condition", true, Some(left), Some(right)) } While(ref cond, ref block, ..) => { let left = e.span.lo() + syntax_pos::BytePos(5); let right = block.span.lo(); (cond, "`while` condition", true, Some(left), Some(right)) }, ForLoop(ref pat, ref cond, ref block, ..) => { self.check_unused_parens_pat(cx, pat, false, false); (cond, "`for` head expression", true, None, Some(block.span.lo())) } Match(ref head, _) => { let left = e.span.lo() + syntax_pos::BytePos(5); (head, "`match` head expression", true, Some(left), None) } Ret(Some(ref value)) => { let left = e.span.lo() + syntax_pos::BytePos(3); (value, "`return` value", false, Some(left), None) } Assign(_, ref value) => (value, "assigned value", false, None, None), AssignOp(.., ref value) => (value, "assigned value", false, None, None), // either function/method call, or something this lint doesn't care about ref call_or_other => { let (args_to_check, call_kind) = match *call_or_other { Call(_, ref args) => (&args[..], "function"), // first "argument" is self (which sometimes needs parens) MethodCall(_, ref args) => (&args[1..], "method"), // actual catch-all arm _ => { return; } }; // Don't lint if this is a nested macro expansion: otherwise, the lint could // trigger in situations that macro authors shouldn't have to care about, e.g., // when a parenthesized token tree matched in one macro expansion is matched as // an expression in another and used as a fn/method argument (Issue #47775) if e.span.ctxt().outer_expn_data().call_site.from_expansion() { return; } let msg = format!("{} argument", call_kind); for arg in args_to_check { self.check_unused_parens_expr(cx, arg, &msg, false, None, None); } return; } }; self.check_unused_parens_expr(cx, &value, msg, followed_by_block, left_pos, right_pos); } fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) { use ast::{PatKind::*, Mutability}; match &p.kind { // Do not lint on `(..)` as that will result in the other arms being useless. Paren(_) // The other cases do not contain sub-patterns. | Wild | Rest | Lit(..) | Mac(..) | Range(..) | Ident(.., None) | Path(..) => return, // These are list-like patterns; parens can always be removed. TupleStruct(_, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps { self.check_unused_parens_pat(cx, p, false, false); }, Struct(_, fps, _) => for f in fps { self.check_unused_parens_pat(cx, &f.pat, false, false); }, // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106. Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false), // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342. // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106. Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Immutable), } } fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) { if let ast::StmtKind::Local(ref local) = s.kind { self.check_unused_parens_pat(cx, &local.pat, false, false); if let Some(ref value) = local.init { self.check_unused_parens_expr(cx, &value, "assigned value", false, None, None); } } } fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) { self.check_unused_parens_pat(cx, &param.pat, true, false); } fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) { self.check_unused_parens_pat(cx, &arm.pat, false, false); } fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) { if let &ast::TyKind::Paren(ref r) = &ty.kind { match &r.kind { &ast::TyKind::TraitObject(..) => {} &ast::TyKind::ImplTrait(_, ref bounds) if bounds.len() > 1 => {} _ => { let pattern_text = if let Ok(snippet) = cx.sess().source_map() .span_to_snippet(ty.span) { snippet } else { pprust::ty_to_string(ty) }; Self::remove_outer_parens(cx, ty.span, &pattern_text, "type", (false, false)); } } } } } declare_lint! { UNUSED_IMPORT_BRACES, Allow, "unnecessary braces around an imported item" } declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]); impl UnusedImportBraces { fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) { if let ast::UseTreeKind::Nested(ref items) = use_tree.kind { // Recursively check nested UseTrees for &(ref tree, _) in items { self.check_use_tree(cx, tree, item); } // Trigger the lint only if there is one nested item if items.len() != 1 { return; } // Trigger the lint if the nested item is a non-self single item let node_name = match items[0].0.kind { ast::UseTreeKind::Simple(rename, ..) => { let orig_ident = items[0].0.prefix.segments.last().unwrap().ident; if orig_ident.name == kw::SelfLower { return; } rename.unwrap_or(orig_ident).name } ast::UseTreeKind::Glob => Symbol::intern("*"), ast::UseTreeKind::Nested(_) => return, }; let msg = format!("braces around {} is unnecessary", node_name); cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg); } } } impl EarlyLintPass for UnusedImportBraces { fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) { if let ast::ItemKind::Use(ref use_tree) = item.kind { self.check_use_tree(cx, use_tree, item); } } } declare_lint! { pub(super) UNUSED_ALLOCATION, Warn, "detects unnecessary allocations that can be eliminated" } declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation { fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) { match e.kind { hir::ExprKind::Box(_) => {} _ => return, } for adj in cx.tables.expr_adjustments(e) { if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind { let msg = match m { adjustment::AutoBorrowMutability::Immutable => "unnecessary allocation, use `&` instead", adjustment::AutoBorrowMutability::Mutable { .. }=> "unnecessary allocation, use `&mut` instead" }; cx.span_lint(UNUSED_ALLOCATION, e.span, msg); } } } }
38.701031
100
0.467692
563f0b30f1d11e056deb255fc2a15a845e535265
2,704
use derpyfile::{DerpyFile, load_config, save_config}; use acquire::{acquire, AcquireMode, AcquireOutcome}; use consts::{CONFIG_FILE, CONFIG_LOCK_FILE}; use std::collections::BTreeMap; use dependency::Dependency; use cmds::CommandContext; use error::DerpyError; pub fn cli_upgrade(context: CommandContext) -> Result<(), DerpyError> { let config_path = context.path.join(CONFIG_FILE); let config = load_config(&config_path)?; let lock_path = context.path.join(CONFIG_LOCK_FILE); let mut lock = if lock_path.is_file() { load_config(&lock_path)? } else { DerpyFile::default() }; let mut lock_file_updated = false; let to_upgrade = if context.matches.is_present("all") { config.dependencies.clone() } else { let to_upgrade_names = context.matches.values_of("dependencies").unwrap() .map(|s| s.into()) .collect::<Vec<_>>(); config.dependencies.iter() .filter(|pair| to_upgrade_names.contains(pair.0)) .map(|pair| (pair.0.clone(), pair.1.clone())) .collect::<BTreeMap<String, Dependency>>() }; for (name, dep) in to_upgrade { let new_lock_version = match acquire(&context.log, &dep, AcquireMode::Upgrade)? { AcquireOutcome::Acquired { at_version } => { println!("- acquired '{}' at version {}", name, at_version); Some(at_version) }, AcquireOutcome::Restored { from_version, to_version } => { println!("- restored '{}' to {} from {}", name, to_version, from_version); None }, AcquireOutcome::UpgradedTo { from_version, to_version } => { println!("- upgraded '{}' to {} from {}", name, to_version, from_version); Some(to_version) }, AcquireOutcome::NoChange { current_version } => { println!("- '{}' up to date at version {}", name, current_version); None }, AcquireOutcome::Ignored { at_version } => { println!("- warning: ignored '{}' - left at version {}", name, at_version); println!(" (dependency {} present but has no lock file entry)", name); None }, }; if let Some(version) = new_lock_version { let mut dependency = dep.clone(); lock_file_updated = true; dependency.version = version; lock.dependencies.insert(dep.name.clone(), dependency); } } if lock_file_updated { save_config(&lock, &lock_path)?; println!("lock file updated"); } Ok(()) }
36.540541
91
0.568417
7511979ab1870cdeda3186b392e3942c6ad15c7a
16,634
use std::{ collections::HashMap, fs, io, path::{Path, PathBuf}, sync::mpsc::{channel, Receiver, Sender}, time::{Duration, UNIX_EPOCH}, }; use distill_core::utils::canonicalize_path; use notify::{watcher, DebouncedEvent, RecommendedWatcher, RecursiveMode, Watcher}; use crate::error::{Error, Result}; use futures::channel::mpsc::UnboundedSender; // Wraps the notify crate: // - supports symlinks // - encapsulates notify so other systems don't use it directly // - generates update messages for all files on startup /// The purpose of DirWatcher is to provide enough information to /// determine which files may be candidates for going through the asset import process. /// It handles updating watches for directories behind symlinks and scans directories on create/delete. pub struct DirWatcher { // the watcher object from the notify crate watcher: RecommendedWatcher, // Symlinks we have discovered and where they point symlink_map: HashMap<PathBuf, PathBuf>, // Refcount of all dirs being watched. We call unwatch on the watcher when it hits 0 watch_refs: HashMap<PathBuf, i32>, // All dirs being watched dirs: Vec<PathBuf>, // Channel for events from the watcher (and we insert events ourselves to indicate shutdown) rx: Receiver<DebouncedEvent>, tx: Sender<DebouncedEvent>, // The final output of this struct goes here asset_tx: UnboundedSender<FileEvent>, } // When dropped, sends an exit "error" message via the same channel we receive messages from notify pub struct StopHandle { tx: Sender<DebouncedEvent>, } #[derive(Debug, Clone)] pub struct FileMetadata { pub file_type: fs::FileType, pub last_modified: u64, pub length: u64, } #[derive(Debug)] pub enum FileEvent { Updated(PathBuf, FileMetadata), Renamed(PathBuf, PathBuf, FileMetadata), Removed(PathBuf), FileError(Error), // ScanStart is called when a directory is about to be scanned. // Scanning can be recursive ScanStart(PathBuf), // ScanEnd indicates the end of a scan. The set of all watched directories is also sent ScanEnd(PathBuf, Vec<PathBuf>), // Watch indicates that a new directory is being watched, probably due to a symlink being created Watch(PathBuf), // Unwatch indicates that a new directory has stopped being watched, probably due to a symlink being removed Unwatch(PathBuf), } // Sanitizes file metadata pub(crate) fn file_metadata(metadata: &fs::Metadata) -> FileMetadata { let modify_time = metadata.modified().unwrap_or(UNIX_EPOCH); let since_epoch = modify_time .duration_since(UNIX_EPOCH) .expect("Time went backwards"); let in_ms = since_epoch.as_secs() * 1000 + u64::from(since_epoch.subsec_nanos()) / 1_000_000; FileMetadata { file_type: metadata.file_type(), length: metadata.len(), last_modified: in_ms, } } impl DirWatcher { // Starts a watcher running on the given paths pub fn from_path_iter<'a, T>(paths: T, chan: UnboundedSender<FileEvent>) -> Result<DirWatcher> where T: IntoIterator<Item = &'a Path>, { let (tx, rx) = channel(); let mut asset_watcher = DirWatcher { watcher: watcher(tx.clone(), Duration::from_millis(300))?, symlink_map: HashMap::new(), watch_refs: HashMap::new(), dirs: Vec::new(), rx, tx, asset_tx: chan, }; for path in paths { let path = PathBuf::from(path); let path = if path.is_relative() { std::env::current_dir()?.join(path) } else { path }; let path = canonicalize_path(&path); asset_watcher.watch(&path)?; } Ok(asset_watcher) } // Returns a StopHandle that will halt watching when it's dropped pub fn stop_handle(&self) -> StopHandle { StopHandle { tx: self.tx.clone(), } } // Visit all files, call handle_notify_event() passing the event created by the provided callback fn scan_directory<F>(&mut self, dir: &Path, evt_create: &F) -> Result<()> where F: Fn(PathBuf) -> DebouncedEvent, { let canonical_dir = canonicalize_path(dir); self.asset_tx .unbounded_send(FileEvent::ScanStart(canonical_dir.clone())) .map_err(|_| Error::SendError)?; let result = self.scan_directory_recurse(&canonical_dir, evt_create); self.asset_tx .unbounded_send(FileEvent::ScanEnd(canonical_dir, self.dirs.clone())) .map_err(|_| Error::SendError)?; result } fn scan_directory_recurse<F>(&mut self, dir: &Path, evt_create: &F) -> Result<()> where F: Fn(PathBuf) -> DebouncedEvent, { match fs::read_dir(dir) { Err(ref e) if e.kind() == io::ErrorKind::NotFound => {} Err(e) => return Err(Error::IO(e)), Ok(dir_entry) => { for entry in dir_entry { match entry { Err(ref e) if e.kind() == io::ErrorKind::NotFound => continue, Err(e) => return Err(Error::IO(e)), Ok(entry) => { let evt = self.handle_notify_event(evt_create(entry.path()), true)?; if let Some(evt) = evt { self.asset_tx .unbounded_send(evt) .map_err(|_| Error::SendError)?; } let metadata; match entry.metadata() { Err(ref e) if e.kind() == io::ErrorKind::NotFound => continue, Err(e) => return Err(Error::IO(e)), Ok(m) => metadata = m, } let is_dir = metadata.is_dir(); if is_dir { self.scan_directory_recurse(&entry.path(), evt_create)?; } } } } } } Ok(()) } pub fn run(&mut self) { // Emit a Create for every path recursively for dir in &self.dirs.clone() { if let Err(err) = self.scan_directory(dir, &|path| DebouncedEvent::Create(path)) { self.asset_tx .unbounded_send(FileEvent::FileError(err)) .expect("Failed to send file error event. Ironic..."); } } loop { match self.rx.recv() { Ok(event) => match self.handle_notify_event(event, false) { // By default, just proxy the event into the channel Ok(maybe_event) => { if let Some(evt) = maybe_event { log::debug!("File event: {:?}", evt); self.asset_tx.unbounded_send(evt).unwrap(); } } Err(err) => match err { // If notify cannot assure correct modification events (sometimes due to overflowing a queue, // may be a limit on the OS) we have to reset to good state bu scanning everything Error::RescanRequired => { for dir in &self.dirs.clone() { if let Err(err) = self.scan_directory(dir, &|path| DebouncedEvent::Create(path)) { self.asset_tx .unbounded_send(FileEvent::FileError(err)) .expect("Failed to send file error event"); } } } Error::Exit => break, _ => self .asset_tx .unbounded_send(FileEvent::FileError(err)) .expect("Failed to send file error event"), }, }, Err(_) => { self.asset_tx .unbounded_send(FileEvent::FileError(Error::RecvError)) .expect("Failed to send file error event"); return; } } } } fn watch(&mut self, path: &Path) -> Result<bool> { let refs = *self.watch_refs.get(path).unwrap_or(&0); match refs { 0 => { self.watcher.watch(path, RecursiveMode::Recursive)?; self.dirs.push(path.to_path_buf()); self.watch_refs.insert(path.to_path_buf(), 1); return Ok(true); } refs if refs > 0 => { self.watch_refs .entry(path.to_path_buf()) .and_modify(|r| *r += 1); } _ => {} } Ok(false) } fn unwatch(&mut self, path: &Path) -> Result<bool> { let refs = *self.watch_refs.get(path).unwrap_or(&0); if refs == 1 { self.watcher.unwatch(path)?; for i in 0..self.dirs.len() { if *path == self.dirs[i] { self.dirs.remove(i); break; } } self.watch_refs.remove(path); return Ok(true); } else if refs > 0 { self.watch_refs .entry(path.to_path_buf()) .and_modify(|r| *r -= 1); } Ok(false) } // Called when we receive about changes, most of the time we will detect that the path is not // a symlink and do nothing fn handle_updated_symlink( &mut self, src: Option<&PathBuf>, dst: Option<&PathBuf>, ) -> Result<bool> { let mut recognized_symlink = false; if let Some(src) = src { if self.symlink_map.contains_key(src) { // This was previous a symlink. Remove the watch, and maybe clean up the watch let to_unwatch = self.symlink_map[src].clone(); match self.unwatch(&to_unwatch) { Ok(unwatched) => { if unwatched { self.scan_directory(&to_unwatch, &|p| DebouncedEvent::Remove(p))?; } self.symlink_map.remove(src); self.asset_tx .unbounded_send(FileEvent::Unwatch(to_unwatch)) .map_err(|_| Error::SendError)?; } Err(err) => { return Err(err); } } recognized_symlink = true; } } if let Some(dst) = dst { let link = fs::read_link(&dst); if let Ok(link_path) = link { let link_path = canonicalize_path(&dst.join(link_path)); match self.watch(&link_path) { Ok(watched) => { if watched { self.scan_directory(&link_path, &|p| DebouncedEvent::Create(p))?; } self.symlink_map.insert(dst.clone(), link_path.clone()); self.asset_tx .unbounded_send(FileEvent::Watch(link_path)) .map_err(|_| Error::SendError)?; } Err(Error::Notify(notify::Error::Generic(text))) if text == "Input watch path is neither a file nor a directory." => { // skip the symlink if it's not a valid path } Err(Error::Notify(notify::Error::PathNotFound)) => {} Err(Error::IO(err)) | Err(Error::Notify(notify::Error::Io(err))) if err.kind() == std::io::ErrorKind::NotFound => { // skip the symlink if it no longer exists or can't be watched } Err(err) => { return Err(err); } } recognized_symlink = true; } } Ok(recognized_symlink) } // Handles events from notify, and manually triggered from calling scan_directory() fn handle_notify_event( &mut self, event: DebouncedEvent, is_scanning: bool, ) -> Result<Option<FileEvent>> { match event { DebouncedEvent::Create(path) | DebouncedEvent::Write(path) => { let path = canonicalize_path(&path); self.handle_updated_symlink(Option::None, Some(&path))?; // Try to get info on this file, following the symlink if necessary let metadata_result = match fs::metadata(&path) { Err(ref e) if e.kind() == io::ErrorKind::NotFound => Ok(None), Err(ref e) if e.kind() == io::ErrorKind::PermissionDenied => { log::warn!( "Permission denied when fetching metadata for create event {:?}", path, ); Ok(None) } Err(e) => Err(Error::IO(e)), Ok(metadata) => Ok(Some(FileEvent::Updated( path.clone(), file_metadata(&metadata), ))), }; // If metadata hit NotFound/PermissionDenied, get metadata without trying to follow symlink match metadata_result { Ok(None) => { if let Ok(metadata) = fs::symlink_metadata(&path) { Ok(Some(FileEvent::Updated(path, file_metadata(&metadata)))) } else { Ok(None) } } result => result, } } DebouncedEvent::Rename(src, dest) => { let src = canonicalize_path(&src); let dest = canonicalize_path(&dest); self.handle_updated_symlink(Some(&src), Some(&dest))?; match fs::metadata(&dest) { Err(ref e) if e.kind() == io::ErrorKind::NotFound => Ok(None), Err(ref e) if e.kind() == io::ErrorKind::PermissionDenied => { log::warn!( "Permission denied when fetching metadata for rename event {:?}->{:?}", src, dest ); Ok(None) } Err(e) => Err(Error::IO(e)), Ok(metadata) => { if metadata.is_dir() && !is_scanning { self.scan_directory(&dest, &|p| { let replaced = canonicalize_path(&src.join( p.strip_prefix(&dest).expect("Failed to strip prefix dir"), )); DebouncedEvent::Rename(replaced, p) })?; } Ok(Some(FileEvent::Renamed( src, dest, file_metadata(&metadata), ))) } } } DebouncedEvent::Remove(path) => { let path = canonicalize_path(&path); self.handle_updated_symlink(Some(&path), Option::None)?; Ok(Some(FileEvent::Removed(path))) } DebouncedEvent::Rescan => Err(Error::RescanRequired), DebouncedEvent::Error(_, _) => Err(Error::Exit), _ => Ok(None), } } } impl Drop for StopHandle { fn drop(&mut self) { let _ = self.tx.send(DebouncedEvent::Error( notify::Error::Generic("EXIT".to_string()), Option::None, )); } }
39.323877
117
0.477756
03042940213aaef1acb00ff5c3f5536b20fe5977
22,768
#[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::CTRL { #[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 LCDENR { bits: bool, } impl LCDENR { #[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 LCDBPPR { bits: u8, } impl LCDBPPR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct LCDBWR { bits: bool, } impl LCDBWR { #[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 LCDTFTR { bits: bool, } impl LCDTFTR { #[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 LCDMONO8R { bits: bool, } impl LCDMONO8R { #[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 LCDDUALR { bits: bool, } impl LCDDUALR { #[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 BGRR { bits: bool, } impl BGRR { #[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 BEBOR { bits: bool, } impl BEBOR { #[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 BEPOR { bits: bool, } impl BEPOR { #[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 LCDPWRR { bits: bool, } impl LCDPWRR { #[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 LCDVCOMPR { bits: u8, } impl LCDVCOMPR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct WATERMARKR { bits: bool, } impl WATERMARKR { #[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 _LCDENW<'a> { w: &'a mut W, } impl<'a> _LCDENW<'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 _LCDBPPW<'a> { w: &'a mut W, } impl<'a> _LCDBPPW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 7; 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 _LCDBWW<'a> { w: &'a mut W, } impl<'a> _LCDBWW<'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 _LCDTFTW<'a> { w: &'a mut W, } impl<'a> _LCDTFTW<'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 _LCDMONO8W<'a> { w: &'a mut W, } impl<'a> _LCDMONO8W<'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 _LCDDUALW<'a> { w: &'a mut W, } impl<'a> _LCDDUALW<'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 } } #[doc = r" Proxy"] pub struct _BGRW<'a> { w: &'a mut W, } impl<'a> _BGRW<'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 = 8; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _BEBOW<'a> { w: &'a mut W, } impl<'a> _BEBOW<'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 = 9; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _BEPOW<'a> { w: &'a mut W, } impl<'a> _BEPOW<'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 = 10; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _LCDPWRW<'a> { w: &'a mut W, } impl<'a> _LCDPWRW<'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 = 11; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _LCDVCOMPW<'a> { w: &'a mut W, } impl<'a> _LCDVCOMPW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 12; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _WATERMARKW<'a> { w: &'a mut W, } impl<'a> _WATERMARKW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - LCD enable control bit. 0 = LCD disabled. Signals LCDLP, LCDDCLK, LCDFP, LCDENAB, and LCDLE are low. 1 = LCD enabled. Signals LCDLP, LCDDCLK, LCDFP, LCDENAB, and LCDLE are high. See LCD power-up and power-down sequence for details on LCD power sequencing."] #[inline] pub fn lcden(&self) -> LCDENR { let bits = { const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }; LCDENR { bits } } #[doc = "Bits 1:3 - LCD bits per pixel: Selects the number of bits per LCD pixel: 000 = 1 bpp. 001 = 2 bpp. 010 = 4 bpp. 011 = 8 bpp. 100 = 16 bpp. 101 = 24 bpp (TFT panel only). 110 = 16 bpp, 5:6:5 mode. 111 = 12 bpp, 4:4:4 mode."] #[inline] pub fn lcdbpp(&self) -> LCDBPPR { let bits = { const MASK: u8 = 7; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) as u8 }; LCDBPPR { bits } } #[doc = "Bit 4 - STN LCD monochrome/color selection. 0 = STN LCD is color. 1 = STN LCD is monochrome. This bit has no meaning in TFT mode."] #[inline] pub fn lcdbw(&self) -> LCDBWR { let bits = { const MASK: bool = true; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) != 0 }; LCDBWR { bits } } #[doc = "Bit 5 - LCD panel TFT type selection. 0 = LCD is an STN display. Use gray scaler. 1 = LCD is a TFT display. Do not use gray scaler."] #[inline] pub fn lcdtft(&self) -> LCDTFTR { let bits = { const MASK: bool = true; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) != 0 }; LCDTFTR { bits } } #[doc = "Bit 6 - Monochrome LCD interface width. This bit controls whether a monochrome STN LCD uses a 4 or 8-bit parallel interface. It has no meaning in other modes and must be programmed to zero. 0 = monochrome LCD uses a 4-bit interface. 1 = monochrome LCD uses a 8-bit interface."] #[inline] pub fn lcdmono8(&self) -> LCDMONO8R { let bits = { const MASK: bool = true; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) != 0 }; LCDMONO8R { bits } } #[doc = "Bit 7 - Single or Dual LCD panel selection. STN LCD interface is: 0 = single-panel. 1 = dual-panel."] #[inline] pub fn lcddual(&self) -> LCDDUALR { let bits = { const MASK: bool = true; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MASK as u32) != 0 }; LCDDUALR { bits } } #[doc = "Bit 8 - Color format selection. 0 = RGB: normal output. 1 = BGR: red and blue swapped."] #[inline] pub fn bgr(&self) -> BGRR { let bits = { const MASK: bool = true; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BGRR { bits } } #[doc = "Bit 9 - Big-endian Byte Order. Controls byte ordering in memory: 0 = little-endian byte order. 1 = big-endian byte order."] #[inline] pub fn bebo(&self) -> BEBOR { let bits = { const MASK: bool = true; const OFFSET: u8 = 9; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BEBOR { bits } } #[doc = "Bit 10 - Big-Endian Pixel Ordering. Controls pixel ordering within a byte: 0 = little-endian ordering within a byte. 1 = big-endian pixel ordering within a byte. The BEPO bit selects between little and big-endian pixel packing for 1, 2, and 4 bpp display modes, it has no effect on 8 or 16 bpp pixel formats. See Pixel serializer for more information on the data format."] #[inline] pub fn bepo(&self) -> BEPOR { let bits = { const MASK: bool = true; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BEPOR { bits } } #[doc = "Bit 11 - LCD power enable. 0 = power not gated through to LCD panel and LCDV\\[23:0\\] signals disabled, (held LOW). 1 = power gated through to LCD panel and LCDV\\[23:0\\] signals enabled, (active). See LCD power-up and power-down sequence for details on LCD power sequencing."] #[inline] pub fn lcdpwr(&self) -> LCDPWRR { let bits = { const MASK: bool = true; const OFFSET: u8 = 11; ((self.bits >> OFFSET) & MASK as u32) != 0 }; LCDPWRR { bits } } #[doc = "Bits 12:13 - LCD Vertical Compare Interrupt. Generate VComp interrupt at: 00 = start of vertical synchronization. 01 = start of back porch. 10 = start of active video. 11 = start of front porch."] #[inline] pub fn lcdvcomp(&self) -> LCDVCOMPR { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) as u8 }; LCDVCOMPR { bits } } #[doc = "Bit 16 - LCD DMA FIFO watermark level. Controls when DMA requests are generated: 0 = An LCD DMA request is generated when either of the DMA FIFOs have four or more empty locations. 1 = An LCD DMA request is generated when either of the DMA FIFOs have eight or more empty locations."] #[inline] pub fn watermark(&self) -> WATERMARKR { let bits = { const MASK: bool = true; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) != 0 }; WATERMARKR { 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 - LCD enable control bit. 0 = LCD disabled. Signals LCDLP, LCDDCLK, LCDFP, LCDENAB, and LCDLE are low. 1 = LCD enabled. Signals LCDLP, LCDDCLK, LCDFP, LCDENAB, and LCDLE are high. See LCD power-up and power-down sequence for details on LCD power sequencing."] #[inline] pub fn lcden(&mut self) -> _LCDENW { _LCDENW { w: self } } #[doc = "Bits 1:3 - LCD bits per pixel: Selects the number of bits per LCD pixel: 000 = 1 bpp. 001 = 2 bpp. 010 = 4 bpp. 011 = 8 bpp. 100 = 16 bpp. 101 = 24 bpp (TFT panel only). 110 = 16 bpp, 5:6:5 mode. 111 = 12 bpp, 4:4:4 mode."] #[inline] pub fn lcdbpp(&mut self) -> _LCDBPPW { _LCDBPPW { w: self } } #[doc = "Bit 4 - STN LCD monochrome/color selection. 0 = STN LCD is color. 1 = STN LCD is monochrome. This bit has no meaning in TFT mode."] #[inline] pub fn lcdbw(&mut self) -> _LCDBWW { _LCDBWW { w: self } } #[doc = "Bit 5 - LCD panel TFT type selection. 0 = LCD is an STN display. Use gray scaler. 1 = LCD is a TFT display. Do not use gray scaler."] #[inline] pub fn lcdtft(&mut self) -> _LCDTFTW { _LCDTFTW { w: self } } #[doc = "Bit 6 - Monochrome LCD interface width. This bit controls whether a monochrome STN LCD uses a 4 or 8-bit parallel interface. It has no meaning in other modes and must be programmed to zero. 0 = monochrome LCD uses a 4-bit interface. 1 = monochrome LCD uses a 8-bit interface."] #[inline] pub fn lcdmono8(&mut self) -> _LCDMONO8W { _LCDMONO8W { w: self } } #[doc = "Bit 7 - Single or Dual LCD panel selection. STN LCD interface is: 0 = single-panel. 1 = dual-panel."] #[inline] pub fn lcddual(&mut self) -> _LCDDUALW { _LCDDUALW { w: self } } #[doc = "Bit 8 - Color format selection. 0 = RGB: normal output. 1 = BGR: red and blue swapped."] #[inline] pub fn bgr(&mut self) -> _BGRW { _BGRW { w: self } } #[doc = "Bit 9 - Big-endian Byte Order. Controls byte ordering in memory: 0 = little-endian byte order. 1 = big-endian byte order."] #[inline] pub fn bebo(&mut self) -> _BEBOW { _BEBOW { w: self } } #[doc = "Bit 10 - Big-Endian Pixel Ordering. Controls pixel ordering within a byte: 0 = little-endian ordering within a byte. 1 = big-endian pixel ordering within a byte. The BEPO bit selects between little and big-endian pixel packing for 1, 2, and 4 bpp display modes, it has no effect on 8 or 16 bpp pixel formats. See Pixel serializer for more information on the data format."] #[inline] pub fn bepo(&mut self) -> _BEPOW { _BEPOW { w: self } } #[doc = "Bit 11 - LCD power enable. 0 = power not gated through to LCD panel and LCDV\\[23:0\\] signals disabled, (held LOW). 1 = power gated through to LCD panel and LCDV\\[23:0\\] signals enabled, (active). See LCD power-up and power-down sequence for details on LCD power sequencing."] #[inline] pub fn lcdpwr(&mut self) -> _LCDPWRW { _LCDPWRW { w: self } } #[doc = "Bits 12:13 - LCD Vertical Compare Interrupt. Generate VComp interrupt at: 00 = start of vertical synchronization. 01 = start of back porch. 10 = start of active video. 11 = start of front porch."] #[inline] pub fn lcdvcomp(&mut self) -> _LCDVCOMPW { _LCDVCOMPW { w: self } } #[doc = "Bit 16 - LCD DMA FIFO watermark level. Controls when DMA requests are generated: 0 = An LCD DMA request is generated when either of the DMA FIFOs have four or more empty locations. 1 = An LCD DMA request is generated when either of the DMA FIFOs have eight or more empty locations."] #[inline] pub fn watermark(&mut self) -> _WATERMARKW { _WATERMARKW { w: self } } }
30.892809
385
0.540012
9024ca80519e923c081402da0fb76de1d4cbbae2
2,249
//! Handles async functions use crate::returned::Returned; use crate::Handle; use crate::Marshal; use futures_executor::ThreadPool; use futures_util::future::RemoteHandle; use futures_util::task::SpawnExt; use futures_util::FutureExt; use std::collections::HashMap; use std::future::Future; use std::lazy::SyncLazy; use std::sync::Mutex; /// Pool of [Future]s being run by Riko's own executor. pub struct Pool { pool: HashMap<Handle, RemoteHandle<()>>, executor: ThreadPool, counter: Handle, } impl Pool { /// Spawns a future. pub fn spawn<F, N, R, T>(&mut self, task: F, notifier: N) -> Handle where F: Future<Output = R> + Send + 'static, N: FnOnce(Handle, Returned<T>) + Send + 'static, R: Into<Returned<T>>, T: Marshal, { let handle = self.new_handle(); let task = async move { let result = task.await.into(); if let Some(token) = POOL.lock().unwrap().pool.remove(&handle) { notifier(handle, result); token.forget() } }; let (task, token) = task.remote_handle(); let old_handle = self.pool.insert(handle, token); assert!(old_handle.is_none(), "Same handle used more than once"); self.executor.spawn(task).expect("Failed to spawn a job"); handle } /// Cancels a [Future] run by this [Pool]. pub fn cancel(&mut self, handle: Handle) { self.pool.remove(&handle); } /// Creates a [Handle] by incrementing the internal counter. /// /// New [Handle]s are always monotonically increasing, which avoid collision. fn new_handle(&mut self) -> Handle { let previous = self.counter; self.counter += 1; previous } } impl Default for Pool { fn default() -> Self { let executor = ThreadPool::builder() .name_prefix("riko-") .create() .expect("Failed to create executor for Riko language bindings"); Self { executor, pool: Default::default(), counter: Default::default(), } } } /// The singleton instance of [Pool]. pub static POOL: SyncLazy<Mutex<Pool>> = SyncLazy::new(Default::default);
29.207792
81
0.593597
bf5482056d4b414378fd4aba1a029bdc127e5f79
189
// run-pass // compile-flags: --test #![feature(main)] #![allow(dead_code)] mod a { fn b() { (|| { #[main] fn c() { panic!(); } })(); } }
11.8125
32
0.354497
1c7604b88ad62cd7100ee4cd89abda5721c48718
4,501
use hitable::{ Hitable, HitRecord, }; use ray::Ray3; use aabb::AABB; use material::Material; use cgmath::{ Point3, Vector3, InnerSpace, }; use std::time::Instant; pub struct Triangle { vertices: [Point3<f32>; 3], surface_normal: Vector3<f32>, material: Material, } impl Triangle { pub fn new(vertices: [Point3<f32>; 3], material: Material) -> Self { let e1 = vertices[1] - vertices[0]; let e2 = vertices[2] - vertices[0]; let surface_normal = e2.cross(e1).normalize(); Self { vertices, surface_normal, material } } } impl Hitable for Triangle { fn hit(&self, r: &Ray3<f32>, t_min: f32, t_max: f32) -> Option<HitRecord> { let e1 = self.vertices[1] - self.vertices[0]; let e2 = self.vertices[2] - self.vertices[0]; let dir = r.direction; let pvec = dir.cross(e2); let det = e1.dot(pvec); if det > -0.00001 && det < 0.00001 { return None } let inv_det = 1.0 / det; let tvec = r.origin - self.vertices[0]; let u = tvec.dot(pvec) * inv_det; if u < 0.0 || u > 1.0 { return None } let qvec = tvec.cross(e1); let v = dir.dot(qvec) * inv_det; if v < 0.0 || u + v > 1.0 { return None } let t = e2.dot(qvec) * inv_det; if t > 0.00001 && t < t_max && t > t_min { return Some(HitRecord::new( t, r.point_at_parameter(t), self.surface_normal, Some(self.material.clone()), )); } None } fn bounding_box(&self, _: Instant, _: Instant) -> Option<AABB> { let mut min = Point3::new(self.vertices[0].x.min(self.vertices[1].x), self.vertices[0].y.min(self.vertices[1].y), self.vertices[0].z.min(self.vertices[1].z)); min = Point3::new(min.x.min(self.vertices[2].x), min.y.min(self.vertices[2].y), min.z.min(self.vertices[2].z)); let mut max = Point3::new(self.vertices[0].x.max(self.vertices[1].x), self.vertices[0].y.max(self.vertices[1].y), self.vertices[0].z.max(self.vertices[1].z)); max = Point3::new(max.x.max(self.vertices[2].x), max.y.max(self.vertices[2].y), max.z.max(self.vertices[2].z)); Some(AABB::new(min, max)) } } pub struct NormalTriangle { vertices: [Point3<f32>; 3], normals: [Vector3<f32>; 3], material: Material, } impl NormalTriangle { pub fn new(vertices: [Point3<f32>; 3], normals: [Vector3<f32>; 3], material: Material) -> Self { Self { vertices, normals, material } } } impl Hitable for NormalTriangle { fn hit(&self, r: &Ray3<f32>, t_min: f32, t_max: f32) -> Option<HitRecord> { let e1 = self.vertices[1] - self.vertices[0]; let e2 = self.vertices[2] - self.vertices[0]; let dir = r.direction; let pvec = dir.cross(e2); let det = e1.dot(pvec); if det > -0.00001 && det < 0.00001 { return None } let inv_det = 1.0 / det; let tvec = r.origin - self.vertices[0]; let u = tvec.dot(pvec) * inv_det; if u < 0.0 || u > 1.0 { return None } let qvec = tvec.cross(e1); let v = dir.dot(qvec) * inv_det; if v < 0.0 || u + v > 1.0 { return None } let t = e2.dot(qvec) * inv_det; let p = r.point_at_parameter(t); if t > 0.00001 && t < t_max && t > t_min { let normal = u * self.normals[1] + v * self.normals[2] + (1f32 - u - v) * self.normals[0]; Some(HitRecord::new( t, p, normal, Some(self.material.clone()), )) } else { None } } fn bounding_box(&self, _: Instant, _: Instant) -> Option<AABB> { let mut min = Point3::new(self.vertices[0].x.min(self.vertices[1].x), self.vertices[0].y.min(self.vertices[1].y), self.vertices[0].z.min(self.vertices[1].z)); min = Point3::new(min.x.min(self.vertices[2].x), min.y.min(self.vertices[2].y), min.z.min(self.vertices[2].z)); let mut max = Point3::new(self.vertices[0].x.max(self.vertices[1].x), self.vertices[0].y.max(self.vertices[1].y), self.vertices[0].z.max(self.vertices[1].z)); max = Point3::new(max.x.max(self.vertices[2].x), max.y.max(self.vertices[2].y), max.z.max(self.vertices[2].z)); Some(AABB::new(min, max)) } }
30.006667
166
0.536992
148b5aa3ca0d5f0453d0125eafb407eccccb0aef
37
mod basepoints; mod batch; mod prop;
9.25
15
0.756757
1c347ad36475c1194d13140a5698690c17e51083
20,017
//! `String` impl use crate::avm2::activation::Activation; use crate::avm2::class::{Class, ClassAttributes}; use crate::avm2::method::{Method, NativeMethodImpl}; use crate::avm2::names::{Namespace, QName}; use crate::avm2::object::{primitive_allocator, Object, TObject}; use crate::avm2::regexp::RegExpFlags; use crate::avm2::value::Value; use crate::avm2::Error; use crate::avm2::{ArrayObject, ArrayStorage}; use crate::string::{AvmString, WString}; use gc_arena::{GcCell, MutationContext}; use std::iter; /// Implements `String`'s instance initializer. pub fn instance_init<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { activation.super_init(this, &[])?; if let Some(mut value) = this.as_primitive_mut(activation.context.gc_context) { if !matches!(*value, Value::String(_)) { *value = args .get(0) .unwrap_or(&Value::String("".into())) .coerce_to_string(activation)? .into(); } } } Ok(Value::Undefined) } /// Implements `String`'s class initializer. pub fn class_init<'gc>( _activation: &mut Activation<'_, 'gc, '_>, _this: Option<Object<'gc>>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { Ok(Value::Undefined) } /// Implements `length` property's getter fn length<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { if let Value::String(s) = this.value_of(activation.context.gc_context)? { return Ok(s.len().into()); } } Ok(Value::Undefined) } /// Implements `String.charAt` fn char_at<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { if let Value::String(s) = this.value_of(activation.context.gc_context)? { // This function takes Number, so if we use coerce_to_i32 instead of coerce_to_number, the value may overflow. let n = args .get(0) .unwrap_or(&Value::Number(0.0)) .coerce_to_number(activation)?; if n < 0.0 { return Ok("".into()); } let index = if !n.is_nan() { n as usize } else { 0 }; let ret = s .get(index) .map(WString::from_unit) .map(|s| AvmString::new(activation.context.gc_context, s)) .unwrap_or_default(); return Ok(ret.into()); } } Ok(Value::Undefined) } /// Implements `String.charCodeAt` fn char_code_at<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { if let Value::String(s) = this.value_of(activation.context.gc_context)? { // This function takes Number, so if we use coerce_to_i32 instead of coerce_to_number, the value may overflow. let n = args .get(0) .unwrap_or(&Value::Number(0.0)) .coerce_to_number(activation)?; if n < 0.0 { return Ok(f64::NAN.into()); } let index = if !n.is_nan() { n as usize } else { 0 }; let ret = s.get(index).map(f64::from).unwrap_or(f64::NAN); return Ok(ret.into()); } } Ok(Value::Undefined) } /// Implements `String.concat` fn concat<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { let mut ret = WString::from(Value::from(this).coerce_to_string(activation)?.as_wstr()); for arg in args { let s = arg.coerce_to_string(activation)?; ret.push_str(&s); } return Ok(AvmString::new(activation.context.gc_context, ret).into()); } Ok(Value::Undefined) } /// Implements `String.fromCharCode` fn from_char_code<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { let mut out = WString::with_capacity(args.len(), false); for arg in args { let i = arg.coerce_to_u32(activation)? as u16; if i == 0 { // Ignore nulls. continue; } out.push(i); } Ok(AvmString::new(activation.context.gc_context, out).into()) } /// Implements `String.indexOf` fn index_of<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { let this = Value::from(this).coerce_to_string(activation)?; let pattern = match args.get(0) { None => return Ok(Value::Undefined), Some(s) => s.clone().coerce_to_string(activation)?, }; let start_index = match args.get(1) { None | Some(Value::Undefined) => 0, Some(n) => n.coerce_to_i32(activation)?.max(0) as usize, }; return this .slice(start_index..) .and_then(|s| s.find(&pattern)) .map(|i| Ok((i + start_index).into())) .unwrap_or_else(|| Ok((-1).into())); // Out of range or not found } Ok(Value::Undefined) } /// Implements `String.lastIndexOf` fn last_index_of<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { let this = Value::from(this).coerce_to_string(activation)?; let pattern = match args.get(0) { None => return Ok(Value::Undefined), Some(s) => s.clone().coerce_to_string(activation)?, }; let start_index = match args.get(1) { None | Some(Value::Undefined) => this.len(), Some(n) => match usize::try_from(n.coerce_to_i32(activation)?) { Ok(n) => n + pattern.len(), Err(_) => return Ok((-1).into()), // Bail out on negative indices. }, }; return this .slice(..start_index) .unwrap_or(&this) .rfind(&pattern) .map(|i| Ok(i.into())) .unwrap_or_else(|| Ok((-1).into())); // Not found } Ok(Value::Undefined) } /// Implements `String.match` fn match_s<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let (Some(this), pattern) = (this, args.get(0).unwrap_or(&Value::Undefined)) { let this = Value::from(this).coerce_to_string(activation)?; let regexp_class = activation.avm2().classes().regexp; let pattern = if !pattern.is_of_type(activation, regexp_class)? { let string = pattern.coerce_to_string(activation)?; regexp_class.construct(activation, &[Value::String(string)])? } else { pattern.coerce_to_object(activation)? }; if let Some(mut regexp) = pattern.as_regexp_mut(activation.context.gc_context) { let mut storage = ArrayStorage::new(0); if regexp.flags().contains(RegExpFlags::GLOBAL) { let mut last = regexp.last_index(); let old_last_index = regexp.last_index(); regexp.set_last_index(0); while let Some(result) = regexp.exec(this) { if regexp.last_index() == last { break; } storage.push( AvmString::new(activation.context.gc_context, &this[result.range()]).into(), ); last = regexp.last_index(); } regexp.set_last_index(0); if old_last_index == regexp.last_index() { regexp.set_last_index(1); } return Ok(ArrayObject::from_storage(activation, storage) .unwrap() .into()); } else { let old = regexp.last_index(); regexp.set_last_index(0); if let Some(result) = regexp.exec(this) { let substrings = result.groups().map(|range| &this[range.unwrap_or(0..0)]); let mut storage = ArrayStorage::new(0); for substring in substrings { storage .push(AvmString::new(activation.context.gc_context, substring).into()); } regexp.set_last_index(old); return Ok(ArrayObject::from_storage(activation, storage) .unwrap() .into()); } else { regexp.set_last_index(old); // If the pattern parameter is a String or a non-global regular expression // and no match is found, the method returns null return Ok(Value::Null); } }; }; } Ok(Value::Null) } /// Implements `String.replace` fn replace<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { let this = Value::from(this).coerce_to_string(activation)?; let pattern = args.get(0).unwrap_or(&Value::Undefined); let replacement = args.get(1).unwrap_or(&Value::Undefined); if replacement .as_object() .and_then(|o| o.as_function_object()) .is_some() { log::warn!("string.replace(_, function) - not implemented"); return Err("NotImplemented".into()); } let replacement = replacement.coerce_to_string(activation)?; if replacement.find(b'$').is_some() { log::warn!("string.replace(_, \"...$...\") - not implemented"); return Err("NotImplemented".into()); } if pattern .as_object() .map(|o| o.as_regexp().is_some()) .unwrap_or(false) { let regexp_object = pattern.as_object().unwrap(); let mut regexp = regexp_object .as_regexp_mut(activation.context.gc_context) .unwrap(); let mut ret = WString::new(); let mut start = 0; let old = regexp.last_index(); regexp.set_last_index(0); while let Some(result) = regexp.exec(this) { ret.push_str(&this[start..result.start()]); ret.push_str(&replacement); start = regexp.last_index(); if result.range().is_empty() { let last_index = regexp.last_index(); if last_index == this.len() { break; } regexp.set_last_index(last_index + 1); } if !regexp.flags().contains(RegExpFlags::GLOBAL) { break; } } regexp.set_last_index(old); ret.push_str(&this[start..]); return Ok(AvmString::new(activation.context.gc_context, ret).into()); } else { let pattern = pattern.coerce_to_string(activation)?; if let Some(position) = this.find(&pattern) { let mut ret = WString::from(&this[..position]); ret.push_str(&replacement); ret.push_str(&this[position + pattern.len()..]); return Ok(AvmString::new(activation.context.gc_context, ret).into()); } else { return Ok(this.into()); } } } Ok(Value::Undefined) } /// Implements `String.slice` fn slice<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { let this = Value::from(this).coerce_to_string(activation)?; let start_index = match args.get(0) { None => 0, Some(n) => { let n = n.coerce_to_number(activation)?; string_wrapping_index(n, this.len()) } }; let end_index = match args.get(1) { None => this.len(), Some(n) => { let n = n.coerce_to_number(activation)?; string_wrapping_index(n, this.len()) } }; return if start_index < end_index { let ret = WString::from(&this[start_index..end_index]); Ok(AvmString::new(activation.context.gc_context, ret).into()) } else { Ok("".into()) }; } Ok(Value::Undefined) } /// Implements `String.split` fn split<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { let delimiter = args.get(0).unwrap_or(&Value::Undefined); if matches!(delimiter, Value::Undefined) { let this = Value::from(this); return Ok( ArrayObject::from_storage(activation, iter::once(this).collect()) .unwrap() .into(), ); } if delimiter .as_object() .map(|o| o.as_regexp().is_some()) .unwrap_or(false) { log::warn!("string.split(regex) - not implemented"); } let this = Value::from(this).coerce_to_string(activation)?; let delimiter = delimiter.coerce_to_string(activation)?; let limit = match args.get(1).unwrap_or(&Value::Undefined) { Value::Undefined => usize::MAX, limit => limit.coerce_to_i32(activation)?.max(0) as usize, }; let storage = if delimiter.is_empty() { // When using an empty delimiter, Str::split adds an extra beginning and trailing item, but Flash does not. // e.g., split("foo", "") returns ["", "f", "o", "o", ""] in Rust but ["f, "o", "o"] in Flash. // Special case this to match Flash's behavior. this.iter() .take(limit) .map(|c| { Value::from(AvmString::new( activation.context.gc_context, WString::from_unit(c), )) }) .collect() } else { this.split(&delimiter) .take(limit) .map(|c| Value::from(AvmString::new(activation.context.gc_context, c))) .collect() }; return Ok(ArrayObject::from_storage(activation, storage) .unwrap() .into()); } Ok(Value::Undefined) } /// Implements `String.substr` fn substr<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { let this_val = Value::from(this); let this = this_val.coerce_to_string(activation)?; if args.is_empty() { return Ok(Value::from(this)); } let start_index = string_wrapping_index( args.get(0) .unwrap_or(&Value::Number(0.)) .coerce_to_number(activation)?, this.len(), ); let len = args .get(1) .unwrap_or(&Value::Number(0x7fffffff as f64)) .coerce_to_number(activation)?; let end_index = if len == f64::INFINITY { this.len() } else { this.len().min(start_index + len as usize) }; let ret = WString::from(&this[start_index..end_index]); return Ok(AvmString::new(activation.context.gc_context, ret).into()); } Ok(Value::Undefined) } /// Implements `String.substring` fn substring<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error> { if let Some(this) = this { let this_val = Value::from(this); let this = this_val.coerce_to_string(activation)?; if args.is_empty() { return Ok(Value::from(this)); } let mut start_index = string_index( args.get(0) .unwrap_or(&Value::Number(0.)) .coerce_to_number(activation)?, this.len(), ); let mut end_index = string_index( args.get(1) .unwrap_or(&Value::Number(0x7fffffff as f64)) .coerce_to_number(activation)?, this.len(), ); if end_index < start_index { std::mem::swap(&mut end_index, &mut start_index); } let ret = WString::from(&this[start_index..end_index]); return Ok(AvmString::new(activation.context.gc_context, ret).into()); } Ok(Value::Undefined) } /// Construct `String`'s class. pub fn create_class<'gc>(mc: MutationContext<'gc, '_>) -> GcCell<'gc, Class<'gc>> { let class = Class::new( QName::new(Namespace::public(), "String"), Some(QName::new(Namespace::public(), "Object").into()), Method::from_builtin(instance_init, "<String instance initializer>", mc), Method::from_builtin(class_init, "<String class initializer>", mc), mc, ); let mut write = class.write(mc); write.set_attributes(ClassAttributes::FINAL | ClassAttributes::SEALED); write.set_instance_allocator(primitive_allocator); const PUBLIC_INSTANCE_PROPERTIES: &[( &str, Option<NativeMethodImpl>, Option<NativeMethodImpl>, )] = &[("length", Some(length), None)]; write.define_public_builtin_instance_properties(mc, PUBLIC_INSTANCE_PROPERTIES); const AS3_INSTANCE_METHODS: &[(&str, NativeMethodImpl)] = &[ ("charAt", char_at), ("charCodeAt", char_code_at), ("concat", concat), ("indexOf", index_of), ("lastIndexOf", last_index_of), ("match", match_s), ("replace", replace), ("slice", slice), ("split", split), ("substr", substr), ("substring", substring), ]; write.define_as3_builtin_instance_methods(mc, AS3_INSTANCE_METHODS); const AS3_CLASS_METHODS: &[(&str, NativeMethodImpl)] = &[("fromCharCode", from_char_code)]; const PUBLIC_CLASS_METHODS: &[(&str, NativeMethodImpl)] = &[("fromCharCode", from_char_code)]; write.define_as3_builtin_class_methods(mc, AS3_CLASS_METHODS); write.define_public_builtin_class_methods(mc, PUBLIC_CLASS_METHODS); class } /// Normalizes an index parameter used in `String` functions such as `substring`. /// The returned index will be within the range of `[0, len]`. fn string_index(i: f64, len: usize) -> usize { if i == f64::INFINITY { len } else if i < 0. { 0 } else { (i as usize).min(len) } } /// Normalizes an wrapping index parameter used in `String` functions such as `slice`. /// Negative values will count backwards from `len`. /// The returned index will be within the range of `[0, len]`. fn string_wrapping_index(i: f64, len: usize) -> usize { if i < 0. { if i.is_infinite() { return 0; } let offset = i as isize; len.saturating_sub((-offset) as usize) } else { if i.is_infinite() { return len; } (i as usize).min(len) } }
33.195688
122
0.534396
db16ee0aefc2ae337e4db06ef61dc59d6a0bf49a
3,335
// Copyright 2019-2021 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT pub use tauri_runtime::{ menu::{ Menu, MenuEntry, MenuItem, MenuUpdate, Submenu, SystemTrayMenu, SystemTrayMenuEntry, SystemTrayMenuItem, TrayHandle, }, SystemTrayEvent, TrayIcon, }; pub use wry::application::{ event::TrayEvent, event_loop::EventLoopProxy, menu::{ ContextMenu as WryContextMenu, CustomMenuItem as WryCustomMenuItem, MenuItem as WryMenuItem, }, }; #[cfg(target_os = "macos")] pub use wry::application::platform::macos::CustomMenuItemExtMacOS; use crate::{Error, Message, Result, TrayMessage}; use tauri_runtime::{menu::MenuHash, UserEvent}; use uuid::Uuid; use std::{ collections::HashMap, sync::{Arc, Mutex}, }; pub type SystemTrayEventHandler = Box<dyn Fn(&SystemTrayEvent) + Send>; pub type SystemTrayEventListeners = Arc<Mutex<HashMap<Uuid, Arc<SystemTrayEventHandler>>>>; pub type SystemTrayItems = Arc<Mutex<HashMap<u16, WryCustomMenuItem>>>; #[derive(Debug, Clone)] pub struct SystemTrayHandle<T: UserEvent> { pub(crate) proxy: EventLoopProxy<super::Message<T>>, } impl<T: UserEvent> TrayHandle for SystemTrayHandle<T> { fn set_icon(&self, icon: TrayIcon) -> Result<()> { self .proxy .send_event(Message::Tray(TrayMessage::UpdateIcon(icon))) .map_err(|_| Error::FailedToSendMessage) } fn set_menu(&self, menu: SystemTrayMenu) -> Result<()> { self .proxy .send_event(Message::Tray(TrayMessage::UpdateMenu(menu))) .map_err(|_| Error::FailedToSendMessage) } fn update_item(&self, id: u16, update: MenuUpdate) -> Result<()> { self .proxy .send_event(Message::Tray(TrayMessage::UpdateItem(id, update))) .map_err(|_| Error::FailedToSendMessage) } #[cfg(target_os = "macos")] fn set_icon_as_template(&self, is_template: bool) -> tauri_runtime::Result<()> { self .proxy .send_event(Message::Tray(TrayMessage::UpdateIconAsTemplate( is_template, ))) .map_err(|_| Error::FailedToSendMessage) } } impl From<SystemTrayMenuItem> for crate::MenuItemWrapper { fn from(item: SystemTrayMenuItem) -> Self { match item { SystemTrayMenuItem::Separator => Self(WryMenuItem::Separator), _ => unimplemented!(), } } } pub fn to_wry_context_menu( custom_menu_items: &mut HashMap<MenuHash, WryCustomMenuItem>, menu: SystemTrayMenu, ) -> WryContextMenu { let mut tray_menu = WryContextMenu::new(); for item in menu.items { match item { SystemTrayMenuEntry::CustomItem(c) => { #[allow(unused_mut)] let mut item = tray_menu.add_item(crate::MenuItemAttributesWrapper::from(&c).0); #[cfg(target_os = "macos")] if let Some(native_image) = c.native_image { item.set_native_image(crate::NativeImageWrapper::from(native_image).0); } custom_menu_items.insert(c.id, item); } SystemTrayMenuEntry::NativeItem(i) => { tray_menu.add_native_item(crate::MenuItemWrapper::from(i).0); } SystemTrayMenuEntry::Submenu(submenu) => { tray_menu.add_submenu( &submenu.title, submenu.enabled, to_wry_context_menu(custom_menu_items, submenu.inner), ); } } } tray_menu }
29.776786
96
0.678261
90564e8ce172477ba8968365843d4a208889e553
2,506
mod components; pub use components::*; mod camera; pub use camera::*; mod player; pub use player::*; mod map; pub use map::*; mod monsters; pub use monsters::*; mod bullets; pub use bullets::*; mod living_beings; pub use living_beings::*; mod monster_ai; pub use monster_ai::*; use super::AppState; use bevy::prelude::*; use bevy_rapier2d::prelude::*; pub struct GamePlugin; impl Plugin for GamePlugin { fn build(&self, app: &mut App) { app.add_system_set(SystemSet::on_enter(AppState::InGame).with_system(spawn_floor.system())) .add_system_set( SystemSet::on_update(AppState::InGame) .with_system(back_to_main_menu_controls.system()), ) .add_plugin(RapierPhysicsPlugin::<NoUserData>::default()) .add_plugin(PlayerPlugin) .add_plugin(MonsterAiPlugin) .add_system(on_level_success.system()) .add_startup_system(setup.system()); } } fn setup(mut commands: Commands) { commands.insert_resource(Materials { player_material: Color::rgb(0.969, 0.769, 0.784).into(), floor_material: Color::rgb(0.7, 0.7, 0.7).into(), monster_material: Color::rgb(0.8, 0., 0.).into(), bullet_material: Color::rgb(0.8, 0.8, 0.).into(), winning_zone_material: Color::rgb(0., 0.75, 1.).into(), }); } fn back_to_main_menu_controls( mut keys: ResMut<Input<KeyCode>>, mut app_state: ResMut<State<AppState>>, ) { if *app_state.current() == AppState::InGame { if keys.just_pressed(KeyCode::Escape) { app_state.set(AppState::MainMenu).unwrap(); keys.reset(KeyCode::Escape); } } } fn on_level_success( mut app_state: ResMut<State<AppState>>, players: Query<Entity, With<Player>>, winning_zones: Query<Entity, With<WinningZone>>, mut contact_events: EventReader<ContactEvent>, ) { for contact_event in contact_events.iter() { if let ContactEvent::Started(h1, h2) = contact_event { let player = players.get_single(); let winning_zone = winning_zones.get_single(); if player.is_ok() && winning_zone.is_ok() { let p = player.unwrap(); let w = winning_zone.unwrap(); if (h1.entity() == p && h2.entity() == w) || (h1.entity() == w && h2.entity() == p) { app_state.set(AppState::BetweenLevels).unwrap(); } } } } }
30.560976
99
0.601756
0e19b63c8b6eea266a0ce5c42e542f03f899c01a
10,135
#![recursion_limit = "256"] extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2::Span; use proc_macro_crate::crate_name; use quote::quote; use syn::{ parse_macro_input, Attribute, Data, DeriveInput, Fields, FieldsNamed, FieldsUnnamed, Ident, Meta, }; #[proc_macro_derive(DeserializeOver, attributes(deserialize_over))] pub fn derive(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let crate_name = crate_name("serde-deserialize-over").unwrap_or("serde_deserialize_over".to_string()); let crate_name = Ident::new(&crate_name, Span::call_site()); let struct_name = input.ident; let data = match input.data { Data::Struct(data) => data, Data::Enum(_) => panic!("`DeserializeOver` cannot be automatically derived for enums"), Data::Union(_) => panic!("`DeserializeOver` cannot be automatically derived for unions"), }; let res = match data.fields { Fields::Named(fields) => impl_named_fields(struct_name, crate_name, fields), Fields::Unnamed(fields) => impl_unnamed_fields(struct_name, crate_name, fields), Fields::Unit => impl_unit(struct_name, crate_name), }; match res { Ok(res) => res, Err(e) => e.to_compile_error().into(), } } #[derive(Clone)] struct FieldInfo { name: Ident, passthrough: bool, } fn impl_generic( struct_name: Ident, real_crate_name: Ident, fields: Vec<FieldInfo>, fields_numbered: bool, ) -> syn::Result<TokenStream> { let deserializer = Ident::new("__deserializer", Span::call_site()); let crate_name = Ident::new("_serde_deserialize_over", Span::call_site()); let export = quote! { #crate_name::export }; let field_enums = fields .iter() .cloned() .enumerate() .map(|(idx, x)| Ident::new(&format!("__field{}", idx), x.name.span())) .collect::<Vec<_>>(); let field_enums = &field_enums; let field_enums_copy1 = field_enums; let field_enums_copy2 = field_enums; let field_names = fields.iter().map(|x| &x.name).cloned().collect::<Vec<_>>(); let field_names = &field_names; let indices = (0usize..fields.len()).collect::<Vec<_>>(); let indices_u64 = indices.iter().map(|x| *x as u64); let missing_field_error_str = syn::LitStr::new( &format!("field index between 0 <= i < {}", fields.len()), Span::call_site(), ); let visit_str_and_bytes_impl = if !fields_numbered { let names_str = field_names .iter() .map(|x| syn::LitStr::new(&x.to_string(), x.span())) .collect::<Vec<_>>(); let names_bytes = field_names .iter() .map(|x| syn::LitByteStr::new(x.to_string().as_bytes(), x.span())) .collect::<Vec<_>>(); quote! { fn visit_str<E>(self, value: &str) -> #export::Result<Self::Value, E> where E: #export::Error { #export::Ok(match value { #( #names_str => __Field::#field_enums, )* _ => __Field::__ignore }) } fn visit_bytes<E>(self, value: &[u8]) -> #export::Result<Self::Value, E> where E: #export::Error { #export::Ok(match value { #( #names_bytes => __Field::#field_enums, )* _ => __Field::__ignore }) } } } else { quote! {} }; let map_de_entries = fields .iter() .map(|field| { let ref name = field.name; if field.passthrough { quote! { map.next_value_seed( #crate_name::DeserializeOverWrapper(&mut (self.0).#name) )? } } else { quote! { (self.0).#name = map.next_value()? } } }) .collect::<Vec<_>>(); let visit_seq_entries = fields .iter() .map(|field| { let ref name = field.name; if field.passthrough { quote! { match seq.next_element_seed( #crate_name::DeserializeOverWrapper(&mut (self.0).#name) )? { Some(()) => (), None => return Ok(()) } } } else { quote! { (self.0).#name = match seq.next_element()? { Some(x) => x, None => return Ok(()) } } } }) .collect::<Vec<_>>(); let inner = quote! { #[allow(unknown_lints)] #[allow(rust_2018_idioms)] extern crate #real_crate_name as #crate_name; #[automatically_derived] impl DeserializeOver for #struct_name { fn deserialize_over<'de, D>(&mut self, #deserializer: D) -> #export::Result<(), D::Error> where D: #export::Deserializer<'de> { #[allow(non_camel_case_types)] enum __Field { #( #field_enums, )* __ignore } impl<'de> #export::Deserialize<'de> for __Field { fn deserialize<D>(#deserializer: D) -> #export::Result<Self, D::Error> where D: #export::Deserializer<'de> { #export::Deserializer::deserialize_identifier(#deserializer, __FieldVisitor) } } struct __FieldVisitor; impl<'de> #export::Visitor<'de> for __FieldVisitor { type Value = __Field; fn expecting(&self, fmt: &mut #export::fmt::Formatter) -> #export::fmt::Result { #export::fmt::Formatter::write_str(fmt, "field identifier") } fn visit_u64<E>(self, value: u64) -> #export::Result<Self::Value, E> where E: #export::Error { use #export::{Ok, Err}; Ok(match value { #( #indices_u64 => __Field::#field_enums, )* _ => return Err(#export::Error::invalid_value( #export::Unexpected::Unsigned(value), &#missing_field_error_str )) }) } #visit_str_and_bytes_impl } struct __Visitor<'a>(pub &'a mut #struct_name); impl<'a, 'de> #export::Visitor<'de> for __Visitor<'a> { type Value = (); fn expecting(&self, fmt: &mut #export::fmt::Formatter) -> #export::fmt::Result { #export::fmt::Formatter::write_str(fmt, concat!("struct ", stringify!(#struct_name))) } fn visit_seq<A>(self, mut seq: A) -> #export::Result<Self::Value, A::Error> where A: #export::SeqAccess<'de> { use #export::{Some, None}; #( #visit_seq_entries; )* Ok(()) } fn visit_map<A>(self, mut map: A) -> #export::Result<Self::Value, A::Error> where A: #export::MapAccess<'de> { use #export::{Some, None, Error}; // State tracking #( let mut #field_enums: bool = false; )* while let Some(key) = map.next_key::<__Field>()? { match key { #( __Field::#field_enums => if #field_enums_copy1 { return Err(<A::Error as Error>::duplicate_field(stringify!(#field_names))); } else { #field_enums_copy2 = true; #map_de_entries; } )* _ => (), } } Ok(()) } } const FIELDS: &[&str] = &[ #( stringify!(#field_names), )* ]; #export::Deserializer::deserialize_struct( #deserializer, stringify!(#struct_name), FIELDS, __Visitor(self) ) } } }; let const_name = Ident::new( &format!("_IMPL_DESERIALIZE_OVER_FOR_{}", struct_name), struct_name.span(), ); Ok(quote! { #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] const #const_name: () = { #inner }; } .into()) } fn impl_named_fields( struct_name: Ident, crate_name: Ident, fields: FieldsNamed, ) -> syn::Result<TokenStream> { let fieldinfos = fields .named .iter() .map(|x| { let attrinfo = parse_attr(x.attrs.iter())?; Ok(FieldInfo { name: x.ident.clone().unwrap(), passthrough: attrinfo.use_deserialize_over, }) }) .collect::<Result<Vec<_>, syn::Error>>()?; return impl_generic(struct_name, crate_name, fieldinfos, false); } fn impl_unnamed_fields( _struct_name: Ident, _crate_name: Ident, _fields: FieldsUnnamed, ) -> syn::Result<TokenStream> { unimplemented!() } fn impl_unit(struct_name: Ident, crate_name: Ident) -> syn::Result<TokenStream> { Ok(quote! { impl ::#crate_name::DeserializeOver for #struct_name { fn deserialize_over<'de, D>(&mut self, de: D) -> Result<(), D::Error> where D: Deserializer<'de> { Ok(()) } } } .into()) } #[derive(Default)] struct ParsedAttr { use_deserialize_over: bool, } fn parse_attr<'a, I>(attrs: I) -> syn::Result<ParsedAttr> where I: Iterator<Item = &'a Attribute>, { let mut result = ParsedAttr::default(); for attr in attrs.into_iter() { match attr.parse_meta()? { Meta::Path(ref path) => { if path.is_ident("deserialize_over") { result.use_deserialize_over = true; } } Meta::List(_) | Meta::NameValue(_) => (), } } Ok(result) }
29.291908
99
0.506265
ac0a0d5709c4081b6449b6ab397e59c2f883da89
1,603
// Copyright 2017 rust-ipfs-api Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. // use ipfs_api_examples::ipfs_api::{IpfsApi, IpfsClient}; const IPFS_IPNS: &str = "/ipns/ipfs.io"; // Creates an Ipfs client, and resolves the Ipfs domain name, and // publishes a path to Ipns. // #[ipfs_api_examples::main] async fn main() { tracing_subscriber::fmt::init(); eprintln!("connecting to localhost:5001..."); let client = IpfsClient::default(); match client.name_resolve(Some(IPFS_IPNS), true, false).await { Ok(resolved) => eprintln!("{} resolves to: {}", IPFS_IPNS, &resolved.path), Err(e) => { eprintln!("error resolving {}: {}", IPFS_IPNS, e); return; } } let publish = match client.name_publish(IPFS_IPNS, true, None, None, None).await { Ok(publish) => { eprintln!("published {} to: /ipns/{}", IPFS_IPNS, &publish.name); publish } Err(e) => { eprintln!("error publishing name: {}", e); return; } }; match client.name_resolve(Some(&publish.name), true, false).await { Ok(resolved) => { eprintln!("/ipns/{} resolves to: {}", &publish.name, &resolved.path); } Err(e) => { eprintln!("error resolving name: {}", e); } } }
30.826923
86
0.593263
9038ac2168886ad8b12ded2aa250e0945bff9796
1,790
use crate::converter::{Converter, IndexWithConverter}; pub trait BackwardIterableIndex: Sized { type T: Copy + Clone; fn get_l(&self, i: u64) -> Self::T; fn lf_map(&self, i: u64) -> u64; fn lf_map2(&self, c: Self::T, i: u64) -> u64; fn len(&self) -> u64; fn iter_backward(&self, i: u64) -> BackwardIterator<Self> { debug_assert!(i < self.len()); BackwardIterator { index: self, i } } } pub struct BackwardIterator<'a, I> where I: BackwardIterableIndex, { index: &'a I, i: u64, } impl<'a, T, I> Iterator for BackwardIterator<'a, I> where T: Copy + Clone, I: BackwardIterableIndex<T = T> + IndexWithConverter<T>, { type Item = <I as BackwardIterableIndex>::T; fn next(&mut self) -> Option<Self::Item> { let c = self.index.get_l(self.i); self.i = self.index.lf_map(self.i); Some(self.index.get_converter().convert_inv(c)) } } pub trait ForwardIterableIndex: Sized { type T: Copy + Clone; fn get_f(&self, i: u64) -> Self::T; fn fl_map(&self, i: u64) -> u64; fn fl_map2(&self, c: Self::T, i: u64) -> u64; fn len(&self) -> u64; fn iter_forward(&self, i: u64) -> ForwardIterator<Self> { debug_assert!(i < self.len()); ForwardIterator { index: self, i } } } pub struct ForwardIterator<'a, I> where I: ForwardIterableIndex, { index: &'a I, i: u64, } impl<'a, T, I> Iterator for ForwardIterator<'a, I> where T: Copy + Clone, I: ForwardIterableIndex<T = T> + IndexWithConverter<T>, { type Item = <I as ForwardIterableIndex>::T; fn next(&mut self) -> Option<Self::Item> { let c = self.index.get_f(self.i); self.i = self.index.fl_map(self.i); Some(self.index.get_converter().convert_inv(c)) } }
25.571429
63
0.599441
72119f7df55a8d58bd79aba26cd10f362daceca6
2,986
use crate::pde_parser::pde_ir::{ir_helper::*, lexer_compositor::*}; use crate::pde_parser::pde_lexer::math::expr; use crate::pde_parser::pde_lexer::math::factor; use crate::pde_parser::pde_lexer::var::var; use nom::branch::alt; use nom::bytes::complete::tag; use nom::character::complete::one_of; use nom::character::complete::space0; use nom::character::complete::u32; use nom::combinator::{eof, opt}; use nom::error::Error; use nom::multi::separated_list1; use nom::number::complete::double; use nom::sequence::delimited; use nom::sequence::pair; use nom::sequence::preceded; use nom::sequence::terminated; use nom::Finish; use nom::IResult; use std::cell::RefCell; use std::ops::Range; use super::pde_ir::lexer_compositor::LexerComp; use super::{SPDETokens, DPDE}; mod fun; mod math; mod var; thread_local!( static VARS: RefCell<Vec<DPDE>> = RefCell::new(vec![]); static CURRENT_VAR: RefCell<Option<SPDETokens>> = RefCell::new(None); static GLOBAL_DIM: RefCell<usize> = RefCell::new(0); static FUN_LEN: RefCell<usize> = RefCell::new(0); ); fn next_id() -> usize { let mut fun_len = None; FUN_LEN.with(|fl| { fun_len = Some(*fl.borrow()); *fl.borrow_mut() += 1; }); fun_len.expect("Could not retreive FUN_LEN in fix_constructor.") } pub fn parse<'a>( context: &[DPDE], // var name current_var: &Option<SPDETokens>, // boundary funciton name fun_len: usize, // number of existing functions global_dim: usize, // dim math: &'a str, ) -> Result<(&'a str, LexerComp), Error<&'a str>> { VARS.with(|v| *v.borrow_mut() = context.to_vec()); CURRENT_VAR.with(|v| *v.borrow_mut() = current_var.clone()); GLOBAL_DIM.with(|v| *v.borrow_mut() = global_dim); FUN_LEN.with(|v| *v.borrow_mut() = fun_len); terminated(delimited(space0, expr, space0), eof)(math).finish() } pub fn stag(t: &'static str) -> impl Fn(&str) -> IResult<&str, &str> { move |s| delimited(space0, tag(t), space0)(s) } pub fn array<T: Clone>( f: impl Fn(&str) -> IResult<&str, T> + Copy, ) -> impl Fn(&str) -> IResult<&str, Vec<T>> { move |s| { delimited( stag("["), separated_list1(delimited(space0, one_of(",;"), space0), f), stag("]"), )(s) .map(|(s, vs)| (s, vs.to_vec())) } } pub fn term(s: &str) -> IResult<&str, LexerComp> { let parens = delimited(stag("("), expr, stag(")")); let arr = |s| array(expr)(s).map(|(s, v)| (s, compact(v).map(vect))); let unary_minus = |s| preceded(stag("-"), factor)(s).map(|(s, v)| (s, LexerComp::from(Const(-1.0)) * v)); alt((parens, arr, num, unary_minus, var))(s) } pub fn range(s: &str) -> IResult<&str, Range<usize>> { pair(u32, opt(preceded(stag(".."), u32)))(s) .map(|(s, (a, b))| (s, a as usize..(b.unwrap_or(a) + 1) as usize)) } pub fn num(s: &str) -> IResult<&str, LexerComp> { double(s).map(|(s, d)| (s, d.into())) }
32.456522
95
0.603818
e227408c55628af5d0e49450c135990424384466
2,049
//! API for analog control (ANACTRL) - always on // use core::marker::PhantomData; // use crate::typestates::Fro96MHzEnabledToken; // use crate::{ raw,}; // UM says: // NOTE: The clock to analog controller module is enabled during boot time // by the boot loader and it should always stay enabled // // So for safety, should enforce it's enabled crate::wrap_always_on_peripheral!(Anactrl, ANACTRL); impl Anactrl { // pub(crate) fn latch_fro_to_usbfs_sof(&mut self) { // // "If this bit is set and the USB peripheral is enabled into full-speed // // device mode, the USB block will provide FRO clock adjustments to // // lock it to the host clock using the SOF packets." // self.raw.fro192m_ctrl.modify(|_, w| w.usbclkadj().set_bit()); // // TODO: do we need any stabilisation? e.g. // // "USBMODCHG If it reads as 1 when reading the DAC_TRIM field and // // USBCLKADJ=1, it should be re-read until it is 0." // // <-- this is mentioned in the UM, but missing in the PAC. // } pub fn is_12mhzclk_enabled(&self) -> bool { self.raw.fro192m_ctrl.read().ena_12mhzclk().is_enable() } /// Supposedly, this is needed for Flash, hence enabled by default pub fn is_48mhzclk_enabled(&self) -> bool { self.raw.fro192m_ctrl.read().ena_48mhzclk().is_enable() } /// UM says not enabled by default, empiricially seems it is pub fn is_96mhzclk_enabled(&self) -> bool { // ewww this hard-faults if 12MHz clock is main clock?! self.raw.fro192m_ctrl.read().ena_96mhzclk().is_enable() && self.raw.fro192m_status.read().clk_valid().is_clkout() } // pub(crate) fn enable_96mhzclk(&self) { // self.raw.fro192m_ctrl.modify(|_, w| w.ena_96mhzclk().enable()); // } // pub fn fro96mhz_enabled_token(&self) -> Option<Fro96MHzEnabledToken> { // if self.is_96mhzclk_enabled() { // Some(Fro96MHzEnabledToken{__: PhantomData}) // } else { // None // } // } }
37.944444
83
0.634944
8f75d65b40925d778e4cfd12140f8f058f4a72ca
1,018
/// ProvidersLdapItem : Specifies the properties for the LDAP authentication provider. #[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct ProvidersLdapItem { /// Specifies the attribute name used when searching for alternate security identities. #[serde(rename = "alternate_security_identities_attribute")] pub alternate_security_identities_attribute: Option<String>, /// If true, enables authentication and identity management through the authentication provider. #[serde(rename = "authentication")] pub authentication: Option<bool>, /// If true, connects the provider to a random server. #[serde(rename = "balance_servers")] pub balance_servers: Option<bool>, /// Specifies the root of the tree in which to search identities. #[serde(rename = "base_dn")] pub base_dn: String, /// Specifies the distinguished name for binding to the LDAP server. #[serde(rename = "bind_dn")] pub bind_dn: Option<String>, }
42.416667
100
0.731827
87ef3d81f839ff896d81a8fe4686eb90ba635e44
1,763
// //! Copyright 2020 Alibaba Group Holding Limited. //! //! 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. pub use concise::*; pub use iteration::{IterCondition, Iteration}; pub use primitive::binary::Binary; pub use primitive::branch::Branch; pub use primitive::sink::{FromStream, Sink}; pub use primitive::source::{IntoDataflow, Source}; pub use primitive::unary::Unary; pub mod notification { use crate::progress::EndOfScope; use crate::Tag; #[derive(Debug, Clone)] pub struct End { pub(crate) port: usize, pub(crate) end: EndOfScope, } #[derive(Debug, Clone)] pub struct Cancel { pub(crate) port: usize, pub(crate) tag: Tag, } impl End { pub fn tag(&self) -> &Tag { &self.end.tag } pub fn port(&self) -> usize { self.port } pub fn take(self) -> EndOfScope { self.end } } impl Cancel { pub fn tag(&self) -> &Tag { &self.tag } pub fn port(&self) -> usize { self.port } } } pub(crate) mod concise; pub mod error; pub mod function; pub(crate) mod iteration; pub mod meta; pub(crate) mod primitive; pub(crate) mod scope;
24.150685
76
0.620533
29704c9f73fb7a5472962b4e52682ca6fefb8aba
185
mod file; mod fmt; mod graph; mod node; mod uses; mod variable; pub use self::file::*; pub use self::graph::*; pub use self::node::*; pub use self::uses::*; pub use self::variable::*;
14.230769
26
0.654054
0ada2d7cbcd04759665ae022804515277b051e47
7,092
// 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. //! Representation of the virtual_device metadata. use crate::common::{ AudioModel, DataUnits, ElementType, Envelope, PointingDevice, ScreenUnits, TargetArchitecture, }; use crate::json::{schema, JsonObject}; use serde::{Deserialize, Serialize}; /// Specifics for a CPU. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct Cpu { /// Target CPU architecture. pub arch: TargetArchitecture, } /// Details of virtual input devices, such as mice. #[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct InputDevice { /// Pointing device for interacting with the target. pub pointing_device: PointingDevice, } /// Details of the virtual device's audio interface, if any. #[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct AudioDevice { /// The model of the emulated audio device, or None. pub model: AudioModel, } /// Screen dimensions for the virtual device, if any. #[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct Screen { pub height: usize, pub width: usize, pub units: ScreenUnits, } /// A generic data structure for indicating quantities of data. #[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct DataAmount { pub quantity: usize, pub units: DataUnits, } /// Specifics for a given platform. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct Hardware { /// Details of the Central Processing Unit (CPU). pub cpu: Cpu, /// Details about any audio devices included in the virtual device. pub audio: AudioDevice, /// The size of the disk image for the virtual device, equivalent to virtual storage capacity. pub storage: DataAmount, /// Details about any input devices, such as a mouse or touchscreen. pub inputs: InputDevice, /// Amount of memory in the virtual device. pub memory: DataAmount, /// The size of the virtual device's screen, measured in pixels. pub window_size: Screen, } /// Description of a virtual (rather than physical) hardware device. /// /// This does not include the data "envelope", i.e. it begins within /data in /// the source json file. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct VirtualDeviceV1 { /// A unique name identifying the virtual device specification. pub name: String, /// An optional human readable description. #[serde(skip_serializing_if = "Option::is_none")] pub description: Option<String>, /// Always "virtual_device" for a VirtualDeviceV1. This is valuable for /// debugging or when writing this record to a json string. #[serde(rename = "type")] pub kind: ElementType, /// Details about the properties of the device. pub hardware: Hardware, } impl JsonObject for Envelope<VirtualDeviceV1> { fn get_schema() -> &'static str { include_str!("../virtual_device-93A41932.json") } fn get_referenced_schemata() -> &'static [&'static str] { &[schema::COMMON, schema::HARDWARE_V1] } } #[cfg(test)] mod tests { use super::*; test_validation! { name = test_validation, kind = Envelope::<VirtualDeviceV1>, data = r#" { "schema_id": "http://fuchsia.com/schemas/sdk/virtual_device-93A41932.json", "data": { "name": "generic-x64", "type": "virtual_device", "hardware": { "audio": { "model": "hda" }, "cpu": { "arch": "x64" }, "inputs": { "pointing_device": "touch" }, "window_size": { "width": 640, "height": 480, "units": "pixels" }, "memory": { "quantity": 1, "units": "gigabytes" }, "storage": { "quantity": 1, "units": "gigabytes" } } } } "#, valid = true, } test_validation! { name = test_validation_skip_behaviors, kind = Envelope::<VirtualDeviceV1>, data = r#" { "schema_id": "http://fuchsia.com/schemas/sdk/virtual_device-93A41932.json", "data": { "name": "generic-x64", "type": "virtual_device", "hardware": { "audio": { "model": "hda" }, "cpu": { "arch": "x64" }, "inputs": { "pointing_device": "touch" }, "window_size": { "width": 640, "height": 480, "units": "pixels" }, "memory": { "quantity": 1, "units": "gigabytes" }, "storage": { "quantity": 1, "units": "gigabytes" } } } } "#, valid = true, } test_validation! { name = test_validation_invalid, kind = Envelope::<VirtualDeviceV1>, data = r#" { "schema_id": "http://fuchsia.com/schemas/sdk/virtual_device-93A41932.json", "data": { "name": "generic-x64", "type": "cc_prebuilt_library", "hardware": { "audio": { "model": "hda" }, "cpu": { "arch": "x64" }, "inputs": { "pointing_device": "touch" }, "window_size": { "width": 640, "height": 480, "units": "pixels" }, "memory": { "quantity": 1, "units": "gigabytes" }, "storage": { "quantity": 1, "units": "gigabytes" } } } } "#, // Incorrect type valid = false, } }
30.568966
98
0.494501
efa9ea2581992804d01162b6a4c7030737b36d9c
8,069
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { anyhow::Error, async_trait::async_trait, clonable_error::ClonableError, fidl::endpoints::ServerEnd, fidl_fuchsia_component as fcomponent, fidl_fuchsia_component_runner as fcrunner, fuchsia_async as fasync, fuchsia_zircon as zx, futures::stream::TryStreamExt, thiserror::Error, }; /// Executes a component instance. /// TODO: The runner should return a trait object to allow the component instance to be stopped, /// binding to services, and observing abnormal termination. In other words, a wrapper that /// encapsulates fcrunner::ComponentController FIDL interfacing concerns. /// TODO: Consider defining an internal representation for `fcrunner::ComponentStartInfo` so as to /// further isolate the `Model` from FIDL interfacting concerns. #[async_trait] pub trait Runner: Sync + Send { #[must_use] async fn start( &self, start_info: fcrunner::ComponentStartInfo, server_end: ServerEnd<fcrunner::ComponentControllerMarker>, ); } /// Errors produced by `Runner`. #[derive(Debug, Error, Clone)] pub enum RunnerError { #[error("invalid arguments provided for component with url \"{}\": {}", url, err)] InvalidArgs { url: String, #[source] err: ClonableError, }, #[error("unable to load component with url \"{}\": {}", url, err)] ComponentLoadError { url: String, #[source] err: ClonableError, }, #[error("runner failed to launch component with url \"{}\": {}", url, err)] ComponentLaunchError { url: String, #[source] err: ClonableError, }, #[error("failed to populate the runtime directory: {}", err)] ComponentRuntimeDirectoryError { #[source] err: ClonableError, }, #[error("failed to connect to the runner: {}", err)] RunnerConnectionError { #[source] err: ClonableError, }, #[error("remote runners unsupported")] Unsupported, } impl RunnerError { pub fn invalid_args(url: impl Into<String>, err: impl Into<Error>) -> RunnerError { RunnerError::InvalidArgs { url: url.into(), err: err.into().into() } } pub fn component_load_error(url: impl Into<String>, err: impl Into<Error>) -> RunnerError { RunnerError::ComponentLoadError { url: url.into(), err: err.into().into() } } pub fn component_launch_error(url: impl Into<String>, err: impl Into<Error>) -> RunnerError { RunnerError::ComponentLaunchError { url: url.into(), err: err.into().into() } } pub fn component_runtime_directory_error(err: impl Into<Error>) -> RunnerError { RunnerError::ComponentRuntimeDirectoryError { err: err.into().into() } } pub fn runner_connection_error(err: impl Into<Error>) -> RunnerError { RunnerError::RunnerConnectionError { err: err.into().into() } } /// Convert this error into its approximate `fuchsia.component.Error` equivalent. pub fn as_fidl_error(&self) -> fcomponent::Error { match self { RunnerError::InvalidArgs { .. } => fcomponent::Error::InvalidArguments, RunnerError::ComponentLoadError { .. } => fcomponent::Error::InstanceCannotStart, RunnerError::ComponentLaunchError { .. } => fcomponent::Error::InstanceCannotStart, RunnerError::ComponentRuntimeDirectoryError { .. } => fcomponent::Error::Internal, RunnerError::RunnerConnectionError { .. } => fcomponent::Error::Internal, RunnerError::Unsupported { .. } => fcomponent::Error::Unsupported, } } /// Convert this error into its approximate `zx::Status` equivalent. pub fn as_zx_status(&self) -> zx::Status { match self { RunnerError::InvalidArgs { .. } => zx::Status::INVALID_ARGS, RunnerError::ComponentLoadError { .. } => zx::Status::UNAVAILABLE, RunnerError::ComponentLaunchError { .. } => zx::Status::UNAVAILABLE, RunnerError::ComponentRuntimeDirectoryError { .. } => zx::Status::INTERNAL, RunnerError::RunnerConnectionError { .. } => zx::Status::INTERNAL, RunnerError::Unsupported { .. } => zx::Status::NOT_SUPPORTED, } } } /// A null runner for components without a runtime environment. /// /// Such environments, even though they don't execute any code, can still be /// used by other components to bind to, which in turn may trigger further /// bindings to its children. pub(super) struct NullRunner {} #[async_trait] impl Runner for NullRunner { async fn start( &self, _start_info: fcrunner::ComponentStartInfo, server_end: ServerEnd<fcrunner::ComponentControllerMarker>, ) { spawn_null_controller_server( server_end .into_stream() .expect("NullRunner failed to convert server channel into request stream"), ); } } /// Spawn an async execution context which takes ownership of `server_end` /// and holds on to it until a stop or kill request is received. fn spawn_null_controller_server(mut request_stream: fcrunner::ComponentControllerRequestStream) { // Listen to the ComponentController server end and exit after the first // one, as this is the contract we have implemented so far. Exiting will // cause our handle to the channel to drop and close the channel. fasync::Task::spawn(async move { while let Ok(Some(request)) = request_stream.try_next().await { match request { fcrunner::ComponentControllerRequest::Stop { control_handle: c } => { c.shutdown(); break; } fcrunner::ComponentControllerRequest::Kill { control_handle: c } => { c.shutdown(); break; } } } }) .detach(); } /// Wrapper for converting fcomponent::Error into the anyhow::Error type. #[derive(Debug, Clone, Error)] pub struct RemoteRunnerError(pub fcomponent::Error); impl std::fmt::Display for RemoteRunnerError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // Use the Debug formatter for Display. use std::fmt::Debug; self.0.fmt(f) } } impl std::convert::From<fcomponent::Error> for RemoteRunnerError { fn from(error: fcomponent::Error) -> RemoteRunnerError { RemoteRunnerError(error) } } /// A runner provided by another component. pub struct RemoteRunner { client: fcrunner::ComponentRunnerProxy, } impl RemoteRunner { pub fn new(client: fcrunner::ComponentRunnerProxy) -> RemoteRunner { RemoteRunner { client } } } #[async_trait] impl Runner for RemoteRunner { async fn start( &self, start_info: fcrunner::ComponentStartInfo, server_end: ServerEnd<fcrunner::ComponentControllerMarker>, ) { self.client.start(start_info, server_end).unwrap(); } } #[cfg(test)] mod tests { use super::*; use fidl::endpoints::{self, Proxy}; #[fuchsia::test] async fn test_null_runner() { let null_runner = NullRunner {}; let (client, server) = endpoints::create_endpoints::<fcrunner::ComponentControllerMarker>().unwrap(); null_runner .start( fcrunner::ComponentStartInfo { resolved_url: None, program: None, ns: None, outgoing_dir: None, runtime_dir: None, ..fcrunner::ComponentStartInfo::EMPTY }, server, ) .await; let proxy = client.into_proxy().expect("failed converting to proxy"); proxy.stop().expect("failed to send message to null runner"); proxy.on_closed().await.expect("failed waiting for channel to close"); } }
36.183857
98
0.632916
1a51912dd30bc079cbcdcb27cc0d00e96662b8b9
1,049
use super::schema::{games, users}; use diesel::{Insertable, Queryable}; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Queryable, Serialize)] pub struct User { pub id: i32, pub name: String, pub pronouns: String, pub age: i32, #[serde(skip)] pub deleted: bool, pub username: String, } #[derive(Debug, Clone, Insertable, Deserialize)] #[table_name = "users"] pub struct NewUser<'a> { pub name: &'a str, pub pronouns: &'a str, pub age: i32, pub username: &'a str, } #[derive(Debug, Clone, Insertable, Deserialize)] #[table_name = "users"] pub struct NewUserOwned { pub name: String, pub pronouns: String, pub age: i32, pub username: String, } #[derive(Debug, Clone, Queryable)] pub struct GameRecord { pub id: i32, pub player_1: i32, pub player_2: i32, pub winner: Option<i32>, pub rounds: Option<i32>, } #[derive(Debug, Clone, Insertable, Deserialize)] #[table_name = "games"] pub struct NewGameRecord { pub player_1: i32, pub player_2: i32, }
21.408163
48
0.648236
4b82558fec007cafce4f44f79a2c1a22674f900e
3,390
#![doc(html_root_url = "https://docs.rs/mio/0.7.0")] #![deny(missing_docs, missing_debug_implementations, rust_2018_idioms)] // Disallow warnings when running tests. #![cfg_attr(test, deny(warnings))] // Disallow warnings in examples. #![doc(test(attr(deny(warnings))))] //! A fast, low-level IO library for Rust focusing on non-blocking APIs, event //! notification, and other useful utilities for building high performance IO //! apps. //! //! # Features //! //! * Non-blocking TCP, UDP //! * I/O event queue backed by epoll, kqueue, and IOCP //! * Zero allocations at runtime //! * Platform specific extensions //! //! # Non-goals //! //! The following are specifically omitted from Mio and are left to the user or //! higher-level libraries. //! //! * File operations //! * Thread pools / multi-threaded event loop //! * Timers //! //! # Platforms //! //! Currently supported platforms: //! //! * Android //! * DragonFly BSD //! * FreeBSD //! * Linux //! * NetBSD //! * OpenBSD //! * Solaris //! * Windows //! * iOS //! * macOS //! //! Mio can handle interfacing with each of the event systems of the //! aforementioned platforms. The details of their implementation are further //! discussed in [`Poll`]. //! //! # Usage //! //! Using Mio starts by creating a [`Poll`], which reads events from the OS and //! puts them into [`Events`]. You can handle IO events from the OS with it. //! //! For more detail, see [`Poll`]. //! //! [`Poll`]: struct.Poll.html //! [`Events`]: struct.Events.html //! //! # Example //! //! ``` //! use mio::*; //! use mio::net::{TcpListener, TcpStream}; //! //! // Setup some tokens to allow us to identify which event is //! // for which socket. //! const SERVER: Token = Token(0); //! const CLIENT: Token = Token(1); //! //! let addr = "127.0.0.1:13265".parse().unwrap(); //! //! // Setup the server socket //! let server = TcpListener::bind(addr).unwrap(); //! //! // Create a poll instance //! let mut poll = Poll::new().unwrap(); //! //! // Start listening for incoming connections //! poll.registry().register(&server, SERVER, Interests::READABLE).unwrap(); //! //! // Setup the client socket //! let sock = TcpStream::connect(addr).unwrap(); //! //! // Register the socket //! poll.registry().register(&sock, CLIENT, Interests::READABLE).unwrap(); //! //! // Create storage for events //! let mut events = Events::with_capacity(1024); //! //! loop { //! poll.poll(&mut events, None).unwrap(); //! //! for event in events.iter() { //! match event.token() { //! SERVER => { //! // Accept and drop the socket immediately, this will close //! // the socket and notify the client of the EOF. //! let _ = server.accept(); //! } //! CLIENT => { //! // The server just shuts down the socket, let's just exit //! // from our event loop. //! return; //! } //! _ => unreachable!(), //! } //! } //! } //! //! ``` mod interests; mod poll; mod sys; mod token; mod waker; pub mod event; pub mod net; #[doc(no_inline)] pub use event::Events; pub use interests::Interests; pub use poll::{Poll, Registry}; pub use token::Token; pub use waker::Waker; #[cfg(unix)] pub mod unix { //! Unix only extensions. pub use crate::sys::SocketAddr; pub use crate::sys::SourceFd; }
25.681818
79
0.599705
bf7254306a3ef1f14a918410551776a1df7d53b8
2,068
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. /// A function that converts a float to a string the represents a human /// readable version of that number. pub fn human_size(size: f64) -> String { let negative = if size.is_sign_positive() { "" } else { "-" }; let size = size.abs(); let units = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; if size < 1_f64 { return format!("{}{}{}", negative, size, "B"); } let delimiter = 1024_f64; let exponent = std::cmp::min( (size.ln() / delimiter.ln()).floor() as i32, (units.len() - 1) as i32, ); let pretty_bytes = format!("{:.2}", size / delimiter.powi(exponent)) .parse::<f64>() .unwrap() * 1_f64; let unit = units[exponent as usize]; format!("{}{}{}", negative, pretty_bytes, unit) } /// A function that converts a milisecond elapsed time to a string that /// represents a human readable version of that time. pub fn human_elapsed(elapsed: u128) -> String { if elapsed < 1_000 { return format!("{}ms", elapsed); } if elapsed < 1_000 * 60 { return format!("{}s", elapsed / 1000); } let seconds = elapsed / 1_000; let minutes = seconds / 60; let seconds_remainder = seconds % 60; format!("{}m{}s", minutes, seconds_remainder) } #[cfg(test)] mod tests { use super::*; #[test] fn test_human_size() { assert_eq!(human_size(1_f64), "1B"); assert_eq!(human_size((12 * 1024) as f64), "12KB"); assert_eq!(human_size((24_i64 * 1024 * 1024) as f64), "24MB"); assert_eq!(human_size((24_i64 * 1024 * 1024 * 1024) as f64), "24GB"); assert_eq!( human_size((24_i64 * 1024 * 1024 * 1024 * 1024) as f64), "24TB" ); } #[test] fn test_human_elapsed() { assert_eq!(human_elapsed(1), "1ms"); assert_eq!(human_elapsed(256), "256ms"); assert_eq!(human_elapsed(1000), "1s"); assert_eq!(human_elapsed(1001), "1s"); assert_eq!(human_elapsed(1020), "1s"); assert_eq!(human_elapsed(70 * 1000), "1m10s"); assert_eq!(human_elapsed(86 * 1000 + 100), "1m26s"); } }
30.411765
74
0.613153
4b03e1555f28edc7434e1b3cc23ca6c3db16f1c8
60
pub use generate::generate; mod generate; mod formatters;
10
27
0.766667
23993025b8877d62961cffd705ee29f678695635
4,539
//! Please see the [project README][1] for usage. //! //! [1]: https://github.com/osa1/lexgen mod ast; mod builtin; mod char_ranges; mod collections; mod dfa; mod display; mod nfa; mod nfa_to_dfa; mod range_map; mod regex_to_nfa; mod semantic_action_table; #[cfg(test)] mod tests; use ast::{Lexer, Regex, Rule, SingleRule, Var}; use collections::Map; use dfa::{StateIdx as DfaStateIdx, DFA}; use nfa::NFA; use nfa_to_dfa::nfa_to_dfa; use semantic_action_table::{SemanticActionIdx, SemanticActionTable}; use std::collections::hash_map::Entry; use proc_macro::TokenStream; use syn::parse::Parser; #[proc_macro] pub fn lexer(input: TokenStream) -> TokenStream { let mut semantic_action_table = SemanticActionTable::new(); let Lexer { public, type_name, user_state_type, token_type, rules: top_level_rules, } = match ast::make_lexer_parser(&mut semantic_action_table).parse(input) { Ok(lexer) => lexer, Err(error) => return TokenStream::from(error.to_compile_error()), }; // Maps DFA names to their initial states in the final DFA let mut dfas: Map<String, dfa::StateIdx> = Default::default(); let mut bindings: Map<Var, Regex> = Default::default(); let mut dfa: Option<DFA<DfaStateIdx, SemanticActionIdx>> = None; let mut user_error_type: Option<syn::Type> = None; let have_named_rules = top_level_rules .iter() .any(|rule| matches!(rule, Rule::RuleSet { .. })); for rule in top_level_rules { match rule { Rule::Binding { var, re } => match bindings.entry(var) { Entry::Occupied(entry) => { panic!("Variable {:?} is defined multiple times", entry.key().0); } Entry::Vacant(entry) => { entry.insert(re); } }, Rule::RuleSet { name, rules } => { if name == "Init" { let dfa = dfa.insert(compile_rules(rules, &bindings)); let initial_state = dfa.initial_state(); if dfas.insert(name.to_string(), initial_state).is_some() { panic!("Rule set {:?} is defined multiple times", name.to_string()); } } else { let dfa = dfa .as_mut() .expect("First rule set should be named \"Init\""); let dfa_ = compile_rules(rules, &bindings); let dfa_idx = dfa.add_dfa(dfa_); if dfas.insert(name.to_string(), dfa_idx).is_some() { panic!("Rule set {:?} is defined multiple times", name.to_string()); } } } Rule::UnnamedRules { rules } => { if dfa.is_some() || have_named_rules { panic!( "Unnamed rules cannot be mixed with named rules. Make sure to either \ have all your rules in `rule ... {} ... {}` syntax, or remove `rule`s \ entirely and have your rules at the top-level.", '{', '}', ); } let dfa = dfa.insert(compile_rules(rules, &bindings)); let initial_state = dfa.initial_state(); dfas.insert("Init".to_owned(), initial_state); } Rule::ErrorType { ty } => match user_error_type { None => { user_error_type = Some(ty); } Some(_) => panic!("Error type defined multiple times"), }, } } // There should be a rule with name "Init" if dfas.get("Init").is_none() { panic!( "There should be a rule set named \"Init\". Current rules: {:?}", dfas.keys().collect::<Vec<&String>>() ); } let dfa = dfa::simplify::simplify(dfa.unwrap(), &mut dfas); dfa::codegen::reify( dfa, semantic_action_table, user_state_type, user_error_type, dfas, type_name, token_type, public, ) .into() } fn compile_rules( rules: Vec<SingleRule>, bindings: &Map<Var, Regex>, ) -> DFA<DfaStateIdx, SemanticActionIdx> { let mut nfa: NFA<SemanticActionIdx> = NFA::new(); for SingleRule { lhs, rhs } in rules { nfa.add_regex(bindings, &lhs, rhs); } nfa_to_dfa(&nfa) }
30.26
95
0.530734
e62f74a861100b7ef534e3e730bd925ee91a9550
12,755
#![no_std] #![no_main] #![feature(lang_items, asm)] extern crate capsules; extern crate cc26x2; extern crate cortexm4; extern crate enum_primitive; #[allow(unused_imports)] use kernel::{create_capability, debug, debug_gpio, static_init}; use capsules::virtual_uart::{MuxUart, UartDevice}; use cc26x2::aon; use cc26x2::prcm; use cc26x2::pwm; use kernel::capabilities; use kernel::hil; use kernel::hil::entropy::Entropy32; use kernel::hil::gpio; use kernel::hil::i2c::I2CMaster; use kernel::hil::rng::Rng; #[macro_use] pub mod io; #[allow(dead_code)] mod ccfg_test; #[allow(dead_code)] mod i2c_tests; #[allow(dead_code)] mod uart_echo; // High frequency oscillator speed pub const HFREQ: u32 = 48 * 1_000_000; // How should the kernel respond when a process faults. const FAULT_RESPONSE: kernel::procs::FaultResponse = kernel::procs::FaultResponse::Panic; // Number of concurrent processes this platform supports. const NUM_PROCS: usize = 3; static mut PROCESSES: [Option<&'static kernel::procs::ProcessType>; NUM_PROCS] = [None, None, None]; #[link_section = ".app_memory"] // Give half of RAM to be dedicated APP memory static mut APP_MEMORY: [u8; 0x10000] = [0; 0x10000]; /// Dummy buffer that causes the linker to reserve enough space for the stack. #[no_mangle] #[link_section = ".stack_buffer"] pub static mut STACK_MEMORY: [u8; 0x1000] = [0; 0x1000]; pub struct Platform { gpio: &'static capsules::gpio::GPIO<'static>, led: &'static capsules::led::LED<'static>, console: &'static capsules::console::Console<'static>, button: &'static capsules::button::Button<'static>, alarm: &'static capsules::alarm::AlarmDriver< 'static, capsules::virtual_alarm::VirtualMuxAlarm<'static, cc26x2::rtc::Rtc>, >, rng: &'static capsules::rng::RngDriver<'static>, i2c_master: &'static capsules::i2c_master::I2CMasterDriver<cc26x2::i2c::I2CMaster<'static>>, ipc: kernel::ipc::IPC, } impl kernel::Platform for Platform { fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R where F: FnOnce(Option<&kernel::Driver>) -> R, { match driver_num { capsules::console::DRIVER_NUM => f(Some(self.console)), capsules::gpio::DRIVER_NUM => f(Some(self.gpio)), capsules::led::DRIVER_NUM => f(Some(self.led)), capsules::button::DRIVER_NUM => f(Some(self.button)), capsules::alarm::DRIVER_NUM => f(Some(self.alarm)), capsules::rng::DRIVER_NUM => f(Some(self.rng)), capsules::i2c_master::DRIVER_NUM => f(Some(self.i2c_master)), kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)), _ => f(None), } } } mod cc1312r; mod cc1352p; pub struct Pinmap { uart0_rx: usize, uart0_tx: usize, i2c0_scl: usize, i2c0_sda: usize, red_led: usize, green_led: usize, button1: usize, button2: usize, gpio0: usize, a0: usize, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize, a6: usize, a7: usize, pwm0: usize, pwm1: usize, } unsafe fn configure_pins(pin: &Pinmap) { cc26x2::gpio::PORT[pin.uart0_rx].enable_uart0_rx(); cc26x2::gpio::PORT[pin.uart0_tx].enable_uart0_tx(); cc26x2::gpio::PORT[pin.i2c0_scl].enable_i2c_scl(); cc26x2::gpio::PORT[pin.i2c0_sda].enable_i2c_sda(); cc26x2::gpio::PORT[pin.red_led].enable_gpio(); cc26x2::gpio::PORT[pin.green_led].enable_gpio(); cc26x2::gpio::PORT[pin.button1].enable_gpio(); cc26x2::gpio::PORT[pin.button2].enable_gpio(); cc26x2::gpio::PORT[pin.gpio0].enable_gpio(); cc26x2::gpio::PORT[pin.a7].enable_analog_input(); cc26x2::gpio::PORT[pin.a6].enable_analog_input(); cc26x2::gpio::PORT[pin.a5].enable_analog_input(); cc26x2::gpio::PORT[pin.a4].enable_analog_input(); cc26x2::gpio::PORT[pin.a3].enable_analog_input(); cc26x2::gpio::PORT[pin.a2].enable_analog_input(); cc26x2::gpio::PORT[pin.a1].enable_analog_input(); cc26x2::gpio::PORT[pin.a0].enable_analog_input(); cc26x2::gpio::PORT[pin.pwm0].enable_pwm(pwm::Timer::GPT0A); cc26x2::gpio::PORT[pin.pwm1].enable_pwm(pwm::Timer::GPT0B); } #[no_mangle] pub unsafe fn reset_handler() { cc26x2::init(); // Create capabilities that the board needs to call certain protected kernel // functions. let process_management_capability = create_capability!(capabilities::ProcessManagementCapability); let main_loop_capability = create_capability!(capabilities::MainLoopCapability); let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability); // Setup AON event defaults aon::AON.setup(); // Power on peripherals (eg. GPIO) prcm::Power::enable_domain(prcm::PowerDomain::Peripherals); // Wait for it to turn on until we continue while !prcm::Power::is_enabled(prcm::PowerDomain::Peripherals) {} // Power on Serial domain prcm::Power::enable_domain(prcm::PowerDomain::Serial); while !prcm::Power::is_enabled(prcm::PowerDomain::Serial) {} let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(&PROCESSES)); // Enable the GPIO clocks prcm::Clock::enable_gpio(); let pinmap: &Pinmap; let chip_id = (cc26x2::rom::HAPI.get_chip_id)(); if chip_id == cc1352p::CHIP_ID { pinmap = &cc1352p::PINMAP; } else { pinmap = &cc1312r::PINMAP; } configure_pins(pinmap); // LEDs let led_pins = static_init!( [( &'static kernel::hil::gpio::Pin, capsules::led::ActivationMode ); 2], [ ( &cc26x2::gpio::PORT[pinmap.red_led], capsules::led::ActivationMode::ActiveHigh ), // Red ( &cc26x2::gpio::PORT[pinmap.green_led], capsules::led::ActivationMode::ActiveHigh ), // Green ] ); let led = static_init!( capsules::led::LED<'static>, capsules::led::LED::new(led_pins) ); // BUTTONS let button_pins = static_init!( [(&'static gpio::InterruptValuePin, capsules::button::GpioMode); 2], [ ( static_init!( gpio::InterruptValueWrapper, gpio::InterruptValueWrapper::new(&cc26x2::gpio::PORT[pinmap.button1]) ) .finalize(), capsules::button::GpioMode::LowWhenPressed ), ( static_init!( gpio::InterruptValueWrapper, gpio::InterruptValueWrapper::new(&cc26x2::gpio::PORT[pinmap.button2]) ) .finalize(), capsules::button::GpioMode::LowWhenPressed ) ] ); let button = static_init!( capsules::button::Button<'static>, capsules::button::Button::new( button_pins, board_kernel.create_grant(&memory_allocation_capability) ) ); for (pin, _) in button_pins.iter() { pin.set_client(button); pin.set_floating_state(hil::gpio::FloatingState::PullUp); } // UART cc26x2::uart::UART0.initialize(); // Create a shared UART channel for the console and for kernel debug. let uart_mux = static_init!( MuxUart<'static>, MuxUart::new( &cc26x2::uart::UART0, &mut capsules::virtual_uart::RX_BUF, 115200 ) ); uart_mux.initialize(); hil::uart::Receive::set_receive_client(&cc26x2::uart::UART0, uart_mux); hil::uart::Transmit::set_transmit_client(&cc26x2::uart::UART0, uart_mux); // Create a UartDevice for the console. let console_uart = static_init!(UartDevice, UartDevice::new(uart_mux, true)); console_uart.setup(); let console = static_init!( capsules::console::Console<'static>, capsules::console::Console::new( console_uart, &mut capsules::console::WRITE_BUF, &mut capsules::console::READ_BUF, board_kernel.create_grant(&memory_allocation_capability) ) ); kernel::hil::uart::Transmit::set_transmit_client(console_uart, console); kernel::hil::uart::Receive::set_receive_client(console_uart, console); // Create virtual device for kernel debug. let debugger_uart = static_init!(UartDevice, UartDevice::new(uart_mux, false)); debugger_uart.setup(); let debugger = static_init!( kernel::debug::DebugWriter, kernel::debug::DebugWriter::new( debugger_uart, &mut kernel::debug::OUTPUT_BUF, &mut kernel::debug::INTERNAL_BUF, ) ); hil::uart::Transmit::set_transmit_client(debugger_uart, debugger); let debug_wrapper = static_init!( kernel::debug::DebugWriterWrapper, kernel::debug::DebugWriterWrapper::new(debugger) ); kernel::debug::set_debug_writer_wrapper(debug_wrapper); cc26x2::i2c::I2C0.initialize(); let i2c_master = static_init!( capsules::i2c_master::I2CMasterDriver<cc26x2::i2c::I2CMaster<'static>>, capsules::i2c_master::I2CMasterDriver::new( &cc26x2::i2c::I2C0, &mut capsules::i2c_master::BUF, board_kernel.create_grant(&memory_allocation_capability) ) ); cc26x2::i2c::I2C0.set_client(i2c_master); cc26x2::i2c::I2C0.enable(); // Setup for remaining GPIO pins let gpio_pins = static_init!( [&'static kernel::hil::gpio::InterruptValuePin; 1], [ // This is the order they appear on the launchxl headers. // Pins 5, 8, 11, 29, 30 static_init!( gpio::InterruptValueWrapper, gpio::InterruptValueWrapper::new(&cc26x2::gpio::PORT[pinmap.gpio0]) ) .finalize() ] ); let gpio = static_init!( capsules::gpio::GPIO<'static>, capsules::gpio::GPIO::new( gpio_pins, board_kernel.create_grant(&memory_allocation_capability) ) ); for pin in gpio_pins.iter() { pin.set_client(gpio); } let rtc = &cc26x2::rtc::RTC; rtc.start(); let mux_alarm = static_init!( capsules::virtual_alarm::MuxAlarm<'static, cc26x2::rtc::Rtc>, capsules::virtual_alarm::MuxAlarm::new(&cc26x2::rtc::RTC) ); rtc.set_client(mux_alarm); let virtual_alarm1 = static_init!( capsules::virtual_alarm::VirtualMuxAlarm<'static, cc26x2::rtc::Rtc>, capsules::virtual_alarm::VirtualMuxAlarm::new(mux_alarm) ); let alarm = static_init!( capsules::alarm::AlarmDriver< 'static, capsules::virtual_alarm::VirtualMuxAlarm<'static, cc26x2::rtc::Rtc>, >, capsules::alarm::AlarmDriver::new( virtual_alarm1, board_kernel.create_grant(&memory_allocation_capability) ) ); virtual_alarm1.set_client(alarm); let entropy_to_random = static_init!( capsules::rng::Entropy32ToRandom<'static>, capsules::rng::Entropy32ToRandom::new(&cc26x2::trng::TRNG) ); let rng = static_init!( capsules::rng::RngDriver<'static>, capsules::rng::RngDriver::new( entropy_to_random, board_kernel.create_grant(&memory_allocation_capability) ) ); cc26x2::trng::TRNG.set_client(entropy_to_random); entropy_to_random.set_client(rng); let pwm_channels = [ pwm::Signal::new(pwm::Timer::GPT0A), pwm::Signal::new(pwm::Timer::GPT0B), pwm::Signal::new(pwm::Timer::GPT1A), pwm::Signal::new(pwm::Timer::GPT1B), pwm::Signal::new(pwm::Timer::GPT2A), pwm::Signal::new(pwm::Timer::GPT2B), pwm::Signal::new(pwm::Timer::GPT3A), pwm::Signal::new(pwm::Timer::GPT3B), ]; // all PWM channels are enabled for pwm_channel in pwm_channels.iter() { pwm_channel.enable(); } let ipc = kernel::ipc::IPC::new(board_kernel, &memory_allocation_capability); let launchxl = Platform { console, gpio, led, button, alarm, rng, i2c_master, ipc, }; let chip = static_init!(cc26x2::chip::Cc26X2, cc26x2::chip::Cc26X2::new(HFREQ)); extern "C" { /// Beginning of the ROM region containing app images. static _sapps: u8; } kernel::procs::load_processes( board_kernel, chip, &_sapps as *const u8, &mut APP_MEMORY, &mut PROCESSES, FAULT_RESPONSE, &process_management_capability, ); board_kernel.kernel_loop(&launchxl, chip, Some(&launchxl.ipc), &main_loop_capability); }
30.73494
100
0.620149
9068d8cf35f46e8b904ea28afab62cff9206af9f
789
// https://leetcode.com/problems/find-pivot-index/ struct Solution; impl Solution { pub fn pivot_index(nums: Vec<i32>) -> i32 { if nums.is_empty() { return -1 } let mut left = 0; let mut right = nums.iter().sum::<i32>(); for i in 0..nums.len() { right -= nums[i]; if left == right { return i as i32 } left += nums[i]; } -1 } } #[cfg(test)] mod tests { use super::*; #[test] fn test_example1() { assert_eq!(Solution::pivot_index(vec![1, 7, 3, 6, 5, 6]), 3); } #[test] fn test_example2() { assert_eq!(Solution::pivot_index(vec![1, 2, 3]), -1); } #[test] fn test_example3() { assert_eq!(Solution::pivot_index(vec![1]), 0); } }
19.243902
69
0.498099
e9438da8e2a79fb3a57ddafdab3ecf249641a6a9
6,797
use pear::parsers::*; use pear::combinators::*; use pear::input::{self, Pear, Extent, Rewind, Input}; use pear::macros::{parser, switch, parse_error, parse_try}; use crate::uri::{Uri, Origin, Authority, Absolute, Reference, Asterisk}; use crate::parse::uri::tables::*; use crate::parse::uri::RawInput; type Result<'a, T> = pear::input::Result<T, RawInput<'a>>; // SAFETY: Every `unsafe` here comes from bytes -> &str conversions. Since all // bytes are checked against tables in `tables.rs`, all of which allow only // ASCII characters, these are all safe. // TODO: We should cap the source we pass into `raw` to the bytes we've actually // checked. Otherwise, we could have good bytes followed by unchecked bad bytes // since eof() may not called. However, note that we only actually expose these // parsers via `parse!()`, which _does_ call `eof()`, so we're externally okay. #[parser(rewind)] pub fn complete<I, P, O>(input: &mut Pear<I>, p: P) -> input::Result<O, I> where I: Input + Rewind, P: FnOnce(&mut Pear<I>) -> input::Result<O, I> { (p()?, eof()?).0 } /// TODO: Have a way to ask for for preference in ambiguity resolution. /// * An ordered [Preference] is probably best. /// * Need to filter/uniqueify. See `uri-pref`. /// Once we have this, we should probably set the default so that `authority` is /// preferred over `absolute`, otherwise something like `foo:3122` is absolute. #[parser] pub fn uri<'a>(input: &mut RawInput<'a>) -> Result<'a, Uri<'a>> { // To resolve all ambiguities with preference, we might need to look at the // complete string twice: origin/ref, asterisk/ref, authority/absolute. switch! { asterisk@complete(asterisk) => Uri::Asterisk(asterisk), origin@complete(origin) => Uri::Origin(origin), authority@complete(authority) => Uri::Authority(authority), absolute@complete(absolute) => Uri::Absolute(absolute), _ => Uri::Reference(reference()?) } } #[parser] pub fn asterisk<'a>(input: &mut RawInput<'a>) -> Result<'a, Asterisk> { eat(b'*')?; Asterisk } #[parser] pub fn origin<'a>(input: &mut RawInput<'a>) -> Result<'a, Origin<'a>> { let (_, path, query) = (peek(b'/')?, path()?, query()?); unsafe { Origin::raw(input.start.into(), path, query) } } #[parser] pub fn authority<'a>(input: &mut RawInput<'a>) -> Result<'a, Authority<'a>> { let prefix = take_while(is_reg_name_char)?; let (user_info, host, port) = switch! { peek(b'[') if prefix.is_empty() => (None, host()?, port()?), eat(b':') => { let suffix = take_while(is_reg_name_char)?; switch! { peek(b':') => { let end = (take_while(is_user_info_char)?, eat(b'@')?).0; (input.span(prefix, end), host()?, port()?) }, eat(b'@') => (input.span(prefix, suffix), host()?, port()?), // FIXME: Rewind to just after prefix to get the right context // to be able to call `port()`. Then remove `maybe_port()`. _ => (None, prefix, maybe_port(&suffix)?) } }, eat(b'@') => (Some(prefix), host()?, port()?), _ => (None, prefix, None), }; unsafe { Authority::raw(input.start.into(), user_info, host, port) } } #[parser] pub fn scheme<'a>(input: &mut RawInput<'a>) -> Result<'a, Extent<&'a [u8]>> { let scheme = take_some_while(is_scheme_char)?; if !scheme.get(0).map_or(false, |b| b.is_ascii_alphabetic()) { parse_error!("invalid scheme")?; } scheme } #[parser] pub fn absolute<'a>(input: &mut RawInput<'a>) -> Result<'a, Absolute<'a>> { let scheme = scheme()?; let (_, (authority, path), query) = (eat(b':')?, hier_part()?, query()?); unsafe { Absolute::raw(input.start.into(), scheme, authority, path, query) } } #[parser] pub fn reference<'a>( input: &mut RawInput<'a>, ) -> Result<'a, Reference<'a>> { let prefix = take_while(is_scheme_char)?; let (scheme, authority, path) = switch! { peek(b':') if prefix.is_empty() => parse_error!("missing scheme")?, eat(b':') => { if !prefix.get(0).map_or(false, |b| b.is_ascii_alphabetic()) { parse_error!("invalid scheme")?; } let (authority, path) = hier_part()?; (Some(prefix), authority, path) }, peek_slice(b"//") if prefix.is_empty() => { let (authority, path) = hier_part()?; (None, authority, path) }, _ => { let path = path()?; let full_path = input.span(prefix, path).unwrap_or(none()?); (None, None, full_path) }, }; let (source, query, fragment) = (input.start.into(), query()?, fragment()?); unsafe { Reference::raw(source, scheme, authority, path, query, fragment) } } #[parser] pub fn hier_part<'a>( input: &mut RawInput<'a> ) -> Result<'a, (Option<Authority<'a>>, Extent<&'a [u8]>)> { switch! { eat_slice(b"//") => { let authority = authority()?; let path = parse_try!(peek(b'/') => path()? => || none()?); (Some(authority), path) }, _ => (None, path()?) } } #[parser] fn host<'a>( input: &mut RawInput<'a>, ) -> Result<'a, Extent<&'a [u8]>> { switch! { peek(b'[') => enclosed(b'[', is_host_char, b']')?, _ => take_while(is_reg_name_char)? } } #[parser] fn port<'a>( input: &mut RawInput<'a>, ) -> Result<'a, Option<u16>> { if !succeeds(input, |i| eat(i, b':')) { return Ok(None); } let bytes = take_n_while(5, |c| c.is_ascii_digit())?; maybe_port(&bytes)? } // FIXME: The context here is wrong since it's empty. We should reset to // current - bytes.len(). Or something like that. #[parser] fn maybe_port<'a>(input: &mut RawInput<'a>, bytes: &[u8]) -> Result<'a, Option<u16>> { if bytes.len() > 5 { parse_error!("port len is out of range")?; } else if !bytes.iter().all(|b| b.is_ascii_digit()) { parse_error!("invalid port bytes")?; } let mut port_num: u32 = 0; for (b, i) in bytes.iter().rev().zip(&[1, 10, 100, 1000, 10000]) { port_num += (b - b'0') as u32 * i; } if port_num > u16::max_value() as u32 { parse_error!("port out of range: {}", port_num)?; } Some(port_num as u16) } #[parser] fn path<'a>(input: &mut RawInput<'a>) -> Result<'a, Extent<&'a [u8]>> { take_while(is_pchar)? } #[parser] fn query<'a>(input: &mut RawInput<'a>) -> Result<'a, Option<Extent<&'a [u8]>>> { parse_try!(eat(b'?') => take_while(is_qchar)?) } #[parser] fn fragment<'a>(input: &mut RawInput<'a>) -> Result<'a, Option<Extent<&'a [u8]>>> { parse_try!(eat(b'#') => take_while(is_qchar)?) }
33.648515
86
0.57187
16234feb778aebe6dd27564fa7da82fae24c55e3
16,287
use std::ops::Range; use regex_syntax::Parser; use anyhow::{bail, Result}; use crate::regex::NFA; fn regex_to_nfa<A: std::hash::Hash + Eq + Copy + std::fmt::Debug>(regex: &str) -> Result<NFA<A>> { let hir = Parser::new().parse(regex)?; hir_to_nfa(&hir) } fn repeated_n_times<A>(mut nfa: NFA<A>, n: u32) -> anyhow::Result<NFA<A>> where A: std::hash::Hash + Eq + Copy + std::fmt::Debug, { let mut result = NFA::<A>::empty(); let mut accounted = 0_u32; for bit_index in 0..=31 { if accounted == n { break; } if n & (1 << bit_index) != 0 { println!("bit_index match {}", bit_index); result.followed_by(nfa.clone())?; accounted |= 1 << bit_index; } // Double nfa in size nfa.followed_by(nfa.clone())?; } Ok(result) } fn hir_to_nfa<A: std::hash::Hash + Eq + Copy + std::fmt::Debug>( hir: &regex_syntax::hir::Hir, ) -> Result<NFA<A>> { match hir.kind() { regex_syntax::hir::HirKind::Empty => Ok(NFA::literal("")), regex_syntax::hir::HirKind::Literal(lit) => match lit { regex_syntax::hir::Literal::Unicode(uni) => Ok(NFA::literal(&uni.to_string())), regex_syntax::hir::Literal::Byte(byte) => Ok(NFA::literal(&byte.to_string())), }, regex_syntax::hir::HirKind::Class(class) => { match class { regex_syntax::hir::Class::Unicode(uni) => { let mut nfa = NFA::<A>::empty(); for range in uni.ranges() { nfa = nfa.or(NFA::<A>::from(range))?; } Ok(nfa) } regex_syntax::hir::Class::Bytes(byte) => { let mut nfa = NFA::empty(); for range in byte.iter() { //Todo check that range is inclusive nfa = nfa.or(NFA::from(Range { start: range.start(), end: range.end(), }))?; } Ok(nfa) } } } regex_syntax::hir::HirKind::Anchor(x) => match x { regex_syntax::hir::Anchor::StartLine => bail!("We dont suport StartLine symbols!"), regex_syntax::hir::Anchor::EndLine => bail!("We dont suport EndLine symbols!"), regex_syntax::hir::Anchor::StartText => bail!("We dont suport StartText symbol!"), regex_syntax::hir::Anchor::EndText => bail!("We dont suport EndText symbol!"), }, regex_syntax::hir::HirKind::WordBoundary(boundary) => { match boundary { regex_syntax::hir::WordBoundary::Unicode => { todo!() // I dont know if we need to suport this } regex_syntax::hir::WordBoundary::UnicodeNegate => { todo!() // I dont know if we need to suport this } regex_syntax::hir::WordBoundary::Ascii => { todo!() // I dont know if we need to suport this } regex_syntax::hir::WordBoundary::AsciiNegate => { todo!() // I dont know if we need to suport this } } } regex_syntax::hir::HirKind::Repetition(x) => { match &x.kind { regex_syntax::hir::RepetitionKind::ZeroOrOne => { let nfa = NFA::<A>::empty(); nfa.or(hir_to_nfa(&x.hir)?) } regex_syntax::hir::RepetitionKind::ZeroOrMore => hir_to_nfa(&x.hir)?.repeat(), regex_syntax::hir::RepetitionKind::OneOrMore => { let nfa = hir_to_nfa(&x.hir)?; let mut fst = nfa.clone(); fst.followed_by(nfa.repeat()?)?; Ok(fst) } regex_syntax::hir::RepetitionKind::Range(range) => match range { // We dont care about greedy vs lazy ranges, since we only use the regex to detect // fullmatch, and dont care about matchgroups. regex_syntax::hir::RepetitionRange::Exactly(exact) => { println!("Exact branch"); let nfa = hir_to_nfa(&x.hir)?; repeated_n_times(nfa, *exact) } regex_syntax::hir::RepetitionRange::AtLeast(exact) => { println!("AT LEAST BRANCH"); let nfa = hir_to_nfa(&x.hir)?; let mut result = repeated_n_times(nfa.clone(), *exact)?; result.followed_by(nfa.repeat()?)?; Ok(result) } regex_syntax::hir::RepetitionRange::Bounded(n, m) => { let mut result = NFA::empty(); let org = hir_to_nfa(&x.hir)?; let mut nfa = repeated_n_times::<A>(org.clone(), *n)?; for _ in *n..=*m { result = result.or(nfa.clone())?; nfa.followed_by(org.clone())?; } Ok(result) } }, } } regex_syntax::hir::HirKind::Group(group) => match &group.kind { regex_syntax::hir::GroupKind::CaptureIndex(_) => hir_to_nfa(&group.hir), regex_syntax::hir::GroupKind::NonCapturing => hir_to_nfa(&group.hir), regex_syntax::hir::GroupKind::CaptureName { name: _, index: _ } => { hir_to_nfa(&group.hir) } }, regex_syntax::hir::HirKind::Concat(cats) => { let mut nfas = cats.iter().map(|hir| hir_to_nfa(hir)); let mut fst = nfas.next().unwrap()?; for nfa in nfas { fst.followed_by(nfa?)?; } Ok(fst) } regex_syntax::hir::HirKind::Alternation(alts) => { let mut nfas = alts.iter().map(|hir| hir_to_nfa(hir)); let mut fst = nfas.next().unwrap()?; for nfa in nfas { fst = fst.or(nfa?)?; } Ok(fst) } } } pub enum RegexConvertError { StartLine, EndLine, StartText, EndText, WordBoundaryUnicode, WordBoundaryUnicodeNegate, WordBoundaryAscii, WordBoundaryAsciiNegate, RegexParseError(regex_syntax::Error), } impl std::fmt::Debug for RegexConvertError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self { RegexConvertError::StartLine => { write!(f,"We don't suprt start line in regex, so ^ is not allowed in the regex without escaping it with \\.") } RegexConvertError::EndLine => { write!(f,"We don't suport end line in regex, so $ is not allowed in the regex without escaping it with \\.") } RegexConvertError::StartText => { write!(f,"We don't suport start text symbol in regex, so \\A is not allowed in the regex.") } RegexConvertError::EndText => { write!(f,"We don't suport end of text symbol in regex, so \\z is not allowed in the regex.") } RegexConvertError::WordBoundaryUnicode => { write!( f, "We don't suport unicode world boundary, so \\b is not allowed in the regex." ) } RegexConvertError::WordBoundaryUnicodeNegate => { write!(f,"We don't suport \"not a unicode world boundary\", so \\B is not allowed in the regex.") } RegexConvertError::WordBoundaryAscii => { write!(f,"We don't suport \"not a unicode world boundary\", so (?-u:\\b) is not allowed in the regex.") } RegexConvertError::WordBoundaryAsciiNegate => { write!(f,"We don't suport \"not a unicode world boundary\", so (?-u:\\B) is not allowed in the regex.") } RegexConvertError::RegexParseError(err) => err.fmt(f), } } } /// Checks if regex contains a feature we don't suport, or it just cant be parsed as /// valid regex. If this test passes for a command, then the only other failurecase for /// creating a nfa is running out of StateId: u32. pub fn we_suport_regex(regex: &str) -> Result<(), RegexConvertError> { let hir = Parser::new().parse(regex); let hir = match hir { Ok(x) => x, Err(e) => return Err(RegexConvertError::RegexParseError(e)), }; we_suport_hir(&hir) } /// Returns wheter or not we are able to parse regex. We dont suport certain features. fn we_suport_hir(hir: &regex_syntax::hir::Hir) -> Result<(), RegexConvertError> { match hir.kind() { regex_syntax::hir::HirKind::Empty => Ok(()), regex_syntax::hir::HirKind::Literal(lit) => match lit { regex_syntax::hir::Literal::Unicode(_) => Ok(()), regex_syntax::hir::Literal::Byte(_) => Ok(()), }, regex_syntax::hir::HirKind::Class(class) => match class { regex_syntax::hir::Class::Unicode(_) => Ok(()), regex_syntax::hir::Class::Bytes(_) => Ok(()), }, regex_syntax::hir::HirKind::Anchor(x) => match x { regex_syntax::hir::Anchor::StartLine => Err(RegexConvertError::StartLine), regex_syntax::hir::Anchor::EndLine => Err(RegexConvertError::EndLine), regex_syntax::hir::Anchor::StartText => Err(RegexConvertError::StartText), regex_syntax::hir::Anchor::EndText => Err(RegexConvertError::EndText), }, regex_syntax::hir::HirKind::WordBoundary(boundary) => match boundary { regex_syntax::hir::WordBoundary::Unicode => Err(RegexConvertError::WordBoundaryUnicode), regex_syntax::hir::WordBoundary::UnicodeNegate => { Err(RegexConvertError::WordBoundaryUnicodeNegate) } regex_syntax::hir::WordBoundary::Ascii => Err(RegexConvertError::WordBoundaryAscii), regex_syntax::hir::WordBoundary::AsciiNegate => { Err(RegexConvertError::WordBoundaryAsciiNegate) } }, regex_syntax::hir::HirKind::Repetition(x) => { match &x.kind { regex_syntax::hir::RepetitionKind::ZeroOrOne => Ok(()), regex_syntax::hir::RepetitionKind::ZeroOrMore => Ok(()), regex_syntax::hir::RepetitionKind::OneOrMore => Ok(()), regex_syntax::hir::RepetitionKind::Range(range) => match range { // We dont care about greedy vs lazy ranges, since we only use the regex to detect // fullmatch, and dont care about matchgroups. regex_syntax::hir::RepetitionRange::Exactly(_) => Ok(()), regex_syntax::hir::RepetitionRange::AtLeast(_) => Ok(()), regex_syntax::hir::RepetitionRange::Bounded(_, _) => Ok(()), }, } } regex_syntax::hir::HirKind::Group(group) => match &group.kind { regex_syntax::hir::GroupKind::CaptureIndex(_) | regex_syntax::hir::GroupKind::NonCapturing | regex_syntax::hir::GroupKind::CaptureName { name: _, index: _ } => Ok(()), }, regex_syntax::hir::HirKind::Concat(cats) => { for meow in cats { if let Err(x) = we_suport_hir(meow) { return Err(x); } } Ok(()) } regex_syntax::hir::HirKind::Alternation(alts) => { for alt in alts { if let Err(x) = we_suport_hir(alt) { return Err(x); } } Ok(()) } } } impl<A: std::hash::Hash + Eq + Copy + std::fmt::Debug> NFA<A> { pub fn regex(string: &str) -> anyhow::Result<NFA<A>> { regex_to_nfa(string) } } #[cfg(test)] mod tests { use super::*; use crate::regex::dfa::DFA; #[test] fn test_we_dont_suport() { let regex = "^"; assert!(we_suport_regex(regex).is_err()); let regex = "$"; assert!(we_suport_regex(regex).is_err()); let regex = "\\A"; assert!(we_suport_regex(regex).is_err()); let regex = "\\z"; assert!(we_suport_regex(regex).is_err()); let regex = "\\b"; assert!(we_suport_regex(regex).is_err()); } #[test] fn simple1() { let nfa = NFA::<usize>::regex("fu.*").unwrap(); let dfa = DFA::<usize>::from(nfa); for case in &["funN", "fu.\"", "fu,-", "fu{:", "fut!"] { assert!(dfa.find(case).is_ok()); } } #[test] fn simple2() { let nfa = NFA::<usize>::regex("fu..*").unwrap(); let dfa = DFA::<usize>::from(nfa); for case in &["funN", "fu.\"", "fu,-", "fu{:", "fut!"] { assert!(dfa.find(case).is_ok()); } for case in &["fu"] { assert!(dfa.find(case).is_err()); } } #[test] fn digit() { let nfa = NFA::<usize>::regex("\\d").unwrap(); let dfa = DFA::<usize>::from(nfa); for case in &["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] { assert!(dfa.find(case).is_ok()); } for case in &["a"] { assert!(dfa.find(case).is_err()); } } #[test] fn not_digit() { let nfa = NFA::<usize>::regex("\\D").unwrap(); let dfa = DFA::<usize>::from(nfa); for case in &["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] { assert!(dfa.find(case).is_err()); } for case in &["a", "q"] { assert!(dfa.find(case).is_ok()); } } #[test] fn direct_sibtraction() { let nfa = NFA::<usize>::regex("[0-9--4]").unwrap(); let dfa = DFA::<usize>::from(nfa); for case in &["1", "2", "3", "5", "6", "7", "8", "9", "0"] { assert!(dfa.find(case).is_ok()); } for case in &["4", "a"] { assert!(dfa.find(case).is_err()); } } #[test] fn repetitions_exact() { let regex = "a{5}"; let nfa = NFA::<usize>::regex(regex).unwrap(); let dfa: DFA<usize> = nfa.into(); //println!("{:?}",dfa); assert!(dfa.find("aaaaa").is_ok()); assert!(dfa.find("aaaa").is_err()); assert!(dfa.find("aaaaaa").is_err()); assert!(dfa.find("").is_err()); } #[test] fn repetitions_at_least() { let regex = "a{5,}"; let nfa = NFA::<usize>::regex(regex).unwrap(); let dfa: DFA<usize> = nfa.into(); assert!(dfa.find("aaaaa").is_ok()); assert!(dfa.find("aaaa").is_err()); assert!(dfa.find("aaaaaa").is_ok()); assert!(dfa.find("").is_err()); } #[test] fn repetitions_between() { let regex = "a{5,8}"; let nfa = NFA::<usize>::regex(regex).unwrap(); let dfa: DFA<usize> = nfa.into(); assert!(dfa.find("aaaaa").is_ok()); assert!(dfa.find("aaaa").is_err()); assert!(dfa.find("aaaaaa").is_ok()); assert!(dfa.find("aaaaaaa").is_ok()); assert!(dfa.find("aaaaaaaa").is_ok()); assert!(dfa.find("aaaaaaaaa").is_err()); assert!(dfa.find("").is_err()); } #[test] fn repetition() { let mut nfa = NFA::<usize>::regex("ho").unwrap(); nfa = nfa.repeat().unwrap(); let dfa: DFA<usize> = nfa.into(); assert!(dfa.find("").is_ok()); assert!(dfa.find("ho").is_ok()); assert!(dfa.find("hoho").is_ok()); assert!(dfa.find("h").is_err()); } #[test] fn repetition_lazy() { let nfa = NFA::<usize>::regex("a{3,5}?").unwrap(); let dfa: DFA<usize> = nfa.into(); assert!(dfa.find("aaa").is_ok()); assert!(dfa.find("aaaa").is_ok()); assert!(dfa.find("aaaaa").is_ok()); assert!(dfa.find("").is_err()); } }
36.931973
125
0.496592
ef4d882daf13d1eb72e294eede4c6111f5dc102c
8,359
//! Handles interfacing with the database. use chrono::Utc; use rocket::{ request::{self, FromRequest, Request}, Outcome, Rocket, }; use rocket_contrib::{ database, databases::mongodb::{ self, bson, coll::{ options::{FindOneAndUpdateOptions, FindOptions}, results::InsertOneResult, Collection, }, db::ThreadedDatabase, doc, oid::ObjectId, to_bson, Bson, Client, Document, ThreadedClient, }, }; use crate::{ configuration::INITIALIZE_DB, facilities::{IDPair, MinimalFacilityData}, }; /// Initializes the database. /// /// This sets up needed invariants in the database, such as indices. pub fn init(rocket: &mut Rocket) { let connection_info = rocket .config() .get_table("databases") .expect("No database configured. Please check out the README.md for information on how to fix this.") .get("sanitary_facilities") .expect("No database configured. Please check out the README.md for information on how to fix this.") .get("url") .expect("No database configured. Please check out the README.md for information on how to fix this.") .as_str() .expect("Invalid database connection string."); let client = Client::with_uri(connection_info).expect("Database connection could not be established."); let facilities_collection = client .db(&*crate::configuration::DATABASE_NAME) .collection(&*crate::configuration::FACILITIES_COLLECTION_NAME); if *INITIALIZE_DB > 0 { // Set up an index for the locations in the `facilities` collection. facilities_collection .create_index(doc! { "geometry": "2dsphere" }, None) .expect("Could not create a required index in the database."); } } /// Specifies the database connection type. /// /// Using this type as a rocket request guard, allows for use of /// database connections in handlers. #[database("sanitary_facilities")] pub struct DatabaseConnection(mongodb::db::Database); /// A request guard for the facilities collection. /// /// This is a short hand for retrieving a database connection and then /// getting the collection from that. pub struct FacilityCollection(mongodb::coll::Collection); impl<'a, 'r> FromRequest<'a, 'r> for FacilityCollection { type Error = (); fn from_request(request: &'a Request<'r>) -> request::Outcome<FacilityCollection, ()> { let database_connection = DatabaseConnection::from_request(request)?; Outcome::Success(FacilityCollection( database_connection .client .db(&crate::configuration::DATABASE_NAME) .collection(&crate::configuration::FACILITIES_COLLECTION_NAME), )) } } impl FacilityCollection { /// Performs the given query on the facility collection returning all results in json. pub fn perform_json_query( &self, filter: Option<Document>, ) -> mongodb::Result<impl Iterator<Item = serde_json::Value>> { perform_json_query(&self.0, filter, None).map(|values| { values.map(|mut val| { if let Some(obj) = val.as_object_mut() { // return `{ "properties": { "_id": <id> } }` instead of `{ "_id": { "$oid": <id> } }`, just like in the accessibility cloud API let id = obj .remove("_id") .expect("MongoDB document doesn't contain `_id`."); obj.entry("properties") .or_insert_with(|| serde_json::json!({}))["_id"] = id["$oid"].clone(); let mut filter_flagged_content = |content: &str| { if let Some(nested_property) = obj .get_mut("properties") .and_then(|props| props.as_object_mut()) .and_then(|props_obj| props_obj.get_mut(content)) .and_then(|images| images.as_array_mut()) { *nested_property = nested_property .drain(..) .filter(|prop| { prop.as_object() .and_then(|prop_obj| prop_obj.get("flagged")) .and_then(|flagged| flagged.as_bool()) != Some(true) }) .collect(); } }; filter_flagged_content("images"); filter_flagged_content("comments"); } val }) }) } /// Performs the given query and returns the data without modifications. /// /// Note that this should not be used for client-facing data. pub fn find_raw( &self, filter: Option<Document>, ) -> mongodb::Result<impl Iterator<Item = serde_json::Value>> { perform_json_query(&self.0, filter, None) } /// Returns a facility by ID. pub fn by_id(&self, id: IDPair) -> mongodb::Result<Option<serde_json::Value>> { self.find_raw(Some(doc! { "properties.sourceId": id.sourceId, "properties.originalId": id.originalId, })) .map(|mut iter| iter.next()) } /// Finds the first facility that matches and updates it according to the update document. pub fn find_one_and_update( &self, filter: Document, mut update: Document, upsert_data: Option<MinimalFacilityData>, ) -> mongodb::Result<Option<Document>> { let upsert = upsert_data.is_some(); if let Some(facility_info) = upsert_data { let old_document = update.insert( "$setOnInsert", doc! { "type": "Feature", "geometry.type": "Point", "geometry.coordinates": [facility_info.lon, facility_info.lat], "properties.category": "toilets" }, ); assert!(old_document.is_none()); } if let Some(set_doc) = update.get_mut("$set").and_then(|doc| match doc { Bson::Document(set_doc) => Some(set_doc), _ => None, }) { set_doc.insert("lastUpdated", Utc::now().to_string()); } else { update.insert("$set", doc! { "lastUpdated": Utc::now().to_string() }); } find_one_and_update(&self.0, filter, update, upsert) } /// Inserts a new facility into the collection. pub fn insert(&self, mut doc: Document) -> mongodb::Result<InsertOneResult> { let id = ObjectId::new()?; let id_str = id.to_string(); doc.insert("_id", id); doc.insert("type", "Feature"); doc.insert("lastUpdated", Utc::now().to_string()); if doc.get_document("properties").is_err() { doc.insert("properties", doc! {}); } let props = match doc.get_mut("properties").unwrap() { Bson::Document(doc) => doc, _ => unreachable!(), }; props.insert("sourceId", &*crate::configuration::SOURCE_ID); props.insert("originalId", id_str); props.insert("category", "toilets"); self.0.insert_one(doc, None) } } /// Performs the given query on the given collection returning all results in json. fn perform_json_query( collection: &Collection, filter: Option<Document>, options: Option<FindOptions>, ) -> mongodb::Result<impl Iterator<Item = serde_json::Value>> { Ok(collection .find(filter, options)? .filter_map(|val| val.ok()) .filter_map(|val| to_bson(&val).ok()) .map(|val| val.into())) } /// Finds the first element that matches and updates it according to the update document. fn find_one_and_update( collection: &Collection, filter: Document, update: Document, upsert: bool, ) -> mongodb::Result<Option<Document>> { let mut options = FindOneAndUpdateOptions::new(); options.upsert = Some(upsert); collection.find_one_and_update(filter, update, Some(options)) }
35.270042
148
0.565857
16e7c0b03979ff41d6db86668d6809d5822d81c5
667
use elasticsearch::cat::CatTemplatesParts; pub(crate) const SUBSYSTEM: &'static str = "cat_templates"; async fn metrics(exporter: &Exporter) -> Result<Vec<Metrics>, elasticsearch::Error> { let response = exporter .client() .cat() .templates(CatTemplatesParts::Name("*")) .format("json") .h(&["*"]) // Return local information, do not retrieve the state from master node (default: false) .local(true) .request_timeout(exporter.options().timeout_for_subsystem(SUBSYSTEM)) .send() .await?; Ok(metric::from_values(response.json::<Vec<Value>>().await?)) } crate::poll_metrics!();
30.318182
96
0.631184
1a35ad37a5b76332ac4ed13a91c829743280c4cd
5,730
// Copyright 2020 Andrej Shadura. // 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 bsd-pidfile-rs project, available at // https://github.com/andrewshadura/bsd-pidfile-rs. It was incorporated // directly into Materialize on August 12, 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. //! PID file management for daemons. //! //! The `pid-file` crate wraps the `pidfile` family of functions provided by BSD //! systems that provide mutual exclusion for daemons via PID files. //! //! Much of the code is inherited from [pidfile_rs], but the build system //! bundles the necessary subset of libbsd rather than relying on libbsd to be //! installed. //! //! [pidfile_rs]: https://docs.rs/pidfile_rs #![warn(missing_docs)] use std::ffi::{CString, NulError}; use std::fmt; use std::fs::Permissions; use std::io; use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::PermissionsExt; use std::path::Path; use std::ptr; use mz_ore::option::OptionExt; #[allow(non_camel_case_types)] #[repr(C)] struct pidfh { private: [u8; 0], } extern "C" { fn pidfile_open( path: *const libc::c_char, mode: libc::mode_t, pid: *const libc::pid_t, ) -> *mut pidfh; fn pidfile_write(pfh: *mut pidfh) -> libc::c_int; fn pidfile_remove(pfh: *mut pidfh) -> libc::c_int; } /// An open PID file. /// /// A process that manages to construct this type holds an exclusive lock on the /// PID file. /// /// Dropping the type will attempt to call [`remove`](PidFile::remove), but any /// errors will be suppressed. Call `remove` manually if you need to handle PID /// file removal errors. pub struct PidFile(*mut pidfh); impl PidFile { /// Attempts to open and lock the specified PID file. /// /// If the file is already locked by another process, it returns /// `Error::AlreadyRunning`. pub fn open<P>(path: P) -> Result<PidFile, Error> where P: AsRef<Path>, { PidFile::open_with(path, Permissions::from_mode(0o600)) } /// Like [`open`](PidFile::open), but opens the file with the specified /// permissions rather than 0600. #[allow(clippy::unnecessary_mut_passed)] // this mut is being passed as a mut pointer pub fn open_with<P>(path: P, permissions: Permissions) -> Result<PidFile, Error> where P: AsRef<Path>, { let path_cstring = CString::new(path.as_ref().as_os_str().as_bytes())?; let mut old_pid: libc::pid_t = -1; #[allow(clippy::useless_conversion)] // the types differ on macos/linux let mode: libc::mode_t = permissions .mode() .try_into() .expect("file permissions not valid libc::mode_t"); let f = unsafe { pidfile_open(path_cstring.as_ptr(), mode, &mut old_pid) }; if !f.is_null() { let r = unsafe { pidfile_write(f) }; if r == 0 { Ok(PidFile(f)) } else { Err(Error::Io(io::Error::last_os_error())) } } else { let err = io::Error::last_os_error(); if err.kind() == io::ErrorKind::AlreadyExists { Err(Error::AlreadyRunning { pid: (old_pid != -1).then(|| old_pid), }) } else { Err(Error::Io(err)) } } } /// Closes the PID file and removes it from the filesystem. pub fn remove(mut self) -> Result<(), Error> { let r = unsafe { pidfile_remove(self.0) }; // Set the pointer to null to prevent drop from calling remove again. self.0 = ptr::null_mut(); if r == 0 { Ok(()) } else { Err(Error::Io(io::Error::last_os_error())) } } } impl Drop for PidFile { fn drop(&mut self) { // If the pointer is null, the PID file has already been removed. if self.0 != ptr::null_mut() { unsafe { pidfile_remove(self.0) }; } } } /// A PID file-related error. #[derive(Debug)] pub enum Error { /// An I/O error occurred. Io(io::Error), /// The provided path had embedded null bytes. Nul(NulError), /// Another process already has the lock on the requested PID file. AlreadyRunning { /// The PID of the existing process, if it is known. pid: Option<i32>, }, } impl From<NulError> for Error { fn from(e: NulError) -> Error { Error::Nul(e) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::Io(e) => write!(f, "unable to open PID file: {}", e), Error::Nul(e) => write!(f, "PID file path contained null bytes: {}", e), Error::AlreadyRunning { pid } => write!( f, "process already running (PID: {})", pid.display_or("<unknown>") ), } } } impl std::error::Error for Error {}
32.191011
89
0.607679
fed71e948eb3346f487434939eae07d441fedbb9
3,941
use super::{ApiLinks, ApiMeta}; use super::{HasPagination, HasResponse, HasValue}; use chrono::{DateTime, Utc}; use method::{Get, List}; use request::ActionRequest; use request::Request; use url::Url; use {ROOT_URL, STATIC_URL_ERROR}; const ACTIONS_SEGMENT: &'static str = "actions"; /// Actions are records of events that have occurred on the resources in your /// account. These can be things like rebooting a Droplet, or transferring an /// image to a new region. /// /// An action object is created every time one of these actions is initiated. /// The action object contains information about the current status of the /// action, start and complete timestamps, and the associated resource type /// and ID. /// /// Every action that creates an action object is available through this /// endpoint. Completed actions are not removed from this list and are always /// available for querying. /// /// [Digital Ocean Documentation.](https://developers.digitalocean.com/documentation/v2/#actions) #[derive(Deserialize, Serialize, Debug, Clone, Getters, Setters)] pub struct Action { /// A unique identifier for each Droplet action event. This is used to /// reference a specific action that was requested. #[get = "pub"] id: usize, /// The current status of the action. The value of this attribute will be /// "in-progress", "completed", or "errored". #[get = "pub"] status: String, /// The type of action that the event is executing (reboot, power_off, /// etc.). #[get = "pub"] started_at: DateTime<Utc>, /// A time value given in ISO8601 combined date and time format that /// represents when the action was completed. #[get = "pub"] completed_at: Option<DateTime<Utc>>, /// A unique identifier for the resource that the action is associated /// with. #[get = "pub"] resource_id: usize, /// The type of resource that the action is associated with. #[get = "pub"] resource_type: String, // /// (deprecated) A slug representing the region where the action occurred. // #[get = "pub"] // #[deprecated(since = "0.0.1", note = "DigitalOcean has deprecated this.")] // region: Option<Region>, /// A slug representing the region where the action occurred. #[get = "pub"] region_slug: Option<String>, } impl Action { /// [Digital Ocean Documentation.](https://developers.digitalocean.com/documentation/v2/#retrieve-an-existing-action) pub fn get(id: usize) -> ActionRequest<Get, Action> { let mut url = ROOT_URL.clone(); url.path_segments_mut() .expect(STATIC_URL_ERROR) .push(ACTIONS_SEGMENT) .push(&id.to_string()); Request::new(url) } /// [Digital Ocean Documentation.](https://developers.digitalocean.com/documentation/v2/#list-all-actions) pub fn list() -> ActionRequest<List, Vec<Action>> { let mut url = ROOT_URL.clone(); url.path_segments_mut() .expect(STATIC_URL_ERROR) .push(ACTIONS_SEGMENT); Request::new(url) } } /// Response type returned from Digital Ocean. #[derive(Deserialize, Serialize, Debug, Clone)] pub struct ActionResponse { action: Action, } impl HasValue for ActionResponse { type Value = Action; fn value(self) -> Action { self.action } } impl HasResponse for Action { type Response = ActionResponse; } /// Response type returned from Digital Ocean. #[derive(Deserialize, Serialize, Debug, Clone)] pub struct ActionListResponse { actions: Vec<Action>, links: ApiLinks, meta: ApiMeta, } impl HasResponse for Vec<Action> { type Response = ActionListResponse; } impl HasPagination for ActionListResponse { fn next_page(&self) -> Option<Url> { self.links.next() } } impl HasValue for ActionListResponse { type Value = Vec<Action>; fn value(self) -> Vec<Action> { self.actions } }
32.04065
121
0.670134
fe1b7c9ad7f2eb749894e58d5fef21d9a0a25d7e
28,430
use crate::*; pub use bessel_internal::*; mod bessel_internal { use crate::*; #[inline(always)] pub fn bessel_j0<S: Simd, E: SimdVectorizedSpecialFunctionsInternal<S>, P: Policy>(mut x: E::Vf) -> E::Vf { /* if P::POLICY.precision == PrecisionPolicy::Reference { let xx4 = x * x * E::Vf::splat_as(0.25); let mut powers = E::Vf::one(); let mut factorial = E::cast_from(1.0); let sum = E::Vf::summation_f_p::<P, _>(1, isize::MAX, |k| { let sign = if k & 1 == 0 { E::Vf::zero() } else { E::Vf::neg_zero() }; factorial = factorial * E::cast_from(k); powers = powers * xx4; let f = E::Vf::splat(factorial); sign ^ powers / f / f }); return match sum { Ok(sum) => sum + E::Vf::one(), Err(_) => E::Vf::zero(), }; } */ let x1 = E::Vf::splat_as(2.4048255576957727686e+00); let x2 = E::Vf::splat_as(5.5200781102863106496e+00); let x11 = E::Vf::splat_as(6.160e+02); let x12 = E::Vf::splat_as(-1.42444230422723137837e-03); let x21 = E::Vf::splat_as(1.4130e+03); let x22 = E::Vf::splat_as(5.46860286310649596604e-04); let den = E::Vf::splat_as(-1.0 / 256.0); let p1 = &[ E::cast_from(-4.1298668500990866786e+11f64), E::cast_from(2.7282507878605942706e+10f64), E::cast_from(-6.2140700423540120665e+08f64), E::cast_from(6.6302997904833794242e+06f64), E::cast_from(-3.6629814655107086448e+04f64), E::cast_from(1.0344222815443188943e+02f64), E::cast_from(-1.2117036164593528341e-01f64), ]; let q1 = &[ E::cast_from(2.3883787996332290397e+12f64), E::cast_from(2.6328198300859648632e+10f64), E::cast_from(1.3985097372263433271e+08f64), E::cast_from(4.5612696224219938200e+05f64), E::cast_from(9.3614022392337710626e+02f64), E::cast_from(1.0f64), E::cast_from(0.0f64), ]; let p2 = &[ E::cast_from(-1.8319397969392084011e+03f64), E::cast_from(-1.2254078161378989535e+04f64), E::cast_from(-7.2879702464464618998e+03f64), E::cast_from(1.0341910641583726701e+04f64), E::cast_from(1.1725046279757103576e+04f64), E::cast_from(4.4176707025325087628e+03f64), E::cast_from(7.4321196680624245801e+02f64), E::cast_from(4.8591703355916499363e+01f64), ]; let q2 = &[ E::cast_from(-3.5783478026152301072e+05f64), E::cast_from(2.4599102262586308984e+05f64), E::cast_from(-8.4055062591169562211e+04f64), E::cast_from(1.8680990008359188352e+04f64), E::cast_from(-2.9458766545509337327e+03f64), E::cast_from(3.3307310774649071172e+02f64), E::cast_from(-2.5258076240801555057e+01f64), E::cast_from(1.0f64), ]; let pc = &[ E::cast_from(2.2779090197304684302e+04f64), E::cast_from(4.1345386639580765797e+04f64), E::cast_from(2.1170523380864944322e+04f64), E::cast_from(3.4806486443249270347e+03f64), E::cast_from(1.5376201909008354296e+02f64), E::cast_from(8.8961548424210455236e-01f64), ]; let qc = &[ E::cast_from(2.2779090197304684318e+04f64), E::cast_from(4.1370412495510416640e+04f64), E::cast_from(2.1215350561880115730e+04f64), E::cast_from(3.5028735138235608207e+03f64), E::cast_from(1.5711159858080893649e+02f64), E::cast_from(1.0f64), ]; let ps = &[ E::cast_from(-8.9226600200800094098e+01f64), E::cast_from(-1.8591953644342993800e+02f64), E::cast_from(-1.1183429920482737611e+02f64), E::cast_from(-2.2300261666214198472e+01f64), E::cast_from(-1.2441026745835638459e+00f64), E::cast_from(-8.8033303048680751817e-03f64), ]; let qs = &[ E::cast_from(5.7105024128512061905e+03f64), E::cast_from(1.1951131543434613647e+04f64), E::cast_from(7.2642780169211018836e+03f64), E::cast_from(1.4887231232283756582e+03f64), E::cast_from(9.0593769594993125859e+01f64), E::cast_from(1.0f64), ]; x = x.abs(); // even function let y00 = E::Vf::one(); let mut y04 = unsafe { E::Vf::undefined() }; let mut y48 = unsafe { E::Vf::undefined() }; let mut y8i = unsafe { E::Vf::undefined() }; let le4 = x.le(E::Vf::splat_as(4.0)); let le8 = x.le(E::Vf::splat_as(8.0)); // between 4 and 8 // if le4 AND le8, then be48 is false. If (NOT le4) AND le8, then be48 is true // a value cannot be le4 AND (NOT le8) let be48 = le4 ^ le8; // 0 < x <= 4 if P::POLICY.avoid_branching || le4.any() { let r = (x * x).poly_rational_p::<P>(p1, q1); y04 = (x + x1) * (den.mul_adde(x11, x) - x12) * r; }; // 4 < x <= 8 if P::POLICY.avoid_branching || be48.any() { let y = E::Vf::splat_as(-1.0 / 64.0).mul_adde(x * x, E::Vf::one()); // y <= 1 given above operation let r = y.poly_p::<P>(p2) / y.poly_p::<P>(q2); y48 = (x + x2) * (den.mul_adde(x21, x) - x22) * r; } // 8 < x <= inf if P::POLICY.avoid_branching || !le8.all() { let factor = E::Vf::FRAC_1_SQRT_PI() / x.sqrt(); let y = E::Vf::splat_as(8.0) / x; let y2 = y * y; // y2 <= 1.0 given above division, no need to do poly_rational let rc = y2.poly_p::<P>(pc) / y2.poly_p::<P>(qc); let rs = y2.poly_p::<P>(ps) / y2.poly_p::<P>(qs); let (sx, cx) = x.sin_cos_p::<P>(); y8i = factor * rc.mul_sube(sx + cx, y * rs * (sx - cx)); } let mut y = y8i; y = le8.select(y48, y); y = le4.select(y04, y); y = x.eq(E::Vf::zero()).select(y00, y); y } #[inline(always)] pub fn bessel_j1<S: Simd, E: SimdVectorizedSpecialFunctionsInternal<S>, P: Policy>(x: E::Vf) -> E::Vf { let x1 = E::Vf::splat_as(3.8317059702075123156e+00f64); let x2 = E::Vf::splat_as(7.0155866698156187535e+00f64); let x11 = E::Vf::splat_as(9.810e+02f64); let x12 = E::Vf::splat_as(-3.2527979248768438556e-04f64); let x21 = E::Vf::splat_as(1.7960e+03f64); let x22 = E::Vf::splat_as(-3.8330184381246462950e-05f64); let den = E::Vf::splat_as(-1.0 / 256.0); let p1 = &[ E::cast_from(-1.4258509801366645672e+11f64), E::cast_from(6.6781041261492395835e+09f64), E::cast_from(-1.1548696764841276794e+08f64), E::cast_from(9.8062904098958257677e+05f64), E::cast_from(-4.4615792982775076130e+03f64), E::cast_from(1.0650724020080236441e+01f64), E::cast_from(-1.0767857011487300348e-02f64), ]; let q1 = &[ E::cast_from(4.1868604460820175290e+12f64), E::cast_from(4.2091902282580133541e+10f64), E::cast_from(2.0228375140097033958e+08f64), E::cast_from(5.9117614494174794095e+05f64), E::cast_from(1.0742272239517380498e+03f64), E::cast_from(1.0f64), E::cast_from(0.0f64), ]; let p2 = &[ E::cast_from(4.6179191852758252278e+00f64), E::cast_from(-7.5023342220781607561e+03f64), E::cast_from(5.0793266148011179143e+06f64), E::cast_from(-1.8113931269860667829e+09f64), E::cast_from(3.5580665670910619166e+11f64), E::cast_from(-3.6658018905416665164e+13f64), E::cast_from(1.6608531731299018674e+15f64), E::cast_from(-1.7527881995806511112e+16f64), ]; let q2 = &[ E::cast_from(1.0f64), E::cast_from(1.3886978985861357615e+03f64), E::cast_from(1.1267125065029138050e+06f64), E::cast_from(6.4872502899596389593e+08f64), E::cast_from(2.7622777286244082666e+11f64), E::cast_from(8.4899346165481429307e+13f64), E::cast_from(1.7128800897135812012e+16f64), E::cast_from(1.7253905888447681194e+18f64), ]; let pc = &[ E::cast_from(-4.4357578167941278571e+06f64), E::cast_from(-9.9422465050776411957e+06f64), E::cast_from(-6.6033732483649391093e+06f64), E::cast_from(-1.5235293511811373833e+06f64), E::cast_from(-1.0982405543459346727e+05f64), E::cast_from(-1.6116166443246101165e+03f64), E::cast_from(0.0f64), ]; let qc = &[ E::cast_from(-4.4357578167941278568e+06f64), E::cast_from(-9.9341243899345856590e+06f64), E::cast_from(-6.5853394797230870728e+06f64), E::cast_from(-1.5118095066341608816e+06f64), E::cast_from(-1.0726385991103820119e+05f64), E::cast_from(-1.4550094401904961825e+03f64), E::cast_from(1.0f64), ]; let ps = &[ E::cast_from(3.3220913409857223519e+04f64), E::cast_from(8.5145160675335701966e+04f64), E::cast_from(6.6178836581270835179e+04f64), E::cast_from(1.8494262873223866797e+04f64), E::cast_from(1.7063754290207680021e+03f64), E::cast_from(3.5265133846636032186e+01f64), E::cast_from(0.0f64), ]; let qs = &[ E::cast_from(7.0871281941028743574e+05f64), E::cast_from(1.8194580422439972989e+06f64), E::cast_from(1.4194606696037208929e+06f64), E::cast_from(4.0029443582266975117e+05f64), E::cast_from(3.7890229745772202641e+04f64), E::cast_from(8.6383677696049909675e+02f64), E::cast_from(1.0f64), ]; let w = x.abs(); let y00 = E::Vf::zero(); let mut y04 = unsafe { E::Vf::undefined() }; let mut y48 = unsafe { E::Vf::undefined() }; let mut y8i = unsafe { E::Vf::undefined() }; let le4 = w.le(E::Vf::splat_as(4.0)); let le8 = w.le(E::Vf::splat_as(8.0)); // between 4 and 8 // if le4 AND le8, then be48 is false. If (NOT le4) AND le8, then be48 is true // a value cannot be le4 AND (NOT le8) let be48 = le4 ^ le8; // 0 < w <= 4 if P::POLICY.avoid_branching || le4.any() { let r = (x * x).poly_rational_p::<P>(p1, q1); y04 = r * w * (w + x1) * (den.mul_adde(x11, w) - x12); } // 4 < w <= 8 if P::POLICY.avoid_branching || be48.any() { let y = E::Vf::one() / (x * x); let r = y.poly_p::<P>(p2) / y.poly_p::<P>(q2); y48 = r * w * (w + x2) * (den.mul_adde(x21, w) - x22); } // 8 < w <= inf if P::POLICY.avoid_branching || !le8.all() { let y = E::Vf::splat_as(8.0) / w; let y2 = y * y; let factor = E::Vf::FRAC_1_SQRT_PI() / w.sqrt(); // y2 <= 1.0 given above division, no need for poly_rational let rc = y2.poly_p::<P>(pc) / y2.poly_p::<P>(qc); let rs = y2.poly_p::<P>(ps) / y2.poly_p::<P>(qs); // in the original, this used x instead of w, but that produced incorrect results let (sx, cx) = w.sin_cos_p::<P>(); y8i = factor * rc.mul_adde(sx - cx, y * rs * (sx + cx)); } let mut y = y8i; y = le8.select(y48, y); y = le4.select(y04, y); y = x.eq(E::Vf::zero()).select(y00, y); y.combine_sign(x) } #[inline(always)] pub fn bessel_y0<S: Simd, E: SimdVectorizedSpecialFunctionsInternal<S>, P: Policy>(x: E::Vf) -> E::Vf { let x1 = E::Vf::splat_as(8.9357696627916752158e-01f64); let x2 = E::Vf::splat_as(3.9576784193148578684e+00f64); let x3 = E::Vf::splat_as(7.0860510603017726976e+00f64); // ln(x1, x2, x3) let lnx1 = E::Vf::splat_as(-0.112522807880794125038133980477252212668015528121886074367185547f64); let lnx2 = E::Vf::splat_as(1.3756575956013471336175786440565011276993580049899787950261170276f64); let lnx3 = E::Vf::splat_as(1.9581282122177381156900951130612350155885109149487567360554102593f64); let x11 = E::Vf::splat_as(2.280e+02f64); let x12 = E::Vf::splat_as(2.9519662791675215849e-03f64); let x21 = E::Vf::splat_as(1.0130e+03f64); let x22 = E::Vf::splat_as(6.4716931485786837568e-04f64); let x31 = E::Vf::splat_as(1.8140e+03f64); let x32 = E::Vf::splat_as(1.1356030177269762362e-04f64); let den = E::Vf::splat_as(-1.0 / 256.0); let p1 = &[ E::cast_from(1.0723538782003176831e+11f64), E::cast_from(-8.3716255451260504098e+09f64), E::cast_from(2.0422274357376619816e+08f64), E::cast_from(-2.1287548474401797963e+06f64), E::cast_from(1.0102532948020907590e+04f64), E::cast_from(-1.8402381979244993524e+01f64), ]; let q1 = &[ E::cast_from(5.8873865738997033405e+11f64), E::cast_from(8.1617187777290363573e+09f64), E::cast_from(5.5662956624278251596e+07f64), E::cast_from(2.3889393209447253406e+05f64), E::cast_from(6.6475986689240190091e+02f64), E::cast_from(1.0f64), ]; let p2 = &[ E::cast_from(1.7427031242901594547e+01f64), E::cast_from(-1.4566865832663635920e+04f64), E::cast_from(4.6905288611678631510e+06f64), E::cast_from(-6.9590439394619619534e+08f64), E::cast_from(4.3600098638603061642e+10f64), E::cast_from(-5.5107435206722644429e+11f64), E::cast_from(-2.2213976967566192242e+13f64), ]; let q2 = &[ E::cast_from(1.0f64), E::cast_from(8.3030857612070288823e+02f64), E::cast_from(4.0669982352539552018e+05f64), E::cast_from(1.3960202770986831075e+08f64), E::cast_from(3.4015103849971240096e+10f64), E::cast_from(5.4266824419412347550e+12f64), E::cast_from(4.3386146580707264428e+14f64), ]; let p3 = &[ E::cast_from(-1.7439661319197499338e+01f64), E::cast_from(2.1363534169313901632e+04f64), E::cast_from(-1.0085539923498211426e+07f64), E::cast_from(2.1958827170518100757e+09f64), E::cast_from(-1.9363051266772083678e+11f64), E::cast_from(-1.2829912364088687306e+11f64), E::cast_from(6.7016641869173237784e+14f64), E::cast_from(-8.0728726905150210443e+15f64), ]; let q3 = &[ E::cast_from(1.0f64), E::cast_from(8.7903362168128450017e+02f64), E::cast_from(5.3924739209768057030e+05f64), E::cast_from(2.4727219475672302327e+08f64), E::cast_from(8.6926121104209825246e+10f64), E::cast_from(2.2598377924042897629e+13f64), E::cast_from(3.9272425569640309819e+15f64), E::cast_from(3.4563724628846457519e+17f64), ]; let pc = &[ E::cast_from(2.2779090197304684302e+04f64), E::cast_from(4.1345386639580765797e+04f64), E::cast_from(2.1170523380864944322e+04f64), E::cast_from(3.4806486443249270347e+03f64), E::cast_from(1.5376201909008354296e+02f64), E::cast_from(8.8961548424210455236e-01f64), ]; let qc = &[ E::cast_from(2.2779090197304684318e+04f64), E::cast_from(4.1370412495510416640e+04f64), E::cast_from(2.1215350561880115730e+04f64), E::cast_from(3.5028735138235608207e+03f64), E::cast_from(1.5711159858080893649e+02f64), E::cast_from(1.0f64), ]; let ps = &[ E::cast_from(-8.9226600200800094098e+01f64), E::cast_from(-1.8591953644342993800e+02f64), E::cast_from(-1.1183429920482737611e+02f64), E::cast_from(-2.2300261666214198472e+01f64), E::cast_from(-1.2441026745835638459e+00f64), E::cast_from(-8.8033303048680751817e-03f64), ]; let qs = &[ E::cast_from(5.7105024128512061905e+03f64), E::cast_from(1.1951131543434613647e+04f64), E::cast_from(7.2642780169211018836e+03f64), E::cast_from(1.4887231232283756582e+03f64), E::cast_from(9.0593769594993125859e+01f64), E::cast_from(1.0f64), ]; let yi0 = E::Vf::nan(); let y00 = E::Vf::neg_infinity(); let mut y03 = unsafe { E::Vf::undefined() }; let mut y355 = unsafe { E::Vf::undefined() }; let mut y558 = unsafe { E::Vf::undefined() }; let mut y8i = unsafe { E::Vf::undefined() }; let le3 = x.le(E::Vf::splat_as(3.0f64)); let le55 = x.le(E::Vf::splat_as(5.5f64)); let le8 = x.le(E::Vf::splat_as(8.0)); // if le3 AND le55, then NOT between. let be355 = le3 ^ le55; // if le55 AND le8, then NOT between. let be558 = le55 ^ le8; let mut j0_2_frac_pi = unsafe { E::Vf::undefined() }; let mut lnx_j0_2_frac_pi = unsafe { E::Vf::undefined() }; let mut xx = unsafe { E::Vf::undefined() }; let mut ixx = unsafe { E::Vf::undefined() }; if P::POLICY.avoid_branching || le8.any() { xx = x * x; ixx = E::Vf::one() / xx; // setup division early to pipeline it j0_2_frac_pi = x.bessel_j_p::<P>(0) * E::Vf::FRAC_2_PI(); lnx_j0_2_frac_pi = x.ln_p::<P>() * j0_2_frac_pi; } if P::POLICY.avoid_branching || le3.any() { let r = xx.poly_rational_p::<P>(p1, q1); let f = (x + x1) * (den.mul_adde(x11, x) - x12); y03 = f.mul_adde(r, lnx1.nmul_adde(j0_2_frac_pi, lnx_j0_2_frac_pi)); } if P::POLICY.avoid_branching || be355.any() { let r = ixx.poly_p::<P>(p2) / ixx.poly_p::<P>(q2); let f = (x + x2) * (den.mul_adde(x21, x) - x22); y355 = f.mul_adde(r, lnx2.nmul_adde(j0_2_frac_pi, lnx_j0_2_frac_pi)); } if P::POLICY.avoid_branching || be558.any() { let r = ixx.poly_p::<P>(p3) / ixx.poly_p::<P>(q3); let f = (x + x3) * (den.mul_adde(x31, x) - x32); y558 = f.mul_adde(r, lnx3.nmul_adde(j0_2_frac_pi, lnx_j0_2_frac_pi)); } if P::POLICY.avoid_branching || !le8.all() { let y = E::Vf::splat_as(8.0) / x; let y2 = y * y; let factor = E::Vf::FRAC_1_SQRT_PI() / x.sqrt(); // y2 <= 1.0 given above division, no need for poly_rational let rc = y2.poly_p::<P>(pc) / y2.poly_p::<P>(qc); let rs = y2.poly_p::<P>(ps) / y2.poly_p::<P>(qs); let (sx, cx) = x.sin_cos_p::<P>(); y8i = factor * rc.mul_adde(sx - cx, y * rs * (cx + sx)); } let mut y = y8i; y = le8.select(y558, y); y = le55.select(y355, y); y = le3.select(y03, y); y = x.eq(E::Vf::zero()).select(y00, y); y = x.lt(E::Vf::zero()).select(yi0, y); y } #[inline(always)] pub fn bessel_y1<S: Simd, E: SimdVectorizedSpecialFunctionsInternal<S>, P: Policy>(x: E::Vf) -> E::Vf { let x1 = E::Vf::splat_as(2.1971413260310170351e+00f64); let x2 = E::Vf::splat_as(5.4296810407941351328e+00f64); let lnx1 = E::Vf::splat_as(0.7871571181569950672690417763111546486043689808047331111421468535); let lnx2 = E::Vf::splat_as(1.6918803920353296781969247742811007463414923906071109385474494417); let x11 = E::Vf::splat_as(5.620e+02f64); let x12 = E::Vf::splat_as(1.8288260310170351490e-03f64); let x21 = E::Vf::splat_as(1.3900e+03f64); let x22 = E::Vf::splat_as(-6.4592058648672279948e-06f64); let den = E::Vf::splat_as(-1.0 / 256.0); let p1 = &[ E::cast_from(4.0535726612579544093e+13f64), E::cast_from(5.4708611716525426053e+12f64), E::cast_from(-3.7595974497819597599e+11f64), E::cast_from(7.2144548214502560419e+09f64), E::cast_from(-5.9157479997408395984e+07f64), E::cast_from(2.2157953222280260820e+05f64), E::cast_from(-3.1714424660046133456e+02f64), ]; let q1 = &[ E::cast_from(3.0737873921079286084e+14f64), E::cast_from(4.1272286200406461981e+12f64), E::cast_from(2.7800352738690585613e+10f64), E::cast_from(1.2250435122182963220e+08f64), E::cast_from(3.8136470753052572164e+05f64), E::cast_from(8.2079908168393867438e+02f64), E::cast_from(1.0f64), ]; let p2 = &[ E::cast_from(-1.2337180442012953128e+03f64), E::cast_from(1.9153806858264202986e+06f64), E::cast_from(-1.1957961912070617006e+09f64), E::cast_from(3.7453673962438488783e+11f64), E::cast_from(-5.9530713129741981618e+13f64), E::cast_from(4.0686275289804744814e+15f64), E::cast_from(-2.3638408497043134724e+16f64), E::cast_from(-5.6808094574724204577e+18f64), E::cast_from(1.1514276357909013326e+19f64), ]; let q2 = &[ E::cast_from(1.0f64), E::cast_from(1.2855164849321609336e+03f64), E::cast_from(1.0453748201934079734e+06f64), E::cast_from(6.3550318087088919566e+08f64), E::cast_from(3.0221766852960403645e+11f64), E::cast_from(1.1187010065856971027e+14f64), E::cast_from(3.0837179548112881950e+16f64), E::cast_from(5.6968198822857178911e+18f64), E::cast_from(5.3321844313316185697e+20f64), ]; let pc = &[ E::cast_from(-4.4357578167941278571e+06f64), E::cast_from(-9.9422465050776411957e+06f64), E::cast_from(-6.6033732483649391093e+06f64), E::cast_from(-1.5235293511811373833e+06f64), E::cast_from(-1.0982405543459346727e+05f64), E::cast_from(-1.6116166443246101165e+03f64), E::cast_from(0.0f64), ]; let qc = &[ E::cast_from(-4.4357578167941278568e+06f64), E::cast_from(-9.9341243899345856590e+06f64), E::cast_from(-6.5853394797230870728e+06f64), E::cast_from(-1.5118095066341608816e+06f64), E::cast_from(-1.0726385991103820119e+05f64), E::cast_from(-1.4550094401904961825e+03f64), E::cast_from(1.0f64), ]; let ps = &[ E::cast_from(3.3220913409857223519e+04f64), E::cast_from(8.5145160675335701966e+04f64), E::cast_from(6.6178836581270835179e+04f64), E::cast_from(1.8494262873223866797e+04f64), E::cast_from(1.7063754290207680021e+03f64), E::cast_from(3.5265133846636032186e+01f64), E::cast_from(0.0f64), ]; let qs = &[ E::cast_from(7.0871281941028743574e+05f64), E::cast_from(1.8194580422439972989e+06f64), E::cast_from(1.4194606696037208929e+06f64), E::cast_from(4.0029443582266975117e+05f64), E::cast_from(3.7890229745772202641e+04f64), E::cast_from(8.6383677696049909675e+02f64), E::cast_from(1.0f64), ]; let yi0 = E::Vf::nan(); let y00 = E::Vf::neg_infinity(); let mut y04 = unsafe { E::Vf::undefined() }; let mut y48 = unsafe { E::Vf::undefined() }; let mut y8i = unsafe { E::Vf::undefined() }; let le4 = x.le(E::Vf::splat_as(4.0)); let le8 = x.le(E::Vf::splat_as(8.0)); let be48 = le4 ^ le8; let mut j1_2_frac_pi = unsafe { E::Vf::undefined() }; let mut lnx_j1_2_frac_pi = unsafe { E::Vf::undefined() }; let mut xx = unsafe { E::Vf::undefined() }; let mut ix = unsafe { E::Vf::undefined() }; if true || P::POLICY.avoid_branching || le8.any() { xx = x * x; ix = E::Vf::one() / x; j1_2_frac_pi = x.bessel_j_p::<P>(1) * E::Vf::FRAC_2_PI(); lnx_j1_2_frac_pi = x.ln_p::<P>() * j1_2_frac_pi; } if P::POLICY.avoid_branching || le4.any() { let r = xx.poly_rational_p::<P>(p1, q1); let f = (x + x1) * (den.mul_adde(x11, x) - x12) * ix; y04 = f.mul_adde(r, lnx1.nmul_add(j1_2_frac_pi, lnx_j1_2_frac_pi)); } if P::POLICY.avoid_branching || be48.any() { let ixx = ix * ix; let r = ixx.poly_p::<P>(p2) / ixx.poly_p::<P>(q2); let f = (x + x2) * (den.mul_adde(x21, x) - x22) * ix; y48 = f.mul_adde(r, lnx2.nmul_add(j1_2_frac_pi, lnx_j1_2_frac_pi)); } if P::POLICY.avoid_branching || !le8.all() { let y = E::Vf::splat_as(8.0) / x; let y2 = y * y; let factor = E::Vf::FRAC_1_SQRT_PI() / x.sqrt(); // y2 <= 1.0 given above division, no need for poly_rational let rc = y2.poly_p::<P>(pc) / y2.poly_p::<P>(qc); let rs = y2.poly_p::<P>(ps) / y2.poly_p::<P>(qs); let (sx, cx) = x.sin_cos_p::<P>(); y8i = factor * rc.nmul_adde(sx + cx, y * rs * (sx - cx)); } let mut y = y8i; y = le8.select(y48, y); y = le4.select(y04, y); y = x.eq(E::Vf::zero()).select(y00, y); y = x.lt(E::Vf::zero()).select(yi0, y); y } #[inline(always)] pub fn bessel_j<S: Simd, E: SimdVectorizedSpecialFunctionsInternal<S>, P: Policy>(x: E::Vf, n: u32) -> E::Vf { let mut j0 = unsafe { E::Vf::undefined() }; let mut j1 = unsafe { E::Vf::undefined() }; if n == 0 || n > 1 { j0 = bessel_j0::<S, E, P>(x); } if n >= 1 { j1 = bessel_j1::<S, E, P>(x); } match n { 0 => j0, 1 => j1, _ => { let one = E::Vf::one(); let zero = E::Vf::zero(); let factor = x.lt(zero).select(E::Vf::neg_one(), one); let mut prev = j0; let mut current = j1 * factor; // abs(x) let mut value = unsafe { E::Vf::undefined() }; let ix = x.abs().reciprocal_p::<P>(); // Generic forward recurrence for k in 1..n { let mult = E::Vf::splat_as(k + k) * ix; value = mult.mul_sub(current, prev); prev = current; current = value; } // TODO: Improve precision around zero value *= factor; if P::POLICY.check_overflow { value = x.eq(zero).select(zero, value); } value } } } #[inline(always)] pub fn bessel_y<S: Simd, E: SimdVectorizedSpecialFunctionsInternal<S>, P: Policy>(x: E::Vf, n: u32) -> E::Vf { let mut y0 = unsafe { E::Vf::undefined() }; let mut y1 = unsafe { E::Vf::undefined() }; // only call y0 and y1 once at most, to encourage inlining if n == 0 || n > 1 { y0 = bessel_y0::<S, E, P>(x); } if n >= 1 { y1 = bessel_y1::<S, E, P>(x); } match n { 0 => y0, 1 => y1, _ => { let mut prev = y0; let mut current = y1; let mut value = unsafe { E::Vf::undefined() }; let ix = x.reciprocal_p::<P>(); for k in 1..n { let mult = E::Vf::splat_as(k + k) * ix; value = mult.mul_sub(current, prev); prev = current; current = value; } value } } } }
38.891929
114
0.539043
1eadd03bacfa00702942a1447e114220446290d9
15,086
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn serialize_operation_crate_operation_associate_firewall_policy( input: &crate::input::AssociateFirewallPolicyInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_associate_firewall_policy_input( &mut object, input, )?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_associate_subnets( input: &crate::input::AssociateSubnetsInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_associate_subnets_input(&mut object, input)?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_create_firewall( input: &crate::input::CreateFirewallInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_create_firewall_input(&mut object, input)?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_create_firewall_policy( input: &crate::input::CreateFirewallPolicyInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_create_firewall_policy_input( &mut object, input, )?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_create_rule_group( input: &crate::input::CreateRuleGroupInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_create_rule_group_input(&mut object, input)?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_delete_firewall( input: &crate::input::DeleteFirewallInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_delete_firewall_input(&mut object, input)?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_delete_firewall_policy( input: &crate::input::DeleteFirewallPolicyInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_delete_firewall_policy_input( &mut object, input, )?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_delete_resource_policy( input: &crate::input::DeleteResourcePolicyInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_delete_resource_policy_input( &mut object, input, )?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_delete_rule_group( input: &crate::input::DeleteRuleGroupInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_delete_rule_group_input(&mut object, input)?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_describe_firewall( input: &crate::input::DescribeFirewallInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_describe_firewall_input(&mut object, input)?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_describe_firewall_policy( input: &crate::input::DescribeFirewallPolicyInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_describe_firewall_policy_input( &mut object, input, )?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_describe_logging_configuration( input: &crate::input::DescribeLoggingConfigurationInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_describe_logging_configuration_input( &mut object, input, )?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_describe_resource_policy( input: &crate::input::DescribeResourcePolicyInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_describe_resource_policy_input( &mut object, input, )?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_describe_rule_group( input: &crate::input::DescribeRuleGroupInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_describe_rule_group_input(&mut object, input)?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_disassociate_subnets( input: &crate::input::DisassociateSubnetsInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_disassociate_subnets_input( &mut object, input, )?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_list_firewall_policies( input: &crate::input::ListFirewallPoliciesInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_list_firewall_policies_input( &mut object, input, )?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_list_firewalls( input: &crate::input::ListFirewallsInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_list_firewalls_input(&mut object, input)?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_list_rule_groups( input: &crate::input::ListRuleGroupsInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_list_rule_groups_input(&mut object, input)?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_list_tags_for_resource( input: &crate::input::ListTagsForResourceInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_list_tags_for_resource_input( &mut object, input, )?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_put_resource_policy( input: &crate::input::PutResourcePolicyInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_put_resource_policy_input(&mut object, input)?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_tag_resource( input: &crate::input::TagResourceInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_tag_resource_input(&mut object, input)?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_untag_resource( input: &crate::input::UntagResourceInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_untag_resource_input(&mut object, input)?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_update_firewall_delete_protection( input: &crate::input::UpdateFirewallDeleteProtectionInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_update_firewall_delete_protection_input( &mut object, input, )?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_update_firewall_description( input: &crate::input::UpdateFirewallDescriptionInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_update_firewall_description_input( &mut object, input, )?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_update_firewall_policy( input: &crate::input::UpdateFirewallPolicyInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_update_firewall_policy_input( &mut object, input, )?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_update_firewall_policy_change_protection( input: &crate::input::UpdateFirewallPolicyChangeProtectionInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_update_firewall_policy_change_protection_input(&mut object, input)?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_update_logging_configuration( input: &crate::input::UpdateLoggingConfigurationInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_update_logging_configuration_input( &mut object, input, )?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_update_rule_group( input: &crate::input::UpdateRuleGroupInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_update_rule_group_input(&mut object, input)?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_update_subnet_change_protection( input: &crate::input::UpdateSubnetChangeProtectionInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_crate_input_update_subnet_change_protection_input( &mut object, input, )?; object.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) }
44.89881
121
0.751094
fedb7c0554039ffd9a71cf292ba6b25128b4e386
1,134
// use std::any::Any; use crate::core::error::Error; use hulunbuir::{Keep, Address}; pub struct Object { content: Box<dyn Any>, keep: fn(&Object) -> Vec<Address>, } impl Keep for Object { fn with_keep<F: FnOnce(&[Address])>(&self, f: F) { f(&(self.keep)(self)) } } fn keep_helper<T: Any + Keep>(object: &Object) -> Vec<Address> { let mut keep_list = Vec::new(); object.downcast_ref::<T>().unwrap().with_keep(|list| keep_list = list.to_vec()); keep_list } impl Object { pub fn new<T: Any + Keep>(content: T) -> Self { Object { content: Box::new(content), keep: keep_helper::<T>, } } } impl Object { pub fn downcast_ref<T: Any>(&self) -> Result<&T, Error> { (&self.content as &dyn Any).downcast_ref().ok_or(Error::TypeMismatch) } pub fn downcast_mut<T: Any>(&mut self) -> Result<&mut T, Error> { (&mut self.content as &mut dyn Any).downcast_mut().ok_or(Error::TypeMismatch) } pub fn downcast<T: Any>(self) -> Result<T, Error> { Ok(*self.content.downcast().map_err(|_| Error::TypeMismatch)?) } }
24.12766
85
0.583774
0e9deb37069a3f4504439b522c38453a3dfb30eb
6,317
extern crate codespan_reporting; // Tested with codespan_reporting v0.9.5 extern crate salsa; // Tested with salsa v0.15.1 use codespan_reporting::{ diagnostic::{Diagnostic, Label, LabelStyle}, files::Files, term::{ self, termcolor::{ColorChoice, StandardStream}, Config, }, }; use std::{cmp::Ordering, fmt, ops::Range, sync::Arc}; fn main() { let mut database = Database::default(); database.set_file_name(FileId(0), Arc::new("crime.rs".to_owned())); database.set_source_text(FileId(0), Arc::new(include_str!("main.rs").to_owned())); database.parse(FileId(0)); } // A standard salsa database to hold all our query info #[salsa::database(SourceDatabaseStorage, ParseDatabaseStorage)] #[derive(Default)] pub struct Database { storage: salsa::Storage<Self>, } impl salsa::Database for Database {} // Implement upcasting for the main database into every query group it holds impl Upcast<dyn SourceDatabase> for Database { fn upcast(&self) -> &dyn SourceDatabase { &*self } } impl Upcast<dyn ParseDatabase> for Database { fn upcast(&self) -> &dyn ParseDatabase { &*self } } // This is the key trait here, it allows all of our trait shenanigans pub trait Upcast<T: ?Sized> { fn upcast(&self) -> &T; } // If we want to be able to use `&dyn ParseDatabase` for rendering errors we must have `Upcast<dyn SourceDatabase>` as a supertrait #[salsa::query_group(ParseDatabaseStorage)] pub trait ParseDatabase: salsa::Database + SourceDatabase + Upcast<dyn SourceDatabase> { // Salsa currently doesn't allow returning unit in a non-explicit way, see https://github.com/salsa-rs/salsa/issues/149 fn parse(&self, file: FileId) -> (); } // Right now all this does is emit an error, but that's just an example fn parse(db: &dyn ParseDatabase, file: FileId) { let writer = StandardStream::stderr(ColorChoice::Auto); let config = Config::default(); let diag = Diagnostic::error() .with_message("This is a crime") .with_labels(vec![Label::new( LabelStyle::Primary, FileId(0), db.line_range(file, 14).unwrap().start..db.line_range(file, 20).unwrap().end - 1, )]); // Using `FileCache::upcast` we can take anything that implements `Upcast<dyn SourceDatabase` and use it for emitting errors term::emit(&mut writer.lock(), &config, &FileCache::upcast(db), &diag).unwrap(); } /// The database that holds all source files #[salsa::query_group(SourceDatabaseStorage)] pub trait SourceDatabase: salsa::Database { /// Get the name of a source file #[salsa::input] fn file_name(&self, file: FileId) -> Arc<String>; /// The source text of a file #[salsa::input] fn source_text(&self, file: FileId) -> Arc<String>; /// The length of a source file fn source_length(&self, file: FileId) -> usize; /// The indices of every line start for the file fn line_starts(&self, file: FileId) -> Arc<Vec<usize>>; /// The index a line starts at fn line_start(&self, file: FileId, line_index: usize) -> Option<usize>; /// The line which a byte index falls on fn line_index(&self, file: FileId, byte_index: usize) -> Option<usize>; /// The range of a single line fn line_range(&self, file: FileId, line_index: usize) -> Option<Range<usize>>; } fn source_length(db: &dyn SourceDatabase, file: FileId) -> usize { db.source_text(file).len() } fn line_starts(db: &dyn SourceDatabase, file: FileId) -> Arc<Vec<usize>> { Arc::new( core::iter::once(0) .chain(db.source_text(file).match_indices('\n').map(|(i, _)| i + 1)) .collect(), ) } fn line_start(db: &dyn SourceDatabase, file: FileId, line_index: usize) -> Option<usize> { let line_starts = db.line_starts(file); match line_index.cmp(&line_starts.len()) { Ordering::Less => line_starts.get(line_index).cloned(), Ordering::Equal => Some(db.source_length(file)), Ordering::Greater => None, } } fn line_index(db: &dyn SourceDatabase, file: FileId, byte_index: usize) -> Option<usize> { match db.line_starts(file).binary_search(&byte_index) { Ok(line) => Some(line), Err(next_line) => Some(next_line - 1), } } fn line_range(db: &dyn SourceDatabase, file: FileId, line_index: usize) -> Option<Range<usize>> { let start = db.line_start(file, line_index)?; let end = db.line_start(file, line_index + 1)?; Some(start..end) } #[derive(Copy, Clone)] pub struct FileCache<'a> { // The advantage of using `SourceDatabase` for rendering errors is that things are done on-demand. // Calculating line ranges and indices can be expensive, especially with lots of large files, and // using queries means that things are only calculated when they're needed and then cached from then on, // making further uses essentially free source: &'a dyn SourceDatabase, } impl<'a> FileCache<'a> { pub fn new(source: &'a dyn SourceDatabase) -> Self { Self { source } } pub fn upcast<T>(source: &'a T) -> Self where T: Upcast<dyn SourceDatabase> + ?Sized, { Self::new(source.upcast()) } } // Note that most methods here will make salsa panic if the requested file hasn't been input yet impl<'a> Files<'a> for FileCache<'a> { type FileId = FileId; // The owning here isn't ideal, but `Arc<String>` doesn't implement `Display` or `AsRef<str>` type Name = String; type Source = String; fn name(&self, file: FileId) -> Option<String> { Some(self.source.file_name(file).as_ref().clone()) } fn source(&self, file: FileId) -> Option<String> { Some(self.source.source_text(file).as_ref().clone()) } fn line_index(&self, file: FileId, byte_index: usize) -> Option<usize> { self.source.line_index(file, byte_index) } fn line_range(&self, file: FileId, line_index: usize) -> Option<Range<usize>> { self.source.line_range(file, line_index) } } impl fmt::Debug for FileCache<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("FileCache").finish() } } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[repr(transparent)] pub struct FileId(pub u32);
32.901042
131
0.656799
5685355c165671c4cf9cd737895626ba5e40b562
28,884
// Copyright 2018 The Epic 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. // Rust Bitcoin Library // Written in 2014 by // Andrew Poelstra <[email protected]> // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. // // You should have received a copy of the CC0 Public Domain Dedication // along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // //! Implementation of BIP32 hierarchical deterministic wallets, as defined //! at https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki //! Modified from above to integrate into epic and allow for different //! hashing algorithms if desired #[cfg(feature = "serde")] use serde; use std::default::Default; use std::io::Cursor; use std::str::FromStr; use std::{error, fmt}; use crate::mnemonic; use crate::util::secp::key::{PublicKey, SecretKey}; use crate::util::secp::{self, ContextFlag, Secp256k1}; use byteorder::{BigEndian, ByteOrder, ReadBytesExt}; use digest::generic_array::GenericArray; use digest::Digest; use hmac::{Hmac, Mac}; use ripemd160::Ripemd160; use sha2::{Sha256, Sha512}; use crate::base58; // Create alias for HMAC-SHA256 type HmacSha512 = Hmac<Sha512>; /// A chain code pub struct ChainCode([u8; 32]); impl_array_newtype!(ChainCode, u8, 32); impl_array_newtype_show!(ChainCode); impl_array_newtype_encodable!(ChainCode, u8, 32); /// A fingerprint pub struct Fingerprint([u8; 4]); impl_array_newtype!(Fingerprint, u8, 4); impl_array_newtype_show!(Fingerprint); impl_array_newtype_encodable!(Fingerprint, u8, 4); impl Default for Fingerprint { fn default() -> Fingerprint { Fingerprint([0, 0, 0, 0]) } } /// Allow different implementations of hash functions used in BIP32 Derivations /// Epic uses blake2 everywhere but the spec calls for SHA512/Ripemd160, so allow /// this in future and allow us to unit test against published BIP32 test vectors /// The function names refer to the place of the hash in the reference BIP32 spec, /// not what the actual implementation is pub trait BIP32Hasher { fn network_priv(&self) -> [u8; 4]; fn network_pub(&self) -> [u8; 4]; fn master_seed() -> [u8; 12]; fn init_sha512(&mut self, seed: &[u8]); fn append_sha512(&mut self, value: &[u8]); fn result_sha512(&mut self) -> [u8; 64]; fn sha_256(&self, input: &[u8]) -> [u8; 32]; fn ripemd_160(&self, input: &[u8]) -> [u8; 20]; } /// Implementation of the above that uses the standard BIP32 Hash algorithms #[derive(Clone, Debug)] pub struct BIP32EpicHasher { is_floo: bool, hmac_sha512: Hmac<Sha512>, } impl BIP32EpicHasher { /// New empty hasher pub fn new(is_floo: bool) -> BIP32EpicHasher { BIP32EpicHasher { is_floo: is_floo, hmac_sha512: HmacSha512::new(GenericArray::from_slice(&[0u8; 128])), } } } impl BIP32Hasher for BIP32EpicHasher { fn network_priv(&self) -> [u8; 4] { match self.is_floo { true => [0x03, 0x27, 0x3A, 0x10], // fprv false => [0x03, 0x3C, 0x04, 0xA4], // gprv } } fn network_pub(&self) -> [u8; 4] { match self.is_floo { true => [0x03, 0x27, 0x3E, 0x4B], // fpub false => [0x03, 0x3C, 0x08, 0xDF], // gpub } } fn master_seed() -> [u8; 12] { b"IamVoldemort".to_owned() } fn init_sha512(&mut self, seed: &[u8]) { self.hmac_sha512 = HmacSha512::new_varkey(seed).expect("HMAC can take key of any size");; } fn append_sha512(&mut self, value: &[u8]) { self.hmac_sha512.input(value); } fn result_sha512(&mut self) -> [u8; 64] { let mut result = [0; 64]; result.copy_from_slice(self.hmac_sha512.result().code().as_slice()); result } fn sha_256(&self, input: &[u8]) -> [u8; 32] { let mut sha2_res = [0; 32]; let mut sha2 = Sha256::new(); sha2.input(input); sha2_res.copy_from_slice(sha2.result().as_slice()); sha2_res } fn ripemd_160(&self, input: &[u8]) -> [u8; 20] { let mut ripemd_res = [0; 20]; let mut ripemd = Ripemd160::new(); ripemd.input(input); ripemd_res.copy_from_slice(ripemd.result().as_slice()); ripemd_res } } /// Extended private key #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct ExtendedPrivKey { /// The network this key is to be used on pub network: [u8; 4], /// How many derivations this key is from the master (which is 0) pub depth: u8, /// Fingerprint of the parent key (0 for master) pub parent_fingerprint: Fingerprint, /// Child number of the key used to derive from parent (0 for master) pub child_number: ChildNumber, /// Secret key pub secret_key: SecretKey, /// Chain code pub chain_code: ChainCode, } /// Extended public key #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct ExtendedPubKey { /// The network this key is to be used on pub network: [u8; 4], /// How many derivations this key is from the master (which is 0) pub depth: u8, /// Fingerprint of the parent key pub parent_fingerprint: Fingerprint, /// Child number of the key used to derive from parent (0 for master) pub child_number: ChildNumber, /// Public key pub public_key: PublicKey, /// Chain code pub chain_code: ChainCode, } /// A child number for a derived key #[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub enum ChildNumber { /// Non-hardened key Normal { /// Key index, within [0, 2^31 - 1] index: u32, }, /// Hardened key Hardened { /// Key index, within [0, 2^31 - 1] index: u32, }, } impl ChildNumber { /// Create a [`Normal`] from an index, panics if the index is not within /// [0, 2^31 - 1]. /// /// [`Normal`]: #variant.Normal pub fn from_normal_idx(index: u32) -> Self { assert_eq!( index & (1 << 31), 0, "ChildNumber indices have to be within [0, 2^31 - 1], is: {}", index ); ChildNumber::Normal { index: index } } /// Create a [`Hardened`] from an index, panics if the index is not within /// [0, 2^31 - 1]. /// /// [`Hardened`]: #variant.Hardened pub fn from_hardened_idx(index: u32) -> Self { assert_eq!( index & (1 << 31), 0, "ChildNumber indices have to be within [0, 2^31 - 1], is: {}", index ); ChildNumber::Hardened { index: index } } /// Returns `true` if the child number is a [`Normal`] value. /// /// [`Normal`]: #variant.Normal pub fn is_normal(&self) -> bool { !self.is_hardened() } /// Returns `true` if the child number is a [`Hardened`] value. /// /// [`Hardened`]: #variant.Hardened pub fn is_hardened(&self) -> bool { match *self { ChildNumber::Hardened { .. } => true, ChildNumber::Normal { .. } => false, } } } impl From<u32> for ChildNumber { fn from(number: u32) -> Self { if number & (1 << 31) != 0 { ChildNumber::Hardened { index: number ^ (1 << 31), } } else { ChildNumber::Normal { index: number } } } } impl From<ChildNumber> for u32 { fn from(cnum: ChildNumber) -> Self { match cnum { ChildNumber::Normal { index } => index, ChildNumber::Hardened { index } => index | (1 << 31), } } } impl fmt::Display for ChildNumber { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { ChildNumber::Hardened { index } => write!(f, "{}'", index), ChildNumber::Normal { index } => write!(f, "{}", index), } } } #[cfg(feature = "serde")] impl<'de> serde::Deserialize<'de> for ChildNumber { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { u32::deserialize(deserializer).map(ChildNumber::from) } } #[cfg(feature = "serde")] impl serde::Serialize for ChildNumber { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { u32::from(*self).serialize(serializer) } } /// A BIP32 error #[derive(Clone, PartialEq, Eq, Debug)] pub enum Error { /// A pk->pk derivation was attempted on a hardened key CannotDeriveFromHardenedKey, /// A secp256k1 error occured Ecdsa(secp::Error), /// A child number was provided that was out of range InvalidChildNumber(ChildNumber), /// Error creating a master seed --- for application use RngError(String), /// Error converting mnemonic to seed MnemonicError(mnemonic::Error), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Error::CannotDeriveFromHardenedKey => { f.write_str("cannot derive hardened key from public key") } Error::Ecdsa(ref e) => fmt::Display::fmt(e, f), Error::InvalidChildNumber(ref n) => write!(f, "child number {} is invalid", n), Error::RngError(ref s) => write!(f, "rng error {}", s), Error::MnemonicError(ref e) => fmt::Display::fmt(e, f), } } } impl error::Error for Error { fn cause(&self) -> Option<&dyn error::Error> { if let Error::Ecdsa(ref e) = *self { Some(e) } else { None } } fn description(&self) -> &str { match *self { Error::CannotDeriveFromHardenedKey => "cannot derive hardened key from public key", Error::Ecdsa(ref e) => error::Error::description(e), Error::InvalidChildNumber(_) => "child number is invalid", Error::RngError(_) => "rng error", Error::MnemonicError(_) => "mnemonic error", } } } impl From<secp::Error> for Error { fn from(e: secp::Error) -> Error { Error::Ecdsa(e) } } impl ExtendedPrivKey { /// Construct a new master key from a seed value pub fn new_master<H>( secp: &Secp256k1, hasher: &mut H, seed: &[u8], ) -> Result<ExtendedPrivKey, Error> where H: BIP32Hasher, { hasher.init_sha512(&H::master_seed()); hasher.append_sha512(seed); let result = hasher.result_sha512(); Ok(ExtendedPrivKey { network: hasher.network_priv(), depth: 0, parent_fingerprint: Default::default(), child_number: ChildNumber::from_normal_idx(0), secret_key: SecretKey::from_slice(secp, &result[..32]).map_err(Error::Ecdsa)?, chain_code: ChainCode::from(&result[32..]), }) } /// Construct a new master key from a mnemonic and a passphrase pub fn from_mnemonic( secp: &Secp256k1, mnemonic: &str, passphrase: &str, is_floo: bool, ) -> Result<ExtendedPrivKey, Error> { let seed = match mnemonic::to_seed(mnemonic, passphrase) { Ok(s) => s, Err(e) => return Err(Error::MnemonicError(e)), }; let mut hasher = BIP32EpicHasher::new(is_floo); let key = r#try!(ExtendedPrivKey::new_master(secp, &mut hasher, &seed)); Ok(key) } /// Attempts to derive an extended private key from a path. pub fn derive_priv<H>( &self, secp: &Secp256k1, hasher: &mut H, cnums: &[ChildNumber], ) -> Result<ExtendedPrivKey, Error> where H: BIP32Hasher, { let mut sk: ExtendedPrivKey = *self; for cnum in cnums { sk = sk.ckd_priv(secp, hasher, *cnum)?; } Ok(sk) } /// Private->Private child key derivation pub fn ckd_priv<H>( &self, secp: &Secp256k1, hasher: &mut H, i: ChildNumber, ) -> Result<ExtendedPrivKey, Error> where H: BIP32Hasher, { hasher.init_sha512(&self.chain_code[..]); let mut be_n = [0; 4]; match i { ChildNumber::Normal { .. } => { // Non-hardened key: compute public data and use that hasher.append_sha512( &PublicKey::from_secret_key(secp, &self.secret_key)?.serialize_vec(secp, true) [..], ); } ChildNumber::Hardened { .. } => { // Hardened key: use only secret data to prevent public derivation hasher.append_sha512(&[0u8]); hasher.append_sha512(&self.secret_key[..]); } } BigEndian::write_u32(&mut be_n, u32::from(i)); hasher.append_sha512(&be_n); let result = hasher.result_sha512(); let mut sk = SecretKey::from_slice(secp, &result[..32]).map_err(Error::Ecdsa)?; sk.add_assign(secp, &self.secret_key) .map_err(Error::Ecdsa)?; Ok(ExtendedPrivKey { network: self.network, depth: self.depth + 1, parent_fingerprint: self.fingerprint(hasher), child_number: i, secret_key: sk, chain_code: ChainCode::from(&result[32..]), }) } /// Returns the HASH160 of the chaincode pub fn identifier<H>(&self, hasher: &mut H) -> [u8; 20] where H: BIP32Hasher, { let secp = Secp256k1::with_caps(ContextFlag::SignOnly); // Compute extended public key let pk: ExtendedPubKey = ExtendedPubKey::from_private::<H>(&secp, self, hasher); // Do SHA256 of just the ECDSA pubkey let sha2_res = hasher.sha_256(&pk.public_key.serialize_vec(&secp, true)[..]); // do RIPEMD160 let ripemd_res = hasher.ripemd_160(&sha2_res); // Return ripemd_res } /// Returns the first four bytes of the identifier pub fn fingerprint<H>(&self, hasher: &mut H) -> Fingerprint where H: BIP32Hasher, { Fingerprint::from(&self.identifier(hasher)[0..4]) } } impl ExtendedPubKey { /// Derives a public key from a private key pub fn from_private<H>(secp: &Secp256k1, sk: &ExtendedPrivKey, hasher: &mut H) -> ExtendedPubKey where H: BIP32Hasher, { ExtendedPubKey { network: hasher.network_pub(), depth: sk.depth, parent_fingerprint: sk.parent_fingerprint, child_number: sk.child_number, public_key: PublicKey::from_secret_key(secp, &sk.secret_key).unwrap(), chain_code: sk.chain_code, } } /// Attempts to derive an extended public key from a path. pub fn derive_pub<H>( &self, secp: &Secp256k1, hasher: &mut H, cnums: &[ChildNumber], ) -> Result<ExtendedPubKey, Error> where H: BIP32Hasher, { let mut pk: ExtendedPubKey = *self; for cnum in cnums { pk = pk.ckd_pub(secp, hasher, *cnum)? } Ok(pk) } /// Compute the scalar tweak added to this key to get a child key pub fn ckd_pub_tweak<H>( &self, secp: &Secp256k1, hasher: &mut H, i: ChildNumber, ) -> Result<(SecretKey, ChainCode), Error> where H: BIP32Hasher, { match i { ChildNumber::Hardened { .. } => Err(Error::CannotDeriveFromHardenedKey), ChildNumber::Normal { index: n } => { hasher.init_sha512(&self.chain_code[..]); hasher.append_sha512(&self.public_key.serialize_vec(secp, true)[..]); let mut be_n = [0; 4]; BigEndian::write_u32(&mut be_n, n); hasher.append_sha512(&be_n); let result = hasher.result_sha512(); let secret_key = SecretKey::from_slice(secp, &result[..32])?; let chain_code = ChainCode::from(&result[32..]); Ok((secret_key, chain_code)) } } } /// Public->Public child key derivation pub fn ckd_pub<H>( &self, secp: &Secp256k1, hasher: &mut H, i: ChildNumber, ) -> Result<ExtendedPubKey, Error> where H: BIP32Hasher, { let (sk, chain_code) = self.ckd_pub_tweak(secp, hasher, i)?; let mut pk = self.public_key.clone(); pk.add_exp_assign(secp, &sk).map_err(Error::Ecdsa)?; Ok(ExtendedPubKey { network: self.network, depth: self.depth + 1, parent_fingerprint: self.fingerprint(secp, hasher), child_number: i, public_key: pk, chain_code: chain_code, }) } /// Returns the HASH160 of the chaincode pub fn identifier<H>(&self, secp: &Secp256k1, hasher: &mut H) -> [u8; 20] where H: BIP32Hasher, { // Do SHA256 of just the ECDSA pubkey let sha2_res = hasher.sha_256(&self.public_key.serialize_vec(secp, true)[..]); // do RIPEMD160 let ripemd_res = hasher.ripemd_160(&sha2_res); // Return ripemd_res } /// Returns the first four bytes of the identifier pub fn fingerprint<H>(&self, secp: &Secp256k1, hasher: &mut H) -> Fingerprint where H: BIP32Hasher, { Fingerprint::from(&self.identifier(secp, hasher)[0..4]) } } impl fmt::Display for ExtendedPrivKey { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let mut ret = [0; 78]; ret[0..4].copy_from_slice(&self.network[0..4]); ret[4] = self.depth as u8; ret[5..9].copy_from_slice(&self.parent_fingerprint[..]); BigEndian::write_u32(&mut ret[9..13], u32::from(self.child_number)); ret[13..45].copy_from_slice(&self.chain_code[..]); ret[45] = 0; ret[46..78].copy_from_slice(&self.secret_key[..]); fmt.write_str(&base58::check_encode_slice(&ret[..])) } } impl FromStr for ExtendedPrivKey { type Err = base58::Error; fn from_str(inp: &str) -> Result<ExtendedPrivKey, base58::Error> { let s = Secp256k1::without_caps(); let data = base58::from_check(inp)?; if data.len() != 78 { return Err(base58::Error::InvalidLength(data.len())); } let cn_int: u32 = Cursor::new(&data[9..13]).read_u32::<BigEndian>().unwrap(); let child_number: ChildNumber = ChildNumber::from(cn_int); let mut network = [0; 4]; network.copy_from_slice(&data[0..4]); Ok(ExtendedPrivKey { network: network, depth: data[4], parent_fingerprint: Fingerprint::from(&data[5..9]), child_number: child_number, chain_code: ChainCode::from(&data[13..45]), secret_key: SecretKey::from_slice(&s, &data[46..78]) .map_err(|e| base58::Error::Other(e.to_string()))?, }) } } impl fmt::Display for ExtendedPubKey { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let secp = Secp256k1::without_caps(); let mut ret = [0; 78]; ret[0..4].copy_from_slice(&self.network[0..4]); ret[4] = self.depth as u8; ret[5..9].copy_from_slice(&self.parent_fingerprint[..]); BigEndian::write_u32(&mut ret[9..13], u32::from(self.child_number)); ret[13..45].copy_from_slice(&self.chain_code[..]); ret[45..78].copy_from_slice(&self.public_key.serialize_vec(&secp, true)[..]); fmt.write_str(&base58::check_encode_slice(&ret[..])) } } impl FromStr for ExtendedPubKey { type Err = base58::Error; fn from_str(inp: &str) -> Result<ExtendedPubKey, base58::Error> { let s = Secp256k1::without_caps(); let data = base58::from_check(inp)?; if data.len() != 78 { return Err(base58::Error::InvalidLength(data.len())); } let cn_int: u32 = Cursor::new(&data[9..13]).read_u32::<BigEndian>().unwrap(); let child_number: ChildNumber = ChildNumber::from(cn_int); let mut network = [0; 4]; network.copy_from_slice(&data[0..4]); Ok(ExtendedPubKey { network: network, depth: data[4], parent_fingerprint: Fingerprint::from(&data[5..9]), child_number: child_number, chain_code: ChainCode::from(&data[13..45]), public_key: PublicKey::from_slice(&s, &data[45..78]) .map_err(|e| base58::Error::Other(e.to_string()))?, }) } } #[cfg(test)] mod tests { use std::str::FromStr; use std::string::ToString; use crate::util::from_hex; use crate::util::secp::Secp256k1; use super::*; use digest::generic_array::GenericArray; use digest::Digest; use hmac::{Hmac, Mac}; use ripemd160::Ripemd160; use sha2::{Sha256, Sha512}; /// Implementation of the above that uses the standard BIP32 Hash algorithms pub struct BIP32ReferenceHasher { hmac_sha512: Hmac<Sha512>, } impl BIP32ReferenceHasher { /// New empty hasher pub fn new() -> BIP32ReferenceHasher { BIP32ReferenceHasher { hmac_sha512: HmacSha512::new(GenericArray::from_slice(&[0u8; 128])), } } } impl BIP32Hasher for BIP32ReferenceHasher { fn network_priv(&self) -> [u8; 4] { // bitcoin network (xprv) (for test vectors) [0x04, 0x88, 0xAD, 0xE4] } fn network_pub(&self) -> [u8; 4] { // bitcoin network (xpub) (for test vectors) [0x04, 0x88, 0xB2, 0x1E] } fn master_seed() -> [u8; 12] { b"Bitcoin seed".to_owned() } fn init_sha512(&mut self, seed: &[u8]) { self.hmac_sha512 = HmacSha512::new_varkey(seed).expect("HMAC can take key of any size");; } fn append_sha512(&mut self, value: &[u8]) { self.hmac_sha512.input(value); } fn result_sha512(&mut self) -> [u8; 64] { let mut result = [0; 64]; result.copy_from_slice(self.hmac_sha512.result().code().as_slice()); result } fn sha_256(&self, input: &[u8]) -> [u8; 32] { let mut sha2_res = [0; 32]; let mut sha2 = Sha256::new(); sha2.input(input); sha2_res.copy_from_slice(sha2.result().as_slice()); sha2_res } fn ripemd_160(&self, input: &[u8]) -> [u8; 20] { let mut ripemd_res = [0; 20]; let mut ripemd = Ripemd160::new(); ripemd.input(input); ripemd_res.copy_from_slice(ripemd.result().as_slice()); ripemd_res } } fn test_path( secp: &Secp256k1, seed: &[u8], path: &[ChildNumber], expected_sk: &str, expected_pk: &str, ) { let mut h = BIP32ReferenceHasher::new(); let mut sk = ExtendedPrivKey::new_master(secp, &mut h, seed).unwrap(); let mut pk = ExtendedPubKey::from_private::<BIP32ReferenceHasher>(secp, &sk, &mut h); // Check derivation convenience method for ExtendedPrivKey assert_eq!( &sk.derive_priv(secp, &mut h, path).unwrap().to_string()[..], expected_sk ); // Check derivation convenience method for ExtendedPubKey, should error // appropriately if any ChildNumber is hardened if path.iter().any(|cnum| cnum.is_hardened()) { assert_eq!( pk.derive_pub(secp, &mut h, path), Err(Error::CannotDeriveFromHardenedKey) ); } else { assert_eq!( &pk.derive_pub(secp, &mut h, path).unwrap().to_string()[..], expected_pk ); } // Derive keys, checking hardened and non-hardened derivation one-by-one for &num in path.iter() { sk = sk.ckd_priv(secp, &mut h, num).unwrap(); match num { ChildNumber::Normal { .. } => { let pk2 = pk.ckd_pub(secp, &mut h, num).unwrap(); pk = ExtendedPubKey::from_private::<BIP32ReferenceHasher>(secp, &sk, &mut h); assert_eq!(pk, pk2); } ChildNumber::Hardened { .. } => { assert_eq!( pk.ckd_pub(secp, &mut h, num), Err(Error::CannotDeriveFromHardenedKey) ); pk = ExtendedPubKey::from_private::<BIP32ReferenceHasher>(secp, &sk, &mut h); } } } // Check result against expected base58 assert_eq!(&sk.to_string()[..], expected_sk); assert_eq!(&pk.to_string()[..], expected_pk); // Check decoded base58 against result let decoded_sk = ExtendedPrivKey::from_str(expected_sk); let decoded_pk = ExtendedPubKey::from_str(expected_pk); assert_eq!(Ok(sk), decoded_sk); assert_eq!(Ok(pk), decoded_pk); } #[test] fn test_vector_1() { let secp = Secp256k1::new(); let seed = from_hex("000102030405060708090a0b0c0d0e0f".to_owned()).unwrap(); // m test_path(&secp, &seed, &[], "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi", "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8"); // m/0h test_path(&secp, &seed, &[ChildNumber::from_hardened_idx(0)], "xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7", "xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw"); // m/0h/1 test_path(&secp, &seed, &[ChildNumber::from_hardened_idx(0), ChildNumber::from_normal_idx(1)], "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs", "xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ"); // m/0h/1/2h test_path(&secp, &seed, &[ChildNumber::from_hardened_idx(0), ChildNumber::from_normal_idx(1), ChildNumber::from_hardened_idx(2)], "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM", "xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5"); // m/0h/1/2h/2 test_path(&secp, &seed, &[ChildNumber::from_hardened_idx(0), ChildNumber::from_normal_idx(1), ChildNumber::from_hardened_idx(2), ChildNumber::from_normal_idx(2)], "xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334", "xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV"); // m/0h/1/2h/2/1000000000 test_path(&secp, &seed, &[ChildNumber::from_hardened_idx(0), ChildNumber::from_normal_idx(1), ChildNumber::from_hardened_idx(2), ChildNumber::from_normal_idx(2), ChildNumber::from_normal_idx(1000000000)], "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76", "xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy"); } #[test] fn test_vector_2() { let secp = Secp256k1::new(); let seed = from_hex("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542".to_owned()).unwrap(); // m test_path(&secp, &seed, &[], "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U", "xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB"); // m/0 test_path(&secp, &seed, &[ChildNumber::from_normal_idx(0)], "xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt", "xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH"); // m/0/2147483647h test_path(&secp, &seed, &[ChildNumber::from_normal_idx(0), ChildNumber::from_hardened_idx(2147483647)], "xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9", "xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a"); // m/0/2147483647h/1 test_path(&secp, &seed, &[ChildNumber::from_normal_idx(0), ChildNumber::from_hardened_idx(2147483647), ChildNumber::from_normal_idx(1)], "xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef", "xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon"); // m/0/2147483647h/1/2147483646h test_path(&secp, &seed, &[ChildNumber::from_normal_idx(0), ChildNumber::from_hardened_idx(2147483647), ChildNumber::from_normal_idx(1), ChildNumber::from_hardened_idx(2147483646)], "xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc", "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL"); // m/0/2147483647h/1/2147483646h/2 test_path(&secp, &seed, &[ChildNumber::from_normal_idx(0), ChildNumber::from_hardened_idx(2147483647), ChildNumber::from_normal_idx(1), ChildNumber::from_hardened_idx(2147483646), ChildNumber::from_normal_idx(2)], "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j", "xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt"); } #[test] fn test_vector_3() { let secp = Secp256k1::new(); let seed = from_hex("4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be".to_owned()).unwrap(); // m test_path(&secp, &seed, &[], "xprv9s21ZrQH143K25QhxbucbDDuQ4naNntJRi4KUfWT7xo4EKsHt2QJDu7KXp1A3u7Bi1j8ph3EGsZ9Xvz9dGuVrtHHs7pXeTzjuxBrCmmhgC6", "xpub661MyMwAqRbcEZVB4dScxMAdx6d4nFc9nvyvH3v4gJL378CSRZiYmhRoP7mBy6gSPSCYk6SzXPTf3ND1cZAceL7SfJ1Z3GC8vBgp2epUt13"); // m/0h test_path(&secp, &seed, &[ChildNumber::from_hardened_idx(0)], "xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L", "xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y"); } #[test] #[cfg(all(feature = "serde", feature = "strason"))] pub fn encode_decode_childnumber() { serde_round_trip!(ChildNumber::from_normal_idx(0)); serde_round_trip!(ChildNumber::from_normal_idx(1)); serde_round_trip!(ChildNumber::from_normal_idx((1 << 31) - 1)); serde_round_trip!(ChildNumber::from_hardened_idx(0)); serde_round_trip!(ChildNumber::from_hardened_idx(1)); serde_round_trip!(ChildNumber::from_hardened_idx((1 << 31) - 1)); } }
31.916022
215
0.694329
f8f49a653e0deff2ee561c549f305b5d93e3df67
12,562
use bevy_input::{ keyboard::{KeyCode, KeyboardInput}, mouse::MouseButton, touch::{ForceTouch, TouchInput, TouchPhase}, ElementState, }; use bevy_math::Vec2; pub fn convert_keyboard_input(keyboard_input: &winit::event::KeyboardInput) -> KeyboardInput { KeyboardInput { scan_code: keyboard_input.scancode, state: convert_element_state(keyboard_input.state), key_code: keyboard_input.virtual_keycode.map(convert_virtual_key_code), } } pub fn convert_element_state(element_state: winit::event::ElementState) -> ElementState { match element_state { winit::event::ElementState::Pressed => ElementState::Pressed, winit::event::ElementState::Released => ElementState::Released, } } pub fn convert_mouse_button(mouse_button: winit::event::MouseButton) -> MouseButton { match mouse_button { winit::event::MouseButton::Left => MouseButton::Left, winit::event::MouseButton::Right => MouseButton::Right, winit::event::MouseButton::Middle => MouseButton::Middle, winit::event::MouseButton::Other(val) => MouseButton::Other(val), } } pub fn convert_touch_input(touch_input: winit::event::Touch) -> TouchInput { TouchInput { phase: match touch_input.phase { winit::event::TouchPhase::Started => TouchPhase::Started, winit::event::TouchPhase::Moved => TouchPhase::Moved, winit::event::TouchPhase::Ended => TouchPhase::Ended, winit::event::TouchPhase::Cancelled => TouchPhase::Cancelled, }, position: Vec2::new(touch_input.location.x as f32, touch_input.location.y as f32), force: touch_input.force.map(|f| match f { winit::event::Force::Calibrated { force, max_possible_force, altitude_angle, } => ForceTouch::Calibrated { force, max_possible_force, altitude_angle, }, winit::event::Force::Normalized(x) => ForceTouch::Normalized(x), }), id: touch_input.id, } } pub fn convert_virtual_key_code(virtual_key_code: winit::event::VirtualKeyCode) -> KeyCode { match virtual_key_code { winit::event::VirtualKeyCode::Key1 => KeyCode::Key1, winit::event::VirtualKeyCode::Key2 => KeyCode::Key2, winit::event::VirtualKeyCode::Key3 => KeyCode::Key3, winit::event::VirtualKeyCode::Key4 => KeyCode::Key4, winit::event::VirtualKeyCode::Key5 => KeyCode::Key5, winit::event::VirtualKeyCode::Key6 => KeyCode::Key6, winit::event::VirtualKeyCode::Key7 => KeyCode::Key7, winit::event::VirtualKeyCode::Key8 => KeyCode::Key8, winit::event::VirtualKeyCode::Key9 => KeyCode::Key9, winit::event::VirtualKeyCode::Key0 => KeyCode::Key0, winit::event::VirtualKeyCode::A => KeyCode::A, winit::event::VirtualKeyCode::B => KeyCode::B, winit::event::VirtualKeyCode::C => KeyCode::C, winit::event::VirtualKeyCode::D => KeyCode::D, winit::event::VirtualKeyCode::E => KeyCode::E, winit::event::VirtualKeyCode::F => KeyCode::F, winit::event::VirtualKeyCode::G => KeyCode::G, winit::event::VirtualKeyCode::H => KeyCode::H, winit::event::VirtualKeyCode::I => KeyCode::I, winit::event::VirtualKeyCode::J => KeyCode::J, winit::event::VirtualKeyCode::K => KeyCode::K, winit::event::VirtualKeyCode::L => KeyCode::L, winit::event::VirtualKeyCode::M => KeyCode::M, winit::event::VirtualKeyCode::N => KeyCode::N, winit::event::VirtualKeyCode::O => KeyCode::O, winit::event::VirtualKeyCode::P => KeyCode::P, winit::event::VirtualKeyCode::Q => KeyCode::Q, winit::event::VirtualKeyCode::R => KeyCode::R, winit::event::VirtualKeyCode::S => KeyCode::S, winit::event::VirtualKeyCode::T => KeyCode::T, winit::event::VirtualKeyCode::U => KeyCode::U, winit::event::VirtualKeyCode::V => KeyCode::V, winit::event::VirtualKeyCode::W => KeyCode::W, winit::event::VirtualKeyCode::X => KeyCode::X, winit::event::VirtualKeyCode::Y => KeyCode::Y, winit::event::VirtualKeyCode::Z => KeyCode::Z, winit::event::VirtualKeyCode::Escape => KeyCode::Escape, winit::event::VirtualKeyCode::F1 => KeyCode::F1, winit::event::VirtualKeyCode::F2 => KeyCode::F2, winit::event::VirtualKeyCode::F3 => KeyCode::F3, winit::event::VirtualKeyCode::F4 => KeyCode::F4, winit::event::VirtualKeyCode::F5 => KeyCode::F5, winit::event::VirtualKeyCode::F6 => KeyCode::F6, winit::event::VirtualKeyCode::F7 => KeyCode::F7, winit::event::VirtualKeyCode::F8 => KeyCode::F8, winit::event::VirtualKeyCode::F9 => KeyCode::F9, winit::event::VirtualKeyCode::F10 => KeyCode::F10, winit::event::VirtualKeyCode::F11 => KeyCode::F11, winit::event::VirtualKeyCode::F12 => KeyCode::F12, winit::event::VirtualKeyCode::F13 => KeyCode::F13, winit::event::VirtualKeyCode::F14 => KeyCode::F14, winit::event::VirtualKeyCode::F15 => KeyCode::F15, winit::event::VirtualKeyCode::F16 => KeyCode::F16, winit::event::VirtualKeyCode::F17 => KeyCode::F17, winit::event::VirtualKeyCode::F18 => KeyCode::F18, winit::event::VirtualKeyCode::F19 => KeyCode::F19, winit::event::VirtualKeyCode::F20 => KeyCode::F20, winit::event::VirtualKeyCode::F21 => KeyCode::F21, winit::event::VirtualKeyCode::F22 => KeyCode::F22, winit::event::VirtualKeyCode::F23 => KeyCode::F23, winit::event::VirtualKeyCode::F24 => KeyCode::F24, winit::event::VirtualKeyCode::Snapshot => KeyCode::Snapshot, winit::event::VirtualKeyCode::Scroll => KeyCode::Scroll, winit::event::VirtualKeyCode::Pause => KeyCode::Pause, winit::event::VirtualKeyCode::Insert => KeyCode::Insert, winit::event::VirtualKeyCode::Home => KeyCode::Home, winit::event::VirtualKeyCode::Delete => KeyCode::Delete, winit::event::VirtualKeyCode::End => KeyCode::End, winit::event::VirtualKeyCode::PageDown => KeyCode::PageDown, winit::event::VirtualKeyCode::PageUp => KeyCode::PageUp, winit::event::VirtualKeyCode::Left => KeyCode::Left, winit::event::VirtualKeyCode::Up => KeyCode::Up, winit::event::VirtualKeyCode::Right => KeyCode::Right, winit::event::VirtualKeyCode::Down => KeyCode::Down, winit::event::VirtualKeyCode::Back => KeyCode::Back, winit::event::VirtualKeyCode::Return => KeyCode::Return, winit::event::VirtualKeyCode::Space => KeyCode::Space, winit::event::VirtualKeyCode::Compose => KeyCode::Compose, winit::event::VirtualKeyCode::Caret => KeyCode::Caret, winit::event::VirtualKeyCode::Numlock => KeyCode::Numlock, winit::event::VirtualKeyCode::Numpad0 => KeyCode::Numpad0, winit::event::VirtualKeyCode::Numpad1 => KeyCode::Numpad1, winit::event::VirtualKeyCode::Numpad2 => KeyCode::Numpad2, winit::event::VirtualKeyCode::Numpad3 => KeyCode::Numpad3, winit::event::VirtualKeyCode::Numpad4 => KeyCode::Numpad4, winit::event::VirtualKeyCode::Numpad5 => KeyCode::Numpad5, winit::event::VirtualKeyCode::Numpad6 => KeyCode::Numpad6, winit::event::VirtualKeyCode::Numpad7 => KeyCode::Numpad7, winit::event::VirtualKeyCode::Numpad8 => KeyCode::Numpad8, winit::event::VirtualKeyCode::Numpad9 => KeyCode::Numpad9, winit::event::VirtualKeyCode::AbntC1 => KeyCode::AbntC1, winit::event::VirtualKeyCode::AbntC2 => KeyCode::AbntC2, winit::event::VirtualKeyCode::NumpadAdd => KeyCode::NumpadAdd, winit::event::VirtualKeyCode::Apostrophe => KeyCode::Apostrophe, winit::event::VirtualKeyCode::Apps => KeyCode::Apps, winit::event::VirtualKeyCode::Asterisk => KeyCode::Asterix, winit::event::VirtualKeyCode::Plus => KeyCode::Plus, winit::event::VirtualKeyCode::At => KeyCode::At, winit::event::VirtualKeyCode::Ax => KeyCode::Ax, winit::event::VirtualKeyCode::Backslash => KeyCode::Backslash, winit::event::VirtualKeyCode::Calculator => KeyCode::Calculator, winit::event::VirtualKeyCode::Capital => KeyCode::Capital, winit::event::VirtualKeyCode::Colon => KeyCode::Colon, winit::event::VirtualKeyCode::Comma => KeyCode::Comma, winit::event::VirtualKeyCode::Convert => KeyCode::Convert, winit::event::VirtualKeyCode::NumpadDecimal => KeyCode::NumpadDecimal, winit::event::VirtualKeyCode::NumpadDivide => KeyCode::NumpadDivide, winit::event::VirtualKeyCode::Equals => KeyCode::Equals, winit::event::VirtualKeyCode::Grave => KeyCode::Grave, winit::event::VirtualKeyCode::Kana => KeyCode::Kana, winit::event::VirtualKeyCode::Kanji => KeyCode::Kanji, winit::event::VirtualKeyCode::LAlt => KeyCode::LAlt, winit::event::VirtualKeyCode::LBracket => KeyCode::LBracket, winit::event::VirtualKeyCode::LControl => KeyCode::LControl, winit::event::VirtualKeyCode::LShift => KeyCode::LShift, winit::event::VirtualKeyCode::LWin => KeyCode::LWin, winit::event::VirtualKeyCode::Mail => KeyCode::Mail, winit::event::VirtualKeyCode::MediaSelect => KeyCode::MediaSelect, winit::event::VirtualKeyCode::MediaStop => KeyCode::MediaStop, winit::event::VirtualKeyCode::Minus => KeyCode::Minus, winit::event::VirtualKeyCode::NumpadMultiply => KeyCode::NumpadMultiply, winit::event::VirtualKeyCode::Mute => KeyCode::Mute, winit::event::VirtualKeyCode::MyComputer => KeyCode::MyComputer, winit::event::VirtualKeyCode::NavigateForward => KeyCode::NavigateForward, winit::event::VirtualKeyCode::NavigateBackward => KeyCode::NavigateBackward, winit::event::VirtualKeyCode::NextTrack => KeyCode::NextTrack, winit::event::VirtualKeyCode::NoConvert => KeyCode::NoConvert, winit::event::VirtualKeyCode::NumpadComma => KeyCode::NumpadComma, winit::event::VirtualKeyCode::NumpadEnter => KeyCode::NumpadEnter, winit::event::VirtualKeyCode::NumpadEquals => KeyCode::NumpadEquals, winit::event::VirtualKeyCode::OEM102 => KeyCode::OEM102, winit::event::VirtualKeyCode::Period => KeyCode::Period, winit::event::VirtualKeyCode::PlayPause => KeyCode::PlayPause, winit::event::VirtualKeyCode::Power => KeyCode::Power, winit::event::VirtualKeyCode::PrevTrack => KeyCode::PrevTrack, winit::event::VirtualKeyCode::RAlt => KeyCode::RAlt, winit::event::VirtualKeyCode::RBracket => KeyCode::RBracket, winit::event::VirtualKeyCode::RControl => KeyCode::RControl, winit::event::VirtualKeyCode::RShift => KeyCode::RShift, winit::event::VirtualKeyCode::RWin => KeyCode::RWin, winit::event::VirtualKeyCode::Semicolon => KeyCode::Semicolon, winit::event::VirtualKeyCode::Slash => KeyCode::Slash, winit::event::VirtualKeyCode::Sleep => KeyCode::Sleep, winit::event::VirtualKeyCode::Stop => KeyCode::Stop, winit::event::VirtualKeyCode::NumpadSubtract => KeyCode::NumpadSubtract, winit::event::VirtualKeyCode::Sysrq => KeyCode::Sysrq, winit::event::VirtualKeyCode::Tab => KeyCode::Tab, winit::event::VirtualKeyCode::Underline => KeyCode::Underline, winit::event::VirtualKeyCode::Unlabeled => KeyCode::Unlabeled, winit::event::VirtualKeyCode::VolumeDown => KeyCode::VolumeDown, winit::event::VirtualKeyCode::VolumeUp => KeyCode::VolumeUp, winit::event::VirtualKeyCode::Wake => KeyCode::Wake, winit::event::VirtualKeyCode::WebBack => KeyCode::WebBack, winit::event::VirtualKeyCode::WebFavorites => KeyCode::WebFavorites, winit::event::VirtualKeyCode::WebForward => KeyCode::WebForward, winit::event::VirtualKeyCode::WebHome => KeyCode::WebHome, winit::event::VirtualKeyCode::WebRefresh => KeyCode::WebRefresh, winit::event::VirtualKeyCode::WebSearch => KeyCode::WebSearch, winit::event::VirtualKeyCode::WebStop => KeyCode::WebStop, winit::event::VirtualKeyCode::Yen => KeyCode::Yen, winit::event::VirtualKeyCode::Copy => KeyCode::Copy, winit::event::VirtualKeyCode::Paste => KeyCode::Paste, winit::event::VirtualKeyCode::Cut => KeyCode::Cut, } }
55.831111
94
0.650931
3912adb8c474a6f070696690d011d0b8856c8f07
752
#[allow(dead_code)] #[allow(unused_imports)] #[allow(unused_variables)] #[allow(unused_must_use)] // Sum of the even fibonacci numbers below 4 millions pub fn evenfib() { let max = 4*i64::pow(10, 6); let mut fib = vec![1,2]; let mut sum = fib[1]; let mut indx = fib.len()-1; while fib[indx] < max { let i = fib.len()-1; let j = fib.len()-2; indx = i; let c = fib[i]+fib[j]; fib.push(c); //check whether the push was successful let tail_fib = &fib[j..=i]; //println!("{:?}", tail_fib); if c >= max { break; } if c%2 == 0 { sum += c} else { sum += 0} } println!("The sum of the even Fibonacci numbers smaller than 4 millions is = {}", sum); }
22.787879
91
0.537234
1e5f29d548beae4f0538f2c4e12b1a4b4c6d1712
5,242
use std::ptr; use std::sync::Arc; use libc::c_int; use crate::client::conn; use crate::rt::Executor as _; use super::error::hyper_code; use super::http_types::{hyper_request, hyper_response}; use super::io::hyper_io; use super::task::{hyper_executor, hyper_task, hyper_task_return_type, AsTaskType, WeakExec}; /// An options builder to configure an HTTP client connection. pub struct hyper_clientconn_options { builder: conn::Builder, /// Use a `Weak` to prevent cycles. exec: WeakExec, } /// An HTTP client connection handle. /// /// These are used to send a request on a single connection. It's possible to /// send multiple requests on a single connection, such as when HTTP/1 /// keep-alive or HTTP/2 is used. pub struct hyper_clientconn { tx: conn::SendRequest<crate::Body>, } // ===== impl hyper_clientconn ===== ffi_fn! { /// Starts an HTTP client connection handshake using the provided IO transport /// and options. /// /// Both the `io` and the `options` are consumed in this function call. /// /// The returned `hyper_task *` must be polled with an executor until the /// handshake completes, at which point the value can be taken. fn hyper_clientconn_handshake(io: *mut hyper_io, options: *mut hyper_clientconn_options) -> *mut hyper_task { let options = non_null! { Box::from_raw(options) ?= ptr::null_mut() }; let io = non_null! { Box::from_raw(io) ?= ptr::null_mut() }; Box::into_raw(hyper_task::boxed(async move { options.builder.handshake::<_, crate::Body>(io) .await .map(|(tx, conn)| { options.exec.execute(Box::pin(async move { let _ = conn.await; })); hyper_clientconn { tx } }) })) } ?= std::ptr::null_mut() } ffi_fn! { /// Send a request on the client connection. /// /// Returns a task that needs to be polled until it is ready. When ready, the /// task yields a `hyper_response *`. fn hyper_clientconn_send(conn: *mut hyper_clientconn, req: *mut hyper_request) -> *mut hyper_task { let mut req = non_null! { Box::from_raw(req) ?= ptr::null_mut() }; // Update request with original-case map of headers req.finalize_request(); let fut = non_null! { &mut *conn ?= ptr::null_mut() }.tx.send_request(req.0); let fut = async move { fut.await.map(hyper_response::wrap) }; Box::into_raw(hyper_task::boxed(fut)) } ?= std::ptr::null_mut() } ffi_fn! { /// Free a `hyper_clientconn *`. fn hyper_clientconn_free(conn: *mut hyper_clientconn) { drop(non_null! { Box::from_raw(conn) ?= () }); } } unsafe impl AsTaskType for hyper_clientconn { fn as_task_type(&self) -> hyper_task_return_type { hyper_task_return_type::HYPER_TASK_CLIENTCONN } } // ===== impl hyper_clientconn_options ===== ffi_fn! { /// Creates a new set of HTTP clientconn options to be used in a handshake. fn hyper_clientconn_options_new() -> *mut hyper_clientconn_options { let mut builder = conn::Builder::new(); builder.http1_preserve_header_case(true); Box::into_raw(Box::new(hyper_clientconn_options { builder, exec: WeakExec::new(), })) } ?= std::ptr::null_mut() } ffi_fn! { /// Free a `hyper_clientconn_options *`. fn hyper_clientconn_options_free(opts: *mut hyper_clientconn_options) { drop(non_null! { Box::from_raw(opts) ?= () }); } } ffi_fn! { /// Set the client background task executor. /// /// This does not consume the `options` or the `exec`. fn hyper_clientconn_options_exec(opts: *mut hyper_clientconn_options, exec: *const hyper_executor) { let opts = non_null! { &mut *opts ?= () }; let exec = non_null! { Arc::from_raw(exec) ?= () }; let weak_exec = hyper_executor::downgrade(&exec); std::mem::forget(exec); opts.builder.executor(weak_exec.clone()); opts.exec = weak_exec; } } ffi_fn! { /// Set the whether to use HTTP2. /// /// Pass `0` to disable, `1` to enable. fn hyper_clientconn_options_http2(opts: *mut hyper_clientconn_options, enabled: c_int) -> hyper_code { #[cfg(feature = "http2")] { let opts = non_null! { &mut *opts ?= hyper_code::HYPERE_INVALID_ARG }; opts.builder.http2_only(enabled != 0); hyper_code::HYPERE_OK } #[cfg(not(feature = "http2"))] { drop(opts); drop(enabled); hyper_code::HYPERE_FEATURE_NOT_ENABLED } } } ffi_fn! { /// Set the whether to include a copy of the raw headers in responses /// received on this connection. /// /// Pass `0` to disable, `1` to enable. /// /// If enabled, see `hyper_response_headers_raw()` for usage. fn hyper_clientconn_options_headers_raw(opts: *mut hyper_clientconn_options, enabled: c_int) -> hyper_code { let opts = non_null! { &mut *opts ?= hyper_code::HYPERE_INVALID_ARG }; opts.builder.http1_headers_raw(enabled != 0); hyper_code::HYPERE_OK } }
32.159509
113
0.61694
e669a7a26c92414580ef50d6f82fdf91fb464032
408
impl Solution { pub fn flip_and_invert_image(a: Vec<Vec<i32>>) -> Vec<Vec<i32>> { let mut a = a.clone(); a.iter() .map(|x| { x.clone() .iter() .map(|y| if y == &0 { 1i32 } else { 0i32 }) .rev() .collect::<Vec<i32>>() }) .collect::<Vec<Vec<i32>>>() } }
27.2
69
0.345588
7119e7aff0fc151ad59330c2dea7f7df3642f286
251
use std::io; pub(super) fn run() -> io::Result<()> { { println!("Year 2019 Day 17 Part 1"); println!("Unimplemented"); } { println!("Year 2019 Day 17 Part 2"); println!("Unimplemented"); } Ok(()) }
17.928571
44
0.482072
481fee282e039b8c4df4a54cf5ed9bed7d70b5e1
1,346
use rapier2d::prelude::*; use rapier_testbed2d::Testbed; pub fn init_world(testbed: &mut Testbed) { /* * World */ let mut bodies = RigidBodySet::new(); let mut colliders = ColliderSet::new(); let impulse_joints = ImpulseJointSet::new(); let multibody_joints = MultibodyJointSet::new(); /* * Create the balls */ let num = 10; let rad = 0.2; let subdiv = 1.0 / (num as f32); for i in 0usize..num { let (x, y) = (i as f32 * subdiv * std::f32::consts::PI * 2.0).sin_cos(); // Build the rigid body. let rb = RigidBodyBuilder::new_dynamic() .translation(vector![x, y]) .linvel(vector![x * 10.0, y * 10.0]) .angvel(100.0) .linear_damping((i + 1) as f32 * subdiv * 10.0) .angular_damping((num - i) as f32 * subdiv * 10.0) .build(); let rb_handle = bodies.insert(rb); // Build the collider. let co = ColliderBuilder::cuboid(rad, rad).build(); colliders.insert_with_parent(co, rb_handle, &mut bodies); } /* * Set up the testbed. */ testbed.set_world_with_params( bodies, colliders, impulse_joints, multibody_joints, Vector::zeros(), (), ); testbed.look_at(point![3.0, 2.0], 50.0); }
25.884615
80
0.543834
79ec0bd1ed8b303b6d849b4b4d2e75187bdcadb2
11,117
extern crate cortex; extern crate rustusb = "usb"; use std::intrinsics::abort; use std::ptr::set_memory; use std::rt::global_heap::malloc_raw; use cortex::regs::{store, load, set, wait_for}; use sim::{enable_clock, USBOTG}; use sim::{select_usb_source}; use rustusb::usb::{UsbPeripheral, UsbModule}; use rustusb::usb::{EndpointType}; use rustusb::stream::StreamHandler; mod sim; static mut USB_PERIPHERAL: Option<FreescaleUsb> = None; static BASE_USB: u32 = 0x4007_2000; static USB_USBTRC0: u32 = BASE_USB + 0x010C; static USB_USBCTRL: u32 = BASE_USB + 0x0100; static USB_CTL: u32 = BASE_USB + 0x0094; static USB_ADDR: u32 = BASE_USB + 0x0098; static USB_CONTROL: u32 = BASE_USB + 0x0108; static USB_INTEN: u32 = BASE_USB + 0x0084; static USB_STAT: u32 = BASE_USB + 0x0090; static USB_ISTAT: *mut u8 = (BASE_USB + 0x0080) as *mut u8; static USB_ERRSTAT: u32 = BASE_USB + 0x0088; static USB_OTGISTAT: u32 = BASE_USB + 0x0010; static USB_BDTPAGE1: u32 = BASE_USB + 0x009C; static USB_BDTPAGE2: u32 = BASE_USB + 0x00B0; static USB_BDTPAGE3: u32 = BASE_USB + 0x00B4; static USB_ENDPT0: u32 = BASE_USB + 0x00C0; pub enum UsbInt { USBRSTEN = 0x01, ERROREN = 0x02, SOFTOKEN = 0x04, TOKDNEEN = 0x08, SLEEPEN = 0x10, RESUMEEN = 0x20, ATTACHEN = 0x40, STALLEN = 0x80 } // fn zero_bdt() { // } // // fn set_bdt() { // // Need a 512 byte aligned memory // let addr: u32 = 0x00; // This should be a pointer to the BDT // unsafe { // store(USB_BDTPAGE1 as *mut u8, (addr << 8) as u8); // store(USB_BDTPAGE2 as *mut u8, (addr << 16) as u8); // store(USB_BDTPAGE3 as *mut u8, (addr << 24) as u8); // } // } // // // /// Read PID from BDT // pub fn get_pid(ep: u8) { // // } // // /// Sets the STALL flag for ENDPTx register // pub fn stall_ep(ep: u32) { // if ep <= 15 { // let addr = USB_ENDPT0 + ep*4; // unsafe { // set(addr as *mut u8, 0x02); // } // } // } // // /// Clears the STALL flag for ENDPTx register // pub fn unstall_ep(ep: u32) { // if ep <= 15 { // let addr = USB_ENDPT0 + ep*4; // unsafe { // clear(addr as *mut u8, 0x02); // } // } // } // // /// Enables the endpoint (also unstalls) // pub fn enable_ep(ep: u32, control: bool, handshake: bool) { // if ep <= 15 { // let addr = USB_ENDPT0 + ep*4; // let val = 0x0c; // | // // (if !control 0x10 else 0) | // // (if handshake 0x01 else 0) // unsafe { // store(addr as *mut u8, val as u8); // } // } // } // // /// Resume token processing // pub fn resume() { // unsafe { // clear(USB_CTL as *mut u8, 0x20); // } // } // // pub fn set_interrupt(val: UsbInt) { // unsafe { // set(USB_INTEN as *mut u8, val as u8); // } // } // pub struct FreescaleUsb { bdt: *mut u32, max_ep: uint, ping: [bool, ..32], } impl FreescaleUsb { /// Create a new instance /// Specify number of endpoints including EP0 pub fn new(max_endpoint: uint) -> &'static mut FreescaleUsb { let size = if max_endpoint > 15 { 512 } else { max_endpoint * 32 }; // Need 512byte aligned memory for BDT // TODO: Need to fix up alignment. Maybe just static assignment? let ptr = unsafe { malloc_raw(512) }; let this =FreescaleUsb { bdt: ptr as *mut u32, max_ep: max_endpoint, ping: [false, ..32], }; unsafe { USB_PERIPHERAL = Some(this); } FreescaleUsb::get() } pub fn get() -> &'static mut FreescaleUsb { unsafe { match USB_PERIPHERAL { Some(ref mut module) => module, None => abort() } } } fn get_bdt_offset(ep: uint, is_tx: bool, is_odd: bool) -> uint { 32*ep + (if is_tx { 16 } else { 0 } ) + (if is_odd { 8 } else { 0 } ) } pub fn get_bdt_setting(&self, ep: uint, is_tx: bool, is_odd: bool) -> u32 { let offset = FreescaleUsb::get_bdt_offset(ep, is_tx, is_odd); let addr = ((self.bdt as u32) + offset as u32) as *mut u32; unsafe { load(addr) } } pub fn set_bdt_setting(&self, ep: uint, is_tx: bool, is_odd: bool, val: u32) { let offset = FreescaleUsb::get_bdt_offset(ep, is_tx, is_odd); let addr = ((self.bdt as u32) + offset as u32) as *mut u32; unsafe { store(addr, val); } } pub fn get_bdt_address(&self, ep: uint, is_tx: bool, is_odd: bool) -> u32 { let offset = FreescaleUsb::get_bdt_offset(ep, is_tx, is_odd) + 4; let addr = ((self.bdt as u32) + offset as u32) as *mut u32; unsafe { load(addr) } } pub fn set_bdt_address(&self, ep: uint, is_tx: bool, is_odd: bool, val: u32) { let offset = FreescaleUsb::get_bdt_offset(ep, is_tx, is_odd) + 4; let addr = ((self.bdt as u32) + offset as u32) as *mut u32; unsafe { store(addr, val); } } fn usb_reset_hard(&self) { unsafe { let addr: *mut u8 = (BASE_USB + 0x010C) as *mut u8; store(addr, 0x80); wait_for(addr as *u8, 0x80, 0x00); } } fn set_interrupts(&self, val: u8) { unsafe { store(USB_INTEN as *mut u8, val as u8); } } } // TODO: Implement Drop trait to free the bdt impl UsbPeripheral for FreescaleUsb { /// Enables the USB peripheral /// Selects clock source, resets peripheral hardware, /// allocates needed memory, runs software usb reset fn init(&self) { // Enable the SIM clock for USB enable_clock(USBOTG); // Set the USB clock source to internal select_usb_source(true); // Cycle the USB module through a hard reset self.usb_reset_hard(); // Load the address of the BDT unsafe { let addr = self.bdt as u32; store(USB_BDTPAGE1 as *mut u8, (addr << 8) as u8); store(USB_BDTPAGE2 as *mut u8, (addr << 16) as u8); store(USB_BDTPAGE3 as *mut u8, (addr << 24) as u8); } // Enable the transceiver and disable pulldowns unsafe { store(USB_USBCTRL as *mut u8, 0x00); } // Run the software USB reset self.reset(); // Enable interrupts for USBRST, TOKDNE and STALL self.set_interrupts(STALLEN as u8 | TOKDNEEN as u8 | USBRSTEN as u8); } /// Attaches the device to the bus /// Enables relevant pullup fn attach(&self) { // Enable the DP pullup unsafe { set(USB_CONTROL as *mut u8, 0x10); } } /// Moves peripheral to default state /// Reset address, reset all endpoints, /// clear any status flags fn reset(&self) { unsafe { // Disable and suspend USB module set(USB_CTL as *mut u8, 0x22); // TODO: Reset pingpong register // Clear any remaining status flags store(USB_ISTAT as *mut u8, 0xFF); store(USB_ERRSTAT as *mut u8, 0xFF); store(USB_OTGISTAT as *mut u8, 0xFF); // Zero out BDT set_memory(self.bdt as *mut u8, 0, self.max_ep*32); // Reset address self.set_address(0x00); // Enable USB module store(USB_CTL as *mut u8, 0x01); } } fn poll(&self) { USB0_Handler(); } fn max_endpoints(&self) -> uint { 16 } fn queue_next(&mut self, ep: uint, is_tx: bool, stream: &StreamHandler) { // Get pingpong status let ping_index = ep*2 + if is_tx { 1 } else { 0 }; let odd = self.ping[ping_index]; // Check BDT is free let stat = self.get_bdt_setting(ep, is_tx, odd); if stat & 0x80 > 0 { unsafe { abort(); } } // Transfer StreamHandler into BDT let addr = stream.address() as u32; self.set_bdt_address(ep, is_tx, odd, addr); let len = stream.len(); let data1 = if stream.data1() { 1 } else { 0 }; // Activate BDT let val = ((len & 0x3FF) << 16) | 0x88 | (data1 << 6); let stat = self.set_bdt_setting(ep, is_tx, odd, val as u32); // Swap pingpong self.ping[ping_index] = !odd; } fn set_address(&self, addr: u8) { unsafe { store(USB_ADDR as *mut u8, addr); } } fn ep_enable(&self, ep: uint, typ: EndpointType) { // Make sure ep is in range if ep > 15 { unsafe { abort(); } } // Work out flags required for type let val = match typ { rustusb::usb::Control => 0x0D, rustusb::usb::TxOnly => 0x15, rustusb::usb::RxOnly => 0x19, rustusb::usb::TxRx => 0x1D, rustusb::usb::IsochronousTx => 0x14, rustusb::usb::IsochronousRx => 0x18 }; // Set enpoint let addr = USB_ENDPT0 + (ep as u32)*4; unsafe { store(addr as *mut u8, val as u8); } } fn ep_stall(&self, ep: uint) { } fn ep_unstall(&self, ep: uint) { } } /// Handler for usb interrupts /// Uses following regs /// ISTAT - To see which flasg are set and clear them after /// STAT - To get info on completed transaction /// Also reads from the BDT specified by STAT register #[no_mangle] pub extern "C" fn USB0_Handler() { // Check module has been initialised (needed?) if !UsbModule::is_ready() { return; } // Get interrupt status let istat = unsafe { load(USB_ISTAT) }; // Get module let module = UsbModule::get(); // On usbrst call reset and return if istat & 1 > 0 { module.on_reset(); return; } // On stall call stall if istat & 0x80 > 0 { module.on_stall(); } // On tokdne call out to handle_transaction // TODO: Will probably need to work differently for isochronous stuff if istat & 0x08 > 0 { // Get token info let stat = unsafe { load(USB_STAT as *mut u8) as uint }; let ep = stat >> 4; let tx = (stat & 0x08) > 0; let odd = (stat & 0x04) > 0; let this = FreescaleUsb::get(); let bdt_info = this.get_bdt_setting(ep, tx, odd); let pid = (bdt_info >> 2) & 0x0F; let len = (bdt_info >> 16) & 0x3FF; module.on_token(ep, tx, pid as uint, len as uint); // Update CTL after processing a SETUP token (will have been paused) if pid == 0x0D { unsafe { store(USB_CTL as *mut u8, 0x01); } } } // Clear flags // TODO: Does this need to be more complicated? unsafe { store(USB_ISTAT, istat); } }
27.723192
82
0.538635
8abb923af30b65a55c351f762c62294f79a9e1c0
39,364
use std::fmt::{self, Display, Formatter}; use std::iter::ExactSizeIterator; use std::slice::Iter; use std::vec::IntoIter; use std::borrow::Cow; use std::prelude::v1::*; use serde::{self, Deserialize, Deserializer}; use serde::de::{self, DeserializeSeed, IntoDeserializer, SeqAccess, Unexpected, Visitor}; use crate::{Integer, IntPriv, Utf8String, Utf8StringRef, Value, ValueRef}; use super::{Error, ValueExt}; use crate::MSGPACK_EXT_STRUCT_NAME; pub fn from_value<T>(val: Value) -> Result<T, Error> where T: for<'de> Deserialize<'de> { deserialize_from(val) } pub fn deserialize_from<'de, T, D>(val: D) -> Result<T, Error> where T: Deserialize<'de>, D: Deserializer<'de, Error = Error> { Deserialize::deserialize(val) } impl de::Error for Error { fn custom<T: Display>(msg: T) -> Self { Error::Syntax(format!("{}", msg)) } } impl<'de> Deserialize<'de> for Value { #[inline] fn deserialize<D>(de: D) -> Result<Self, D::Error> where D: de::Deserializer<'de> { struct ValueVisitor; impl<'de> serde::de::Visitor<'de> for ValueVisitor { type Value = Value; fn expecting(&self, fmt: &mut Formatter<'_>) -> Result<(), fmt::Error> { "any valid MessagePack value".fmt(fmt) } #[inline] fn visit_some<D>(self, de: D) -> Result<Value, D::Error> where D: de::Deserializer<'de> { Deserialize::deserialize(de) } #[inline] fn visit_none<E>(self) -> Result<Value, E> { Ok(Value::Nil) } #[inline] fn visit_unit<E>(self) -> Result<Value, E> { Ok(Value::Nil) } #[inline] fn visit_bool<E>(self, value: bool) -> Result<Value, E> { Ok(Value::Boolean(value)) } #[inline] fn visit_u64<E>(self, value: u64) -> Result<Value, E> { Ok(Value::from(value)) } #[inline] fn visit_i64<E>(self, value: i64) -> Result<Value, E> { Ok(Value::from(value)) } #[inline] fn visit_f32<E>(self, value: f32) -> Result<Value, E> { Ok(Value::F32(value)) } #[inline] fn visit_f64<E>(self, value: f64) -> Result<Value, E> { Ok(Value::F64(value)) } #[inline] fn visit_string<E>(self, value: String) -> Result<Value, E> { Ok(Value::String(Utf8String::from(value))) } #[inline] fn visit_str<E>(self, value: &str) -> Result<Value, E> where E: de::Error { self.visit_string(String::from(value)) } #[inline] fn visit_seq<V>(self, mut visitor: V) -> Result<Value, V::Error> where V: SeqAccess<'de> { let mut vec = Vec::new(); while let Some(elem) = visitor.next_element()? { vec.push(elem); } Ok(Value::Array(vec)) } #[inline] fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> where E: de::Error { Ok(Value::Binary(v.to_owned())) } #[inline] fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> where E: de::Error { Ok(Value::Binary(v)) } #[inline] fn visit_map<V>(self, mut visitor: V) -> Result<Value, V::Error> where V: de::MapAccess<'de> { let mut pairs = vec![]; while let Some(key) = visitor.next_key()? { let val = visitor.next_value()?; pairs.push((key, val)); } Ok(Value::Map(pairs)) } #[inline] fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { struct ExtValueVisitor; impl<'de> serde::de::Visitor<'de> for ExtValueVisitor { type Value = Value; fn expecting(&self, fmt: &mut Formatter<'_>) -> Result<(), fmt::Error> { "a valid MessagePack Ext".fmt(fmt) } #[inline] fn visit_seq<V>(self, mut seq: V) -> Result<Value, V::Error> where V: SeqAccess<'de> { let tag = seq.next_element()? .ok_or_else(|| de::Error::invalid_length(0, &self))?; let bytes: serde_bytes::ByteBuf = seq.next_element()? .ok_or_else(|| de::Error::invalid_length(1, &self))?; Ok(Value::Ext(tag, bytes.to_vec())) } } deserializer.deserialize_tuple(2, ExtValueVisitor) } } de.deserialize_any(ValueVisitor) } } impl<'de> Deserialize<'de> for ValueRef<'de> { #[inline] fn deserialize<D>(de: D) -> Result<Self, D::Error> where D: Deserializer<'de> { struct ValueVisitor; impl<'de> de::Visitor<'de> for ValueVisitor { type Value = ValueRef<'de>; fn expecting(&self, fmt: &mut Formatter<'_>) -> Result<(), fmt::Error> { "any valid MessagePack value".fmt(fmt) } #[inline] fn visit_some<D>(self, de: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de> { Deserialize::deserialize(de) } #[inline] fn visit_none<E>(self) -> Result<Self::Value, E> { Ok(ValueRef::Nil) } #[inline] fn visit_unit<E>(self) -> Result<Self::Value, E> { Ok(ValueRef::Nil) } #[inline] fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E> { Ok(ValueRef::Boolean(value)) } #[inline] fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> { Ok(ValueRef::from(value)) } #[inline] fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> { Ok(ValueRef::from(value)) } #[inline] fn visit_f32<E>(self, value: f32) -> Result<Self::Value, E> { Ok(ValueRef::F32(value)) } #[inline] fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E> { Ok(ValueRef::F64(value)) } #[inline] fn visit_borrowed_str<E>(self, value: &'de str) -> Result<Self::Value, E> where E: de::Error { Ok(ValueRef::String(Utf8StringRef::from(value))) } #[inline] fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> where V: SeqAccess<'de> { let mut vec = Vec::new(); while let Some(elem) = visitor.next_element()? { vec.push(elem); } Ok(ValueRef::Array(vec)) } #[inline] fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E> where E: de::Error { Ok(ValueRef::Binary(v)) } #[inline] fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> where V: de::MapAccess<'de> { let mut vec = Vec::new(); while let Some(key) = visitor.next_key()? { let val = visitor.next_value()?; vec.push((key, val)); } Ok(ValueRef::Map(vec)) } #[inline] fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { struct ExtValueRefVisitor; impl<'de> serde::de::Visitor<'de> for ExtValueRefVisitor { type Value = ValueRef<'de>; fn expecting(&self, fmt: &mut Formatter<'_>) -> Result<(), fmt::Error> { "a valid MessagePack Ext".fmt(fmt) } #[inline] fn visit_seq<V>(self, mut seq: V) -> Result<ValueRef<'de>, V::Error> where V: SeqAccess<'de> { let tag = seq.next_element()? .ok_or_else(|| de::Error::invalid_length(0, &"invalid ext sequence"))?; let bytes: &[u8] = seq.next_element()? .ok_or_else(|| de::Error::invalid_length(1, &"invalid ext sequence"))?; Ok(ValueRef::Ext(tag, bytes)) } } deserializer.deserialize_tuple(2, ExtValueRefVisitor) } } de.deserialize_any(ValueVisitor) } } impl<'de> Deserializer<'de> for Value { type Error = Error; #[inline] fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { match self { Value::Nil => visitor.visit_unit(), Value::Boolean(v) => visitor.visit_bool(v), Value::Integer(Integer { n }) => { match n { IntPriv::PosInt(v) => visitor.visit_u64(v), IntPriv::NegInt(v) => visitor.visit_i64(v) } } Value::F32(v) => visitor.visit_f32(v), Value::F64(v) => visitor.visit_f64(v), Value::String(v) => { match v.s { Ok(v) => visitor.visit_string(v), Err(v) => visitor.visit_byte_buf(v.0), } } Value::Binary(v) => visitor.visit_byte_buf(v), Value::Array(v) => { let len = v.len(); let mut de = SeqDeserializer::new(v.into_iter()); let seq = visitor.visit_seq(&mut de)?; if de.iter.len() == 0 { Ok(seq) } else { Err(de::Error::invalid_length(len, &"fewer elements in array")) } } Value::Map(v) => { let len = v.len(); let mut de = MapDeserializer::new(v.into_iter()); let map = visitor.visit_map(&mut de)?; if de.iter.len() == 0 { Ok(map) } else { Err(de::Error::invalid_length(len, &"fewer elements in map")) } } Value::Ext(tag, data) => { let de = ExtDeserializer::new_owned(tag, data); visitor.visit_newtype_struct(de) } } } #[inline] fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { ValueBase::deserialize_option(self, visitor) } #[inline] fn deserialize_enum<V>(self, _name: &str, _variants: &'static [&'static str], visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { ValueBase::deserialize_enum(self, visitor) } #[inline] fn deserialize_newtype_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { if name == MSGPACK_EXT_STRUCT_NAME { match self { Value::Ext(tag, data) => { let ext_de = ExtDeserializer::new_owned(tag, data); return visitor.visit_newtype_struct(ext_de); } other => { return Err(de::Error::invalid_type(other.unexpected(), &"expected Ext")) } } } visitor.visit_newtype_struct(self) } #[inline] fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { ValueBase::deserialize_unit_struct(self, visitor) } forward_to_deserialize_any! { bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq bytes byte_buf map tuple_struct struct identifier tuple ignored_any } } impl<'de> Deserializer<'de> for ValueRef<'de> { type Error = Error; #[inline] fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { match self { ValueRef::Nil => visitor.visit_unit(), ValueRef::Boolean(v) => visitor.visit_bool(v), ValueRef::Integer(Integer { n }) => { match n { IntPriv::PosInt(v) => visitor.visit_u64(v), IntPriv::NegInt(v) => visitor.visit_i64(v) } } ValueRef::F32(v) => visitor.visit_f32(v), ValueRef::F64(v) => visitor.visit_f64(v), ValueRef::String(v) => { match v.s { Ok(v) => visitor.visit_borrowed_str(v), Err(v) => visitor.visit_borrowed_bytes(v.0), } } ValueRef::Binary(v) => visitor.visit_borrowed_bytes(v), ValueRef::Array(v) => { let len = v.len(); let mut de = SeqDeserializer::new(v.into_iter()); let seq = visitor.visit_seq(&mut de)?; if de.iter.len() == 0 { Ok(seq) } else { Err(de::Error::invalid_length(len, &"fewer elements in array")) } } ValueRef::Map(v) => { let len = v.len(); let mut de = MapDeserializer::new(v.into_iter()); let map = visitor.visit_map(&mut de)?; if de.iter.len() == 0 { Ok(map) } else { Err(de::Error::invalid_length(len, &"fewer elements in map")) } } ValueRef::Ext(tag, data) => { let de = ExtDeserializer::new_ref(tag, data); visitor.visit_newtype_struct(de) } } } #[inline] fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { ValueBase::deserialize_option(self, visitor) } #[inline] fn deserialize_enum<V>(self, _name: &str, _variants: &'static [&'static str], visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { ValueBase::deserialize_enum(self, visitor) } #[inline] fn deserialize_newtype_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { if name == MSGPACK_EXT_STRUCT_NAME { match self { ValueRef::Ext(tag, data) => { let ext_de = ExtDeserializer::new_ref(tag, data); return visitor.visit_newtype_struct(ext_de); } other => { return Err(de::Error::invalid_type(other.unexpected(), &"expected Ext")) } } } visitor.visit_newtype_struct(self) } #[inline] fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { ValueBase::deserialize_unit_struct(self, visitor) } forward_to_deserialize_any! { bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq bytes byte_buf map tuple_struct struct identifier tuple ignored_any } } impl<'de> Deserializer<'de> for &'de ValueRef<'de> { type Error = Error; #[inline] fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { match *self { ValueRef::Nil => visitor.visit_unit(), ValueRef::Boolean(v) => visitor.visit_bool(v), ValueRef::Integer(Integer { n }) => { match n { IntPriv::PosInt(v) => visitor.visit_u64(v), IntPriv::NegInt(v) => visitor.visit_i64(v) } } ValueRef::F32(v) => visitor.visit_f32(v), ValueRef::F64(v) => visitor.visit_f64(v), ValueRef::String(v) => { match v.s { Ok(v) => visitor.visit_borrowed_str(v), Err(v) => visitor.visit_borrowed_bytes(v.0), } } ValueRef::Binary(v) => visitor.visit_borrowed_bytes(v), ValueRef::Array(ref v) => { let len = v.len(); let mut de = SeqDeserializer::new(v.iter()); let seq = visitor.visit_seq(&mut de)?; if de.iter.len() == 0 { Ok(seq) } else { Err(de::Error::invalid_length(len, &"fewer elements in array")) } } ValueRef::Map(ref v) => { let len = v.len(); let mut de = MapRefDeserializer::new(v.iter()); let map = visitor.visit_map(&mut de)?; if de.iter.len() == 0 { Ok(map) } else { Err(de::Error::invalid_length(len, &"fewer elements in map")) } } ValueRef::Ext(tag, data) => { let de = ExtDeserializer::new_ref(tag, data); visitor.visit_newtype_struct(de) } } } #[inline] fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { if let ValueRef::Nil = *self { visitor.visit_none() } else { visitor.visit_some(self) } } #[inline] fn deserialize_enum<V>(self, _name: &str, _variants: &'static [&'static str], visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { match self { &ValueRef::Array(ref v) => { let len = v.len(); let mut iter = v.iter(); if !(len == 1 || len == 2) { return Err(de::Error::invalid_length(len, &"array with one or two elements")); } let id = match iter.next() { Some(id) => deserialize_from(id)?, None => { return Err(de::Error::invalid_length(len, &"array with one or two elements")); } }; visitor.visit_enum(EnumRefDeserializer::new(id, iter.next())) } other => Err(de::Error::invalid_type(other.unexpected(), &"array, map or int")), } } #[inline] fn deserialize_newtype_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { if name == MSGPACK_EXT_STRUCT_NAME { match self { ValueRef::Ext(tag, data) => { let ext_de = ExtDeserializer::new_ref(*tag, data); return visitor.visit_newtype_struct(ext_de); } other => { return Err(de::Error::invalid_type(other.unexpected(), &"expected Ext")) } } } visitor.visit_newtype_struct(self) } #[inline] fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { match self { &ValueRef::Array(ref v) => { if v.is_empty() { visitor.visit_unit() } else { Err(de::Error::invalid_length(v.len(), &"empty array")) } } other => Err(de::Error::invalid_type(other.unexpected(), &"empty array")), } } forward_to_deserialize_any! { bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq bytes byte_buf map tuple_struct struct identifier tuple ignored_any } } struct ExtDeserializer<'de> { tag: Option<i8>, data: Option<Cow<'de, [u8]>>, } impl<'de> ExtDeserializer<'de> { fn new_owned(tag: i8, data: Vec<u8>) -> Self { ExtDeserializer { tag: Some(tag), data: Some(Cow::Owned(data)), } } fn new_ref(tag: i8, data: &'de [u8]) -> Self { ExtDeserializer { tag: Some(tag), data: Some(Cow::Borrowed(data)), } } } impl<'de> SeqAccess<'de> for ExtDeserializer<'de> { type Error = Error; fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error> where T: DeserializeSeed<'de>, { if self.tag.is_some() || self.data.is_some() { return Ok(Some(seed.deserialize(self)?)); } Ok(None) } } /// Deserializer for Ext (expecting sequence) impl<'a, 'de: 'a> Deserializer<'de> for ExtDeserializer<'de> { type Error = Error; #[inline] fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { visitor.visit_seq(self) } forward_to_deserialize_any! { bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option seq bytes byte_buf map unit_struct newtype_struct struct identifier tuple enum ignored_any tuple_struct } } /// Deserializer for Ext SeqAccess elements impl<'a, 'de: 'a> Deserializer<'de> for &'a mut ExtDeserializer<'de> { type Error = Error; #[inline] fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { if self.tag.is_some() { let tag = self.tag.take().unwrap(); visitor.visit_i8(tag) } else if self.data.is_some() { let data = self.data.take().unwrap(); match data { Cow::Owned(data) => visitor.visit_byte_buf(data), Cow::Borrowed(data) => visitor.visit_borrowed_bytes(data) } } else { unreachable!("ext seq only has two elements"); } } forward_to_deserialize_any! { bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option seq bytes byte_buf map unit_struct newtype_struct tuple_struct struct identifier tuple enum ignored_any } } struct SeqDeserializer<I> { iter: I, } impl<I> SeqDeserializer<I> { fn new(iter: I) -> Self { Self { iter } } } impl<'de, I, U> SeqAccess<'de> for SeqDeserializer<I> where I: Iterator<Item = U>, U: Deserializer<'de, Error = Error> { type Error = Error; fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> where T: de::DeserializeSeed<'de> { match self.iter.next() { Some(val) => seed.deserialize(val).map(Some), None => Ok(None), } } } impl<'de, I, U> Deserializer<'de> for SeqDeserializer<I> where I: ExactSizeIterator<Item = U>, U: Deserializer<'de, Error = Error> { type Error = Error; #[inline] fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { let len = self.iter.len(); if len == 0 { visitor.visit_unit() } else { let ret = visitor.visit_seq(&mut self)?; let rem = self.iter.len(); if rem == 0 { Ok(ret) } else { Err(de::Error::invalid_length(len, &"fewer elements in array")) } } } forward_to_deserialize_any! { bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option seq bytes byte_buf map unit_struct newtype_struct tuple_struct struct identifier tuple enum ignored_any } } struct MapDeserializer<I, U> { val: Option<U>, iter: I, } impl<I, U> MapDeserializer<I, U> { fn new(iter: I) -> Self { Self { val: None, iter, } } } impl<'de, I, U> de::MapAccess<'de> for MapDeserializer<I, U> where I: Iterator<Item = (U, U)>, U: ValueBase<'de> { type Error = Error; fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> where T: DeserializeSeed<'de> { match self.iter.next() { Some((key, val)) => { self.val = Some(val); seed.deserialize(key).map(Some) } None => Ok(None), } } fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error> where T: DeserializeSeed<'de> { match self.val.take() { Some(val) => seed.deserialize(val), None => Err(de::Error::custom("value is missing")), } } } impl<'de, I, U> Deserializer<'de> for MapDeserializer<I, U> where I: Iterator<Item = (U, U)>, U: ValueBase<'de> { type Error = Error; #[inline] fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { visitor.visit_map(self) } forward_to_deserialize_any! { bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option seq bytes byte_buf map unit_struct newtype_struct tuple_struct struct identifier tuple enum ignored_any } } struct EnumDeserializer<U> { id: u32, value: Option<U>, } impl<U> EnumDeserializer<U> { pub fn new(id: u32, value: Option<U>) -> Self { Self { id, value, } } } impl<'de, U: ValueBase<'de> + ValueExt> de::EnumAccess<'de> for EnumDeserializer<U> { type Error = Error; type Variant = VariantDeserializer<U>; fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> where V: de::DeserializeSeed<'de> { let variant = self.id.into_deserializer(); let visitor = VariantDeserializer { value: self.value }; seed.deserialize(variant).map(|v| (v, visitor)) } } struct VariantDeserializer<U> { value: Option<U>, } impl<'de, U: ValueBase<'de> + ValueExt> de::VariantAccess<'de> for VariantDeserializer<U> { type Error = Error; fn unit_variant(self) -> Result<(), Error> { // Can accept only [u32]. match self.value { Some(v) => { match v.into_iter() { Ok(ref v) if v.len() == 0 => Ok(()), Ok(..) => Err(de::Error::invalid_value(Unexpected::Seq, &"empty array")), Err(v) => Err(de::Error::invalid_value(v.unexpected(), &"empty array")), } } None => Ok(()), } } fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Error> where T: de::DeserializeSeed<'de> { // Can accept both [u32, T...] and [u32, [T]] cases. match self.value { Some(v) => { match v.into_iter() { Ok(mut iter) => { if iter.len() > 1 { seed.deserialize(SeqDeserializer::new(iter)) } else { let val = match iter.next() { Some(val) => seed.deserialize(val), None => return Err(de::Error::invalid_value(Unexpected::Seq, &"array with one element")), }; if iter.next().is_some() { Err(de::Error::invalid_value(Unexpected::Seq, &"array with one element")) } else { val } } } Err(v) => seed.deserialize(v), } } None => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant")), } } fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error> where V: Visitor<'de> { // Can accept [u32, [T...]]. match self.value { Some(v) => { match v.into_iter() { Ok(v) => Deserializer::deserialize_any(SeqDeserializer::new(v), visitor), Err(v) => Err(de::Error::invalid_type(v.unexpected(), &"tuple variant")), } } None => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant")) } } fn struct_variant<V>(self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value, Error> where V: Visitor<'de>, { match self.value { Some(v) => { match v.into_iter() { Ok(iter) => Deserializer::deserialize_any(SeqDeserializer::new(iter), visitor), Err(v) => { match v.into_map_iter() { Ok(iter) => Deserializer::deserialize_any(MapDeserializer::new(iter), visitor), Err(v) => Err(de::Error::invalid_type(v.unexpected(), &"struct variant")), } } } } None => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant")) } } } pub struct MapRefDeserializer<'de> { val: Option<&'de ValueRef<'de>>, iter: Iter<'de, (ValueRef<'de>, ValueRef<'de>)>, } impl<'de> MapRefDeserializer<'de> { fn new(iter: Iter<'de, (ValueRef<'de>, ValueRef<'de>)>) -> Self { Self { val: None, iter, } } } impl<'de> de::MapAccess<'de> for MapRefDeserializer<'de> { type Error = Error; fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> where T: DeserializeSeed<'de> { match self.iter.next() { Some(&(ref key, ref val)) => { self.val = Some(val); seed.deserialize(key).map(Some) } None => Ok(None), } } fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error> where T: DeserializeSeed<'de> { match self.val.take() { Some(val) => seed.deserialize(val), None => Err(de::Error::custom("value is missing")), } } } impl<'de> Deserializer<'de> for MapRefDeserializer<'de> { type Error = Error; #[inline] fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { visitor.visit_map(self) } forward_to_deserialize_any! { bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option seq bytes byte_buf map unit_struct newtype_struct tuple_struct struct identifier tuple enum ignored_any } } pub struct EnumRefDeserializer<'de> { id: u32, value: Option<&'de ValueRef<'de>>, } impl<'de> EnumRefDeserializer<'de> { pub fn new(id: u32, value: Option<&'de ValueRef<'de>>) -> Self { Self { id, value, } } } impl<'de> de::EnumAccess<'de> for EnumRefDeserializer<'de> { type Error = Error; type Variant = VariantRefDeserializer<'de>; fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> where V: de::DeserializeSeed<'de> { let variant = self.id.into_deserializer(); let visitor = VariantRefDeserializer { value: self.value }; seed.deserialize(variant).map(|v| (v, visitor)) } } pub struct VariantRefDeserializer<'de> { value: Option<&'de ValueRef<'de>>, } impl<'de> de::VariantAccess<'de> for VariantRefDeserializer<'de> { type Error = Error; fn unit_variant(self) -> Result<(), Error> { // Can accept only [u32]. match self.value { Some(&ValueRef::Array(ref v)) => { if v.is_empty() { Ok(()) } else { Err(de::Error::invalid_value(Unexpected::Seq, &"empty array")) } } Some(v) => Err(de::Error::invalid_value(v.unexpected(), &"empty array")), None => Ok(()), } } fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Error> where T: de::DeserializeSeed<'de> { // Can accept both [u32, T...] and [u32, [T]] cases. match self.value { Some(&ValueRef::Array(ref v)) => { let len = v.len(); let mut iter = v.iter(); if len > 1 { seed.deserialize(SeqDeserializer::new(iter)) } else { let val = match iter.next() { Some(val) => seed.deserialize(val), None => return Err(de::Error::invalid_length(len, &"array with one element")), }; if iter.next().is_some() { Err(de::Error::invalid_length(len, &"array with one element")) } else { val } } } Some(v) => seed.deserialize(v), None => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant")), } } fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error> where V: Visitor<'de> { // Can accept [u32, [T...]]. match self.value { Some(&ValueRef::Array(ref v)) => { Deserializer::deserialize_any(SeqDeserializer::new(v.iter()), visitor) } Some(v) => Err(de::Error::invalid_type(v.unexpected(), &"tuple variant")), None => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant")) } } fn struct_variant<V>(self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value, Error> where V: Visitor<'de>, { match self.value { Some(&ValueRef::Array(ref v)) => { Deserializer::deserialize_any(SeqDeserializer::new(v.iter()), visitor) } Some(&ValueRef::Map(ref v)) => { Deserializer::deserialize_any(MapRefDeserializer::new(v.iter()), visitor) } Some(v) => Err(de::Error::invalid_type(v.unexpected(), &"struct variant")), None => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant")) } } } // TODO: Ugly hack. Needed for avoiding copy-pasting similar code, but I don't like it. trait ValueBase<'de>: Deserializer<'de, Error = Error> + ValueExt { type Item: ValueBase<'de>; type Iter: ExactSizeIterator<Item = Self::Item>; type MapIter: Iterator<Item = (Self::Item, Self::Item)>; type MapDeserializer: Deserializer<'de>; fn is_nil(&self) -> bool; fn into_iter(self) -> Result<Self::Iter, Self::Item>; fn into_map_iter(self) -> Result<Self::MapIter, Self::Item>; #[inline] fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { if self.is_nil() { visitor.visit_none() } else { visitor.visit_some(self) } } #[inline] fn deserialize_enum<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { match self.into_iter() { Ok(mut iter) => { if !(iter.len() == 1 || iter.len() == 2) { return Err(de::Error::invalid_length(iter.len(), &"array with one or two elements")); } let id = match iter.next() { Some(id) => deserialize_from(id)?, None => { return Err(de::Error::invalid_value(Unexpected::Seq, &"array with one or two elements")); } }; visitor.visit_enum(EnumDeserializer::new(id, iter.next())) } Err(other) => { Err(de::Error::invalid_type(other.unexpected(), &"array, map or int")) } } } #[inline] fn deserialize_newtype_struct<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { visitor.visit_newtype_struct(self) } #[inline] fn deserialize_unit_struct<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de> { match self.into_iter() { Ok(iter) => { if iter.len() == 0 { visitor.visit_unit() } else { Err(de::Error::invalid_type(Unexpected::Seq, &"empty array")) } } Err(other) => Err(de::Error::invalid_type(other.unexpected(), &"empty array")), } } } impl<'de> ValueBase<'de> for Value { type Item = Value; type Iter = IntoIter<Value>; type MapIter = IntoIter<(Value, Value)>; type MapDeserializer = MapDeserializer<Self::MapIter, Self::Item>; #[inline] fn is_nil(&self) -> bool { if let Value::Nil = *self { true } else { false } } #[inline] fn into_iter(self) -> Result<Self::Iter, Self::Item> { match self { Value::Array(v) => Ok(v.into_iter()), other => Err(other) } } #[inline] fn into_map_iter(self) -> Result<Self::MapIter, Self::Item> { match self { Value::Map(v) => Ok(v.into_iter()), other => Err(other) } } } impl<'de> ValueBase<'de> for ValueRef<'de> { type Item = ValueRef<'de>; type Iter = IntoIter<ValueRef<'de>>; type MapIter = IntoIter<(ValueRef<'de>, ValueRef<'de>)>; type MapDeserializer = MapDeserializer<Self::MapIter, Self::Item>; #[inline] fn is_nil(&self) -> bool { if let ValueRef::Nil = *self { true } else { false } } #[inline] fn into_iter(self) -> Result<Self::Iter, Self::Item> { match self { ValueRef::Array(v) => Ok(v.into_iter()), other => Err(other) } } #[inline] fn into_map_iter(self) -> Result<Self::MapIter, Self::Item> { match self { ValueRef::Map(v) => Ok(v.into_iter()), other => Err(other) } } }
31.643087
126
0.489508
3a3d226d6f25ffd9007489d03dd47798df514cfc
397
mod backends; mod cache; mod calls; mod compatability; mod context; pub mod errors; mod instance; mod memory; mod middleware; mod modules; pub mod testing; mod wasm_store; pub use crate::cache::CosmCache; pub use crate::calls::{ call_handle, call_handle_raw, call_init, call_init_raw, call_query, call_query_raw, }; pub use crate::instance::Instance; pub use crate::modules::FileSystemCache;
19.85
87
0.7733